All files / utils spaceJoin.js

100% Statements 108/108
96.26% Branches 103/107
100% Functions 17/17
100% Lines 88/88

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              13x               13x                               13x   13x 13x   13x 39x   119x     13x   85x                       34x 20x   19x 1x   18x   18x 70x 43x 1x   42x     17x 16x 1x   15x 1x             1x 1x 1x     15x 15x 2x         1x   1x     14x         43x   238x                             14x           14x 1x     13x   12x     12x 12x 2x   10x   10x 10x 1x     9x   41x           9x 1x             8x 10x 3x 1x         2x 4x 1x             6x               11x 19x 10x 9x 16x 8x         64x               13x                   64x   61x     60x 60x   57x     57x 57x   44x 44x   42x     42x 42x   36x               19x 19x 18x 53x 31x     18x     13x                        
// @implements UC-SPACE-003.1, UC-SPACE-004.1, UC-SPACE-006.1, UC-SPACE-020.1
/**
 * Joining a flow from its public space (docs/architecture/FLOW_SPACE.md,
 * "Membership requests"): the `space.join` settings, which of the membership
 * entity's fields the public join form can show, and how a slug resolves to a
 * flow whose joining is open.
 */
const { GetCommand } = require('@aws-sdk/lib-dynamodb')
 
/**
 * Field types the join form renders. Images and files go through the
 * request's own uploads (utils/membershipRequestFiles.js). Anything else needs
 * a read of the flow's private data (relations, users, entity references) or
 * is set by the server (workflow).
 */
const JOIN_FIELD_TYPES = [
  'text',
  'textarea',
  'email',
  'number',
  'date',
  'select',
  'multiselect',
  'boolean',
  'image',
  'image_set',
  'file',
  'file_set'
]
 
/** A flow can't be flooded: beyond this many pending requests, new ones are refused */
const MAX_PENDING_REQUESTS = 500
 
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const MAX_PRIVACY_CONTACT_LENGTH = 254
 
const isPlainObject = (value) =>
  value !== null && typeof value === 'object' && !Array.isArray(value)
 
const isNonEmptyString = (value) => typeof value === 'string' && value.trim().length > 0
 
/** Optional keys: an id when set, otherwise absent */
const OPTIONAL_ID_KEYS = ['entityId', 'userFieldId', 'formerMemberFieldId', 'formerMemberStateId']
 
const isUnset = (value) => value === undefined || value === null || value === ''
 
/**
 * Shape check of `space.join` (no database read): ids are strings, the privacy
 * contact an email. Unknown keys are dropped. `null`/absent means joining is
 * closed. The membership entity is optional; with one, the member field is
 * required and the former member state (a workflow field and one of its
 * states) optional.
 * @param {unknown} join
 * @returns {{ valid: true, value: object | undefined } | { valid: false, error: string }}
 */
function validateJoinShape(join) {
  if (join === undefined || join === null) return { valid: true, value: undefined }
  if (!isPlainObject(join)) return { valid: false, error: 'space.join must be an object' }
 
  if (!isNonEmptyString(join.defaultRoleId)) {
    return { valid: false, error: 'space.join.defaultRoleId must be a non-empty string' }
  }
  const value = { defaultRoleId: join.defaultRoleId }
 
  for (const key of OPTIONAL_ID_KEYS) {
    if (isUnset(join[key])) continue
    if (!isNonEmptyString(join[key])) {
      return { valid: false, error: `space.join.${key} must be a non-empty string` }
    }
    value[key] = join[key]
  }
 
  if (value.entityId) {
    if (!value.userFieldId) {
      return { valid: false, error: 'space.join.userFieldId is required with an entityId' }
    }
    if (!!value.formerMemberFieldId !== !!value.formerMemberStateId) {
      return {
        valid: false,
        error: 'space.join.formerMemberFieldId and formerMemberStateId go together'
      }
    }
  } else {
    // Without a membership entity there is no member field nor former member state
    delete value.userFieldId
    delete value.formerMemberFieldId
    delete value.formerMemberStateId
  }
 
  const contact = join.privacyContact
  if (!isUnset(contact)) {
    if (
      typeof contact !== 'string' ||
      contact.length > MAX_PRIVACY_CONTACT_LENGTH ||
      !EMAIL_REGEX.test(contact.trim())
    ) {
      return { valid: false, error: 'space.join.privacyContact must be an email' }
    }
    value.privacyContact = contact.trim()
  }
 
  return { valid: true, value }
}
 
/** The membership entity's fields the join form shows: supported types, never the member field */
function joinFormFields(entity, userFieldId) {
  return (entity?.fields || []).filter(
    (field) =>
      field.fieldId &&
      field.fieldId !== userFieldId &&
      !field.deprecated &&
      JOIN_FIELD_TYPES.includes(field.type)
  )
}
 
