@venizia/ignis 0.4.8-9 → 0.5.0-0
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/base/applications/base.js +5 -2
- package/dist/esm/base/applications/base.js.map +1 -1
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +1 -1
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
- package/dist/esm/components/api-reference/common/keys.d.ts +2 -1
- package/dist/esm/components/api-reference/common/keys.js +4 -1
- package/dist/esm/components/api-reference/common/keys.js.map +1 -1
- package/dist/esm/components/api-reference/common/types.d.ts +7 -4
- package/dist/esm/components/api-reference/common/types.js.map +1 -1
- package/dist/esm/components/api-reference/component.js +8 -3
- package/dist/esm/components/api-reference/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/component.js +13 -18
- package/dist/esm/components/auth/authenticate/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/controllers/factory.js +1 -1
- package/dist/esm/components/auth/authenticate/controllers/factory.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/jwks/controller.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/jwks/definitions.d.ts +2 -2
- package/dist/esm/components/auth/authenticate/controllers/service-certs/controller.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/service-certs/definitions.d.ts +2 -2
- package/dist/esm/components/auth/authenticate/services/basic/service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/basic/service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +5 -3
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +19 -2
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +2 -2
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +10 -22
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +16 -112
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/service/signer.service.d.ts +11 -0
- package/dist/esm/components/auth/authenticate/services/service/signer.service.js +18 -0
- package/dist/esm/components/auth/authenticate/services/service/signer.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/basic.strategy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jwks/issuer.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jwks/verifier.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jws.strategy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +1 -2
- package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
- package/dist/esm/components/auth/authorize/component.js.map +1 -1
- package/dist/esm/components/controller/grpc/common/types.d.ts +1 -1
- package/dist/esm/components/controller/grpc/common/types.js +4 -1
- package/dist/esm/components/controller/grpc/common/types.js.map +1 -1
- package/dist/esm/components/controller/grpc/grpc.component.js.map +1 -1
- package/dist/esm/components/health-check/common/keys.d.ts +4 -2
- package/dist/esm/components/health-check/common/keys.js +7 -2
- package/dist/esm/components/health-check/common/keys.js.map +1 -1
- package/dist/esm/components/health-check/common/types.d.ts +1 -1
- package/dist/esm/components/health-check/common/types.js.map +1 -1
- package/dist/esm/components/health-check/component.js +1 -3
- package/dist/esm/components/health-check/component.js.map +1 -1
- package/dist/esm/components/mail/common/constants.d.ts +32 -14
- package/dist/esm/components/mail/common/constants.js +25 -32
- package/dist/esm/components/mail/common/constants.js.map +1 -1
- package/dist/esm/components/mail/common/errors.d.ts +19 -1
- package/dist/esm/components/mail/common/errors.js +13 -1
- package/dist/esm/components/mail/common/errors.js.map +1 -1
- package/dist/esm/components/mail/common/keys.d.ts +14 -11
- package/dist/esm/components/mail/common/keys.js +34 -11
- package/dist/esm/components/mail/common/keys.js.map +1 -1
- package/dist/esm/components/mail/common/types/message.d.ts +7 -4
- package/dist/esm/components/mail/common/types/message.js.map +1 -1
- package/dist/esm/components/mail/common/types/options.d.ts +54 -10
- package/dist/esm/components/mail/common/types/options.js.map +1 -1
- package/dist/esm/components/mail/common/types/queue.d.ts +25 -12
- package/dist/esm/components/mail/common/types/queue.js.map +1 -1
- package/dist/esm/components/mail/common/types/template.d.ts +8 -4
- package/dist/esm/components/mail/common/types/template.js.map +1 -1
- package/dist/esm/components/mail/common/types/verification.d.ts +1 -0
- package/dist/esm/components/mail/common/types/verification.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.d.ts +3 -1
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +27 -33
- 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 +11 -6
- 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.d.ts +2 -3
- 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.d.ts +2 -3
- 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/generators/numeric-code.d.ts +1 -6
- package/dist/esm/components/mail/services/generators/numeric-code.js +3 -31
- package/dist/esm/components/mail/services/generators/numeric-code.js.map +1 -1
- package/dist/esm/components/mail/services/generators/random-token.d.ts +4 -1
- package/dist/esm/components/mail/services/generators/random-token.js +9 -6
- package/dist/esm/components/mail/services/generators/random-token.js.map +1 -1
- package/dist/esm/components/mail/services/mail.service.d.ts +1 -2
- package/dist/esm/components/mail/services/mail.service.js +22 -19
- package/dist/esm/components/mail/services/mail.service.js.map +1 -1
- package/dist/esm/components/mail/services/template.service.d.ts +8 -6
- package/dist/esm/components/mail/services/template.service.js +34 -33
- 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 +2 -0
- package/dist/esm/components/mail/utilities/index.js +2 -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 +12 -58
- package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
- package/dist/esm/components/mail/utilities/template-renderer.utility.d.ts +31 -0
- package/dist/esm/components/mail/utilities/template-renderer.utility.js +184 -0
- package/dist/esm/components/mail/utilities/template-renderer.utility.js.map +1 -0
- package/dist/esm/components/mail/utilities/type.utility.d.ts +2 -3
- package/dist/esm/components/mail/utilities/type.utility.js +6 -7
- package/dist/esm/components/mail/utilities/type.utility.js.map +1 -1
- package/dist/esm/components/request-tracker/component.d.ts +2 -1
- package/dist/esm/components/request-tracker/component.js +5 -5
- package/dist/esm/components/request-tracker/component.js.map +1 -1
- package/dist/esm/components/server-info/common/keys.d.ts +2 -1
- package/dist/esm/components/server-info/common/keys.js +4 -1
- package/dist/esm/components/server-info/common/keys.js.map +1 -1
- package/dist/esm/components/server-info/common/types.d.ts +1 -1
- package/dist/esm/components/server-info/common/types.js.map +1 -1
- package/dist/esm/components/server-info/component.js +1 -3
- package/dist/esm/components/server-info/component.js.map +1 -1
- package/dist/esm/components/socket-io/common/keys.d.ts +9 -6
- package/dist/esm/components/socket-io/common/keys.js +19 -6
- package/dist/esm/components/socket-io/common/keys.js.map +1 -1
- package/dist/esm/components/socket-io/component.js +1 -1
- package/dist/esm/components/socket-io/component.js.map +1 -1
- package/dist/esm/components/socket-io/handlers/bun.handler.d.ts +13 -3
- package/dist/esm/components/socket-io/handlers/bun.handler.js.map +1 -1
- package/dist/esm/components/static-asset/common/constants.d.ts +51 -24
- package/dist/esm/components/static-asset/common/constants.js +75 -47
- package/dist/esm/components/static-asset/common/constants.js.map +1 -1
- package/dist/esm/components/static-asset/common/errors.d.ts +30 -35
- package/dist/esm/components/static-asset/common/errors.js +31 -33
- package/dist/esm/components/static-asset/common/errors.js.map +1 -1
- package/dist/esm/components/static-asset/common/index.d.ts +1 -1
- package/dist/esm/components/static-asset/common/index.js +1 -1
- package/dist/esm/components/static-asset/common/index.js.map +1 -1
- package/dist/esm/components/static-asset/common/keys.d.ts +14 -2
- package/dist/esm/components/static-asset/common/keys.js +17 -2
- package/dist/esm/components/static-asset/common/keys.js.map +1 -1
- package/dist/esm/components/static-asset/common/types.d.ts +267 -147
- package/dist/esm/components/static-asset/common/types.js.map +1 -1
- package/dist/esm/components/static-asset/common/validation.d.ts +10 -0
- package/dist/esm/components/static-asset/common/validation.js +8 -0
- package/dist/esm/components/static-asset/common/validation.js.map +1 -0
- package/dist/esm/components/static-asset/component.d.ts +4 -2
- package/dist/esm/components/static-asset/component.js +27 -31
- package/dist/esm/components/static-asset/component.js.map +1 -1
- package/dist/esm/components/static-asset/controller/factory.d.ts +37 -79
- package/dist/esm/components/static-asset/controller/factory.js +26 -917
- 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 +62 -0
- package/dist/esm/components/static-asset/controller/routes/context.js +45 -0
- package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/definition.d.ts +40 -0
- package/dist/esm/components/static-asset/controller/routes/definition.js +83 -0
- package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.d.ts +3 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js +153 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/labels.d.ts +16 -0
- package/dist/esm/components/static-asset/controller/routes/labels.js +19 -0
- package/dist/esm/components/static-asset/controller/routes/labels.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/objects.d.ts +7 -0
- package/dist/esm/components/static-asset/controller/routes/objects.js +193 -0
- package/dist/esm/components/static-asset/controller/routes/objects.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/serve.d.ts +29 -0
- package/dist/esm/components/static-asset/controller/routes/serve.js +152 -0
- package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/table.d.ts +12 -0
- package/dist/esm/components/static-asset/controller/routes/table.js +52 -0
- package/dist/esm/components/static-asset/controller/routes/table.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/upload.d.ts +10 -0
- package/dist/esm/components/static-asset/controller/routes/upload.js +175 -0
- package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -0
- package/dist/esm/components/static-asset/index.d.ts +2 -1
- package/dist/esm/components/static-asset/index.js +2 -1
- package/dist/esm/components/static-asset/index.js.map +1 -1
- package/dist/esm/components/static-asset/models/base.model.d.ts +4 -4
- package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
- package/dist/esm/components/static-asset/services/commitment.service.d.ts +103 -0
- package/dist/esm/components/static-asset/services/commitment.service.js +252 -0
- package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -0
- package/dist/esm/components/static-asset/services/index.d.ts +3 -0
- package/dist/esm/components/static-asset/services/index.js +3 -0
- package/dist/esm/components/static-asset/services/index.js.map +1 -0
- package/dist/esm/components/static-asset/services/policy.service.d.ts +45 -0
- package/dist/esm/components/static-asset/services/policy.service.js +104 -0
- package/dist/esm/components/static-asset/services/policy.service.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +28 -0
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js +112 -0
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/entry.utility.d.ts +69 -0
- package/dist/esm/components/static-asset/utilities/entry.utility.js +160 -0
- package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/index.d.ts +6 -0
- package/dist/esm/components/static-asset/utilities/index.js +6 -0
- package/dist/esm/components/static-asset/utilities/index.js.map +1 -0
- package/dist/esm/components/static-asset/{ingest.d.ts → utilities/ingest.utility.d.ts} +8 -8
- package/dist/esm/components/static-asset/{ingest.js → utilities/ingest.utility.js} +21 -23
- package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -0
- package/dist/esm/components/static-asset/{controller/key-scope.d.ts → utilities/key-scope.utility.d.ts} +21 -2
- package/dist/esm/components/static-asset/utilities/key-scope.utility.js +74 -0
- package/dist/esm/components/static-asset/utilities/key-scope.utility.js.map +1 -0
- package/dist/esm/components/static-asset/{controller/meta-link.d.ts → utilities/meta-link.utility.d.ts} +9 -9
- package/dist/esm/components/static-asset/{controller/meta-link.js → utilities/meta-link.utility.js} +10 -10
- package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/object-link.utility.d.ts +16 -0
- package/dist/esm/components/static-asset/utilities/object-link.utility.js +20 -0
- package/dist/esm/components/static-asset/utilities/object-link.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.d.ts +39 -0
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.js +53 -0
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +43 -0
- package/dist/esm/components/static-asset/utilities/route-options.utility.js +71 -0
- package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +5 -0
- package/dist/esm/components/static-asset/utilities/toggle.utility.js +5 -0
- package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -0
- package/dist/esm/components/websocket/common/keys.d.ts +12 -10
- package/dist/esm/components/websocket/common/keys.js +31 -10
- package/dist/esm/components/websocket/common/keys.js.map +1 -1
- package/dist/esm/components/websocket/component.js.map +1 -1
- package/dist/esm/testing/assert-application-boots.d.ts +2 -2
- package/dist/esm/testing/assert-application-boots.js +6 -2
- package/dist/esm/testing/assert-application-boots.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
- package/dist/esm/components/static-asset/common/commit-token.d.ts +0 -28
- package/dist/esm/components/static-asset/common/commit-token.js +0 -48
- package/dist/esm/components/static-asset/common/commit-token.js.map +0 -1
- package/dist/esm/components/static-asset/controller/base.definition.d.ts +0 -30
- package/dist/esm/components/static-asset/controller/base.definition.js +0 -307
- package/dist/esm/components/static-asset/controller/base.definition.js.map +0 -1
- package/dist/esm/components/static-asset/controller/key-scope.js +0 -41
- package/dist/esm/components/static-asset/controller/key-scope.js.map +0 -1
- package/dist/esm/components/static-asset/controller/meta-link.js.map +0 -1
- package/dist/esm/components/static-asset/controller/route-options.d.ts +0 -29
- package/dist/esm/components/static-asset/controller/route-options.js +0 -47
- package/dist/esm/components/static-asset/controller/route-options.js.map +0 -1
- package/dist/esm/components/static-asset/ingest.js.map +0 -1
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { StorageUtility, } from '@venizia/ignis-helpers';
|
|
2
|
+
import { ResolverUtility, } from '@venizia/ignis-helpers/common';
|
|
3
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
4
|
+
import { BaseService } from '@venizia/ignis-kernel';
|
|
5
|
+
import { StaticAssetDefaults, StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages, } from '../common/index.js';
|
|
6
|
+
import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
|
|
7
|
+
import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
|
|
8
|
+
import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
|
|
9
|
+
import { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
|
|
10
|
+
/**
|
|
11
|
+
* Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
|
|
12
|
+
* callable without a request. A service that saves its own record commits the upload in the same
|
|
13
|
+
* call instead of asking the client for a second request.
|
|
14
|
+
*
|
|
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
|
+
*/
|
|
18
|
+
export class StaticAssetUploadCommitService extends BaseService {
|
|
19
|
+
constructor(opts) {
|
|
20
|
+
super({ scope: opts.scope });
|
|
21
|
+
this.options = opts;
|
|
22
|
+
const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({
|
|
23
|
+
keyPrefix: opts.keyPrefix,
|
|
24
|
+
pendingPrefix: opts.directUpload.pendingPrefix,
|
|
25
|
+
helper: opts.helper,
|
|
26
|
+
scope: opts.scope,
|
|
27
|
+
});
|
|
28
|
+
this.keyPrefix = prefixes.keyPrefix;
|
|
29
|
+
this.pendingPrefix = prefixes.pendingPrefix;
|
|
30
|
+
this.policyKeyPrefix = prefixes.policyKeyPrefix;
|
|
31
|
+
}
|
|
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) {
|
|
34
|
+
const payload = StaticAssetCommitTokenUtility.read({
|
|
35
|
+
token: opts.token,
|
|
36
|
+
secretKey: this.options.directUpload.secretKey,
|
|
37
|
+
});
|
|
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)) {
|
|
44
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
45
|
+
}
|
|
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 };
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
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.
|
|
66
|
+
*/
|
|
67
|
+
async validate(opts) {
|
|
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
|
+
};
|
|
84
|
+
}
|
|
85
|
+
runValidation(opts) {
|
|
86
|
+
const { helper, directUpload } = this.options;
|
|
87
|
+
if (!directUpload.validation) {
|
|
88
|
+
return { isValid: true, issues: [] };
|
|
89
|
+
}
|
|
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
|
+
});
|
|
96
|
+
}
|
|
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
|
+
*/
|
|
104
|
+
async commit(opts) {
|
|
105
|
+
const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;
|
|
106
|
+
// Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
|
|
107
|
+
// token fails without a round trip, so timing says nothing.
|
|
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);
|
|
112
|
+
}
|
|
113
|
+
// Labels, not authorization - the token deliberately carries no business fields, so they travel
|
|
114
|
+
// beside it rather than inside it.
|
|
115
|
+
const labels = opts.labels ?? {};
|
|
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 });
|
|
120
|
+
// The copy IS the commit; removing the temporary object is cleanup. A failure here
|
|
121
|
+
// leaves one object for the lifecycle rule, and failing the request would tell the
|
|
122
|
+
// caller their upload did not work when it did.
|
|
123
|
+
try {
|
|
124
|
+
await helper.removeObject({ bucket: bucketRef, object: pendingObject });
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
this.logger
|
|
128
|
+
.for('UPLOAD_COMMIT')
|
|
129
|
+
.warn('Committed, but the pending object remains | key: %s | error: %s', pendingObject.key, error);
|
|
130
|
+
}
|
|
131
|
+
// The two paths have to agree: without this a client reading `metaLink` off the
|
|
132
|
+
// response renders an empty state with no error - the failure nobody reports.
|
|
133
|
+
let metaLinkResult;
|
|
134
|
+
if (metaLink) {
|
|
135
|
+
try {
|
|
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
|
+
};
|
|
141
|
+
const data = await StaticAssetMetaLinkUtility.createRow({
|
|
142
|
+
metaLink,
|
|
143
|
+
helper,
|
|
144
|
+
storage,
|
|
145
|
+
uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({
|
|
146
|
+
helper,
|
|
147
|
+
bucket: bucketRef,
|
|
148
|
+
object,
|
|
149
|
+
link,
|
|
150
|
+
fileStat,
|
|
151
|
+
}),
|
|
152
|
+
fileStat,
|
|
153
|
+
labels,
|
|
154
|
+
});
|
|
155
|
+
metaLinkResult = { data };
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// The object IS committed by now. A 500 would send the caller back with a token
|
|
159
|
+
// whose source no longer exists, so this rides the body as a code, like UPLOAD.
|
|
160
|
+
this.logger
|
|
161
|
+
.for('UPLOAD_COMMIT')
|
|
162
|
+
.error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);
|
|
163
|
+
metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
bucket: bucketRef,
|
|
168
|
+
object,
|
|
169
|
+
owner,
|
|
170
|
+
metadata,
|
|
171
|
+
link,
|
|
172
|
+
metaLink: metaLinkResult,
|
|
173
|
+
};
|
|
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
|
+
}
|
|
251
|
+
}
|
|
252
|
+
//# sourceMappingURL=commitment.service.js.map
|
|
@@ -0,0 +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;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;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC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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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './commitment.service';\nexport * from './policy.service';\n"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type IPostPolicy, type IStorageHelper } from '@venizia/ignis-helpers';
|
|
2
|
+
import type { TValueOrAsyncResolver } from '@venizia/ignis-helpers/common';
|
|
3
|
+
import { BaseService } from '@venizia/ignis-kernel';
|
|
4
|
+
import type { TStaticAssetDirectUploadOptions, TStaticAssetUploadPolicyRequest } from '../common/index.js';
|
|
5
|
+
/** What the client posts to the storage, plus the key it lands under and the token that commits it. */
|
|
6
|
+
export type TStaticAssetUploadPolicy = IPostPolicy & {
|
|
7
|
+
objectName: string;
|
|
8
|
+
commitToken: string;
|
|
9
|
+
};
|
|
10
|
+
/** What an `StaticAssetUploadPolicyService` needs, all of it one options entry already carries. */
|
|
11
|
+
export interface IStaticAssetUploadPolicyServiceOptions {
|
|
12
|
+
/** Names the logger; the controller's own name is the usual value. */
|
|
13
|
+
scope: string;
|
|
14
|
+
helper: IStorageHelper;
|
|
15
|
+
/** A policy names ONE bucket, so a direct upload has no bucket in its URL. */
|
|
16
|
+
bucket: TValueOrAsyncResolver<string>;
|
|
17
|
+
/** 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. */
|
|
18
|
+
keyPrefix: string;
|
|
19
|
+
directUpload: Pick<TStaticAssetDirectUploadOptions, 'maxBytes' | 'expires' | 'secretKey' | 'pendingPrefix'>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Signs the permission for a browser to post bytes straight to storage: the body of the
|
|
23
|
+
* `upload-policy` route, callable without a request.
|
|
24
|
+
*
|
|
25
|
+
* Authorization is NOT here. A policy is a write credential, and who may ask for one is the route's
|
|
26
|
+
* `directUpload.authorize`; code that calls this service has decided that for itself.
|
|
27
|
+
*/
|
|
28
|
+
export declare class StaticAssetUploadPolicyService extends BaseService {
|
|
29
|
+
private readonly options;
|
|
30
|
+
private readonly policyKeyPrefix;
|
|
31
|
+
private readonly commitLifetimeMs?;
|
|
32
|
+
constructor(opts: IStaticAssetUploadPolicyServiceOptions);
|
|
33
|
+
/** `undefined` when `expires.commit` is not set: the token then dies with the policy. */
|
|
34
|
+
private static resolveCommitLifetimeMs;
|
|
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
|
+
*/
|
|
40
|
+
issuePolicies(opts: {
|
|
41
|
+
files: TStaticAssetUploadPolicyRequest['files'];
|
|
42
|
+
owner: string;
|
|
43
|
+
}): Promise<TStaticAssetUploadPolicy[]>;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=policy.service.d.ts.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { EchoUtility } from '@venizia/ignis-helpers';
|
|
2
|
+
import { DurationMultipliers, ResolverUtility } from '@venizia/ignis-helpers/common';
|
|
3
|
+
import { getError, UuidHelper } from '@venizia/ignis-helpers/core';
|
|
4
|
+
import { BaseService } from '@venizia/ignis-kernel';
|
|
5
|
+
import { StaticAssetDefaults, StaticAssetErrors, StaticAssetTokenStages } from '../common/index.js';
|
|
6
|
+
import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
|
|
7
|
+
import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
|
|
8
|
+
/**
|
|
9
|
+
* Signs the permission for a browser to post bytes straight to storage: the body of the
|
|
10
|
+
* `upload-policy` route, callable without a request.
|
|
11
|
+
*
|
|
12
|
+
* Authorization is NOT here. A policy is a write credential, and who may ask for one is the route's
|
|
13
|
+
* `directUpload.authorize`; code that calls this service has decided that for itself.
|
|
14
|
+
*/
|
|
15
|
+
export class StaticAssetUploadPolicyService extends BaseService {
|
|
16
|
+
constructor(opts) {
|
|
17
|
+
super({ scope: opts.scope });
|
|
18
|
+
this.options = opts;
|
|
19
|
+
this.commitLifetimeMs = StaticAssetUploadPolicyService.resolveCommitLifetimeMs({
|
|
20
|
+
scope: opts.scope,
|
|
21
|
+
commit: opts.directUpload.expires?.commit,
|
|
22
|
+
});
|
|
23
|
+
this.policyKeyPrefix = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({
|
|
24
|
+
keyPrefix: opts.keyPrefix,
|
|
25
|
+
pendingPrefix: opts.directUpload.pendingPrefix,
|
|
26
|
+
helper: opts.helper,
|
|
27
|
+
scope: opts.scope,
|
|
28
|
+
}).policyKeyPrefix;
|
|
29
|
+
}
|
|
30
|
+
/** `undefined` when `expires.commit` is not set: the token then dies with the policy. */
|
|
31
|
+
static resolveCommitLifetimeMs(opts) {
|
|
32
|
+
const { scope, commit } = opts;
|
|
33
|
+
if (commit === undefined) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
const lifetimeMs = DurationMultipliers.toMilliseconds(commit);
|
|
37
|
+
if (lifetimeMs === null || lifetimeMs <= 0) {
|
|
38
|
+
throw getError({
|
|
39
|
+
message: `[${scope}] directUpload.expires.commit is not a usable duration | unit: ${commit.unit} | value: ${commit.value}`,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return lifetimeMs;
|
|
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
|
+
*/
|
|
49
|
+
async issuePolicies(opts) {
|
|
50
|
+
const { helper, bucket, directUpload } = this.options;
|
|
51
|
+
const bucketName = await ResolverUtility.resolveValueAsync({ value: bucket });
|
|
52
|
+
const policies = [];
|
|
53
|
+
for (const file of opts.files) {
|
|
54
|
+
if (file.size !== undefined && file.size > directUpload.maxBytes) {
|
|
55
|
+
throw getError({
|
|
56
|
+
error: StaticAssetErrors.UPLOAD_TOO_LARGE,
|
|
57
|
+
message: `File '${file.fileName}' is ${file.size} bytes, over the ${directUpload.maxBytes} the policy allows`,
|
|
58
|
+
});
|
|
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
|
+
}
|
|
73
|
+
// Generated, never taken from the caller: a key the caller picks is a key the caller
|
|
74
|
+
// can collide with, and the pending object is the one thing a policy authorizes.
|
|
75
|
+
const objectName = `${this.policyKeyPrefix}${UuidHelper.getInstance().v4()}/${file.fileName}`;
|
|
76
|
+
const policy = await helper.presignPost({
|
|
77
|
+
bucket: { name: bucketName },
|
|
78
|
+
object: { key: objectName },
|
|
79
|
+
maxBytes: directUpload.maxBytes,
|
|
80
|
+
contentType: file.contentType,
|
|
81
|
+
expiresIn: directUpload.expires?.upload,
|
|
82
|
+
});
|
|
83
|
+
policies.push({
|
|
84
|
+
...policy,
|
|
85
|
+
objectName,
|
|
86
|
+
commitToken: StaticAssetCommitTokenUtility.build({
|
|
87
|
+
payload: {
|
|
88
|
+
bucket: { name: bucketName },
|
|
89
|
+
object: { key: objectName },
|
|
90
|
+
expiresAt: this.commitLifetimeMs === undefined
|
|
91
|
+
? new Date(policy.expiresAt).getTime()
|
|
92
|
+
: Date.now() + this.commitLifetimeMs,
|
|
93
|
+
owner: opts.owner,
|
|
94
|
+
metadata,
|
|
95
|
+
stage: StaticAssetTokenStages.ISSUED,
|
|
96
|
+
},
|
|
97
|
+
secretKey: directUpload.secretKey,
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return policies;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=policy.service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,CAAC;QACH,IAAI,CAAC,eAAe,GAAG,0BAA0B,CAAC,2BAA2B,CAAC;YAC5E,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,aAAa;YAC9C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC,eAAe,CAAC;IACrB,CAAC;IAED,yFAAyF;IACjF,MAAM,CAAC,uBAAuB,CAAC,IAGtC;QACC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CA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AAC,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"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { IStaticAssetCommitTokenPayload } from '../common/types.js';
|
|
2
|
+
/** Signs and reads the token the commit route trusts instead of a key a caller names. */
|
|
3
|
+
export declare class StaticAssetCommitTokenUtility {
|
|
4
|
+
private static encode;
|
|
5
|
+
private static sign;
|
|
6
|
+
private static isRecord;
|
|
7
|
+
private static isStringRecord;
|
|
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. */
|
|
9
|
+
private static parse;
|
|
10
|
+
private static parsePin;
|
|
11
|
+
/** Signs the payload so the commit route can trust the key it is handed. */
|
|
12
|
+
static build(opts: {
|
|
13
|
+
payload: IStaticAssetCommitTokenPayload;
|
|
14
|
+
secretKey: string;
|
|
15
|
+
}): string;
|
|
16
|
+
/**
|
|
17
|
+
* Reads a commit token back, or throws.
|
|
18
|
+
*
|
|
19
|
+
* Verification happens BEFORE any storage call, which is what makes the commit route refuse to be a
|
|
20
|
+
* name prober: a forged token fails without a round trip, so timing says nothing about what exists.
|
|
21
|
+
*/
|
|
22
|
+
static read(opts: {
|
|
23
|
+
token: string;
|
|
24
|
+
secretKey: string;
|
|
25
|
+
now?: number;
|
|
26
|
+
}): IStaticAssetCommitTokenPayload;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=commit-token.utility.d.ts.map
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';
|
|
2
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
3
|
+
import { StaticAssetTokenStages } from '../common/constants.js';
|
|
4
|
+
import { StaticAssetErrors } from '../common/errors.js';
|
|
5
|
+
/** Signs and reads the token the commit route trusts instead of a key a caller names. */
|
|
6
|
+
export class StaticAssetCommitTokenUtility {
|
|
7
|
+
static encode(payload) {
|
|
8
|
+
return Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
9
|
+
}
|
|
10
|
+
// `Hash.hmac` refuses an empty secret: an unkeyed signature is one anyone can compute.
|
|
11
|
+
static sign(opts) {
|
|
12
|
+
return Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({
|
|
13
|
+
message: opts.body,
|
|
14
|
+
secret: opts.secretKey,
|
|
15
|
+
opts: { outputEncoding: HashOutputEncodings.BASE64URL },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
static isRecord(value) {
|
|
19
|
+
return typeof value === 'object' && value !== null;
|
|
20
|
+
}
|
|
21
|
+
static isStringRecord(value) {
|
|
22
|
+
return (StaticAssetCommitTokenUtility.isRecord(value) &&
|
|
23
|
+
!Array.isArray(value) &&
|
|
24
|
+
Object.values(value).every((entry) => typeof entry === 'string'));
|
|
25
|
+
}
|
|
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. */
|
|
27
|
+
static parse(opts) {
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(Buffer.from(opts.body, 'base64url').toString('utf8'));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
34
|
+
}
|
|
35
|
+
if (!StaticAssetCommitTokenUtility.isRecord(parsed)) {
|
|
36
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
37
|
+
}
|
|
38
|
+
const { bucket, object, expiresAt, owner, metadata, stage, pin } = parsed;
|
|
39
|
+
if (!StaticAssetCommitTokenUtility.isRecord(bucket) ||
|
|
40
|
+
typeof bucket.name !== 'string' ||
|
|
41
|
+
!StaticAssetCommitTokenUtility.isRecord(object) ||
|
|
42
|
+
typeof object.key !== 'string' ||
|
|
43
|
+
typeof expiresAt !== 'number' ||
|
|
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) {
|
|
60
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
bucket: { name: bucket.name },
|
|
64
|
+
object: { key: object.key },
|
|
65
|
+
expiresAt,
|
|
66
|
+
owner,
|
|
67
|
+
metadata,
|
|
68
|
+
stage,
|
|
69
|
+
pin: StaticAssetCommitTokenUtility.parsePin({ pin }),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
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. */
|
|
82
|
+
static build(opts) {
|
|
83
|
+
const body = StaticAssetCommitTokenUtility.encode(opts.payload);
|
|
84
|
+
return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Reads a commit token back, or throws.
|
|
88
|
+
*
|
|
89
|
+
* Verification happens BEFORE any storage call, which is what makes the commit route refuse to be a
|
|
90
|
+
* name prober: a forged token fails without a round trip, so timing says nothing about what exists.
|
|
91
|
+
*/
|
|
92
|
+
static read(opts) {
|
|
93
|
+
const { token, secretKey, now = Date.now() } = opts;
|
|
94
|
+
const parts = token.split('.');
|
|
95
|
+
const [body, signature] = parts;
|
|
96
|
+
if (parts.length !== 2 || !body || !signature) {
|
|
97
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
98
|
+
}
|
|
99
|
+
if (!Hash.equals({
|
|
100
|
+
value: signature,
|
|
101
|
+
expected: StaticAssetCommitTokenUtility.sign({ body, secretKey }),
|
|
102
|
+
})) {
|
|
103
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
104
|
+
}
|
|
105
|
+
const payload = StaticAssetCommitTokenUtility.parse({ body });
|
|
106
|
+
if (payload.expiresAt <= now) {
|
|
107
|
+
throw getError(StaticAssetErrors.EXPIRED_COMMIT_TOKEN);
|
|
108
|
+
}
|
|
109
|
+
return payload;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=commit-token.utility.js.map
|