@venizia/ignis 0.4.8-12 → 0.4.8-14

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 (95) hide show
  1. package/dist/esm/components/mail/common/constants.d.ts +24 -14
  2. package/dist/esm/components/mail/common/constants.js +19 -32
  3. package/dist/esm/components/mail/common/constants.js.map +1 -1
  4. package/dist/esm/components/mail/common/errors.d.ts +10 -1
  5. package/dist/esm/components/mail/common/errors.js +7 -1
  6. package/dist/esm/components/mail/common/errors.js.map +1 -1
  7. package/dist/esm/components/mail/common/types/queue.d.ts +15 -8
  8. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  9. package/dist/esm/components/mail/common/types/template.d.ts +3 -2
  10. package/dist/esm/components/mail/common/types/template.js.map +1 -1
  11. package/dist/esm/components/mail/component.js +11 -2
  12. package/dist/esm/components/mail/component.js.map +1 -1
  13. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +9 -8
  14. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  15. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.d.ts +2 -0
  16. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js +17 -10
  17. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js.map +1 -1
  18. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +4 -4
  19. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
  20. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js +15 -6
  21. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
  22. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js +2 -2
  23. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
  24. package/dist/esm/components/mail/providers/mail-queue-executor.provider.d.ts +2 -2
  25. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js +7 -9
  26. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js.map +1 -1
  27. package/dist/esm/components/mail/providers/mail-transporter.provider.js +7 -7
  28. package/dist/esm/components/mail/providers/mail-transporter.provider.js.map +1 -1
  29. package/dist/esm/components/mail/services/mail.service.js +21 -19
  30. package/dist/esm/components/mail/services/mail.service.js.map +1 -1
  31. package/dist/esm/components/mail/services/template.service.d.ts +4 -1
  32. package/dist/esm/components/mail/services/template.service.js +24 -16
  33. package/dist/esm/components/mail/services/template.service.js.map +1 -1
  34. package/dist/esm/components/mail/utilities/attachment.utility.js +8 -6
  35. package/dist/esm/components/mail/utilities/attachment.utility.js.map +1 -1
  36. package/dist/esm/components/mail/utilities/header.utility.d.ts +14 -0
  37. package/dist/esm/components/mail/utilities/header.utility.js +44 -0
  38. package/dist/esm/components/mail/utilities/header.utility.js.map +1 -0
  39. package/dist/esm/components/mail/utilities/index.d.ts +1 -0
  40. package/dist/esm/components/mail/utilities/index.js +1 -0
  41. package/dist/esm/components/mail/utilities/index.js.map +1 -1
  42. package/dist/esm/components/mail/utilities/mime.utility.d.ts +5 -1
  43. package/dist/esm/components/mail/utilities/mime.utility.js +9 -55
  44. package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
  45. package/dist/esm/components/static-asset/common/constants.d.ts +13 -5
  46. package/dist/esm/components/static-asset/common/constants.js +11 -10
  47. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  48. package/dist/esm/components/static-asset/common/errors.d.ts +36 -9
  49. package/dist/esm/components/static-asset/common/errors.js +36 -9
  50. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  51. package/dist/esm/components/static-asset/common/types.d.ts +66 -23
  52. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  53. package/dist/esm/components/static-asset/component.js +1 -1
  54. package/dist/esm/components/static-asset/component.js.map +1 -1
  55. package/dist/esm/components/static-asset/controller/factory.d.ts +2 -166
  56. package/dist/esm/components/static-asset/controller/factory.js +7 -20
  57. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  58. package/dist/esm/components/static-asset/controller/index.d.ts +1 -0
  59. package/dist/esm/components/static-asset/controller/index.js +1 -0
  60. package/dist/esm/components/static-asset/controller/index.js.map +1 -1
  61. package/dist/esm/components/static-asset/controller/routes/context.d.ts +1 -1
  62. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -1
  63. package/dist/esm/components/static-asset/controller/routes/definition.js +15 -6
  64. package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -1
  65. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +32 -4
  66. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -1
  67. package/dist/esm/components/static-asset/controller/routes/serve.d.ts +14 -2
  68. package/dist/esm/components/static-asset/controller/routes/serve.js +40 -15
  69. package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -1
  70. package/dist/esm/components/static-asset/controller/routes/upload.js +11 -10
  71. package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -1
  72. package/dist/esm/components/static-asset/services/commitment.service.d.ts +48 -18
  73. package/dist/esm/components/static-asset/services/commitment.service.js +155 -44
  74. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
  75. package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
  76. package/dist/esm/components/static-asset/services/policy.service.js +22 -2
  77. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
  78. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +3 -1
  79. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +39 -5
  80. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
  81. package/dist/esm/components/static-asset/utilities/entry.utility.js +9 -2
  82. package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -1
  83. package/dist/esm/components/static-asset/utilities/index.d.ts +1 -0
  84. package/dist/esm/components/static-asset/utilities/index.js +1 -0
  85. package/dist/esm/components/static-asset/utilities/index.js.map +1 -1
  86. package/dist/esm/components/static-asset/utilities/pinned-file.utility.d.ts +39 -0
  87. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js +53 -0
  88. package/dist/esm/components/static-asset/utilities/pinned-file.utility.js.map +1 -0
  89. package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +6 -7
  90. package/dist/esm/components/static-asset/utilities/route-options.utility.js +9 -23
  91. package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
  92. package/dist/presets/app/preset.json +4 -4
  93. package/dist/presets/lib/preset.json +3 -3
  94. package/dist/presets/shared/preset.json +1 -1
  95. package/package.json +6 -6
