@payloadcms/figma 0.1.0-internal.10c3b07 → 0.1.0-internal.fbdc0d3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/{utils → adapters}/asset-collection.d.ts +10 -4
  3. package/dist/{utils → adapters}/asset-collection.js +58 -17
  4. package/dist/{utils → adapters}/build-lambda-zip.d.ts +4 -2
  5. package/dist/adapters/build-lambda-zip.js +111 -0
  6. package/dist/adapters/configureNextjsCache.d.ts +8 -0
  7. package/dist/adapters/configureNextjsCache.js +55 -0
  8. package/dist/{utils → adapters}/deploy-output/resolveOutputPath.d.ts +1 -1
  9. package/dist/adapters/fs-utils.d.ts +39 -0
  10. package/dist/adapters/fs-utils.js +135 -0
  11. package/dist/adapters/index.d.ts +4 -0
  12. package/dist/adapters/index.js +3 -0
  13. package/dist/adapters/lambda-runtime/nextjs-cache.d.ts +40 -0
  14. package/dist/adapters/lambda-runtime/nextjs-cache.js +174 -0
  15. package/dist/adapters/nextjs.d.ts +12 -0
  16. package/dist/adapters/nextjs.js +67 -0
  17. package/dist/{utils/adapters → adapters}/nitro.d.ts +2 -2
  18. package/dist/{utils/adapters → adapters}/nitro.js +54 -29
  19. package/dist/adapters/secret-files.d.ts +25 -0
  20. package/dist/adapters/secret-files.js +50 -0
  21. package/dist/adapters/types.d.ts +42 -0
  22. package/dist/adapters/types.js +1 -0
  23. package/dist/{utils/adapters → adapters}/vite.d.ts +1 -1
  24. package/dist/{utils/adapters → adapters}/vite.js +4 -3
  25. package/dist/api/control-plane.d.ts +11 -0
  26. package/dist/api/control-plane.js +26 -0
  27. package/dist/auth/headless-oauth-flow.js +4 -0
  28. package/dist/auth/oauth-flow.js +17 -0
  29. package/dist/auth/refresh.js +12 -12
  30. package/dist/auth/requested-scopes.d.ts +1 -0
  31. package/dist/auth/requested-scopes.js +3 -0
  32. package/dist/auth/token-store.d.ts +16 -0
  33. package/dist/auth/token-store.js +33 -0
  34. package/dist/auth/types.d.ts +5 -3
  35. package/dist/commands/bootstrap.js +3 -0
  36. package/dist/commands/build-lambda-zip.js +1 -1
  37. package/dist/commands/deploy.js +2 -2
  38. package/dist/commands/init.js +72 -2
  39. package/dist/commands/upgrade.js +65 -1
  40. package/dist/commands/upload-schema.js +3 -4
  41. package/dist/config/oauth.js +6 -1
  42. package/dist/constants.d.ts +0 -2
  43. package/dist/constants.js +0 -3
  44. package/dist/db-content-api/generated/content-api-types.d.ts +6 -2
  45. package/dist/db-content-api/utilities/auth.d.ts +1 -4
  46. package/dist/db-content-api/utilities/auth.js +1 -1
  47. package/dist/db-content-api/utilities/data/index.js +8 -2
  48. package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts +3 -11
  49. package/dist/db-content-api/utilities/data/removeVirtualFields.js +12 -50
  50. package/dist/db-content-api/utilities/schema/buildDocumentSchema.js +9 -4
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +2 -0
  53. package/dist/next/image-loader.d.ts +6 -0
  54. package/dist/next/image-loader.js +14 -0
  55. package/dist/oauth/components/LoginButton/index.js +66 -19
  56. package/dist/oauth/components/LoginButton/index.scss +121 -15
  57. package/dist/oauth/defaults.js +4 -1
  58. package/dist/plugin/build-config.d.ts +13 -3
  59. package/dist/plugin/build-config.js +198 -59
  60. package/dist/plugin/cache-revalidation-hooks.d.ts +6 -0
  61. package/dist/plugin/cache-revalidation-hooks.js +69 -0
  62. package/dist/plugin/cloud-limits/CloudLimitModal/index.d.ts +2 -1
  63. package/dist/plugin/cloud-limits/icons/ExternalLinkIcon.d.ts +2 -1
  64. package/dist/plugin/make-permission-access/make-permission-access.d.ts +8 -0
  65. package/dist/plugin/make-permission-access/make-permission-access.js +24 -0
  66. package/dist/storage-content-api/api-types.d.ts +5 -2
  67. package/dist/storage-content-api/buildBaseMediaResponseHeaders.d.ts +1 -1
  68. package/dist/storage-content-api/buildBaseMediaResponseHeaders.js +3 -1
  69. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.d.ts +8 -6
  70. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.js +17 -12
  71. package/dist/storage-content-api/buildMediaRequestHeaders.d.ts +1 -0
  72. package/dist/storage-content-api/buildMediaRequestHeaders.js +14 -0
  73. package/dist/storage-content-api/buildMediaResponseHeaders.d.ts +3 -3
  74. package/dist/storage-content-api/buildMediaResponseHeaders.js +25 -18
  75. package/dist/storage-content-api/client-uploads/generate.d.ts +7 -3
  76. package/dist/storage-content-api/client-uploads/generate.js +22 -21
  77. package/dist/storage-content-api/client.d.ts +0 -2
  78. package/dist/storage-content-api/client.js +2 -2
  79. package/dist/storage-content-api/copyFile.d.ts +16 -0
  80. package/dist/storage-content-api/copyFile.js +90 -0
  81. package/dist/storage-content-api/deleteFile.d.ts +8 -0
  82. package/dist/storage-content-api/deleteFile.js +18 -0
  83. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.d.ts +11 -0
  84. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.js +33 -0
  85. package/dist/storage-content-api/getMediaType.d.ts +1 -0
  86. package/dist/storage-content-api/getMediaType.js +3 -0
  87. package/dist/storage-content-api/handleUpload.d.ts +1 -2
  88. package/dist/storage-content-api/handleUpload.js +13 -157
  89. package/dist/storage-content-api/hasSupportedContentEncoding.d.ts +1 -1
  90. package/dist/storage-content-api/hasSupportedContentEncoding.js +4 -2
  91. package/dist/storage-content-api/index.js +17 -8
  92. package/dist/storage-content-api/mediaErrorResponse.d.ts +1 -1
  93. package/dist/storage-content-api/mediaErrorResponse.js +2 -2
  94. package/dist/storage-content-api/resolveDownloadResponseHeaders.d.ts +5 -0
  95. package/dist/storage-content-api/resolveDownloadResponseHeaders.js +13 -0
  96. package/dist/storage-content-api/shouldAttachMedia.d.ts +1 -0
  97. package/dist/storage-content-api/{getInlineContentType.js → shouldAttachMedia.js} +8 -7
  98. package/dist/storage-content-api/staticHandler.d.ts +2 -1
  99. package/dist/storage-content-api/staticHandler.js +47 -53
  100. package/dist/storage-content-api/types.d.ts +4 -1
  101. package/dist/storage-content-api/uploadFileData.d.ts +10 -0
  102. package/dist/storage-content-api/uploadFileData.js +145 -0
  103. package/dist/utils/build-detection.js +3 -3
  104. package/dist/utils/cache-bootstrap.js +1 -0
  105. package/dist/utils/deploy-adapter.d.ts +2 -34
  106. package/dist/utils/deploy-adapter.js +16 -9
  107. package/dist/utils/env-management.d.ts +15 -0
  108. package/dist/utils/env-management.js +47 -0
  109. package/dist/utils/lambda-config.js +14 -9
  110. package/dist/utils/load-payload-config.js +1 -6
  111. package/dist/utils/next-image-loader-config.d.ts +2 -0
  112. package/dist/utils/next-image-loader-config.js +63 -0
  113. package/dist/utils/next-image-loader-file.d.ts +2 -0
  114. package/dist/utils/next-image-loader-file.js +11 -0
  115. package/dist/utils/payload-config-ast.d.ts +5 -0
  116. package/dist/utils/payload-config-ast.js +73 -4
  117. package/dist/utils/payload-config-modifier.js +3 -0
  118. package/dist/utils/payload-secret.d.ts +28 -0
  119. package/dist/utils/payload-secret.js +34 -0
  120. package/package.json +22 -10
  121. package/dist/storage-content-api/getInlineContentType.d.ts +0 -1
  122. package/dist/storage-content-api/handleDelete.d.ts +0 -7
  123. package/dist/storage-content-api/handleDelete.js +0 -15
  124. package/dist/storage-content-api/utilities/getSafeFilename.d.ts +0 -11
  125. package/dist/storage-content-api/utilities/getSafeFilename.js +0 -59
  126. package/dist/storage-content-api/utilities/index.d.ts +0 -2
  127. package/dist/storage-content-api/utilities/index.js +0 -2
  128. package/dist/storage-content-api/utilities/parseUploadReference.d.ts +0 -17
  129. package/dist/storage-content-api/utilities/parseUploadReference.js +0 -27
  130. package/dist/utils/adapters/nextjs.d.ts +0 -8
  131. package/dist/utils/adapters/nextjs.js +0 -64
  132. package/dist/utils/build-lambda-zip.js +0 -73
  133. package/dist/utils/fs-utils.d.ts +0 -12
  134. package/dist/utils/fs-utils.js +0 -55
  135. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput/getNextRelativeAppDir.d.ts +0 -0
  136. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput/getNextRelativeAppDir.js +0 -0
  137. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput.d.ts +0 -0
  138. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput.js +0 -0
  139. /package/dist/{utils → adapters}/deploy-output/inspectNitroOutput.d.ts +0 -0
  140. /package/dist/{utils → adapters}/deploy-output/inspectNitroOutput.js +0 -0
  141. /package/dist/{utils → adapters}/deploy-output/isFile.d.ts +0 -0
  142. /package/dist/{utils → adapters}/deploy-output/isFile.js +0 -0
  143. /package/dist/{utils → adapters}/deploy-output/readJson.d.ts +0 -0
  144. /package/dist/{utils → adapters}/deploy-output/readJson.js +0 -0
  145. /package/dist/{utils → adapters}/deploy-output/resolveNitroOutputLayout.d.ts +0 -0
  146. /package/dist/{utils → adapters}/deploy-output/resolveNitroOutputLayout.js +0 -0
  147. /package/dist/{utils → adapters}/deploy-output/resolveOutputPath.js +0 -0
  148. /package/dist/{utils → adapters}/deploy-output/resolveWithin.d.ts +0 -0
  149. /package/dist/{utils → adapters}/deploy-output/resolveWithin.js +0 -0
