@venizia/ignis 0.4.8-12 → 0.4.8-13

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 (27) hide show
  1. package/dist/esm/components/static-asset/common/constants.d.ts +8 -1
  2. package/dist/esm/components/static-asset/common/constants.js +6 -1
  3. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  4. package/dist/esm/components/static-asset/common/errors.d.ts +18 -9
  5. package/dist/esm/components/static-asset/common/errors.js +18 -9
  6. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  7. package/dist/esm/components/static-asset/common/types.d.ts +19 -5
  8. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  9. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +8 -2
  10. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -1
  11. package/dist/esm/components/static-asset/services/commitment.service.d.ts +17 -6
  12. package/dist/esm/components/static-asset/services/commitment.service.js +79 -30
  13. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
  14. package/dist/esm/components/static-asset/services/policy.service.js +2 -1
  15. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
  16. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +1 -0
  17. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +26 -1
  18. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
  19. package/dist/esm/components/static-asset/utilities/index.d.ts +1 -0
  20. package/dist/esm/components/static-asset/utilities/index.js +1 -0
  21. package/dist/esm/components/static-asset/utilities/index.js.map +1 -1
  22. package/dist/esm/components/static-asset/utilities/pinned-file.utility.d.ts +39 -0
  23. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js +53 -0
  24. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js.map +1 -0
  25. package/dist/presets/app/preset.json +3 -3
  26. package/dist/presets/lib/preset.json +2 -2
  27. package/package.json +5 -5
@@ -6,7 +6,7 @@ export declare class StaticAssetHeaders {
6
6
  /** Of what a controller sends with every object. */
7
7
  static readonly NOSNIFF = "nosniff";
8
8
  static readonly CSP_SANDBOX = "sandbox";
9
- static readonly RANGE_UNIT = "bytes";
9
+ static readonly RANGE_UNIT: "bytes";
10
10
  }
11
11
  /** Content types the controller serves. */
