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 | 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 86x 6x 44x 6x 6x 23x 23x 10x 10x 10x 14x 14x 19x 19x 3x 16x 62x 59x 39x 39x 40x 37x 37x 36x 87x 87x 81x 81x 81x 5x 76x 76x 6x 5x 9x 8x 7x 7x 26x 25x 24x 24x 23x 23x 23x 23x 23x 11x 11x 11x 11x 11x 22x 16x 16x 16x 16x 13x 21x 13x 9x 9x 1x 6x | /**
* Pieces shared by the space pages Lambdas (docs/architecture/FLOW_SPACE.md,
* "Pages and content blocks").
*/
const { isDeepStrictEqual } = require('node:util')
const { GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3')
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner')
const { resolveActiveFlow } = require('../shared/activeFlow')
const { permissionChecker } = require('../utils/PermissionChecker')
const { flowKeyGuard, deleteKeys } = require('../utils/s3Cleanup')
const { withImageUrls, pageImageKeys, pagesLinkingTo } = require('../utils/spacePages')
const { resolveBlocks, resolveListItems, withoutFrozenFields } = require('../utils/spaceData')
const SPACE_SLUG_REGEX = /^[a-z0-9-]{1,100}$/
const CORS_HEADERS = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
const respond = (statusCode, body) => ({
statusCode,
headers: CORS_HEADERS,
body: JSON.stringify(body)
})
/**
* How a public read is cached: a minute by the spaces CDN
* (Flows-Spaces-Cdn-Stack), so a published change shows within a minute
* while a crowd of visitors (or a bot) reaches the API once a minute per URL;
* never by the browser, so an editor checking a change isn't served an older
* copy. Far below the one-hour signed URLs inside the response.
*/
const PUBLIC_CACHE_CONTROL = 'public, max-age=0, s-maxage=60'
/** A response of a public endpoint (no authentication): cacheable, except errors */
const respondPublic = (statusCode, body) => ({
statusCode,
headers:
statusCode < 500 ? { ...CORS_HEADERS, 'Cache-Control': PUBLIC_CACHE_CONTROL } : CORS_HEADERS,
body: JSON.stringify(body)
})
const IMAGE_URL_TTL_SECONDS = 3600
const s3Client = new S3Client({ region: 'eu-central-1' })
/**
* Signs a one-hour read URL for an image of the flow's pages. A visitor may
* have no account, so the authenticated presigned-read-url endpoint can't be
* used; the key guard keeps this from ever signing a key outside the flow.
*/
function imageSigner(flowId) {
const guard = flowKeyGuard(flowId)
return async (key) => {
const bucket = process.env.ATTACHMENTS_BUCKET_NAME
Iif (!bucket || typeof key !== 'string' || !guard(key)) return undefined
return getSignedUrl(s3Client, new GetObjectCommand({ Bucket: bucket, Key: key }), {
expiresIn: IMAGE_URL_TTL_SECONDS
})
}
}
/**
* Signs one-hour read URLs for the files of an entity's items shown by a data
* block; never a key outside that entity (`entities/{entityId}/…`).
*/
function itemSigner(entityId) {
const prefix = `entities/${entityId}/`
return async (key) => {
const bucket = process.env.ATTACHMENTS_BUCKET_NAME
if (!bucket || typeof key !== 'string' || !key.startsWith(prefix) || key.includes('..')) {
return undefined
}
return getSignedUrl(s3Client, new GetObjectCommand({ Bucket: bucket, Key: key }), {
expiresIn: IMAGE_URL_TTL_SECONDS
})
}
}
/** One page record, or undefined */
async function getPage(docClient, flowId, slug) {
const result = await docClient.send(
new GetCommand({ TableName: process.env.FLOW_PAGES_TABLE_NAME, Key: { flowId, slug } })
)
return result.Item
}
/**
* Every page of a flow (at most LIMITS.pagesPerFlow, so one or two pages of
* Query results), optionally projected
*/
async function listPages(docClient, flowId, projection) {
const pages = []
let ExclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: process.env.FLOW_PAGES_TABLE_NAME,
KeyConditionExpression: 'flowId = :flowId',
ExpressionAttributeValues: { ':flowId': flowId },
...projection,
ExclusiveStartKey
})
)
pages.push(...(result.Items || []))
ExclusiveStartKey = result.LastEvaluatedKey
} while (ExclusiveStartKey)
return pages
}
/**
* The caller's access to the flow named in the path: it must be their
* verified active flow (X-Flow-Id), so a permission held in one flow never
* acts on another flow's pages. `canEdit`: they hold `pages:update`.
* @returns {Promise<{ userId, flowId, canEdit } | { response }>}
*/
async function memberAccess(event) {
const userId = event.requestContext?.authorizer?.claims?.sub
if (!userId) return { response: respond(401, { error: 'Not authenticated' }) }
const flowId = event.pathParameters?.flowId
const activeFlow = await resolveActiveFlow(event)
if (!flowId || activeFlow?.flowId !== flowId) {
return { response: respond(403, { error: 'Access denied - not your active flow' }) }
}
const { hasPermission } = await permissionChecker.hasPermission(userId, flowId, 'pages:update', {
membership: activeFlow.membership
})
return { userId, flowId, canEdit: hasPermission, membership: activeFlow.membership }
}
const forbidden = () =>
respond(403, { error: 'Forbidden - Insufficient permissions', required: 'pages:update' })
const pageNotFound = () => respond(404, { error: 'Page not found' })
/**
* 409 PAGE_LINKED when the published version of another page links to
* `slug`, which therefore can't go away (UC-SPACE-016.1); null otherwise
*/
async function refuseIfLinked(docClient, flowId, slug) {
const pages = await listPages(docClient, flowId, { ProjectionExpression: 'slug, published' })
const linking = pagesLinkingTo(pages, slug)
return linking.length ? respond(409, { error: 'PAGE_LINKED', pages: linking }) : null
}
/**
* The flow whose space is published at `slug`, or null: an unknown slug, a
* flow that isn't active and an unpublished space look the same, so the
* public endpoints never tell whether a private flow exists.
*/
async function loadSpaceFlow(docClient, slug) {
if (typeof slug !== 'string' || !SPACE_SLUG_REGEX.test(slug)) return null
const slugResult = await docClient.send(
new GetCommand({ TableName: process.env.FLOW_SLUGS_TABLE_NAME, Key: { slug } })
)
const flowId = slugResult.Item?.flowId
if (!flowId) return null
const flowResult = await docClient.send(
new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: flowId } })
)
const flow = flowResult.Item
return flow && flow.status === 'active' && flow.space?.enabled === true ? flow : null
}
/**
* A version of a page as returned to a reader: images signed, data blocks
* with their items (utils/spaceData.js). `draft`: an unavailable data block is
* kept and marked, for the editor, instead of left out.
*/
async function readableVersion(docClient, version, flowId, { draft = false } = {}) {
const blocks = await resolveBlocks(docClient, version.blocks, {
flowId,
itemSigner,
draft
})
return {
title: version.title,
blocks: await withImageUrls(blocks, imageSigner(flowId)),
...(version.publishedAt && { publishedAt: version.publishedAt })
}
}
/**
* The next items of an item list of a published version ("load more",
* UC-SPACE-019.1), from `?offset=`: a response, 404 for an unknown block or
* offset
*/
async function publishedBlockItems(docClient, event, version, flowId, reply = respond) {
const blockId = event.pathParameters?.blockId
const offset = Number(event.queryStringParameters?.offset ?? 0)
const block = (version.blocks || []).find((b) => b.id === blockId)
const result = block
? await resolveListItems(docClient, block, { flowId, itemSigner, offset })
: null
return result ? reply(200, result) : reply(404, { error: 'Block not found' })
}
/**
* Whether the draft differs from the published version (or nothing is
* published). Compared by content, not as JSON: DynamoDB doesn't keep the
* order of a map's keys, so the same content can come back in another order.
*/
function hasUnpublishedChanges(page) {
if (!page.published) return true
const { title, blocks } = page.published
const published = { title, blocks: (blocks || []).map(withoutFrozenFields) }
return !isDeepStrictEqual(page.draft, published)
}
/** What an editor gets of a page: its settings and its draft, images signed */
async function editorView(docClient, page) {
return {
slug: page.slug,
visibility: page.visibility,
showInMenu: page.showInMenu,
menuOrder: page.menuOrder,
...(page.icon && { icon: page.icon }),
draft: await readableVersion(docClient, page.draft, page.flowId, { draft: true }),
published: page.published
? { title: page.published.title, publishedAt: page.published.publishedAt }
: null,
hasUnpublishedChanges: hasUnpublishedChanges(page),
updatedAt: page.updatedAt
}
}
/** Deletes the images `before` used that `after` (null: deleted page) no longer uses */
async function deleteUnusedImages(flowId, before, after) {
const kept = pageImageKeys(after)
const unused = [...pageImageKeys(before)].filter((key) => !kept.has(key))
if (unused.length === 0) return
try {
await deleteKeys(s3Client, process.env.ATTACHMENTS_BUCKET_NAME, unused, flowKeyGuard(flowId))
} catch (error) {
console.error('Failed to delete unused page images:', { flowId, error })
}
}
module.exports = {
CORS_HEADERS,
PUBLIC_CACHE_CONTROL,
respond,
respondPublic,
imageSigner,
itemSigner,
getPage,
listPages,
memberAccess,
forbidden,
pageNotFound,
refuseIfLinked,
loadSpaceFlow,
readableVersion,
publishedBlockItems,
hasUnpublishedChanges,
editorView,
deleteUnusedImages
}
|