All files / utils entityImageCopy.js

93.47% Statements 43/46
80.95% Branches 34/42
100% Functions 9/9
100% Lines 38/38

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 1493x 3x   3x         9x     8x         8x 8x 2x   8x                                           16x   16x   16x       16x 16x     15x               13x   3x     3x         28x   28x 5x 5x   5x 1x   2x                   4x                               5x 5x             5x       38x   33x 11x 11x   4x 1x   2x                 3x                   3x  
const { S3Client, CopyObjectCommand, HeadObjectCommand } = require('@aws-sdk/client-s3')
const { randomUUID } = require('crypto')
 
const s3Client = new S3Client({})
 
// MetadataDirective REPLACE also resets Content-Type & co. to S3 defaults, so
// the source's own headers are read first and carried over explicitly.
async function buildOwnerOverrides({ sourceKey, targetEntityId, targetItemId, owner }) {
  const head = await s3Client.send(
    new HeadObjectCommand({ Bucket: process.env.ATTACHMENTS_BUCKET_NAME, Key: sourceKey })
  )
  const metadata = {
    ...(head.Metadata || {}),
    userid: owner.userId,
    entityid: targetEntityId
  }
  if (owner.flowId) metadata.flowid = owner.flowId
  if (targetItemId) metadata.itemid = targetItemId
  else delete metadata.itemid
 
  return {
    MetadataDirective: 'REPLACE',
    Metadata: metadata,
    ...(head.ContentType && { ContentType: head.ContentType }),
    ...(head.CacheControl && { CacheControl: head.CacheControl }),
    ...(head.ContentDisposition && { ContentDisposition: head.ContentDisposition })
  }
}
 
// Copied items/entities must not share S3 objects with the source: if the
// source image is later deleted (e.g. via clear-all), the copy would lose
// its image. The target key is entityId-scoped, no flowId segment — same key
// shape as regular entity/item uploads (see uploads/presigned-url.js), so the
// copy's images stay reachable even if the target entity is later
// transferred to another flow (UC-FLOW-007.1 AC-4).
//
// `owner` ({ userId, flowId }) is who the copy is billed to: S3 `CopyObject`
// keeps the *source* object's Metadata by default, and the s3_storage credit
// consumer (uploads/s3-usage-consumer.js) debits whichever `userid` it finds
// there — i.e. the original uploader, not the person forking. When given, the
// copy's Metadata is replaced so the copier is charged instead.
async function copyImageObject({ sourceKey, targetEntityId, targetItemId, fieldId, owner }) {
  Iif (!sourceKey || typeof sourceKey !== 'string') return sourceKey
 
  const extension = sourceKey.includes('.') ? sourceKey.split('.').pop() : 'bin'
  // The entity's own picture/icon has no itemId segment (see uploads/presigned-url.js).
  const targetKey = targetItemId
    ? `entities/${targetEntityId}/${targetItemId}/${fieldId}/${randomUUID()}.${extension}`
    : `entities/${targetEntityId}/${fieldId}/${randomUUID()}.${extension}`
 
  try {
    const ownerOverrides = owner
      ? await buildOwnerOverrides({ sourceKey, targetEntityId, targetItemId, owner })
      : {}
    await s3Client.send(
      new CopyObjectCommand({
        Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
        Key: targetKey,
        CopySource: encodeURIComponent(`${process.env.ATTACHMENTS_BUCKET_NAME}/${sourceKey}`),
        ...ownerOverrides
      })
    )
    return targetKey
  } catch (error) {
    console.error(`Failed to copy S3 object ${sourceKey}:`, error.message)
    // Fall back to the source key so the copy still has a (shared) image
    // rather than losing it entirely.
    return sourceKey
  }
}
 
async function copyImageFields({ item, fields, targetEntityId, owner }) {
  const imageFields = (fields || []).filter((f) => f.type === 'image' || f.type === 'image_set')
 
  for (const field of imageFields) {
    const value = item[field.fieldId]
    Iif (!value) continue
 
    if (Array.isArray(value)) {
      item[field.fieldId] = await Promise.all(
        value.map((key) =>
          copyImageObject({
            sourceKey: key,
            targetEntityId,
            targetItemId: item.id,
            fieldId: field.fieldId,
            owner
          })
        )
      )
    } else {
      item[field.fieldId] = await copyImageObject({
        sourceKey: value,
        targetEntityId,
        targetItemId: item.id,
        fieldId: field.fieldId,
        owner
      })
    }
  }
}
 
// A `file`/`file_set` value is `{ key, name, size, type }` (see
// item-data-schema.js's checkFileField), not a bare key like image/image_set
// — copyImageObject only touches `.key`, everything else about the value is
// preserved as-is.
async function copyFileObject(fileValue, { targetEntityId, targetItemId, fieldId, owner }) {
  Iif (!fileValue || typeof fileValue !== 'object') return fileValue
  const key = await copyImageObject({
    sourceKey: fileValue.key,
    targetEntityId,
    targetItemId,
    fieldId,
    owner
  })
  return { ...fileValue, key }
}
 
async function copyFileFields({ item, fields, targetEntityId, owner }) {
  const fileFields = (fields || []).filter((f) => f.type === 'file' || f.type === 'file_set')
 
  for (const field of fileFields) {
    const value = item[field.fieldId]
    if (!value) continue
 
    if (Array.isArray(value)) {
      item[field.fieldId] = await Promise.all(
        value.map((fileValue) =>
          copyFileObject(fileValue, {
            targetEntityId,
            targetItemId: item.id,
            fieldId: field.fieldId,
            owner
          })
        )
      )
    } else {
      item[field.fieldId] = await copyFileObject(value, {
        targetEntityId,
        targetItemId: item.id,
        fieldId: field.fieldId,
        owner
      })
    }
  }
}
 
module.exports = { copyImageObject, copyImageFields, copyFileFields }