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 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 121x 25x 2x 8x 25x 45x 25x 35x 2x 11x 11x 11x 3x 1x 8x 8x 4x 4x 2x 2x 8x 3x 3x 2x 1x 1x 1x 2x 21x 21x 20x 20x 2x 2x 6x 12x 12x 12x 70x 12x 12x 12x 11x 11x 11x 11x 11x 11x 10x 10x 10x 10x 10x 10x 10x 2x 2x 8x 1x 8x 5x 1x 1x 1x 5x 1x 1x 11x 11x 11x 35x 35x 16x 11x 68x 11x 11x 1x 11x 11x 11x 10x 10x 10x 10x 9x 9x 9x 9x 9x 9x 1x 1x 8x 1x 1x 7x 2x 2x 5x 5x 5x 4x 27x 27x 2x 25x 25x 1x 24x 30x 30x 29x 28x 28x 28x 25x 25x 24x 24x 23x 23x 23x 23x 14x 14x 14x 3x 3x 3x 2x 1x 11x 10x 10x 10x 7x 10x 11x 11x 11x 11x 2x 52x 52x 52x 52x 50x 50x 49x 49x 1x 48x 1x 47x 41x 36x 33x 61x 3x 30x 3x 3x 2x 2x | // @implements UC-SPACE-005.1, UC-SPACE-006.1, UC-SPACE-007.1, UC-SPACE-020.1
/**
* POST /v1/flows/{flowId}/membership-requests/{userId}
* Body: `{ decision: 'approve' | 'refuse' | 'ban' | 'unban', roleIds?: string[] }`
*
* - approve: with a membership entity, the answers go to the requester's
* membership item — their existing one when they have one (a former
* member's, UC-SPACE-006.1), else a new one with the member field set to
* them; then the membership and the decided request are written in one
* transaction. The item goes first because it is the step that can be
* refused (answers no longer fitting the entity, a unique value taken):
* failing there leaves nothing behind. Without a membership entity, only
* the transaction.
* - refuse / ban: the answers are removed and the decision kept.
*
* A request's images and files (UC-SPACE-020.1) are copied into the item's own
* keys before it is written, billed to the approver, then the request's are
* deleted; a refusal or ban deletes them.
* - unban: the banned row is deleted, so the user may ask again.
*
* See docs/architecture/FLOW_SPACE.md "Membership requests".
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
GetCommand,
QueryCommand,
TransactWriteCommand,
DeleteCommand
} = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { createItem } = require('../items/createItem')
const { prepareNewItemData } = require('../items/newItemData')
const { writeItemUpdate, finishItemUpdate } = require('../items/itemUpdate')
const { joinFormFields } = require('../utils/spaceJoin')
const { findMembershipItems, membershipDataError } = require('../utils/membershipItem')
const { scheduleWakeUpSafely } = require('../utils/wakeUpScheduler')
const { batchWrite } = require('../utils/batchWrite')
const { adjustCounters } = require('../utils/referenceCounters')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { notifyPermissionsChanged } = require('../utils/permissionsChangedPush')
const { emailDecision } = require('../utils/membershipRequestEmails')
const { respond, statusKey, verifiedPathFlowId } = require('./shared')
const {
copyRequestFilesToItem,
deleteItemCopies,
deleteRequestFiles
} = require('../utils/membershipRequestFiles')
const { randomUUID } = require('crypto')
const { S3Client } = require('@aws-sdk/client-s3')
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const s3Client = new S3Client({})
const DECISIONS = ['approve', 'refuse', 'ban', 'unban']
const getItem = async (TableName, Key) =>
(await docClient.send(new GetCommand({ TableName, Key }))).Item
/** Write that ends a pending request: decision kept, answers removed, pending count lowered */
function decidedRequestActions(flowId, userId, status, deciderId, now) {
return [
{
Update: {
TableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
Key: { flowId, userId },
ConditionExpression: '#status = :pending',
UpdateExpression:
'SET #status = :status, statusCreatedAt = :statusKey, decidedAt = :now, decidedBy = :decider REMOVE answers',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: {
':pending': 'pending',
':status': status,
':statusKey': statusKey(status, now),
':now': now,
':decider': deciderId
}
}
},
{
Update: {
TableName: process.env.FLOWS_TABLE_NAME,
Key: { id: flowId },
UpdateExpression: 'ADD pendingRequestCount :minusOne',
ExpressionAttributeValues: { ':minusOne': -1 }
}
}
]
}
const isConditionFailure = (error, index) =>
error.name === 'TransactionCanceledException' &&
error.CancellationReasons?.[index]?.Code === 'ConditionalCheckFailed'
/** The flow's role ids among `roleIds`, or null when one is not a role of the flow */
async function validRoleIds(flowId, roleIds) {
const result = await docClient.send(
new QueryCommand({
TableName: process.env.ROLES_TABLE_NAME,
KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
ExpressionAttributeValues: { ':pk': `FLOW#${flowId}`, ':sk': 'ROLE#' },
ProjectionExpression: 'roleId'
})
)
const flowRoleIds = new Set((result.Items || []).map((role) => role.roleId))
const unique = [...new Set(roleIds)]
return unique.every((roleId) => flowRoleIds.has(roleId)) ? unique : null
}
/** Validates the answers against the entity as it is now; first error or null */
const answersError = membershipDataError
async function decideEnd(flowId, userId, status, deciderId) {
const now = new Date().toISOString()
try {
await docClient.send(
new TransactWriteCommand({
TransactItems: decidedRequestActions(flowId, userId, status, deciderId, now)
})
)
} catch (error) {
if (isConditionFailure(error, 0)) return respond(404, { error: 'No pending request' })
throw error
}
await deleteRequestFiles(process.env.ATTACHMENTS_BUCKET_NAME, flowId, userId)
// A refusal is told to the requester; a ban is not (UC-SPACE-007.1 AC-2)
if (status === 'refused') {
try {
const flow = await getItem(process.env.FLOWS_TABLE_NAME, { id: flowId })
Eif (flow) await emailDecision({ docClient, flow, userId, decision: 'refused' })
} catch (error) {
console.error('Failed to email a refused membership request:', error)
}
}
return respond(200, { userId, status, decidedAt: now })
}
async function unban(flowId, userId) {
try {
await docClient.send(
new DeleteCommand({
TableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
Key: { flowId, userId },
ConditionExpression: '#status = :banned',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':banned': 'banned' }
})
)
} catch (error) {
if (error.name === 'ConditionalCheckFailedException') {
return respond(404, { error: 'No banned request' })
}
throw error
}
return respond(200, { userId, status: 'unbanned' })
}
const storageCredits = (bytes, pricing) =>
Math.ceil((Math.max(0, bytes) / 1024) * pricing.dynamodb_storage_credits_per_kb)
/** 402 when the approver can't pay `required` storage credits, else null */
async function insufficientCredits(deciderId, required) {
if (required <= 0) return null
const { balance, isPlatformAdmin } = await getCreditsBalance(
docClient,
process.env.USERS_TABLE_NAME,
deciderId
)
if (isPlatformAdmin || balance >= required) return null
return respond(402, { error: 'INSUFFICIENT_CREDITS', required, balance })
}
const answersNoLongerValid = (fieldId, reason) =>
respond(409, { error: 'ANSWERS_NO_LONGER_VALID', fieldId, reason })
/**
* Creates the requester's membership item from the answers, as items/create.js
* would. Returns the error response, or what the steps after the membership
* write need.
*/
async function createMembershipItem({ flowId, userId, deciderId, entity, userField, answers }) {
const fields = entity.fields || []
// Only answers to fields still on the entity; the member field is the requester
const data = {}
for (const field of fields) {
if (answers && field.fieldId in answers) data[field.fieldId] = answers[field.fieldId]
}
data[userField.fieldId] = userField.reference?.multiple ? [userId] : userId
const invalid = answersError(fields, data)
if (invalid) return { response: answersNoLongerValid(invalid.fieldId, invalid.error) }
const now = new Date().toISOString()
const { wakeUpAt } = await prepareNewItemData({
docClient,
fields,
data,
actor: deciderId,
now,
flowId
})
// Same credits rule as any item creation: the caller (the approver) pays
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const storageCost = storageCredits(Buffer.byteLength(JSON.stringify(data)), pricing)
const noCredits = await insufficientCredits(deciderId, storageCost)
if (noCredits) return { response: noCredits }
// The request's files become the item's own, billed to the approver
const bucket = process.env.ATTACHMENTS_BUCKET_NAME
const itemId = randomUUID()
const files = await copyRequestFilesToItem({
bucket,
fields,
data,
flowId,
userId,
entityId: entity.id,
itemId,
owner: { userId: deciderId, flowId }
})
let created
try {
created = await createItem({
docClient,
itemsTableName: process.env.TABLE_NAME,
fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entityId: entity.id,
itemId,
flowId,
fields,
data: files.data,
createdBy: deciderId,
createdAt: now
})
} catch (error) {
await deleteItemCopies(bucket, entity.id, itemId, files.copiedKeys)
throw error
}
const { conflictFieldId, item, textSearchRequests, referencedEntityIds } = created
if (conflictFieldId) {
await deleteItemCopies(bucket, entity.id, itemId, files.copiedKeys)
return { response: answersNoLongerValid(conflictFieldId, 'UNIQUE_FIELD_CONFLICT') }
}
if (wakeUpAt) {
await scheduleWakeUpSafely({
entityId: entity.id,
itemId: item.id,
wakeUpAt,
docClient,
itemsTableName: process.env.TABLE_NAME
})
}
return {
item,
pricing,
storageCost,
operation: 'item_create',
// Best-effort, once the membership exists, as in items/create.js
finish: async () => {
if (textSearchRequests.length > 0) {
try {
await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
} catch (textSearchError) {
console.error('Failed to write text-search index rows:', textSearchError)
}
}
if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME && referencedEntityIds.size > 0) {
await adjustCounters(
docClient,
process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
flowId,
new Map([...referencedEntityIds].map((refEntityId) => [refEntityId, 1]))
)
}
}
}
}
/**
* Updates a former member's membership item with the new answers, as
* items/update.js would: the join form's fields take the new answers (an
* unanswered one is cleared), the other fields are kept, and the former member
* state's workflow field goes back to its start state.
*/
async function updateMembershipItem({
flowId,
requesterId,
deciderId,
entity,
join,
existing,
answers
}) {
const fields = entity.fields || []
const changes = {}
for (const field of joinFormFields(entity, join.userFieldId)) {
const answer = answers?.[field.fieldId]
if (answer !== undefined) changes[field.fieldId] = answer
else if (existing[field.fieldId] !== undefined) changes[field.fieldId] = null
}
const workflowField = fields.find(
(field) => field.fieldId === join.formerMemberFieldId && field.type === 'workflow'
)
const startStateId = workflowField?.workflowDefinition?.startStateId
if (startStateId && existing[workflowField.fieldId] !== startStateId) {
changes[workflowField.fieldId] = startStateId
}
const merged = { ...existing, ...changes }
const invalid = answersError(fields, merged)
if (invalid) return { response: answersNoLongerValid(invalid.fieldId, invalid.error) }
// Same credits rule as any item update: the growth only, paid by the approver
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const storageCost = storageCredits(
Buffer.byteLength(JSON.stringify(merged)) - Buffer.byteLength(JSON.stringify(existing)),
pricing
)
const noCredits = await insufficientCredits(deciderId, storageCost)
if (noCredits) return { response: noCredits }
// The request's files become the item's own, billed to the approver; the
// files they replace are deleted by finishItemUpdate
const bucket = process.env.ATTACHMENTS_BUCKET_NAME
const files = await copyRequestFilesToItem({
bucket,
fields,
data: changes,
flowId,
userId: requesterId,
entityId: entity.id,
itemId: existing.id,
owner: { userId: deciderId, flowId }
})
const dropCopies = () => deleteItemCopies(bucket, entity.id, existing.id, files.copiedKeys)
let written
try {
written = await writeItemUpdate({
docClient,
itemsTableName: process.env.TABLE_NAME,
entityId: entity.id,
existing,
fields,
changes: files.data,
actor: deciderId,
flowId,
now: new Date().toISOString()
})
} catch (error) {
await dropCopies()
throw error
}
if (written.status === 'invalid') {
await dropCopies()
return { response: answersNoLongerValid(written.fieldId, written.error) }
}
if (written.status === 'conflict') {
await dropCopies()
return { response: answersNoLongerValid(written.fieldId, 'UNIQUE_FIELD_CONFLICT') }
}
// Changed by someone else meanwhile: approving again reads it afresh
if (written.status === 'modified') {
await dropCopies()
return { response: respond(409, { error: 'ITEM_MODIFIED' }) }
}
const item = written.status === 'ok' ? written.item : existing
return {
item,
pricing,
storageCost,
operation: 'item_update',
finish: async () => {
if (written.status !== 'ok') return
await finishItemUpdate({
docClient,
s3Client,
entityId: entity.id,
existing,
fields,
item,
flowId
})
}
}
}
/** The membership entity and its member field, or the 409 when they are gone */
async function loadMembershipEntity(flowId, join) {
const entity = await getItem(process.env.ENTITIES_TABLE_NAME, { id: join.entityId })
if (!entity || entity.flowId !== flowId) {
return { response: respond(409, { error: 'MEMBERSHIP_ENTITY_NOT_SET' }) }
}
const userField = (entity.fields || []).find((field) => field.fieldId === join.userFieldId)
if (!userField || userField.type !== 'user') {
return { response: respond(409, { error: 'MEMBERSHIP_ENTITY_NOT_SET' }) }
}
return { entity, userField }
}
async function approve({ flowId, userId, deciderId, roleIds }) {
const [request, flow, existingMembership] = await Promise.all([
getItem(process.env.MEMBERSHIP_REQUESTS_TABLE_NAME, { flowId, userId }),
getItem(process.env.FLOWS_TABLE_NAME, { id: flowId }),
getItem(process.env.FLOW_MEMBERSHIPS_TABLE_NAME, { userId, flowId })
])
if (request?.status !== 'pending') return respond(404, { error: 'No pending request' })
if (existingMembership?.status === 'active') return respond(409, { error: 'ALREADY_MEMBER' })
const join = flow?.space?.join || {}
const membershipEntity = join.entityId ? await loadMembershipEntity(flowId, join) : null
if (membershipEntity?.response) return membershipEntity.response
const roles = await validRoleIds(flowId, roleIds)
if (!roles) return respond(400, { error: 'roleIds must be roles of this flow' })
let written = null
if (membershipEntity) {
const { entity, userField } = membershipEntity
const [existing] = await findMembershipItems({
docClient,
itemsTableName: process.env.TABLE_NAME,
entityId: entity.id,
userField,
userId
})
written = existing
? await updateMembershipItem({
flowId,
requesterId: userId,
deciderId,
entity,
join,
existing,
answers: request.answers
})
: await createMembershipItem({
flowId,
userId,
deciderId,
entity,
userField,
answers: request.answers
})
if (written.response) return written.response
}
const now = new Date().toISOString()
try {
await docClient.send(
new TransactWriteCommand({
TransactItems: [
...decidedRequestActions(flowId, userId, 'approved', deciderId, now),
{
// A pending invitation of the same user is turned into this membership
Put: {
TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
Item: {
userId,
flowId,
roleIds: roles,
status: 'active',
invitedBy: deciderId,
joinedVia: 'request',
joinedAt: now
},
ConditionExpression: 'attribute_not_exists(userId) OR #status = :pending',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':pending': 'pending' }
}
}
]
})
)
} catch (error) {
// Lost a race (another approver, or the user joined meanwhile): the item
// just written has no membership behind it — reported, not rolled back
Eif (written) {
console.error('Membership request approval failed after the membership item write:', {
flowId,
userId,
itemId: written.item.id,
error: error.name
})
}
if (isConditionFailure(error, 0)) return respond(404, { error: 'No pending request' })
if (isConditionFailure(error, 2)) return respond(409, { error: 'ALREADY_MEMBER' })
throw error
}
if (written) {
// Best-effort from here, as in items/create.js: the item and the membership exist
try {
const { writeUnits } = getConsumedCapacity()
await debitCredits(docClient, {
usersTableName: process.env.USERS_TABLE_NAME,
creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
userId: deciderId,
flowId,
charges: [
{
pool: 'dynamodb_storage',
operation: written.operation,
costCredits: written.storageCost,
referenceId: written.item.id
},
{
pool: 'dynamodb_throughput',
operation: written.operation,
costCredits: Math.ceil(
writeUnits * written.pricing.dynamodb_throughput_credits_per_wru
),
referenceId: written.item.id
}
]
})
} catch (creditError) {
console.error('Failed to debit credits for membership item:', creditError)
}
await written.finish()
}
// The files now live in the item (or the flow has no membership entity)
await deleteRequestFiles(process.env.ATTACHMENTS_BUCKET_NAME, flowId, userId)
// The new member's open tabs reload their flows
await notifyPermissionsChanged([userId], flowId)
await emailDecision({ docClient, flow, userId, decision: 'approved' })
return respond(200, {
userId,
status: 'approved',
decidedAt: now,
...(written && { itemId: written.item.id }),
roleIds: roles
})
}
const decideHandler = async (event) => {
try {
const deciderId = event.requestContext?.authorizer?.claims?.sub
const flowId = await verifiedPathFlowId(event)
if (!flowId) return respond(403, { error: 'Access denied - not your active flow' })
const userId = event.pathParameters?.userId
if (!userId) return respond(400, { error: 'Missing userId' })
let body
try {
body = JSON.parse(event.body || '{}')
} catch {
return respond(400, { error: 'Invalid JSON body' })
}
if (!DECISIONS.includes(body.decision)) {
return respond(400, { error: `decision must be one of: ${DECISIONS.join(', ')}` })
}
if (body.decision === 'refuse') return await decideEnd(flowId, userId, 'refused', deciderId)
if (body.decision === 'ban') return await decideEnd(flowId, userId, 'banned', deciderId)
if (body.decision === 'unban') return await unban(flowId, userId)
if (
!Array.isArray(body.roleIds) ||
body.roleIds.length === 0 ||
!body.roleIds.every((roleId) => typeof roleId === 'string' && roleId)
) {
return respond(400, { error: 'roleIds must be a non-empty array of role ids' })
}
return await approve({ flowId, userId, deciderId, roleIds: body.roleIds })
} catch (error) {
console.error('Error deciding membership request:', error)
return respond(500, { error: 'Failed to decide membership request' })
}
}
exports.handler = requirePermission(decideHandler, { permission: 'members:approve' })
exports.decideHandler = decideHandler
|