@harrylabsj/kiwi 0.9.0 → 0.11.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/README.md +1 -1
- package/contracts/card-publication/0.1.2/request.schema.json +78 -0
- package/contracts/kiwi-contracts.lock.json +2 -2
- package/contracts/manifest.json +127 -1
- package/contracts/merchant-management/1.0/README.md +109 -0
- package/contracts/merchant-management/1.0/approval-decision.schema.json +16 -0
- package/contracts/merchant-management/1.0/approval-preview.schema.json +26 -0
- package/contracts/merchant-management/1.0/connector-delivery-manifest.schema.json +78 -0
- package/contracts/merchant-management/1.0/management-error.schema.json +30 -0
- package/contracts/merchant-management/1.0/operation-receipt.schema.json +28 -0
- package/contracts/merchant-management/1.0/runtime-management-descriptor.schema.json +33 -0
- package/contracts/merchant-management/1.0/runtime-status.schema.json +42 -0
- package/contracts/merchant-rfq/0.1.0/delivery-record.schema.json +206 -0
- package/contracts/merchant-rfq/0.1.0/fact-snapshot.schema.json +118 -0
- package/contracts/merchant-rfq/0.1.0/handoff-record.schema.json +251 -0
- package/contracts/merchant-rfq/0.1.0/pricing-input.schema.json +139 -0
- package/contracts/merchant-rfq/0.1.0/quote-revision.schema.json +153 -0
- package/contracts/merchant-rfq/0.1.0/release-request.schema.json +121 -0
- package/contracts/merchant-rfq/0.1.0/rfq-case.schema.json +357 -0
- package/contracts/merchant-rfq/0.1.0/source-record.schema.json +162 -0
- package/contracts/merchant-workbench/1.0/README.md +6 -0
- package/contracts/merchant-workbench/1.0/money.schema.json +19 -0
- package/contracts/merchant-workbench/1.0/problem.schema.json +73 -0
- package/contracts/runtime-binding/0.1.2/binding-request.schema.json +73 -0
- package/contracts/runtime-binding/0.1.2/claims.schema.json +100 -0
- package/contracts/runtime-binding/0.1.2/document.schema.json +161 -0
- package/contracts/vectors/binding-thumbprint.json +15 -0
- package/dist/a2a/node.d.ts +96 -2
- package/dist/a2a/node.js +164 -91
- package/dist/a2a/node.js.map +1 -1
- package/dist/a2a/server/errors.d.ts +8 -0
- package/dist/a2a/server/errors.js +8 -0
- package/dist/a2a/server/errors.js.map +1 -1
- package/dist/a2a/server/merchant-handler.d.ts +13 -0
- package/dist/a2a/server/merchant-handler.js +267 -34
- package/dist/a2a/server/merchant-handler.js.map +1 -1
- package/dist/a2a/server/pipeline.d.ts +15 -10
- package/dist/a2a/server/pipeline.js +48 -18
- package/dist/a2a/server/pipeline.js.map +1 -1
- package/dist/a2a/server/server.d.ts +20 -1
- package/dist/a2a/server/server.js +87 -13
- package/dist/a2a/server/server.js.map +1 -1
- package/dist/a2a/server/task-registry.d.ts +31 -11
- package/dist/a2a/server/task-registry.js +65 -20
- package/dist/a2a/server/task-registry.js.map +1 -1
- package/dist/a2a/server/types.d.ts +23 -0
- package/dist/a2a/signing-key.d.ts +6 -0
- package/dist/a2a/signing-key.js +12 -0
- package/dist/a2a/signing-key.js.map +1 -1
- package/dist/agent/buyer/buyer-tools.js +1 -1
- package/dist/agent/buyer/buyer-tools.js.map +1 -1
- package/dist/agent/host/web-renderer.d.ts +5 -0
- package/dist/agent/host/web-renderer.js +25 -6
- package/dist/agent/host/web-renderer.js.map +1 -1
- package/dist/agent/kernel.js +6 -6
- package/dist/agent/kernel.js.map +1 -1
- package/dist/agent/memory/schema.d.ts +1 -1
- package/dist/agent/memory/schema.js +190 -1
- package/dist/agent/memory/schema.js.map +1 -1
- package/dist/agent/memory/store.js +3 -1
- package/dist/agent/memory/store.js.map +1 -1
- package/dist/agent/merchant/action-candidate.d.ts +1 -0
- package/dist/agent/merchant/action-candidate.js +42 -24
- package/dist/agent/merchant/action-candidate.js.map +1 -1
- package/dist/agent/merchant/fake-merchant-client.d.ts +30 -1
- package/dist/agent/merchant/fake-merchant-client.js +151 -2
- package/dist/agent/merchant/fake-merchant-client.js.map +1 -1
- package/dist/agent/merchant/intelligence/default-backend.js +2 -2
- package/dist/agent/merchant/intelligence/default-backend.js.map +1 -1
- package/dist/agent/merchant/merchant-client.d.ts +38 -5
- package/dist/agent/merchant/merchant-client.js +103 -8
- package/dist/agent/merchant/merchant-client.js.map +1 -1
- package/dist/agent/merchant/types.d.ts +107 -0
- package/dist/agent/merchant/types.js +69 -0
- package/dist/agent/merchant/types.js.map +1 -1
- package/dist/alerts/external-delivery.d.ts +78 -0
- package/dist/alerts/external-delivery.js +256 -0
- package/dist/alerts/external-delivery.js.map +1 -0
- package/dist/auth/app-oauth-callback.d.ts +38 -0
- package/dist/auth/app-oauth-callback.js +119 -0
- package/dist/auth/app-oauth-callback.js.map +1 -0
- package/dist/auth/merchant-oauth.js +15 -41
- package/dist/auth/merchant-oauth.js.map +1 -1
- package/dist/auth/merchant-pairing.d.ts +51 -0
- package/dist/auth/merchant-pairing.js +66 -16
- package/dist/auth/merchant-pairing.js.map +1 -1
- package/dist/auth/merchant-sessions.d.ts +7 -1
- package/dist/auth/merchant-sessions.js +25 -3
- package/dist/auth/merchant-sessions.js.map +1 -1
- package/dist/buyer-core/build-service.d.ts +3 -1
- package/dist/buyer-core/build-service.js +4 -1
- package/dist/buyer-core/build-service.js.map +1 -1
- package/dist/buyer-core/merchant-index.d.ts +20 -0
- package/dist/buyer-core/merchant-index.js +83 -12
- package/dist/buyer-core/merchant-index.js.map +1 -1
- package/dist/buyer-core/network-search.d.ts +92 -0
- package/dist/buyer-core/network-search.js +144 -0
- package/dist/buyer-core/network-search.js.map +1 -0
- package/dist/buyer-core/product-summary.d.ts +71 -0
- package/dist/buyer-core/product-summary.js +63 -0
- package/dist/buyer-core/product-summary.js.map +1 -0
- package/dist/buyer-core/service.d.ts +26 -0
- package/dist/buyer-core/service.js +38 -8
- package/dist/buyer-core/service.js.map +1 -1
- package/dist/cli.js +22 -243
- package/dist/cli.js.map +1 -1
- package/dist/cloud/binding/audit.d.ts +72 -0
- package/dist/cloud/binding/audit.js +137 -0
- package/dist/cloud/binding/audit.js.map +1 -0
- package/dist/cloud/binding/issuance.d.ts +76 -0
- package/dist/cloud/binding/issuance.js +121 -0
- package/dist/cloud/binding/issuance.js.map +1 -0
- package/dist/cloud/binding/proofs.d.ts +110 -0
- package/dist/cloud/binding/proofs.js +200 -0
- package/dist/cloud/binding/proofs.js.map +1 -0
- package/dist/cloud/binding/runtime-challenge.d.ts +48 -0
- package/dist/cloud/binding/runtime-challenge.js +178 -0
- package/dist/cloud/binding/runtime-challenge.js.map +1 -0
- package/dist/cloud/bootstrap.d.ts +63 -0
- package/dist/cloud/bootstrap.js +937 -0
- package/dist/cloud/bootstrap.js.map +1 -0
- package/dist/cloud/config.d.ts +91 -0
- package/dist/cloud/config.js +229 -0
- package/dist/cloud/config.js.map +1 -0
- package/dist/cloud/http-router.d.ts +61 -0
- package/dist/cloud/http-router.js +127 -0
- package/dist/cloud/http-router.js.map +1 -0
- package/dist/cloud/main.d.ts +16 -0
- package/dist/cloud/main.js +64 -0
- package/dist/cloud/main.js.map +1 -0
- package/dist/cloud/onboarding/local-fallback.d.ts +86 -0
- package/dist/cloud/onboarding/local-fallback.js +98 -0
- package/dist/cloud/onboarding/local-fallback.js.map +1 -0
- package/dist/cloud/onboarding/steps.d.ts +95 -0
- package/dist/cloud/onboarding/steps.js +175 -0
- package/dist/cloud/onboarding/steps.js.map +1 -0
- package/dist/cloud/onboarding/store.d.ts +136 -0
- package/dist/cloud/onboarding/store.js +472 -0
- package/dist/cloud/onboarding/store.js.map +1 -0
- package/dist/cloud/onboarding/types.d.ts +132 -0
- package/dist/cloud/onboarding/types.js +152 -0
- package/dist/cloud/onboarding/types.js.map +1 -0
- package/dist/cloud/product-source.d.ts +97 -0
- package/dist/cloud/product-source.js +226 -0
- package/dist/cloud/product-source.js.map +1 -0
- package/dist/cloud/readiness.d.ts +49 -0
- package/dist/cloud/readiness.js +54 -0
- package/dist/cloud/readiness.js.map +1 -0
- package/dist/commerce/data-source.d.ts +5 -0
- package/dist/commerce/data-source.js.map +1 -1
- package/dist/config/provider-kind.d.ts +26 -0
- package/dist/config/provider-kind.js +19 -0
- package/dist/config/provider-kind.js.map +1 -0
- package/dist/contracts/cloud-contracts.d.ts +23 -0
- package/dist/contracts/cloud-contracts.js +90 -0
- package/dist/contracts/cloud-contracts.js.map +1 -0
- package/dist/counterparty/a2a-direct/index.d.ts +3 -0
- package/dist/counterparty/a2a-direct/index.js +22 -6
- package/dist/counterparty/a2a-direct/index.js.map +1 -1
- package/dist/counterparty/registry.d.ts +2 -0
- package/dist/counterparty/registry.js +2 -0
- package/dist/counterparty/registry.js.map +1 -1
- package/dist/counterparty/shopping-cli-hosted/index.d.ts +3 -0
- package/dist/counterparty/shopping-cli-hosted/index.js +9 -2
- package/dist/counterparty/shopping-cli-hosted/index.js.map +1 -1
- package/dist/discovery/catalog-source/buyer-follows.js +2 -2
- package/dist/discovery/catalog-source/buyer-follows.js.map +1 -1
- package/dist/discovery/catalog-source/cloud-card.d.ts +184 -0
- package/dist/discovery/catalog-source/cloud-card.js +379 -0
- package/dist/discovery/catalog-source/cloud-card.js.map +1 -0
- package/dist/discovery/catalog-source/cloud-hosting.d.ts +71 -0
- package/dist/discovery/catalog-source/cloud-hosting.js +70 -0
- package/dist/discovery/catalog-source/cloud-hosting.js.map +1 -0
- package/dist/discovery/catalog-source/errors.d.ts +12 -2
- package/dist/discovery/catalog-source/errors.js +14 -1
- package/dist/discovery/catalog-source/errors.js.map +1 -1
- package/dist/discovery/catalog-source/index.d.ts +2 -0
- package/dist/discovery/catalog-source/index.js +2 -0
- package/dist/discovery/catalog-source/index.js.map +1 -1
- package/dist/discovery/catalog-source/kiwi-source.js +2 -2
- package/dist/discovery/catalog-source/kiwi-source.js.map +1 -1
- package/dist/discovery/catalog-source/merchant-publications.d.ts +2 -2
- package/dist/discovery/catalog-source/merchant-publications.js +10 -5
- package/dist/discovery/catalog-source/merchant-publications.js.map +1 -1
- package/dist/discovery/catalog-source/source.js +2 -2
- package/dist/discovery/catalog-source/source.js.map +1 -1
- package/dist/discovery/merchant-subscriptions.d.ts +45 -0
- package/dist/discovery/merchant-subscriptions.js +319 -0
- package/dist/discovery/merchant-subscriptions.js.map +1 -0
- package/dist/discovery/resolve.d.ts +38 -0
- package/dist/discovery/resolve.js +100 -7
- package/dist/discovery/resolve.js.map +1 -1
- package/dist/fanout/orchestrator.d.ts +2 -0
- package/dist/fanout/orchestrator.js +4 -1
- package/dist/fanout/orchestrator.js.map +1 -1
- package/dist/handoff/ledger.d.ts +1 -0
- package/dist/handoff/ledger.js +3 -0
- package/dist/handoff/ledger.js.map +1 -1
- package/dist/handoff/transaction.js +1 -1
- package/dist/handoff/transaction.js.map +1 -1
- package/dist/http/merchant-engagement-api.d.ts +10 -0
- package/dist/http/merchant-engagement-api.js +138 -0
- package/dist/http/merchant-engagement-api.js.map +1 -0
- package/dist/http/merchant-feed-api.d.ts +7 -0
- package/dist/http/merchant-feed-api.js +129 -0
- package/dist/http/merchant-feed-api.js.map +1 -0
- package/dist/http/merchant-follow-api.d.ts +15 -0
- package/dist/http/merchant-follow-api.js +192 -0
- package/dist/http/merchant-follow-api.js.map +1 -0
- package/dist/http/merchant-management/api.d.ts +241 -0
- package/dist/http/merchant-management/api.js +2785 -0
- package/dist/http/merchant-management/api.js.map +1 -0
- package/dist/http/merchant-management/draft-store.d.ts +51 -0
- package/dist/http/merchant-management/draft-store.js +95 -0
- package/dist/http/merchant-management/draft-store.js.map +1 -0
- package/dist/http/merchant-management/event-projection.d.ts +41 -0
- package/dist/http/merchant-management/event-projection.js +190 -0
- package/dist/http/merchant-management/event-projection.js.map +1 -0
- package/dist/http/merchant-management/operation-store.d.ts +97 -0
- package/dist/http/merchant-management/operation-store.js +252 -0
- package/dist/http/merchant-management/operation-store.js.map +1 -0
- package/dist/http/merchant-management/page.d.ts +29 -0
- package/dist/http/merchant-management/page.js +346 -0
- package/dist/http/merchant-management/page.js.map +1 -0
- package/dist/http/merchant-management/problem-client.d.ts +19 -0
- package/dist/http/merchant-management/problem-client.js +55 -0
- package/dist/http/merchant-management/problem-client.js.map +1 -0
- package/dist/http/merchant-management/problem.d.ts +74 -0
- package/dist/http/merchant-management/problem.js +112 -0
- package/dist/http/merchant-management/problem.js.map +1 -0
- package/dist/http/merchant-management/reconciliation-worker.d.ts +95 -0
- package/dist/http/merchant-management/reconciliation-worker.js +397 -0
- package/dist/http/merchant-management/reconciliation-worker.js.map +1 -0
- package/dist/http/merchant-management/service-state.d.ts +86 -0
- package/dist/http/merchant-management/service-state.js +217 -0
- package/dist/http/merchant-management/service-state.js.map +1 -0
- package/dist/http/merchant-management/trusted-page.d.ts +3 -0
- package/dist/http/merchant-management/trusted-page.js +73 -0
- package/dist/http/merchant-management/trusted-page.js.map +1 -0
- package/dist/http/merchant-management/webauthn-confirmation.d.ts +148 -0
- package/dist/http/merchant-management/webauthn-confirmation.js +517 -0
- package/dist/http/merchant-management/webauthn-confirmation.js.map +1 -0
- package/dist/http/merchant-privacy-api.d.ts +9 -0
- package/dist/http/merchant-privacy-api.js +96 -0
- package/dist/http/merchant-privacy-api.js.map +1 -0
- package/dist/mcp/merchant-rfq-resources.d.ts +37 -0
- package/dist/mcp/merchant-rfq-resources.js +132 -0
- package/dist/mcp/merchant-rfq-resources.js.map +1 -0
- package/dist/mcp/merchant-rfq-tools.d.ts +61 -0
- package/dist/mcp/merchant-rfq-tools.js +584 -0
- package/dist/mcp/merchant-rfq-tools.js.map +1 -0
- package/dist/mcp/merchant-runtime-assembly.d.ts +74 -0
- package/dist/mcp/merchant-runtime-assembly.js +473 -0
- package/dist/mcp/merchant-runtime-assembly.js.map +1 -0
- package/dist/mcp/merchant-server.d.ts +64 -1
- package/dist/mcp/merchant-server.js +245 -23
- package/dist/mcp/merchant-server.js.map +1 -1
- package/dist/mcp/tools.js +8 -2
- package/dist/mcp/tools.js.map +1 -1
- package/dist/merchant/application/actor.d.ts +85 -0
- package/dist/merchant/application/actor.js +162 -0
- package/dist/merchant/application/actor.js.map +1 -0
- package/dist/merchant/application/money.d.ts +35 -0
- package/dist/merchant/application/money.js +124 -0
- package/dist/merchant/application/money.js.map +1 -0
- package/dist/merchant/application/service.d.ts +228 -0
- package/dist/merchant/application/service.js +262 -0
- package/dist/merchant/application/service.js.map +1 -0
- package/dist/merchant/clock-safety.d.ts +50 -0
- package/dist/merchant/clock-safety.js +153 -0
- package/dist/merchant/clock-safety.js.map +1 -0
- package/dist/merchant/engagement-store.d.ts +32 -0
- package/dist/merchant/engagement-store.js +119 -0
- package/dist/merchant/engagement-store.js.map +1 -0
- package/dist/merchant/exact-product-executors.d.ts +11 -0
- package/dist/merchant/exact-product-executors.js +132 -0
- package/dist/merchant/exact-product-executors.js.map +1 -0
- package/dist/merchant/feed-executors.d.ts +17 -0
- package/dist/merchant/feed-executors.js +151 -0
- package/dist/merchant/feed-executors.js.map +1 -0
- package/dist/merchant/feed-store.d.ts +141 -0
- package/dist/merchant/feed-store.js +496 -0
- package/dist/merchant/feed-store.js.map +1 -0
- package/dist/merchant/follow-store.d.ts +66 -0
- package/dist/merchant/follow-store.js +295 -0
- package/dist/merchant/follow-store.js.map +1 -0
- package/dist/merchant/grant-executors.d.ts +11 -0
- package/dist/merchant/grant-executors.js +136 -0
- package/dist/merchant/grant-executors.js.map +1 -0
- package/dist/merchant/grant-store.d.ts +125 -0
- package/dist/merchant/grant-store.js +313 -0
- package/dist/merchant/grant-store.js.map +1 -0
- package/dist/merchant/inventory-executors.d.ts +47 -0
- package/dist/merchant/inventory-executors.js +91 -0
- package/dist/merchant/inventory-executors.js.map +1 -0
- package/dist/merchant/listing-executors.d.ts +51 -0
- package/dist/merchant/listing-executors.js +100 -0
- package/dist/merchant/listing-executors.js.map +1 -0
- package/dist/merchant/operation-receipts.d.ts +57 -0
- package/dist/merchant/operation-receipts.js +138 -0
- package/dist/merchant/operation-receipts.js.map +1 -0
- package/dist/merchant/promotion-broadcast-recovery.d.ts +22 -0
- package/dist/merchant/promotion-broadcast-recovery.js +74 -0
- package/dist/merchant/promotion-broadcast-recovery.js.map +1 -0
- package/dist/merchant/promotion-broadcast-workflow.d.ts +42 -0
- package/dist/merchant/promotion-broadcast-workflow.js +171 -0
- package/dist/merchant/promotion-broadcast-workflow.js.map +1 -0
- package/dist/merchant/promotion-executors.d.ts +18 -0
- package/dist/merchant/promotion-executors.js +133 -0
- package/dist/merchant/promotion-executors.js.map +1 -0
- package/dist/merchant/promotion-store.d.ts +114 -0
- package/dist/merchant/promotion-store.js +325 -0
- package/dist/merchant/promotion-store.js.map +1 -0
- package/dist/merchant/promotion-time.d.ts +19 -0
- package/dist/merchant/promotion-time.js +162 -0
- package/dist/merchant/promotion-time.js.map +1 -0
- package/dist/merchant/quote-calculator.d.ts +32 -0
- package/dist/merchant/quote-calculator.js +70 -0
- package/dist/merchant/quote-calculator.js.map +1 -0
- package/dist/merchant/service-control-executors.d.ts +15 -0
- package/dist/merchant/service-control-executors.js +52 -0
- package/dist/merchant/service-control-executors.js.map +1 -0
- package/dist/merchant/workbench-service.d.ts +1 -0
- package/dist/merchant/workbench-service.js +11 -1
- package/dist/merchant/workbench-service.js.map +1 -1
- package/dist/merchant-admin/pending-page.d.ts +104 -0
- package/dist/merchant-admin/pending-page.js +20 -0
- package/dist/merchant-admin/pending-page.js.map +1 -1
- package/dist/merchant-admin/rfq-page.d.ts +105 -0
- package/dist/merchant-admin/rfq-page.js +176 -0
- package/dist/merchant-admin/rfq-page.js.map +1 -0
- package/dist/merchant-core/commands.d.ts +27 -0
- package/dist/merchant-core/commands.js +90 -1
- package/dist/merchant-core/commands.js.map +1 -1
- package/dist/merchant-core/executor.d.ts +27 -3
- package/dist/merchant-core/executor.js +13 -4
- package/dist/merchant-core/executor.js.map +1 -1
- package/dist/merchant-core/rfq/artifacts.d.ts +78 -0
- package/dist/merchant-core/rfq/artifacts.js +219 -0
- package/dist/merchant-core/rfq/artifacts.js.map +1 -0
- package/dist/merchant-core/rfq/data-source-adapter.d.ts +49 -0
- package/dist/merchant-core/rfq/data-source-adapter.js +128 -0
- package/dist/merchant-core/rfq/data-source-adapter.js.map +1 -0
- package/dist/merchant-core/rfq/delivery.d.ts +43 -0
- package/dist/merchant-core/rfq/delivery.js +57 -0
- package/dist/merchant-core/rfq/delivery.js.map +1 -0
- package/dist/merchant-core/rfq/fact-resolver.d.ts +76 -0
- package/dist/merchant-core/rfq/fact-resolver.js +220 -0
- package/dist/merchant-core/rfq/fact-resolver.js.map +1 -0
- package/dist/merchant-core/rfq/handoff.d.ts +54 -0
- package/dist/merchant-core/rfq/handoff.js +71 -0
- package/dist/merchant-core/rfq/handoff.js.map +1 -0
- package/dist/merchant-core/rfq/policy.d.ts +77 -0
- package/dist/merchant-core/rfq/policy.js +104 -0
- package/dist/merchant-core/rfq/policy.js.map +1 -0
- package/dist/merchant-core/rfq/pricing.d.ts +48 -0
- package/dist/merchant-core/rfq/pricing.js +150 -0
- package/dist/merchant-core/rfq/pricing.js.map +1 -0
- package/dist/merchant-core/rfq/quote-revisions.d.ts +52 -0
- package/dist/merchant-core/rfq/quote-revisions.js +126 -0
- package/dist/merchant-core/rfq/quote-revisions.js.map +1 -0
- package/dist/merchant-core/rfq/release-coordinator.d.ts +99 -0
- package/dist/merchant-core/rfq/release-coordinator.js +355 -0
- package/dist/merchant-core/rfq/release-coordinator.js.map +1 -0
- package/dist/merchant-core/rfq/repository.d.ts +398 -0
- package/dist/merchant-core/rfq/repository.js +855 -0
- package/dist/merchant-core/rfq/repository.js.map +1 -0
- package/dist/merchant-core/rfq/service.d.ts +398 -0
- package/dist/merchant-core/rfq/service.js +1036 -0
- package/dist/merchant-core/rfq/service.js.map +1 -0
- package/dist/merchant-core/rfq/source-records.d.ts +97 -0
- package/dist/merchant-core/rfq/source-records.js +349 -0
- package/dist/merchant-core/rfq/source-records.js.map +1 -0
- package/dist/merchant-core/rfq/types.d.ts +197 -0
- package/dist/merchant-core/rfq/types.js +110 -0
- package/dist/merchant-core/rfq/types.js.map +1 -0
- package/dist/merchant-core/service.d.ts +118 -1
- package/dist/merchant-core/service.js +202 -7
- package/dist/merchant-core/service.js.map +1 -1
- package/dist/merchant-core/storage/clock-skew-alerts.d.ts +21 -0
- package/dist/merchant-core/storage/clock-skew-alerts.js +67 -0
- package/dist/merchant-core/storage/clock-skew-alerts.js.map +1 -0
- package/dist/merchant-core/storage/leased-job.d.ts +42 -0
- package/dist/merchant-core/storage/leased-job.js +38 -0
- package/dist/merchant-core/storage/leased-job.js.map +1 -0
- package/dist/merchant-core/storage/operation-lifecycle.d.ts +78 -0
- package/dist/merchant-core/storage/operation-lifecycle.js +111 -0
- package/dist/merchant-core/storage/operation-lifecycle.js.map +1 -0
- package/dist/merchant-core/storage/redact.d.ts +29 -0
- package/dist/merchant-core/storage/redact.js +34 -0
- package/dist/merchant-core/storage/redact.js.map +1 -0
- package/dist/merchant-core/storage/schema.d.ts +24 -0
- package/dist/merchant-core/storage/schema.js +22 -0
- package/dist/merchant-core/storage/schema.js.map +1 -0
- package/dist/merchant-core/storage/transaction.d.ts +47 -0
- package/dist/merchant-core/storage/transaction.js +28 -0
- package/dist/merchant-core/storage/transaction.js.map +1 -0
- package/dist/merchant-gateway/catalog-publications.d.ts +25 -0
- package/dist/merchant-gateway/catalog-publications.js +37 -0
- package/dist/merchant-gateway/catalog-publications.js.map +1 -1
- package/dist/merchant-gateway/catalog-tools.js +42 -4
- package/dist/merchant-gateway/catalog-tools.js.map +1 -1
- package/dist/merchant-gateway/cli.js +6 -3
- package/dist/merchant-gateway/cli.js.map +1 -1
- package/dist/merchant-gateway/entry-server.js +57 -10
- package/dist/merchant-gateway/entry-server.js.map +1 -1
- package/dist/merchant-gateway/instance-registration.d.ts +1 -0
- package/dist/merchant-gateway/instance-registration.js +11 -2
- package/dist/merchant-gateway/instance-registration.js.map +1 -1
- package/dist/merchant-gateway/instance-tools.d.ts +3 -3
- package/dist/merchant-gateway/instance-tools.js +13 -11
- package/dist/merchant-gateway/instance-tools.js.map +1 -1
- package/dist/merchant-gateway/pinned-fetch.d.ts +3 -1
- package/dist/merchant-gateway/pinned-fetch.js +24 -5
- package/dist/merchant-gateway/pinned-fetch.js.map +1 -1
- package/dist/negotiation/domain/objects.d.ts +7 -0
- package/dist/negotiation/domain/objects.js +8 -0
- package/dist/negotiation/domain/objects.js.map +1 -1
- package/dist/negotiation/idempotency/store.d.ts +23 -0
- package/dist/negotiation/idempotency/store.js +72 -1
- package/dist/negotiation/idempotency/store.js.map +1 -1
- package/dist/negotiation/idempotency/types.d.ts +16 -0
- package/dist/negotiation/idempotency/types.js +2 -0
- package/dist/negotiation/idempotency/types.js.map +1 -1
- package/dist/negotiation/lease/store.d.ts +18 -22
- package/dist/negotiation/lease/store.js +133 -88
- package/dist/negotiation/lease/store.js.map +1 -1
- package/dist/negotiation/ledger/event.d.ts +6 -0
- package/dist/negotiation/ledger/event.js +1 -0
- package/dist/negotiation/ledger/event.js.map +1 -1
- package/dist/negotiation/ledger/index.d.ts +4 -2
- package/dist/negotiation/ledger/index.js +1 -0
- package/dist/negotiation/ledger/index.js.map +1 -1
- package/dist/negotiation/ledger/payload-segments.d.ts +51 -0
- package/dist/negotiation/ledger/payload-segments.js +247 -0
- package/dist/negotiation/ledger/payload-segments.js.map +1 -0
- package/dist/negotiation/ledger/store.d.ts +34 -0
- package/dist/negotiation/ledger/store.js +162 -0
- package/dist/negotiation/ledger/store.js.map +1 -1
- package/dist/negotiation/recovery/recover.js +1 -1
- package/dist/negotiation/recovery/recover.js.map +1 -1
- package/dist/privacy/ledger-payload-deletion.d.ts +10 -0
- package/dist/privacy/ledger-payload-deletion.js +31 -0
- package/dist/privacy/ledger-payload-deletion.js.map +1 -0
- package/dist/privacy/local-backup-deletion.d.ts +13 -0
- package/dist/privacy/local-backup-deletion.js +115 -0
- package/dist/privacy/local-backup-deletion.js.map +1 -0
- package/dist/privacy/workbench-retention.d.ts +105 -0
- package/dist/privacy/workbench-retention.js +501 -0
- package/dist/privacy/workbench-retention.js.map +1 -0
- package/dist/runtime/model.d.ts +1 -1
- package/dist/runtime/model.js +3 -3
- package/dist/runtime/model.js.map +1 -1
- package/dist/trust/binding/claims.d.ts +92 -0
- package/dist/trust/binding/claims.js +175 -0
- package/dist/trust/binding/claims.js.map +1 -0
- package/dist/trust/binding/thumbprint.d.ts +35 -0
- package/dist/trust/binding/thumbprint.js +88 -0
- package/dist/trust/binding/thumbprint.js.map +1 -0
- package/dist/trust/binding/verify.d.ts +84 -0
- package/dist/trust/binding/verify.js +121 -0
- package/dist/trust/binding/verify.js.map +1 -0
- package/dist/trust/identity/auth-verifier.d.ts +9 -0
- package/dist/trust/identity/auth-verifier.js +10 -2
- package/dist/trust/identity/auth-verifier.js.map +1 -1
- package/dist/trust/identity/jws.d.ts +22 -1
- package/dist/trust/identity/jws.js +31 -2
- package/dist/trust/identity/jws.js.map +1 -1
- package/package.json +12 -4
- package/skills/kiwi-buyer/SKILL.md +33 -2
|
@@ -0,0 +1,2785 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* 商家私有管理 API(BD 设计 §9/§10/§11:`/merchant/api/*`,契约
|
|
18
|
+
* `merchant-management/1`,schemas 见 contracts/merchant-management/1.0/)。
|
|
19
|
+
*
|
|
20
|
+
* 职责边界(BD §8.1 的「HTTP/MCP 适配层」行):
|
|
21
|
+
* - 路由、会话→已验证主体、CSRF/Origin、输入 Schema 校验、幂等与错误映射;
|
|
22
|
+
* - **不**重写报价/审批规则:业务全部经 BD-01 `MerchantApplicationService`
|
|
23
|
+
* 与 core 命令日志;本层只编排权威操作记录(§10.2 的幂等顺序)。
|
|
24
|
+
*
|
|
25
|
+
* 鉴权(一个部署单元 ≠ 一个权限域,红线 4):
|
|
26
|
+
* - 会话与 /admin 同源(`MerchantAdminSessions`,kiwi_admin cookie,12h);
|
|
27
|
+
* A2A Bearer/签名与 Catalog OAuth **不是**管理凭据(UC11);
|
|
28
|
+
* - 写请求必须携带会话绑定的 CSRF 头(HMAC(sessionId, 进程密钥),恒定时间
|
|
29
|
+
* 比较);请求带 Origin 时必须命中允许 origin 列表(精确匹配,BD §7.2;
|
|
30
|
+
* CORS 不是认证);
|
|
31
|
+
* - 主体只从会话派生:正文/路径/头里的 merchant_id/actor_id 一律不认(UC10);
|
|
32
|
+
* 跨商家对象统一 404,不透露对方存在(UC09)。
|
|
33
|
+
*
|
|
34
|
+
* 幂等(§10.2):先认证与归属 → 规范化输入 → 权威存储查
|
|
35
|
+
* `(merchant_id, actor_id, command_type, idempotency_key)`;同键同摘要回放原
|
|
36
|
+
* 回执,同键异摘要 409。校验/授权类失败在触达执行前 `release()` 回滚占位,
|
|
37
|
+
* 允许修正后用原键重试;执行层异常且无法证明「未执行」→ 记 unknown 并保留
|
|
38
|
+
* operation_id 查询路径(§11.1),绝不当作失败自动重做。
|
|
39
|
+
*/
|
|
40
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
41
|
+
import { contentHash } from "../../agent/merchant/action-candidate.js";
|
|
42
|
+
import { ADMIN_SESSION_COOKIE } from "../../auth/merchant-sessions.js";
|
|
43
|
+
import { parseProductTable, ProductTableError, productTableDigest, } from "../../cloud/product-source.js";
|
|
44
|
+
import { MerchantImportDraftStore } from "./draft-store.js";
|
|
45
|
+
import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, } from "../../merchant/application/actor.js";
|
|
46
|
+
import { MANAGEMENT_API_MAJOR, MANAGEMENT_ERROR_STATUS, ManagementError, MerchantApplicationService, } from "../../merchant/application/service.js";
|
|
47
|
+
import { managementRequestDigest, MerchantManagementOperationStore } from "./operation-store.js";
|
|
48
|
+
import { OnboardingStore } from "../../cloud/onboarding/store.js";
|
|
49
|
+
import { requestsDisabledLocalImplementation } from "../../cloud/onboarding/local-fallback.js";
|
|
50
|
+
import { checkStepSubmission, planWizard, WIZARD_STEPS } from "../../cloud/onboarding/steps.js";
|
|
51
|
+
import { createWorkbenchProblem } from "./problem.js";
|
|
52
|
+
import { WorkbenchConfirmationError, } from "./webauthn-confirmation.js";
|
|
53
|
+
import { MerchantWorkbenchError, } from "../../merchant/workbench-service.js";
|
|
54
|
+
import { parseExactMoney, WorkbenchMoneyError, WORKBENCH_CURRENCY_TABLE_VERSION, } from "../../merchant/application/money.js";
|
|
55
|
+
import { EXACT_PRODUCT_TOOLS } from "../../merchant/exact-product-executors.js";
|
|
56
|
+
import { SERVICE_CONTROL_TOOLS } from "../../merchant/service-control-executors.js";
|
|
57
|
+
import { BROADCAST_TOOLS } from "../../merchant/feed-executors.js";
|
|
58
|
+
import { MerchantFeedError } from "../../merchant/feed-store.js";
|
|
59
|
+
import { GRANT_TOOLS } from "../../merchant/grant-executors.js";
|
|
60
|
+
import { PROMOTION_TOOLS } from "../../merchant/promotion-executors.js";
|
|
61
|
+
import { MerchantPromotionError, } from "../../merchant/promotion-store.js";
|
|
62
|
+
import { WorkbenchEventProjectionError, } from "./event-projection.js";
|
|
63
|
+
import { GRANT_ACTIONS, MerchantGrantError, } from "../../merchant/grant-store.js";
|
|
64
|
+
const API_PREFIX = "/merchant/api";
|
|
65
|
+
const WORKBENCH_API_PREFIX = "/merchant/api/v1";
|
|
66
|
+
const MAX_BODY_BYTES = 1_048_576;
|
|
67
|
+
/** 非候选写命令确认引用的有效期(BD §7.3:短时、单次)。 */
|
|
68
|
+
const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
|
|
69
|
+
class BodyTooLarge {
|
|
70
|
+
}
|
|
71
|
+
export function createMerchantManagementApiHandler(options) {
|
|
72
|
+
const log = options.log ??
|
|
73
|
+
((line) => {
|
|
74
|
+
process.stderr.write(line);
|
|
75
|
+
});
|
|
76
|
+
const now = options.now ?? (() => new Date());
|
|
77
|
+
const operations = options.operations;
|
|
78
|
+
// CSRF 进程密钥:令牌 = HMAC(sessionId, key)。重启后页面重新拉取 /session
|
|
79
|
+
// 即可取到新令牌;跨进程不可推导,持 Cookie 者本就可推导(CSRF 威胁模型成立)。
|
|
80
|
+
const csrfKey = randomBytes(32);
|
|
81
|
+
const baseDeps = {
|
|
82
|
+
merchantId: options.merchantId,
|
|
83
|
+
generation: options.generation,
|
|
84
|
+
runtimeVersion: options.runtimeVersion,
|
|
85
|
+
readiness: options.readiness,
|
|
86
|
+
serviceState: () => options.serviceState.state,
|
|
87
|
+
// 对话私有工具取决于 B07(平台动态绑定能力),未验证前一律 false(§4.2)。
|
|
88
|
+
capabilities: () => ({ management_page: true, dialog_tools: false }),
|
|
89
|
+
listCandidates: options.listPending,
|
|
90
|
+
getCandidate: (candidateId) => options.listPending().find((item) => item.candidate_id === candidateId),
|
|
91
|
+
getOperation: (operationId) => operations.get(operationId, options.merchantId),
|
|
92
|
+
decide: async () => {
|
|
93
|
+
// 只读实例不携带执行通道;审批执行必须走 executionService(带 operationId)。
|
|
94
|
+
throw new ManagementError("invalid_input", "decision execution requires the write path");
|
|
95
|
+
},
|
|
96
|
+
...(options.policy !== undefined ? { policy: options.policy } : {}),
|
|
97
|
+
...(options.products !== undefined ? { products: options.products } : {}),
|
|
98
|
+
...(options.now !== undefined ? { now: options.now } : {}),
|
|
99
|
+
};
|
|
100
|
+
const readService = new MerchantApplicationService(baseDeps);
|
|
101
|
+
/** 执行实例:deps.decide 绑定本次幂等占位的 operationId(回执可对账)。 */
|
|
102
|
+
function executionService(operationId) {
|
|
103
|
+
return new MerchantApplicationService({
|
|
104
|
+
...baseDeps,
|
|
105
|
+
decide: async (input) => {
|
|
106
|
+
await options.executeDecision({
|
|
107
|
+
candidateId: input.candidateId,
|
|
108
|
+
actorId: input.actorId,
|
|
109
|
+
merchantId: input.merchantId,
|
|
110
|
+
approve: input.approve,
|
|
111
|
+
confirmationRef: input.confirmationRef,
|
|
112
|
+
idempotencyKey: input.idempotencyKey,
|
|
113
|
+
});
|
|
114
|
+
return { operationId, status: "succeeded" };
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
return (req, res) => {
|
|
119
|
+
void handle(req, res).catch((err) => {
|
|
120
|
+
respondError(res, err);
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
async function handle(req, res) {
|
|
124
|
+
const method = req.method ?? "GET";
|
|
125
|
+
let url;
|
|
126
|
+
try {
|
|
127
|
+
url = new URL(req.url ?? "/", "http://merchant-management.internal");
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
writeJson(res, 400, errorBody("invalid_input", "invalid request target"));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const pathname = url.pathname;
|
|
134
|
+
if (pathname !== API_PREFIX && !pathname.startsWith(`${API_PREFIX}/`)) {
|
|
135
|
+
writeJson(res, 404, errorBody("not_found", "unknown management api path"));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (pathname === WORKBENCH_API_PREFIX || pathname.startsWith(`${WORKBENCH_API_PREFIX}/`)) {
|
|
139
|
+
const requestId = `req_${randomBytes(12).toString("hex")}`;
|
|
140
|
+
const rest = pathname === WORKBENCH_API_PREFIX ? "/" : pathname.slice(WORKBENCH_API_PREFIX.length);
|
|
141
|
+
try {
|
|
142
|
+
if (method === "GET") {
|
|
143
|
+
await routeWorkbenchV1Get(req, res, url, rest, requestId);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (method === "POST") {
|
|
147
|
+
await routeWorkbenchV1Post(req, res, rest, requestId);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
{
|
|
151
|
+
writeWorkbenchProblem(res, "VALIDATION_ERROR", requestId, "请求方法不可用", "该 Workbench 路由当前只接受 GET/POST。", { allow: "GET, POST" });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
respondWorkbenchError(res, error, requestId);
|
|
157
|
+
}
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const rest = pathname === API_PREFIX ? "/" : pathname.slice(API_PREFIX.length);
|
|
161
|
+
try {
|
|
162
|
+
if (method === "GET") {
|
|
163
|
+
await routeGet(req, res, url, rest);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (method === "POST") {
|
|
167
|
+
await routePost(req, res, rest);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
if (err instanceof BodyTooLarge) {
|
|
173
|
+
writeJson(res, 413, errorBody("invalid_input", "request body too large"));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
respondError(res, err);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (isKnownPath(rest)) {
|
|
180
|
+
writeJson(res, 405, errorBody("invalid_input", "method not allowed"), { allow: "GET, POST" });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
writeJson(res, 404, errorBody("not_found", "unknown management api path"));
|
|
184
|
+
}
|
|
185
|
+
// ── 只读路由(认证即鉴权入口;业务授权在服务层逐次复核)────────────────
|
|
186
|
+
/** Workbench v1 读取面复用同一应用服务;未实现路由明确失败,不返回假数据。 */
|
|
187
|
+
async function routeWorkbenchV1Get(req, res, url, rest, requestId) {
|
|
188
|
+
if (rest === "/overview") {
|
|
189
|
+
const auth = requireActor(req);
|
|
190
|
+
const runtime = await readService.getStatus(auth.ctx);
|
|
191
|
+
const pendingApprovals = options
|
|
192
|
+
.listPending()
|
|
193
|
+
.filter((candidate) => candidate.status === "pending_approval").length;
|
|
194
|
+
let negotiationsOverview = {
|
|
195
|
+
observable: false,
|
|
196
|
+
value: null,
|
|
197
|
+
reason: "unified_negotiation_projection_unavailable",
|
|
198
|
+
};
|
|
199
|
+
if (options.negotiations !== undefined) {
|
|
200
|
+
try {
|
|
201
|
+
const result = await options.negotiations.list(1);
|
|
202
|
+
negotiationsOverview = { observable: true, value: { total: result.total } };
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
negotiationsOverview = {
|
|
206
|
+
observable: false,
|
|
207
|
+
value: null,
|
|
208
|
+
reason: "negotiation_authority_unavailable",
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
writeJson(res, 200, {
|
|
213
|
+
generated_at: now().toISOString(),
|
|
214
|
+
runtime,
|
|
215
|
+
approvals: { observable: true, pending: pendingApprovals },
|
|
216
|
+
broadcasts: options.workbenchFeed === undefined
|
|
217
|
+
? { observable: false, value: null, reason: "feed_authority_unavailable" }
|
|
218
|
+
: {
|
|
219
|
+
observable: true,
|
|
220
|
+
value: options.workbenchFeed.summary(auth.ctx.merchantId),
|
|
221
|
+
},
|
|
222
|
+
promotions: options.workbenchPromotions === undefined
|
|
223
|
+
? { observable: false, value: null, reason: "promotion_authority_unavailable" }
|
|
224
|
+
: {
|
|
225
|
+
observable: true,
|
|
226
|
+
value: options.workbenchPromotions.summary(auth.ctx.merchantId),
|
|
227
|
+
},
|
|
228
|
+
followers: options.followerSummary === undefined
|
|
229
|
+
? {
|
|
230
|
+
observable: false,
|
|
231
|
+
value: null,
|
|
232
|
+
reason: "verified_buyer_identity_resolver_unavailable",
|
|
233
|
+
}
|
|
234
|
+
: {
|
|
235
|
+
observable: true,
|
|
236
|
+
value: { active_verified_subjects: options.followerSummary() },
|
|
237
|
+
},
|
|
238
|
+
engagement: options.engagementSummary === undefined
|
|
239
|
+
? { observable: false, value: null, reason: "engagement_authority_unavailable" }
|
|
240
|
+
: { observable: true, value: options.engagementSummary() },
|
|
241
|
+
negotiations: negotiationsOverview,
|
|
242
|
+
}, { "x-request-id": requestId });
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (rest === "/runtime/status") {
|
|
246
|
+
const auth = requireActor(req);
|
|
247
|
+
writeJson(res, 200, await readService.getStatus(auth.ctx), { "x-request-id": requestId });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (rest === "/products") {
|
|
251
|
+
const auth = requireActor(req);
|
|
252
|
+
authorizeOrThrow(auth.ctx, "products:read");
|
|
253
|
+
const channel = options.exactProducts;
|
|
254
|
+
if (channel === undefined) {
|
|
255
|
+
throw new ManagementError("unavailable", "exact product authority is not configured");
|
|
256
|
+
}
|
|
257
|
+
const query = pageQuery(url);
|
|
258
|
+
const offset = query.cursor === undefined ? 0 : Number.parseInt(query.cursor, 10);
|
|
259
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
260
|
+
throw new ManagementError("invalid_input", "product cursor is invalid");
|
|
261
|
+
}
|
|
262
|
+
const limit = Math.min(query.limit ?? 50, 100);
|
|
263
|
+
const all = await channel.list();
|
|
264
|
+
writeJson(res, 200, {
|
|
265
|
+
items: all.slice(offset, offset + limit).map(exactProductProjection),
|
|
266
|
+
next_cursor: offset + limit < all.length ? String(offset + limit) : null,
|
|
267
|
+
total: all.length,
|
|
268
|
+
}, { "x-request-id": requestId });
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const productMatch = /^\/products\/([^/]+)$/.exec(rest);
|
|
272
|
+
if (productMatch !== null) {
|
|
273
|
+
const auth = requireActor(req);
|
|
274
|
+
authorizeOrThrow(auth.ctx, "products:read");
|
|
275
|
+
const channel = options.exactProducts;
|
|
276
|
+
if (channel === undefined) {
|
|
277
|
+
throw new ManagementError("unavailable", "exact product authority is not configured");
|
|
278
|
+
}
|
|
279
|
+
writeJson(res, 200, exactProductProjection(await channel.get(pathSegment(productMatch[1] ?? ""))), { "x-request-id": requestId });
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (rest === "/approvals") {
|
|
283
|
+
const auth = requireActor(req);
|
|
284
|
+
writeJson(res, 200, await readService.listApprovals(auth.ctx, pageQuery(url)), {
|
|
285
|
+
"x-request-id": requestId,
|
|
286
|
+
});
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (rest === "/negotiations") {
|
|
290
|
+
const auth = requireActor(req);
|
|
291
|
+
authorizeOrThrow(auth.ctx, "approvals:read");
|
|
292
|
+
const channel = options.negotiations;
|
|
293
|
+
if (channel === undefined) {
|
|
294
|
+
throw new ManagementError("unavailable", "negotiation authority is not configured");
|
|
295
|
+
}
|
|
296
|
+
const query = pageQuery(url);
|
|
297
|
+
writeJson(res, 200, await channel.list(query.limit), { "x-request-id": requestId });
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const negotiationMatch = /^\/negotiations\/([^/]+)$/.exec(rest);
|
|
301
|
+
if (negotiationMatch !== null) {
|
|
302
|
+
const auth = requireActor(req);
|
|
303
|
+
authorizeOrThrow(auth.ctx, "approvals:read");
|
|
304
|
+
const channel = options.negotiations;
|
|
305
|
+
if (channel === undefined) {
|
|
306
|
+
throw new ManagementError("unavailable", "negotiation authority is not configured");
|
|
307
|
+
}
|
|
308
|
+
writeJson(res, 200, await channel.get(pathSegment(negotiationMatch[1] ?? "")), {
|
|
309
|
+
"x-request-id": requestId,
|
|
310
|
+
});
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (rest === "/broadcasts") {
|
|
314
|
+
const auth = requireActor(req);
|
|
315
|
+
authorizeOrThrow(auth.ctx, "approvals:read");
|
|
316
|
+
const feed = requireWorkbenchFeed();
|
|
317
|
+
writeJson(res, 200, feed.listBroadcasts(auth.ctx.merchantId, pageQuery(url)), {
|
|
318
|
+
"x-request-id": requestId,
|
|
319
|
+
});
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (rest === "/operator-grants") {
|
|
323
|
+
const auth = requireActor(req);
|
|
324
|
+
authorizeOrThrow(auth.ctx, "grants:manage");
|
|
325
|
+
const grants = requireWorkbenchGrants();
|
|
326
|
+
writeJson(res, 200, grants.listGrants(auth.ctx.merchantId, pageQuery(url)), {
|
|
327
|
+
"x-request-id": requestId,
|
|
328
|
+
});
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (rest === "/promotions") {
|
|
332
|
+
const auth = requireActor(req);
|
|
333
|
+
authorizeOrThrow(auth.ctx, "products:read");
|
|
334
|
+
writeJson(res, 200, requireWorkbenchPromotions().listPromotions(auth.ctx.merchantId, pageQuery(url)), { "x-request-id": requestId });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const promotionMatch = /^\/promotions\/([^/]+)$/.exec(rest);
|
|
338
|
+
if (promotionMatch !== null) {
|
|
339
|
+
const auth = requireActor(req);
|
|
340
|
+
authorizeOrThrow(auth.ctx, "products:read");
|
|
341
|
+
const value = requireWorkbenchPromotions().getPromotion(auth.ctx.merchantId, pathSegment(promotionMatch[1] ?? ""));
|
|
342
|
+
if (value === undefined)
|
|
343
|
+
throw new ManagementError("not_found", "unknown promotion");
|
|
344
|
+
writeJson(res, 200, value, { "x-request-id": requestId });
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const promotionWorkflowMatch = /^\/promotion-workflows\/([^/]+)$/.exec(rest);
|
|
348
|
+
if (promotionWorkflowMatch !== null) {
|
|
349
|
+
const auth = requireActor(req);
|
|
350
|
+
authorizeOrThrow(auth.ctx, "operations:read");
|
|
351
|
+
const workflow = options.promotionBroadcastWorkflows?.get(auth.ctx.merchantId, pathSegment(promotionWorkflowMatch[1] ?? ""));
|
|
352
|
+
if (workflow === undefined) {
|
|
353
|
+
throw new ManagementError("not_found", "unknown promotion broadcast workflow");
|
|
354
|
+
}
|
|
355
|
+
writeJson(res, 200, workflow, { "x-request-id": requestId });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const broadcastMatch = /^\/broadcasts\/([^/]+)$/.exec(rest);
|
|
359
|
+
if (broadcastMatch !== null) {
|
|
360
|
+
const auth = requireActor(req);
|
|
361
|
+
authorizeOrThrow(auth.ctx, "approvals:read");
|
|
362
|
+
const value = requireWorkbenchFeed().getBroadcast(auth.ctx.merchantId, pathSegment(broadcastMatch[1] ?? ""));
|
|
363
|
+
if (value === undefined)
|
|
364
|
+
throw new ManagementError("not_found", "unknown broadcast");
|
|
365
|
+
writeJson(res, 200, value, { "x-request-id": requestId });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const approvalMatch = /^\/approvals\/([^/]+)$/.exec(rest);
|
|
369
|
+
if (approvalMatch !== null) {
|
|
370
|
+
const auth = requireActor(req);
|
|
371
|
+
writeJson(res, 200, await readService.getApproval(auth.ctx, pathSegment(approvalMatch[1] ?? "")), { "x-request-id": requestId });
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const operationMatch = /^\/operations\/([^/]+)$/.exec(rest);
|
|
375
|
+
if (operationMatch !== null) {
|
|
376
|
+
const auth = requireActor(req);
|
|
377
|
+
writeJson(res, 200, readService.getOperation(auth.ctx, pathSegment(operationMatch[1] ?? "")), { "x-request-id": requestId });
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (rest === "/alerts") {
|
|
381
|
+
const auth = requireActor(req);
|
|
382
|
+
authorizeOrThrow(auth.ctx, "operations:read");
|
|
383
|
+
const store = options.workbenchReconciliation;
|
|
384
|
+
if (store === undefined) {
|
|
385
|
+
throw new ManagementError("unavailable", "Workbench alert authority is not configured");
|
|
386
|
+
}
|
|
387
|
+
writeJson(res, 200, store.listAlerts(auth.ctx.merchantId, pageQuery(url)), {
|
|
388
|
+
"x-request-id": requestId,
|
|
389
|
+
});
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (rest === "/events") {
|
|
393
|
+
const auth = requireActor(req);
|
|
394
|
+
authorizeOrThrow(auth.ctx, "operations:read");
|
|
395
|
+
const store = options.workbenchEvents;
|
|
396
|
+
if (store === undefined) {
|
|
397
|
+
throw new ManagementError("unavailable", "Workbench event projection is not configured");
|
|
398
|
+
}
|
|
399
|
+
const query = pageQuery(url);
|
|
400
|
+
writeJson(res, 200, store.list(auth.ctx.merchantId, {
|
|
401
|
+
...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
|
|
402
|
+
...(query.limit !== undefined ? { limit: query.limit } : {}),
|
|
403
|
+
}), { "x-request-id": requestId });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
const privacyRequestMatch = /^\/privacy-requests\/([^/]+)$/u.exec(rest);
|
|
407
|
+
if (privacyRequestMatch !== null) {
|
|
408
|
+
const auth = requireActor(req);
|
|
409
|
+
authorizeOrThrow(auth.ctx, "operations:read");
|
|
410
|
+
const request = options.workbenchRetention?.getRequest(pathSegment(privacyRequestMatch[1] ?? ""), auth.ctx.merchantId);
|
|
411
|
+
if (request === undefined) {
|
|
412
|
+
throw new ManagementError("not_found", "unknown privacy request");
|
|
413
|
+
}
|
|
414
|
+
writeJson(res, 200, {
|
|
415
|
+
request_id: request.requestId,
|
|
416
|
+
status: request.status,
|
|
417
|
+
consent_generation: request.consentGeneration,
|
|
418
|
+
received_at: request.receivedAt,
|
|
419
|
+
updated_at: request.updatedAt,
|
|
420
|
+
...(request.limitationReason !== undefined
|
|
421
|
+
? { limitation_reason: request.limitationReason }
|
|
422
|
+
: {}),
|
|
423
|
+
}, { "x-request-id": requestId });
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const confirmationMatch = /^\/confirmations\/([^/]+)$/.exec(rest);
|
|
427
|
+
if (confirmationMatch !== null) {
|
|
428
|
+
const auth = requireActor(req);
|
|
429
|
+
writeJson(res, 200, requireWorkbenchConfirmations().requestProjection({
|
|
430
|
+
confirmationId: pathSegment(confirmationMatch[1] ?? ""),
|
|
431
|
+
merchantId: auth.ctx.merchantId,
|
|
432
|
+
actorId: auth.ctx.actorId,
|
|
433
|
+
}), { "x-request-id": requestId });
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
const confirmationRefMatch = /^\/confirmations\/by-ref\/([^/]+)$/.exec(rest);
|
|
437
|
+
if (confirmationRefMatch !== null) {
|
|
438
|
+
const auth = requireActor(req);
|
|
439
|
+
writeJson(res, 200, requireWorkbenchConfirmations().requestProjectionByRef({
|
|
440
|
+
requestRef: pathSegment(confirmationRefMatch[1] ?? ""),
|
|
441
|
+
merchantId: auth.ctx.merchantId,
|
|
442
|
+
actorId: auth.ctx.actorId,
|
|
443
|
+
}), { "x-request-id": requestId });
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
|
|
447
|
+
}
|
|
448
|
+
async function routeWorkbenchV1Post(req, res, rest, requestId) {
|
|
449
|
+
if (rest === "/runtime/safety-stops") {
|
|
450
|
+
const auth = requireActor(req);
|
|
451
|
+
assertWriteGuards(req, auth.sessionId);
|
|
452
|
+
authorizeOrThrow(auth.ctx, "service:pause");
|
|
453
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
454
|
+
"expected_revision",
|
|
455
|
+
"reason",
|
|
456
|
+
"idempotency_key",
|
|
457
|
+
]);
|
|
458
|
+
const expectedRevision = requireInteger(fields["expected_revision"], "expected_revision");
|
|
459
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
460
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
461
|
+
const requestDigest = managementRequestDigest({
|
|
462
|
+
expected_revision: expectedRevision,
|
|
463
|
+
reason: reason ?? null,
|
|
464
|
+
});
|
|
465
|
+
const begun = operations.begin({
|
|
466
|
+
merchantId: auth.ctx.merchantId,
|
|
467
|
+
actorId: auth.ctx.actorId,
|
|
468
|
+
commandType: "runtime.safety_stop",
|
|
469
|
+
idempotencyKey,
|
|
470
|
+
requestDigest,
|
|
471
|
+
});
|
|
472
|
+
if (begun.kind === "conflict") {
|
|
473
|
+
throw new ManagementError("conflict", "idempotency key was reused with another request");
|
|
474
|
+
}
|
|
475
|
+
if (begun.kind === "replay") {
|
|
476
|
+
writeJson(res, 200, begun.receipt, { "x-request-id": requestId });
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (expectedRevision !== options.serviceState.serviceRevision) {
|
|
480
|
+
operations.release(begun.operationId);
|
|
481
|
+
throw new ManagementError("precondition_changed", "service revision changed");
|
|
482
|
+
}
|
|
483
|
+
try {
|
|
484
|
+
const applied = options.serviceState.pause(reason);
|
|
485
|
+
const receipt = {
|
|
486
|
+
...staticReceipt(begun.operationId, "runtime.safety_stop", "succeeded"),
|
|
487
|
+
resource_ref: "service",
|
|
488
|
+
result_revision: applied.service_revision,
|
|
489
|
+
completed_at: now().toISOString(),
|
|
490
|
+
};
|
|
491
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
492
|
+
writeJson(res, 200, receipt, { "x-request-id": requestId });
|
|
493
|
+
}
|
|
494
|
+
catch (error) {
|
|
495
|
+
operations.release(begun.operationId);
|
|
496
|
+
throw error;
|
|
497
|
+
}
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (rest === "/pricing/previews") {
|
|
501
|
+
const auth = requireActor(req);
|
|
502
|
+
authorizeOrThrow(auth.ctx, "products:read");
|
|
503
|
+
const fields = objectFields(await readJsonBody(req), ["sku", "quantity"]);
|
|
504
|
+
const channel = options.quotePreview;
|
|
505
|
+
if (channel === undefined) {
|
|
506
|
+
throw new ManagementError("unavailable", "shared quote calculator is unavailable");
|
|
507
|
+
}
|
|
508
|
+
const result = await channel(requireString(fields["sku"], "sku"), requirePositiveInteger(fields["quantity"], "quantity"));
|
|
509
|
+
writeJson(res, 200, result, { "x-request-id": requestId });
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
if (rest === "/runtime/mode-drafts") {
|
|
513
|
+
const auth = requireActor(req);
|
|
514
|
+
assertWriteGuards(req, auth.sessionId);
|
|
515
|
+
authorizeOrThrow(auth.ctx, "service:resume");
|
|
516
|
+
if (auth.ctx.role !== "owner") {
|
|
517
|
+
throw new ManagementError("forbidden", "only owner can prepare service recovery");
|
|
518
|
+
}
|
|
519
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
520
|
+
"target_state",
|
|
521
|
+
"expected_revision",
|
|
522
|
+
"reason",
|
|
523
|
+
]);
|
|
524
|
+
if (fields["target_state"] !== "OPERATING") {
|
|
525
|
+
throw new ManagementError("invalid_input", "runtime mode draft currently supports target_state=OPERATING only");
|
|
526
|
+
}
|
|
527
|
+
const expectedRevision = requirePositiveInteger(fields["expected_revision"], "expected_revision");
|
|
528
|
+
if (expectedRevision !== options.serviceState.serviceRevision) {
|
|
529
|
+
throw new ManagementError("precondition_changed", "service revision changed");
|
|
530
|
+
}
|
|
531
|
+
const channel = options.prepareServiceResume;
|
|
532
|
+
if (channel === undefined) {
|
|
533
|
+
throw new ManagementError("unavailable", "service recovery candidate is unavailable");
|
|
534
|
+
}
|
|
535
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
536
|
+
const prepared = await channel({
|
|
537
|
+
expectedRevision,
|
|
538
|
+
...(reason !== undefined ? { reason } : {}),
|
|
539
|
+
});
|
|
540
|
+
writeJson(res, 201, prepared, { "x-request-id": requestId });
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (rest === "/webauthn/registrations/options") {
|
|
544
|
+
const auth = requireActor(req);
|
|
545
|
+
assertWriteGuards(req, auth.sessionId);
|
|
546
|
+
const registration = await requireRegistrationAuthorization(req, auth.ctx);
|
|
547
|
+
const begun = await requireWorkbenchConfirmations().beginCredentialRegistration({
|
|
548
|
+
merchantId: auth.ctx.merchantId,
|
|
549
|
+
actorId: auth.ctx.actorId,
|
|
550
|
+
rpName: registration.rpName,
|
|
551
|
+
rpId: registration.rpId,
|
|
552
|
+
origin: registration.origin,
|
|
553
|
+
userName: auth.ctx.actorId,
|
|
554
|
+
userDisplayName: auth.ctx.actorId,
|
|
555
|
+
});
|
|
556
|
+
writeJson(res, 201, begun, { "x-request-id": requestId });
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
const registrationVerify = /^\/webauthn\/registrations\/([^/]+)\/verify$/.exec(rest);
|
|
560
|
+
if (registrationVerify !== null) {
|
|
561
|
+
const auth = requireActor(req);
|
|
562
|
+
assertWriteGuards(req, auth.sessionId);
|
|
563
|
+
await requireRegistrationAuthorization(req, auth.ctx);
|
|
564
|
+
const body = await readJsonBody(req);
|
|
565
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
566
|
+
throw new ManagementError("invalid_input", "registration response must be an object");
|
|
567
|
+
}
|
|
568
|
+
const result = await requireWorkbenchConfirmations().finishCredentialRegistration({
|
|
569
|
+
registrationId: pathSegment(registrationVerify[1] ?? ""),
|
|
570
|
+
merchantId: auth.ctx.merchantId,
|
|
571
|
+
actorId: auth.ctx.actorId,
|
|
572
|
+
response: body,
|
|
573
|
+
});
|
|
574
|
+
writeJson(res, 201, result, { "x-request-id": requestId });
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if (rest === "/confirmations") {
|
|
578
|
+
const auth = requireActor(req);
|
|
579
|
+
assertWriteGuards(req, auth.sessionId);
|
|
580
|
+
authorizeOrThrow(auth.ctx, "approvals:decide");
|
|
581
|
+
const confirmations = requireWorkbenchConfirmations();
|
|
582
|
+
if (!confirmations.hasUsableCredential(auth.ctx.merchantId, auth.ctx.actorId)) {
|
|
583
|
+
throw new WorkbenchConfirmationError("credential_unavailable", "actor has no verified WebAuthn credential");
|
|
584
|
+
}
|
|
585
|
+
const fields = objectFields(await readJsonBody(req), ["candidate_id", "decision"]);
|
|
586
|
+
const candidateId = requireString(fields["candidate_id"], "candidate_id");
|
|
587
|
+
const decision = requireDecision(fields["decision"]);
|
|
588
|
+
const candidate = options.listPending().find((item) => item.candidate_id === candidateId);
|
|
589
|
+
if (candidate === undefined || candidate.status !== "pending_approval") {
|
|
590
|
+
throw new ManagementError("not_found", `unknown pending candidate: ${candidateId}`);
|
|
591
|
+
}
|
|
592
|
+
const expiresAt = new Date(Math.min(Date.parse(candidate.expires_at), now().getTime() + CONFIRMATION_TTL_MS)).toISOString();
|
|
593
|
+
const decisionAuthorization = authorizeBroadcastCandidate(auth.ctx, candidate, "broadcast.decide") ??
|
|
594
|
+
authorizeGrantCandidate(auth.ctx, candidate) ??
|
|
595
|
+
authorizePromotionCandidate(auth.ctx, candidate) ??
|
|
596
|
+
authorizeProductCandidate(auth.ctx, candidate) ??
|
|
597
|
+
authorizeServiceControlCandidate(auth.ctx, candidate);
|
|
598
|
+
const confirmation = confirmations.createRequest({
|
|
599
|
+
merchantId: auth.ctx.merchantId,
|
|
600
|
+
actorId: auth.ctx.actorId,
|
|
601
|
+
candidateId,
|
|
602
|
+
approvalGeneration: 1,
|
|
603
|
+
decision,
|
|
604
|
+
operationId: `wop_${randomBytes(16).toString("hex")}`,
|
|
605
|
+
actionDigest: contentHash({
|
|
606
|
+
arguments: candidate.arguments,
|
|
607
|
+
preconditions: candidate.preconditions,
|
|
608
|
+
}),
|
|
609
|
+
actionSnapshot: {
|
|
610
|
+
merchant_id: auth.ctx.merchantId,
|
|
611
|
+
candidate_id: candidateId,
|
|
612
|
+
decision,
|
|
613
|
+
tool: candidate.tool,
|
|
614
|
+
arguments: candidate.arguments,
|
|
615
|
+
preconditions: candidate.preconditions,
|
|
616
|
+
risk: candidate.risk,
|
|
617
|
+
candidate_expires_at: candidate.expires_at,
|
|
618
|
+
...(decisionAuthorization !== undefined
|
|
619
|
+
? { decision_authorization: decisionAuthorization }
|
|
620
|
+
: {}),
|
|
621
|
+
},
|
|
622
|
+
expectedVersion: 1,
|
|
623
|
+
expiresAt,
|
|
624
|
+
});
|
|
625
|
+
writeJson(res, 201, {
|
|
626
|
+
confirmation_id: confirmation.confirmationId,
|
|
627
|
+
request_ref: confirmation.requestRef,
|
|
628
|
+
expires_at: confirmation.expiresAt,
|
|
629
|
+
}, { "x-request-id": requestId });
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
const optionsMatch = /^\/confirmations\/([^/]+)\/assertion-options$/.exec(rest);
|
|
633
|
+
if (optionsMatch !== null) {
|
|
634
|
+
const auth = requireActor(req);
|
|
635
|
+
assertWriteGuards(req, auth.sessionId);
|
|
636
|
+
writeJson(res, 200, requireWorkbenchConfirmations().assertionOptions({
|
|
637
|
+
confirmationId: pathSegment(optionsMatch[1] ?? ""),
|
|
638
|
+
merchantId: auth.ctx.merchantId,
|
|
639
|
+
actorId: auth.ctx.actorId,
|
|
640
|
+
}), { "x-request-id": requestId });
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const decisionMatch = /^\/approvals\/([^/]+)\/decisions$/.exec(rest);
|
|
644
|
+
if (decisionMatch !== null) {
|
|
645
|
+
const auth = requireActor(req);
|
|
646
|
+
assertWriteGuards(req, auth.sessionId);
|
|
647
|
+
authorizeOrThrow(auth.ctx, "approvals:decide");
|
|
648
|
+
const candidateId = pathSegment(decisionMatch[1] ?? "");
|
|
649
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
650
|
+
"confirmation_id",
|
|
651
|
+
"decision",
|
|
652
|
+
"expected_version",
|
|
653
|
+
"assertion",
|
|
654
|
+
]);
|
|
655
|
+
const assertionFields = objectFields(fields["assertion"], [
|
|
656
|
+
"credential_id",
|
|
657
|
+
"client_data_json",
|
|
658
|
+
"authenticator_data",
|
|
659
|
+
"signature",
|
|
660
|
+
]);
|
|
661
|
+
const assertion = {
|
|
662
|
+
credentialId: requireString(assertionFields["credential_id"], "credential_id"),
|
|
663
|
+
clientDataJSON: requireString(assertionFields["client_data_json"], "client_data_json"),
|
|
664
|
+
authenticatorData: requireString(assertionFields["authenticator_data"], "authenticator_data"),
|
|
665
|
+
signature: requireString(assertionFields["signature"], "signature"),
|
|
666
|
+
};
|
|
667
|
+
const candidate = options.listPending().find((item) => item.candidate_id === candidateId);
|
|
668
|
+
if (candidate === undefined || candidate.status !== "pending_approval") {
|
|
669
|
+
throw new ManagementError("not_found", `unknown pending candidate: ${candidateId}`);
|
|
670
|
+
}
|
|
671
|
+
const currentAuthorization = authorizeBroadcastCandidate(auth.ctx, candidate, "broadcast.decide") ??
|
|
672
|
+
authorizeGrantCandidate(auth.ctx, candidate) ??
|
|
673
|
+
authorizePromotionCandidate(auth.ctx, candidate) ??
|
|
674
|
+
authorizeProductCandidate(auth.ctx, candidate) ??
|
|
675
|
+
authorizeServiceControlCandidate(auth.ctx, candidate);
|
|
676
|
+
if (currentAuthorization !== undefined) {
|
|
677
|
+
const confirmationId = requireString(fields["confirmation_id"], "confirmation_id");
|
|
678
|
+
const frozen = requireWorkbenchConfirmations().requestProjection({
|
|
679
|
+
confirmationId,
|
|
680
|
+
merchantId: auth.ctx.merchantId,
|
|
681
|
+
actorId: auth.ctx.actorId,
|
|
682
|
+
}).snapshot["decision_authorization"];
|
|
683
|
+
if (!sameAuthorizationGeneration(frozen, currentAuthorization)) {
|
|
684
|
+
throw new ManagementError("forbidden", "broadcast authorization changed after confirmation was created");
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const outcome = requireWorkbenchConfirmations().finalizeDecision({
|
|
688
|
+
confirmationId: requireString(fields["confirmation_id"], "confirmation_id"),
|
|
689
|
+
merchantId: auth.ctx.merchantId,
|
|
690
|
+
actorId: auth.ctx.actorId,
|
|
691
|
+
candidateId,
|
|
692
|
+
approvalGeneration: 1,
|
|
693
|
+
decision: requireDecision(fields["decision"]),
|
|
694
|
+
actionDigest: contentHash({
|
|
695
|
+
arguments: candidate.arguments,
|
|
696
|
+
preconditions: candidate.preconditions,
|
|
697
|
+
}),
|
|
698
|
+
expectedVersion: requireInteger(fields["expected_version"], "expected_version"),
|
|
699
|
+
assertion,
|
|
700
|
+
});
|
|
701
|
+
writeJson(res, outcome.kind === "decided" ? 202 : 200, {
|
|
702
|
+
operation_id: outcome.operationId,
|
|
703
|
+
status: outcome.kind === "decided" ? "accepted" : "already_decided",
|
|
704
|
+
decision: outcome.decision,
|
|
705
|
+
...(outcome.kind === "already_decided" ? { decided_by: outcome.actorId } : {}),
|
|
706
|
+
}, { "x-request-id": requestId });
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
// The v1 Workbench page uses these same application services. Keeping the
|
|
710
|
+
// handlers shared avoids a second import/policy implementation while the
|
|
711
|
+
// surrounding v1 dispatcher maps thrown errors to RFC 9457 Problem Details.
|
|
712
|
+
if (rest === "/products/import-drafts") {
|
|
713
|
+
await postProductsImportDraft(req, res);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
const importCommitMatch = /^\/products\/import-drafts\/([^/]+)\/commit$/.exec(rest);
|
|
717
|
+
if (importCommitMatch !== null) {
|
|
718
|
+
await postProductsImportCommit(req, res, pathSegment(importCommitMatch[1] ?? ""));
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (rest === "/policy/drafts") {
|
|
722
|
+
await postPolicyDraft(req, res);
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
const policyCommitMatch = /^\/policy\/drafts\/([^/]+)\/commit$/.exec(rest);
|
|
726
|
+
if (policyCommitMatch !== null) {
|
|
727
|
+
await postPolicyCommit(req, res, pathSegment(policyCommitMatch[1] ?? ""));
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if (rest === "/broadcasts/drafts") {
|
|
731
|
+
const auth = requireActor(req);
|
|
732
|
+
assertWriteGuards(req, auth.sessionId);
|
|
733
|
+
authorizeOrThrow(auth.ctx, "broadcast:draft");
|
|
734
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
735
|
+
"action",
|
|
736
|
+
"broadcast_id",
|
|
737
|
+
"expected_revision",
|
|
738
|
+
"broadcast",
|
|
739
|
+
"reason",
|
|
740
|
+
]);
|
|
741
|
+
const action = requireString(fields["action"], "action");
|
|
742
|
+
if (action !== "publish" && action !== "revise" && action !== "withdraw") {
|
|
743
|
+
throw new ManagementError("invalid_input", "action must be publish, revise or withdraw");
|
|
744
|
+
}
|
|
745
|
+
const scoped = authorizeBroadcastAction(auth.ctx, "broadcast.draft");
|
|
746
|
+
const authorization = {
|
|
747
|
+
actor_id: auth.ctx.actorId,
|
|
748
|
+
actor_role: auth.ctx.role,
|
|
749
|
+
action: "broadcast.draft",
|
|
750
|
+
authorization_generation: scoped.generation,
|
|
751
|
+
matched_grant_ids: scoped.grantIds,
|
|
752
|
+
};
|
|
753
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
754
|
+
let prepared;
|
|
755
|
+
if (action === "publish") {
|
|
756
|
+
const channel = options.prepareBroadcastPublish;
|
|
757
|
+
if (channel === undefined)
|
|
758
|
+
throw new ManagementError("unavailable", "broadcast prepare is unavailable");
|
|
759
|
+
prepared = await channel({
|
|
760
|
+
broadcast: requireObject(fields["broadcast"], "broadcast"),
|
|
761
|
+
authorization,
|
|
762
|
+
...(reason !== undefined ? { reason } : {}),
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
else if (action === "revise") {
|
|
766
|
+
const channel = options.prepareBroadcastRevise;
|
|
767
|
+
if (channel === undefined)
|
|
768
|
+
throw new ManagementError("unavailable", "broadcast prepare is unavailable");
|
|
769
|
+
prepared = await channel({
|
|
770
|
+
broadcastId: requireString(fields["broadcast_id"], "broadcast_id"),
|
|
771
|
+
expectedRevision: requireInteger(fields["expected_revision"], "expected_revision"),
|
|
772
|
+
broadcast: requireObject(fields["broadcast"], "broadcast"),
|
|
773
|
+
authorization,
|
|
774
|
+
...(reason !== undefined ? { reason } : {}),
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
else {
|
|
778
|
+
const channel = options.prepareBroadcastWithdraw;
|
|
779
|
+
if (channel === undefined)
|
|
780
|
+
throw new ManagementError("unavailable", "broadcast prepare is unavailable");
|
|
781
|
+
prepared = await channel({
|
|
782
|
+
broadcastId: requireString(fields["broadcast_id"], "broadcast_id"),
|
|
783
|
+
expectedRevision: requireInteger(fields["expected_revision"], "expected_revision"),
|
|
784
|
+
authorization,
|
|
785
|
+
...(reason !== undefined ? { reason } : {}),
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
writeJson(res, 201, prepared, { "x-request-id": requestId });
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
if (rest === "/change-drafts") {
|
|
792
|
+
const auth = requireActor(req);
|
|
793
|
+
assertWriteGuards(req, auth.sessionId);
|
|
794
|
+
authorizeOrThrow(auth.ctx, "products:draft");
|
|
795
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
796
|
+
"kind",
|
|
797
|
+
"sku",
|
|
798
|
+
"title",
|
|
799
|
+
"money",
|
|
800
|
+
"expected_authority_version",
|
|
801
|
+
"stock",
|
|
802
|
+
"paused",
|
|
803
|
+
"description",
|
|
804
|
+
"category",
|
|
805
|
+
"tags",
|
|
806
|
+
"delivery_attributes",
|
|
807
|
+
"handoff_destination",
|
|
808
|
+
"reason",
|
|
809
|
+
]);
|
|
810
|
+
const kind = requireString(fields["kind"], "kind");
|
|
811
|
+
const sku = requireString(fields["sku"], "sku");
|
|
812
|
+
const createExact = kind === "product_create_exact";
|
|
813
|
+
const scoped = createExact
|
|
814
|
+
? authorizeProductCreateAction(auth.ctx)
|
|
815
|
+
: authorizeProductAction(auth.ctx, "product.draft", [sku]);
|
|
816
|
+
const authorization = {
|
|
817
|
+
actor_id: auth.ctx.actorId,
|
|
818
|
+
actor_role: auth.ctx.role,
|
|
819
|
+
action: createExact ? "product.create" : "product.draft",
|
|
820
|
+
resource_type: createExact ? "merchant" : "product",
|
|
821
|
+
resource_ids: [sku],
|
|
822
|
+
authorization_generation: scoped.generation,
|
|
823
|
+
matched_grant_ids: scoped.grantIds,
|
|
824
|
+
};
|
|
825
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
826
|
+
let prepared;
|
|
827
|
+
if (kind === "inventory_update") {
|
|
828
|
+
const channel = options.prepareInventoryUpdate;
|
|
829
|
+
if (channel === undefined) {
|
|
830
|
+
throw new ManagementError("unavailable", "inventory candidate preparation is unavailable");
|
|
831
|
+
}
|
|
832
|
+
const stock = requireInteger(fields["stock"], "stock");
|
|
833
|
+
if (stock < 0)
|
|
834
|
+
throw new ManagementError("invalid_input", "stock must be non-negative");
|
|
835
|
+
prepared = await channel({
|
|
836
|
+
sku,
|
|
837
|
+
stock,
|
|
838
|
+
authorization,
|
|
839
|
+
...(reason !== undefined ? { reason } : {}),
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
else if (kind === "listing_change") {
|
|
843
|
+
const channel = options.prepareListingChange;
|
|
844
|
+
if (channel === undefined) {
|
|
845
|
+
throw new ManagementError("unavailable", "listing candidate preparation is unavailable");
|
|
846
|
+
}
|
|
847
|
+
if (typeof fields["paused"] !== "boolean") {
|
|
848
|
+
throw new ManagementError("invalid_input", "paused must be a boolean");
|
|
849
|
+
}
|
|
850
|
+
prepared = await channel({
|
|
851
|
+
sku,
|
|
852
|
+
paused: fields["paused"],
|
|
853
|
+
authorization,
|
|
854
|
+
...(reason !== undefined ? { reason } : {}),
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
else if (kind === "product_create_exact") {
|
|
858
|
+
const channel = options.prepareExactProductCreate;
|
|
859
|
+
if (channel === undefined) {
|
|
860
|
+
throw new ManagementError("unavailable", "exact product creation candidate preparation is unavailable");
|
|
861
|
+
}
|
|
862
|
+
prepared = await channel({
|
|
863
|
+
sku,
|
|
864
|
+
title: requireString(fields["title"], "title"),
|
|
865
|
+
money: requireExactMoneyInput(fields["money"]),
|
|
866
|
+
stock: requireNonNegativeInteger(fields["stock"], "stock"),
|
|
867
|
+
expectedAuthorityVersion: requirePositiveInteger(fields["expected_authority_version"], "expected_authority_version"),
|
|
868
|
+
authorization,
|
|
869
|
+
...(typeof fields["description"] === "string"
|
|
870
|
+
? { description: fields["description"] }
|
|
871
|
+
: {}),
|
|
872
|
+
...(typeof fields["category"] === "string" ? { category: fields["category"] } : {}),
|
|
873
|
+
...(fields["tags"] !== undefined
|
|
874
|
+
? { tags: requireStringArray(fields["tags"], "tags") }
|
|
875
|
+
: {}),
|
|
876
|
+
...(fields["delivery_attributes"] !== undefined
|
|
877
|
+
? {
|
|
878
|
+
deliveryAttributes: requireStringArray(fields["delivery_attributes"], "delivery_attributes"),
|
|
879
|
+
}
|
|
880
|
+
: {}),
|
|
881
|
+
...(typeof fields["handoff_destination"] === "string"
|
|
882
|
+
? { handoffDestination: fields["handoff_destination"] }
|
|
883
|
+
: {}),
|
|
884
|
+
...(reason !== undefined ? { reason } : {}),
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
else if (kind === "product_money_update_exact") {
|
|
888
|
+
const channel = options.prepareExactProductMoneyUpdate;
|
|
889
|
+
if (channel === undefined) {
|
|
890
|
+
throw new ManagementError("unavailable", "exact product money candidate preparation is unavailable");
|
|
891
|
+
}
|
|
892
|
+
prepared = await channel({
|
|
893
|
+
sku,
|
|
894
|
+
money: requireExactMoneyInput(fields["money"]),
|
|
895
|
+
expectedAuthorityVersion: requirePositiveInteger(fields["expected_authority_version"], "expected_authority_version"),
|
|
896
|
+
authorization,
|
|
897
|
+
...(reason !== undefined ? { reason } : {}),
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
else {
|
|
901
|
+
throw new ManagementError("invalid_input", "kind must be inventory_update, listing_change, product_create_exact or product_money_update_exact");
|
|
902
|
+
}
|
|
903
|
+
writeJson(res, 201, prepared, { "x-request-id": requestId });
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
if (rest === "/operator-grant-drafts") {
|
|
907
|
+
const auth = requireActor(req);
|
|
908
|
+
assertWriteGuards(req, auth.sessionId);
|
|
909
|
+
authorizeOrThrow(auth.ctx, "grants:manage");
|
|
910
|
+
if (auth.ctx.role !== "owner") {
|
|
911
|
+
throw new ManagementError("forbidden", "only owner can prepare grant changes");
|
|
912
|
+
}
|
|
913
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
914
|
+
"action",
|
|
915
|
+
"subject_id",
|
|
916
|
+
"grant_action",
|
|
917
|
+
"resource_type",
|
|
918
|
+
"resource_selector",
|
|
919
|
+
"expires_at",
|
|
920
|
+
"grant_id",
|
|
921
|
+
"reason",
|
|
922
|
+
]);
|
|
923
|
+
const action = requireString(fields["action"], "action");
|
|
924
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
925
|
+
let prepared;
|
|
926
|
+
if (action === "create") {
|
|
927
|
+
const channel = options.prepareGrantCreate;
|
|
928
|
+
if (channel === undefined)
|
|
929
|
+
throw new ManagementError("unavailable", "grant prepare is unavailable");
|
|
930
|
+
prepared = await channel({
|
|
931
|
+
ownerActorId: auth.ctx.actorId,
|
|
932
|
+
subjectId: requireString(fields["subject_id"], "subject_id"),
|
|
933
|
+
action: requireGrantAction(fields["grant_action"]),
|
|
934
|
+
resourceType: requireGrantResourceType(fields["resource_type"]),
|
|
935
|
+
resourceSelector: requireGrantSelector(fields["resource_selector"]),
|
|
936
|
+
expiresAt: requireString(fields["expires_at"], "expires_at"),
|
|
937
|
+
...(reason !== undefined ? { reason } : {}),
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
else if (action === "revoke") {
|
|
941
|
+
const channel = options.prepareGrantRevoke;
|
|
942
|
+
if (channel === undefined)
|
|
943
|
+
throw new ManagementError("unavailable", "grant prepare is unavailable");
|
|
944
|
+
prepared = await channel({
|
|
945
|
+
ownerActorId: auth.ctx.actorId,
|
|
946
|
+
grantId: requireString(fields["grant_id"], "grant_id"),
|
|
947
|
+
...(reason !== undefined ? { reason } : {}),
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
else {
|
|
951
|
+
throw new ManagementError("invalid_input", "action must be create or revoke");
|
|
952
|
+
}
|
|
953
|
+
writeJson(res, 201, prepared, { "x-request-id": requestId });
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
if (rest === "/promotions/drafts") {
|
|
957
|
+
const auth = requireActor(req);
|
|
958
|
+
assertWriteGuards(req, auth.sessionId);
|
|
959
|
+
authorizeOrThrow(auth.ctx, "products:draft");
|
|
960
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
961
|
+
"sku_refs",
|
|
962
|
+
"rule",
|
|
963
|
+
"audience",
|
|
964
|
+
"starts",
|
|
965
|
+
"ends",
|
|
966
|
+
"timezone",
|
|
967
|
+
"ends_date_inclusive",
|
|
968
|
+
"stackable",
|
|
969
|
+
"priority",
|
|
970
|
+
]);
|
|
971
|
+
const skuRefs = requireStringArray(fields["sku_refs"], "sku_refs");
|
|
972
|
+
authorizeProductAction(auth.ctx, "product.draft", skuRefs);
|
|
973
|
+
const created = requireWorkbenchPromotions().createDraft(auth.ctx.merchantId, {
|
|
974
|
+
skuRefs,
|
|
975
|
+
rule: fields["rule"],
|
|
976
|
+
audience: requirePublicAudience(fields["audience"]),
|
|
977
|
+
starts: requireString(fields["starts"], "starts"),
|
|
978
|
+
ends: requireString(fields["ends"], "ends"),
|
|
979
|
+
timezone: requireString(fields["timezone"], "timezone"),
|
|
980
|
+
...(fields["ends_date_inclusive"] === true ? { endsDateInclusive: true } : {}),
|
|
981
|
+
...(fields["stackable"] === true ? { stackable: true } : {}),
|
|
982
|
+
...(fields["priority"] !== undefined
|
|
983
|
+
? { priority: requireInteger(fields["priority"], "priority") }
|
|
984
|
+
: {}),
|
|
985
|
+
});
|
|
986
|
+
writeJson(res, 201, created, { "x-request-id": requestId });
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const promotionDraftMatch = /^\/promotions\/([^/]+)\/(publish|withdraw)-drafts$/.exec(rest);
|
|
990
|
+
if (promotionDraftMatch !== null) {
|
|
991
|
+
const auth = requireActor(req);
|
|
992
|
+
assertWriteGuards(req, auth.sessionId);
|
|
993
|
+
authorizeOrThrow(auth.ctx, "products:draft");
|
|
994
|
+
const promotionId = pathSegment(promotionDraftMatch[1] ?? "");
|
|
995
|
+
const promotion = requireWorkbenchPromotions().getPromotion(auth.ctx.merchantId, promotionId);
|
|
996
|
+
if (promotion === undefined)
|
|
997
|
+
throw new ManagementError("not_found", "unknown promotion");
|
|
998
|
+
authorizeProductAction(auth.ctx, "product.draft", promotion.sku_refs);
|
|
999
|
+
const fields = objectFields(await readJsonBody(req), [
|
|
1000
|
+
"expected_revision",
|
|
1001
|
+
"reason",
|
|
1002
|
+
"broadcast",
|
|
1003
|
+
]);
|
|
1004
|
+
const expectedRevision = requireInteger(fields["expected_revision"], "expected_revision");
|
|
1005
|
+
const reason = optionalString(fields["reason"], "reason");
|
|
1006
|
+
const publish = promotionDraftMatch[2] === "publish";
|
|
1007
|
+
const channel = publish ? options.preparePromotionPublish : options.preparePromotionWithdraw;
|
|
1008
|
+
if (channel === undefined) {
|
|
1009
|
+
throw new ManagementError("unavailable", "promotion candidate preparation is unavailable");
|
|
1010
|
+
}
|
|
1011
|
+
const broadcast = fields["broadcast"] === undefined
|
|
1012
|
+
? undefined
|
|
1013
|
+
: requireObject(fields["broadcast"], "broadcast");
|
|
1014
|
+
let workflowId;
|
|
1015
|
+
let broadcastAuthorization;
|
|
1016
|
+
if (publish) {
|
|
1017
|
+
if (options.promotionBroadcastWorkflows === undefined) {
|
|
1018
|
+
throw new ManagementError("unavailable", "promotion workflow authority is unavailable");
|
|
1019
|
+
}
|
|
1020
|
+
if (broadcast !== undefined) {
|
|
1021
|
+
authorizeOrThrow(auth.ctx, "broadcast:draft");
|
|
1022
|
+
const scoped = authorizeBroadcastAction(auth.ctx, "broadcast.draft");
|
|
1023
|
+
broadcastAuthorization = {
|
|
1024
|
+
actor_id: auth.ctx.actorId,
|
|
1025
|
+
actor_role: auth.ctx.role,
|
|
1026
|
+
action: "broadcast.draft",
|
|
1027
|
+
authorization_generation: scoped.generation,
|
|
1028
|
+
matched_grant_ids: scoped.grantIds,
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
workflowId = options.promotionBroadcastWorkflows.create({
|
|
1032
|
+
merchantId: auth.ctx.merchantId,
|
|
1033
|
+
promotionId,
|
|
1034
|
+
...(broadcast !== undefined ? { broadcast } : {}),
|
|
1035
|
+
...(broadcastAuthorization !== undefined ? { broadcastAuthorization } : {}),
|
|
1036
|
+
}).workflow_id;
|
|
1037
|
+
}
|
|
1038
|
+
let prepared;
|
|
1039
|
+
try {
|
|
1040
|
+
prepared = await channel({
|
|
1041
|
+
promotionId,
|
|
1042
|
+
expectedRevision,
|
|
1043
|
+
...(workflowId !== undefined ? { workflowId } : {}),
|
|
1044
|
+
...(broadcastAuthorization !== undefined ? { broadcastAuthorization } : {}),
|
|
1045
|
+
...(reason !== undefined ? { reason } : {}),
|
|
1046
|
+
});
|
|
1047
|
+
if (workflowId !== undefined) {
|
|
1048
|
+
const candidateId = candidateIdFromPreparation(prepared);
|
|
1049
|
+
if (!options.promotionBroadcastWorkflows.bindPromotionCandidate(auth.ctx.merchantId, workflowId, candidateId)) {
|
|
1050
|
+
throw new Error("promotion workflow candidate binding failed");
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
catch (error) {
|
|
1055
|
+
if (workflowId !== undefined) {
|
|
1056
|
+
options.promotionBroadcastWorkflows?.markFailed(auth.ctx.merchantId, workflowId, error instanceof Error ? error.message : String(error));
|
|
1057
|
+
}
|
|
1058
|
+
throw error;
|
|
1059
|
+
}
|
|
1060
|
+
const response = workflowId !== undefined &&
|
|
1061
|
+
prepared !== null &&
|
|
1062
|
+
typeof prepared === "object" &&
|
|
1063
|
+
!Array.isArray(prepared)
|
|
1064
|
+
? { ...prepared, workflow_id: workflowId }
|
|
1065
|
+
: prepared;
|
|
1066
|
+
writeJson(res, 201, response, { "x-request-id": requestId });
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const retryPromotionBroadcast = /^\/promotion-workflows\/([^/]+)\/retry-broadcast$/.exec(rest);
|
|
1070
|
+
if (retryPromotionBroadcast !== null) {
|
|
1071
|
+
const auth = requireActor(req);
|
|
1072
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1073
|
+
authorizeOrThrow(auth.ctx, "broadcast:draft");
|
|
1074
|
+
const workflows = options.promotionBroadcastWorkflows;
|
|
1075
|
+
const prepare = options.prepareBroadcastPublish;
|
|
1076
|
+
if (workflows === undefined || prepare === undefined) {
|
|
1077
|
+
throw new ManagementError("unavailable", "promotion broadcast retry is unavailable");
|
|
1078
|
+
}
|
|
1079
|
+
const workflowId = pathSegment(retryPromotionBroadcast[1] ?? "");
|
|
1080
|
+
if (workflows.get(auth.ctx.merchantId, workflowId)?.status !== "partial") {
|
|
1081
|
+
throw new ManagementError("conflict", "workflow is not in a retryable partial state");
|
|
1082
|
+
}
|
|
1083
|
+
const broadcast = workflows.broadcastContent(auth.ctx.merchantId, workflowId);
|
|
1084
|
+
if (broadcast === undefined) {
|
|
1085
|
+
throw new ManagementError("conflict", "workflow is not in a retryable partial state");
|
|
1086
|
+
}
|
|
1087
|
+
const scoped = authorizeBroadcastAction(auth.ctx, "broadcast.draft");
|
|
1088
|
+
const authorization = {
|
|
1089
|
+
actor_id: auth.ctx.actorId,
|
|
1090
|
+
actor_role: auth.ctx.role,
|
|
1091
|
+
action: "broadcast.draft",
|
|
1092
|
+
authorization_generation: scoped.generation,
|
|
1093
|
+
matched_grant_ids: scoped.grantIds,
|
|
1094
|
+
};
|
|
1095
|
+
const prepared = await prepare({
|
|
1096
|
+
broadcast,
|
|
1097
|
+
authorization,
|
|
1098
|
+
workflowId,
|
|
1099
|
+
reason: "retry promotion workflow broadcast draft only",
|
|
1100
|
+
});
|
|
1101
|
+
const candidateId = candidateIdFromPreparation(prepared);
|
|
1102
|
+
const workflow = workflows.markBroadcastPending(auth.ctx.merchantId, workflowId, candidateId);
|
|
1103
|
+
writeJson(res, 201, {
|
|
1104
|
+
...prepared,
|
|
1105
|
+
workflow,
|
|
1106
|
+
}, { "x-request-id": requestId });
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
const acknowledgeAlert = /^\/alerts\/([^/]+)\/acknowledgements$/.exec(rest);
|
|
1110
|
+
if (acknowledgeAlert !== null) {
|
|
1111
|
+
const auth = requireActor(req);
|
|
1112
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1113
|
+
authorizeOrThrow(auth.ctx, "alerts:ack");
|
|
1114
|
+
objectFields(await readJsonBody(req), []);
|
|
1115
|
+
const store = options.workbenchReconciliation;
|
|
1116
|
+
if (store === undefined) {
|
|
1117
|
+
throw new ManagementError("unavailable", "Workbench alert authority is not configured");
|
|
1118
|
+
}
|
|
1119
|
+
const alertId = pathSegment(acknowledgeAlert[1] ?? "");
|
|
1120
|
+
if (!store.acknowledgeAlert(auth.ctx.merchantId, alertId, auth.ctx.actorId)) {
|
|
1121
|
+
throw new ManagementError("not_found", "unknown alert");
|
|
1122
|
+
}
|
|
1123
|
+
writeJson(res, 200, { alert_id: alertId, acknowledged: true }, { "x-request-id": requestId });
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench 写路由不存在或尚未实现。");
|
|
1127
|
+
}
|
|
1128
|
+
function requireWorkbenchConfirmations() {
|
|
1129
|
+
if (options.workbenchConfirmations === undefined) {
|
|
1130
|
+
throw new WorkbenchConfirmationError("credential_unavailable", "trusted confirmation channel is not configured");
|
|
1131
|
+
}
|
|
1132
|
+
return options.workbenchConfirmations;
|
|
1133
|
+
}
|
|
1134
|
+
function requireWorkbenchFeed() {
|
|
1135
|
+
if (options.workbenchFeed === undefined) {
|
|
1136
|
+
throw new ManagementError("unavailable", "Workbench Feed authority is not configured");
|
|
1137
|
+
}
|
|
1138
|
+
return options.workbenchFeed;
|
|
1139
|
+
}
|
|
1140
|
+
function requireWorkbenchGrants() {
|
|
1141
|
+
if (options.workbenchGrants === undefined) {
|
|
1142
|
+
throw new ManagementError("unavailable", "Workbench grant authority is not configured");
|
|
1143
|
+
}
|
|
1144
|
+
return options.workbenchGrants;
|
|
1145
|
+
}
|
|
1146
|
+
function requireWorkbenchPromotions() {
|
|
1147
|
+
if (options.workbenchPromotions === undefined) {
|
|
1148
|
+
throw new ManagementError("unavailable", "Workbench promotion authority is not configured");
|
|
1149
|
+
}
|
|
1150
|
+
return options.workbenchPromotions;
|
|
1151
|
+
}
|
|
1152
|
+
function authorizeBroadcastAction(actor, action) {
|
|
1153
|
+
if (actor.role === "owner") {
|
|
1154
|
+
return {
|
|
1155
|
+
generation: options.workbenchGrants?.authorizationGeneration(actor.merchantId, actor.actorId) ?? 0,
|
|
1156
|
+
grantIds: [],
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
const grants = options.workbenchGrants;
|
|
1160
|
+
if (grants === undefined)
|
|
1161
|
+
throw new ManagementError("forbidden", "scoped grants are unavailable");
|
|
1162
|
+
const result = grants.authorize(actor, { action, resourceType: "merchant" });
|
|
1163
|
+
if (!result.authorized)
|
|
1164
|
+
throw new ManagementError("forbidden", `missing scoped grant: ${action}`);
|
|
1165
|
+
return { generation: result.generation, grantIds: result.grantIds };
|
|
1166
|
+
}
|
|
1167
|
+
function authorizeProductAction(actor, action, resourceIds) {
|
|
1168
|
+
if (actor.role === "owner") {
|
|
1169
|
+
return {
|
|
1170
|
+
generation: options.workbenchGrants?.authorizationGeneration(actor.merchantId, actor.actorId) ?? 0,
|
|
1171
|
+
grantIds: [],
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
const grants = options.workbenchGrants;
|
|
1175
|
+
if (grants === undefined)
|
|
1176
|
+
throw new ManagementError("forbidden", "scoped grants are unavailable");
|
|
1177
|
+
const result = grants.authorize(actor, {
|
|
1178
|
+
action,
|
|
1179
|
+
resourceType: "product",
|
|
1180
|
+
resourceIds,
|
|
1181
|
+
});
|
|
1182
|
+
if (!result.authorized)
|
|
1183
|
+
throw new ManagementError("forbidden", `missing scoped grant: ${action}`);
|
|
1184
|
+
return { generation: result.generation, grantIds: result.grantIds };
|
|
1185
|
+
}
|
|
1186
|
+
function authorizeProductCreateAction(actor) {
|
|
1187
|
+
if (actor.role === "owner") {
|
|
1188
|
+
return {
|
|
1189
|
+
generation: options.workbenchGrants?.authorizationGeneration(actor.merchantId, actor.actorId) ?? 0,
|
|
1190
|
+
grantIds: [],
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
const grants = options.workbenchGrants;
|
|
1194
|
+
if (grants === undefined)
|
|
1195
|
+
throw new ManagementError("forbidden", "scoped grants are unavailable");
|
|
1196
|
+
const result = grants.authorize(actor, {
|
|
1197
|
+
action: "product.create",
|
|
1198
|
+
resourceType: "merchant",
|
|
1199
|
+
});
|
|
1200
|
+
if (!result.authorized) {
|
|
1201
|
+
throw new ManagementError("forbidden", "missing scoped grant: product.create");
|
|
1202
|
+
}
|
|
1203
|
+
return { generation: result.generation, grantIds: result.grantIds };
|
|
1204
|
+
}
|
|
1205
|
+
function authorizeBroadcastCandidate(actor, candidate, action) {
|
|
1206
|
+
if (!Object.values(BROADCAST_TOOLS).includes(candidate.tool)) {
|
|
1207
|
+
return undefined;
|
|
1208
|
+
}
|
|
1209
|
+
authorizeOrThrow(actor, "broadcast:decide");
|
|
1210
|
+
const scoped = authorizeBroadcastAction(actor, action);
|
|
1211
|
+
return {
|
|
1212
|
+
actor_id: actor.actorId,
|
|
1213
|
+
actor_role: actor.role,
|
|
1214
|
+
action,
|
|
1215
|
+
authorization_generation: scoped.generation,
|
|
1216
|
+
matched_grant_ids: scoped.grantIds,
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
function authorizeGrantCandidate(actor, candidate) {
|
|
1220
|
+
if (!Object.values(GRANT_TOOLS).includes(candidate.tool)) {
|
|
1221
|
+
return undefined;
|
|
1222
|
+
}
|
|
1223
|
+
authorizeOrThrow(actor, "grants:manage");
|
|
1224
|
+
if (actor.role !== "owner") {
|
|
1225
|
+
throw new ManagementError("forbidden", "only owner can decide grant changes");
|
|
1226
|
+
}
|
|
1227
|
+
return {
|
|
1228
|
+
actor_id: actor.actorId,
|
|
1229
|
+
actor_role: actor.role,
|
|
1230
|
+
action: "grants.manage",
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
function authorizePromotionCandidate(actor, candidate) {
|
|
1234
|
+
if (!Object.values(PROMOTION_TOOLS).includes(candidate.tool)) {
|
|
1235
|
+
return undefined;
|
|
1236
|
+
}
|
|
1237
|
+
authorizeOrThrow(actor, "products:decide");
|
|
1238
|
+
const promotionId = String(candidate.arguments["promotion_id"] ?? "");
|
|
1239
|
+
const promotion = requireWorkbenchPromotions().getPromotion(actor.merchantId, promotionId);
|
|
1240
|
+
if (promotion === undefined)
|
|
1241
|
+
throw new ManagementError("not_found", "unknown promotion");
|
|
1242
|
+
const scoped = authorizeProductAction(actor, "product.decide", promotion.sku_refs);
|
|
1243
|
+
return {
|
|
1244
|
+
actor_id: actor.actorId,
|
|
1245
|
+
actor_role: actor.role,
|
|
1246
|
+
action: "product.decide",
|
|
1247
|
+
resource_type: "product",
|
|
1248
|
+
resource_ids: promotion.sku_refs,
|
|
1249
|
+
authorization_generation: scoped.generation,
|
|
1250
|
+
matched_grant_ids: scoped.grantIds,
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
function authorizeProductCandidate(actor, candidate) {
|
|
1254
|
+
const productScopedTools = new Set([
|
|
1255
|
+
"draft_product_change",
|
|
1256
|
+
"kiwi_merchant_prepare_product_update",
|
|
1257
|
+
"kiwi_merchant_prepare_inventory_update",
|
|
1258
|
+
"kiwi_merchant_prepare_listing_change",
|
|
1259
|
+
EXACT_PRODUCT_TOOLS.updateMoney,
|
|
1260
|
+
]);
|
|
1261
|
+
const createsProduct = candidate.tool === "kiwi_merchant_prepare_product_create" ||
|
|
1262
|
+
candidate.tool === EXACT_PRODUCT_TOOLS.create;
|
|
1263
|
+
if (!createsProduct && !productScopedTools.has(candidate.tool))
|
|
1264
|
+
return undefined;
|
|
1265
|
+
authorizeOrThrow(actor, "products:decide");
|
|
1266
|
+
if (createsProduct) {
|
|
1267
|
+
const sku = candidate.tool === EXACT_PRODUCT_TOOLS.create
|
|
1268
|
+
? requireString(candidate.arguments["sku"], "candidate sku")
|
|
1269
|
+
: requireString(requireObject(candidate.arguments["product"], "candidate product")["sku"], "candidate product.sku");
|
|
1270
|
+
const generation = options.workbenchGrants?.authorizationGeneration(actor.merchantId, actor.actorId) ?? 0;
|
|
1271
|
+
if (actor.role !== "owner") {
|
|
1272
|
+
const grants = options.workbenchGrants;
|
|
1273
|
+
if (grants === undefined) {
|
|
1274
|
+
throw new ManagementError("forbidden", "scoped grants are unavailable");
|
|
1275
|
+
}
|
|
1276
|
+
const result = grants.authorize(actor, {
|
|
1277
|
+
action: "product.create",
|
|
1278
|
+
resourceType: "merchant",
|
|
1279
|
+
});
|
|
1280
|
+
if (!result.authorized) {
|
|
1281
|
+
throw new ManagementError("forbidden", "missing scoped grant: product.create");
|
|
1282
|
+
}
|
|
1283
|
+
return {
|
|
1284
|
+
actor_id: actor.actorId,
|
|
1285
|
+
actor_role: actor.role,
|
|
1286
|
+
action: "product.create",
|
|
1287
|
+
resource_type: "merchant",
|
|
1288
|
+
resource_ids: [sku],
|
|
1289
|
+
authorization_generation: result.generation,
|
|
1290
|
+
matched_grant_ids: result.grantIds,
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
return {
|
|
1294
|
+
actor_id: actor.actorId,
|
|
1295
|
+
actor_role: actor.role,
|
|
1296
|
+
action: "product.create",
|
|
1297
|
+
resource_type: "merchant",
|
|
1298
|
+
resource_ids: [sku],
|
|
1299
|
+
authorization_generation: generation,
|
|
1300
|
+
matched_grant_ids: [],
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
const sku = requireString(candidate.arguments["sku"], "candidate sku");
|
|
1304
|
+
const scoped = authorizeProductAction(actor, "product.decide", [sku]);
|
|
1305
|
+
return {
|
|
1306
|
+
actor_id: actor.actorId,
|
|
1307
|
+
actor_role: actor.role,
|
|
1308
|
+
action: "product.decide",
|
|
1309
|
+
resource_type: "product",
|
|
1310
|
+
resource_ids: [sku],
|
|
1311
|
+
authorization_generation: scoped.generation,
|
|
1312
|
+
matched_grant_ids: scoped.grantIds,
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
function authorizeServiceControlCandidate(actor, candidate) {
|
|
1316
|
+
if (candidate.tool !== SERVICE_CONTROL_TOOLS.resume)
|
|
1317
|
+
return undefined;
|
|
1318
|
+
authorizeOrThrow(actor, "service:resume");
|
|
1319
|
+
if (actor.role !== "owner") {
|
|
1320
|
+
throw new ManagementError("forbidden", "only owner can decide service recovery");
|
|
1321
|
+
}
|
|
1322
|
+
return {
|
|
1323
|
+
actor_id: actor.actorId,
|
|
1324
|
+
actor_role: actor.role,
|
|
1325
|
+
action: "service.resume",
|
|
1326
|
+
authorization_generation: 0,
|
|
1327
|
+
matched_grant_ids: [],
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
async function requireRegistrationAuthorization(req, actor) {
|
|
1331
|
+
const registration = options.webauthnRegistration;
|
|
1332
|
+
if (registration === undefined || !(await registration.authorize(req, actor))) {
|
|
1333
|
+
throw new WorkbenchConfirmationError("credential_unavailable", "independent WebAuthn registration authorization is unavailable");
|
|
1334
|
+
}
|
|
1335
|
+
return registration;
|
|
1336
|
+
}
|
|
1337
|
+
async function routeGet(req, res, url, rest) {
|
|
1338
|
+
if (rest === "/session") {
|
|
1339
|
+
const auth = requireActor(req);
|
|
1340
|
+
writeJson(res, 200, {
|
|
1341
|
+
api_version: `${MANAGEMENT_API_MAJOR}`,
|
|
1342
|
+
actor_id: auth.session.principal_id,
|
|
1343
|
+
merchant_id: auth.session.merchant_id,
|
|
1344
|
+
role: auth.session.role,
|
|
1345
|
+
expires_at: auth.session.expires_at,
|
|
1346
|
+
csrf_token: csrfTokenFor(auth.sessionId),
|
|
1347
|
+
});
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
if (rest === "/status") {
|
|
1351
|
+
const auth = requireActor(req);
|
|
1352
|
+
writeJson(res, 200, await readService.getStatus(auth.ctx));
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
if (rest === "/products") {
|
|
1356
|
+
const auth = requireActor(req);
|
|
1357
|
+
writeJson(res, 200, await readService.listProducts(auth.ctx, pageQuery(url)));
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
if (rest === "/onboarding") {
|
|
1361
|
+
const auth = requireActor(req);
|
|
1362
|
+
authorizeOrThrow(auth.ctx, "onboarding:manage");
|
|
1363
|
+
const channel = onboardingChannel();
|
|
1364
|
+
const record = channel.store.activeRecord(auth.ctx.merchantId) ?? null;
|
|
1365
|
+
writeJson(res, 200, { record, plan: record === null ? null : planWizard(record) });
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
if (rest === "/policy") {
|
|
1369
|
+
const auth = requireActor(req);
|
|
1370
|
+
writeJson(res, 200, await readService.getPolicy(auth.ctx));
|
|
1371
|
+
return;
|
|
1372
|
+
}
|
|
1373
|
+
if (rest === "/approvals") {
|
|
1374
|
+
const auth = requireActor(req);
|
|
1375
|
+
writeJson(res, 200, await readService.listApprovals(auth.ctx, pageQuery(url)));
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
const approvalMatch = /^\/approvals\/([^/]+)$/.exec(rest);
|
|
1379
|
+
if (approvalMatch !== null) {
|
|
1380
|
+
const auth = requireActor(req);
|
|
1381
|
+
writeJson(res, 200, await readService.getApproval(auth.ctx, pathSegment(approvalMatch[1] ?? "")));
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
const operationMatch = /^\/operations\/([^/]+)$/.exec(rest);
|
|
1385
|
+
if (operationMatch !== null) {
|
|
1386
|
+
const auth = requireActor(req);
|
|
1387
|
+
writeJson(res, 200, readService.getOperation(auth.ctx, pathSegment(operationMatch[1] ?? "")));
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
if (isKnownPath(rest)) {
|
|
1391
|
+
writeJson(res, 405, errorBody("invalid_input", "method not allowed"), { allow: "POST" });
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
writeJson(res, 404, errorBody("not_found", "unknown management api path"));
|
|
1395
|
+
}
|
|
1396
|
+
// ── 写路由(BD §10.1;每条都过 CSRF/Origin + 幂等 + 服务层复检)──────────
|
|
1397
|
+
async function routePost(req, res, rest) {
|
|
1398
|
+
if (rest === "/confirmations") {
|
|
1399
|
+
await postConfirmation(req, res);
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
if (rest === "/onboarding/intents") {
|
|
1403
|
+
await postOnboardingIntent(req, res);
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
const advanceMatch = /^\/onboarding\/([^/]+)\/advance$/.exec(rest);
|
|
1407
|
+
if (advanceMatch !== null) {
|
|
1408
|
+
await postOnboardingAdvance(req, res, pathSegment(advanceMatch[1] ?? ""));
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
const cancelMatch = /^\/onboarding\/([^/]+)\/cancel$/.exec(rest);
|
|
1412
|
+
if (cancelMatch !== null) {
|
|
1413
|
+
await postOnboardingCancel(req, res, pathSegment(cancelMatch[1] ?? ""));
|
|
1414
|
+
return;
|
|
1415
|
+
}
|
|
1416
|
+
const refusedMatch = /^\/onboarding\/([^/]+)\/consent-refused$/.exec(rest);
|
|
1417
|
+
if (refusedMatch !== null) {
|
|
1418
|
+
await postOnboardingConsentRefused(req, res, pathSegment(refusedMatch[1] ?? ""));
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
if (rest === "/service/pause") {
|
|
1422
|
+
await postServicePause(req, res);
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
if (rest === "/service/resume") {
|
|
1426
|
+
await postServiceResume(req, res);
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
const decisionMatch = /^\/approvals\/([^/]+)\/(approve|reject)$/.exec(rest);
|
|
1430
|
+
if (decisionMatch !== null) {
|
|
1431
|
+
await postApprovalDecision(req, res, pathSegment(decisionMatch[1] ?? ""), decisionMatch[2] === "approve");
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
if (rest === "/products/import-drafts") {
|
|
1435
|
+
await postProductsImportDraft(req, res);
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
const importCommitMatch = /^\/products\/import-drafts\/([^/]+)\/commit$/.exec(rest);
|
|
1439
|
+
if (importCommitMatch !== null) {
|
|
1440
|
+
await postProductsImportCommit(req, res, pathSegment(importCommitMatch[1] ?? ""));
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
if (rest === "/policy/drafts") {
|
|
1444
|
+
await postPolicyDraft(req, res);
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
const policyCommitMatch = /^\/policy\/drafts\/([^/]+)\/commit$/.exec(rest);
|
|
1448
|
+
if (policyCommitMatch !== null) {
|
|
1449
|
+
await postPolicyCommit(req, res, pathSegment(policyCommitMatch[1] ?? ""));
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
if (isKnownPath(rest)) {
|
|
1453
|
+
writeJson(res, 405, errorBody("invalid_input", "method not allowed"), { allow: "GET" });
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1456
|
+
writeJson(res, 404, errorBody("not_found", "unknown management api path"));
|
|
1457
|
+
}
|
|
1458
|
+
/**
|
|
1459
|
+
* POST /confirmations —— 生成短时单次确认引用(BD §10.1)。
|
|
1460
|
+
* 候选审批确认绑定候选摘要/主体/商家/动作(core 凭证存储,执行层核销);
|
|
1461
|
+
* 非候选命令目前仅 service.resume(管理确认表,单次核销)。
|
|
1462
|
+
* **确认引用不能由普通对话工具申请**(§7.3)——本端点只接受页面会话。
|
|
1463
|
+
*/
|
|
1464
|
+
// ── 开通向导(M4 §5.4)──────────────────────────────────────────────
|
|
1465
|
+
//
|
|
1466
|
+
// 写在这里而不是 /admin/*:那是"审核面"(一次性确认凭证、无 CSRF),本 API 面
|
|
1467
|
+
// 已有会话→主体 + CSRF + 幂等四元组 + 错误码映射,向导是商家自己的操作(BD §9)。
|
|
1468
|
+
/** 向导依赖;未配置 → 503(不伪造一个能用的向导)。 */
|
|
1469
|
+
function onboardingChannel() {
|
|
1470
|
+
const channel = options.onboarding;
|
|
1471
|
+
if (channel === undefined) {
|
|
1472
|
+
throw new ManagementError("unavailable", "onboarding is not configured");
|
|
1473
|
+
}
|
|
1474
|
+
return channel;
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* POST /onboarding/intents —— 打开/复用开通意图(§7.1:重复点击只返回同一条)。
|
|
1478
|
+
*
|
|
1479
|
+
* 幂等:同键同摘要回原结果、同键不同摘要 409(与其它写命令同口径)。
|
|
1480
|
+
*/
|
|
1481
|
+
async function postOnboardingIntent(req, res) {
|
|
1482
|
+
const auth = requireActor(req);
|
|
1483
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1484
|
+
const body = await readJsonBody(req);
|
|
1485
|
+
const fields = objectFields(body, [
|
|
1486
|
+
"intent_id",
|
|
1487
|
+
"version_digest",
|
|
1488
|
+
"idempotency_key",
|
|
1489
|
+
"new_generation",
|
|
1490
|
+
]);
|
|
1491
|
+
authorizeOrThrow(auth.ctx, "onboarding:manage");
|
|
1492
|
+
const channel = onboardingChannel();
|
|
1493
|
+
const intentId = requireString(fields["intent_id"], "intent_id");
|
|
1494
|
+
const versionDigest = requireString(fields["version_digest"], "version_digest");
|
|
1495
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
1496
|
+
const newGeneration = fields["new_generation"] === true;
|
|
1497
|
+
const requestDigest = managementRequestDigest({
|
|
1498
|
+
intent_id: intentId,
|
|
1499
|
+
version_digest: versionDigest,
|
|
1500
|
+
new_generation: newGeneration,
|
|
1501
|
+
});
|
|
1502
|
+
const probed = operations.probe({
|
|
1503
|
+
merchantId: auth.ctx.merchantId,
|
|
1504
|
+
actorId: auth.ctx.actorId,
|
|
1505
|
+
commandType: "onboarding.open_intent",
|
|
1506
|
+
idempotencyKey,
|
|
1507
|
+
requestDigest,
|
|
1508
|
+
});
|
|
1509
|
+
if (probed.kind === "replay") {
|
|
1510
|
+
writeJson(res, 200, probed.receipt);
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
if (probed.kind === "conflict") {
|
|
1514
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
const begun = operations.begin({
|
|
1518
|
+
merchantId: auth.ctx.merchantId,
|
|
1519
|
+
actorId: auth.ctx.actorId,
|
|
1520
|
+
commandType: "onboarding.open_intent",
|
|
1521
|
+
idempotencyKey,
|
|
1522
|
+
requestDigest,
|
|
1523
|
+
});
|
|
1524
|
+
if (begun.kind === "replay") {
|
|
1525
|
+
writeJson(res, 200, begun.receipt);
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
if (begun.kind === "conflict") {
|
|
1529
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
try {
|
|
1533
|
+
const record = channel.store.openIntent({
|
|
1534
|
+
merchantId: auth.ctx.merchantId,
|
|
1535
|
+
intentId,
|
|
1536
|
+
versionDigest,
|
|
1537
|
+
idempotencyKey: `onb-open:${idempotencyKey}`,
|
|
1538
|
+
requestDigest,
|
|
1539
|
+
...(newGeneration ? { newGeneration: true } : {}),
|
|
1540
|
+
});
|
|
1541
|
+
const receipt = {
|
|
1542
|
+
...staticReceipt(begun.operationId, "onboarding.open_intent", "succeeded"),
|
|
1543
|
+
resource_ref: `onboarding:${record.recordId}`,
|
|
1544
|
+
completed_at: now().toISOString(),
|
|
1545
|
+
};
|
|
1546
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
1547
|
+
writeJson(res, 200, { ...receipt, record });
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
catch (err) {
|
|
1551
|
+
// 存储层拒绝(非法输入/冲突)→ 释放占位;未产生业务效果,可修正后原键重试。
|
|
1552
|
+
operations.release(begun.operationId);
|
|
1553
|
+
respondError(res, err);
|
|
1554
|
+
return;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
/**
|
|
1558
|
+
* POST /onboarding/{id}/advance —— 推进**一步**(§5.4)。
|
|
1559
|
+
*
|
|
1560
|
+
* 证据纪律(T007/T029):请求体**只能给 `note`(留痕用)**,不能给权威证据。
|
|
1561
|
+
* 需要权威证据的步骤由服务端 `platformEvidence` 适配器去平台取回执;适配器未配置
|
|
1562
|
+
* 或取不到 → **不推进**(503 / 拒绝),绝不接受客户端自称的"查询回执"。
|
|
1563
|
+
*/
|
|
1564
|
+
async function postOnboardingAdvance(req, res, recordId) {
|
|
1565
|
+
const auth = requireActor(req);
|
|
1566
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1567
|
+
const body = await readJsonBody(req);
|
|
1568
|
+
const fields = objectFields(body, ["step", "expected_revision", "idempotency_key", "note"]);
|
|
1569
|
+
authorizeOrThrow(auth.ctx, "onboarding:manage");
|
|
1570
|
+
const channel = onboardingChannel();
|
|
1571
|
+
const stepId = requireString(fields["step"], "step");
|
|
1572
|
+
const expectedRevision = requireInteger(fields["expected_revision"], "expected_revision");
|
|
1573
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
1574
|
+
const note = optionalString(fields["note"], "note");
|
|
1575
|
+
const record = channel.store.getRecord(recordId);
|
|
1576
|
+
if (record === undefined || record.merchantId !== auth.ctx.merchantId) {
|
|
1577
|
+
// 不区分"不存在"与"不归本商家"(防枚举)
|
|
1578
|
+
throw new ManagementError("not_found", `unknown onboarding record: ${recordId}`);
|
|
1579
|
+
}
|
|
1580
|
+
const definition = WIZARD_STEPS.find((step) => step.id === stepId);
|
|
1581
|
+
if (definition === undefined) {
|
|
1582
|
+
throw new ManagementError("invalid_input", `unknown wizard step: ${stepId}`);
|
|
1583
|
+
}
|
|
1584
|
+
const requestDigest = managementRequestDigest({
|
|
1585
|
+
record_id: recordId,
|
|
1586
|
+
step: stepId,
|
|
1587
|
+
expected_revision: expectedRevision,
|
|
1588
|
+
});
|
|
1589
|
+
const probed = operations.probe({
|
|
1590
|
+
merchantId: auth.ctx.merchantId,
|
|
1591
|
+
actorId: auth.ctx.actorId,
|
|
1592
|
+
commandType: "onboarding.advance",
|
|
1593
|
+
idempotencyKey,
|
|
1594
|
+
requestDigest,
|
|
1595
|
+
});
|
|
1596
|
+
if (probed.kind === "replay") {
|
|
1597
|
+
writeJson(res, 200, probed.receipt);
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
if (probed.kind === "conflict") {
|
|
1601
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
const begun = operations.begin({
|
|
1605
|
+
merchantId: auth.ctx.merchantId,
|
|
1606
|
+
actorId: auth.ctx.actorId,
|
|
1607
|
+
commandType: "onboarding.advance",
|
|
1608
|
+
idempotencyKey,
|
|
1609
|
+
requestDigest,
|
|
1610
|
+
});
|
|
1611
|
+
if (begun.kind === "replay") {
|
|
1612
|
+
writeJson(res, 200, begun.receipt);
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
if (begun.kind === "conflict") {
|
|
1616
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
try {
|
|
1620
|
+
// 证据获取与准入判定排在**幂等探测之后**:同键重放必须先回原回执(UC20),
|
|
1621
|
+
// 不能被"适配器未配置/取不到回执"的 503 抢先——那是两条不同的语义。
|
|
1622
|
+
let evidence;
|
|
1623
|
+
if (definition.requiresAuthoritativeEvidence) {
|
|
1624
|
+
const adapter = channel.platformEvidence;
|
|
1625
|
+
if (adapter === undefined) {
|
|
1626
|
+
operations.release(begun.operationId);
|
|
1627
|
+
throw new ManagementError("tool_binding_unavailable", `step ${stepId} needs authoritative platform evidence; the platform adapter is not configured`);
|
|
1628
|
+
}
|
|
1629
|
+
const obtained = await adapter({ stepId, recordId: record.recordId });
|
|
1630
|
+
if (requestsDisabledLocalImplementation(obtained)) {
|
|
1631
|
+
throw new ManagementError("unavailable", `platform capability ${obtained.code || "cloud_service_unavailable"} is unavailable; local implementation fallback is disabled`);
|
|
1632
|
+
}
|
|
1633
|
+
if (obtained?.kind === "platform_failure") {
|
|
1634
|
+
throw new ManagementError("unavailable", `platform did not return an authoritative receipt (${obtained.code || "platform_failure"})`);
|
|
1635
|
+
}
|
|
1636
|
+
if (obtained === undefined) {
|
|
1637
|
+
operations.release(begun.operationId);
|
|
1638
|
+
throw new ManagementError("unavailable", `platform did not return an authoritative receipt for step ${stepId}`);
|
|
1639
|
+
}
|
|
1640
|
+
evidence = obtained;
|
|
1641
|
+
}
|
|
1642
|
+
else if (note !== undefined) {
|
|
1643
|
+
// 非权威留痕(例如商家拒绝的原因):记录,但不推进任何状态(§7.2)。
|
|
1644
|
+
channel.store.recordPendingEvidence(record.recordId, {
|
|
1645
|
+
kind: "text_claim",
|
|
1646
|
+
summary: note,
|
|
1647
|
+
observedAt: now().toISOString(),
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
// 提交前准入判定(状态不对/证据不足都在写之前拒,避免半途改状态)。
|
|
1651
|
+
const verdict = checkStepSubmission(record, definition.id, evidence);
|
|
1652
|
+
if (!verdict.ok) {
|
|
1653
|
+
operations.release(begun.operationId);
|
|
1654
|
+
throw new ManagementError(verdict.code === "evidence_not_authoritative" ? "forbidden" : "conflict", verdict.reason);
|
|
1655
|
+
}
|
|
1656
|
+
const advanced = channel.store.advance({
|
|
1657
|
+
recordId: record.recordId,
|
|
1658
|
+
expectedRevision,
|
|
1659
|
+
nextStatus: definition.advancesTo,
|
|
1660
|
+
step: definition.id,
|
|
1661
|
+
...(evidence !== undefined ? { evidence } : {}),
|
|
1662
|
+
});
|
|
1663
|
+
const receipt = {
|
|
1664
|
+
...staticReceipt(begun.operationId, "onboarding.advance", "succeeded"),
|
|
1665
|
+
resource_ref: `onboarding:${advanced.recordId}`,
|
|
1666
|
+
result_revision: advanced.revision,
|
|
1667
|
+
completed_at: now().toISOString(),
|
|
1668
|
+
};
|
|
1669
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
1670
|
+
writeJson(res, 200, { ...receipt, record: advanced });
|
|
1671
|
+
return;
|
|
1672
|
+
}
|
|
1673
|
+
catch (err) {
|
|
1674
|
+
// 状态/证据被存储层拒 → 未产生效果,释放占位。
|
|
1675
|
+
operations.release(begun.operationId);
|
|
1676
|
+
respondError(res, err);
|
|
1677
|
+
return;
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
/** POST /onboarding/{id}/cancel —— 撤销开通意图(终态;不自动删已有云资源)。 */
|
|
1681
|
+
async function postOnboardingCancel(req, res, recordId) {
|
|
1682
|
+
await onboardSimpleCommand(res, req, recordId, "onboarding.cancel", (store, record) => store.cancel(record.recordId, record.revision));
|
|
1683
|
+
}
|
|
1684
|
+
/** POST /onboarding/{id}/consent-refused —— T007:商家拒绝授权 = 保持等待。 */
|
|
1685
|
+
async function postOnboardingConsentRefused(req, res, recordId) {
|
|
1686
|
+
await onboardSimpleCommand(res, req, recordId, "onboarding.consent_refused", (store, record, note) => store.recordConsentRefused(record.recordId, record.revision, note !== undefined ? { note } : {}));
|
|
1687
|
+
}
|
|
1688
|
+
/** cancel / consent-refused 共用的薄编排(同幂等口径,避免两份重复代码)。 */
|
|
1689
|
+
async function onboardSimpleCommand(res, req, recordId, commandType, run) {
|
|
1690
|
+
const auth = requireActor(req);
|
|
1691
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1692
|
+
const body = await readJsonBody(req);
|
|
1693
|
+
const fields = objectFields(body, ["expected_revision", "idempotency_key", "note"]);
|
|
1694
|
+
authorizeOrThrow(auth.ctx, "onboarding:manage");
|
|
1695
|
+
const channel = onboardingChannel();
|
|
1696
|
+
const expectedRevision = requireInteger(fields["expected_revision"], "expected_revision");
|
|
1697
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
1698
|
+
const note = optionalString(fields["note"], "note");
|
|
1699
|
+
const record = channel.store.getRecord(recordId);
|
|
1700
|
+
if (record === undefined || record.merchantId !== auth.ctx.merchantId) {
|
|
1701
|
+
throw new ManagementError("not_found", `unknown onboarding record: ${recordId}`);
|
|
1702
|
+
}
|
|
1703
|
+
if (record.revision !== expectedRevision) {
|
|
1704
|
+
throw new ManagementError("precondition_changed", `record is at revision ${record.revision}, expected ${expectedRevision}`);
|
|
1705
|
+
}
|
|
1706
|
+
const requestDigest = managementRequestDigest({
|
|
1707
|
+
record_id: recordId,
|
|
1708
|
+
expected_revision: expectedRevision,
|
|
1709
|
+
});
|
|
1710
|
+
const probed = operations.probe({
|
|
1711
|
+
merchantId: auth.ctx.merchantId,
|
|
1712
|
+
actorId: auth.ctx.actorId,
|
|
1713
|
+
commandType,
|
|
1714
|
+
idempotencyKey,
|
|
1715
|
+
requestDigest,
|
|
1716
|
+
});
|
|
1717
|
+
if (probed.kind === "replay") {
|
|
1718
|
+
writeJson(res, 200, probed.receipt);
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
if (probed.kind === "conflict") {
|
|
1722
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
const begun = operations.begin({
|
|
1726
|
+
merchantId: auth.ctx.merchantId,
|
|
1727
|
+
actorId: auth.ctx.actorId,
|
|
1728
|
+
commandType,
|
|
1729
|
+
idempotencyKey,
|
|
1730
|
+
requestDigest,
|
|
1731
|
+
});
|
|
1732
|
+
if (begun.kind === "replay") {
|
|
1733
|
+
writeJson(res, 200, begun.receipt);
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1736
|
+
if (begun.kind === "conflict") {
|
|
1737
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
try {
|
|
1741
|
+
const updated = run(channel.store, record, note);
|
|
1742
|
+
const receipt = {
|
|
1743
|
+
...staticReceipt(begun.operationId, commandType, "succeeded"),
|
|
1744
|
+
resource_ref: `onboarding:${record.recordId}`,
|
|
1745
|
+
completed_at: now().toISOString(),
|
|
1746
|
+
};
|
|
1747
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
1748
|
+
writeJson(res, 200, { ...receipt, record: updated });
|
|
1749
|
+
return;
|
|
1750
|
+
}
|
|
1751
|
+
catch (err) {
|
|
1752
|
+
operations.release(begun.operationId);
|
|
1753
|
+
respondError(res, err);
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
async function postConfirmation(req, res) {
|
|
1758
|
+
const auth = requireActor(req);
|
|
1759
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1760
|
+
const body = await readJsonBody(req);
|
|
1761
|
+
const fields = objectFields(body, [
|
|
1762
|
+
"candidate_id",
|
|
1763
|
+
"action",
|
|
1764
|
+
"arguments_hash",
|
|
1765
|
+
"preconditions_hash",
|
|
1766
|
+
"target",
|
|
1767
|
+
"expected_service_revision",
|
|
1768
|
+
]);
|
|
1769
|
+
if (fields.target !== undefined || fields.expected_service_revision !== undefined) {
|
|
1770
|
+
const target = requireString(fields.target, "target");
|
|
1771
|
+
if (target !== "service.resume") {
|
|
1772
|
+
throw new ManagementError("invalid_input", `unsupported confirmation target: ${target}`);
|
|
1773
|
+
}
|
|
1774
|
+
authorizeOrThrow(auth.ctx, "service:resume");
|
|
1775
|
+
const expectedRevision = requireInteger(fields.expected_service_revision, "expected_service_revision");
|
|
1776
|
+
if (expectedRevision !== options.serviceState.serviceRevision) {
|
|
1777
|
+
throw new ManagementError("precondition_changed", "service revision changed");
|
|
1778
|
+
}
|
|
1779
|
+
const targetDigest = managementRequestDigest({
|
|
1780
|
+
target,
|
|
1781
|
+
expected_service_revision: expectedRevision,
|
|
1782
|
+
});
|
|
1783
|
+
const confirmation = operations.createConfirmation({
|
|
1784
|
+
merchantId: auth.ctx.merchantId,
|
|
1785
|
+
actorId: auth.ctx.actorId,
|
|
1786
|
+
target,
|
|
1787
|
+
targetDigest,
|
|
1788
|
+
ttlMs: CONFIRMATION_TTL_MS,
|
|
1789
|
+
});
|
|
1790
|
+
writeJson(res, 200, {
|
|
1791
|
+
target,
|
|
1792
|
+
confirmation_ref: confirmation.ref,
|
|
1793
|
+
expires_at: confirmation.expires_at,
|
|
1794
|
+
});
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
authorizeOrThrow(auth.ctx, "approvals:decide");
|
|
1798
|
+
const candidateId = requireString(fields.candidate_id, "candidate_id");
|
|
1799
|
+
const action = requireString(fields.action, "action");
|
|
1800
|
+
if (action !== "approve" && action !== "reject") {
|
|
1801
|
+
throw new ManagementError("invalid_input", "action must be approve or reject");
|
|
1802
|
+
}
|
|
1803
|
+
const candidate = options.listPending().find((item) => item.candidate_id === candidateId);
|
|
1804
|
+
if (candidate === undefined) {
|
|
1805
|
+
throw new ManagementError("not_found", `unknown candidate: ${candidateId}`);
|
|
1806
|
+
}
|
|
1807
|
+
if (candidate.status !== "pending_approval") {
|
|
1808
|
+
throw new ManagementError("conflict", `candidate is not awaiting approval (status: ${candidate.status})`);
|
|
1809
|
+
}
|
|
1810
|
+
const argumentsHash = requireString(fields.arguments_hash, "arguments_hash");
|
|
1811
|
+
const preconditionsHash = requireString(fields.preconditions_hash, "preconditions_hash");
|
|
1812
|
+
if (candidate.arguments_hash !== argumentsHash ||
|
|
1813
|
+
candidate.preconditions_hash !== preconditionsHash) {
|
|
1814
|
+
throw new ManagementError("precondition_changed", "candidate changed since preview");
|
|
1815
|
+
}
|
|
1816
|
+
if (Date.parse(candidate.expires_at) <= now().getTime()) {
|
|
1817
|
+
throw new ManagementError("precondition_changed", "candidate has expired");
|
|
1818
|
+
}
|
|
1819
|
+
const confirmationRef = options.mintCandidateConfirmation({
|
|
1820
|
+
candidateId,
|
|
1821
|
+
candidateDigest: contentHash({
|
|
1822
|
+
arguments: candidate.arguments,
|
|
1823
|
+
preconditions: candidate.preconditions,
|
|
1824
|
+
}),
|
|
1825
|
+
principalId: auth.session.principal_id,
|
|
1826
|
+
merchantId: auth.session.merchant_id,
|
|
1827
|
+
action,
|
|
1828
|
+
});
|
|
1829
|
+
writeJson(res, 200, {
|
|
1830
|
+
target: "approval",
|
|
1831
|
+
candidate_id: candidateId,
|
|
1832
|
+
action,
|
|
1833
|
+
confirmation_ref: confirmationRef,
|
|
1834
|
+
expires_at: candidate.expires_at,
|
|
1835
|
+
});
|
|
1836
|
+
}
|
|
1837
|
+
/** POST /approvals/{id}/approve|reject —— 幂等占位 → 服务层复检 → 执行 → 落回执。 */
|
|
1838
|
+
async function postApprovalDecision(req, res, candidateId, approve) {
|
|
1839
|
+
const commandType = `approval.${approve ? "approve" : "reject"}`;
|
|
1840
|
+
const auth = requireActor(req);
|
|
1841
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1842
|
+
const body = await readJsonBody(req);
|
|
1843
|
+
const fields = objectFields(body, [
|
|
1844
|
+
"arguments_hash",
|
|
1845
|
+
"preconditions_hash",
|
|
1846
|
+
"confirmation_ref",
|
|
1847
|
+
"reason",
|
|
1848
|
+
"idempotency_key",
|
|
1849
|
+
]);
|
|
1850
|
+
const argumentsHash = requireString(fields.arguments_hash, "arguments_hash");
|
|
1851
|
+
const preconditionsHash = requireString(fields.preconditions_hash, "preconditions_hash");
|
|
1852
|
+
const confirmationRef = requireString(fields.confirmation_ref, "confirmation_ref");
|
|
1853
|
+
const idempotencyKey = requireString(fields.idempotency_key, "idempotency_key");
|
|
1854
|
+
const reason = optionalString(fields.reason, "reason");
|
|
1855
|
+
const requestDigest = managementRequestDigest({
|
|
1856
|
+
candidate_id: candidateId,
|
|
1857
|
+
arguments_hash: argumentsHash,
|
|
1858
|
+
preconditions_hash: preconditionsHash,
|
|
1859
|
+
confirmation_ref: confirmationRef,
|
|
1860
|
+
...(reason !== undefined ? { reason } : {}),
|
|
1861
|
+
});
|
|
1862
|
+
const begun = operations.begin({
|
|
1863
|
+
merchantId: auth.ctx.merchantId,
|
|
1864
|
+
actorId: auth.ctx.actorId,
|
|
1865
|
+
commandType,
|
|
1866
|
+
idempotencyKey,
|
|
1867
|
+
requestDigest,
|
|
1868
|
+
});
|
|
1869
|
+
if (begun.kind === "replay") {
|
|
1870
|
+
writeJson(res, 200, begun.receipt);
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
if (begun.kind === "conflict") {
|
|
1874
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
try {
|
|
1878
|
+
// expected_revision 传 0:本版契约用 arguments/preconditions 哈希作为
|
|
1879
|
+
// 条件更新证明(BD §11.2 的等价机制;候选对象暂无持久 revision 字段)。
|
|
1880
|
+
const receipt = await executionService(begun.operationId).decideApproval(auth.ctx, candidateId, {
|
|
1881
|
+
expected_revision: 0,
|
|
1882
|
+
arguments_hash: argumentsHash,
|
|
1883
|
+
preconditions_hash: preconditionsHash,
|
|
1884
|
+
confirmation_ref: confirmationRef,
|
|
1885
|
+
}, { approve, idempotencyKey, ...(reason !== undefined ? { reason } : {}) });
|
|
1886
|
+
operations.complete(begun.operationId, toStorageStatus(receipt.status), receipt);
|
|
1887
|
+
writeJson(res, 200, receipt);
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
catch (err) {
|
|
1891
|
+
if (err instanceof ManagementError) {
|
|
1892
|
+
// 校验/授权/摘要/状态/过期类失败:未触达执行 → 释放占位,原键可重试。
|
|
1893
|
+
operations.release(begun.operationId);
|
|
1894
|
+
respondError(res, err);
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1898
|
+
if (message.includes("确认凭证")) {
|
|
1899
|
+
// core 凭证校验拒绝 = 未执行(凭证未被核销):释放占位,重新签确认后原键可重试。
|
|
1900
|
+
operations.release(begun.operationId);
|
|
1901
|
+
respondError(res, new ManagementError("forbidden", "confirmation reference is invalid or expired"));
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
// 无法证明「未执行」→ 记 unknown,保留对账路径(BD §11.1),绝不自动重做。
|
|
1905
|
+
log(`[merchant-management] ${commandType} 执行异常:${message}\n`);
|
|
1906
|
+
const receipt = staticReceipt(begun.operationId, commandType, "unknown");
|
|
1907
|
+
operations.complete(begun.operationId, "unknown", receipt);
|
|
1908
|
+
respondError(res, new ManagementError("unavailable", `execution outcome unknown; query operation ${begun.operationId} before retrying`));
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
/** POST /service/pause —— 拒新询价;既有任务不受影响(T012 语义)。 */
|
|
1912
|
+
async function postServicePause(req, res) {
|
|
1913
|
+
const auth = requireActor(req);
|
|
1914
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1915
|
+
const body = await readJsonBody(req);
|
|
1916
|
+
const fields = objectFields(body, ["reason", "expected_service_revision", "idempotency_key"]);
|
|
1917
|
+
authorizeOrThrow(auth.ctx, "service:pause");
|
|
1918
|
+
const expectedRevision = requireInteger(fields.expected_service_revision, "expected_service_revision");
|
|
1919
|
+
const idempotencyKey = requireString(fields.idempotency_key, "idempotency_key");
|
|
1920
|
+
const reason = optionalString(fields.reason, "reason");
|
|
1921
|
+
if (expectedRevision !== options.serviceState.serviceRevision) {
|
|
1922
|
+
throw new ManagementError("precondition_changed", "service revision changed");
|
|
1923
|
+
}
|
|
1924
|
+
const begun = operations.begin({
|
|
1925
|
+
merchantId: auth.ctx.merchantId,
|
|
1926
|
+
actorId: auth.ctx.actorId,
|
|
1927
|
+
commandType: "service.pause",
|
|
1928
|
+
idempotencyKey,
|
|
1929
|
+
requestDigest: managementRequestDigest({
|
|
1930
|
+
expected_service_revision: expectedRevision,
|
|
1931
|
+
...(reason !== undefined ? { reason } : {}),
|
|
1932
|
+
}),
|
|
1933
|
+
});
|
|
1934
|
+
if (begun.kind === "replay") {
|
|
1935
|
+
writeJson(res, 200, begun.receipt);
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
if (begun.kind === "conflict") {
|
|
1939
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
try {
|
|
1943
|
+
const applied = options.serviceState.pause(reason);
|
|
1944
|
+
const receipt = {
|
|
1945
|
+
...staticReceipt(begun.operationId, "service.pause", "succeeded"),
|
|
1946
|
+
resource_ref: "service",
|
|
1947
|
+
result_revision: applied.service_revision,
|
|
1948
|
+
completed_at: now().toISOString(),
|
|
1949
|
+
};
|
|
1950
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
1951
|
+
writeJson(res, 200, receipt);
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
catch (err) {
|
|
1955
|
+
if (err instanceof ManagementError) {
|
|
1956
|
+
operations.release(begun.operationId);
|
|
1957
|
+
respondError(res, err);
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
throw err;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
/** POST /service/resume —— owner 专属 + 确认引用 + 就绪门(BD §10.1)。 */
|
|
1964
|
+
async function postServiceResume(req, res) {
|
|
1965
|
+
const auth = requireActor(req);
|
|
1966
|
+
assertWriteGuards(req, auth.sessionId);
|
|
1967
|
+
const body = await readJsonBody(req);
|
|
1968
|
+
const fields = objectFields(body, [
|
|
1969
|
+
"expected_service_revision",
|
|
1970
|
+
"confirmation_ref",
|
|
1971
|
+
"idempotency_key",
|
|
1972
|
+
]);
|
|
1973
|
+
authorizeOrThrow(auth.ctx, "service:resume");
|
|
1974
|
+
const expectedRevision = requireInteger(fields.expected_service_revision, "expected_service_revision");
|
|
1975
|
+
const confirmationRef = requireString(fields.confirmation_ref, "confirmation_ref");
|
|
1976
|
+
const idempotencyKey = requireString(fields.idempotency_key, "idempotency_key");
|
|
1977
|
+
if (expectedRevision !== options.serviceState.serviceRevision) {
|
|
1978
|
+
throw new ManagementError("precondition_changed", "service revision changed");
|
|
1979
|
+
}
|
|
1980
|
+
// 确认引用在触达执行前核销(单次);失败 = 未授权确认 → 403,不留占位。
|
|
1981
|
+
if (!operations.consumeConfirmation({
|
|
1982
|
+
ref: confirmationRef,
|
|
1983
|
+
merchantId: auth.ctx.merchantId,
|
|
1984
|
+
actorId: auth.ctx.actorId,
|
|
1985
|
+
target: "service.resume",
|
|
1986
|
+
targetDigest: managementRequestDigest({
|
|
1987
|
+
target: "service.resume",
|
|
1988
|
+
expected_service_revision: expectedRevision,
|
|
1989
|
+
}),
|
|
1990
|
+
})) {
|
|
1991
|
+
throw new ManagementError("forbidden", "confirmation reference is invalid or expired");
|
|
1992
|
+
}
|
|
1993
|
+
const begun = operations.begin({
|
|
1994
|
+
merchantId: auth.ctx.merchantId,
|
|
1995
|
+
actorId: auth.ctx.actorId,
|
|
1996
|
+
commandType: "service.resume",
|
|
1997
|
+
idempotencyKey,
|
|
1998
|
+
requestDigest: managementRequestDigest({ expected_service_revision: expectedRevision }),
|
|
1999
|
+
});
|
|
2000
|
+
if (begun.kind === "replay") {
|
|
2001
|
+
writeJson(res, 200, begun.receipt);
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
if (begun.kind === "conflict") {
|
|
2005
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
// 就绪门:恢复前重新取就绪结论;失败/异常都发生在迁移之前 → 释放占位。
|
|
2009
|
+
let readiness;
|
|
2010
|
+
try {
|
|
2011
|
+
readiness = await options.readiness();
|
|
2012
|
+
}
|
|
2013
|
+
catch {
|
|
2014
|
+
operations.release(begun.operationId);
|
|
2015
|
+
respondError(res, new ManagementError("unavailable", "readiness check failed; refusing to resume"));
|
|
2016
|
+
return;
|
|
2017
|
+
}
|
|
2018
|
+
const failedChecks = Object.entries(readiness.checks)
|
|
2019
|
+
.filter(([, check]) => !check.ok)
|
|
2020
|
+
.map(([name]) => name);
|
|
2021
|
+
try {
|
|
2022
|
+
const applied = options.serviceState.resume(readiness.ready, failedChecks);
|
|
2023
|
+
const receipt = {
|
|
2024
|
+
...staticReceipt(begun.operationId, "service.resume", "succeeded"),
|
|
2025
|
+
resource_ref: "service",
|
|
2026
|
+
result_revision: applied.service_revision,
|
|
2027
|
+
completed_at: now().toISOString(),
|
|
2028
|
+
};
|
|
2029
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
2030
|
+
writeJson(res, 200, receipt);
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
catch (err) {
|
|
2034
|
+
if (err instanceof ManagementError) {
|
|
2035
|
+
operations.release(begun.operationId);
|
|
2036
|
+
respondError(res, err);
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
throw err;
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
// ── 商品导入(BD §10.1:校验预览 → 确认提交;全批成功或全批不变)────────
|
|
2043
|
+
/**
|
|
2044
|
+
* POST /products/import-drafts —— 整表严格校验(任何行错误 → 整表拒绝并报
|
|
2045
|
+
* 行号)+ 当前表 CAS(base_digest)+ 增/改/留/删预览;只存草稿,不动商品表。
|
|
2046
|
+
* 语义是**整表替换**:新表未包含的 SKU 提交后即移除(预览给出 removed 数)。
|
|
2047
|
+
*/
|
|
2048
|
+
async function postProductsImportDraft(req, res) {
|
|
2049
|
+
const auth = requireActor(req);
|
|
2050
|
+
assertWriteGuards(req, auth.sessionId);
|
|
2051
|
+
const body = await readJsonBody(req);
|
|
2052
|
+
const fields = objectFields(body, ["table", "base_digest", "idempotency_key"]);
|
|
2053
|
+
authorizeOrThrow(auth.ctx, "products:import");
|
|
2054
|
+
const importChannel = options.productsImport;
|
|
2055
|
+
if (importChannel === undefined) {
|
|
2056
|
+
throw new ManagementError("unavailable", "product import storage is not configured");
|
|
2057
|
+
}
|
|
2058
|
+
let table;
|
|
2059
|
+
try {
|
|
2060
|
+
table = parseProductTable(fields["table"], "request body");
|
|
2061
|
+
}
|
|
2062
|
+
catch (err) {
|
|
2063
|
+
if (err instanceof ProductTableError) {
|
|
2064
|
+
throw new ManagementError("invalid_input", err.message);
|
|
2065
|
+
}
|
|
2066
|
+
throw err;
|
|
2067
|
+
}
|
|
2068
|
+
if (table.merchant_id !== options.merchantId) {
|
|
2069
|
+
throw new ManagementError("forbidden", "product table merchant_id does not match this instance");
|
|
2070
|
+
}
|
|
2071
|
+
let base;
|
|
2072
|
+
try {
|
|
2073
|
+
base = importChannel.currentTable();
|
|
2074
|
+
}
|
|
2075
|
+
catch (err) {
|
|
2076
|
+
if (err instanceof ProductTableError) {
|
|
2077
|
+
throw new ManagementError("unavailable", `current product table unavailable (${err.code})`);
|
|
2078
|
+
}
|
|
2079
|
+
throw err;
|
|
2080
|
+
}
|
|
2081
|
+
const baseDigest = optionalString(fields["base_digest"], "base_digest");
|
|
2082
|
+
if (baseDigest !== undefined && baseDigest !== base.digest) {
|
|
2083
|
+
throw new ManagementError("precondition_changed", "product table changed since preview");
|
|
2084
|
+
}
|
|
2085
|
+
const currentBySku = new Map(base.records.map((record) => [record.sku, record]));
|
|
2086
|
+
let added = 0;
|
|
2087
|
+
let updated = 0;
|
|
2088
|
+
let unchanged = 0;
|
|
2089
|
+
for (const record of table.products) {
|
|
2090
|
+
const previous = currentBySku.get(record.sku);
|
|
2091
|
+
if (previous === undefined)
|
|
2092
|
+
added += 1;
|
|
2093
|
+
else if (JSON.stringify(previous) === JSON.stringify(record))
|
|
2094
|
+
unchanged += 1;
|
|
2095
|
+
else
|
|
2096
|
+
updated += 1;
|
|
2097
|
+
}
|
|
2098
|
+
const removedCount = base.records.filter((record) => !table.products.some((item) => item.sku === record.sku)).length;
|
|
2099
|
+
const digest = productTableDigest(table);
|
|
2100
|
+
const created = options.drafts.create({
|
|
2101
|
+
merchantId: auth.ctx.merchantId,
|
|
2102
|
+
kind: "products_import",
|
|
2103
|
+
payloadJson: JSON.stringify(table),
|
|
2104
|
+
payloadDigest: digest,
|
|
2105
|
+
...(base.digest !== "" ? { baseDigest: base.digest } : {}),
|
|
2106
|
+
});
|
|
2107
|
+
writeJson(res, 200, {
|
|
2108
|
+
draft_id: created.draftId,
|
|
2109
|
+
digest,
|
|
2110
|
+
reused: created.reused,
|
|
2111
|
+
base_digest: base.digest === "" ? null : base.digest,
|
|
2112
|
+
preview: {
|
|
2113
|
+
rows_total: table.products.length,
|
|
2114
|
+
added,
|
|
2115
|
+
updated,
|
|
2116
|
+
unchanged,
|
|
2117
|
+
removed: removedCount,
|
|
2118
|
+
},
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
/** POST /products/import-drafts/{id}/commit —— 原子落盘;结果不可分辨时记 unknown。 */
|
|
2122
|
+
async function postProductsImportCommit(req, res, draftId) {
|
|
2123
|
+
const auth = requireActor(req);
|
|
2124
|
+
assertWriteGuards(req, auth.sessionId);
|
|
2125
|
+
const body = await readJsonBody(req);
|
|
2126
|
+
const fields = objectFields(body, ["expected_draft_digest", "idempotency_key"]);
|
|
2127
|
+
authorizeOrThrow(auth.ctx, "products:import");
|
|
2128
|
+
const importChannel = options.productsImport;
|
|
2129
|
+
if (importChannel === undefined) {
|
|
2130
|
+
throw new ManagementError("unavailable", "product import storage is not configured");
|
|
2131
|
+
}
|
|
2132
|
+
const draft = options.drafts.getPayload(auth.ctx.merchantId, draftId);
|
|
2133
|
+
if (draft === undefined) {
|
|
2134
|
+
throw new ManagementError("not_found", `unknown draft: ${draftId}`);
|
|
2135
|
+
}
|
|
2136
|
+
if (draft.kind !== "products_import") {
|
|
2137
|
+
throw new ManagementError("invalid_input", "draft is not a products import");
|
|
2138
|
+
}
|
|
2139
|
+
const expectedDigest = requireString(fields["expected_draft_digest"], "expected_draft_digest");
|
|
2140
|
+
if (expectedDigest !== draft.payload_digest) {
|
|
2141
|
+
throw new ManagementError("precondition_changed", "draft digest does not match");
|
|
2142
|
+
}
|
|
2143
|
+
let table;
|
|
2144
|
+
try {
|
|
2145
|
+
table = JSON.parse(draft.payload_json);
|
|
2146
|
+
}
|
|
2147
|
+
catch {
|
|
2148
|
+
throw new ManagementError("invalid_input", "draft payload is corrupted");
|
|
2149
|
+
}
|
|
2150
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
2151
|
+
const requestDigest = managementRequestDigest({
|
|
2152
|
+
draft_id: draftId,
|
|
2153
|
+
expected_draft_digest: expectedDigest,
|
|
2154
|
+
});
|
|
2155
|
+
// 幂等探测先于草稿状态检查:同键重放必须回原回执,不能被「已提交」挡住(UC20)。
|
|
2156
|
+
const probed = operations.probe({
|
|
2157
|
+
merchantId: auth.ctx.merchantId,
|
|
2158
|
+
actorId: auth.ctx.actorId,
|
|
2159
|
+
commandType: "products.import_commit",
|
|
2160
|
+
idempotencyKey,
|
|
2161
|
+
requestDigest,
|
|
2162
|
+
});
|
|
2163
|
+
if (probed.kind === "replay") {
|
|
2164
|
+
writeJson(res, 200, probed.receipt);
|
|
2165
|
+
return;
|
|
2166
|
+
}
|
|
2167
|
+
if (probed.kind === "conflict") {
|
|
2168
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
2169
|
+
return;
|
|
2170
|
+
}
|
|
2171
|
+
if (draft.status === "committed") {
|
|
2172
|
+
throw new ManagementError("conflict", "draft has already been committed");
|
|
2173
|
+
}
|
|
2174
|
+
const begun = operations.begin({
|
|
2175
|
+
merchantId: auth.ctx.merchantId,
|
|
2176
|
+
actorId: auth.ctx.actorId,
|
|
2177
|
+
commandType: "products.import_commit",
|
|
2178
|
+
idempotencyKey,
|
|
2179
|
+
requestDigest,
|
|
2180
|
+
});
|
|
2181
|
+
if (begun.kind === "replay") {
|
|
2182
|
+
writeJson(res, 200, begun.receipt);
|
|
2183
|
+
return;
|
|
2184
|
+
}
|
|
2185
|
+
if (begun.kind === "conflict") {
|
|
2186
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
try {
|
|
2190
|
+
const written = importChannel.commit(table);
|
|
2191
|
+
const marked = options.drafts.markCommitted(auth.ctx.merchantId, draftId);
|
|
2192
|
+
if (!marked) {
|
|
2193
|
+
// 并发重复提交:文件已写入同一内容,占位释放即可(不产生第二份业务效果)。
|
|
2194
|
+
operations.release(begun.operationId);
|
|
2195
|
+
writeJson(res, 409, errorBody("conflict", "draft has already been committed"));
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
const receipt = {
|
|
2199
|
+
...staticReceipt(begun.operationId, "products.import_commit", "succeeded"),
|
|
2200
|
+
resource_ref: `products-table:${written.digest}`,
|
|
2201
|
+
completed_at: now().toISOString(),
|
|
2202
|
+
};
|
|
2203
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
2204
|
+
writeJson(res, 200, receipt);
|
|
2205
|
+
return;
|
|
2206
|
+
}
|
|
2207
|
+
catch (err) {
|
|
2208
|
+
if (err instanceof ProductTableError) {
|
|
2209
|
+
// 落盘前的校验/租户失败:商品表未动 → 释放占位,可修正后原键重试。
|
|
2210
|
+
operations.release(begun.operationId);
|
|
2211
|
+
respondError(res, new ManagementError("invalid_input", err.message));
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2214
|
+
// 文件系统失败且无法证明「未生效」→ 记 unknown,先查 GET /products 对账。
|
|
2215
|
+
log(`[merchant-management] products.import_commit 执行异常:${err instanceof Error ? err.message : String(err)}\n`);
|
|
2216
|
+
const receipt = staticReceipt(begun.operationId, "products.import_commit", "unknown");
|
|
2217
|
+
operations.complete(begun.operationId, "unknown", receipt);
|
|
2218
|
+
respondError(res, new ManagementError("unavailable", `commit outcome unknown; query operation ${begun.operationId} and GET /products before retrying`));
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
// ── 策略草稿(BD §7.4:敏感原文只进私有存储;API 只见摘要与版本)──────────
|
|
2222
|
+
/** POST /policy/drafts —— patch 原文入库;响应只含 draft_id 与摘要。 */
|
|
2223
|
+
async function postPolicyDraft(req, res) {
|
|
2224
|
+
const auth = requireActor(req);
|
|
2225
|
+
assertWriteGuards(req, auth.sessionId);
|
|
2226
|
+
const body = await readJsonBody(req);
|
|
2227
|
+
const fields = objectFields(body, ["patch", "expected_policy_revision"]);
|
|
2228
|
+
authorizeOrThrow(auth.ctx, "policy:draft");
|
|
2229
|
+
const patch = fields["patch"];
|
|
2230
|
+
if (patch === null || typeof patch !== "object" || Array.isArray(patch)) {
|
|
2231
|
+
throw new ManagementError("invalid_input", "patch must be a JSON object");
|
|
2232
|
+
}
|
|
2233
|
+
const current = options.policy?.();
|
|
2234
|
+
const expectedRevision = fields["expected_policy_revision"];
|
|
2235
|
+
if (expectedRevision !== undefined) {
|
|
2236
|
+
const expected = requireInteger(expectedRevision, "expected_policy_revision");
|
|
2237
|
+
if (current === undefined || current.version !== expected) {
|
|
2238
|
+
throw new ManagementError("precondition_changed", "policy revision changed");
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const patchObject = patch;
|
|
2242
|
+
const digest = managementRequestDigest(patchObject);
|
|
2243
|
+
const created = options.drafts.create({
|
|
2244
|
+
merchantId: auth.ctx.merchantId,
|
|
2245
|
+
kind: "policy_override",
|
|
2246
|
+
payloadJson: JSON.stringify(patchObject),
|
|
2247
|
+
payloadDigest: digest,
|
|
2248
|
+
...(current !== undefined ? { baseDigest: current.digest } : {}),
|
|
2249
|
+
});
|
|
2250
|
+
writeJson(res, 200, {
|
|
2251
|
+
draft_id: created.draftId,
|
|
2252
|
+
digest,
|
|
2253
|
+
reused: created.reused,
|
|
2254
|
+
base_digest: current?.digest ?? null,
|
|
2255
|
+
});
|
|
2256
|
+
}
|
|
2257
|
+
/** POST /policy/drafts/{id}/commit —— 应用策略补丁;回执只含版本与摘要(红线 6)。 */
|
|
2258
|
+
async function postPolicyCommit(req, res, draftId) {
|
|
2259
|
+
const auth = requireActor(req);
|
|
2260
|
+
assertWriteGuards(req, auth.sessionId);
|
|
2261
|
+
const body = await readJsonBody(req);
|
|
2262
|
+
const fields = objectFields(body, ["expected_draft_digest", "idempotency_key"]);
|
|
2263
|
+
authorizeOrThrow(auth.ctx, "policy:draft");
|
|
2264
|
+
const apply = options.policyApply;
|
|
2265
|
+
if (apply === undefined) {
|
|
2266
|
+
throw new ManagementError("unavailable", "policy apply is not configured");
|
|
2267
|
+
}
|
|
2268
|
+
const draft = options.drafts.getPayload(auth.ctx.merchantId, draftId);
|
|
2269
|
+
if (draft === undefined) {
|
|
2270
|
+
throw new ManagementError("not_found", `unknown draft: ${draftId}`);
|
|
2271
|
+
}
|
|
2272
|
+
if (draft.kind !== "policy_override") {
|
|
2273
|
+
throw new ManagementError("invalid_input", "draft is not a policy override");
|
|
2274
|
+
}
|
|
2275
|
+
const expectedDigest = requireString(fields["expected_draft_digest"], "expected_draft_digest");
|
|
2276
|
+
if (expectedDigest !== draft.payload_digest) {
|
|
2277
|
+
throw new ManagementError("precondition_changed", "draft digest does not match");
|
|
2278
|
+
}
|
|
2279
|
+
const idempotencyKey = requireString(fields["idempotency_key"], "idempotency_key");
|
|
2280
|
+
const requestDigest = managementRequestDigest({
|
|
2281
|
+
draft_id: draftId,
|
|
2282
|
+
expected_draft_digest: expectedDigest,
|
|
2283
|
+
});
|
|
2284
|
+
// 幂等探测先于草稿状态检查(同 UC20:重放不被「已提交」挡住)。
|
|
2285
|
+
const probed = operations.probe({
|
|
2286
|
+
merchantId: auth.ctx.merchantId,
|
|
2287
|
+
actorId: auth.ctx.actorId,
|
|
2288
|
+
commandType: "policy.commit",
|
|
2289
|
+
idempotencyKey,
|
|
2290
|
+
requestDigest,
|
|
2291
|
+
});
|
|
2292
|
+
if (probed.kind === "replay") {
|
|
2293
|
+
writeJson(res, 200, probed.receipt);
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
if (probed.kind === "conflict") {
|
|
2297
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
if (draft.status === "committed") {
|
|
2301
|
+
throw new ManagementError("conflict", "draft has already been committed");
|
|
2302
|
+
}
|
|
2303
|
+
const begun = operations.begin({
|
|
2304
|
+
merchantId: auth.ctx.merchantId,
|
|
2305
|
+
actorId: auth.ctx.actorId,
|
|
2306
|
+
commandType: "policy.commit",
|
|
2307
|
+
idempotencyKey,
|
|
2308
|
+
requestDigest,
|
|
2309
|
+
});
|
|
2310
|
+
if (begun.kind === "replay") {
|
|
2311
|
+
writeJson(res, 200, begun.receipt);
|
|
2312
|
+
return;
|
|
2313
|
+
}
|
|
2314
|
+
if (begun.kind === "conflict") {
|
|
2315
|
+
writeJson(res, 409, errorBody("conflict", "idempotency key was already used with a different request"));
|
|
2316
|
+
return;
|
|
2317
|
+
}
|
|
2318
|
+
let patch;
|
|
2319
|
+
try {
|
|
2320
|
+
patch = JSON.parse(draft.payload_json);
|
|
2321
|
+
}
|
|
2322
|
+
catch {
|
|
2323
|
+
throw new ManagementError("invalid_input", "draft payload is corrupted");
|
|
2324
|
+
}
|
|
2325
|
+
try {
|
|
2326
|
+
const applied = await apply(patch);
|
|
2327
|
+
options.drafts.markCommitted(auth.ctx.merchantId, draftId);
|
|
2328
|
+
const receipt = {
|
|
2329
|
+
...staticReceipt(begun.operationId, "policy.commit", "succeeded"),
|
|
2330
|
+
resource_ref: `policy:v${applied.version}`,
|
|
2331
|
+
result_revision: applied.version,
|
|
2332
|
+
completed_at: now().toISOString(),
|
|
2333
|
+
};
|
|
2334
|
+
operations.complete(begun.operationId, "succeeded", receipt);
|
|
2335
|
+
writeJson(res, 200, receipt);
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
catch (err) {
|
|
2339
|
+
// apply 是「校验 + 原子写」:校验失败未生效 → 释放占位可修正重试
|
|
2340
|
+
// (错误消息来自 runtime 校验层,不含策略数值本身)。
|
|
2341
|
+
operations.release(begun.operationId);
|
|
2342
|
+
respondError(res, new ManagementError("invalid_input", err instanceof Error ? err.message : String(err)));
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
// ── 认证与防护 ─────────────────────────────────────────────────────
|
|
2346
|
+
function requireActor(req) {
|
|
2347
|
+
const sessionId = cookieValue(req, ADMIN_SESSION_COOKIE);
|
|
2348
|
+
const session = sessionId !== undefined ? options.sessions.getSession(sessionId) : undefined;
|
|
2349
|
+
if (sessionId === undefined || session === undefined) {
|
|
2350
|
+
throw new ManagementError("unauthorized", "management session required");
|
|
2351
|
+
}
|
|
2352
|
+
const ctx = createVerifiedActorContext({
|
|
2353
|
+
actorId: session.principal_id,
|
|
2354
|
+
merchantId: session.merchant_id,
|
|
2355
|
+
role: session.role,
|
|
2356
|
+
authMethod: "admin-session",
|
|
2357
|
+
generation: options.generation(),
|
|
2358
|
+
requestId: `mreq_${randomBytes(8).toString("hex")}`,
|
|
2359
|
+
expiresAt: session.expires_at,
|
|
2360
|
+
});
|
|
2361
|
+
return { sessionId, session, ctx };
|
|
2362
|
+
}
|
|
2363
|
+
/**
|
|
2364
|
+
* 适配层授权门(confirmations/pause/resume 在进入服务层之前先挡越权;
|
|
2365
|
+
* 服务层仍逐次复检——两层都要过,类型检查通过不算授权)。
|
|
2366
|
+
*/
|
|
2367
|
+
function authorizeOrThrow(ctx, permission) {
|
|
2368
|
+
const actor = assertVerifiedActor(ctx, now());
|
|
2369
|
+
if (!hasPermission(actor, permission)) {
|
|
2370
|
+
throw new ManagementError("forbidden", `missing permission: ${permission}`);
|
|
2371
|
+
}
|
|
2372
|
+
if (actor.merchantId !== options.merchantId) {
|
|
2373
|
+
throw new ManagementError("not_found", "resource does not belong to this merchant");
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
function assertWriteGuards(req, sessionId) {
|
|
2377
|
+
const presented = singleHeader(req, "x-csrf-token");
|
|
2378
|
+
if (!csrfValid(sessionId, presented)) {
|
|
2379
|
+
throw new ManagementError("forbidden", "missing or invalid CSRF token");
|
|
2380
|
+
}
|
|
2381
|
+
const origin = singleHeader(req, "origin");
|
|
2382
|
+
if (origin !== undefined &&
|
|
2383
|
+
options.allowedOrigins !== undefined &&
|
|
2384
|
+
!options.allowedOrigins.includes(origin)) {
|
|
2385
|
+
throw new ManagementError("forbidden", "origin is not allowed for management writes");
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
function csrfTokenFor(sessionId) {
|
|
2389
|
+
return createHmac("sha256", csrfKey).update(sessionId).digest("base64url");
|
|
2390
|
+
}
|
|
2391
|
+
function csrfValid(sessionId, presented) {
|
|
2392
|
+
if (presented === undefined || presented === "")
|
|
2393
|
+
return false;
|
|
2394
|
+
const expected = Buffer.from(csrfTokenFor(sessionId));
|
|
2395
|
+
const actual = Buffer.from(presented);
|
|
2396
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
2397
|
+
}
|
|
2398
|
+
// ── 输入与输出辅助 ─────────────────────────────────────────────────
|
|
2399
|
+
async function readJsonBody(req) {
|
|
2400
|
+
const chunks = [];
|
|
2401
|
+
let size = 0;
|
|
2402
|
+
for await (const chunk of req) {
|
|
2403
|
+
size += chunk.length;
|
|
2404
|
+
if (size > MAX_BODY_BYTES)
|
|
2405
|
+
throw new BodyTooLarge();
|
|
2406
|
+
chunks.push(chunk);
|
|
2407
|
+
}
|
|
2408
|
+
if (chunks.length === 0) {
|
|
2409
|
+
throw new ManagementError("invalid_input", "JSON body required");
|
|
2410
|
+
}
|
|
2411
|
+
try {
|
|
2412
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
2413
|
+
}
|
|
2414
|
+
catch {
|
|
2415
|
+
throw new ManagementError("invalid_input", "body must be valid JSON");
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
function staticReceipt(operationId, commandType, status) {
|
|
2419
|
+
const stamp = now().toISOString();
|
|
2420
|
+
return {
|
|
2421
|
+
operation_id: operationId,
|
|
2422
|
+
command_type: commandType,
|
|
2423
|
+
status,
|
|
2424
|
+
resource_ref: null,
|
|
2425
|
+
result_revision: null,
|
|
2426
|
+
created_at: stamp,
|
|
2427
|
+
...(status === "succeeded" || status === "failed"
|
|
2428
|
+
? { completed_at: stamp }
|
|
2429
|
+
: { completed_at: null }),
|
|
2430
|
+
support_id: `sup_${operationId.slice(-8)}`,
|
|
2431
|
+
};
|
|
2432
|
+
}
|
|
2433
|
+
function toStorageStatus(status) {
|
|
2434
|
+
if (status === "succeeded" || status === "failed")
|
|
2435
|
+
return status;
|
|
2436
|
+
return "unknown";
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
// ── 模块级纯函数 ───────────────────────────────────────────────────────
|
|
2440
|
+
function isKnownPath(rest) {
|
|
2441
|
+
if (rest === "/session" ||
|
|
2442
|
+
rest === "/status" ||
|
|
2443
|
+
rest === "/products" ||
|
|
2444
|
+
rest === "/policy" ||
|
|
2445
|
+
rest === "/approvals" ||
|
|
2446
|
+
rest === "/confirmations" ||
|
|
2447
|
+
rest === "/service/pause" ||
|
|
2448
|
+
rest === "/service/resume" ||
|
|
2449
|
+
rest === "/products/import-drafts" ||
|
|
2450
|
+
rest === "/policy/drafts" ||
|
|
2451
|
+
rest === "/onboarding") {
|
|
2452
|
+
return true;
|
|
2453
|
+
}
|
|
2454
|
+
return (/^\/approvals\/[^/]+(\/approve|\/reject)?$/.test(rest) ||
|
|
2455
|
+
/^\/operations\/[^/]+$/.test(rest) ||
|
|
2456
|
+
/^\/products\/import-drafts\/[^/]+\/commit$/.test(rest) ||
|
|
2457
|
+
/^\/policy\/drafts\/[^/]+\/commit$/.test(rest) ||
|
|
2458
|
+
/^\/onboarding\/([^/]+)\/(advance|cancel|consent-refused)$/.test(rest));
|
|
2459
|
+
}
|
|
2460
|
+
function pageQuery(url) {
|
|
2461
|
+
const out = {};
|
|
2462
|
+
const cursor = url.searchParams.get("cursor");
|
|
2463
|
+
if (cursor !== null && cursor !== "")
|
|
2464
|
+
out.cursor = cursor;
|
|
2465
|
+
const limitRaw = url.searchParams.get("limit");
|
|
2466
|
+
if (limitRaw !== null) {
|
|
2467
|
+
const limit = Number.parseInt(limitRaw, 10);
|
|
2468
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
2469
|
+
throw new ManagementError("invalid_input", "limit must be a positive integer");
|
|
2470
|
+
}
|
|
2471
|
+
out.limit = limit;
|
|
2472
|
+
}
|
|
2473
|
+
return out;
|
|
2474
|
+
}
|
|
2475
|
+
function pathSegment(raw) {
|
|
2476
|
+
try {
|
|
2477
|
+
return decodeURIComponent(raw);
|
|
2478
|
+
}
|
|
2479
|
+
catch {
|
|
2480
|
+
throw new ManagementError("invalid_input", "invalid path encoding");
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
function objectFields(body, allowed) {
|
|
2484
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
2485
|
+
throw new ManagementError("invalid_input", "body must be a JSON object");
|
|
2486
|
+
}
|
|
2487
|
+
for (const key of Object.keys(body)) {
|
|
2488
|
+
if (!allowed.includes(key)) {
|
|
2489
|
+
throw new ManagementError("invalid_input", `unknown field: ${key}`);
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
return body;
|
|
2493
|
+
}
|
|
2494
|
+
function requireString(value, field) {
|
|
2495
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
2496
|
+
throw new ManagementError("invalid_input", `${field} must be a non-empty string`);
|
|
2497
|
+
}
|
|
2498
|
+
return value;
|
|
2499
|
+
}
|
|
2500
|
+
function requireObject(value, field) {
|
|
2501
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
2502
|
+
throw new ManagementError("invalid_input", `${field} must be a JSON object`);
|
|
2503
|
+
}
|
|
2504
|
+
return value;
|
|
2505
|
+
}
|
|
2506
|
+
function sameAuthorizationGeneration(frozen, current) {
|
|
2507
|
+
if (frozen === null || typeof frozen !== "object" || Array.isArray(frozen))
|
|
2508
|
+
return false;
|
|
2509
|
+
const value = frozen;
|
|
2510
|
+
return (value["actor_id"] === current["actor_id"] &&
|
|
2511
|
+
value["actor_role"] === current["actor_role"] &&
|
|
2512
|
+
value["action"] === current["action"] &&
|
|
2513
|
+
value["authorization_generation"] === current["authorization_generation"]);
|
|
2514
|
+
}
|
|
2515
|
+
function optionalString(value, field) {
|
|
2516
|
+
if (value === undefined)
|
|
2517
|
+
return undefined;
|
|
2518
|
+
return requireString(value, field);
|
|
2519
|
+
}
|
|
2520
|
+
function requireInteger(value, field) {
|
|
2521
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
2522
|
+
throw new ManagementError("invalid_input", `${field} must be an integer`);
|
|
2523
|
+
}
|
|
2524
|
+
return value;
|
|
2525
|
+
}
|
|
2526
|
+
function requireNonNegativeInteger(value, field) {
|
|
2527
|
+
const integer = requireInteger(value, field);
|
|
2528
|
+
if (integer < 0)
|
|
2529
|
+
throw new ManagementError("invalid_input", `${field} must be non-negative`);
|
|
2530
|
+
return integer;
|
|
2531
|
+
}
|
|
2532
|
+
function requirePositiveInteger(value, field) {
|
|
2533
|
+
const integer = requireInteger(value, field);
|
|
2534
|
+
if (integer < 1)
|
|
2535
|
+
throw new ManagementError("invalid_input", `${field} must be positive`);
|
|
2536
|
+
return integer;
|
|
2537
|
+
}
|
|
2538
|
+
function requireDecision(value) {
|
|
2539
|
+
if (value !== "approve" && value !== "reject") {
|
|
2540
|
+
throw new ManagementError("invalid_input", "decision must be approve or reject");
|
|
2541
|
+
}
|
|
2542
|
+
return value;
|
|
2543
|
+
}
|
|
2544
|
+
function requireGrantAction(value) {
|
|
2545
|
+
if (typeof value !== "string" || !GRANT_ACTIONS.includes(value)) {
|
|
2546
|
+
throw new ManagementError("invalid_input", "grant_action is invalid");
|
|
2547
|
+
}
|
|
2548
|
+
return value;
|
|
2549
|
+
}
|
|
2550
|
+
function requireGrantResourceType(value) {
|
|
2551
|
+
if (value !== "merchant" && value !== "product") {
|
|
2552
|
+
throw new ManagementError("invalid_input", "resource_type must be merchant or product");
|
|
2553
|
+
}
|
|
2554
|
+
return value;
|
|
2555
|
+
}
|
|
2556
|
+
function requireGrantSelector(value) {
|
|
2557
|
+
if (value === "merchant" || value === "all_products")
|
|
2558
|
+
return value;
|
|
2559
|
+
if (!Array.isArray(value) ||
|
|
2560
|
+
value.length === 0 ||
|
|
2561
|
+
value.some((item) => typeof item !== "string")) {
|
|
2562
|
+
throw new ManagementError("invalid_input", "resource_selector is invalid");
|
|
2563
|
+
}
|
|
2564
|
+
return value;
|
|
2565
|
+
}
|
|
2566
|
+
function requireStringArray(value, field) {
|
|
2567
|
+
if (!Array.isArray(value) ||
|
|
2568
|
+
value.length === 0 ||
|
|
2569
|
+
value.some((item) => typeof item !== "string")) {
|
|
2570
|
+
throw new ManagementError("invalid_input", `${field} must be a non-empty string array`);
|
|
2571
|
+
}
|
|
2572
|
+
return value;
|
|
2573
|
+
}
|
|
2574
|
+
function requirePublicAudience(value) {
|
|
2575
|
+
if (value !== "public") {
|
|
2576
|
+
throw new ManagementError("invalid_input", "audience must be public");
|
|
2577
|
+
}
|
|
2578
|
+
return value;
|
|
2579
|
+
}
|
|
2580
|
+
function candidateIdFromPreparation(value) {
|
|
2581
|
+
const prepared = requireObject(value, "prepared candidate");
|
|
2582
|
+
const candidate = requireObject(prepared["candidate"], "prepared candidate.candidate");
|
|
2583
|
+
return requireString(candidate["candidate_id"], "prepared candidate.candidate_id");
|
|
2584
|
+
}
|
|
2585
|
+
function exactProductProjection(product) {
|
|
2586
|
+
if (product.currency_table_version !== WORKBENCH_CURRENCY_TABLE_VERSION) {
|
|
2587
|
+
throw new ManagementError("unavailable", "exact product currency table version does not match Workbench v1");
|
|
2588
|
+
}
|
|
2589
|
+
return {
|
|
2590
|
+
sku: product.sku,
|
|
2591
|
+
merchant_id: product.merchant_id,
|
|
2592
|
+
title: product.title,
|
|
2593
|
+
description: product.description,
|
|
2594
|
+
category: product.category,
|
|
2595
|
+
tags: product.tags,
|
|
2596
|
+
stock: product.stock,
|
|
2597
|
+
money: {
|
|
2598
|
+
currency: product.currency,
|
|
2599
|
+
amount_minor: product.price_minor,
|
|
2600
|
+
currency_table_version: product.currency_table_version,
|
|
2601
|
+
},
|
|
2602
|
+
authority_version: product.authority_version,
|
|
2603
|
+
delivery_attributes: product.delivery_attributes,
|
|
2604
|
+
handoff_destination: product.handoff_destination,
|
|
2605
|
+
};
|
|
2606
|
+
}
|
|
2607
|
+
function requireExactMoneyInput(value) {
|
|
2608
|
+
const record = requireObject(value, "money");
|
|
2609
|
+
if (record["currency_table_version"] !== WORKBENCH_CURRENCY_TABLE_VERSION) {
|
|
2610
|
+
throw new ManagementError("invalid_input", `money.currency_table_version must be ${WORKBENCH_CURRENCY_TABLE_VERSION}`);
|
|
2611
|
+
}
|
|
2612
|
+
return parseExactMoney(record, { requireOperatingSupport: true });
|
|
2613
|
+
}
|
|
2614
|
+
function cookieValue(req, name) {
|
|
2615
|
+
const header = req.headers.cookie;
|
|
2616
|
+
if (header === undefined)
|
|
2617
|
+
return undefined;
|
|
2618
|
+
for (const part of header.split(";")) {
|
|
2619
|
+
const eq = part.indexOf("=");
|
|
2620
|
+
if (eq === -1)
|
|
2621
|
+
continue;
|
|
2622
|
+
if (part.slice(0, eq).trim() === name)
|
|
2623
|
+
return part.slice(eq + 1).trim();
|
|
2624
|
+
}
|
|
2625
|
+
return undefined;
|
|
2626
|
+
}
|
|
2627
|
+
function singleHeader(req, name) {
|
|
2628
|
+
const value = req.headers[name];
|
|
2629
|
+
if (Array.isArray(value))
|
|
2630
|
+
return value[0];
|
|
2631
|
+
return value;
|
|
2632
|
+
}
|
|
2633
|
+
function errorBody(code, message, opts = {}) {
|
|
2634
|
+
return {
|
|
2635
|
+
code,
|
|
2636
|
+
message,
|
|
2637
|
+
retryable: opts.retryable ?? false,
|
|
2638
|
+
support_id: opts.supportId ?? `sup_${randomBytes(4).toString("hex")}`,
|
|
2639
|
+
};
|
|
2640
|
+
}
|
|
2641
|
+
function writeJson(res, status, body, extra = {}) {
|
|
2642
|
+
if (res.headersSent) {
|
|
2643
|
+
res.end();
|
|
2644
|
+
return;
|
|
2645
|
+
}
|
|
2646
|
+
res.writeHead(status, {
|
|
2647
|
+
"content-type": "application/json; charset=utf-8",
|
|
2648
|
+
"cache-control": "no-store",
|
|
2649
|
+
pragma: "no-cache",
|
|
2650
|
+
...extra,
|
|
2651
|
+
});
|
|
2652
|
+
res.end(JSON.stringify(body));
|
|
2653
|
+
}
|
|
2654
|
+
function writeWorkbenchProblem(res, code, requestId, title, detail, details) {
|
|
2655
|
+
const body = createWorkbenchProblem(code, {
|
|
2656
|
+
title,
|
|
2657
|
+
detail,
|
|
2658
|
+
requestId,
|
|
2659
|
+
...(details !== undefined ? { details } : {}),
|
|
2660
|
+
});
|
|
2661
|
+
if (res.headersSent) {
|
|
2662
|
+
res.end();
|
|
2663
|
+
return;
|
|
2664
|
+
}
|
|
2665
|
+
res.writeHead(body.status, {
|
|
2666
|
+
"content-type": "application/problem+json; charset=utf-8",
|
|
2667
|
+
"cache-control": "no-store",
|
|
2668
|
+
pragma: "no-cache",
|
|
2669
|
+
"x-request-id": requestId,
|
|
2670
|
+
});
|
|
2671
|
+
res.end(JSON.stringify(body));
|
|
2672
|
+
}
|
|
2673
|
+
function respondWorkbenchError(res, error, requestId) {
|
|
2674
|
+
if (error instanceof WorkbenchEventProjectionError) {
|
|
2675
|
+
writeWorkbenchProblem(res, "VALIDATION_ERROR", requestId, "事件游标无效", error.message);
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
if (error instanceof WorkbenchMoneyError) {
|
|
2679
|
+
writeWorkbenchProblem(res, error.code === "MONEY_RANGE_EXCEEDED" || error.code === "MONEY_PRECISION_UNRECOVERABLE"
|
|
2680
|
+
? error.code
|
|
2681
|
+
: "VALIDATION_ERROR", requestId, "金额请求未完成", error.message);
|
|
2682
|
+
return;
|
|
2683
|
+
}
|
|
2684
|
+
if (error instanceof MerchantWorkbenchError) {
|
|
2685
|
+
const code = error.kind === "not_found"
|
|
2686
|
+
? "RESOURCE_NOT_FOUND"
|
|
2687
|
+
: error.kind === "validation"
|
|
2688
|
+
? "VALIDATION_ERROR"
|
|
2689
|
+
: error.kind === "auth"
|
|
2690
|
+
? "PERMISSION_REVOKED"
|
|
2691
|
+
: "DEPENDENCY_UNAVAILABLE";
|
|
2692
|
+
writeWorkbenchProblem(res, code, requestId, "磋商请求未完成", error.message);
|
|
2693
|
+
return;
|
|
2694
|
+
}
|
|
2695
|
+
if (error instanceof MerchantPromotionError) {
|
|
2696
|
+
const code = error.code === "clock_skew"
|
|
2697
|
+
? "RUNTIME_PAUSED"
|
|
2698
|
+
: error.code === "not_found"
|
|
2699
|
+
? "RESOURCE_NOT_FOUND"
|
|
2700
|
+
: error.code === "version_conflict"
|
|
2701
|
+
? "VERSION_CONFLICT"
|
|
2702
|
+
: "VALIDATION_ERROR";
|
|
2703
|
+
writeWorkbenchProblem(res, code, requestId, "促销请求未完成", error.message);
|
|
2704
|
+
return;
|
|
2705
|
+
}
|
|
2706
|
+
if (error instanceof MerchantGrantError) {
|
|
2707
|
+
const code = error.code === "not_found"
|
|
2708
|
+
? "RESOURCE_NOT_FOUND"
|
|
2709
|
+
: error.code === "invalid_input"
|
|
2710
|
+
? "VALIDATION_ERROR"
|
|
2711
|
+
: "PERMISSION_REVOKED";
|
|
2712
|
+
writeWorkbenchProblem(res, code, requestId, "授权未通过", error.message);
|
|
2713
|
+
return;
|
|
2714
|
+
}
|
|
2715
|
+
if (error instanceof MerchantFeedError) {
|
|
2716
|
+
const code = error.code === "not_found"
|
|
2717
|
+
? "RESOURCE_NOT_FOUND"
|
|
2718
|
+
: error.code === "version_conflict"
|
|
2719
|
+
? "VERSION_CONFLICT"
|
|
2720
|
+
: "VALIDATION_ERROR";
|
|
2721
|
+
writeWorkbenchProblem(res, code, requestId, "广播请求未完成", error.message);
|
|
2722
|
+
return;
|
|
2723
|
+
}
|
|
2724
|
+
if (error instanceof WorkbenchConfirmationError) {
|
|
2725
|
+
const mapping = {
|
|
2726
|
+
invalid_registration: "CONFIRMATION_INVALID",
|
|
2727
|
+
confirmation_not_found: "RESOURCE_NOT_FOUND",
|
|
2728
|
+
confirmation_expired: "CONFIRMATION_EXPIRED",
|
|
2729
|
+
confirmation_consumed: "CONFIRMATION_INVALID",
|
|
2730
|
+
confirmation_binding_mismatch: "CONFIRMATION_INVALID",
|
|
2731
|
+
credential_unavailable: "CONFIRMATION_CHANNEL_UNAVAILABLE",
|
|
2732
|
+
assertion_invalid: "CONFIRMATION_INVALID",
|
|
2733
|
+
};
|
|
2734
|
+
writeWorkbenchProblem(res, mapping[error.code], requestId, "可信确认未完成", error.message);
|
|
2735
|
+
return;
|
|
2736
|
+
}
|
|
2737
|
+
if (error instanceof ActorContextError) {
|
|
2738
|
+
if (error.code === "expired_context") {
|
|
2739
|
+
writeWorkbenchProblem(res, "UNAUTHENTICATED", requestId, "需要重新登录", "管理会话或主体上下文已经过期。");
|
|
2740
|
+
return;
|
|
2741
|
+
}
|
|
2742
|
+
writeWorkbenchProblem(res, "INTERNAL_ERROR", requestId, "主体校验失败", "主体上下文完整性校验失败。");
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
if (error instanceof ManagementError) {
|
|
2746
|
+
const mapping = {
|
|
2747
|
+
unauthorized: "UNAUTHENTICATED",
|
|
2748
|
+
forbidden: "PERMISSION_REVOKED",
|
|
2749
|
+
not_found: "RESOURCE_NOT_FOUND",
|
|
2750
|
+
conflict: "VERSION_CONFLICT",
|
|
2751
|
+
precondition_changed: "VERSION_CONFLICT",
|
|
2752
|
+
invalid_input: "VALIDATION_ERROR",
|
|
2753
|
+
rate_limited: "RATE_LIMITED",
|
|
2754
|
+
unavailable: "DEPENDENCY_UNAVAILABLE",
|
|
2755
|
+
tool_binding_unavailable: "DEPENDENCY_UNAVAILABLE",
|
|
2756
|
+
update_required: "VERSION_CONFLICT",
|
|
2757
|
+
};
|
|
2758
|
+
writeWorkbenchProblem(res, mapping[error.code] ?? "INTERNAL_ERROR", requestId, "请求未完成", error.message, { support_id: error.supportId });
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
process.stderr.write(`[merchant-management] Workbench 未预期异常:${error instanceof Error ? error.message : String(error)}\n`);
|
|
2762
|
+
writeWorkbenchProblem(res, "INTERNAL_ERROR", requestId, "内部错误", "请求未完成,请使用请求编号联系支持。");
|
|
2763
|
+
}
|
|
2764
|
+
function respondError(res, err) {
|
|
2765
|
+
if (res.headersSent) {
|
|
2766
|
+
res.end();
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
if (err instanceof ActorContextError) {
|
|
2770
|
+
if (err.code === "expired_context") {
|
|
2771
|
+
writeJson(res, 401, errorBody("unauthorized", "management session or actor context expired"));
|
|
2772
|
+
return;
|
|
2773
|
+
}
|
|
2774
|
+
process.stderr.write(`[merchant-management] 主体上下文完整性异常:${err.message}\n`);
|
|
2775
|
+
writeJson(res, 503, errorBody("unavailable", "actor context integrity failure"));
|
|
2776
|
+
return;
|
|
2777
|
+
}
|
|
2778
|
+
if (err instanceof ManagementError) {
|
|
2779
|
+
writeJson(res, MANAGEMENT_ERROR_STATUS[err.code], errorBody(err.code, err.message, { retryable: err.retryable, supportId: err.supportId }));
|
|
2780
|
+
return;
|
|
2781
|
+
}
|
|
2782
|
+
process.stderr.write(`[merchant-management] 未预期异常:${err instanceof Error ? err.message : String(err)}\n`);
|
|
2783
|
+
writeJson(res, 503, errorBody("unavailable", "internal error"));
|
|
2784
|
+
}
|
|
2785
|
+
//# sourceMappingURL=api.js.map
|