12
12
  export declare class StaticAssetContentTypes {
@@ -38,6 +38,13 @@ export declare class MetaLinkRecreateActions {
38
38
  }
39
39
  /** One of the `MetaLinkRecreateActions` values. */
40
40
  export type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;
41
+ /** Where a commit token is in its life: issued with the policy, then validated against the content it pins. */
42
+ export declare class StaticAssetTokenStages {
43
+ static readonly ISSUED = "issued";
44
+ static readonly VALIDATED = "validated";
45
+ }
46
+ /** One of the `StaticAssetTokenStages` values. */
47
+ export type TStaticAssetTokenStage = TConstValue<typeof StaticAssetTokenStages>;
41
48
  /** Defaults of the static asset component. */
42
49
  export declare class StaticAssetDefaults {
43
50
  /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
@@ -11,7 +11,7 @@ export class StaticAssetHeaders {
11
11
  /** Of what a controller sends with every object. */
12
12
  static { this.NOSNIFF = 'nosniff'; }
13
13
  static { this.CSP_SANDBOX = 'sandbox'; }
14
- static { this.RANGE_UNIT = 'bytes'; }
14
+ static { this.RANGE_UNIT = HTTP.HeaderValues.RANGE_UNIT_BYTES; }
15
15
  }
16
16
  /** Content types the controller serves. */
17
17
  export class StaticAssetContentTypes {
@@ -67,6 +67,11 @@ export class MetaLinkRecreateActions {
67
67
  static { this.CREATED = 'created'; }
68
68
  static { this.REFRESHED = 'refreshed'; }
69
69
  }
70
+ /** Where a commit token is in its life: issued with the policy, then validated against the content it pins. */
71
+ export class StaticAssetTokenStages {
72
+ static { this.ISSUED = 'issued'; }
73
+ static { this.VALIDATED = 'validated'; }
74
+ }
70
75
  /** Defaults of the static asset component. */
71
76
  export class StaticAssetDefaults {
72
77
  /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,4EAA4E;AAC5E,MAAM,OAAO,kBAAkB;IAC7B,uGAAuG;aACvF,YAAO,GAAG;QACxB,IAAI,CAAC,OAAO,CAAC,gBAAgB;QAC7B,IAAI,CAAC,OAAO,CAAC,aAAa;QAC1B,IAAI,CAAC,OAAO,CAAC,IAAI;QACjB,IAAI,CAAC,OAAO,CAAC,aAAa;KAClB,CAAC;IAEX,oDAAoD;aACpC,YAAO,GAAG,SAAS,CAAC;aACpB,gBAAW,GAAG,SAAS,CAAC;aACxB,eAAU,GAAG,OAAO,CAAC;;AAGvC,2CAA2C;AAC3C,MAAM,OAAO,uBAAuB;IAClC;;;;OAIG;aACa,eAAU,GAAG,IAAI,GAAG,CAAS;QAC3C,IAAI,CAAC,YAAY,CAAC,SAAS;QAC3B,IAAI,CAAC,YAAY,CAAC,UAAU;QAC5B,IAAI,CAAC,YAAY,CAAC,SAAS;QAC3B,IAAI,CAAC,YAAY,CAAC,UAAU;QAC5B,YAAY;QACZ,WAAW;QACX,cAAc;QACd,WAAW;QACX,YAAY;QACZ,YAAY;QACZ,WAAW;QACX,WAAW;QACX,IAAI,CAAC,YAAY,CAAC,eAAe;QACjC,IAAI,CAAC,YAAY,CAAC,UAAU;QAC5B,IAAI,CAAC,YAAY,CAAC,QAAQ;KAC3B,CAAC,CAAC;;AAGL,2EAA2E;AAC3E,MAAM,OAAO,oBAAoB;aACf,WAAM,GAAG,QAAQ,CAAC;aAClB,iBAAY,GAAG,aAAa,CAAC;aAC7B,kBAAa,GAAG,cAAc,CAAC;aAC/B,uBAAkB,GAAG,iBAAiB,CAAC;aACvC,4BAAuB,GAAG,sBAAsB,CAAC;aAEjD,kBAAa,GAAG,cAAc,CAAC;aAC/B,kBAAa,GAAG,cAAc,CAAC;aAC/B,oBAAe,GAAG,gBAAgB,CAAC;aAEnC,uBAAkB,GAAG,kBAAkB,CAAC;IAExD,wCAAwC;aACxB,QAAG,GAAG;QACpB,oBAAoB,CAAC,kBAAkB;QACvC,oBAAoB,CAAC,uBAAuB;QAC5C,oBAAoB,CAAC,MAAM;QAC3B,oBAAoB,CAAC,aAAa;QAClC,oBAAoB,CAAC,YAAY;QACjC,oBAAoB,CAAC,aAAa;QAClC,oBAAoB,CAAC,aAAa;QAClC,oBAAoB,CAAC,eAAe;QACpC,oBAAoB,CAAC,kBAAkB;KAC/B,CAAC;;AAGb,+FAA+F;AAC/F,MAAM,OAAO,uBAAuB;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,cAAS,GAAG,WAAW,CAAC;;AAM1C,8CAA8C;AAC9C,MAAM,OAAO,mBAAmB;IAC9B,yHAAyH;aACzG,mBAAc,GAAG,UAAU,CAAC;IAE5C,sGAAsG;aACtF,qBAAgB,GAAG,EAAE,CAAC;;AAGxC,iEAAiE;AACjE,MAAM,OAAO,wBAAwB;IACnC,2LAA2L;aAC3K,kBAAa,GAAG,yBAAyB,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** The response headers a controller echoes from the backend's metadata. */\nexport class StaticAssetHeaders {\n /** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */\n static readonly ALLOWED = [\n HTTP.Headers.CONTENT_ENCODING,\n HTTP.Headers.CACHE_CONTROL,\n HTTP.Headers.ETAG,\n HTTP.Headers.LAST_MODIFIED,\n ] as const;\n\n /** Of what a controller sends with every object. */\n static readonly NOSNIFF = 'nosniff';\n static readonly CSP_SANDBOX = 'sandbox';\n static readonly RANGE_UNIT = 'bytes';\n}\n\n/** Content types the controller serves. */\nexport class StaticAssetContentTypes {\n /**\n * Types the controller will let a browser render, keyed off the object name. Anything absent here is\n * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`\n * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.\n */\n static readonly RENDERABLE = new Set<string>([\n HTTP.HeaderValues.IMAGE_PNG,\n HTTP.HeaderValues.IMAGE_JPEG,\n HTTP.HeaderValues.IMAGE_GIF,\n HTTP.HeaderValues.IMAGE_WEBP,\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n 'video/mp4',\n 'video/webm',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n HTTP.HeaderValues.APPLICATION_PDF,\n HTTP.HeaderValues.TEXT_PLAIN,\n HTTP.HeaderValues.TEXT_CSV,\n ]);\n}\n\n/** The built-in routes of a generated controller, the keys of `routes`. */\nexport class StaticAssetRouteKeys {\n static readonly UPLOAD = 'upload';\n static readonly LIST_OBJECTS = 'listObjects';\n static readonly DELETE_OBJECT = 'deleteObject';\n static readonly GET_OBJECT_BY_NAME = 'getObjectByName';\n static readonly DOWNLOAD_OBJECT_BY_NAME = 'downloadObjectByName';\n\n static readonly UPLOAD_POLICY = 'uploadPolicy';\n static readonly UPLOAD_COMMIT = 'uploadCommit';\n static readonly UPLOAD_VALIDATE = 'uploadValidate';\n\n static readonly RECREATE_META_LINK = 'recreateMetaLink';\n\n /** Every key, in registration order. */\n static readonly ALL = [\n StaticAssetRouteKeys.GET_OBJECT_BY_NAME,\n StaticAssetRouteKeys.DOWNLOAD_OBJECT_BY_NAME,\n StaticAssetRouteKeys.UPLOAD,\n StaticAssetRouteKeys.DELETE_OBJECT,\n StaticAssetRouteKeys.LIST_OBJECTS,\n StaticAssetRouteKeys.UPLOAD_POLICY,\n StaticAssetRouteKeys.UPLOAD_COMMIT,\n StaticAssetRouteKeys.UPLOAD_VALIDATE,\n StaticAssetRouteKeys.RECREATE_META_LINK,\n ] as const;\n}\n\n/** What `recreate-metalink` did: refreshed the rows of an object, or created its first one. */\nexport class MetaLinkRecreateActions {\n static readonly CREATED = 'created';\n static readonly REFRESHED = 'refreshed';\n}\n\n/** One of the `MetaLinkRecreateActions` values. */\nexport type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;\n\n/** Defaults of the static asset component. */\nexport class StaticAssetDefaults {\n /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */\n static readonly PENDING_PREFIX = 'pending/';\n\n /** The most file parts one upload request may carry unless `serverUpload.maxFiles` says otherwise. */\n static readonly MAX_UPLOAD_FILES = 20;\n}\n\n/** Codes the component reports in a body instead of throwing. */\nexport class StaticAssetMetaLinkCodes {\n /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */\n static readonly CREATE_FAILED = 'META_LINK_CREATE_FAILED';\n}\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,4EAA4E;AAC5E,MAAM,OAAO,kBAAkB;IAC7B,uGAAuG;aACvF,YAAO,GAAG;QACxB,IAAI,CAAC,OAAO,CAAC,gBAAgB;QAC7B,IAAI,CAAC,OAAO,CAAC,aAAa;QAC1B,IAAI,CAAC,OAAO,CAAC,IAAI;QACjB,IAAI,CAAC,OAAO,CAAC,aAAa;KAClB,CAAC;IAEX,oDAAoD;aACpC,YAAO,GAAG,SAAS,CAAC;aACpB,gBAAW,GAAG,SAAS,CAAC;aACxB,eAAU,GAAG,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC;;AAGlE,2CAA2C;AAC3C,MAAM,OAAO,uBAAuB;IAClC;;;;OAIG;aACa,eAAU,GAAG,IAAI,GAAG,CAAS;QAC3C,IAAI,CAAC,YAAY,CAAC,SAAS;QAC3B,IAAI,CAAC,YAAY,CAAC,UAAU;QAC5B,IAAI,CAAC,YAAY,CAAC,SAAS;QAC3B,IAAI,CAAC,YAAY,CAAC,UAAU;QAC5B,YAAY;QACZ,WAAW;QACX,cAAc;Q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3K,kBAAa,GAAG,yBAAyB,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** The response headers a controller echoes from the backend's metadata. */\nexport class StaticAssetHeaders {\n /** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */\n static readonly ALLOWED = [\n HTTP.Headers.CONTENT_ENCODING,\n HTTP.Headers.CACHE_CONTROL,\n HTTP.Headers.ETAG,\n HTTP.Headers.LAST_MODIFIED,\n ] as const;\n\n /** Of what a controller sends with every object. */\n static readonly NOSNIFF = 'nosniff';\n static readonly CSP_SANDBOX = 'sandbox';\n static readonly RANGE_UNIT = HTTP.HeaderValues.RANGE_UNIT_BYTES;\n}\n\n/** Content types the controller serves. */\nexport class StaticAssetContentTypes {\n /**\n * Types the controller will let a browser render, keyed off the object name. Anything absent here is\n * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`\n * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.\n */\n static readonly RENDERABLE = new Set<string>([\n HTTP.HeaderValues.IMAGE_PNG,\n HTTP.HeaderValues.IMAGE_JPEG,\n HTTP.HeaderValues.IMAGE_GIF,\n HTTP.HeaderValues.IMAGE_WEBP,\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n 'video/mp4',\n 'video/webm',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n HTTP.HeaderValues.APPLICATION_PDF,\n HTTP.HeaderValues.TEXT_PLAIN,\n HTTP.HeaderValues.TEXT_CSV,\n ]);\n}\n\n/** The built-in routes of a generated controller, the keys of `routes`. */\nexport class StaticAssetRouteKeys {\n static readonly UPLOAD = 'upload';\n static readonly LIST_OBJECTS = 'listObjects';\n static readonly DELETE_OBJECT = 'deleteObject';\n static readonly GET_OBJECT_BY_NAME = 'getObjectByName';\n static readonly DOWNLOAD_OBJECT_BY_NAME = 'downloadObjectByName';\n\n static readonly UPLOAD_POLICY = 'uploadPolicy';\n static readonly UPLOAD_COMMIT = 'uploadCommit';\n static readonly UPLOAD_VALIDATE = 'uploadValidate';\n\n static readonly RECREATE_META_LINK = 'recreateMetaLink';\n\n /** Every key, in registration order. */\n static readonly ALL = [\n StaticAssetRouteKeys.GET_OBJECT_BY_NAME,\n StaticAssetRouteKeys.DOWNLOAD_OBJECT_BY_NAME,\n StaticAssetRouteKeys.UPLOAD,\n StaticAssetRouteKeys.DELETE_OBJECT,\n StaticAssetRouteKeys.LIST_OBJECTS,\n StaticAssetRouteKeys.UPLOAD_POLICY,\n StaticAssetRouteKeys.UPLOAD_COMMIT,\n StaticAssetRouteKeys.UPLOAD_VALIDATE,\n StaticAssetRouteKeys.RECREATE_META_LINK,\n ] as const;\n}\n\n/** What `recreate-metalink` did: refreshed the rows of an object, or created its first one. */\nexport class MetaLinkRecreateActions {\n static readonly CREATED = 'created';\n static readonly REFRESHED = 'refreshed';\n}\n\n/** One of the `MetaLinkRecreateActions` values. */\nexport type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;\n\n/** Where a commit token is in its life: issued with the policy, then validated against the content it pins. */\nexport class StaticAssetTokenStages {\n static readonly ISSUED = 'issued';\n static readonly VALIDATED = 'validated';\n}\n\n/** One of the `StaticAssetTokenStages` values. */\nexport type TStaticAssetTokenStage = TConstValue<typeof StaticAssetTokenStages>;\n\n/** Defaults of the static asset component. */\nexport class StaticAssetDefaults {\n /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */\n static readonly PENDING_PREFIX = 'pending/';\n\n /** The most file parts one upload request may carry unless `serverUpload.maxFiles` says otherwise. */\n static readonly MAX_UPLOAD_FILES = 20;\n}\n\n/** Codes the component reports in a body instead of throwing. */\nexport class StaticAssetMetaLinkCodes {\n /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */\n static readonly CREATE_FAILED = 'META_LINK_CREATE_FAILED';\n}\n"]}
@@ -9,15 +9,6 @@ export declare const StaticAssetErrors: {
9
9
  readonly statusCode: 403;
10
10
  readonly category: "validation";
11
11
  };
12
- /** Raised by `commit`, never by the validate route: the route answers `{ isValid: false, issues }`, and an invalid file simply cannot be committed. */
13
- readonly UPLOAD_INVALID: {
14
- readonly message: {
15
- readonly text: "The uploaded file did not pass validation";
16
- readonly code: "core.static_asset.upload_invalid";
17
- };
18
- readonly statusCode: 422;
19
- readonly category: "validation";
20
- };
21
12
  /** Both upload paths - one condition, one code to branch on. */
22
13
  readonly UPLOAD_TOO_LARGE: {
23
14
  readonly message: {
@@ -44,6 +35,24 @@ export declare const StaticAssetErrors: {
44
35
  readonly statusCode: 400;
45
36
  readonly category: "validation";
46
37
  };
38
+ /** The pending object is not the one that was read: it was overwritten or removed after the pin. Raised by a pinned read and by the commit copy. */
39
+ readonly UPLOAD_CHANGED: {
40
+ readonly message: {
41
+ readonly text: "The uploaded file changed after it was validated";
42
+ readonly code: "core.static_asset.upload_changed";
43
+ };
44
+ readonly statusCode: 409;
45
+ readonly category: "validation";
46
+ };
47
+ /** With a `validation` on, `commit` takes the token `upload-validate` returned, not the one the policy issued. */
48
+ readonly UPLOAD_NOT_VALIDATED: {
49
+ readonly message: {
50
+ readonly text: "The upload has not been validated";
51
+ readonly code: "core.static_asset.upload_not_validated";
52
+ };
53
+ readonly statusCode: 422;
54
+ readonly category: "validation";
55
+ };
47
56
  readonly BUCKET_NAME_INVALID: {
48
57
  readonly message: {
49
58
  readonly text: "Invalid bucket name";
@@ -10,15 +10,6 @@ export const StaticAssetErrors = {
10
10
  statusCode: HTTP.ResultCodes.RS_4.Forbidden,
11
11
  category: ErrorScopes.VALIDATION,
12
12
  },
13
- /** Raised by `commit`, never by the validate route: the route answers `{ isValid: false, issues }`, and an invalid file simply cannot be committed. */
14
- UPLOAD_INVALID: {
15
- message: {
16
- text: 'The uploaded file did not pass validation',
17
- code: 'core.static_asset.upload_invalid',
18
- },
19
- statusCode: HTTP.ResultCodes.RS_4.UnprocessableEntity,
20
- category: ErrorScopes.VALIDATION,
21
- },
22
13
  /** Both upload paths - one condition, one code to branch on. */
23
14
  UPLOAD_TOO_LARGE: {
24
15
  message: {
@@ -39,6 +30,24 @@ export const StaticAssetErrors = {
39
30
  statusCode: HTTP.ResultCodes.RS_4.BadRequest,
40
31
  category: ErrorScopes.VALIDATION,
41
32
  },
33
+ /** The pending object is not the one that was read: it was overwritten or removed after the pin. Raised by a pinned read and by the commit copy. */
34
+ UPLOAD_CHANGED: {
35
+ message: {
36
+ text: 'The uploaded file changed after it was validated',
37
+ code: 'core.static_asset.upload_changed',
38
+ },
39
+ statusCode: HTTP.ResultCodes.RS_4.Conflict,
40
+ category: ErrorScopes.VALIDATION,
41
+ },
42
+ /** With a `validation` on, `commit` takes the token `upload-validate` returned, not the one the policy issued. */
43
+ UPLOAD_NOT_VALIDATED: {
44
+ message: {
45
+ text: 'The upload has not been validated',
46
+ code: 'core.static_asset.upload_not_validated',
47
+ },
48
+ statusCode: HTTP.ResultCodes.RS_4.UnprocessableEntity,
49
+ category: ErrorScopes.VALIDATION,
50
+ },
42
51
  BUCKET_NAME_INVALID: {
43
52
  message: { text: 'Invalid bucket name', code: 'core.static_asset.bucket_name_invalid' },
44
53
  statusCode: HTTP.ResultCodes.RS_4.BadRequest,
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,uIAAuI;AACvI,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,qBAAqB,EAAE;QACrB,OAAO,EAAE;YACP,IAAI,EAAE,uBAAuB;YAC7B,IAAI,EAAE,yCAAyC;SAChD;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS;QAC3C,QAAQ,EAAE,WAAW,CAAC,UAAU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AAW,CAAC,UAAU;KACjC;IACD,wGAAwG;IACxG,uBAAuB,EAAE;QACvB,OAAO,EAAE;YACP,IAAI,EAAE,yDAAyD;YAC/D,IAAI,EAAE,2CAA2C;SAClD;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,UAAU,EAAE;QACV,OAAO,EAAE,EAAE,IAAI,EAAE,oBAAoB,EAAE,IAAI,EAAE,8BAA8B,EAAE;QAC7E,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;CACkD,CAAC","sourcesContent":["import type { TErrorDefinition, TRegisterErrors } from '@venizia/ignis-helpers/core';\nimport { ErrorScopes } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** Codes a client branches on for a rejected static-asset request. A throw site may override `message` to name the offending value. */\nexport const StaticAssetErrors = {\n UPLOAD_NOT_AUTHORIZED: {\n message: {\n text: 'Not allowed to upload',\n code: 'core.static_asset.upload_not_authorized',\n },\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n category: ErrorScopes.VALIDATION,\n },\n /** Raised by `commit`, never by the validate route: the route answers `{ isValid: false, issues }`, and an invalid file simply cannot be committed. */\n UPLOAD_INVALID: {\n message: {\n text: 'The uploaded file did not pass validation',\n code: 'core.static_asset.upload_invalid',\n },\n statusCode: HTTP.ResultCodes.RS_4.UnprocessableEntity,\n category: ErrorScopes.VALIDATION,\n },\n /** Both upload paths - one condition, one code to branch on. */\n UPLOAD_TOO_LARGE: {\n message: {\n text: 'File is larger than the maximum allowed',\n code: 'core.static_asset.upload_too_large',\n },\n statusCode: HTTP.ResultCodes.RS_4.ContentTooLarge,\n category: ErrorScopes.VALIDATION,\n },\n /** Deliberately not 404 and deliberately not \"expired\": a caller learns only that the token is no good, never whether the key it names exists. */\n INVALID_COMMIT_TOKEN: {\n message: { text: 'Invalid commit token', code: 'core.static_asset.invalid_commit_token' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n EXPIRED_COMMIT_TOKEN: {\n message: { text: 'Commit token has expired', code: 'core.static_asset.expired_commit_token' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n BUCKET_NAME_INVALID: {\n message: { text: 'Invalid bucket name', code: 'core.static_asset.bucket_name_invalid' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n OBJECT_NAME_INVALID: {\n message: {\n text: 'Invalid object name or path',\n code: 'core.static_asset.object_name_invalid',\n },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n /** The application's naming hook produced a key outside the entry's `keyPrefix`; nothing is written. */\n OBJECT_KEY_OUT_OF_SCOPE: {\n message: {\n text: 'Object key is outside the key prefix of this controller',\n code: 'core.static_asset.object_key_out_of_scope',\n },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n FILE_EMPTY: {\n message: { text: 'Empty file content', code: 'core.static_asset.file_empty' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n} as const satisfies Record<string, TErrorDefinition>;\n\n/** Registers these codes with the shared key registry so a consumer gets autocomplete on `messageCode`. */\ndeclare module '@venizia/ignis-helpers' {\n interface IErrorKeyRegistry extends TRegisterErrors<typeof StaticAssetErrors> {}\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,uIAAuI;AACvI,MAAM,CAAC,MAAM,i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B;QACrD,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,mBAAmB,EAAE;QACnB,OAAO,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,uCAAuC,EAAE;QACvF,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,mBAAmB,EAAE;QACnB,OAAO,EAAE;YACP,IAAI,EAAE,6BAA6B;YACnC,IAAI,EAAE,uCAAuC;SAC9C;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,wGAAwG;IACxG,uBAAuB,EAAE;QACvB,OAAO,EAAE;YACP,IAAI,EAAE,yDAAyD;YAC/D,IAAI,EAAE,2CAA2C;SAClD;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,UAAU,EAAE;QACV,OAAO,EAAE,EAAE,IAAI,EAAE,oBAAoB,EAAE,IAAI,EAAE,8BAA8B,EAAE;QAC7E,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;CACkD,CAAC","sourcesContent":["import type { TErrorDefinition, TRegisterErrors } from '@venizia/ignis-helpers/core';\nimport { ErrorScopes } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** Codes a client branches on for a rejected static-asset request. A throw site may override `message` to name the offending value. */\nexport const StaticAssetErrors = {\n UPLOAD_NOT_AUTHORIZED: {\n message: {\n text: 'Not allowed to upload',\n code: 'core.static_asset.upload_not_authorized',\n },\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n category: ErrorScopes.VALIDATION,\n },\n /** Both upload paths - one condition, one code to branch on. */\n UPLOAD_TOO_LARGE: {\n message: {\n text: 'File is larger than the maximum allowed',\n code: 'core.static_asset.upload_too_large',\n },\n statusCode: HTTP.ResultCodes.RS_4.ContentTooLarge,\n category: ErrorScopes.VALIDATION,\n },\n /** Deliberately not 404 and deliberately not \"expired\": a caller learns only that the token is no good, never whether the key it names exists. */\n INVALID_COMMIT_TOKEN: {\n message: { text: 'Invalid commit token', code: 'core.static_asset.invalid_commit_token' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n EXPIRED_COMMIT_TOKEN: {\n message: { text: 'Commit token has expired', code: 'core.static_asset.expired_commit_token' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n /** The pending object is not the one that was read: it was overwritten or removed after the pin. Raised by a pinned read and by the commit copy. */\n UPLOAD_CHANGED: {\n message: {\n text: 'The uploaded file changed after it was validated',\n code: 'core.static_asset.upload_changed',\n },\n statusCode: HTTP.ResultCodes.RS_4.Conflict,\n category: ErrorScopes.VALIDATION,\n },\n /** With a `validation` on, `commit` takes the token `upload-validate` returned, not the one the policy issued. */\n UPLOAD_NOT_VALIDATED: {\n message: {\n text: 'The upload has not been validated',\n code: 'core.static_asset.upload_not_validated',\n },\n statusCode: HTTP.ResultCodes.RS_4.UnprocessableEntity,\n category: ErrorScopes.VALIDATION,\n },\n BUCKET_NAME_INVALID: {\n message: { text: 'Invalid bucket name', code: 'core.static_asset.bucket_name_invalid' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n OBJECT_NAME_INVALID: {\n message: {\n text: 'Invalid object name or path',\n code: 'core.static_asset.object_name_invalid',\n },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n /** The application's naming hook produced a key outside the entry's `keyPrefix`; nothing is written. */\n OBJECT_KEY_OUT_OF_SCOPE: {\n message: {\n text: 'Object key is outside the key prefix of this controller',\n code: 'core.static_asset.object_key_out_of_scope',\n },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n FILE_EMPTY: {\n message: { text: 'Empty file content', code: 'core.static_asset.file_empty' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n} as const satisfies Record<string, TErrorDefinition>;\n\n/** Registers these codes with the shared key registry so a consumer gets autocomplete on `messageCode`. */\ndeclare module '@venizia/ignis-helpers' {\n interface IErrorKeyRegistry extends TRegisterErrors<typeof StaticAssetErrors> {}\n}\n"]}
@@ -6,7 +6,8 @@ import type { DiskHelper, IBucketRef, IFileStat, IObjectLocation, IObjectRef, IS
6
6
  import type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';
7
7
  import type { TConstValue, TValueOrAsyncResolver, ValueOrPromise } from '@venizia/ignis-helpers/common';
8
8
  import type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
9
- import type { StaticAssetRouteKeys } from './constants.js';
9
+ import type { StaticAssetRouteKeys, TStaticAssetTokenStage } from './constants.js';
10
+ import type { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
10
11
  /**
11
12
  * A feature that is on or off. `{ use: false }` is the whole off state; `{ use: true, ... }` carries
12
13
  * the options. One shape for every switch, so an option is never read from a feature that is off.
@@ -96,8 +97,8 @@ export type TStaticAssetDirectUploadOptions = {
96
97
  commit?: IDuration;
97
98
  };
98
99
  /**
99
- * Checks the pending file. On, the component registers `POST {base}/upload-validate`, and
100
- * `commit` runs the same check first and refuses an invalid file with `UPLOAD_INVALID`.
100
+ * Checks the pending file. On, the component registers `POST {base}/upload-validate`, which
101
+ * answers the token `commit` takes, and `commit` accepts no other.
101
102
  * Build it with `StaticAssetValidation.define`.
102
103
  */
103
104
  validation: TToggle<IStaticAssetValidation<z.ZodType>>;
@@ -115,11 +116,16 @@ export interface IStaticAssetValidationResult<Issue> {
115
116
  export interface IStaticAssetValidation<IssueSchema extends z.ZodType> {
116
117
  /** The shape of ONE issue. It types the handler's answer and documents the route's response. */
117
118
  issueSchema: IssueSchema;
118
- handler: (opts: IObjectLocation & {
119
+ /** Runs once per `upload-validate`. Read the file through `file`: every read is pinned to the content `commit` will copy. */
120
+ handler: (opts: {
121
+ file: StaticAssetPinnedFile;
119
122
  owner?: string;
120
- helper: IStorageHelper;
121
123
  }) => ValueOrPromise<IStaticAssetValidationResult<z.infer<IssueSchema>>>;
122
124
  }
125
+ /** What `validate` answers. `commitToken` is present only when the file is valid: it is the token `commit` takes. */
126
+ export interface IStaticAssetValidateResult<Issue> extends IStaticAssetValidationResult<Issue> {
127
+ commitToken?: string;
128
+ }
123
129
  /** Body of the upload policy route: the files the client intends to upload. */
124
130
  export type TStaticAssetUploadPolicyRequest = {
125
131
  files: Array<{
@@ -242,6 +248,11 @@ export type TStaticAssetEntry<Schema extends TMetaLinkCompatibleSchema = TMetaLi
242
248
  } & TStaticAssetStorage;
243
249
  /** Static asset entries keyed by an application-chosen name; each key becomes one controller. */
244
250
  export type TStaticAssetComponentOptions<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = Record<string, TStaticAssetEntry<Schema>>;
251
+ /** The content a validation read: the ETag, and the version id when the storage has real versions. */
252
+ export interface IStaticAssetPin {
253
+ etag: string;
254
+ versionId?: string;
255
+ }
245
256
  /**
246
257
  * What a commit token binds: the pending object a policy was issued for, when the grant dies and,
247
258
  * when the application supplies one, who it was issued to. Other business fields are deliberately
@@ -253,6 +264,9 @@ export interface IStaticAssetCommitTokenPayload {
253
264
  expiresAt: number;
254
265
  /** Absent when `directUpload.resolveOwner` is not set; present, the token commits only for that owner. */
255
266
  owner?: string;
267
+ stage: TStaticAssetTokenStage;
268
+ /** Present from `VALIDATED` on: `commit` copies only content that still matches it. */
269
+ pin?: IStaticAssetPin;
256
270
  }
257
271
  export {};
258
272
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteAuthConfig, TRouteContext } from '@/base';\nimport type { z } from '@hono/zod-openapi';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type { DefaultCRUDRepository, TTableObject } from '@venizia/ignis-connectors/postgres';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n StorageTypes,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type {\n TConstValue,\n TValueOrAsyncResolver,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetRouteKeys } from './constants';\n\n/**\n * A feature that is on or off. `{ use: false }` is the whole off state; `{ use: true, ... }` carries\n * the options. One shape for every switch, so an option is never read from a feature that is off.\n */\nexport type TToggle<Options extends object = Record<never, never>> =\n | { use: false }\n | ({ use: true } & Options);\n\n/** The storage backends a static asset entry can serve from: the helpers that declare one. */\nexport type TStaticAssetStorageType = typeof StorageTypes.DISK | typeof StorageTypes.BUN_S3;\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written - the scope and the default naming - so the hook may keep it, extend it or ignore it. */\nexport type TStaticAssetObjectKeyResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TStaticAssetDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n/** Path parameters of the object routes. */\nexport type TStaticAssetObjectParams = { objectName: string };\n\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TStaticAssetUploadLabels = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n};\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TStaticAssetDirectUploadOptions = {\n /**\n * Who may use direct upload. Guards every direct-upload route. There is no safe default for a\n * route that hands out a write credential, so leaving it out is allowed only when the entry's\n * `auth` already authenticates or authorizes: then `auth` is the gate. With neither, the\n * component refuses to start.\n */\n authorize?: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /**\n * Who the upload belongs to. Called on every direct-upload route: the policy route signs the\n * answer into the commit token, and the other routes refuse a token whose owner differs. Absent,\n * a token commits for whoever holds it.\n */\n resolveOwner?: (opts: { context: TRouteContext }) => ValueOrPromise<string>;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * The most files one upload-policy request may name; more is a 422.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /**\n * Where a policy may write: not empty, ends with `/`, made of valid key segments, and neither\n * inside the entry's `keyPrefix` nor containing it - a pending object must never be readable\n * through the entry's own routes. The final key is NEVER in a policy, so content cannot be\n * replaced after the commit. The lifecycle rule that collects abandoned uploads targets this prefix.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n expires?: {\n /**\n * How long the browser may post the bytes: the POST policy's lifetime.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n upload?: IDuration;\n\n /**\n * How long the commit token stays good, for validating and committing after the upload. The\n * pending object must outlive it, so the lifecycle rule on `pendingPrefix` has to be longer still.\n *\n * @default `upload`\n */\n commit?: IDuration;\n };\n\n /**\n * Checks the pending file. On, the component registers `POST {base}/upload-validate`, and\n * `commit` runs the same check first and refuses an invalid file with `UPLOAD_INVALID`.\n * Build it with `StaticAssetValidation.define`.\n */\n validation: TToggle<IStaticAssetValidation<z.ZodType>>;\n};\n\n/** What a validation answers: whether the file may be committed, and the problems the user should see. */\nexport interface IStaticAssetValidationResult<Issue> {\n isValid: boolean;\n issues: Issue[];\n}\n\n/**\n * The application's own check of an uploaded file, run on the PENDING object before anything is\n * committed. The component owns the route and the refusal; the application owns only this logic.\n * Build it with `StaticAssetValidation.define` so the handler is typed by `issueSchema`.\n */\nexport interface IStaticAssetValidation<IssueSchema extends z.ZodType> {\n /** The shape of ONE issue. It types the handler's answer and documents the route's response. */\n issueSchema: IssueSchema;\n handler: (\n opts: IObjectLocation & { owner?: string; helper: IStorageHelper },\n ) => ValueOrPromise<IStaticAssetValidationResult<z.infer<IssueSchema>>>;\n}\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TStaticAssetUploadPolicyRequest = {\n files: Array<{ fileName: string; contentType?: string; size?: number }>;\n};\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n repository: TValueOrAsyncResolver<DefaultCRUDRepository<Schema>>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels: form fields on an upload, beside the commit token on a direct one. */\n labels: TStaticAssetUploadLabels;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. `authenticate` and `authorize` replace the entry's `auth` for this route, and `{ skip: true }` leaves it open. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses' | 'authenticate' | 'authorize'>\n> &\n TRouteAuthConfig;\n\n/** Authentication and authorization for every built-in route of an entry; a route's own `authenticate`/`authorize` replaces it for that route. */\nexport type TStaticAssetAuth = TRouteAuthConfig & {\n /**\n * `{ use: true }` leaves `getObjectByName` and `downloadObjectByName` unauthenticated, so a\n * browser can show an image without a token. `listObjects` is NOT public: listing a bucket is not\n * reading an object.\n *\n * @default { use: false }\n */\n publicRead?: TToggle;\n};\n\n/** The name of a built-in route, the key of `routes`. */\nexport type TStaticAssetRouteKey = TConstValue<typeof StaticAssetRouteKeys>;\n\n/**\n * What each built-in route does: `{ use: false }` turns it off, `{ use: true, ... }` turns it on\n * with those overrides. A route left out is on as built.\n */\nexport type TStaticAssetRoutes = Partial<\n Record<TStaticAssetRouteKey, TToggle<TStaticAssetRouteConfig>>\n>;\n\n/** Uploading through the application: the browser sends the bytes to `POST /objects` and the application writes them to the storage. */\nexport type TStaticAssetServerUploadOptions = {\n /** Largest file the route accepts. Absent means no ceiling. Checked against `content-length` before the body is read, then per file after parsing. */\n maxBytes?: number;\n\n /**\n * The most file parts one request may carry; more is refused with 413 before anything is written.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /** The one hook that decides the key an uploaded file is stored under. Absent keeps the default naming. Under a `keyPrefix` a key outside the scope is refused, never rewritten. */\n objectKey?: TStaticAssetObjectKeyResolver;\n};\n\n/** Direct upload is a POST policy, which only S3 can sign, and its pending objects stay out of the served scope only when the entry has a `keyPrefix`. */\ntype TStaticAssetDirectUploadScope =\n | { keyPrefix?: string; directUpload: { use: false } }\n | { keyPrefix: string; directUpload: { use: true } & TStaticAssetDirectUploadOptions };\n\n/** The storage helper decides which direct upload shapes are possible. */\ntype TStaticAssetStorage =\n | ({ helper: BunS3Helper } & TStaticAssetDirectUploadScope)\n | { helper: DiskHelper; keyPrefix?: string; directUpload: { use: false } };\n\n/** One storage backend with its generated controller. Every switch is a toggle; a toggle left out is a type error, so nothing is on or off by accident. */\nexport type TStaticAssetEntry<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n basePath: string;\n\n /** The controller's name. Absent, it is derived from the entry's key. */\n name?: string;\n\n /** The single bucket every route uses. The function form is read per request, so an environment variable can be read lazily. */\n bucket: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this entry owns, e.g. `inventory/`. Every route refuses a key outside it as a\n * 404 without calling the storage, `listObjects` lists only inside it, and an upload key must\n * land inside it. `maxFolderDepth` counts the folders below it. Required with\n * `directUpload`: it keeps the pending prefix outside everything the routes serve.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n /**\n * Folders a key may nest below the `keyPrefix`, for every route of the entry: reads and deletes\n * too, so it holds for keys that arrive by direct upload or ingest.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The link stored and returned for an object. Absent builds the URL of this controller's own object route. */\n link?: (opts: IObjectLocation) => string;\n\n /** Authentication and authorization of every built-in route of this entry. Absent leaves every route open; `publicRead` is the only way a read route is public on purpose. */\n auth?: TStaticAssetAuth;\n\n serverUpload: TToggle<TStaticAssetServerUploadOptions>;\n\n /** Every upload also writes a MetaLink row, and the object's deletion removes it. */\n metaLink: TToggle<TMetaLinkConfig<Schema>>;\n\n routes?: TStaticAssetRoutes;\n\n extend?: {\n /** Registered BEFORE every built-in route, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n before?: TStaticAssetDefineExtraRoutes;\n /** Registered after every built-in route. */\n after?: TStaticAssetDefineExtraRoutes;\n };\n} & TStaticAssetStorage;\n\n/** Static asset entries keyed by an application-chosen name; each key becomes one controller. */\nexport type TStaticAssetComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = Record<string, TStaticAssetEntry<Schema>>;\n\n/**\n * What a commit token binds: the pending object a policy was issued for, when the grant dies and,\n * when the application supplies one, who it was issued to. Other business fields are deliberately\n * absent - which order or tenant an upload belongs to is the application's.\n */\nexport interface IStaticAssetCommitTokenPayload {\n bucket: IBucketRef;\n object: IObjectRef;\n expiresAt: number;\n /** Absent when `directUpload.resolveOwner` is not set; present, the token commits only for that owner. */\n owner?: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteAuthConfig, TRouteContext } from '@/base';\nimport type { z } from '@hono/zod-openapi';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type { DefaultCRUDRepository, TTableObject } from '@venizia/ignis-connectors/postgres';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n StorageTypes,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type {\n TConstValue,\n TValueOrAsyncResolver,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetRouteKeys, TStaticAssetTokenStage } from './constants';\nimport type { StaticAssetPinnedFile } from '../utilities/pinned-file.utility';\n\n/**\n * A feature that is on or off. `{ use: false }` is the whole off state; `{ use: true, ... }` carries\n * the options. One shape for every switch, so an option is never read from a feature that is off.\n */\nexport type TToggle<Options extends object = Record<never, never>> =\n | { use: false }\n | ({ use: true } & Options);\n\n/** The storage backends a static asset entry can serve from: the helpers that declare one. */\nexport type TStaticAssetStorageType = typeof StorageTypes.DISK | typeof StorageTypes.BUN_S3;\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written - the scope and the default naming - so the hook may keep it, extend it or ignore it. */\nexport type TStaticAssetObjectKeyResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TStaticAssetDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n/** Path parameters of the object routes. */\nexport type TStaticAssetObjectParams = { objectName: string };\n\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TStaticAssetUploadLabels = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n};\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TStaticAssetDirectUploadOptions = {\n /**\n * Who may use direct upload. Guards every direct-upload route. There is no safe default for a\n * route that hands out a write credential, so leaving it out is allowed only when the entry's\n * `auth` already authenticates or authorizes: then `auth` is the gate. With neither, the\n * component refuses to start.\n */\n authorize?: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /**\n * Who the upload belongs to. Called on every direct-upload route: the policy route signs the\n * answer into the commit token, and the other routes refuse a token whose owner differs. Absent,\n * a token commits for whoever holds it.\n */\n resolveOwner?: (opts: { context: TRouteContext }) => ValueOrPromise<string>;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * The most files one upload-policy request may name; more is a 422.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /**\n * Where a policy may write: not empty, ends with `/`, made of valid key segments, and neither\n * inside the entry's `keyPrefix` nor containing it - a pending object must never be readable\n * through the entry's own routes. The final key is NEVER in a policy, so content cannot be\n * replaced after the commit. The lifecycle rule that collects abandoned uploads targets this prefix.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n expires?: {\n /**\n * How long the browser may post the bytes: the POST policy's lifetime.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n upload?: IDuration;\n\n /**\n * How long the commit token stays good, for validating and committing after the upload. The\n * pending object must outlive it, so the lifecycle rule on `pendingPrefix` has to be longer still.\n *\n * @default `upload`\n */\n commit?: IDuration;\n };\n\n /**\n * Checks the pending file. On, the component registers `POST {base}/upload-validate`, which\n * answers the token `commit` takes, and `commit` accepts no other.\n * Build it with `StaticAssetValidation.define`.\n */\n validation: TToggle<IStaticAssetValidation<z.ZodType>>;\n};\n\n/** What a validation answers: whether the file may be committed, and the problems the user should see. */\nexport interface IStaticAssetValidationResult<Issue> {\n isValid: boolean;\n issues: Issue[];\n}\n\n/**\n * The application's own check of an uploaded file, run on the PENDING object before anything is\n * committed. The component owns the route and the refusal; the application owns only this logic.\n * Build it with `StaticAssetValidation.define` so the handler is typed by `issueSchema`.\n */\nexport interface IStaticAssetValidation<IssueSchema extends z.ZodType> {\n /** The shape of ONE issue. It types the handler's answer and documents the route's response. */\n issueSchema: IssueSchema;\n\n /** Runs once per `upload-validate`. Read the file through `file`: every read is pinned to the content `commit` will copy. */\n handler: (opts: {\n file: StaticAssetPinnedFile;\n owner?: string;\n }) => ValueOrPromise<IStaticAssetValidationResult<z.infer<IssueSchema>>>;\n}\n\n/** What `validate` answers. `commitToken` is present only when the file is valid: it is the token `commit` takes. */\nexport interface IStaticAssetValidateResult<Issue> extends IStaticAssetValidationResult<Issue> {\n commitToken?: string;\n}\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TStaticAssetUploadPolicyRequest = {\n files: Array<{ fileName: string; contentType?: string; size?: number }>;\n};\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n repository: TValueOrAsyncResolver<DefaultCRUDRepository<Schema>>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels: form fields on an upload, beside the commit token on a direct one. */\n labels: TStaticAssetUploadLabels;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. `authenticate` and `authorize` replace the entry's `auth` for this route, and `{ skip: true }` leaves it open. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses' | 'authenticate' | 'authorize'>\n> &\n TRouteAuthConfig;\n\n/** Authentication and authorization for every built-in route of an entry; a route's own `authenticate`/`authorize` replaces it for that route. */\nexport type TStaticAssetAuth = TRouteAuthConfig & {\n /**\n * `{ use: true }` leaves `getObjectByName` and `downloadObjectByName` unauthenticated, so a\n * browser can show an image without a token. `listObjects` is NOT public: listing a bucket is not\n * reading an object.\n *\n * @default { use: false }\n */\n publicRead?: TToggle;\n};\n\n/** The name of a built-in route, the key of `routes`. */\nexport type TStaticAssetRouteKey = TConstValue<typeof StaticAssetRouteKeys>;\n\n/**\n * What each built-in route does: `{ use: false }` turns it off, `{ use: true, ... }` turns it on\n * with those overrides. A route left out is on as built.\n */\nexport type TStaticAssetRoutes = Partial<\n Record<TStaticAssetRouteKey, TToggle<TStaticAssetRouteConfig>>\n>;\n\n/** Uploading through the application: the browser sends the bytes to `POST /objects` and the application writes them to the storage. */\nexport type TStaticAssetServerUploadOptions = {\n /** Largest file the route accepts. Absent means no ceiling. Checked against `content-length` before the body is read, then per file after parsing. */\n maxBytes?: number;\n\n /**\n * The most file parts one request may carry; more is refused with 413 before anything is written.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /** The one hook that decides the key an uploaded file is stored under. Absent keeps the default naming. Under a `keyPrefix` a key outside the scope is refused, never rewritten. */\n objectKey?: TStaticAssetObjectKeyResolver;\n};\n\n/** Direct upload is a POST policy, which only S3 can sign, and its pending objects stay out of the served scope only when the entry has a `keyPrefix`. */\ntype TStaticAssetDirectUploadScope =\n | { keyPrefix?: string; directUpload: { use: false } }\n | { keyPrefix: string; directUpload: { use: true } & TStaticAssetDirectUploadOptions };\n\n/** The storage helper decides which direct upload shapes are possible. */\ntype TStaticAssetStorage =\n | ({ helper: BunS3Helper } & TStaticAssetDirectUploadScope)\n | { helper: DiskHelper; keyPrefix?: string; directUpload: { use: false } };\n\n/** One storage backend with its generated controller. Every switch is a toggle; a toggle left out is a type error, so nothing is on or off by accident. */\nexport type TStaticAssetEntry<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n basePath: string;\n\n /** The controller's name. Absent, it is derived from the entry's key. */\n name?: string;\n\n /** The single bucket every route uses. The function form is read per request, so an environment variable can be read lazily. */\n bucket: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this entry owns, e.g. `inventory/`. Every route refuses a key outside it as a\n * 404 without calling the storage, `listObjects` lists only inside it, and an upload key must\n * land inside it. `maxFolderDepth` counts the folders below it. Required with\n * `directUpload`: it keeps the pending prefix outside everything the routes serve.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n /**\n * Folders a key may nest below the `keyPrefix`, for every route of the entry: reads and deletes\n * too, so it holds for keys that arrive by direct upload or ingest.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The link stored and returned for an object. Absent builds the URL of this controller's own object route. */\n link?: (opts: IObjectLocation) => string;\n\n /** Authentication and authorization of every built-in route of this entry. Absent leaves every route open; `publicRead` is the only way a read route is public on purpose. */\n auth?: TStaticAssetAuth;\n\n serverUpload: TToggle<TStaticAssetServerUploadOptions>;\n\n /** Every upload also writes a MetaLink row, and the object's deletion removes it. */\n metaLink: TToggle<TMetaLinkConfig<Schema>>;\n\n routes?: TStaticAssetRoutes;\n\n extend?: {\n /** Registered BEFORE every built-in route, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n before?: TStaticAssetDefineExtraRoutes;\n /** Registered after every built-in route. */\n after?: TStaticAssetDefineExtraRoutes;\n };\n} & TStaticAssetStorage;\n\n/** Static asset entries keyed by an application-chosen name; each key becomes one controller. */\nexport type TStaticAssetComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = Record<string, TStaticAssetEntry<Schema>>;\n\n/** The content a validation read: the ETag, and the version id when the storage has real versions. */\nexport interface IStaticAssetPin {\n etag: string;\n versionId?: string;\n}\n\n/**\n * What a commit token binds: the pending object a policy was issued for, when the grant dies and,\n * when the application supplies one, who it was issued to. Other business fields are deliberately\n * absent - which order or tenant an upload belongs to is the application's.\n */\nexport interface IStaticAssetCommitTokenPayload {\n bucket: IBucketRef;\n object: IObjectRef;\n expiresAt: number;\n /** Absent when `directUpload.resolveOwner` is not set; present, the token commits only for that owner. */\n owner?: string;\n stage: TStaticAssetTokenStage;\n /** Present from `VALIDATED` on: `commit` copies only content that still matches it. */\n pin?: IStaticAssetPin;\n}\n"]}
@@ -109,8 +109,14 @@ const uploadValidate = {
109
109
  method: HTTP.Methods.POST,
110
110
  path: '/upload-validate',
111
111
  body: CommitTokenSchema,
112
- response: z.object({ isValid: z.boolean(), issues: z.array(validation.issueSchema) }),
113
- description: 'Whether the pending file may be committed, and the issues found',
112
+ response: z.object({
113
+ isValid: z.boolean(),
114
+ issues: z.array(validation.issueSchema),
115
+ commitToken: z.string().optional().openapi({
116
+ description: 'Present only when the file is valid: commit with this token',
117
+ }),
118
+ }),
119
+ description: 'Whether the pending file may be committed, the issues found, and the token to commit it with',
114
120
  }),
115
121
  handler: async (ctx) => {
116
122
  const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });
@@ -1 +1 @@
1
- {"version":3,"file":"direct-upload.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/direct-upload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;A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AAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;gBACrF,WAAW,EAAE,iEAAiE;aAC/E,CAAC;YACF,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACrB,MAAM,KAAK,GAAG,MAAM,4BAA4B,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,CAAC;gBACxE,MAAM,EAAE,WAAW,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAA0B,MAAM,CAAC,CAAC;gBAEvE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,CAAC;gBAElF,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpD,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAwB,CAAC,YAAY,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC","sourcesContent":["import type { TRouteContext } from '@/base/controllers';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n StaticAssetDefaults,\n StaticAssetErrors,\n StaticAssetRouteKeys,\n type TStaticAssetUploadPolicyRequest,\n} from '../../common';\nimport {\n type IStaticAssetRoute,\n type IStaticAssetRouteEnv,\n StaticAssetFeatures,\n StaticAssetRouteUtility,\n} from './context';\nimport { StaticAssetDefinition } from './definition';\nimport { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels';\nimport { MetaLinkOutcomeSchema } from './upload';\n\nclass StaticAssetDirectUploadGuard {\n static require(opts: { env: IStaticAssetRouteEnv }) {\n return StaticAssetRouteUtility.requireFeature({\n value: opts.env.directUpload,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n });\n }\n\n /** First on every direct upload route: nothing below runs for a caller who may not use direct upload. Returns the owner the token is signed for or checked against. */\n static async guard(opts: {\n ctx: TRouteContext;\n direct: ReturnType<typeof StaticAssetDirectUploadGuard.require>;\n }): Promise<string | undefined> {\n const { ctx, direct } = opts;\n const isAuthorized = await direct.authorize({ context: ctx });\n\n if (!isAuthorized) {\n throw getError({ error: StaticAssetErrors.UPLOAD_NOT_AUTHORIZED });\n }\n\n return direct.resolveOwner?.({ context: ctx });\n }\n}\n\nconst CommitTokenSchema = z.object({ commitToken: z.string().min(1) });\n\nconst uploadPolicy: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_POLICY,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-policy',\n body: z.object({\n files: z\n .array(\n z.object({\n fileName: z.string().min(1),\n contentType: z.string().optional(),\n size: z.number().int().nonnegative().optional(),\n }),\n )\n .max(direct.maxFiles ?? StaticAssetDefaults.MAX_UPLOAD_FILES),\n }),\n response: z.array(\n z.object({\n postURL: z.string(),\n formData: z.record(z.string(), z.string()),\n objectName: z.string(),\n commitToken: z.string(),\n expiresAt: z.string(),\n }),\n ),\n description: 'One signed POST policy per file, plus the token its commit is claimed with',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { files } = ctx.req.valid<TStaticAssetUploadPolicyRequest>('json');\n\n const policies = await direct.policyService.issuePolicies({ files, owner });\n\n return ctx.json(policies, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\nconst uploadCommit: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_COMMIT,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-commit',\n // The labels sit beside the token, not inside it: the token is an HMAC over\n // { bucket, key, expiresAt } and deliberately carries no business fields.\n body: CommitTokenSchema.extend(UploadLabelsSchema.shape),\n response: z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string() }),\n link: z.string(),\n metaLink: MetaLinkOutcomeSchema,\n }),\n description: 'The object at its final key, copied out of the pending prefix',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { commitToken, ...fields } = ctx.req.valid<{ commitToken: string }>('json');\n const labels = StaticAssetLabelsUtility.parse({ fields });\n const result = await direct.commitService.commit({\n token: commitToken,\n owner,\n labels,\n });\n\n return ctx.json(result, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\n/** Only with a `validation`: the application adds logic, never a route of its own. */\nconst uploadValidate: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_VALIDATE,\n feature: StaticAssetFeatures.VALIDATION,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n const validation = StaticAssetRouteUtility.requireFeature({\n value: direct.validation,\n feature: StaticAssetFeatures.VALIDATION,\n });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-validate',\n body: CommitTokenSchema,\n response: z.object({ isValid: z.boolean(), issues: z.array(validation.issueSchema) }),\n description: 'Whether the pending file may be committed, and the issues found',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { commitToken } = ctx.req.valid<{ commitToken: string }>('json');\n\n const result = await direct.commitService.validate({ token: commitToken, owner });\n\n return ctx.json(result, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\nexport const directUploadRoutes: IStaticAssetRoute[] = [uploadPolicy, uploadCommit, uploadValidate];\n"]}
1
+ {"version":3,"file":"direct-upload.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/direct-upload.ts"],"names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C,IAAI;gBACzB,IAAI,EAAE,kBAAkB;gBACxB,IAAI,EAAE,iBAAiB;gBACvB,QAAQ,EAAE,CAAC,CAAC,MAAM,CAAC;oBACjB,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE;oBACpB,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC;oBACvC,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC;wBACzC,WAAW,EAAE,6DAA6D;qBAC3E,CAAC;iBACH,CAAC;gBACF,WAAW,EACT,8FAA8F;aACjG,CAAC;YACF,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACrB,MAAM,KAAK,GAAG,MAAM,4BAA4B,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,CAAC;gBACxE,MAAM,EAAE,WAAW,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAA0B,MAAM,CAAC,CAAC;gBAEvE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,CAAC;gBAElF,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpD,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAwB,CAAC,YAAY,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC","sourcesContent":["import type { TRouteContext } from '@/base/controllers';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n StaticAssetDefaults,\n StaticAssetErrors,\n StaticAssetRouteKeys,\n type TStaticAssetUploadPolicyRequest,\n} from '../../common';\nimport {\n type IStaticAssetRoute,\n type IStaticAssetRouteEnv,\n StaticAssetFeatures,\n StaticAssetRouteUtility,\n} from './context';\nimport { StaticAssetDefinition } from './definition';\nimport { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels';\nimport { MetaLinkOutcomeSchema } from './upload';\n\nclass StaticAssetDirectUploadGuard {\n static require(opts: { env: IStaticAssetRouteEnv }) {\n return StaticAssetRouteUtility.requireFeature({\n value: opts.env.directUpload,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n });\n }\n\n /** First on every direct upload route: nothing below runs for a caller who may not use direct upload. Returns the owner the token is signed for or checked against. */\n static async guard(opts: {\n ctx: TRouteContext;\n direct: ReturnType<typeof StaticAssetDirectUploadGuard.require>;\n }): Promise<string | undefined> {\n const { ctx, direct } = opts;\n const isAuthorized = await direct.authorize({ context: ctx });\n\n if (!isAuthorized) {\n throw getError({ error: StaticAssetErrors.UPLOAD_NOT_AUTHORIZED });\n }\n\n return direct.resolveOwner?.({ context: ctx });\n }\n}\n\nconst CommitTokenSchema = z.object({ commitToken: z.string().min(1) });\n\nconst uploadPolicy: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_POLICY,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-policy',\n body: z.object({\n files: z\n .array(\n z.object({\n fileName: z.string().min(1),\n contentType: z.string().optional(),\n size: z.number().int().nonnegative().optional(),\n }),\n )\n .max(direct.maxFiles ?? StaticAssetDefaults.MAX_UPLOAD_FILES),\n }),\n response: z.array(\n z.object({\n postURL: z.string(),\n formData: z.record(z.string(), z.string()),\n objectName: z.string(),\n commitToken: z.string(),\n expiresAt: z.string(),\n }),\n ),\n description: 'One signed POST policy per file, plus the token its commit is claimed with',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { files } = ctx.req.valid<TStaticAssetUploadPolicyRequest>('json');\n\n const policies = await direct.policyService.issuePolicies({ files, owner });\n\n return ctx.json(policies, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\nconst uploadCommit: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_COMMIT,\n feature: StaticAssetFeatures.DIRECT_UPLOAD,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-commit',\n // The labels sit beside the token, not inside it: the token is an HMAC over\n // { bucket, key, expiresAt } and deliberately carries no business fields.\n body: CommitTokenSchema.extend(UploadLabelsSchema.shape),\n response: z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string() }),\n link: z.string(),\n metaLink: MetaLinkOutcomeSchema,\n }),\n description: 'The object at its final key, copied out of the pending prefix',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { commitToken, ...fields } = ctx.req.valid<{ commitToken: string }>('json');\n const labels = StaticAssetLabelsUtility.parse({ fields });\n const result = await direct.commitService.commit({\n token: commitToken,\n owner,\n labels,\n });\n\n return ctx.json(result, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\n/** Only with a `validation`: the application adds logic, never a route of its own. */\nconst uploadValidate: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD_VALIDATE,\n feature: StaticAssetFeatures.VALIDATION,\n build: (env) => {\n const direct = StaticAssetDirectUploadGuard.require({ env });\n const validation = StaticAssetRouteUtility.requireFeature({\n value: direct.validation,\n feature: StaticAssetFeatures.VALIDATION,\n });\n\n return {\n config: StaticAssetDefinition.json({\n method: HTTP.Methods.POST,\n path: '/upload-validate',\n body: CommitTokenSchema,\n response: z.object({\n isValid: z.boolean(),\n issues: z.array(validation.issueSchema),\n commitToken: z.string().optional().openapi({\n description: 'Present only when the file is valid: commit with this token',\n }),\n }),\n description:\n 'Whether the pending file may be committed, the issues found, and the token to commit it with',\n }),\n handler: async (ctx) => {\n const owner = await StaticAssetDirectUploadGuard.guard({ ctx, direct });\n const { commitToken } = ctx.req.valid<{ commitToken: string }>('json');\n\n const result = await direct.commitService.validate({ token: commitToken, owner });\n\n return ctx.json(result, HTTP.ResultCodes.RS_2.Ok);\n },\n };\n },\n};\n\nexport const directUploadRoutes: IStaticAssetRoute[] = [uploadPolicy, uploadCommit, uploadValidate];\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { z } from '@hono/zod-openapi';
2
- import type { IBucketRef, IObjectLocation, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';
2
+ import { type IBucketRef, type IObjectLocation, type IObjectRef, type IStorageHelper, type IUploadResult } from '@venizia/ignis-helpers';
3
3
  import { BaseService } from '@venizia/ignis-kernel';
4
- import type { IStaticAssetValidation, IStaticAssetValidationResult, TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadLabels } from '../common/index.js';
4
+ import type { IStaticAssetValidation, IStaticAssetValidateResult, TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadLabels } from '../common/index.js';
5
5
  import type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
6
6
  /** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */
7
7
  export interface IStaticAssetCommitResult {
@@ -40,6 +40,8 @@ export declare class StaticAssetUploadCommitService<Schema extends TMetaLinkComp
40
40
  private readonly keyPrefix;
41
41
  private readonly pendingPrefix;
42
42
  constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>);
43
+ /** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */
44
+ private readPayload;
43
45
  /**
44
46
  * Everything `commit` checks before it touches storage, and nothing else: the signature, the
45
47
  * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
@@ -54,20 +56,29 @@ export declare class StaticAssetUploadCommitService<Schema extends TMetaLinkComp
54
56
  owner?: string;
55
57
  }): IObjectLocation;
56
58
  /**
57
- * `verify`, then the application's own check of the pending file. With no `validation` configured
58
- * every file is valid. The issues are the application's, in the shape of its `issueSchema`.
59
+ * `verify`, then the application's own check of the pending file, read once through a file pinned
60
+ * to the content that is there now. A valid file answers the token `commit` takes: it is bound to
61
+ * that content and dies when the incoming token does. An invalid one answers its issues and no token.
62
+ * A token of either stage may be validated again, which pins whatever is there at that moment.
59
63
  */
60
64
  validate(opts: {
61
65
  token: string;
62
66
  owner?: string;
63
- }): Promise<IStaticAssetValidationResult<unknown>>;
67
+ }): Promise<IStaticAssetValidateResult<unknown>>;
64
68
  private runValidation;
65
- /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */
69
+ /**
70
+ * Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
71
+ * row. With a `validation` on it takes the token `validate` returned and never runs the handler; the
72
+ * copy then happens only if the content still matches the pin. A MetaLink failure rides the result
73
+ * as a code: the object IS committed by then.
74
+ */
66
75
  commit(opts: {
67
76
  token: string;
68
77
  /** Who is committing. A token issued to an owner commits only for that owner. */
69
78
  owner?: string;
70
79
  labels?: TStaticAssetUploadLabels;
71
80
  }): Promise<IStaticAssetCommitResult>;
81
+ /** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
82
+ private copyPinned;
72
83
  }
73
84
  //# sourceMappingURL=commitment.service.d.ts.map
@@ -1,9 +1,11 @@
1
+ import { StorageUtility, } from '@venizia/ignis-helpers';
1
2
  import { getError } from '@venizia/ignis-helpers/core';
2
3
  import { BaseService } from '@venizia/ignis-kernel';
3
- import { StaticAssetErrors, StaticAssetMetaLinkCodes } from '../common/index.js';
4
+ import { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages } from '../common/index.js';
4
5
  import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
5
6
  import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
6
7
  import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
8
+ import { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
7
9
  /**
8
10
  * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
9
11
  * callable without a request. A service that saves its own record commits the upload in the same
@@ -26,16 +28,8 @@ export class StaticAssetUploadCommitService extends BaseService {
26
28
  this.keyPrefix = prefixes.keyPrefix;
27
29
  this.pendingPrefix = prefixes.pendingPrefix;
28
30
  }
29
- /**
30
- * Everything `commit` checks before it touches storage, and nothing else: the signature, the
31
- * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
32
- * no side effect, so an application can read an uploaded file and report its problems to the user
33
- * before anything is committed.
34
- *
35
- * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
36
- * than that the token is no good: a caller learns nothing about which keys exist.
37
- */
38
- verify(opts) {
31
+ /** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */
32
+ readPayload(opts) {
39
33
  const payload = StaticAssetCommitTokenUtility.read({
40
34
  token: opts.token,
41
35
  secretKey: this.options.directUpload.secretKey,
@@ -49,44 +43,76 @@ export class StaticAssetUploadCommitService extends BaseService {
49
43
  key: payload.object.key.slice(this.pendingPrefix.length),
50
44
  keyPrefix: this.keyPrefix,
51
45
  });
46
+ return payload;
47
+ }
48
+ /**
49
+ * Everything `commit` checks before it touches storage, and nothing else: the signature, the
50
+ * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
51
+ * no side effect, so an application can read an uploaded file and report its problems to the user
52
+ * before anything is committed.
53
+ *
54
+ * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
55
+ * than that the token is no good: a caller learns nothing about which keys exist.
56
+ */
57
+ verify(opts) {
58
+ const payload = this.readPayload(opts);
52
59
  return { bucket: payload.bucket, object: payload.object };
53
60
  }
54
61
  /**
55
- * `verify`, then the application's own check of the pending file. With no `validation` configured
56
- * every file is valid. The issues are the application's, in the shape of its `issueSchema`.
62
+ * `verify`, then the application's own check of the pending file, read once through a file pinned
63
+ * to the content that is there now. A valid file answers the token `commit` takes: it is bound to
64
+ * that content and dies when the incoming token does. An invalid one answers its issues and no token.
65
+ * A token of either stage may be validated again, which pins whatever is there at that moment.
57
66
  */
58
67
  async validate(opts) {
59
- const pending = this.verify({ token: opts.token, owner: opts.owner });
60
- return this.runValidation({ pending, owner: opts.owner });
68
+ const { helper, directUpload, scope } = this.options;
69
+ const payload = this.readPayload(opts);
70
+ const location = { bucket: payload.bucket, object: payload.object };
71
+ const stat = await helper.getStat(location);
72
+ const pin = StaticAssetPinnedFile.pinOf({ stat, scope });
73
+ const result = await this.runValidation({ location, pin, size: stat.size, owner: opts.owner });
74
+ if (!result.isValid) {
75
+ return { isValid: false, issues: result.issues };
76
+ }
77
+ return {
78
+ ...result,
79
+ commitToken: StaticAssetCommitTokenUtility.build({
80
+ payload: { ...payload, stage: StaticAssetTokenStages.VALIDATED, pin },
81
+ secretKey: directUpload.secretKey,
82
+ }),
83
+ };
61
84
  }
62
- async runValidation(opts) {
85
+ runValidation(opts) {
63
86
  const { helper, directUpload } = this.options;
64
87
  if (!directUpload.validation) {
65
88
  return { isValid: true, issues: [] };
66
89
  }
67
- return directUpload.validation.handler({ ...opts.pending, owner: opts.owner, helper });
90
+ const { location, pin, size, owner } = opts;
91
+ return directUpload.validation.handler({
92
+ file: new StaticAssetPinnedFile({ helper, location, pin, size }),
93
+ owner,
94
+ });
68
95
  }
69
- /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */
96
+ /**
97
+ * Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
98
+ * row. With a `validation` on it takes the token `validate` returned and never runs the handler; the
99
+ * copy then happens only if the content still matches the pin. A MetaLink failure rides the result
100
+ * as a code: the object IS committed by then.
101
+ */
70
102
  async commit(opts) {
71
- const { helper, storage, metaLink, link: buildLink } = this.options;
103
+ const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;
72
104
  // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
73
105
  // token fails without a round trip, so timing says nothing.
74
- const pending = this.verify({ token: opts.token, owner: opts.owner });
75
- const { bucket: bucketRef, object: pendingObject } = pending;
76
- // An invalid file never leaves the pending prefix: this runs before the copy.
77
- const validation = await this.runValidation({ pending, owner: opts.owner });
78
- if (!validation.isValid) {
79
- throw getError(StaticAssetErrors.UPLOAD_INVALID);
106
+ const payload = this.readPayload(opts);
107
+ const { bucket: bucketRef, object: pendingObject, pin } = payload;
108
+ if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {
109
+ throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);
80
110
  }
81
111
  // Labels, not authorization - the token deliberately carries no business fields, so they travel
82
112
  // beside it rather than inside it.
83
113
  const labels = opts.labels ?? {};
84
114
  const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };
85
- await helper.copyObject({
86
- bucket: bucketRef,
87
- source: pendingObject,
88
- destination: object,
89
- });
115
+ await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });
90
116
  // The copy IS the commit; removing the temporary object is cleanup. A failure here
91
117
  // leaves one object for the lifecycle rule, and failing the request would tell the
92
118
  // caller their upload did not work when it did.
@@ -137,5 +163,28 @@ export class StaticAssetUploadCommitService extends BaseService {
137
163
  metaLink: metaLinkResult,
138
164
  };
139
165
  }
166
+ /** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
167
+ async copyPinned(opts) {
168
+ const { bucket, source, destination, pin } = opts;
169
+ const condition = pin ? StaticAssetPinnedFile.conditionOf({ pin }) : {};
170
+ try {
171
+ await this.options.helper.copyObject({
172
+ bucket,
173
+ source,
174
+ destination,
175
+ ifMatch: condition.ifMatch,
176
+ sourceVersionId: condition.versionId,
177
+ });
178
+ }
179
+ catch (error) {
180
+ // With a pin the object was there when it was validated: a miss now is a change as much as other content is.
181
+ if (pin &&
182
+ (StorageUtility.isPreconditionFailedError({ error }) ||
183
+ StorageUtility.isNotFoundError({ error }))) {
184
+ throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });
185
+ }
186
+ throw error;
187
+ }
188
+ }
140
189
  }
141
190
  //# sourceMappingURL=commitment.service.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAS7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AA8B5E;;;;;;;;GAQG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAKnB,YAAY,IAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QAEpB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,2BAA2B,CAAC;YACtE,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,aAAa;YAC9C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IAC9C,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,IAAuC;QAC5C,MAAM,OAAO,GAAG,6BAA6B,CAAC,IAAI,CAAC;YACjD,KA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;CACF","sourcesContent":["import type { z } from '@hono/zod-openapi';\nimport type {\n IBucketRef,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n} from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors, StaticAssetMetaLinkCodes } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n IStaticAssetValidation,\n IStaticAssetValidationResult,\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadLabels,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {\n /** Absent, every file is valid. */\n validation?: IStaticAssetValidation<z.ZodType>;\n };\n storage: TStaticAssetStorageType;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */\n link: (opts: IObjectLocation) => string;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy. It names an owner only when\n * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who\n * holds the token can.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix: string;\n private readonly pendingPrefix: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /**\n * Everything `commit` checks before it touches storage, and nothing else: the signature, the\n * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and\n * no side effect, so an application can read an uploaded file and report its problems to the user\n * before anything is committed.\n *\n * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more\n * than that the token is no good: a caller learns nothing about which keys exist.\n */\n verify(opts: { token: string; owner?: string }): IObjectLocation {\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.token,\n secretKey: this.options.directUpload.secretKey,\n });\n\n // The same error as a forged token: a caller learns only that the token is no good for them.\n if (payload.owner !== undefined && payload.owner !== opts.owner) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({\n key: payload.object.key.slice(this.pendingPrefix.length),\n keyPrefix: this.keyPrefix,\n });\n\n return { bucket: payload.bucket, object: payload.object };\n }\n\n /**\n * `verify`, then the application's own check of the pending file. With no `validation` configured\n * every file is valid. The issues are the application's, in the shape of its `issueSchema`.\n */\n async validate(opts: {\n token: string;\n owner?: string;\n }): Promise<IStaticAssetValidationResult<unknown>> {\n const pending = this.verify({ token: opts.token, owner: opts.owner });\n\n return this.runValidation({ pending, owner: opts.owner });\n }\n\n private async runValidation(opts: {\n pending: IObjectLocation;\n owner?: string;\n }): Promise<IStaticAssetValidationResult<unknown>> {\n const { helper, directUpload } = this.options;\n\n if (!directUpload.validation) {\n return { isValid: true, issues: [] };\n }\n\n return directUpload.validation.handler({ ...opts.pending, owner: opts.owner, helper });\n }\n\n /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */\n async commit(opts: {\n token: string;\n /** Who is committing. A token issued to an owner commits only for that owner. */\n owner?: string;\n labels?: TStaticAssetUploadLabels;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, storage, metaLink, link: buildLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const pending = this.verify({ token: opts.token, owner: opts.owner });\n const { bucket: bucketRef, object: pendingObject } = pending;\n\n // An invalid file never leaves the pending prefix: this runs before the copy.\n const validation = await this.runValidation({ pending, owner: opts.owner });\n\n if (!validation.isValid) {\n throw getError(StaticAssetErrors.UPLOAD_INVALID);\n }\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const labels = opts.labels ?? {};\n\n const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };\n\n await helper.copyObject({\n bucket: bucketRef,\n source: pendingObject,\n destination: object,\n });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = buildLink({ bucket: bucketRef, object });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n labels,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n metaLink: metaLinkResult,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AACA,OAAO,EACL,cAAc,GAMf,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAChG,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAY7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AA8BzE;;;;;;;;GAQG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAKnB,YAAY,IAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QAEpB,MAAM,QAAQ,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IAAI;YACJ,QAAQ,EAAE,cAAc;SACzB,CAAC;IACJ,CAAC;IAED,wGAAwG;IAChG,KAAK,CAAC,UAAU,CAAC,IAKxB;QACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAClD,MAAM,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,qBAAqB,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;gBACnC,MAAM;gBACN,MAAM;gBACN,WAAW;gBACX,OAAO,EAAE,SAAS,CAAC,OAAO;gBAC1B,eAAe,EAAE,SAAS,CAAC,SAAS;aACrC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,6GAA6G;YAC7G,IACE,GAAG;gBACH,CAAC,cAAc,CAAC,yBAAyB,CAAC,EAAE,KAAK,EAAE,CAAC;oBAClD,cAAc,CAAC,eAAe,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,EAC5C,CAAC;gBACD,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5E,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { z } from '@hono/zod-openapi';\nimport {\n StorageUtility,\n type IBucketRef,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelper,\n type IUploadResult,\n} from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n IStaticAssetValidation,\n IStaticAssetCommitTokenPayload,\n IStaticAssetPin,\n IStaticAssetValidateResult,\n IStaticAssetValidationResult,\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadLabels,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport { StaticAssetPinnedFile } from '../utilities/pinned-file.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {\n /** Absent, every file is valid. */\n validation?: IStaticAssetValidation<z.ZodType>;\n };\n storage: TStaticAssetStorageType;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */\n link: (opts: IObjectLocation) => string;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy. It names an owner only when\n * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who\n * holds the token can.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix: string;\n private readonly pendingPrefix: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */\n private readPayload(opts: { token: string; owner?: string }): IStaticAssetCommitTokenPayload {\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.token,\n secretKey: this.options.directUpload.secretKey,\n });\n\n // The same error as a forged token: a caller learns only that the token is no good for them.\n if (payload.owner !== undefined && payload.owner !== opts.owner) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({\n key: payload.object.key.slice(this.pendingPrefix.length),\n keyPrefix: this.keyPrefix,\n });\n\n return payload;\n }\n\n /**\n * Everything `commit` checks before it touches storage, and nothing else: the signature, the\n * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and\n * no side effect, so an application can read an uploaded file and report its problems to the user\n * before anything is committed.\n *\n * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more\n * than that the token is no good: a caller learns nothing about which keys exist.\n */\n verify(opts: { token: string; owner?: string }): IObjectLocation {\n const payload = this.readPayload(opts);\n\n return { bucket: payload.bucket, object: payload.object };\n }\n\n /**\n * `verify`, then the application's own check of the pending file, read once through a file pinned\n * to the content that is there now. A valid file answers the token `commit` takes: it is bound to\n * that content and dies when the incoming token does. An invalid one answers its issues and no token.\n * A token of either stage may be validated again, which pins whatever is there at that moment.\n */\n async validate(opts: {\n token: string;\n owner?: string;\n }): Promise<IStaticAssetValidateResult<unknown>> {\n const { helper, directUpload, scope } = this.options;\n const payload = this.readPayload(opts);\n const location = { bucket: payload.bucket, object: payload.object };\n\n const stat = await helper.getStat(location);\n const pin = StaticAssetPinnedFile.pinOf({ stat, scope });\n const result = await this.runValidation({ location, pin, size: stat.size, owner: opts.owner });\n\n if (!result.isValid) {\n return { isValid: false, issues: result.issues };\n }\n\n return {\n ...result,\n commitToken: StaticAssetCommitTokenUtility.build({\n payload: { ...payload, stage: StaticAssetTokenStages.VALIDATED, pin },\n secretKey: directUpload.secretKey,\n }),\n };\n }\n\n private runValidation(opts: {\n location: IObjectLocation;\n pin: IStaticAssetPin;\n size: number;\n owner?: string;\n }): ValueOrPromise<IStaticAssetValidationResult<unknown>> {\n const { helper, directUpload } = this.options;\n\n if (!directUpload.validation) {\n return { isValid: true, issues: [] };\n }\n\n const { location, pin, size, owner } = opts;\n\n return directUpload.validation.handler({\n file: new StaticAssetPinnedFile({ helper, location, pin, size }),\n owner,\n });\n }\n\n /**\n * Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the\n * row. With a `validation` on it takes the token `validate` returned and never runs the handler; the\n * copy then happens only if the content still matches the pin. A MetaLink failure rides the result\n * as a code: the object IS committed by then.\n */\n async commit(opts: {\n token: string;\n /** Who is committing. A token issued to an owner commits only for that owner. */\n owner?: string;\n labels?: TStaticAssetUploadLabels;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const payload = this.readPayload(opts);\n const { bucket: bucketRef, object: pendingObject, pin } = payload;\n\n if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {\n throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);\n }\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const labels = opts.labels ?? {};\n\n const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };\n\n await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = buildLink({ bucket: bucketRef, object });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n labels,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n metaLink: metaLinkResult,\n };\n }\n\n /** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */\n private async copyPinned(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n pin?: IStaticAssetPin;\n }): Promise<void> {\n const { bucket, source, destination, pin } = opts;\n const condition = pin ? StaticAssetPinnedFile.conditionOf({ pin }) : {};\n\n try {\n await this.options.helper.copyObject({\n bucket,\n source,\n destination,\n ifMatch: condition.ifMatch,\n sourceVersionId: condition.versionId,\n });\n } catch (error) {\n // With a pin the object was there when it was validated: a miss now is a change as much as other content is.\n if (\n pin &&\n (StorageUtility.isPreconditionFailedError({ error }) ||\n StorageUtility.isNotFoundError({ error }))\n ) {\n throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });\n }\n\n throw error;\n }\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { DurationMultipliers, ResolverUtility } from '@venizia/ignis-helpers/common';
2
2
  import { getError, UuidHelper } from '@venizia/ignis-helpers/core';
3
3
  import { BaseService } from '@venizia/ignis-kernel';
4
- import { StaticAssetErrors } from '../common/index.js';
4
+ import { StaticAssetErrors, StaticAssetTokenStages } from '../common/index.js';
5
5
  import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
6
6
  import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
7
7
  /**
@@ -73,6 +73,7 @@ export class StaticAssetUploadPolicyService extends BaseService {
73
73
  ? new Date(policy.expiresAt).getTime()
74
74
  : Date.now() + this.commitLifetimeMs,
75
75
  owner: opts.owner,
76
+ stage: StaticAssetTokenStages.ISSUED,
76
77
  },
77
78
  secretKey: directUpload.secretKey,
78
79
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"policy.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/policy.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAoB5E;;;;;;GAMG;AACH,MAAM,OAAO,8BAA+B,SAAQ,WAAW;IAK7D,YAAY,IAA4C;QACtD,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC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AAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,gBAAgB;wBACxC,KAAK,EAAE,IAAI,CAAC,KAAK;qBAClB;oBACD,SAAS,EAAE,YAAY,CAAC,SAAS;iBAClC,CAAC;aACH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import type { IPostPolicy, IStorageHelper } from '@venizia/ignis-helpers';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport { DurationMultipliers, ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { TValueOrAsyncResolver } from '@venizia/ignis-helpers/common';\nimport { getError, UuidHelper } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type { TStaticAssetDirectUploadOptions, TStaticAssetUploadPolicyRequest } from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\n\n/** What the client posts to the storage, plus the key it lands under and the token that commits it. */\nexport type TStaticAssetUploadPolicy = IPostPolicy & { objectName: string; commitToken: string };\n\n/** What an `StaticAssetUploadPolicyService` needs, all of it one options entry already carries. */\nexport interface IStaticAssetUploadPolicyServiceOptions {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** A policy names ONE bucket, so a direct upload has no bucket in its URL. */\n bucket: TValueOrAsyncResolver<string>;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. Required: it keeps the pending prefix out of everything the routes serve. */\n keyPrefix: string;\n directUpload: Pick<\n TStaticAssetDirectUploadOptions,\n 'maxBytes' | 'expires' | 'secretKey' | 'pendingPrefix'\n >;\n}\n\n/**\n * Signs the permission for a browser to post bytes straight to storage: the body of the\n * `upload-policy` route, callable without a request.\n *\n * Authorization is NOT here. A policy is a write credential, and who may ask for one is the route's\n * `directUpload.authorize`; code that calls this service has decided that for itself.\n */\nexport class StaticAssetUploadPolicyService extends BaseService {\n private readonly options: IStaticAssetUploadPolicyServiceOptions;\n private readonly policyKeyPrefix: string;\n private readonly commitLifetimeMs?: number;\n\n constructor(opts: IStaticAssetUploadPolicyServiceOptions) {\n super({ scope: opts.scope });\n\n this.options = opts;\n this.commitLifetimeMs = StaticAssetUploadPolicyService.resolveCommitLifetimeMs({\n scope: opts.scope,\n commit: opts.directUpload.expires?.commit,\n });\n this.policyKeyPrefix = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n }).policyKeyPrefix;\n }\n\n /** `undefined` when `expires.commit` is not set: the token then dies with the policy. */\n private static resolveCommitLifetimeMs(opts: {\n scope: string;\n commit?: IDuration;\n }): number | undefined {\n const { scope, commit } = opts;\n\n if (commit === undefined) {\n return undefined;\n }\n\n const lifetimeMs = DurationMultipliers.toMilliseconds(commit);\n\n if (lifetimeMs === null || lifetimeMs <= 0) {\n throw getError({\n message: `[${scope}] directUpload.expires.commit is not a usable duration | unit: ${commit.unit} | value: ${commit.value}`,\n });\n }\n\n return lifetimeMs;\n }\n\n /** One signed policy per file. A size over `maxBytes` is refused before any policy is signed. */\n async issuePolicies(opts: {\n files: TStaticAssetUploadPolicyRequest['files'];\n owner?: string;\n }): Promise<TStaticAssetUploadPolicy[]> {\n const { helper, bucket, directUpload } = this.options;\n const bucketName = await ResolverUtility.resolveValueAsync({ value: bucket });\n\n const policies: TStaticAssetUploadPolicy[] = [];\n\n for (const file of opts.files) {\n if (file.size !== undefined && file.size > directUpload.maxBytes) {\n throw getError({\n error: StaticAssetErrors.UPLOAD_TOO_LARGE,\n message: `File '${file.fileName}' is ${file.size} bytes, over the ${directUpload.maxBytes} the policy allows`,\n });\n }\n\n // Generated, never taken from the caller: a key the caller picks is a key the caller\n // can collide with, and the pending object is the one thing a policy authorizes.\n const objectName = `${this.policyKeyPrefix}${UuidHelper.getInstance().v4()}/${file.fileName}`;\n const policy = await helper.presignPost({\n bucket: { name: bucketName },\n object: { key: objectName },\n maxBytes: directUpload.maxBytes,\n contentType: file.contentType,\n expiresIn: directUpload.expires?.upload,\n });\n\n policies.push({\n ...policy,\n objectName,\n commitToken: StaticAssetCommitTokenUtility.build({\n payload: {\n bucket: { name: bucketName },\n object: { key: objectName },\n expiresAt:\n this.commitLifetimeMs === undefined\n ? new Date(policy.expiresAt).getTime()\n : Date.now() + this.commitLifetimeMs,\n owner: opts.owner,\n },\n secretKey: directUpload.secretKey,\n }),\n });\n }\n\n return policies;\n }\n}\n"]}
1
+ {"version":3,"file":"policy.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/policy.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACtE,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAoB5E;;;;;;GAMG;AACH,MAAM,OAAO,8BAA+B,SAAQ,WAAW;IAK7D,YAAY,IAA4C;QACtD,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,gBAAgB,GAAG,8BAA8B,CAAC,uBAAuB,CAAC;YAC7E,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM;SAC1C,CAAC,CAAC;QACH,IAAI,CAAC,eAAe,GAAG,0BAA0B,CAAC,2BA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{ IPostPolicy, IStorageHelper } from '@venizia/ignis-helpers';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport { DurationMultipliers, ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { TValueOrAsyncResolver } from '@venizia/ignis-helpers/common';\nimport { getError, UuidHelper } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors, StaticAssetTokenStages } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type { TStaticAssetDirectUploadOptions, TStaticAssetUploadPolicyRequest } from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\n\n/** What the client posts to the storage, plus the key it lands under and the token that commits it. */\nexport type TStaticAssetUploadPolicy = IPostPolicy & { objectName: string; commitToken: string };\n\n/** What an `StaticAssetUploadPolicyService` needs, all of it one options entry already carries. */\nexport interface IStaticAssetUploadPolicyServiceOptions {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** A policy names ONE bucket, so a direct upload has no bucket in its URL. */\n bucket: TValueOrAsyncResolver<string>;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. Required: it keeps the pending prefix out of everything the routes serve. */\n keyPrefix: string;\n directUpload: Pick<\n TStaticAssetDirectUploadOptions,\n 'maxBytes' | 'expires' | 'secretKey' | 'pendingPrefix'\n >;\n}\n\n/**\n * Signs the permission for a browser to post bytes straight to storage: the body of the\n * `upload-policy` route, callable without a request.\n *\n * Authorization is NOT here. A policy is a write credential, and who may ask for one is the route's\n * `directUpload.authorize`; code that calls this service has decided that for itself.\n */\nexport class StaticAssetUploadPolicyService extends BaseService {\n private readonly options: IStaticAssetUploadPolicyServiceOptions;\n private readonly policyKeyPrefix: string;\n private readonly commitLifetimeMs?: number;\n\n constructor(opts: IStaticAssetUploadPolicyServiceOptions) {\n super({ scope: opts.scope });\n\n this.options = opts;\n this.commitLifetimeMs = StaticAssetUploadPolicyService.resolveCommitLifetimeMs({\n scope: opts.scope,\n commit: opts.directUpload.expires?.commit,\n });\n this.policyKeyPrefix = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n }).policyKeyPrefix;\n }\n\n /** `undefined` when `expires.commit` is not set: the token then dies with the policy. */\n private static resolveCommitLifetimeMs(opts: {\n scope: string;\n commit?: IDuration;\n }): number | undefined {\n const { scope, commit } = opts;\n\n if (commit === undefined) {\n return undefined;\n }\n\n const lifetimeMs = DurationMultipliers.toMilliseconds(commit);\n\n if (lifetimeMs === null || lifetimeMs <= 0) {\n throw getError({\n message: `[${scope}] directUpload.expires.commit is not a usable duration | unit: ${commit.unit} | value: ${commit.value}`,\n });\n }\n\n return lifetimeMs;\n }\n\n /** One signed policy per file. A size over `maxBytes` is refused before any policy is signed. */\n async issuePolicies(opts: {\n files: TStaticAssetUploadPolicyRequest['files'];\n owner?: string;\n }): Promise<TStaticAssetUploadPolicy[]> {\n const { helper, bucket, directUpload } = this.options;\n const bucketName = await ResolverUtility.resolveValueAsync({ value: bucket });\n\n const policies: TStaticAssetUploadPolicy[] = [];\n\n for (const file of opts.files) {\n if (file.size !== undefined && file.size > directUpload.maxBytes) {\n throw getError({\n error: StaticAssetErrors.UPLOAD_TOO_LARGE,\n message: `File '${file.fileName}' is ${file.size} bytes, over the ${directUpload.maxBytes} the policy allows`,\n });\n }\n\n // Generated, never taken from the caller: a key the caller picks is a key the caller\n // can collide with, and the pending object is the one thing a policy authorizes.\n const objectName = `${this.policyKeyPrefix}${UuidHelper.getInstance().v4()}/${file.fileName}`;\n const policy = await helper.presignPost({\n bucket: { name: bucketName },\n object: { key: objectName },\n maxBytes: directUpload.maxBytes,\n contentType: file.contentType,\n expiresIn: directUpload.expires?.upload,\n });\n\n policies.push({\n ...policy,\n objectName,\n commitToken: StaticAssetCommitTokenUtility.build({\n payload: {\n bucket: { name: bucketName },\n object: { key: objectName },\n expiresAt:\n this.commitLifetimeMs === undefined\n ? new Date(policy.expiresAt).getTime()\n : Date.now() + this.commitLifetimeMs,\n owner: opts.owner,\n stage: StaticAssetTokenStages.ISSUED,\n },\n secretKey: directUpload.secretKey,\n }),\n });\n }\n\n return policies;\n }\n}\n"]}
@@ -6,6 +6,7 @@ export declare class StaticAssetCommitTokenUtility {
6
6
  private static isRecord;
7
7
  /** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */
8
8
  private static parse;
9
+ private static parsePin;
9
10
  /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */
10
11
  static build(opts: {
11
12
  payload: IStaticAssetCommitTokenPayload;
@@ -1,5 +1,6 @@
1
1
  import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';
2
2
  import { getError } from '@venizia/ignis-helpers/core';
3
+ import { StaticAssetTokenStages } from '../common/constants.js';
3
4
  import { StaticAssetErrors } from '../common/errors.js';
4
5
  /** Signs and reads the token the commit route trusts instead of a key a caller names. */
5
6
  export class StaticAssetCommitTokenUtility {
@@ -29,7 +30,7 @@ export class StaticAssetCommitTokenUtility {
29
30
  if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {
30
31
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
31
32
  }
32
- const { bucket, object, expiresAt, owner } = parsed;
33
+ const { bucket, object, expiresAt, owner, stage, pin } = parsed;
33
34
  if (!StaticAssetCommitTokenUtility.isRecord(bucket) ||
34
35
  typeof bucket.name !== 'string' ||
35
36
  !StaticAssetCommitTokenUtility.isRecord(object) ||
@@ -38,13 +39,37 @@ export class StaticAssetCommitTokenUtility {
38
39
  (owner !== undefined && typeof owner !== 'string')) {
39
40
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
40
41
  }
42
+ if (stage === StaticAssetTokenStages.ISSUED) {
43
+ return {
44
+ bucket: { name: bucket.name },
45
+ object: { key: object.key },
46
+ expiresAt,
47
+ owner,
48
+ stage,
49
+ };
50
+ }
51
+ // A validated token without its pin would commit unpinned content: it is no token.
52
+ if (stage !== StaticAssetTokenStages.VALIDATED) {
53
+ throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
54
+ }
41
55
  return {
42
56
  bucket: { name: bucket.name },
43
57
  object: { key: object.key },
44
58
  expiresAt,
45
59
  owner,
60
+ stage,
61
+ pin: StaticAssetCommitTokenUtility.parsePin({ pin }),
46
62
  };
47
63
  }
64
+ static parsePin(opts) {
65
+ const { pin } = opts;
66
+ if (!StaticAssetCommitTokenUtility.isRecord(pin) ||
67
+ typeof pin.etag !== 'string' ||
68
+ (pin.versionId !== undefined && typeof pin.versionId !== 'string')) {
69
+ throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
70
+ }
71
+ return { etag: pin.etag, versionId: pin.versionId };
72
+ }
48
73
  /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */
49
74
  static build(opts) {
50
75
  const body = StaticAssetCommitTokenUtility.encode(opts.payload);
@@ -1 +1 @@
1
- {"version":3,"file":"commit-token.utility.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/commit-token.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD,yFAAyF;AACzF,MAAM,OAAO,6BAA6B;IAChC,MAAM,CAAC,MAAM,CAAC,OAAuC;QAC3D,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;IACpE,CAAC;IAED,uFAAuF;IAC/E,MAAM,CAAC,IAAI,CAAC,IAAyC;QAC3D,OAAO,IAAI,CAAC,aAAa,CAAC,cAAc,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AC7B,MAAM,QAAQ,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,CAAC;QACzD,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { StaticAssetErrors } from '../common/errors';\nimport type { IStaticAssetCommitTokenPayload } from '../common/types';\n\n/** Signs and reads the token the commit route trusts instead of a key a caller names. */\nexport class StaticAssetCommitTokenUtility {\n private static encode(payload: IStaticAssetCommitTokenPayload): string {\n return Buffer.from(JSON.stringify(payload)).toString('base64url');\n }\n\n // `Hash.hmac` refuses an empty secret: an unkeyed signature is one anyone can compute.\n private static sign(opts: { body: string; secretKey: string }): string {\n return Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({\n message: opts.body,\n secret: opts.secretKey,\n opts: { outputEncoding: HashOutputEncodings.BASE64URL },\n });\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n }\n\n /** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */\n private static parse(opts: { body: string }): IStaticAssetCommitTokenPayload {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(Buffer.from(opts.body, 'base64url').toString('utf8'));\n } catch {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const { bucket, object, expiresAt, owner } = parsed;\n\n if (\n !StaticAssetCommitTokenUtility.isRecord(bucket) ||\n typeof bucket.name !== 'string' ||\n !StaticAssetCommitTokenUtility.isRecord(object) ||\n typeof object.key !== 'string' ||\n typeof expiresAt !== 'number' ||\n (owner !== undefined && typeof owner !== 'string')\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n return {\n bucket: { name: bucket.name },\n object: { key: object.key },\n expiresAt,\n owner,\n };\n }\n\n /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */\n static build(opts: { payload: IStaticAssetCommitTokenPayload; secretKey: string }): string {\n const body = StaticAssetCommitTokenUtility.encode(opts.payload);\n\n return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;\n }\n\n /**\n * Reads a commit token back, or throws.\n *\n * Verification happens BEFORE any storage call, which is what makes the commit route refuse to be a\n * name prober: a forged token fails without a round trip, so timing says nothing about what exists.\n */\n static read(opts: {\n token: string;\n secretKey: string;\n now?: number;\n }): IStaticAssetCommitTokenPayload {\n const { token, secretKey, now = Date.now() } = opts;\n const [body, signature] = token.split('.');\n\n if (!body || !signature) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (\n !Hash.equals({\n value: signature,\n expected: StaticAssetCommitTokenUtility.sign({ body, secretKey }),\n })\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const payload = StaticAssetCommitTokenUtility.parse({ body });\n\n if (payload.expiresAt <= now) {\n throw getError(StaticAssetErrors.EXPIRED_COMMIT_TOKEN);\n }\n\n return payload;\n }\n}\n"]}
1
+ {"version":3,"file":"commit-token.utility.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/commit-token.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD,yFAAyF;AACzF,MAAM,OAAO,6BAA6B;IAChC,MAAM,CAAC,MAAM,CAAC,OAAuC;QAC3D,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAA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CAAC;CACF","sourcesContent":["import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { StaticAssetTokenStages } from '../common/constants';\nimport { StaticAssetErrors } from '../common/errors';\nimport type { IStaticAssetCommitTokenPayload, IStaticAssetPin } from '../common/types';\n\n/** Signs and reads the token the commit route trusts instead of a key a caller names. */\nexport class StaticAssetCommitTokenUtility {\n private static encode(payload: IStaticAssetCommitTokenPayload): string {\n return Buffer.from(JSON.stringify(payload)).toString('base64url');\n }\n\n // `Hash.hmac` refuses an empty secret: an unkeyed signature is one anyone can compute.\n private static sign(opts: { body: string; secretKey: string }): string {\n return Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({\n message: opts.body,\n secret: opts.secretKey,\n opts: { outputEncoding: HashOutputEncodings.BASE64URL },\n });\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n }\n\n /** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */\n private static parse(opts: { body: string }): IStaticAssetCommitTokenPayload {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(Buffer.from(opts.body, 'base64url').toString('utf8'));\n } catch {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const { bucket, object, expiresAt, owner, stage, pin } = parsed;\n\n if (\n !StaticAssetCommitTokenUtility.isRecord(bucket) ||\n typeof bucket.name !== 'string' ||\n !StaticAssetCommitTokenUtility.isRecord(object) ||\n typeof object.key !== 'string' ||\n typeof expiresAt !== 'number' ||\n (owner !== undefined && typeof owner !== 'string')\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (stage === StaticAssetTokenStages.ISSUED) {\n return {\n bucket: { name: bucket.name },\n object: { key: object.key },\n expiresAt,\n owner,\n stage,\n };\n }\n\n // A validated token without its pin would commit unpinned content: it is no token.\n if (stage !== StaticAssetTokenStages.VALIDATED) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n return {\n bucket: { name: bucket.name },\n object: { key: object.key },\n expiresAt,\n owner,\n stage,\n pin: StaticAssetCommitTokenUtility.parsePin({ pin }),\n };\n }\n\n private static parsePin(opts: { pin: unknown }): IStaticAssetPin {\n const { pin } = opts;\n\n if (\n !StaticAssetCommitTokenUtility.isRecord(pin) ||\n typeof pin.etag !== 'string' ||\n (pin.versionId !== undefined && typeof pin.versionId !== 'string')\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n return { etag: pin.etag, versionId: pin.versionId };\n }\n\n /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */\n static build(opts: { payload: IStaticAssetCommitTokenPayload; secretKey: string }): string {\n const body = StaticAssetCommitTokenUtility.encode(opts.payload);\n\n return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;\n }\n\n /**\n * Reads a commit token back, or throws.\n *\n * Verification happens BEFORE any storage call, which is what makes the commit route refuse to be a\n * name prober: a forged token fails without a round trip, so timing says nothing about what exists.\n */\n static read(opts: {\n token: string;\n secretKey: string;\n now?: number;\n }): IStaticAssetCommitTokenPayload {\n const { token, secretKey, now = Date.now() } = opts;\n const [body, signature] = token.split('.');\n\n if (!body || !signature) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (\n !Hash.equals({\n value: signature,\n expected: StaticAssetCommitTokenUtility.sign({ body, secretKey }),\n })\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const payload = StaticAssetCommitTokenUtility.parse({ body });\n\n if (payload.expiresAt <= now) {\n throw getError(StaticAssetErrors.EXPIRED_COMMIT_TOKEN);\n }\n\n return payload;\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  export * from './commit-token.utility.js';
2
2
  export * from './ingest.utility.js';
3
3
  export * from './object-link.utility.js';
4
+ export * from './pinned-file.utility.js';
4
5
  export * from './toggle.utility.js';
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,6 @@
1
1
  export * from './commit-token.utility.js';
2
2
  export * from './ingest.utility.js';
3
3
  export * from './object-link.utility.js';
4
+ export * from './pinned-file.utility.js';
4
5
  export * from './toggle.utility.js';
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './commit-token.utility';\nexport * from './ingest.utility';\nexport * from './object-link.utility';\nexport * from './toggle.utility';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './commit-token.utility';\nexport * from './ingest.utility';\nexport * from './object-link.utility';\nexport * from './pinned-file.utility';\nexport * from './toggle.utility';\n"]}
@@ -0,0 +1,39 @@
1
+ import { type IFileStat, type IObjectLocation, type IStorageHelper } from '@venizia/ignis-helpers';
2
+ import { type IStaticAssetPin } from '../common/index.js';
3
+ /**
4
+ * The pending file as `validation.handler` sees it. Every read asks the storage for exactly the
5
+ * content that was pinned, so a handler cannot parse bytes that are not the ones `commit` will copy:
6
+ * a read that finds other content or no object throws `UPLOAD_CHANGED`.
7
+ */
8
+ export declare class StaticAssetPinnedFile {
9
+ readonly key: string;
10
+ readonly size: number;
11
+ private readonly helper;
12
+ private readonly location;
13
+ private readonly pin;
14
+ constructor(opts: {
15
+ helper: IStorageHelper;
16
+ location: IObjectLocation;
17
+ pin: IStaticAssetPin;
18
+ size: number;
19
+ });
20
+ /** What a read or a copy requires of the object: the exact version when the pin has one, else the ETag. */
21
+ static conditionOf(opts: {
22
+ pin: IStaticAssetPin;
23
+ }): {
24
+ ifMatch?: string;
25
+ versionId?: string;
26
+ };
27
+ /** The pin of what the storage holds now. An object with no ETag cannot be pinned. */
28
+ static pinOf(opts: {
29
+ stat: IFileStat;
30
+ scope: string;
31
+ }): IStaticAssetPin;
32
+ stream(opts?: {
33
+ range?: {
34
+ start: number;
35
+ end?: number;
36
+ };
37
+ }): Promise<ReadableStream<Uint8Array>>;
38
+ }
39
+ //# sourceMappingURL=pinned-file.utility.d.ts.map
@@ -0,0 +1,53 @@
1
+ import { StorageUtility, } from '@venizia/ignis-helpers';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ import { StaticAssetErrors } from '../common/index.js';
4
+ /**
5
+ * The pending file as `validation.handler` sees it. Every read asks the storage for exactly the
6
+ * content that was pinned, so a handler cannot parse bytes that are not the ones `commit` will copy:
7
+ * a read that finds other content or no object throws `UPLOAD_CHANGED`.
8
+ */
9
+ export class StaticAssetPinnedFile {
10
+ constructor(opts) {
11
+ this.helper = opts.helper;
12
+ this.location = opts.location;
13
+ this.pin = opts.pin;
14
+ this.key = opts.location.object.key;
15
+ this.size = opts.size;
16
+ }
17
+ /** What a read or a copy requires of the object: the exact version when the pin has one, else the ETag. */
18
+ static conditionOf(opts) {
19
+ const { pin } = opts;
20
+ return pin.versionId === undefined ? { ifMatch: pin.etag } : { versionId: pin.versionId };
21
+ }
22
+ /** The pin of what the storage holds now. An object with no ETag cannot be pinned. */
23
+ static pinOf(opts) {
24
+ const { stat, scope } = opts;
25
+ if (!stat.etag) {
26
+ throw getError({
27
+ message: `[${scope}] The storage reported no ETag for the pending object | a pinned validation needs one`,
28
+ });
29
+ }
30
+ return {
31
+ etag: stat.etag,
32
+ versionId: StorageUtility.realVersionId({ value: stat.versionId }),
33
+ };
34
+ }
35
+ async stream(opts) {
36
+ try {
37
+ const stream = await this.helper.getObjectStream({
38
+ ...this.location,
39
+ range: opts?.range,
40
+ ...StaticAssetPinnedFile.conditionOf({ pin: this.pin }),
41
+ });
42
+ return stream;
43
+ }
44
+ catch (error) {
45
+ if (StorageUtility.isPreconditionFailedError({ error }) ||
46
+ StorageUtility.isNotFoundError({ error })) {
47
+ throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });
48
+ }
49
+ throw error;
50
+ }
51
+ }
52
+ }
53
+ //# sourceMappingURL=pinned-file.utility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pinned-file.utility.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/pinned-file.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,GAIf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAwB,MAAM,WAAW,CAAC;AAEpE;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IAQhC,YAAY,IAKX;QACC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC9B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;IACxB,CAAC;IAED,2GAA2G;IAC3G,MAAM,CAAC,WAAW,CAAC,IAA8B;QAC/C,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAErB,OAAO,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,IAAI,EA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';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { StaticAssetErrors, type IStaticAssetPin } from '../common';\n\n/**\n * The pending file as `validation.handler` sees it. Every read asks the storage for exactly the\n * content that was pinned, so a handler cannot parse bytes that are not the ones `commit` will copy:\n * a read that finds other content or no object throws `UPLOAD_CHANGED`.\n */\nexport class StaticAssetPinnedFile {\n readonly key: string;\n readonly size: number;\n\n private readonly helper: IStorageHelper;\n private readonly location: IObjectLocation;\n private readonly pin: IStaticAssetPin;\n\n constructor(opts: {\n helper: IStorageHelper;\n location: IObjectLocation;\n pin: IStaticAssetPin;\n size: number;\n }) {\n this.helper = opts.helper;\n this.location = opts.location;\n this.pin = opts.pin;\n this.key = opts.location.object.key;\n this.size = opts.size;\n }\n\n /** What a read or a copy requires of the object: the exact version when the pin has one, else the ETag. */\n static conditionOf(opts: { pin: IStaticAssetPin }): { ifMatch?: string; versionId?: string } {\n const { pin } = opts;\n\n return pin.versionId === undefined ? { ifMatch: pin.etag } : { versionId: pin.versionId };\n }\n\n /** The pin of what the storage holds now. An object with no ETag cannot be pinned. */\n static pinOf(opts: { stat: IFileStat; scope: string }): IStaticAssetPin {\n const { stat, scope } = opts;\n\n if (!stat.etag) {\n throw getError({\n message: `[${scope}] The storage reported no ETag for the pending object | a pinned validation needs one`,\n });\n }\n\n return {\n etag: stat.etag,\n versionId: StorageUtility.realVersionId({ value: stat.versionId }),\n };\n }\n\n async stream(opts?: {\n range?: { start: number; end?: number };\n }): Promise<ReadableStream<Uint8Array>> {\n try {\n const stream = await this.helper.getObjectStream({\n ...this.location,\n range: opts?.range,\n ...StaticAssetPinnedFile.conditionOf({ pin: this.pin }),\n });\n\n return stream;\n } catch (error) {\n if (\n StorageUtility.isPreconditionFailedError({ error }) ||\n StorageUtility.isNotFoundError({ error })\n ) {\n throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });\n }\n\n throw error;\n }\n }\n}\n"]}
@@ -14,9 +14,9 @@
14
14
  "dependencies": {
15
15
  "@hono/zod-openapi": "^1.6.3",
16
16
  "@scalar/hono-api-reference": "^0.12.13",
17
- "@venizia/ignis": "0.4.8-12",
18
- "@venizia/ignis-boot": "0.4.8-9",
19
- "@venizia/ignis-helpers": "0.4.8-9",
17
+ "@venizia/ignis": "0.4.8-13",
18
+ "@venizia/ignis-boot": "0.4.8-10",
19
+ "@venizia/ignis-helpers": "0.4.8-10",
20
20
  "hono": "^4.13.13",
21
21
  "winston": "^3.19.0",
22
22
  "winston-daily-rotate-file": "^5.0.0",
@@ -5,14 +5,14 @@
5
5
  "devDependencies": {
6
6
  "@types/bun": "^1.4.3",
7
7
  "@venizia/dev-configs": "0.4.8-7",
8
- "@venizia/ignis": "0.4.8-12",
8
+ "@venizia/ignis": "0.4.8-13",
9
9
  "eslint": "^10.13.0",
10
10
  "oxlint": "1.89.0",
11
11
  "oxlint-tsgolint": "7.0.2004",
12
12
  "typescript": "^6.0.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "@venizia/ignis": "0.4.8-12"
15
+ "@venizia/ignis": "0.4.8-13"
16
16
  },
17
17
  "scripts": {
18
18
  "typecheck": "bun check",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis",
3
- "version": "0.4.8-12",
3
+ "version": "0.4.8-13",
4
4
  "description": "TypeScript server framework with decorator-based DI, the repository pattern and a component system, on Hono. Features auto-generated OpenAPI docs, Drizzle ORM type-safe SQL, JWT/Basic authentication, Casbin authorization, convention-based bootstrapping, and pluggable components for health checks, Swagger UI, mail, Socket.IO, and static assets. Built for Bun.",
5
5
  "keywords": [
6
6
  "access-control",
@@ -134,11 +134,11 @@
134
134
  "force-update": "sh ../../scripts/build/force-update.sh"
135
135
  },
136
136
  "dependencies": {
137
- "@venizia/ignis-connectors": "0.4.8-11",
137
+ "@venizia/ignis-connectors": "0.4.8-12",
138
138
  "@venizia/ignis-filter": "0.4.7-4",
139
- "@venizia/ignis-helpers": "0.4.8-9",
139
+ "@venizia/ignis-helpers": "0.4.8-10",
140
140
  "@venizia/ignis-inversion": "0.4.7-3",
141
- "@venizia/ignis-kernel": "0.4.8-11",
141
+ "@venizia/ignis-kernel": "0.4.8-12",
142
142
  "reflect-metadata": "^0.2.2"
143
143
  },
144
144
  "devDependencies": {
@@ -152,7 +152,7 @@
152
152
  "@types/nodemailer": "^8.0.2",
153
153
  "@types/pg": "^8.23.1",
154
154
  "@venizia/dev-configs": "0.4.8-7",
155
- "@venizia/ignis-boot": "0.4.8-9",
155
+ "@venizia/ignis-boot": "0.4.8-10",
156
156
  "casbin": "^5.51.1",
157
157
  "eslint": "^10.13.0",
158
158
  "meilisearch": "^0.62.0",