Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 1x 1x 1x 32x 31x 31x 2x 2x 2x 1x 1x 31x 31x 1x 31x 31x 31x 31x 31x 31x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 5x 31x 5x 31x 31x 31x 31x 31x 93x 31x 1x 35x 35x 35x 35x 1x 34x 34x 2x 32x 3x 3x 3x 3x 3x 29x 28x 28x 28x 1x 1x | const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
GetCommand,
DeleteCommand,
PutCommand,
QueryCommand
} = require('@aws-sdk/lib-dynamodb')
const {
CognitoIdentityProviderClient,
AdminDeleteUserCommand
} = require('@aws-sdk/client-cognito-identity-provider')
const { batchDelete } = require('../utils/batchWrite')
const { computeFlowDeletionImpact, cascadeDeleteFlow } = require('../utils/flowDeletionCascade')
const { deleteAllSubscriptionsForUser } = require('../utils/entitySubscriptions')
const { deleteAllLikesForUser } = require('../utils/itemLikes')
const { deleteAllCommentDataForUser, commentTablesFromEnv } = require('../utils/commentCleanup')
const { deleteAllFollowsForUser } = require('../utils/userFollows')
const {
deleteAllPacksForFlow,
deleteAllPacksForAuthor,
deleteAllPackLikesForUser
} = require('../utils/packCleanup')
const { deleteSearchIndexRows, syncUserSearchIndex } = require('../utils/directorySearchIndex')
const { deleteAllConversationsForUser } = require('../utils/conversationCleanup')
const { deleteAllBlocksForUser } = require('../utils/directMessages')
const { deleteAllNotificationsForUser } = require('../utils/notifications')
const { deleteMembershipRequestsOfUser } = require('../utils/membershipRequestCleanup')
const { deleteCreditsAndUsageForUser } = require('../utils/userUsageCleanup')
const { isE2eTestEmail } = require('../utils/e2eTestUser')
const { buildNewUserItem } = require('../utils/newUserItem')
const { S3Client } = require('@aws-sdk/client-s3')
const { userKeyGuard, deleteKeys, deletePrefix } = require('../utils/s3Cleanup')
const dynamoClient = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(dynamoClient)
const cognitoClient = new CognitoIdentityProviderClient({})
const s3Client = new S3Client({ region: 'eu-central-1' })
const getCorsHeaders = () => ({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
async function deleteFlowData(flowId, slug) {
// Account deletion is already an irreversible, non-interactive cascade with
// no per-flow confirmation step, so entities with active links transfer
// automatically to their top consumer flow without a confirm round-trip
// (contrast with the user-facing DELETE /v1/flows/:flowId, which requires
// confirmTransfer=true first).
const impact = await computeFlowDeletionImpact(docClient, {
entitiesTableName: process.env.ENTITIES_TABLE_NAME,
entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
countersTableName: process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
flowId
})
await cascadeDeleteFlow(docClient, {
flowsTableName: process.env.FLOWS_TABLE_NAME,
flowSlugsTableName: process.env.FLOW_SLUGS_TABLE_NAME,
entitiesTableName: process.env.ENTITIES_TABLE_NAME,
itemsTableName: process.env.ITEMS_TABLE_NAME,
rolesTableName: process.env.ROLES_TABLE_NAME,
flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
countersTableName: process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
apiKeysTableName: process.env.API_KEYS_TABLE,
fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entitySubscriberCountTableName: process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
entitySubscriptionsTableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
itemLikesTableName: process.env.ITEM_LIKES_TABLE_NAME,
itemLikeCountTableName: process.env.ITEM_LIKE_COUNT_TABLE_NAME,
commentTables: commentTablesFromEnv() ?? undefined,
commentBlocksTableName: process.env.COMMENT_BLOCKS_TABLE_NAME,
membershipRequestsTableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
flowPagesTableName: process.env.FLOW_PAGES_TABLE_NAME,
s3Client,
attachmentsBucketName: process.env.ATTACHMENTS_BUCKET_NAME,
flowId,
slug,
impact
})
await deleteAllPacksForFlow(docClient, flowId)
}
/**
* Deletes everything the user owns or left behind across the platform — owned
* flows (full cascade), memberships, API keys, subscriptions, likes, comments
* and moderation footprint, follows, conversations, DM blocks, nickname reservation, e2e
* credits/usage, search-index rows and S3 files — but NOT the Cognito user.
* The UsersTable row is handed to `replaceUserRow`, called at the point where
* the full deletion has always removed it (after the credits purge, before the
* files), so the caller decides whether it is deleted or rebuilt.
*
* @param {string} userId
* @param {() => Promise<void>} replaceUserRow
*/
async function purgeUserData(userId, replaceUserRow) {
// 1. Find all memberships for this user (owned + non-owned flows)
const membershipsResult = await docClient.send(
new QueryCommand({
TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
KeyConditionExpression: 'userId = :userId',
ExpressionAttributeValues: { ':userId': userId }
})
)
const memberships = membershipsResult.Items ?? []
// 2. Cascade-delete owned flows; remove membership record for non-owned flows
for (const membership of memberships) {
const flowId = membership.flowId
const flowResult = await docClient.send(
new GetCommand({
TableName: process.env.FLOWS_TABLE_NAME,
Key: { id: flowId }
})
)
if (flowResult.Item?.ownerId === userId) {
// Owner: cascade-delete the entire flow (entities, items, roles, memberships, flow)
await deleteFlowData(flowId, flowResult.Item.slug)
} else {
// Not owner: only remove this user's membership
await docClient.send(
new DeleteCommand({
TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
Key: { userId, flowId }
})
)
}
}
// 3. Delete API keys created by this user
const apiKeysResult = await docClient.send(
new QueryCommand({
TableName: process.env.API_KEYS_TABLE,
IndexName: 'createdByIndex',
KeyConditionExpression: 'createdBy = :userId',
ExpressionAttributeValues: { ':userId': userId }
})
)
await batchDelete(
docClient,
process.env.API_KEYS_TABLE,
(apiKeysResult.Items ?? []).map((k) => ({ id: k.id }))
)
// 3b. Delete this user's own subscriptions to other flows' public
// entities (independent of the owned-flow cascade above, which only
// covers entities this user owned).
Eif (process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME) {
await deleteAllSubscriptionsForUser(
docClient,
process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
userId,
process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME
)
}
// 3c. Delete this user's own likes on any item (independent of the
// owned-flow cascade above, which only covers items this user owned).
Eif (process.env.ITEM_LIKES_TABLE_NAME) {
await deleteAllLikesForUser(
docClient,
process.env.ITEM_LIKES_TABLE_NAME,
userId,
process.env.ITEM_LIKE_COUNT_TABLE_NAME
)
}
// 3c'. Delete this user's own comments (a tombstone when they have replies,
// so other people's threads stay intact) and their moderation footprint:
// submissions, votes, review points and reputation.
const commentTables = commentTablesFromEnv()
if (commentTables) {
await deleteAllCommentDataForUser(docClient, commentTables, userId)
}
// 3c''. Delete the packs this user authored in flows that stay, and their
// likes on any pack.
await deleteAllPacksForAuthor(docClient, userId)
await deleteAllPackLikesForUser(docClient, userId)
// 3d. Delete this user's follow relationships, in both directions (who
// they follow, and who follows them) — independent of the owned-flow
// cascade above, which has nothing to do with user-to-user follows.
Eif (process.env.USER_FOLLOWS_TABLE_NAME) {
await deleteAllFollowsForUser(
docClient,
process.env.USER_FOLLOWS_TABLE_NAME,
process.env.USER_FOLLOWER_COUNT_TABLE_NAME,
userId
)
}
// 3e. Delete this user's messaging inbox (and any conversation nobody else
// is part of anymore, with its messages).
Eif (process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME) {
await deleteAllConversationsForUser(docClient, {
participantsTableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
conversationsTableName: process.env.CONVERSATIONS_TABLE_NAME,
messagesTableName: process.env.MESSAGES_TABLE_NAME,
userId
})
}
// 3e'. Delete the Direct Message blocks this user placed or received.
Eif (process.env.USER_BLOCKS_TABLE_NAME) {
await deleteAllBlocksForUser(docClient, process.env.USER_BLOCKS_TABLE_NAME, userId)
}
// 3f. Delete this user's notifications inbox.
Eif (process.env.NOTIFICATIONS_TABLE_NAME) {
await deleteAllNotificationsForUser(docClient, userId)
}
// 3g. Delete this user's requests to join flows, answers included.
await deleteMembershipRequestsOfUser(
docClient,
{
tableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
flowsTableName: process.env.FLOWS_TABLE_NAME,
s3Client,
attachmentsBucketName: process.env.ATTACHMENTS_BUCKET_NAME
},
userId
)
// 4. Release the user's nickname reservation, if any (the UsersTable row
// itself is deleted or rebuilt by the caller)
const userResult = await docClient.send(
new GetCommand({
TableName: process.env.USERS_TABLE_NAME,
Key: { id: userId }
})
)
if (userResult.Item?.nickname) {
await docClient.send(
new DeleteCommand({
TableName: process.env.NICKNAMES_TABLE_NAME,
Key: { nickname: userResult.Item.nickname }
})
)
}
// The credits ledger and usage summaries are an accounting trail that
// outlives a real user's account, but pure noise for a throwaway e2e
// account — purge them for those only.
if (process.env.CREDITS_LEDGER_TABLE_NAME && isE2eTestEmail(userResult.Item?.email)) {
await deleteCreditsAndUsageForUser(docClient, {
creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
usageDailyTableName: process.env.USAGE_DAILY_SUMMARY_TABLE_NAME,
usageMonthlyTableName: process.env.USAGE_MONTHLY_SUMMARY_TABLE_NAME,
userId
})
}
// 4a. Delete or rebuild the UsersTable record
await replaceUserRow()
// 4b. Drop the user's search-index rows so they stop appearing in searches
await deleteSearchIndexRows(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, 'USER', userId)
// 4c. The user's own files: profile picture (and anything else under their
// account folder) plus their import-preview and export scratch objects. Their
// owned flows' files were already removed by the flow cascade above.
const bucket = process.env.ATTACHMENTS_BUCKET_NAME
await deleteKeys(s3Client, bucket, [userResult.Item?.profilePicture], userKeyGuard(userId))
for (const folder of ['users', 'imports', 'exports']) {
await deletePrefix(s3Client, bucket, `${folder}/${userId}/`)
}
// Images and files of a join form not sent (UC-SPACE-020.1)
await deletePrefix(s3Client, bucket, `membership-requests/drafts/${userId}/`)
}
exports.handler = async (event) => {
try {
const claims = event.requestContext?.authorizer?.claims
const userId = claims?.sub
if (!userId) {
return {
statusCode: 401,
headers: getCorsHeaders(),
body: JSON.stringify({ error: 'Not authenticated' })
}
}
// keepAccount=true wipes the account back to a just-signed-up state instead
// of deleting it. It exists only so the e2e suite can reuse a small fixed
// pool of Cognito accounts (every distinct user who signs in is a billed
// MAU, even if deleted afterwards). e2e-test-* emails are auto-confirmed in
// every stage, so the email check alone would let anyone in prod reset
// their own credits: ALLOW_E2E_ACCOUNT_RESET is only set on dev/test.
const keepAccount = event.queryStringParameters?.keepAccount === 'true'
if (
keepAccount &&
!(process.env.ALLOW_E2E_ACCOUNT_RESET === 'true' && isE2eTestEmail(claims.email))
) {
return {
statusCode: 403,
headers: getCorsHeaders(),
body: JSON.stringify({ error: 'Account reset is only available to e2e test accounts' })
}
}
if (keepAccount) {
const userItem = buildNewUserItem({ id: userId, email: claims.email, name: claims.name })
await purgeUserData(userId, () =>
docClient.send(new PutCommand({ TableName: process.env.USERS_TABLE_NAME, Item: userItem }))
)
// After the purge, which dropped the old search-index rows
await syncUserSearchIndex(
docClient,
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
userId,
null,
userItem
)
return { statusCode: 204, headers: getCorsHeaders(), body: '' }
}
await purgeUserData(userId, () =>
docClient.send(
new DeleteCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
)
)
// 5. Delete from Cognito (last step — user can no longer authenticate after this)
await cognitoClient.send(
new AdminDeleteUserCommand({
UserPoolId: process.env.USER_POOL_ID,
Username: userId
})
)
return {
statusCode: 204,
headers: getCorsHeaders(),
body: ''
}
} catch (error) {
console.error('Error deleting user account:', error)
return {
statusCode: 500,
headers: getCorsHeaders(),
body: JSON.stringify({ error: 'Failed to delete account' })
}
}
}
|