@@ -1,17 +1,19 @@
1
+ import { StorageUtility, } from '@venizia/ignis-helpers';
2
+ import { ResolverUtility, } from '@venizia/ignis-helpers/common';
1
3
  import { getError } from '@venizia/ignis-helpers/core';
2
4
  import { BaseService } from '@venizia/ignis-kernel';
3
- import { StaticAssetErrors, StaticAssetMetaLinkCodes } from '../common/index.js';
5
+ import { StaticAssetDefaults, StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages, } from '../common/index.js';
4
6
  import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
5
7
  import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
6
8
  import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
9
+ import { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
7
10
  /**
8
11
  * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
9
12
  * callable without a request. A service that saves its own record commits the upload in the same
10
13
  * call instead of asking the client for a second request.
11
14
  *
12
- * The token proves the key was issued by a policy. It names an owner only when
13
- * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who
14
- * holds the token can.
15
+ * The token proves the key was issued by a policy, to one owner, with the metadata the application
16
+ * chose for the file. A commit is single-use: it refuses a destination that already holds an object.
15
17
  */
16
18
  export class StaticAssetUploadCommitService extends BaseService {
17
19
  constructor(opts) {
@@ -25,68 +27,96 @@ export class StaticAssetUploadCommitService extends BaseService {
25
27
  });
26
28
  this.keyPrefix = prefixes.keyPrefix;
27
29
  this.pendingPrefix = prefixes.pendingPrefix;
30
+ this.policyKeyPrefix = prefixes.policyKeyPrefix;
28
31
  }
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) {
32
+ /** The signature, the expiry, the owner, the bucket and the pending scope: the checks every stage of a token starts with. */
33
+ async readPayload(opts) {
39
34
  const payload = StaticAssetCommitTokenUtility.read({
40
35
  token: opts.token,
41
36
  secretKey: this.options.directUpload.secretKey,
42
37
  });
43
- // The same error as a forged token: a caller learns only that the token is no good for them.
44
- if (payload.owner !== undefined && payload.owner !== opts.owner) {
38
+ const bucketName = await ResolverUtility.resolveValueAsync({ value: this.options.bucket });
39
+ // One error for every refusal: a caller learns only that the token is no good for them. A token
40
+ // another entry signed with the same secret must not land here, in its bucket or outside its scope.
41
+ if (payload.owner !== opts.owner ||
42
+ payload.bucket.name !== bucketName ||
43
+ !payload.object.key.startsWith(this.policyKeyPrefix)) {
45
44
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
46
45
  }
47
- // A token another controller signed with the same secret must not land outside this scope.
48
- StaticAssetKeyScopeUtility.assertInScope({
49
- key: payload.object.key.slice(this.pendingPrefix.length),
50
- keyPrefix: this.keyPrefix,
51
- });
52
- return { bucket: payload.bucket, object: payload.object };
46
+ return payload;
47
+ }
48
+ /**
49
+ * Everything `commit` checks before it touches storage, and nothing else: the signature, the
50
+ * expiry, the owner, the bucket and the pending scope. Returns the PENDING object with the token's
51
+ * owner and metadata, with no storage call and no side effect, so an application can read an
52
+ * uploaded file and report its problems to the user 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
+ async verify(opts) {
58
+ const { bucket, object, owner, metadata } = await this.readPayload(opts);
59
+ return { bucket, object, owner, metadata };
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 = await 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, payload });
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, payload } = opts;
91
+ return directUpload.validation.handler({
92
+ file: new StaticAssetPinnedFile({ helper, location, pin, size }),
93
+ owner: payload.owner,
94
+ metadata: payload.metadata,
95
+ });
68
96
  }
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. */
97
+ /**
98
+ * Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
99
+ * row. With a `validation` on it takes the token `validate` returned and never runs the handler; the
100
+ * copy then happens only if the content still matches the pin. The final key is the default one
101
+ * unless `resolvers.commit.destination` names another; either way it must be free, so a token
102
+ * commits once. A MetaLink failure rides the result as a code: the object IS committed by then.
103
+ */
70
104
  async commit(opts) {
71
- const { helper, storage, metaLink, link: buildLink } = this.options;
105
+ const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;
72
106
  // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
73
107
  // 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);
108
+ const payload = await this.readPayload(opts);
109
+ const { bucket: bucketRef, object: pendingObject, owner, metadata, pin } = payload;
110
+ if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {
111
+ throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);
80
112
  }
81
113
  // Labels, not authorization - the token deliberately carries no business fields, so they travel
82
114
  // beside it rather than inside it.
83
115
  const labels = opts.labels ?? {};
84
- const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };
85
- await helper.copyObject({
86
- bucket: bucketRef,
87
- source: pendingObject,
88
- destination: object,
89
- });
116
+ const object = await this.resolveDestination({ payload, destination: opts.destination });
117
+ const link = buildLink({ bucket: bucketRef, object });
118
+ await this.assertDestinationFree({ bucket: bucketRef, object, link });
119
+ await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });
90
120
  // The copy IS the commit; removing the temporary object is cleanup. A failure here