/**
 * Checks `space.join` against the flow's data: the role is one of the flow's
 * and, with a membership entity, the entity is one of the flow's, the member
 * field a `user` field of it, every mandatory field one the join form can show,
 * and the former member state a state of one of its workflow fields.
 * @returns {Promise<{ valid: true } | { valid: false, error: string, fieldId?: string }>}
 */
async function validateJoinTargets(docClient, flowId, join) {
  const roleResult = await docClient.send(
    new GetCommand({
      TableName: process.env.ROLES_TABLE_NAME,
      Key: { PK: `FLOW#${flowId}`, SK: `ROLE#${join.defaultRoleId}` }
    })
  )
  if (!roleResult.Item) {
    return { valid: false, error: 'space.join.defaultRoleId must be a role of this flow' }
  }
 
  if (!join.entityId) return { valid: true }
 
  const entityResult = await docClient.send(
    new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: join.entityId } })
  )
  const entity = entityResult.Item
  if (!entity || entity.flowId !== flowId) {
    return { valid: false, error: 'space.join.entityId must be an entity of this flow' }
  }
  const fields = entity.fields || []
 
  const userField = fields.find((field) => field.fieldId === join.userFieldId)
  if (!userField || userField.type !== 'user') {
    return { valid: false, error: 'space.join.userFieldId must be a user field of the entity' }
  }
 
  const unsupported = fields.find(
    (field) =>
      field.mandatory &&
      !field.deprecated &&
      field.fieldId !== join.userFieldId &&
      field.type !== 'workflow' &&
      !JOIN_FIELD_TYPES.includes(field.type)
  )
  if (unsupported) {
    return {
      valid: false,
      error: 'JOIN_FORM_UNSUPPORTED_MANDATORY_FIELD',
      fieldId: unsupported.fieldId
    }
  }
 
  if (join.formerMemberFieldId) {
    const workflowField = fields.find((field) => field.fieldId === join.formerMemberFieldId)
    if (workflowField?.type !== 'workflow' || !workflowField.workflowDefinition) {
      return {
        valid: false,
        error: 'space.join.formerMemberFieldId must be a workflow field of the entity'
      }
    }
    const states = workflowField.workflowDefinition.states || []
    if (!states.some((state) => state.id === join.formerMemberStateId)) {
      return {
        valid: false,
        error: 'space.join.formerMemberStateId must be a state of that workflow'
      }
    }
  }
 
  return { valid: true }
}
 
/**
 * The former member state of `join`, when its membership entity (`entity`)
 * still has it: the workflow field and the state ids, else null.
 */
function formerMemberState(join, entity) {
  if (!join?.formerMemberFieldId || !join.formerMemberStateId || !entity) return null
  const field = (entity.fields || []).find((f) => f.fieldId === join.formerMemberFieldId)
  if (field?.type !== 'workflow' || !field.workflowDefinition) return null
  const states = field.workflowDefinition.states || []
  if (!states.some((state) => state.id === join.formerMemberStateId)) return null
  return { field, stateId: join.formerMemberStateId }
}
 
/** Whether a flow record is open to membership requests */
function isJoinOpen(flow) {
  return (
    !!flow &&
    flow.status === 'active' &&
    flow.space?.enabled === true &&
    isNonEmptyString(flow.space?.join?.defaultRoleId)
  )
}
 
const SLUG_REGEX = /^[a-z0-9-]{1,100}$/
 
/**
 * Resolves a slug to a flow open to membership requests, with its membership
 * entity (null when the flow has none). Null for an unknown slug, a closed
 * space or a membership entity deleted since alike, so callers answer the same
 * 404 for each.
 * @returns {Promise<{ flow: object, entity: object | null } | null>}
 */
async function loadJoinableFlow(docClient, slug) {
  if (typeof slug !== 'string' || !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
  if (!isJoinOpen(flow)) return null
 
  const entityId = flow.space.join.entityId
  if (!entityId) return { flow, entity: null }
 
  const entityResult = await docClient.send(
    new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: entityId } })
  )
  const entity = entityResult.Item
  if (!entity || entity.flowId !== flowId) return null
 
  return { flow, entity }
}
 
/**
 * Keeps only the answers to fields the join form shows, so a requester can't
 * set the member field, a workflow state or any field hidden from them.
 */
function pickAnswers(fields, answers) {
  const picked = {}
  if (!isPlainObject(answers)) return picked
  for (const field of fields) {
    if (Object.prototype.hasOwnProperty.call(answers, field.fieldId)) {
      picked[field.fieldId] = answers[field.fieldId]
    }
  }
  return picked
}
 
module.exports = {
  JOIN_FIELD_TYPES,
  MAX_PENDING_REQUESTS,
  validateJoinShape,
  validateJoinTargets,
  joinFormFields,
  formerMemberState,
  isJoinOpen,
  loadJoinableFlow,
  pickAnswers,
  SLUG_REGEX
}