@@ -1,5 +1,6 @@
1
1
  import { buildBaseMediaResponseHeaders } from './buildBaseMediaResponseHeaders.js';
2
- import { getInlineContentType } from './getInlineContentType.js';
2
+ import { getMediaType } from './getMediaType.js';
3
+ import { shouldAttachMedia } from './shouldAttachMedia.js';
3
4
  const FORWARDED_MEDIA_RESPONSE_HEADERS = [
4
5
  'Cache-Control',
5
6
  'Content-Length',
@@ -8,38 +9,44 @@ const FORWARDED_MEDIA_RESPONSE_HEADERS = [
8
9
  'Last-Modified'
9
10
  ];
10
11
  const ATTACHMENT_CSP = "sandbox; default-src 'none'; base-uri 'none'; form-action 'none'";
11
- export const buildMediaResponseHeaders = ({ filename, upstream })=>{
12
+ export function buildMediaResponseHeaders({ filename, upstreamHeaders }) {
12
13
  const headers = buildBaseMediaResponseHeaders();
13
14
  for (const name of FORWARDED_MEDIA_RESPONSE_HEADERS){
14
- const value = upstream.get(name);
15
+ const value = upstreamHeaders.get(name);
15
16
  if (value) {
16
17
  headers.set(name, value);
17
18
  }
18
19
  }
19
- const contentType = getInlineContentType(upstream.get('Content-Type'));
20
- if (contentType) {
21
- headers.set('Content-Type', contentType);
22
- } else {
20
+ if (shouldAttachMedia(upstreamHeaders)) {
23
21
  headers.set('Content-Type', 'application/octet-stream');
24
22
  headers.set('Content-Disposition', attachmentDisposition(filename));
25
23
  headers.set('Content-Security-Policy', ATTACHMENT_CSP);
24
+ } else {
25
+ // Send only the approved media type; do not pass through untrusted parameters.
26
+ headers.set('Content-Type', getMediaType(upstreamHeaders));
26
27
  }
27
28
  return headers;
28
- };
29
- const attachmentDisposition = (filename)=>{
30
- let decodedName;
29
+ }
30
+ function attachmentDisposition(filename) {
31
+ const sanitizedName = sanitizeFilename(filename);
32
+ const safeName = Array.from(sanitizedName).slice(0, 255).join('') || 'download';
33
+ let utf8Name;
31
34
  try {
32
- decodedName = decodeURIComponent(filename);
35
+ // encodeURIComponent leaves !, ', (, ), and * unchanged. Encode those five characters as % escapes.
36
+ utf8Name = encodeURIComponent(safeName).replace(/[!'()*]/g, (character)=>`%${character.charCodeAt(0).toString(16).toUpperCase()}`);
33
37
  } catch {
34
- decodedName = 'download';
38
+ // Invalid UTF-16, such as an unpaired surrogate, cannot be encoded in filename*.
39
+ return `attachment; filename="download"; filename*=UTF-8''download`;
35
40
  }
36
- const sanitizedName = sanitizeFilename(decodedName);
37
- const safeName = Array.from(sanitizedName).slice(0, 255).join('') || 'download';
38
- const asciiName = safeName.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
39
- const utf8Name = encodeURIComponent(safeName).replace(/[!'()*]/g, (character)=>`%${character.charCodeAt(0).toString(16).toUpperCase()}`);
41
+ // Replace non-ASCII and control characters, quotes, backslashes, and % with underscores.
42
+ const asciiName = safeName.replace(/[^\x20-\x7e]/g, '_').replace(/["\\%]/g, '_');
40
43
  return `attachment; filename="${asciiName}"; filename*=UTF-8''${utf8Name}`;
41
- };
42
- const sanitizeFilename = (filename)=>Array.from(filename, (character)=>{
44
+ }
45
+ function sanitizeFilename(filename) {
46
+ // Replace control characters (0–31 and 127) and slashes with underscores.
47
+ // This keeps newlines and directory paths out of the download name.
48
+ return Array.from(filename, (character)=>{
43
49
  const codePoint = character.codePointAt(0);
44
50
  return codePoint < 32 || codePoint === 127 || character === '/' || character === '\\' ? '_' : character;
45
51
  }).join('');
52
+ }
@@ -3,12 +3,16 @@ import type { StorageClient } from '../client.js';
3
3
  type Args = {
4
4
  access?: UploadInstructionsAccess;
5
5
  client: StorageClient;
6
+ collectionPrefix?: string;
6
7
  };
7
8
  /**
8
9
  * v4 client-upload entry point. Payload core calls this from
9
10
  * `POST /api/upload-instructions`; we sign a Content API upload URL and hand the
10
- * browser an `http` PUT instruction plus an `uploadReference` that
11
- * `handleUpload`/`staticHandler` use to recognize the already-uploaded file.
11
+ * browser an `http` PUT instruction plus a signed upload receipt.
12
+ *
13
+ * Each upload gets its own `_objectKey`, so it never overwrites another object.
14
+ * Payload verifies the receipt before it reads the uploaded file back through
15
+ * `staticHandler`, and it does not upload the original again in `handleUpload`.
12
16
  */
13
- export declare const getGenerateUploadInstructions: ({ access, client, }: Args) => GenerateUploadInstructions;
17
+ export declare const getGenerateUploadInstructions: ({ access, client, collectionPrefix, }: Args) => GenerateUploadInstructions;
14
18
  export {};
@@ -1,13 +1,17 @@
1
- import path from 'path';
1
+ import { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import { APIError, Forbidden } from 'payload';
3
- import { getSafeFilename } from '../utilities/index.js';
4
- const defaultAccess = ({ req })=>!!req.user;
3
+ import { assertClientUploadAllowed } from 'payload/internal';
4
+ import { passesMakeViewerWriteGate } from '../../plugin/make-permission-access/make-permission-access.js';
5
+ const defaultAccess = ({ req })=>Boolean(req.user) && passesMakeViewerWriteGate(req.user);
5
6
  /**
6
7
  * v4 client-upload entry point. Payload core calls this from
7
8
  * `POST /api/upload-instructions`; we sign a Content API upload URL and hand the
8
- * browser an `http` PUT instruction plus an `uploadReference` that
9
- * `handleUpload`/`staticHandler` use to recognize the already-uploaded file.
10
- */ export const getGenerateUploadInstructions = ({ access = defaultAccess, client })=>{
9
+ * browser an `http` PUT instruction plus a signed upload receipt.
10
+ *
11
+ * Each upload gets its own `_objectKey`, so it never overwrites another object.
12
+ * Payload verifies the receipt before it reads the uploaded file back through
13
+ * `staticHandler`, and it does not upload the original again in `handleUpload`.
14
+ */ export const getGenerateUploadInstructions = ({ access = defaultAccess, client, collectionPrefix = '' })=>{
11
15
  const generate = async ({ collectionSlug, docPrefix, filename, filesize, mimeType, overrideAccess, req })=>{
12
16
  if (!overrideAccess && !await access({
13
17
  collectionSlug,
@@ -15,21 +19,24 @@ const defaultAccess = ({ req })=>!!req.user;
15
19
  })) {
16
20
  throw new Forbidden();
17
21
  }
18
- const safeFilename = await getSafeFilename({
22
+ assertClientUploadAllowed({
23
+ collection: req.payload.collections[collectionSlug]?.config,
24
+ filename,
25
+ mimeType
26
+ });
27
+ const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({
28
+ collectionPrefix,
19
29
  collectionSlug,
20
- desiredFilename: filename,
30
+ docPrefix,
31
+ filename,
21
32
  req
22
33
  });
23
- // Key by `<prefix>/<filename>` to match the read path (staticHandler/generateURL
24
- // via getFilePrefix) and handleUpload. The Figma plugin sets no prefix, so
25
- // docPrefix is blank today and this is just the filename.
26
- const fileKey = path.posix.join(docPrefix ?? '', safeFilename);
27
34
  const { data, error, response } = await client.POST('/api/v0/uploads/sign', {
28
35
  body: {
29
36
  collectionId: collectionSlug,
30
37
  contentType: mimeType,
31
38
  expiresIn: 3600,
32
- filename: fileKey
39
+ filename: storageFilePath
33
40
  }
34
41
  });
35
42
  if (error) {
@@ -43,16 +50,10 @@ const defaultAccess = ({ req })=>!!req.user;
43
50
  return {
44
51
  type: 'http',
45
52
  file: {
46
- collectionSlug,
47
- filename: safeFilename,
53
+ filename: sanitizedFilename,
48
54
  mimeType,
49
55
  size: filesize,
50
- uploadReference: {
51
- clientUploaded: true,
52
- filename: safeFilename,
53
- mimeType,
54
- prefix: docPrefix ?? ''
55
- }
56
+ uploadReference
56
57
  },
57
58
  // The presigned URL is signed with `contentType: mimeType`, so the browser
58
59
  // PUT must carry a matching Content-Type header or S3 rejects the signature.
@@ -1,7 +1,5 @@
1
- import type { Middleware } from 'openapi-fetch';
2
1
  import createClient from 'openapi-fetch';
3
2
  import type { UploadPaths } from './api-types.js';
4
3
  import type { StorageClientConfig } from './types.js';
5
4
  export type StorageClient = ReturnType<typeof createClient<UploadPaths>>;
6
5
  export declare function createStorageClient(config: StorageClientConfig): StorageClient;
7
- export declare function createStorageAuthMiddleware(config: StorageClientConfig): Middleware;
@@ -8,7 +8,7 @@ export function createStorageClient(config) {
8
8
  client.use(createStorageAuthMiddleware(config));
9
9
  return client;
10
10
  }
11
- export function createStorageAuthMiddleware(config) {
11
+ function createStorageAuthMiddleware(config) {
12
12
  return {
13
13
  async onRequest ({ request }) {
14
14
  if ('contentApiKey' in config) {
@@ -26,7 +26,7 @@ export function createStorageAuthMiddleware(config) {
26
26
  throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
27
27
  }
28
28
  request.headers.set('Authorization', `Bearer ${token}`);
29
- } else if (auth.mode === 'devJwt') {
29
+ } else {
30
30
  const token = await fetchDevJwt(config.baseUrl, contentSystemId);
31
31
  request.headers.set('Authorization', `Bearer ${token}`);
32
32
  }
@@ -0,0 +1,16 @@
1
+ import type { CopyFile } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { StorageClient } from './client.js';
3
+ type Args = {
4
+ client: StorageClient;
5
+ };
6
+ /**
7
+ * Copies `from` to `to` and keeps `from`, so older versions can still read it.
8
+ *
9
+ * The Content API has no copy endpoint, so the bytes are downloaded and uploaded again with
10
+ * the source Content-Type. The Content API stores no other object metadata.
11
+ *
12
+ * The destination check is not atomic. Payload puts a new `_objectKey` in `to`, so two
13
+ * copies to the same key at the same time are not expected.
14
+ */
15
+ export declare const getCopyFile: ({ client }: Args) => CopyFile;
16
+ export {};
@@ -0,0 +1,90 @@
1
+ import { APIError } from 'payload';
2
+ import { uploadFileData } from './uploadFileData.js';
3
+ const PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS = 300;
4
+ /**
5
+ * Copies `from` to `to` and keeps `from`, so older versions can still read it.
6
+ *
7
+ * The Content API has no copy endpoint, so the bytes are downloaded and uploaded again with
8
+ * the source Content-Type. The Content API stores no other object metadata.
9
+ *
10
+ * The destination check is not atomic. Payload puts a new `_objectKey` in `to`, so two
11
+ * copies to the same key at the same time are not expected.
12
+ */ export const getCopyFile = ({ client })=>{
13
+ return async ({ collection, from, mimeType, req, to })=>{
14
+ if (from === to) {
15
+ throw new Error('Storage copy requires different source and destination keys');
16
+ }
17
+ const collectionId = collection.slug;
18
+ // The Content API role can list the bucket, so a missing object returns 404, not 403.
19
+ const destination = await fetchObject({
20
+ client,
21
+ collectionId,
22
+ headers: {
23
+ Range: 'bytes=0-0'
24
+ },
25
+ key: to,
26
+ signal: req.signal
27
+ });
28
+ await cancelResponseBody(destination);
29
+ if (destination.status !== 404) {
30
+ if (destination.ok || destination.status === 416) {
31
+ throw new APIError(`Storage destination already exists: ${to}`, 409);
32
+ }
33
+ throw new Error(`Failed to check storage destination: ${destination.status}`);
34
+ }
35
+ const source = await fetchObject({
36
+ client,
37
+ collectionId,
38
+ key: from,
39
+ signal: req.signal
40
+ });
41
+ if (!source.ok) {
42
+ await cancelResponseBody(source);
43
+ throw new Error(`Failed to read storage source: ${source.status}`);
44
+ }
45
+ const fileData = Buffer.from(await source.arrayBuffer());
46
+ await uploadFileData({
47
+ client,
48
+ collectionId,
49
+ fileData,
50
+ fileKey: to,
51
+ mimeType: source.headers.get('Content-Type') || mimeType || 'application/octet-stream'
52
+ });
53
+ };
54
+ };
55
+ async function fetchObject({ client, collectionId, headers, key, signal }) {
56
+ const { data, error, response } = await client.POST('/api/v0/uploads/download/sign', {
57
+ body: {
58
+ collectionId,
59
+ expiresIn: PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS,
60
+ filename: key,
61
+ responseHeaders: {
62
+ cacheControl: 'private, no-store'
63
+ }
64
+ }
65
+ });
66
+ if (error) {
67
+ throw new APIError(`Failed to get presigned download URL: ${error.message}`, response.status, {
68
+ code: error.code
69
+ });
70
+ }
71
+ if (!data) {
72
+ throw new Error('No response while getting presigned download URL');
73
+ }
74
+ try {
75
+ return await fetch(data.url, {
76
+ headers,
77
+ signal
78
+ });
79
+ } catch {
80
+ // Fetch errors can contain the signed URL; throw only a fixed message to avoid exposing it.
81
+ throw new Error('Failed to fetch file from storage');
82
+ }
83
+ }
84
+ async function cancelResponseBody(response) {
85
+ try {
86
+ await response.body?.cancel();
87
+ } catch {
88
+ // The body is not read; cancellation is best-effort cleanup.
89
+ }
90
+ }
@@ -0,0 +1,8 @@
1
+ import type { DeleteFile } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { StorageClient } from './client.js';
3
+ type Args = {
4
+ client: StorageClient;
5
+ };
6
+ /** Deletes the object at `storageFilePath`. Payload resolves the complete path. */
7
+ export declare const getDeleteFile: ({ client }: Args) => DeleteFile;
8
+ export {};
@@ -0,0 +1,18 @@
1
+ import { APIError } from 'payload';
2
+ /** Deletes the object at `storageFilePath`. Payload resolves the complete path. */ export const getDeleteFile = ({ client })=>{
3
+ return async ({ collection, storageFilePath })=>{
4
+ const { error, response } = await client.DELETE('/api/v0/uploads/{collectionId}/{filename}', {
5
+ params: {
6
+ path: {
7
+ collectionId: collection.slug,
8
+ filename: storageFilePath
9
+ }
10
+ }
11
+ });
12
+ if (error || !response.ok) {
13
+ throw new APIError(`Failed to delete file: ${error?.message ?? response.statusText}`, response.status, {
14
+ code: error?.code
15
+ });
16
+ }
17
+ };
18
+ };
@@ -0,0 +1,11 @@
1
+ import type { Payload } from 'payload';
2
+ export declare const DEFAULT_MEDIA_CACHE_CONTROL = "private, no-store";
3
+ export declare const MAX_MEDIA_CACHE_CONTROL_LENGTH = 1024;
4
+ type DownloadResponseHeaderPolicy = {
5
+ cacheControl: string;
6
+ };
7
+ export declare const getDownloadResponseHeaderPolicy: ({ logger, responseHeaders, }: {
8
+ logger: Pick<Payload["logger"], "debug">;
9
+ responseHeaders: Headers;
10
+ }) => DownloadResponseHeaderPolicy;
11
+ export {};
@@ -0,0 +1,33 @@
1
+ export const DEFAULT_MEDIA_CACHE_CONTROL = 'private, no-store';
2
+ export const MAX_MEDIA_CACHE_CONTROL_LENGTH = 1024;
3
+ const PRINTABLE_ASCII_REGEX = /^[\x20-\x7e]+$/;
4
+ export const getDownloadResponseHeaderPolicy = ({ logger, responseHeaders })=>{
5
+ const configuredCacheControl = responseHeaders.get('Cache-Control')?.trim();
6
+ const isCacheControlValid = hasValidCacheControl(configuredCacheControl);
7
+ const hasIgnoredHeaders = [
8
+ ...responseHeaders.keys()
9
+ ].some((name)=>name !== 'cache-control');
10
+ const rejectedCacheControlOverride = !isCacheControlValid;
11
+ if (hasIgnoredHeaders || rejectedCacheControlOverride) {
12
+ logger.debug({
13
+ hasIgnoredResponseHeaders: hasIgnoredHeaders,
14
+ msg: 'Filtered media response header overrides',
15
+ rejectedCacheControlOverride
16
+ });
17
+ }
18
+ return {
19
+ cacheControl: isCacheControlValid && configuredCacheControl ? configuredCacheControl : DEFAULT_MEDIA_CACHE_CONTROL
20
+ };
21
+ };
22
+ function hasValidCacheControl(cacheControl) {
23
+ if (cacheControl == null) {
24
+ return false;
25
+ }
26
+ if (cacheControl.length === 0 || cacheControl.length > MAX_MEDIA_CACHE_CONTROL_LENGTH) {
27
+ return false;
28
+ }
29
+ if (!PRINTABLE_ASCII_REGEX.test(cacheControl)) {
30
+ return false;
31
+ }
32
+ return true;
33
+ }
@@ -0,0 +1 @@
1
+ export declare function getMediaType(headers: Headers): string;
@@ -0,0 +1,3 @@
1
+ export function getMediaType(headers) {
2
+ return headers.get('Content-Type')?.split(';', 1).at(0)?.trim().toLowerCase() || '';
3
+ }
@@ -4,7 +4,6 @@ import type { StorageClient } from './client.js';
4
4
  type Args = {
5
5
  client: StorageClient;
6
6
  collection: CollectionConfig;
7
- prefix?: string;
8
7
  };
9
- export declare const getHandleUpload: ({ client, collection, prefix }: Args) => HandleUpload;
8
+ export declare const getHandleUpload: ({ client, collection }: Args) => HandleUpload;
10
9
  export {};
@@ -1,162 +1,18 @@
1
1
  import fs from 'fs';
2
- import path from 'path';
3
- import { APIError } from 'payload';
4
- import { parseUploadReference } from './utilities/index.js';
5
- const PART_SIZE = 64 * 1024 * 1024 // 64MB per part
6
- ;
7
- const MAX_FILE_SIZE_BEFORE_MULTIPART = 100 * 1024 * 1024 // 100MB
8
- ;
9
- export const getHandleUpload = ({ client, collection, prefix = '' })=>{
10
- return async ({ data, file })=>{
11
- // Skip if the client already uploaded THIS SPECIFIC file. Resized versions
12
- // (different filename) should still be uploaded.
13
- const reference = parseUploadReference(file.uploadReference);
14
- const isOriginalClientUploaded = reference.clientUploaded === true && file.filename === reference.filename;
15
- if (isOriginalClientUploaded) {
16
- return data;
17
- }
18
- const collectionId = collection.slug;
19
- const fileKey = path.posix.join(data.prefix || prefix, file.filename);
2
+ import { uploadFileData } from './uploadFileData.js';
3
+ // Payload skips the original of a verified direct browser upload, so every file here
4
+ // must be written. `storageFilePath` already includes the prefixes and `_objectKey`.
5
+ export const getHandleUpload = ({ client, collection })=>{
6
+ return async ({ data, file, storageFilePath })=>{
20
7
  const fileData = file.tempFilePath ? fs.readFileSync(file.tempFilePath) : file.buffer;
21
- const fileSize = file.filesize || fileData.length;
22
- if (fileSize > MAX_FILE_SIZE_BEFORE_MULTIPART) {
23
- await uploadMultipart({
24
- client,
25
- collectionId,
26
- fileData,
27
- fileKey,
28
- mimeType: file.mimeType
29
- });
30
- } else {
31
- await uploadSingleFile({
32
- client,
33
- collectionId,
34
- fileData,
35
- fileKey,
36
- mimeType: file.mimeType
37
- });
38
- }
8
+ await uploadFileData({
9
+ client,
10
+ collectionId: collection.slug,
11
+ fileData,
12
+ fileKey: storageFilePath,
13
+ fileSize: file.filesize || fileData.length,
14
+ mimeType: file.mimeType
15
+ });
39
16
  return data;
40
17
  };
41
18
  };
42
- async function uploadSingleFile({ client, collectionId, fileData, fileKey, mimeType }) {
43
- const { data, error, response } = await client.POST('/api/v0/uploads/sign', {
44
- body: {
45
- collectionId,
46
- contentType: mimeType,
47
- expiresIn: 3600,
48
- filename: fileKey
49
- }
50
- });
51
- if (error) {
52
- throw new APIError(`Failed to get presigned upload URL: ${error.message}`, response.status, {
53
- code: error.code
54
- });
55
- }
56
- if (!data) {
57
- throw new Error('No response while getting presigned upload URL');
58
- }
59
- const uploadResponse = await fetch(data.url, {
60
- // TS's BodyInit type rejects Buffer<ArrayBufferLike>; wrap as Uint8Array
61
- // (a valid ArrayBufferView) — byte-identical.
62
- body: new Uint8Array(fileData),
63
- headers: {
64
- 'Content-Type': mimeType
65
- },
66
- method: 'PUT'
67
- });
68
- if (!uploadResponse.ok) {
69
- throw new Error(`Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`);
70
- }
71
- }
72
- async function uploadMultipart({ client, collectionId, fileData, fileKey, mimeType }) {
73
- const { data: initiateData, error: initiateError, response: initiateResponse } = await client.POST('/api/v0/uploads/multipart/initiate', {
74
- body: {
75
- collectionId,
76
- contentType: mimeType,
77
- filename: fileKey
78
- }
79
- });
80
- if (initiateError) {
81
- throw new APIError(`Failed to initiate multipart upload: ${initiateError.message}`, initiateResponse.status, {
82
- code: initiateError.code
83
- });
84
- }
85
- if (!initiateData) {
86
- throw new Error('No response while initiating multipart upload');
87
- }
88
- const { uploadId } = initiateData;
89
- try {
90
- const numParts = Math.ceil(fileData.length / PART_SIZE);
91
- const partNumbers = Array.from({
92
- length: numParts
93
- }, (_, i)=>i + 1);
94
- const { data: partsData, error: partsError, response: partsResponse } = await client.POST('/api/v0/uploads/multipart/parts', {
95
- body: {
96
- collectionId,
97
- expiresIn: 3600,
98
- filename: fileKey,
99
- partNumbers,
100
- uploadId
101
- }
102
- });
103
- if (partsError) {
104
- throw new APIError(`Failed to get part URLs: ${partsError.message}`, partsResponse.status, {
105
- code: partsError.code
106
- });
107
- }
108
- if (!partsData) {
109
- throw new Error('No response while getting part URLs');
110
- }
111
- const { parts } = partsData;
112
- if (!parts || !Array.isArray(parts)) {
113
- throw new Error('Invalid response from part URLs endpoint: parts is not an array');
114
- }
115
- const uploadedParts = await Promise.all(parts.map(async ({ partNumber, url })=>{
116
- const start = (partNumber - 1) * PART_SIZE;
117
- const end = Math.min(start + PART_SIZE, fileData.length);
118
- const partData = fileData.slice(start, end);
119
- const uploadResponse = await fetch(url, {
120
- body: partData,
121
- headers: {
122
- 'Content-Type': mimeType
123
- },
124
- method: 'PUT'
125
- });
126
- const etag = uploadResponse.headers.get('ETag');
127
- if (!etag) {
128
- throw new Error(`No ETag returned for part ${partNumber}`);
129
- }
130
- return {
131
- ETag: etag,
132
- PartNumber: partNumber
133
- };
134
- }));
135
- const { error: completeError, response: completeResponse } = await client.POST('/api/v0/uploads/multipart/complete', {
136
- body: {
137
- collectionId,
138
- filename: fileKey,
139
- parts: uploadedParts,
140
- uploadId
141
- }
142
- });
143
- if (completeError) {
144
- throw new APIError(`Failed to complete multipart upload: ${completeError.message}`, completeResponse.status, {
145
- code: completeError.code
146
- });
147
- }
148
- } catch (error) {
149
- try {
150
- await client.POST('/api/v0/uploads/multipart/abort', {
151
- body: {
152
- collectionId,
153
- filename: fileKey,
154
- uploadId
155
- }
156
- });
157
- } catch {
158
- // Ignore abort errors
159
- }
160
- throw error;
161
- }
162
- }
@@ -1 +1 @@
1
- export declare const hasSupportedContentEncoding: (headers: Headers) => boolean;
1
+ export declare function hasSupportedContentEncoding(headers: Headers): boolean;
@@ -1,4 +1,6 @@
1
- export const hasSupportedContentEncoding = (headers)=>{
1
+ // Fetch can automatically decompress a file without updating its size or byte-range headers.
2
+ // Reject compressed responses so the headers still match the bytes we send.
3
+ export function hasSupportedContentEncoding(headers) {
2
4
  const contentEncoding = headers.get('content-encoding')?.trim().toLowerCase();
3
5
  return contentEncoding == null || contentEncoding === '' || contentEncoding === 'identity';
4
- };
6
+ }
@@ -1,35 +1,44 @@
1
1
  import { createStorageClient } from './client.js';
2
2
  import { getGenerateUploadInstructions } from './client-uploads/generate.js';
3
+ import { getCopyFile } from './copyFile.js';
4
+ import { getDeleteFile } from './deleteFile.js';
3
5
  import { getGenerateURL } from './generateURL.js';
4
- import { getHandleDelete } from './handleDelete.js';
5
6
  import { getHandleUpload } from './handleUpload.js';
6
7
  import { getHandler } from './staticHandler.js';
7
8
  export function contentApiStorageAdapter(config) {
8
9
  return ({ collection, prefix })=>{
9
10
  const client = createStorageClient(config);
10
11
  const baseUrl = config.baseUrl;
12
+ const deleteFile = getDeleteFile({
13
+ client
14
+ });
11
15
  return {
12
16
  name: 'content-api',
17
+ copyFile: getCopyFile({
18
+ client
19
+ }),
20
+ deleteFile,
13
21
  generateURL: getGenerateURL({
14
22
  baseUrl
15
23
  }),
16
- handleDelete: getHandleDelete({
17
- client
18
- }),
24
+ handleDelete: deleteFile,
19
25
  handleUpload: getHandleUpload({
20
26
  client,
21
- collection,
22
- prefix
27
+ collection
23
28
  }),
24
29
  staticHandler: getHandler({
25
30
  client,
26
- collection
31
+ collection,
32
+ prefix
27
33
  }),
28
34
  uploadInstructions: {
29
35
  enabled: true,
30
36
  generate: getGenerateUploadInstructions({
31
- client
37
+ access: config.uploadInstructionsAccess,
38
+ client,
39
+ collectionPrefix: prefix
32
40
  }),
41
+ requiresUploadReceipt: true,
33
42
  useInAdmin: true
34
43
  }
35
44
  };
@@ -1 +1 @@
1
- export declare const mediaErrorResponse: (status: number, body: string, contentRange?: string) => Response;
1
+ export declare function mediaErrorResponse(status: number, body: string, contentRange?: string): Response;
@@ -1,5 +1,5 @@
1
1
  import { buildBaseMediaResponseHeaders } from './buildBaseMediaResponseHeaders.js';
2
- export const mediaErrorResponse = (status, body, contentRange)=>{
2
+ export function mediaErrorResponse(status, body, contentRange) {
3
3
  const headers = buildBaseMediaResponseHeaders();
4
4
  headers.set('Content-Type', 'text/plain;charset=UTF-8');
5
5
  if (contentRange) {
@@ -9,4 +9,4 @@ export const mediaErrorResponse = (status, body, contentRange)=>{
9
9
  headers,
10
10
  status
11
11
  });
12
- };
12
+ }