91
121
  // leaves one object for the lifecycle rule, and failing the request would tell the
92
122
  // caller their upload did not work when it did.
@@ -98,13 +128,16 @@ export class StaticAssetUploadCommitService extends BaseService {
98
128
  .for('UPLOAD_COMMIT')
99
129
  .warn('Committed, but the pending object remains | key: %s | error: %s', pendingObject.key, error);
100
130
  }
101
- const link = buildLink({ bucket: bucketRef, object });
102
131
  // The two paths have to agree: without this a client reading `metaLink` off the
103
132
  // response renders an empty state with no error - the failure nobody reports.
104
133
  let metaLinkResult;
105
134
  if (metaLink) {
106
135
  try {
107
- const fileStat = await helper.getStat({ bucket: bucketRef, object });
136
+ const stat = await helper.getStat({ bucket: bucketRef, object });
137
+ const fileStat = {
138
+ ...stat,
139
+ metadata: { ...stat.metadata, [StaticAssetDefaults.META_LINK_METADATA_KEY]: metadata },
140
+ };
108
141
  const data = await StaticAssetMetaLinkUtility.createRow({
109
142
  metaLink,
110
143
  helper,
@@ -133,9 +166,87 @@ export class StaticAssetUploadCommitService extends BaseService {
133
166
  return {
134
167
  bucket: bucketRef,
135
168
  object,
169
+ owner,
170
+ metadata,
136
171
  link,
137
172
  metaLink: metaLinkResult,
138
173
  };
139
174
  }
175
+ /** The default key is the pending one without the pending prefix; the application's resolver may name another, inside the scope. */
176
+ async resolveDestination(opts) {
177
+ const { helper, scope, objectKeyMaxDepth } = this.options;
178
+ const { object } = opts.payload;
179
+ const defaultKey = object.key.slice(this.pendingPrefix.length);
180
+ const resolved = await this.pickDestination({
181
+ ...opts.payload,
182
+ destination: opts.destination,
183
+ defaultKey,
184
+ });
185
+ if (!resolved) {
186
+ return { key: defaultKey };
187
+ }
188
+ if (!StaticAssetKeyScopeUtility.isInScope({ key: resolved.key, keyPrefix: this.keyPrefix })) {
189
+ throw getError({
190
+ error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,
191
+ message: `[${scope}] destination is outside the key prefix of this entry | keyPrefix: ${this.keyPrefix}`,
192
+ });
193
+ }
194
+ if (!helper.isValidObjectKey({ object: resolved, maxDepth: objectKeyMaxDepth })) {
195
+ throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });
196
+ }
197
+ return { key: resolved.key };
198
+ }
199
+ /** The caller's `destination`, else the resolver's, else none: the default key. */
200
+ pickDestination(opts) {
201
+ const { owner, metadata, defaultKey, destination } = opts;
202
+ const resolve = this.options.directUpload.resolvers.commit?.destination;
203
+ if (destination || !resolve) {
204
+ return destination;
205
+ }
206
+ return resolve({
207
+ owner,
208
+ metadata,
209
+ file: { fileName: defaultKey.slice(defaultKey.lastIndexOf('/') + 1) },
210
+ defaultKey,
211
+ });
212
+ }
213
+ /** The token's only commit: a second one, or a re-post to the pending key, must not overwrite what the first one stored. */
214
+ async assertDestinationFree(opts) {
215
+ const { bucket, object, link } = opts;
216
+ try {
217
+ await this.options.helper.getStat({ bucket, object });
218
+ }
219
+ catch (error) {
220
+ if (StorageUtility.isNotFoundError({ error })) {
221
+ return;
222
+ }
223
+ throw error;
224
+ }
225
+ // The caller already holds a valid token for this owner, so naming the committed object leaks nothing, and a client whose first answer was lost can still get its link.
226
+ throw getError({ error: StaticAssetErrors.UPLOAD_ALREADY_COMMITTED, extra: { object, link } });
227
+ }
228
+ /** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
229
+ async copyPinned(opts) {
230
+ const { bucket, source, destination, pin } = opts;
231
+ const condition = pin ? StaticAssetPinnedFile.conditionOf({ pin }) : {};
232
+ try {
233
+ await this.options.helper.copyObject({
234
+ bucket,
235
+ source,
236
+ destination,
237
+ ifMatch: condition.ifMatch,
238
+ sourceVersionId: condition.versionId,
239
+ });
240
+ }
241
+ catch (error) {
242
+ // With a pin the object was there when it was validated: a miss now is a change as much as other content is.
243
+ if (pin &&
244
+ (StorageUtility.isPreconditionFailedError({ error }) ||
245
+ StorageUtility.isNotFoundError({ error }))) {
246
+ throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });
247
+ }
248
+ throw error;
249
+ }
250
+ }
140
251
  }
141
252
  //# sourceMappingURL=commitment.service.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-as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,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAEtD,gFAAgF;QAChF,8EAA8E;QAC9E,IAAI,cAAyC,CAAC;QAE9C,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;gBACrE,MAAM,IAAI,GAAG,MAAM,0BAA0B,CAAC,SAAS,CAAC;oBACtD,QAAQ;oBACR,MAAM;oBACN,OAAO;oBACP,YAAY,EAAE,0BAA0B,CAAC,uBAAuB,CAAC;wBAC/D,MAAM;wBACN,MAAM,EAAE,SAAS;wBACjB,MAAM;wBACN,IAAI;wBACJ,QAAQ;qBACT,CAAC;oBACF,QAAQ;oBACR,MAAM;iBACP,CAAC,CAAC;gBAEH,cAAc,GAAG,EAAE,IAAI,EAAE,CAAC;YAC5B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,gFAAgF;gBAChF,gFAAgF;gBAChF,IAAI,CAAC,MAAM;qBACR,GAAG,CAAC,eAAe,CAAC;qBACpB,KAAK,CAAC,wDAAwD,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBACtF,cAAc,GAAG,EAAE,KAAK,EAAE,wBAAwB,CAAC,aAAa,EAAE,CAAC;YACrE,CAAC;QACH,CAAC;QAED,OAAO;YACL,MAAM,EAAE,SAAS;YACjB,MAAM;YACN,IAAI;YACJ,QAAQ,EAAE,cAAc;SACzB,CAAC;IACJ,CAAC;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;AAChC,OAAO,EACL,eAAe,GAGhB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAa7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAuCzE;;;;;;;GAOG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAMnB,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;YACn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,CAAC;QAED,wKAAwK;QACxK,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,wBAAwB,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IACjG,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 {\n ResolverUtility,\n type TValueOrAsyncResolver,\n type ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport {\n StaticAssetDefaults,\n StaticAssetErrors,\n StaticAssetMetaLinkCodes,\n StaticAssetTokenStages,\n} 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 TStaticAssetTokenMetadata,\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 owner: string;\n metadata: TStaticAssetTokenMetadata;\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 bucket the entry resolves; a token naming another is refused. */\n bucket: TValueOrAsyncResolver<string>;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix: string;\n /** Folders a final key may nest, the scope's own included. */\n objectKeyMaxDepth: number;\n directUpload: Pick<\n TStaticAssetDirectUploadOptions,\n 'secretKey' | 'pendingPrefix' | 'resolvers'\n > & {\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, to one owner, with the metadata the application\n * chose for the file. A commit is single-use: it refuses a destination that already holds an object.\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 private readonly policyKeyPrefix: 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 this.policyKeyPrefix = prefixes.policyKeyPrefix;\n }\n\n /** The signature, the expiry, the owner, the bucket and the pending scope: the checks every stage of a token starts with. */\n private async readPayload(opts: {\n token: string;\n owner: string;\n }): Promise<IStaticAssetCommitTokenPayload> {\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.token,\n secretKey: this.options.directUpload.secretKey,\n });\n const bucketName = await ResolverUtility.resolveValueAsync({ value: this.options.bucket });\n\n // One error for every refusal: a caller learns only that the token is no good for them. A token\n // another entry signed with the same secret must not land here, in its bucket or outside its scope.\n if (\n payload.owner !== opts.owner ||\n payload.bucket.name !== bucketName ||\n !payload.object.key.startsWith(this.policyKeyPrefix)\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\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, the bucket and the pending scope. Returns the PENDING object with the token's\n * owner and metadata, with no storage call and no side effect, so an application can read an\n * uploaded file and report its problems to the user 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 async verify(opts: {\n token: string;\n owner: string;\n }): Promise<IObjectLocation & { owner: string; metadata: TStaticAssetTokenMetadata }> {\n const { bucket, object, owner, metadata } = await this.readPayload(opts);\n\n return { bucket, object, owner, metadata };\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 = await 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, payload });\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 payload: IStaticAssetCommitTokenPayload;\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, payload } = opts;\n\n return directUpload.validation.handler({\n file: new StaticAssetPinnedFile({ helper, location, pin, size }),\n owner: payload.owner,\n metadata: payload.metadata,\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. The final key is the default one\n * unless `resolvers.commit.destination` names another; either way it must be free, so a token\n * commits once. A MetaLink failure rides the result as a code: the object IS committed by then.\n */\n async commit(opts: {\n token: string;\n /** Who is committing: a token commits only for the owner it was issued to. */\n owner: string;\n labels?: TStaticAssetUploadLabels;\n /** The final key for this call. It wins over `resolvers.commit.destination` and passes the same checks. */\n destination?: IObjectRef;\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 = await this.readPayload(opts);\n const { bucket: bucketRef, object: pendingObject, owner, metadata, 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 = await this.resolveDestination({ payload, destination: opts.destination });\n const link = buildLink({ bucket: bucketRef, object });\n\n await this.assertDestinationFree({ bucket: bucketRef, object, link });\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 // 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 stat = await helper.getStat({ bucket: bucketRef, object });\n const fileStat = {\n ...stat,\n metadata: { ...stat.metadata, [StaticAssetDefaults.META_LINK_METADATA_KEY]: metadata },\n };\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 owner,\n metadata,\n link,\n metaLink: metaLinkResult,\n };\n }\n\n /** The default key is the pending one without the pending prefix; the application's resolver may name another, inside the scope. */\n private async resolveDestination(opts: {\n payload: IStaticAssetCommitTokenPayload;\n destination?: IObjectRef;\n }): Promise<IObjectRef> {\n const { helper, scope, objectKeyMaxDepth } = this.options;\n const { object } = opts.payload;\n const defaultKey = object.key.slice(this.pendingPrefix.length);\n const resolved = await this.pickDestination({\n ...opts.payload,\n destination: opts.destination,\n defaultKey,\n });\n\n if (!resolved) {\n return { key: defaultKey };\n }\n\n if (!StaticAssetKeyScopeUtility.isInScope({ key: resolved.key, keyPrefix: this.keyPrefix })) {\n throw getError({\n error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,\n message: `[${scope}] destination is outside the key prefix of this entry | keyPrefix: ${this.keyPrefix}`,\n });\n }\n\n if (!helper.isValidObjectKey({ object: resolved, maxDepth: objectKeyMaxDepth })) {\n throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });\n }\n\n return { key: resolved.key };\n }\n\n /** The caller's `destination`, else the resolver's, else none: the default key. */\n private pickDestination(opts: {\n owner: string;\n metadata: TStaticAssetTokenMetadata;\n defaultKey: string;\n destination?: IObjectRef;\n }): ValueOrPromise<IObjectRef | undefined> {\n const { owner, metadata, defaultKey, destination } = opts;\n const resolve = this.options.directUpload.resolvers.commit?.destination;\n\n if (destination || !resolve) {\n return destination;\n }\n\n return resolve({\n owner,\n metadata,\n file: { fileName: defaultKey.slice(defaultKey.lastIndexOf('/') + 1) },\n defaultKey,\n });\n }\n\n /** The token's only commit: a second one, or a re-post to the pending key, must not overwrite what the first one stored. */\n private async assertDestinationFree(opts: {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n }): Promise<void> {\n const { bucket, object, link } = opts;\n\n try {\n await this.options.helper.getStat({ bucket, object });\n } catch (error) {\n if (StorageUtility.isNotFoundError({ error })) {\n return;\n }\n\n throw error;\n }\n\n // The caller already holds a valid token for this owner, so naming the committed object leaks nothing, and a client whose first answer was lost can still get its link.\n throw getError({ error: StaticAssetErrors.UPLOAD_ALREADY_COMMITTED, extra: { object, link } });\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,4 +1,4 @@
1
- import type { IPostPolicy, IStorageHelper } from '@venizia/ignis-helpers';
1
+ import { type IPostPolicy, type IStorageHelper } from '@venizia/ignis-helpers';
2
2
  import type { TValueOrAsyncResolver } from '@venizia/ignis-helpers/common';
3
3
  import { BaseService } from '@venizia/ignis-kernel';
4
4
  import type { TStaticAssetDirectUploadOptions, TStaticAssetUploadPolicyRequest } from '../common/index.js';
@@ -32,10 +32,14 @@ export declare class StaticAssetUploadPolicyService extends BaseService {
32
32
  constructor(opts: IStaticAssetUploadPolicyServiceOptions);
33
33
  /** `undefined` when `expires.commit` is not set: the token then dies with the policy. */
34
34
  private static resolveCommitLifetimeMs;
35
- /** One signed policy per file. A size over `maxBytes` is refused before any policy is signed. */
35
+ /**
36
+ * One signed policy per file. A size over `maxBytes`, a name that is not one valid key segment and
37
+ * `metadata` over the cap are refused before any policy is signed. `files[].metadata` is what the
38
+ * token signs: the caller has already decided it (the route runs `resolvers.metadata`).
39
+ */
36
40
  issuePolicies(opts: {
37
41
  files: TStaticAssetUploadPolicyRequest['files'];
38
- owner?: string;
42
+ owner: string;
39
43
  }): Promise<TStaticAssetUploadPolicy[]>;
40
44
  }
41
45
  //# sourceMappingURL=policy.service.d.ts.map
@@ -1,7 +1,8 @@
1
+ import { EchoUtility } from '@venizia/ignis-helpers';
1
2
  import { DurationMultipliers, ResolverUtility } from '@venizia/ignis-helpers/common';
2
3
  import { getError, UuidHelper } from '@venizia/ignis-helpers/core';
3
4
  import { BaseService } from '@venizia/ignis-kernel';
4
- import { StaticAssetErrors } from '../common/index.js';
5
+ import { StaticAssetDefaults, StaticAssetErrors, StaticAssetTokenStages } from '../common/index.js';
5
6
  import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
6
7
  import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
7
8
  /**
@@ -40,7 +41,11 @@ export class StaticAssetUploadPolicyService extends BaseService {
40
41
  }
41
42
  return lifetimeMs;
42
43
  }
43
- /** One signed policy per file. A size over `maxBytes` is refused before any policy is signed. */
44
+ /**
45
+ * One signed policy per file. A size over `maxBytes`, a name that is not one valid key segment and
46
+ * `metadata` over the cap are refused before any policy is signed. `files[].metadata` is what the
47
+ * token signs: the caller has already decided it (the route runs `resolvers.metadata`).
48
+ */
44
49
  async issuePolicies(opts) {
45
50
  const { helper, bucket, directUpload } = this.options;
46
51
  const bucketName = await ResolverUtility.resolveValueAsync({ value: bucket });
@@ -52,6 +57,19 @@ export class StaticAssetUploadPolicyService extends BaseService {
52
57
  message: `File '${file.fileName}' is ${file.size} bytes, over the ${directUpload.maxBytes} the policy allows`,
53
58
  });
54
59
  }
