@venizia/ignis 0.4.8-13 → 0.4.8-15
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.
- package/dist/esm/components/mail/common/constants.d.ts +24 -14
- package/dist/esm/components/mail/common/constants.js +19 -32
- package/dist/esm/components/mail/common/constants.js.map +1 -1
- package/dist/esm/components/mail/common/errors.d.ts +10 -1
- package/dist/esm/components/mail/common/errors.js +7 -1
- package/dist/esm/components/mail/common/errors.js.map +1 -1
- package/dist/esm/components/mail/common/types/queue.d.ts +15 -8
- package/dist/esm/components/mail/common/types/queue.js.map +1 -1
- package/dist/esm/components/mail/common/types/template.d.ts +3 -2
- package/dist/esm/components/mail/common/types/template.js.map +1 -1
- package/dist/esm/components/mail/component.js +11 -2
- package/dist/esm/components/mail/component.js.map +1 -1
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +13 -12
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.d.ts +2 -0
- package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js +17 -10
- package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +4 -4
- package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js +15 -6
- package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js +2 -2
- package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/providers/mail-queue-executor.provider.d.ts +2 -2
- package/dist/esm/components/mail/providers/mail-queue-executor.provider.js +7 -9
- package/dist/esm/components/mail/providers/mail-queue-executor.provider.js.map +1 -1
- package/dist/esm/components/mail/providers/mail-transporter.provider.js +7 -7
- package/dist/esm/components/mail/providers/mail-transporter.provider.js.map +1 -1
- package/dist/esm/components/mail/services/mail.service.js +21 -19
- package/dist/esm/components/mail/services/mail.service.js.map +1 -1
- package/dist/esm/components/mail/services/template.service.d.ts +4 -1
- package/dist/esm/components/mail/services/template.service.js +24 -16
- package/dist/esm/components/mail/services/template.service.js.map +1 -1
- package/dist/esm/components/mail/utilities/attachment.utility.js +8 -6
- package/dist/esm/components/mail/utilities/attachment.utility.js.map +1 -1
- package/dist/esm/components/mail/utilities/header.utility.d.ts +14 -0
- package/dist/esm/components/mail/utilities/header.utility.js +44 -0
- package/dist/esm/components/mail/utilities/header.utility.js.map +1 -0
- package/dist/esm/components/mail/utilities/index.d.ts +1 -0
- package/dist/esm/components/mail/utilities/index.js +1 -0
- package/dist/esm/components/mail/utilities/index.js.map +1 -1
- package/dist/esm/components/mail/utilities/mime.utility.d.ts +5 -1
- package/dist/esm/components/mail/utilities/mime.utility.js +9 -55
- package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
- package/dist/esm/components/static-asset/common/constants.d.ts +5 -4
- package/dist/esm/components/static-asset/common/constants.js +5 -9
- package/dist/esm/components/static-asset/common/constants.js.map +1 -1
- package/dist/esm/components/static-asset/common/errors.d.ts +18 -0
- package/dist/esm/components/static-asset/common/errors.js +18 -0
- package/dist/esm/components/static-asset/common/errors.js.map +1 -1
- package/dist/esm/components/static-asset/common/types.d.ts +47 -18
- package/dist/esm/components/static-asset/common/types.js.map +1 -1
- package/dist/esm/components/static-asset/component.js +1 -1
- package/dist/esm/components/static-asset/component.js.map +1 -1
- package/dist/esm/components/static-asset/controller/factory.d.ts +2 -166
- package/dist/esm/components/static-asset/controller/factory.js +7 -20
- package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
- package/dist/esm/components/static-asset/controller/index.d.ts +1 -0
- package/dist/esm/components/static-asset/controller/index.js +1 -0
- package/dist/esm/components/static-asset/controller/index.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/context.d.ts +1 -1
- package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/definition.js +15 -6
- package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js +24 -2
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/serve.d.ts +14 -2
- package/dist/esm/components/static-asset/controller/routes/serve.js +40 -15
- package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/upload.js +11 -10
- package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -1
- package/dist/esm/components/static-asset/services/commitment.service.d.ts +35 -16
- package/dist/esm/components/static-asset/services/commitment.service.js +92 -30
- package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
- package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
- package/dist/esm/components/static-asset/services/policy.service.js +21 -2
- package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +2 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js +14 -5
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/entry.utility.js +9 -2
- package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +6 -7
- package/dist/esm/components/static-asset/utilities/route-options.utility.js +9 -23
- package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
- package/dist/presets/app/preset.json +4 -4
- package/dist/presets/lib/preset.json +3 -3
- package/dist/presets/shared/preset.json +1 -1
- package/package.json +8 -8
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { StorageUtility, } from '@venizia/ignis-helpers';
|
|
2
|
+
import { ResolverUtility, } from '@venizia/ignis-helpers/common';
|
|
2
3
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
3
4
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
4
|
-
import { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages } from '../common/index.js';
|
|
5
|
+
import { StaticAssetDefaults, StaticAssetErrors, StaticAssetMetaLinkCodes, 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
|
import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
|
|
@@ -11,9 +12,8 @@ import { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
|
|
|
11
12
|
* callable without a request. A service that saves its own record commits the upload in the same
|
|
12
13
|
* call instead of asking the client for a second request.
|
|
13
14
|
*
|
|
14
|
-
* The token proves the key was issued by a policy
|
|
15
|
-
*
|
|
16
|
-
* 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.
|
|
17
17
|
*/
|
|
18
18
|
export class StaticAssetUploadCommitService extends BaseService {
|
|
19
19
|
constructor(opts) {
|
|
@@ -27,36 +27,36 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
27
27
|
});
|
|
28
28
|
this.keyPrefix = prefixes.keyPrefix;
|
|
29
29
|
this.pendingPrefix = prefixes.pendingPrefix;
|
|
30
|
+
this.policyKeyPrefix = prefixes.policyKeyPrefix;
|
|
30
31
|
}
|
|
31
|
-
/** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */
|
|
32
|
-
readPayload(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) {
|
|
33
34
|
const payload = StaticAssetCommitTokenUtility.read({
|
|
34
35
|
token: opts.token,
|
|
35
36
|
secretKey: this.options.directUpload.secretKey,
|
|
36
37
|
});
|
|
37
|
-
|
|
38
|
-
|
|
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)) {
|
|
39
44
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
40
45
|
}
|
|
41
|
-
// A token another controller signed with the same secret must not land outside this scope.
|
|
42
|
-
StaticAssetKeyScopeUtility.assertInScope({
|
|
43
|
-
key: payload.object.key.slice(this.pendingPrefix.length),
|
|
44
|
-
keyPrefix: this.keyPrefix,
|
|
45
|
-
});
|
|
46
46
|
return payload;
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
49
|
* Everything `commit` checks before it touches storage, and nothing else: the signature, the
|
|
50
|
-
* expiry, the owner and the
|
|
51
|
-
* no side effect, so an application can read an
|
|
52
|
-
* before anything is committed.
|
|
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
53
|
*
|
|
54
54
|
* A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
|
|
55
55
|
* than that the token is no good: a caller learns nothing about which keys exist.
|
|
56
56
|
*/
|
|
57
|
-
verify(opts) {
|
|
58
|
-
const
|
|
59
|
-
return { bucket
|
|
57
|
+
async verify(opts) {
|
|
58
|
+
const { bucket, object, owner, metadata } = await this.readPayload(opts);
|
|
59
|
+
return { bucket, object, owner, metadata };
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
62
|
* `verify`, then the application's own check of the pending file, read once through a file pinned
|
|
@@ -66,11 +66,11 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
66
66
|
*/
|
|
67
67
|
async validate(opts) {
|
|
68
68
|
const { helper, directUpload, scope } = this.options;
|
|
69
|
-
const payload = this.readPayload(opts);
|
|
69
|
+
const payload = await this.readPayload(opts);
|
|
70
70
|
const location = { bucket: payload.bucket, object: payload.object };
|
|
71
71
|
const stat = await helper.getStat(location);
|
|
72
72
|
const pin = StaticAssetPinnedFile.pinOf({ stat, scope });
|
|
73
|
-
const result = await this.runValidation({ location, pin, size: stat.size,
|
|
73
|
+
const result = await this.runValidation({ location, pin, size: stat.size, payload });
|
|
74
74
|
if (!result.isValid) {
|
|
75
75
|
return { isValid: false, issues: result.issues };
|
|
76
76
|
}
|
|
@@ -87,31 +87,35 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
87
87
|
if (!directUpload.validation) {
|
|
88
88
|
return { isValid: true, issues: [] };
|
|
89
89
|
}
|
|
90
|
-
const { location, pin, size,
|
|
90
|
+
const { location, pin, size, payload } = opts;
|
|
91
91
|
return directUpload.validation.handler({
|
|
92
92
|
file: new StaticAssetPinnedFile({ helper, location, pin, size }),
|
|
93
|
-
owner,
|
|
93
|
+
owner: payload.owner,
|
|
94
|
+
metadata: payload.metadata,
|
|
94
95
|
});
|
|
95
96
|
}
|
|
96
97
|
/**
|
|
97
98
|
* Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
|
|
98
99
|
* 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.
|
|
100
|
-
*
|
|
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.
|
|
101
103
|
*/
|
|
102
104
|
async commit(opts) {
|
|
103
105
|
const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;
|
|
104
106
|
// Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
|
|
105
107
|
// token fails without a round trip, so timing says nothing.
|
|
106
|
-
const payload = this.readPayload(opts);
|
|
107
|
-
const { bucket: bucketRef, object: pendingObject, pin } = payload;
|
|
108
|
+
const payload = await this.readPayload(opts);
|
|
109
|
+
const { bucket: bucketRef, object: pendingObject, owner, metadata, pin } = payload;
|
|
108
110
|
if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {
|
|
109
111
|
throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);
|
|
110
112
|
}
|
|
111
113
|
// Labels, not authorization - the token deliberately carries no business fields, so they travel
|
|
112
114
|
// beside it rather than inside it.
|
|
113
115
|
const labels = opts.labels ?? {};
|
|
114
|
-
const object = {
|
|
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 });
|
|
115
119
|
await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });
|
|
116
120
|
// The copy IS the commit; removing the temporary object is cleanup. A failure here
|
|
117
121
|
// leaves one object for the lifecycle rule, and failing the request would tell the
|
|
@@ -124,13 +128,16 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
124
128
|
.for('UPLOAD_COMMIT')
|
|
125
129
|
.warn('Committed, but the pending object remains | key: %s | error: %s', pendingObject.key, error);
|
|
126
130
|
}
|
|
127
|
-
const link = buildLink({ bucket: bucketRef, object });
|
|
128
131
|
// The two paths have to agree: without this a client reading `metaLink` off the
|
|
129
132
|
// response renders an empty state with no error - the failure nobody reports.
|
|
130
133
|
let metaLinkResult;
|
|
131
134
|
if (metaLink) {
|
|
132
135
|
try {
|
|
133
|
-
const
|
|
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
|
+
};
|
|
134
141
|
const data = await StaticAssetMetaLinkUtility.createRow({
|
|
135
142
|
metaLink,
|
|
136
143
|
helper,
|
|
@@ -159,10 +166,65 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
159
166
|
return {
|
|
160
167
|
bucket: bucketRef,
|
|
161
168
|
object,
|
|
169
|
+
owner,
|
|
170
|
+
metadata,
|
|
162
171
|
link,
|
|
163
172
|
metaLink: metaLinkResult,
|
|
164
173
|
};
|
|
165
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
|
+
}
|
|
166
228
|
/** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
|
|
167
229
|
async copyPinned(opts) {
|
|
168
230
|
const { bucket, source, destination, pin } = opts;
|
|
@@ -1 +1 @@
|
|
|
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,MA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ACH,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
|
+
{"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;QAE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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
|
|
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
|
-
/**
|
|
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
|
|
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, StaticAssetTokenStages } 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
|
-
/**
|
|
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,7 @@ 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,
|
|
76
95
|
stage: StaticAssetTokenStages.ISSUED,
|
|
77
96
|
},
|
|
78
97
|
secretKey: directUpload.secretKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/policy.service.ts"],"names":[],"mappings":"
|
|
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,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,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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,10 +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
10
|
private static parsePin;
|
|
10
|
-
/** Signs
|
|
11
|
+
/** Signs the payload so the commit route can trust the key it is handed. */
|
|
11
12
|
static build(opts: {
|
|
12
13
|
payload: IStaticAssetCommitTokenPayload;
|
|
13
14
|
secretKey: string;
|
|
@@ -18,6 +18,11 @@ export class StaticAssetCommitTokenUtility {
|
|
|
18
18
|
static isRecord(value) {
|
|
19
19
|
return typeof value === 'object' && value !== null;
|
|
20
20
|
}
|
|
21
|
+
static isStringRecord(value) {
|
|
22
|
+
return (StaticAssetCommitTokenUtility.isRecord(value) &&
|
|
23
|
+
!Array.isArray(value) &&
|
|
24
|
+
Object.values(value).every((entry) => typeof entry === 'string'));
|
|
25
|
+
}
|
|
21
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. */
|
|
22
27
|
static parse(opts) {
|
|
23
28
|
let parsed;
|
|
@@ -30,13 +35,14 @@ export class StaticAssetCommitTokenUtility {
|
|
|
30
35
|
if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {
|
|
31
36
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
32
37
|
}
|
|
33
|
-
const { bucket, object, expiresAt, owner, stage, pin } = parsed;
|
|
38
|
+
const { bucket, object, expiresAt, owner, metadata, stage, pin } = parsed;
|
|
34
39
|
if (!StaticAssetCommitTokenUtility.isRecord(bucket) ||
|
|
35
40
|
typeof bucket.name !== 'string' ||
|
|
36
41
|
!StaticAssetCommitTokenUtility.isRecord(object) ||
|
|
37
42
|
typeof object.key !== 'string' ||
|
|
38
43
|
typeof expiresAt !== 'number' ||
|
|
39
|
-
|
|
44
|
+
typeof owner !== 'string' ||
|
|
45
|
+
!StaticAssetCommitTokenUtility.isStringRecord(metadata)) {
|
|
40
46
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
41
47
|
}
|
|
42
48
|
if (stage === StaticAssetTokenStages.ISSUED) {
|
|
@@ -45,6 +51,7 @@ export class StaticAssetCommitTokenUtility {
|
|
|
45
51
|
object: { key: object.key },
|
|
46
52
|
expiresAt,
|
|
47
53
|
owner,
|
|
54
|
+
metadata,
|
|
48
55
|
stage,
|
|
49
56
|
};
|
|
50
57
|
}
|
|
@@ -57,6 +64,7 @@ export class StaticAssetCommitTokenUtility {
|
|
|
57
64
|
object: { key: object.key },
|
|
58
65
|
expiresAt,
|
|
59
66
|
owner,
|
|
67
|
+
metadata,
|
|
60
68
|
stage,
|
|
61
69
|
pin: StaticAssetCommitTokenUtility.parsePin({ pin }),
|
|
62
70
|
};
|
|
@@ -70,7 +78,7 @@ export class StaticAssetCommitTokenUtility {
|
|
|
70
78
|
}
|
|
71
79
|
return { etag: pin.etag, versionId: pin.versionId };
|
|
72
80
|
}
|
|
73
|
-
/** Signs
|
|
81
|
+
/** Signs the payload so the commit route can trust the key it is handed. */
|
|
74
82
|
static build(opts) {
|
|
75
83
|
const body = StaticAssetCommitTokenUtility.encode(opts.payload);
|
|
76
84
|
return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;
|
|
@@ -83,8 +91,9 @@ export class StaticAssetCommitTokenUtility {
|
|
|
83
91
|
*/
|
|
84
92
|
static read(opts) {
|
|
85
93
|
const { token, secretKey, now = Date.now() } = opts;
|
|
86
|
-
const
|
|
87
|
-
|
|
94
|
+
const parts = token.split('.');
|
|
95
|
+
const [body, signature] = parts;
|
|
96
|
+
if (parts.length !== 2 || !body || !signature) {
|
|
88
97
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
89
98
|
}
|
|
90
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,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;
|
|
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,CAAC,aAAa,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpD,OAAO,EAAE,IAAI,CAAC,IAAI;YA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AE,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"]}
|
|
@@ -47,6 +47,11 @@ export class StaticAssetEntryUtility {
|
|
|
47
47
|
message: `[${name}] directUpload needs keyPrefix | the pending prefix stays out of what the routes serve only when the entry has a scope of its own`,
|
|
48
48
|
});
|
|
49
49
|
}
|
|
50
|
+
if (directUpload && typeof directUpload.resolvers?.owner !== 'function') {
|
|
51
|
+
throw getError({
|
|
52
|
+
message: `[${name}] directUpload needs resolvers.owner | a token is signed for one owner, and the commit refuses any other`,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
50
55
|
if (directUpload && directUpload.authorize === undefined) {
|
|
51
56
|
if (!StaticAssetEntryUtility.isGuarded({ auth })) {
|
|
52
57
|
throw getError({
|
|
@@ -88,8 +93,8 @@ export class StaticAssetEntryUtility {
|
|
|
88
93
|
bucket,
|
|
89
94
|
keyPrefix: scope?.keyPrefix,
|
|
90
95
|
maxFolderDepth,
|
|
91
|
-
// `maxFolderDepth` counts the caller's folders; the scope's own are
|
|
92
|
-
objectKeyMaxDepth: maxFolderDepth + (scope?.depth ?? 0),
|
|
96
|
+
// `maxFolderDepth` counts the caller's folders; the scope's own and the framework's uuid folder are not input.
|
|
97
|
+
objectKeyMaxDepth: maxFolderDepth + (scope?.depth ?? 0) + 1,
|
|
93
98
|
auth: auth && {
|
|
94
99
|
authenticate: auth.authenticate,
|
|
95
100
|
authorize: auth.authorize,
|
|
@@ -141,7 +146,9 @@ export class StaticAssetEntryUtility {
|
|
|
141
146
|
commitService: new StaticAssetUploadCommitService({
|
|
142
147
|
scope: resolved.name,
|
|
143
148
|
helper: resolved.helper,
|
|
149
|
+
bucket: resolved.bucket,
|
|
144
150
|
keyPrefix,
|
|
151
|
+
objectKeyMaxDepth: resolved.objectKeyMaxDepth,
|
|
145
152
|
directUpload,
|
|
146
153
|
storage: resolved.storage,
|
|
147
154
|
metaLink: resolved.metaLink,
|