All files / flows get-space.js

100% Statements 41/41
100% Branches 34/34
100% Functions 6/6
100% Lines 35/35

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  1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x   7x               14x 14x 9x                         1x 15x 15x 15x   13x     12x 12x   11x     11x 11x   7x                   7x 7x   7x                             2x   3x                 1x 1x      
// @implements UC-SPACE-021.1, UC-SPACE-002.1, UC-SPACE-004.1, UC-SPACE-010.1, UC-SPACE-018.1
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3')
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner')
const { flowKeyGuard } = require('../utils/s3Cleanup')
const { isJoinOpen } = require('../utils/spaceJoin')
const { buildMenu, HOME_SLUG } = require('../utils/spacePages')
const { listPages, respondPublic } = require('../space-pages/shared')
 
const client = new DynamoDBClient({})
const ddb = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const SLUG_REGEX = /^[a-z0-9-]{1,100}$/
const IMAGE_URL_TTL_SECONDS = 3600
 
const notFound = () => respondPublic(404, { error: 'Space not found' })
 
/**
 * Signs a read URL for the flow's picture/icon. The visitor may have no
 * account, so the usual authenticated presigned-read-url endpoint can't be
 * used; the key guard keeps this from ever signing a key outside the flow.
 */
async function signedImageUrl(flowId, key) {
  const bucket = process.env.ATTACHMENTS_BUCKET_NAME
  if (!bucket || typeof key !== 'string' || !flowKeyGuard(flowId)(key)) return undefined
  return getSignedUrl(s3Client, new GetObjectCommand({ Bucket: bucket, Key: key }), {
    expiresIn: IMAGE_URL_TTL_SECONDS
  })
}
 
/**
 * Get a flow's public space (public, no authentication)
 * GET /v1/spaces/{slug}
 *
 * Only public fields are returned. A flow that doesn't exist, isn't active or
 * hasn't published its space gives the same 404, so the endpoint never tells
 * whether a private flow exists.
 */
exports.handler = async (event) => {
  try {
    const slug = event.pathParameters?.slug
    if (typeof slug !== 'string' || !SLUG_REGEX.test(slug)) return notFound()
 
    const slugResult = await ddb.send(
      new GetCommand({ TableName: process.env.FLOW_SLUGS_TABLE_NAME, Key: { slug } })
    )
    const flowId = slugResult.Item?.flowId
    if (!flowId) return notFound()
 
    const flowResult = await ddb.send(
      new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: flowId } })
    )
    const flow = flowResult.Item
    if (!flow || flow.status !== 'active' || flow.space?.enabled !== true) return notFound()
 
    const [pictureUrl, iconUrl, pages] = await Promise.all([
      signedImageUrl(flowId, flow.picture),
      signedImageUrl(flowId, flow.icon),
      // Only what the menu needs: never a draft nor a page's blocks
      listPages(ddb, flowId, {
        ProjectionExpression:
          'slug, visibility, showInMenu, menuOrder, #icon, published.title, published.publishedAt',
        ExpressionAttributeNames: { '#icon': 'icon' }
      })
    ])
    const publicPages = pages.filter((page) => page.published && page.visibility === 'everyone')
    const defaultLanguage = flow.defaultLanguage || 'en'
 
    return respondPublic(200, {
      slug: flow.slug,
      name: flow.name,
      defaultLanguage,
      // The languages the flow's content is written in: the reader picks one of them
      languages:
        Array.isArray(flow.enabledLanguages) && flow.enabledLanguages.length
          ? flow.enabledLanguages
          : [defaultLanguage],
      theme: flow.space.theme || {},
      // Only whether a join form exists: the membership entity stays private
      joinOpen: isJoinOpen(flow),
      // The published pages for everyone (UC-SPACE-010.1); a member's browser
      // adds the members-only ones from GET /v1/flows/{flowId}/pages
      menu: buildMenu(publicPages),
      hasHome: publicPages.some((page) => page.slug === HOME_SLUG),
      // Every page visible to everyone, in the menu or not, for its sitemap (UC-SPACE-021.1)
      publicPages: publicPages.map((page) => ({
        slug: page.slug,
        ...(page.published.publishedAt && { publishedAt: page.published.publishedAt })
      })),
      ...(flow.description && { description: flow.description }),
      ...(pictureUrl && { pictureUrl }),
      ...(iconUrl && { iconUrl })
    })
  } catch (error) {
    console.error('Error getting flow space:', error)
    return respondPublic(500, { error: 'Failed to get space' })
  }
}