60
+ if (!helper.isValidSegment({ segment: file.fileName })) {
61
+ throw getError({
62
+ error: StaticAssetErrors.OBJECT_NAME_INVALID,
63
+ message: `File name is not one valid key segment | fileName: ${EchoUtility.toSafeEcho({ value: file.fileName })}`,
64
+ });
65
+ }
66
+ const metadata = file.metadata ?? {};
67
+ if (Buffer.byteLength(JSON.stringify(metadata)) > StaticAssetDefaults.MAX_TOKEN_METADATA_BYTES) {
68
+ throw getError({
69
+ error: StaticAssetErrors.UPLOAD_METADATA_INVALID,
70
+ message: `Metadata of '${file.fileName}' is over ${StaticAssetDefaults.MAX_TOKEN_METADATA_BYTES} bytes`,
71
+ });
72
+ }
55
73
  // Generated, never taken from the caller: a key the caller picks is a key the caller
56
74
  // can collide with, and the pending object is the one thing a policy authorizes.
57
75
  const objectName = `${this.policyKeyPrefix}${UuidHelper.getInstance().v4()}/${file.fileName}`;
@@ -73,6 +91,8 @@ export class StaticAssetUploadPolicyService extends BaseService {
73
91
  ? new Date(policy.expiresAt).getTime()
74
92
  : Date.now() + this.commitLifetimeMs,
75
93
  owner: opts.owner,
94
+ metadata,
95
+ stage: StaticAssetTokenStages.ISSUED,
76
96
  },
77
97
  secretKey: directUpload.secretKey,
78
98
  }),
@@ -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,c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,EAAE,UAAU,EAAE;wBAC5B,MAAM,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE;wBAC3B,SAAS,EACP,IAAI,CAAC,gBAAgB,KAAK,SAAS;4BACjC,CAAC,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE;4BACtC,CAAC,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":"AAAA,OAAO,EAAE,WAAW,EAAyC,MAAM,wBAAwB,CAAC;AAE5F,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,mBAAmB,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAC3F,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,CA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C;YAC9F,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC;gBACtC,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE;gBAC5B,MAAM,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE;gBAC3B,QAAQ,EAAE,YAAY,CAAC,QAAQ;gBAC/B,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,SAAS,EAAE,YAAY,CAAC,OAAO,EAAE,MAAM;aACxC,CAAC,CAAC;YAEH,QAAQ,CAAC,IAAI,CAAC;gBACZ,GAAG,MAAM;gBACT,UAAU;gBACV,WAAW,EAAE,6BAA6B,CAAC,KAAK,CAAC;oBAC/C,OAAO,EAAE;wBACP,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE;wBAC5B,MAAM,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE;wBAC3B,SAAS,EACP,IAAI,CAAC,gBAAgB,KAAK,SAAS;4BACjC,CAAC,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE;4BACtC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,gBAAgB;wBACxC,KAAK,EAAE,IAAI,CAAC,KAAK;wBACjB,QAAQ;wBACR,KAAK,EAAE,sBAAsB,CAAC,MAAM;qBACrC;oBACD,SAAS,EAAE,YAAY,CAAC,SAAS;iBAClC,CAAC;aACH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { EchoUtility, type IPostPolicy, type 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 { StaticAssetDefaults, 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 /**\n * One signed policy per file. A size over `maxBytes`, a name that is not one valid key segment and\n * `metadata` over the cap are refused before any policy is signed. `files[].metadata` is what the\n * token signs: the caller has already decided it (the route runs `resolvers.metadata`).\n */\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 if (!helper.isValidSegment({ segment: file.fileName })) {\n throw getError({\n error: StaticAssetErrors.OBJECT_NAME_INVALID,\n message: `File name is not one valid key segment | fileName: ${EchoUtility.toSafeEcho({ value: file.fileName })}`,\n });\n }\n\n const metadata = file.metadata ?? {};\n\n if (\n Buffer.byteLength(JSON.stringify(metadata)) > StaticAssetDefaults.MAX_TOKEN_METADATA_BYTES\n ) {\n throw getError({\n error: StaticAssetErrors.UPLOAD_METADATA_INVALID,\n message: `Metadata of '${file.fileName}' is over ${StaticAssetDefaults.MAX_TOKEN_METADATA_BYTES} bytes`,\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 metadata,\n stage: StaticAssetTokenStages.ISSUED,\n },\n secretKey: directUpload.secretKey,\n }),\n });\n }\n\n return policies;\n }\n}\n"]}
@@ -4,9 +4,11 @@ export declare class StaticAssetCommitTokenUtility {
4
4
  private static encode;
5
5
  private static sign;
6
6
  private static isRecord;
7
+ private static isStringRecord;
7
8
  /** 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
9
  private static parse;
9
- /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */
10
+ private static parsePin;
11
+ /** Signs the payload so the commit route can trust the key it is handed. */
10
12
  static build(opts: {
11
13
  payload: IStaticAssetCommitTokenPayload;
12
14
  secretKey: string;
@@ -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 {
@@ -17,6 +18,11 @@ export class StaticAssetCommitTokenUtility {
17
18
  static isRecord(value) {
18
19
  return typeof value === 'object' && value !== null;
19
20
  }
21
+ static isStringRecord(value) {
22
+ return (StaticAssetCommitTokenUtility.isRecord(value) &&
23
+ !Array.isArray(value) &&
24
+ Object.values(value).every((entry) => typeof entry === 'string'));
25
+ }
20
26
  /** 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. */
21
27
  static parse(opts) {
22
28
  let parsed;
@@ -29,13 +35,28 @@ export class StaticAssetCommitTokenUtility {
29
35
  if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {
30
36
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
31
37
  }
32
- const { bucket, object, expiresAt, owner } = parsed;
38
+ const { bucket, object, expiresAt, owner, metadata, stage, pin } = parsed;
33
39
  if (!StaticAssetCommitTokenUtility.isRecord(bucket) ||
34
40
  typeof bucket.name !== 'string' ||
35
41
  !StaticAssetCommitTokenUtility.isRecord(object) ||
36
42
  typeof object.key !== 'string' ||
37
43
  typeof expiresAt !== 'number' ||
38
- (owner !== undefined && typeof owner !== 'string')) {
44
+ typeof owner !== 'string' ||
45
+ !StaticAssetCommitTokenUtility.isStringRecord(metadata)) {
46
+ throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
47
+ }
48
+ if (stage === StaticAssetTokenStages.ISSUED) {
49
+ return {
50
+ bucket: { name: bucket.name },
51
+ object: { key: object.key },
52
+ expiresAt,
53
+ owner,
54
+ metadata,
55
+ stage,
56
+ };
57
+ }
58
+ // A validated token without its pin would commit unpinned content: it is no token.
59
+ if (stage !== StaticAssetTokenStages.VALIDATED) {
39
60
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
40
61
  }
41
62
  return {
@@ -43,9 +64,21 @@ export class StaticAssetCommitTokenUtility {
43
64
  object: { key: object.key },
44
65
  expiresAt,
45
66
  owner,
67
+ metadata,
68
+ stage,
69
+ pin: StaticAssetCommitTokenUtility.parsePin({ pin }),
46
70
  };
47
71
  }
48
- /** Signs `{ bucket, object, expiresAt, owner? }` so the commit route can trust the key it is handed. */
72
+ static parsePin(opts) {
73
+ const { pin } = opts;
74
+ if (!StaticAssetCommitTokenUtility.isRecord(pin) ||
75
+ typeof pin.etag !== 'string' ||
76
+ (pin.versionId !== undefined && typeof pin.versionId !== 'string')) {
77
+ throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
78
+ }
79
+ return { etag: pin.etag, versionId: pin.versionId };
80
+ }
81
+ /** Signs the payload so the commit route can trust the key it is handed. */
49
82
  static build(opts) {
50
83
  const body = StaticAssetCommitTokenUtility.encode(opts.payload);
51
84
  return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;
@@ -58,8 +91,9 @@ export class StaticAssetCommitTokenUtility {
58
91
  */
59
92
  static read(opts) {
60
93
  const { token, secretKey, now = Date.now() } = opts;
61
- const [body, signature] = token.split('.');
62
- if (!body || !signature) {
94
+ const parts = token.split('.');
95
+ const [body, signature] = parts;
96
+ if (parts.length !== 2 || !body || !signature) {
63
97
  throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
64
98
  }
65
99
  if (!Hash.equals({
@@ -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,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpD,OAAO,EAAE,IAAI,CAAC,IAAI;YAClB,MAAM,EAAE,IAAI,CAAC,SAAS;YACtB,IAAI,EAAE,EAAE,cA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orithms, 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;AAOrD,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,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iBAAiB,CAAC,oBAAoB,CAAC,CAAC;QACzD,CAAC;QAED,MAAM,OAAO,GAAG,6BAA6B,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAE9D,IAAI,OAAO,CAAC,SAAS,IAAI,GAAG,EAAE,CAAC;YAC7B,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 { StaticAssetTokenStages } from '../common/constants';\nimport { StaticAssetErrors } from '../common/errors';\nimport type {\n IStaticAssetCommitTokenPayload,\n IStaticAssetPin,\n TStaticAssetTokenMetadata,\n} 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 private static isStringRecord(value: unknown): value is TStaticAssetTokenMetadata {\n return (\n StaticAssetCommitTokenUtility.isRecord(value) &&\n !Array.isArray(value) &&\n Object.values(value).every((entry) => typeof entry === 'string')\n );\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, metadata, 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 typeof owner !== 'string' ||\n !StaticAssetCommitTokenUtility.isStringRecord(metadata)\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 metadata,\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 metadata,\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 the payload 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 parts = token.split('.');\n const [body, signature] = parts;\n\n if (parts.length !== 2 || !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"]}