@vesviet/agent-skills 5.7.3 → 5.10.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/INDEX.md +21 -18
- package/README.md +11 -10
- package/VERSION +1 -1
- package/adapters/antigravity/ANTIGRAVITY.md +89 -4
- package/adapters/antigravity/INDEX_TIER1.json +1294 -0
- package/adapters/antigravity/a2a-config.template.yaml +22 -8
- package/adapters/antigravity/role-skill-index.json +48 -19
- package/adapters/claude/CLAUDE_ADAPTER.md +1 -1
- package/adapters/claude/settings.template.json +7 -3
- package/adapters/cursor/hooks.template.json +3 -1
- package/core/contracts/README.md +4 -1
- package/core/contracts/schemas/INDEX.md +7 -1
- package/core/contracts/schemas/a2a-artifact.json +9 -2
- package/core/contracts/schemas/a2a-jsonrpc-envelope.json +7 -2
- package/core/contracts/schemas/a2a-task-progress.json +15 -4
- package/core/contracts/schemas/a2a-task.json +11 -3
- package/core/contracts/schemas/agent-card.json +48 -1
- package/core/contracts/schemas/agent-skills-discovery.json +91 -0
- package/core/contracts/schemas/compliance-report.json +255 -0
- package/core/contracts/schemas/mcp-server-card.json +193 -0
- package/core/contracts/schemas/seo-content-brief.json +1 -1
- package/core/contracts/schemas/seo-weekly-board.json +1 -1
- package/core/contracts/schemas/series-article.json +1 -1
- package/core/policies/action-boundaries.yaml +334 -2
- package/core/policies/mcp-tool-map.yaml +61 -4
- package/core/roles/3d-graphics-engineer.md +5 -1
- package/core/roles/README.md +1 -1
- package/core/roles/agent-coordinator.md +21 -3
- package/core/roles/agent-discovery-engineer.md +27 -8
- package/core/roles/ai-systems-engineer.md +3 -1
- package/core/roles/aws-engineer.md +6 -8
- package/core/roles/backend-developer.md +5 -5
- package/core/roles/business-analyst.md +4 -2
- package/core/roles/cloudflare-engineer.md +4 -2
- package/core/roles/content-manager.md +3 -1
- package/core/roles/content-writer.md +3 -1
- package/core/roles/data-analyst.md +3 -1
- package/core/roles/data-engineer.md +3 -1
- package/core/roles/devops-engineer.md +9 -9
- package/core/roles/ecommerce-engineer.md +7 -7
- package/core/roles/frontend-developer.md +10 -8
- package/core/roles/game-developer.md +5 -3
- package/core/roles/mmo-engineer.md +8 -9
- package/core/roles/mobile-engineer.md +5 -3
- package/core/roles/product-manager.md +8 -9
- package/core/roles/project-manager.md +10 -13
- package/core/roles/prompt-engineer.md +6 -4
- package/core/roles/qa-engineer.md +9 -9
- package/core/roles/references/vietnam-accounting-specialist-review-checklist.md +6 -6
- package/core/roles/researcher.md +12 -14
- package/core/roles/reverse-engineer.md +5 -2
- package/core/roles/reviewer.md +7 -5
- package/core/roles/role-standard.md +23 -1
- package/core/roles/sdet.md +7 -5
- package/core/roles/security-engineer.md +9 -7
- package/core/roles/seo-analyst.md +9 -7
- package/core/roles/solution-architect.md +8 -9
- package/core/roles/sre.md +8 -6
- package/core/roles/system-engineer.md +20 -20
- package/core/roles/task-planner.md +8 -10
- package/core/roles/teacher.md +8 -6
- package/core/roles/technical-architect.md +10 -8
- package/core/roles/technical-lead.md +9 -7
- package/core/roles/technical-writer.md +8 -6
- package/core/roles/ui-ux-designer.md +8 -7
- package/core/roles/vietnam-accounting-specialist.md +26 -24
- package/core/roles/vietnam-legal-counsel.md +6 -4
- package/core/rules/code.md +11 -6
- package/core/skills/README.md +3 -2
- package/core/skills/agent/agent-a2a-protocol/SKILL.md +25 -93
- package/core/skills/agent/agent-memory-compaction/SKILL.md +27 -0
- package/core/skills/agent/architect-mcp-server/SKILL.md +35 -27
- package/core/skills/agent/configure-agent-commerce/SKILL.md +2 -0
- package/core/skills/agent/configure-agent-commerce/examples/ucp-commerce-manifest-and-endpoints.json +55 -0
- package/core/skills/agent/configure-agent-commerce/references/acp-ucp-agent-commerce-manifest-specs.md +66 -0
- package/core/skills/agent/configure-agent-skills/SKILL.md +60 -68
- package/core/skills/agent/manage-agent-identity/SKILL.md +2 -0
- package/core/skills/agent/manage-agent-identity/examples/agent-identity-spire-workload.yaml +72 -0
- package/core/skills/agent/manage-agent-identity/references/nhi-lifecycle-and-token-rotation.md +45 -0
- package/core/skills/ai/openrouter-task/SKILL.md +5 -5
- package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-cases.json +529 -0
- package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-manifest.yaml +61 -0
- package/core/skills/ai-agent/agent-evaluation/scripts/run-eval-benchmark.py +856 -0
- package/core/skills/ai-agent/agent-evaluation/tests/test_golden_benchmarks.py +248 -0
- package/core/skills/ai-agent/context-optimization/SKILL.md +61 -60
- package/core/skills/ai-agent/context-optimization/examples/context-pruner-and-reorderer.py +85 -0
- package/core/skills/ai-agent/context-optimization/references/token-budgeting-and-attention-allocation.md +47 -0
- package/core/skills/ai-agent/memory-hygiene/SKILL.md +13 -0
- package/core/skills/ai-agent/memory-hygiene/examples/memory-audit-and-compaction-routine.py +90 -0
- package/core/skills/ai-agent/memory-hygiene/references/agent-memory-vault-spec.md +137 -0
- package/core/skills/ai-agent/memory-hygiene/references/owasp-asi06-and-memory-poisoning-defense.md +38 -0
- package/core/skills/backend/add-api-endpoint/examples/express-zod-rfc9457-endpoint.md +329 -0
- package/core/skills/backend/add-api-endpoint/examples/kratos-go-clean-architecture-endpoint.md +405 -0
- package/core/skills/backend/add-api-endpoint/references/idempotency-and-rate-limiting.md +116 -0
- package/core/skills/backend/add-event-handler/SKILL.md +1 -1
- package/core/skills/backend/scaffold-new-service/SKILL.md +2 -1
- package/core/skills/backend/scaffold-new-service/references/deep-modules-and-seams.md +43 -0
- package/core/skills/business/elicit-requirements/SKILL.md +1 -0
- package/core/skills/commerce/handle-checkout-flow/SKILL.md +3 -1
- package/core/skills/commerce/handle-checkout-flow/examples/production-checkout-orchestrator.ts +185 -0
- package/core/skills/commerce/handle-checkout-flow/references/pci-dss-v4-and-agentic-checkout-specs.md +72 -0
- package/core/skills/commerce/integrate-payment-gateway/SKILL.md +3 -1
- package/core/skills/commerce/integrate-payment-gateway/examples/resilient-webhook-and-mpp-handler.ts +164 -0
- package/core/skills/commerce/integrate-payment-gateway/references/mpp-x402-and-webhook-security-specs.md +47 -0
- package/core/skills/commerce/manage-order-fulfillment/SKILL.md +3 -1
- package/core/skills/commerce/manage-order-fulfillment/examples/temporal-fulfillment-saga.ts +104 -0
- package/core/skills/commerce/manage-order-fulfillment/references/event-sourced-fulfillment-and-carrier-webhooks.md +58 -0
- package/core/skills/commerce/manage-product-catalog/SKILL.md +3 -1
- package/core/skills/commerce/manage-product-catalog/examples/hybrid-search-and-governance-pipeline.ts +120 -0
- package/core/skills/commerce/manage-product-catalog/references/semantic-vector-catalog-and-graphrag.md +54 -0
- package/core/skills/content/write-article/SKILL.md +1 -1
- package/core/skills/document/pdf/SKILL.md +1 -0
- package/core/skills/document/pdf/references/pdf-acroforms-and-pdfplumber-specs.md +54 -0
- package/core/skills/document/pdf/scripts/check_fillable_fields.py +144 -0
- package/core/skills/document/pdf/scripts/fill_fillable_fields.py +145 -0
- package/core/skills/documentation/configure-llms-txt/SKILL.md +2 -0
- package/core/skills/documentation/configure-llms-txt/examples/canonical-llms-txt-and-full-txt.md +45 -0
- package/core/skills/documentation/configure-llms-txt/references/llms-txt-and-llms-full-txt-standard.md +37 -0
- package/core/skills/documentation/write-documentation/SKILL.md +3 -1
- package/core/skills/documentation/write-documentation/examples/microservice-production-readme-and-api-docs.md +70 -0
- package/core/skills/documentation/write-documentation/references/diataxis-framework-and-doc-standards.md +62 -0
- package/core/skills/foundation/ai-risk-assessment/SKILL.md +3 -5
- package/core/skills/foundation/ai-risk-assessment/examples/genai-system-risk-register.md +67 -0
- package/core/skills/foundation/ai-risk-assessment/references/nist-ai-rmf-and-eu-ai-act-taxonomy.md +49 -0
- package/core/skills/foundation/conduct-research/SKILL.md +1 -1
- package/core/skills/foundation/discernment-nudge/SKILL.md +1 -0
- package/core/skills/foundation/plan-technical-delivery/SKILL.md +2 -1
- package/core/skills/foundation/release-notes/SKILL.md +2 -3
- package/core/skills/foundation/release-notes/examples/enterprise-platform-release-notes.md +42 -0
- package/core/skills/foundation/release-notes/references/keep-a-changelog-and-semver-governance.md +43 -0
- package/core/skills/foundation/systematic-debugging/SKILL.md +5 -0
- package/core/skills/foundation/write-tests/examples/anti-tautological-tdd-walkthrough.md +204 -0
- package/core/skills/foundation/write-tests/examples/testcontainers-kratos-integration-test.md +186 -0
- package/core/skills/foundation/write-tests/references/contract-and-chaos-testing.md +187 -0
- package/core/skills/frontend/INDEX.json +16 -0
- package/core/skills/frontend/add-page-route/SKILL.md +3 -1
- package/core/skills/frontend/add-page-route/examples/streaming-rsc-page-with-view-transition.tsx +133 -0
- package/core/skills/frontend/add-page-route/references/rsc-routing-and-view-transitions.md +72 -0
- package/core/skills/frontend/add-ui-component/SKILL.md +3 -1
- package/core/skills/frontend/add-ui-component/examples/compound-dialog-and-form-actions.tsx +193 -0
- package/core/skills/frontend/add-ui-component/references/react19-component-standards-and-anti-slop.md +55 -0
- package/core/skills/frontend/component-composition/SKILL.md +2 -1
- package/core/skills/frontend/component-composition/examples/headless-combobox-compound-component.tsx +207 -0
- package/core/skills/frontend/frontend-testing/SKILL.md +3 -1
- package/core/skills/frontend/frontend-testing/examples/playwright-e2e-with-msw-and-axe.spec.ts +87 -0
- package/core/skills/frontend/frontend-testing/references/playwright-msw-and-a11y-testing-standards.md +78 -0
- package/core/skills/frontend/implement-ai-disclosure/SKILL.md +118 -0
- package/core/skills/frontend/implement-webmcp/SKILL.md +3 -1
- package/core/skills/frontend/implement-webmcp/examples/webmcp-provider-and-hitl-modal.tsx +163 -0
- package/core/skills/frontend/implement-webmcp/references/webmcp-architecture-and-hitl-security.md +48 -0
- package/core/skills/frontend/integrate-api-client/SKILL.md +3 -1
- package/core/skills/frontend/integrate-api-client/examples/orval-query-and-streaming-mutation.ts +102 -0
- package/core/skills/frontend/integrate-api-client/references/orval-tanstack-query-and-streaming-specs.md +57 -0
- package/core/skills/frontend/setup-design-system/SKILL.md +3 -1
- package/core/skills/frontend/setup-design-system/examples/tailwind-v4-theme-and-dtcg-tokens.css +87 -0
- package/core/skills/frontend/setup-design-system/references/tailwind-v4-oklch-and-dtcg-tokens.md +61 -0
- package/core/skills/frontend/setup-visual-regression/SKILL.md +3 -1
- package/core/skills/frontend/setup-visual-regression/examples/visual-regression-playwright.config.ts +83 -0
- package/core/skills/frontend/setup-visual-regression/references/visual-regression-docker-and-masking-specs.md +46 -0
- package/core/skills/gamedev/abstract-input-actions/SKILL.md +2 -0
- package/core/skills/gamedev/abstract-input-actions/examples/input-action-manager.ts +85 -0
- package/core/skills/gamedev/abstract-input-actions/references/action-mapping-and-analog-deadzones.md +54 -0
- package/core/skills/gamedev/architect-ecs-systems/SKILL.md +2 -0
- package/core/skills/gamedev/architect-ecs-systems/examples/bevy-flecs-combat-system.rs +73 -0
- package/core/skills/gamedev/architect-ecs-systems/references/data-oriented-design-and-archetype-ecs.md +39 -0
- package/core/skills/gamedev/author-game-ai/SKILL.md +2 -0
- package/core/skills/gamedev/author-game-ai/examples/modular-behavior-tree-ai.ts +98 -0
- package/core/skills/gamedev/author-game-ai/references/behavior-trees-and-utility-ai-curves.md +47 -0
- package/core/skills/gamedev/configure-physics-collision/SKILL.md +2 -0
- package/core/skills/gamedev/configure-physics-collision/examples/kinematic-physics-substepping.cpp +100 -0
- package/core/skills/gamedev/configure-physics-collision/references/continuous-collision-detection-and-substepping.md +50 -0
- package/core/skills/gamedev/develop-gameplay-systems/SKILL.md +2 -0
- package/core/skills/gamedev/develop-gameplay-systems/examples/kinematic-character-controller.gd +86 -0
- package/core/skills/gamedev/develop-gameplay-systems/references/deterministic-gameplay-state-machines.md +42 -0
- package/core/skills/gamedev/implement-save-persistence/SKILL.md +2 -0
- package/core/skills/gamedev/implement-save-persistence/examples/versioned-save-manager.ts +127 -0
- package/core/skills/gamedev/implement-save-persistence/references/versioned-save-schemas-and-checksums.md +44 -0
- package/core/skills/gamedev/render-webgl-threejs/SKILL.md +2 -0
- package/core/skills/gamedev/render-webgl-threejs/examples/production-threejs-webgpu-scene.ts +116 -0
- package/core/skills/gamedev/render-webgl-threejs/references/webgpu-threejs-pbr-pipeline.md +56 -0
- package/core/skills/mmo/analyze-campaign-roi/SKILL.md +2 -0
- package/core/skills/mmo/analyze-campaign-roi/examples/campaign-roi-and-roas-dashboard.py +80 -0
- package/core/skills/mmo/analyze-campaign-roi/references/multi-touch-attribution-and-cpa-analytics.md +33 -0
- package/core/skills/mmo/create-automation-script/SKILL.md +2 -0
- package/core/skills/mmo/create-automation-script/examples/stealth-browser-automation-flow.ts +65 -0
- package/core/skills/mmo/create-automation-script/references/stealth-cdp-and-behavioral-mimicry.md +37 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/SKILL.md +2 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/examples/proxy-health-probe-and-rotation-daemon.py +75 -0
- package/core/skills/mmo/deploy-mmo-infrastructure/references/proxy-pool-rotation-and-anti-detect-specs.md +45 -0
- package/core/skills/mmo/deploy-proxyware-fleet/SKILL.md +2 -0
- package/core/skills/mmo/deploy-proxyware-fleet/examples/docker-compose-depin-light-node-fleet.yaml +52 -0
- package/core/skills/mmo/deploy-proxyware-fleet/references/depin-bandwidth-monetization-node-specs.md +43 -0
- package/core/skills/mmo/generate-mmo-content/SKILL.md +2 -0
- package/core/skills/mmo/generate-mmo-content/examples/pseo-programmatic-page-generator.ts +76 -0
- package/core/skills/mmo/generate-mmo-content/references/pseo-landing-pages-and-social-video-hooks.md +39 -0
- package/core/skills/mmo/manage-mmo-assets/SKILL.md +2 -0
- package/core/skills/mmo/manage-mmo-assets/examples/mmo-asset-vault-manager.py +63 -0
- package/core/skills/mmo/manage-mmo-assets/references/mmo-asset-rbac-and-vault-isolation.md +38 -0
- package/core/skills/mmo/setup-tracking-system/SKILL.md +2 -0
- package/core/skills/mmo/setup-tracking-system/examples/meta-capi-s2s-event-dispatcher.ts +79 -0
- package/core/skills/mmo/setup-tracking-system/references/server-to-server-postback-and-capi-specs.md +45 -0
- package/core/skills/platform/add-telemetry-instrumentation/SKILL.md +2 -0
- package/core/skills/platform/add-telemetry-instrumentation/examples/kratos-otel-middleware-instrumentation.go +87 -0
- package/core/skills/platform/add-telemetry-instrumentation/references/opentelemetry-semantic-conventions-2026.md +37 -0
- package/core/skills/platform/aws-infrastructure/SKILL.md +2 -0
- package/core/skills/platform/aws-infrastructure/examples/opentofu-eks-pod-identity-vpc.tf +101 -0
- package/core/skills/platform/aws-infrastructure/references/opentofu-aws-zero-trust-and-irsa.md +40 -0
- package/core/skills/platform/setup-deployment/SKILL.md +4 -0
- package/core/skills/platform/setup-deployment/examples/kustomize-production-service-manifests.yaml +123 -0
- package/core/skills/platform/setup-deployment/references/interactive-hitl-wizard.md +55 -0
- package/core/skills/platform/setup-deployment/references/k8s-gitops-and-kustomize-invariants.md +40 -0
- package/core/skills/platform/supply-chain-security/SKILL.md +2 -0
- package/core/skills/platform/supply-chain-security/examples/github-actions-sbom-cosign.yaml +57 -0
- package/core/skills/platform/supply-chain-security/references/slsa-provenance-and-sbom-sigstore.md +60 -0
- package/core/skills/product/build-story-map/SKILL.md +2 -0
- package/core/skills/repo-ops/review-code/SKILL.md +2 -2
- package/core/skills/repo-ops/review-code/examples/adversarial-two-axis-pr-review.md +167 -0
- package/core/skills/repo-ops/review-code/examples/ai-vibe-slop-remediation.md +220 -0
- package/core/skills/repo-ops/review-code/references/supply-chain-and-migration-safety.md +103 -0
- package/core/skills/repo-ops/review-service/SKILL.md +1 -1
- package/core/skills/security-data/database-maintenance/SKILL.md +1 -1
- package/core/skills/security-data/manage-secrets/SKILL.md +2 -0
- package/core/skills/security-data/manage-secrets/examples/external-secrets-vault-crds.yaml +53 -0
- package/core/skills/security-data/manage-secrets/references/zero-trust-secret-rotation-and-eso.md +30 -0
- package/core/skills/security-data/manage-vietnam-accounting/SKILL.md +7 -7
- package/core/skills/security-data/prompt-injection-defense/SKILL.md +2 -0
- package/core/skills/security-data/prompt-injection-defense/examples/bounded-tool-execution-wrapper.py +78 -0
- package/core/skills/security-data/prompt-injection-defense/references/prompt-injection-taxonomy-and-delimiters.md +37 -0
- package/core/skills/security-data/reverse-engineer-binary/SKILL.md +2 -0
- package/core/skills/security-data/reverse-engineer-binary/examples/binary-triage-and-vulnerability-dossier.md +58 -0
- package/core/skills/security-data/reverse-engineer-binary/references/ghidra-radare2-and-rea-evidence-ledgers.md +43 -0
- package/core/skills/security-data/security-audit/SKILL.md +3 -1
- package/core/skills/security-data/security-audit/examples/enterprise-service-security-audit-report.md +54 -0
- package/core/skills/security-data/security-audit/references/owasp-asi-and-cvss4-threat-modeling.md +39 -0
- package/core/skills/security-data/skill-preflight-ast-check/SKILL.md +2 -0
- package/core/skills/security-data/skill-preflight-ast-check/references/ast-lethal-trifecta-and-static-vetting.md +38 -0
- package/core/skills/security-data/skill-preflight-ast-check/scripts/scan-skill-ast.py +127 -0
- package/overlays/README.md +1 -1
- package/overlays/security-research/README.md +1 -1
- package/package.json +2 -2
- package/overlays/security-research/skills/reverse-engineer-binary/SKILL.md +0 -129
package/core/skills/commerce/handle-checkout-flow/examples/production-checkout-orchestrator.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production Checkout Orchestrator
|
|
3
|
+
*
|
|
4
|
+
* Implements end-to-end checkout orchestration adhering to:
|
|
5
|
+
* - PCI DSS v4.0.1 Zero-CDE principles
|
|
6
|
+
* - Mandatory address validation lifecycle prior to tax/shipping
|
|
7
|
+
* - Agentic Commerce Protocol (ACP / UCP v2026-08-25) pre-auth gating
|
|
8
|
+
* - Economic Nexus 80% threshold monitoring
|
|
9
|
+
* - Two-phase inventory reservation with TTL
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface Address {
|
|
13
|
+
line1: string;
|
|
14
|
+
line2?: string;
|
|
15
|
+
city: string;
|
|
16
|
+
state: string;
|
|
17
|
+
postalCode: string;
|
|
18
|
+
country: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface AddressValidationResult {
|
|
22
|
+
isValid: boolean;
|
|
23
|
+
normalizedAddress?: Address;
|
|
24
|
+
errorSubcode?: 'MISSING_SECONDARY_UNIT' | 'INVALID_POSTAL_CODE' | 'UNRESOLVED_STREET';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CartLineItem {
|
|
28
|
+
sku: string;
|
|
29
|
+
quantity: number;
|
|
30
|
+
unitPriceCents: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CheckoutSessionRequest {
|
|
34
|
+
sessionId: string;
|
|
35
|
+
customerId: string;
|
|
36
|
+
agentPreAuthToken?: string;
|
|
37
|
+
items: CartLineItem[];
|
|
38
|
+
shippingAddress: Address;
|
|
39
|
+
idempotencyKey: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface TaxCalculationResult {
|
|
43
|
+
taxCents: number;
|
|
44
|
+
effectiveRate: number;
|
|
45
|
+
nexusAlertTriggered: boolean;
|
|
46
|
+
jurisdictionCode: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ThreeDsContext {
|
|
50
|
+
deviceFingerprint: string;
|
|
51
|
+
ipAddress: string;
|
|
52
|
+
userAgent: string;
|
|
53
|
+
challengePreference: 'no_preference' | 'challenge_mandate';
|
|
54
|
+
scaExemptionRequested?: 'low_value' | 'transaction_risk_analysis';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CheckoutFinalizationResult {
|
|
58
|
+
orderId: string;
|
|
59
|
+
status: 'confirmed' | 'requires_3ds_challenge' | 'rejected';
|
|
60
|
+
totalCents: number;
|
|
61
|
+
reservationId: string;
|
|
62
|
+
threeDsPayload?: {
|
|
63
|
+
acsUrl: string;
|
|
64
|
+
cReq: string;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class ProductionCheckoutOrchestrator {
|
|
69
|
+
private readonly nexusTracker: Map<string, { totalRevenueCents: number; count: number }> = new Map();
|
|
70
|
+
private readonly NEXUS_REVENUE_THRESHOLD_CENTS = 10_000_000; // $100,000
|
|
71
|
+
private readonly NEXUS_ALERT_RATIO = 0.8; // 80% alert
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Validates shipping address before any tax or shipping calculation.
|
|
75
|
+
*/
|
|
76
|
+
public async validateShippingAddress(address: Address): Promise<AddressValidationResult> {
|
|
77
|
+
if (!address.line1 || !address.postalCode || !address.country) {
|
|
78
|
+
return { isValid: false, errorSubcode: 'UNRESOLVED_STREET' };
|
|
79
|
+
}
|
|
80
|
+
// Simulate postal code check
|
|
81
|
+
if (!/^\d{5}(-\d{4})?$/.test(address.postalCode) && address.country === 'US') {
|
|
82
|
+
return { isValid: false, errorSubcode: 'INVALID_POSTAL_CODE' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
isValid: true,
|
|
87
|
+
normalizedAddress: {
|
|
88
|
+
...address,
|
|
89
|
+
line1: address.line1.trim().toUpperCase(),
|
|
90
|
+
city: address.city.trim().toUpperCase(),
|
|
91
|
+
state: address.state.trim().toUpperCase(),
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Verifies agentic commerce spending bounds under ACP / UCP specifications.
|
|
98
|
+
*/
|
|
99
|
+
public verifyAgentSpendingLimit(agentToken: string, proposedAmountCents: number): boolean {
|
|
100
|
+
const MAX_AUTONOMOUS_LIMIT_CENTS = 50_000; // $500 per transaction
|
|
101
|
+
if (!agentToken || proposedAmountCents > MAX_AUTONOMOUS_LIMIT_CENTS) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Computes tax and monitors economic nexus thresholds.
|
|
109
|
+
*/
|
|
110
|
+
public calculateTaxAndCheckNexus(state: string, subtotalCents: number): TaxCalculationResult {
|
|
111
|
+
const current = this.nexusTracker.get(state) || { totalRevenueCents: 0, count: 0 };
|
|
112
|
+
const newTotal = current.totalRevenueCents + subtotalCents;
|
|
113
|
+
const newCount = current.count + 1;
|
|
114
|
+
this.nexusTracker.set(state, { totalRevenueCents: newTotal, count: newCount });
|
|
115
|
+
|
|
116
|
+
const nexusAlertTriggered = newTotal >= (this.NEXUS_REVENUE_THRESHOLD_CENTS * this.NEXUS_ALERT_RATIO);
|
|
117
|
+
const taxRate = 0.0825; // Standard 8.25% mock jurisdiction tax
|
|
118
|
+
const taxCents = Math.round(subtotalCents * taxRate);
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
taxCents,
|
|
122
|
+
effectiveRate: taxRate,
|
|
123
|
+
nexusAlertTriggered,
|
|
124
|
+
jurisdictionCode: `${state}-STATE-SALES`,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Full checkout lifecycle orchestration.
|
|
130
|
+
*/
|
|
131
|
+
public async processCheckout(
|
|
132
|
+
request: CheckoutSessionRequest,
|
|
133
|
+
threeDs: ThreeDsContext
|
|
134
|
+
): Promise<CheckoutFinalizationResult> {
|
|
135
|
+
// 1. Mandatory Address Validation Gate
|
|
136
|
+
const addressValidation = await this.validateShippingAddress(request.shippingAddress);
|
|
137
|
+
if (!addressValidation.isValid || !addressValidation.normalizedAddress) {
|
|
138
|
+
throw new Error(`Address validation failed with subcode: ${addressValidation.errorSubcode}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 2. Compute Item Subtotal Server-Side (Zero Client-Trust)
|
|
142
|
+
const subtotalCents = request.items.reduce(
|
|
143
|
+
(sum, item) => sum + item.quantity * item.unitPriceCents,
|
|
144
|
+
0
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
// 3. Agentic Spending Gate if operating autonomously
|
|
148
|
+
if (request.agentPreAuthToken) {
|
|
149
|
+
const allowed = this.verifyAgentSpendingLimit(request.agentPreAuthToken, subtotalCents);
|
|
150
|
+
if (!allowed) {
|
|
151
|
+
throw new Error('Agent autonomous spending limit exceeded or invalid pre-auth token');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 4. Tax Engine & Nexus Evaluation
|
|
156
|
+
const tax = this.calculateTaxAndCheckNexus(addressValidation.normalizedAddress.state, subtotalCents);
|
|
157
|
+
const shippingCents = 1200; // $12.00 flat priority rate
|
|
158
|
+
const totalCents = subtotalCents + tax.taxCents + shippingCents;
|
|
159
|
+
|
|
160
|
+
// 5. Two-Phase Inventory Hold (Soft reserve with 15-minute TTL)
|
|
161
|
+
const reservationId = `res_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
162
|
+
|
|
163
|
+
// 6. EMV 3DS 2.3.1 Evaluation
|
|
164
|
+
const isExempt = subtotalCents < 3000; // €30 / $30 low-value exemption
|
|
165
|
+
if (!isExempt && threeDs.challengePreference === 'challenge_mandate') {
|
|
166
|
+
return {
|
|
167
|
+
orderId: `ord_${request.sessionId}`,
|
|
168
|
+
status: 'requires_3ds_challenge',
|
|
169
|
+
totalCents,
|
|
170
|
+
reservationId,
|
|
171
|
+
threeDsPayload: {
|
|
172
|
+
acsUrl: 'https://acs.bank.example/3ds-auth',
|
|
173
|
+
cReq: Buffer.from(JSON.stringify({ sessionId: request.sessionId, totalCents })).toString('base64'),
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
orderId: `ord_${request.sessionId}`,
|
|
180
|
+
status: 'confirmed',
|
|
181
|
+
totalCents,
|
|
182
|
+
reservationId,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# PCI DSS v4.0.1 and Agentic Checkout Specifications (2026)
|
|
2
|
+
|
|
3
|
+
## 1. Regulatory & Compliance Architecture
|
|
4
|
+
|
|
5
|
+
### 1.1 PCI DSS v4.0.1 Core Requirements
|
|
6
|
+
Compliance with Payment Card Industry Data Security Standard (PCI DSS) v4.0.1 is mandatory across all checkout touchpoints:
|
|
7
|
+
|
|
8
|
+
- **Requirement 6.4.3 (Script Integrity on Payment Pages)**:
|
|
9
|
+
- All JavaScript executed within payment contexts (both first-party and third-party) must be explicitly inventoried with legitimate business justification.
|
|
10
|
+
- Scripts must be loaded with **Subresource Integrity (SRI)** hashes (`integrity="sha384-..."`) and cryptographically bound via a per-request strict **Content Security Policy (CSP)** nonce (`script-src 'nonce-<random-b64>' 'strict-dynamic'`).
|
|
11
|
+
- Inline event handlers (`onclick`, `onload`) are strictly prohibited.
|
|
12
|
+
- **Requirement 11.6.1 (Client-Side Tamper Detection)**:
|
|
13
|
+
- Implement continuous or weekly automated integrity checks comparing live script hashes and HTTP headers against canonical deployment baselines.
|
|
14
|
+
- Immediate alerting on unauthorized script injection or DOM tampering (Magecart / digital skimming mitigation).
|
|
15
|
+
- **SAQ A Scope Boundaries**:
|
|
16
|
+
- Entire cardholder data environment (CDE) must be fully outsourced to validated third-party payment processors using hosted fields, iframes, or modal redirects.
|
|
17
|
+
- Zero raw Primary Account Numbers (PAN), CVV/CVC, or track data may enter the merchant runtime, application memory, or logging layer.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Agentic Commerce Protocols (ACP & UCP)
|
|
22
|
+
|
|
23
|
+
### 2.1 Protocol Topology
|
|
24
|
+
Modern commerce systems support autonomous agent transactions across two interoperable frameworks:
|
|
25
|
+
- **Agentic Commerce Protocol (ACP)** (OpenAI / Stripe): Optimized for headless, tool-driven instant checkout inside conversational runtimes.
|
|
26
|
+
- **Universal Commerce Protocol (UCP v2026-08-25)**: Open standard (Apache 2.0) compatible with Agent-to-Agent (A2A 1.0), AP2 v0.2, and Model Context Protocol (MCP).
|
|
27
|
+
|
|
28
|
+
### 2.2 Autonomous Payment Gates & Risk Controls
|
|
29
|
+
- **Pre-Authorization Limits**: Each agent session must operate within an explicit credit line or balance authorization token (e.g., maximum $500 per transaction, $2,000 per 24 hours).
|
|
30
|
+
- **Merchant of Record (MoR)**: Explicit declaration of MoR for tax remittance, chargeback liability, and regulatory reporting on agent-initiated sales.
|
|
31
|
+
- **AP2 v0.2 (Human-Not-Present FIDO Token)**: Autonomous checkout uses pre-authorized cryptographic assertions bound to the user's biometric authenticator, bypassing interactive browser challenges.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 3. Risk-Based Authentication & Frictionless 3DS
|
|
36
|
+
|
|
37
|
+
### 3.1 EMV 3DS 2.3.1 Specification
|
|
38
|
+
- Over 100 contextual attributes transmitted in the 3DS request: device fingerprint, behavioral telemetry, IP velocity, browser plugins, account age, shipping/billing address match.
|
|
39
|
+
- **Strong Customer Authentication (SCA) Exemption Engine**:
|
|
40
|
+
- *Low-Value Transactions*: Transactions < €30 or regional equivalent.
|
|
41
|
+
- *Transaction Risk Analysis (TRA)*: Qualified acquirer exemption for low-fraud merchant tiers.
|
|
42
|
+
- *Trusted Beneficiary / Whitelisting*: Customer-approved merchant exemptions.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 4. Address Validation Lifecycle
|
|
47
|
+
|
|
48
|
+
Address validation must occur as an isolated, mandatory gate **prior** to tax calculation or shipping carrier quotation:
|
|
49
|
+
1. **Normalization**: Parse street lines, postal codes, and regional subdivisions via Loqate, Google Maps Address Validation, or Smarty Streets.
|
|
50
|
+
2. **Subcode Resolution**: Evaluate granular API subcodes (`MISSING_SECONDARY_UNIT`, `INVALID_POSTAL_CODE`, `UNCONFIRMED_STREET`). Reject or prompt correction before downstream processing.
|
|
51
|
+
3. **Delivery Point Validation (DPV)**: Confirm mailable delivery point status (`DPV: Y`).
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 5. Tax Engine & Economic Nexus Decision Tree
|
|
56
|
+
|
|
57
|
+
### 5.1 Tax Engine Selection Matrix
|
|
58
|
+
- **Stripe Tax**: Recommended for digital-native merchants operating entirely on Stripe infrastructure; automated registration and instant calculation.
|
|
59
|
+
- **TaxJar**: Multi-channel retailers (combining custom e-commerce with Shopify/Amazon); automated filing support.
|
|
60
|
+
- **Avalara AvaTax**: Enterprise systems with complex supply chains, custom ERPs (SAP, NetSuite), cross-border VAT/GST, and specialized commodity exemptions.
|
|
61
|
+
|
|
62
|
+
### 5.2 Economic Nexus 80% Early-Warning System
|
|
63
|
+
- Monitor state-by-state gross receipts and transaction frequencies.
|
|
64
|
+
- Trigger automatic alert and compliance ticket when volume reaches 80% of statutory nexus thresholds (e.g., $80,000 revenue or 160 transactions in $100K/200-transaction jurisdictions).
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 6. Vietnam Regulatory Compliance (Decree 248/2026/ND-CP)
|
|
69
|
+
|
|
70
|
+
- **Seller Identity Verification**: Digital identity verification mandatory for all marketplace sellers prior to catalog listing and payout clearance.
|
|
71
|
+
- **Platform Disclosures**: Public display of platform rights, resolution dispute standards, transparent pricing structures, and affiliate partner relationships.
|
|
72
|
+
- **Electronic ID Integration**: Electronic citizen ID verification (VNeID level 2) enforced for commercial sellers and live streamers.
|
|
@@ -179,5 +179,7 @@ Skip emission for local sandbox experiments that do not cross a role boundary.
|
|
|
179
179
|
- **security-audit**: Review payment integration for PCI exposure
|
|
180
180
|
- **add-api-endpoint**: Scaffold the payment and webhook controller endpoints
|
|
181
181
|
- **configure-agent-commerce**: Implement x402 HTTP billing, MPP endpoints, and agent commerce registration
|
|
182
|
+
- Companion reference: `references/mpp-x402-and-webhook-security-specs.md`
|
|
183
|
+
- Companion example: `examples/resilient-webhook-and-mpp-handler.ts`
|
|
182
184
|
|
|
183
|
-
Last updated: 2026-
|
|
185
|
+
Last updated: 2026-11-08
|
package/core/skills/commerce/integrate-payment-gateway/examples/resilient-webhook-and-mpp-handler.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resilient Webhook and MPP (HTTP 402) Payment Handler
|
|
3
|
+
*
|
|
4
|
+
* Implements:
|
|
5
|
+
* - Constant-time HMAC SHA-256 raw payload signature verification
|
|
6
|
+
* - 300-second replay attack protection window
|
|
7
|
+
* - Fast queue-first response (<500ms) with distributed deduplication
|
|
8
|
+
* - HTTP 402 / x402 programmatic agent negotiation
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as crypto from 'crypto';
|
|
12
|
+
|
|
13
|
+
export interface WebhookEventPayload {
|
|
14
|
+
id: string;
|
|
15
|
+
type: string;
|
|
16
|
+
created: number; // Unix timestamp
|
|
17
|
+
data: {
|
|
18
|
+
object: {
|
|
19
|
+
id: string;
|
|
20
|
+
amount: number;
|
|
21
|
+
currency: string;
|
|
22
|
+
status: string;
|
|
23
|
+
metadata?: Record<string, string>;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface IngestionQueue {
|
|
29
|
+
enqueue(topic: string, event: WebhookEventPayload): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DistributedLockProvider {
|
|
33
|
+
acquire(key: string, ttlMs: number): Promise<boolean>;
|
|
34
|
+
release(key: string): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class ResilientPaymentHandler {
|
|
38
|
+
constructor(
|
|
39
|
+
private readonly webhookSecret: string,
|
|
40
|
+
private readonly queue: IngestionQueue,
|
|
41
|
+
private readonly lockProvider: DistributedLockProvider
|
|
42
|
+
) {}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Verifies raw payload signature using constant-time HMAC comparison.
|
|
46
|
+
*/
|
|
47
|
+
public verifyStripeSignature(rawBody: Buffer, signatureHeader: string): boolean {
|
|
48
|
+
const parts = signatureHeader.split(',');
|
|
49
|
+
let timestamp = '';
|
|
50
|
+
let expectedSignature = '';
|
|
51
|
+
|
|
52
|
+
for (const part of parts) {
|
|
53
|
+
const [key, value] = part.trim().split('=');
|
|
54
|
+
if (key === 't') timestamp = value;
|
|
55
|
+
if (key === 'v1') expectedSignature = value;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!timestamp || !expectedSignature) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Check 300-second replay window
|
|
63
|
+
const eventTime = parseInt(timestamp, 10);
|
|
64
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
|
65
|
+
if (Math.abs(currentTime - eventTime) > 300) {
|
|
66
|
+
return false; // Replay window exceeded
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Compute expected HMAC digest over raw bytes
|
|
70
|
+
const signedPayload = `${timestamp}.${rawBody.toString('utf-8')}`;
|
|
71
|
+
const computedSignature = crypto
|
|
72
|
+
.createHmac('sha256', this.webhookSecret)
|
|
73
|
+
.update(signedPayload)
|
|
74
|
+
.digest('hex');
|
|
75
|
+
|
|
76
|
+
const bufComputed = Buffer.from(computedSignature, 'utf-8');
|
|
77
|
+
const bufExpected = Buffer.from(expectedSignature, 'utf-8');
|
|
78
|
+
|
|
79
|
+
if (bufComputed.length !== bufExpected.length) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return crypto.timingSafeEqual(bufComputed, bufExpected);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Queue-first webhook ingestion endpoint handler.
|
|
88
|
+
*/
|
|
89
|
+
public async handleWebhook(
|
|
90
|
+
rawBody: Buffer,
|
|
91
|
+
signatureHeader: string
|
|
92
|
+
): Promise<{ statusCode: number; message: string }> {
|
|
93
|
+
const startTime = Date.now();
|
|
94
|
+
|
|
95
|
+
// 1. Signature Verification
|
|
96
|
+
const isValid = this.verifyStripeSignature(rawBody, signatureHeader);
|
|
97
|
+
if (!isValid) {
|
|
98
|
+
return { statusCode: 400, message: 'Invalid signature or expired replay window' };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 2. Parse Event JSON safely after signature check
|
|
102
|
+
const event: WebhookEventPayload = JSON.parse(rawBody.toString('utf-8'));
|
|
103
|
+
|
|
104
|
+
// 3. Distributed Deduplication Lock
|
|
105
|
+
const lockKey = `lock:webhook:event:${event.id}`;
|
|
106
|
+
const acquired = await this.lockProvider.acquire(lockKey, 30_000);
|
|
107
|
+
if (!acquired) {
|
|
108
|
+
// Event already being handled concurrently
|
|
109
|
+
return { statusCode: 200, message: 'Event already in processing' };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// 4. Offload to Queue for asynchronous background processing
|
|
114
|
+
await this.queue.enqueue('payment.events', event);
|
|
115
|
+
|
|
116
|
+
const durationMs = Date.now() - startTime;
|
|
117
|
+
if (durationMs > 500) {
|
|
118
|
+
console.warn(`[PERF ALERT] Webhook ingestion took ${durationMs}ms (>500ms SLA)`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return { statusCode: 200, message: 'Enqueued' };
|
|
122
|
+
} finally {
|
|
123
|
+
await this.lockProvider.release(lockKey);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Generates an HTTP 402 Payment Required response for autonomous agent callers (MPP / x402).
|
|
129
|
+
*/
|
|
130
|
+
public generateMppChallenge(
|
|
131
|
+
resourceId: string,
|
|
132
|
+
priceUsdc: number,
|
|
133
|
+
depositAddress: string
|
|
134
|
+
): {
|
|
135
|
+
statusCode: 402;
|
|
136
|
+
headers: Record<string, string>;
|
|
137
|
+
body: Record<string, unknown>;
|
|
138
|
+
} {
|
|
139
|
+
const challengePayload = {
|
|
140
|
+
version: 'x402-v1',
|
|
141
|
+
resource_id: resourceId,
|
|
142
|
+
accepted_currencies: ['USDC-BASE', 'USDC-TEMPO'],
|
|
143
|
+
amount: priceUsdc,
|
|
144
|
+
deposit_address: depositAddress,
|
|
145
|
+
valid_until: Math.floor(Date.now() / 1000) + 900, // 15 min expiry
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const encodedChallenge = Buffer.from(JSON.stringify(challengePayload)).toString('base64');
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
statusCode: 402,
|
|
152
|
+
headers: {
|
|
153
|
+
'Content-Type': 'application/json',
|
|
154
|
+
'Payment-Required': encodedChallenge,
|
|
155
|
+
'WWW-Authenticate': `MPP realm="api", token="${encodedChallenge}"`,
|
|
156
|
+
},
|
|
157
|
+
body: {
|
|
158
|
+
error: 'Payment Required',
|
|
159
|
+
message: 'Resource requires pre-authorized MPP / x402 token or crypto settlement.',
|
|
160
|
+
challenge: challengePayload,
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Machine Payments Protocol (MPP), x402, and Webhook Security Specifications (2026)
|
|
2
|
+
|
|
3
|
+
## 1. Webhook Ingestion & Cryptographic Verification
|
|
4
|
+
|
|
5
|
+
### 1.1 HMAC SHA-256 Signature Hardening
|
|
6
|
+
Payment webhook endpoints are the primary target for unauthorized state transition tampering. The following invariants are non-negotiable:
|
|
7
|
+
- **Raw Payload Preservation**: The HMAC signature must be calculated exclusively over the raw, unparsed byte buffer of the HTTP request body (`req.rawBody`). Any JSON re-serialization before verification introduces whitespace/key-ordering mutations that break cryptographic integrity.
|
|
8
|
+
- **Constant-Time Comparison**: Comparison between computed and transmitted HMAC digests must use constant-time operations (`crypto.timingSafeEqual` in Node.js or `hmac.compare_digest` in Python) to prevent statistical timing side-channel attacks.
|
|
9
|
+
- **Replay Window Enforcement**: Reject any webhook where the payload timestamp drifts by more than 300 seconds ($T_{drift} > 300\text{s}$) relative to server time ($T_{now}$).
|
|
10
|
+
|
|
11
|
+
### 1.2 Queue-First Architecture (<500ms SLA)
|
|
12
|
+
To guarantee high availability and prevent gateway timeouts:
|
|
13
|
+
1. Verify signature over raw bytes.
|
|
14
|
+
2. Persist the raw event to an asynchronous durable message queue (Kafka, Cloudflare Queues, AWS SQS, or RabbitMQ).
|
|
15
|
+
3. Immediately return HTTP `200 OK` within 500ms.
|
|
16
|
+
4. Downstream consumer workers execute business logic (ledger booking, fulfillment dispatch).
|
|
17
|
+
|
|
18
|
+
### 1.3 Dual-Write Idempotency Guards
|
|
19
|
+
Webhook delivery semantics are strictly at-least-once. To ensure exactly-once execution:
|
|
20
|
+
- **Database Composite Constraint**: Enforce a unique database constraint on `(provider, event_id, event_type)`.
|
|
21
|
+
- **Distributed Lock**: Acquire a distributed lock (Redis Redlock or PostgreSQL Advisory Lock) keyed by `lock:payment:event:<event_id>` with a 30-second TTL before initiating order state transitions.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 2. Machine Payments Protocol (MPP) & HTTP 402 / x402
|
|
26
|
+
|
|
27
|
+
### 2.1 Autonomous Agent Payment Flow
|
|
28
|
+
Autonomous AI agents interact with paywalled APIs via the Machine Payments Protocol (MPP) and the open x402 specification:
|
|
29
|
+
|
|
30
|
+
1. **Challenge Stage**: Client agent requests a restricted resource; server responds with HTTP `402 Payment Required` accompanied by the `Payment-Required` challenge header containing base64-encoded payment schemes, pricing, and deposit addresses.
|
|
31
|
+
2. **Credential Negotiation**:
|
|
32
|
+
- *Fiat / Cards*: Shared Payment Tokens (SPTs) or off-session `SetupIntents` with `setup_future_usage: "off_session"`.
|
|
33
|
+
- *Stablecoins*: USDC on Base or Tempo network via Coinbase Developer Platform (CDP) facilitators.
|
|
34
|
+
3. **Settlement Verification**:
|
|
35
|
+
- Merchant validates the on-chain transaction receipt or Stripe `crypto` transaction verification object (`POST /v1/crypto/deposit_addresses`).
|
|
36
|
+
4. **Fulfillment**: Once verified, the server yields the requested resource payload with payment confirmation headers.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 3. Account-to-Account (A2A) Pay by Bank Settlement
|
|
41
|
+
|
|
42
|
+
### 3.1 Asynchronous Settlement State Machine
|
|
43
|
+
Bank-to-bank direct payment rails (Plaid, TrueLayer, Stripe Pay by Bank) execute across asynchronous settlement phases:
|
|
44
|
+
- `processing`: Initial customer bank consent and payment initiation.
|
|
45
|
+
- `pending`: ACH/SEPA clearance in flight. Inventory must be protected with a soft TTL lock (typically 48–72 hours).
|
|
46
|
+
- `settled`: Final funds settlement confirmed via signed webhook. Order transitions to `paid`, locking inventory hard.
|
|
47
|
+
- `failed` / `cancelled`: Settlement rejected or NSF. Soft inventory lock automatically releases via sweeper.
|
|
@@ -193,5 +193,7 @@ Skip emission for single-order experiments that do not cross a role boundary.
|
|
|
193
193
|
- **add-event-handler**: Handle carrier tracking webhooks and order state events
|
|
194
194
|
- **add-api-endpoint**: Expose fulfillment status and return endpoints
|
|
195
195
|
- **incident-report**: Escalate lost packages, carrier failures, and refund disputes
|
|
196
|
+
- Companion reference: `references/event-sourced-fulfillment-and-carrier-webhooks.md`
|
|
197
|
+
- Companion example: `examples/temporal-fulfillment-saga.ts`
|
|
196
198
|
|
|
197
|
-
Last updated: 2026-
|
|
199
|
+
Last updated: 2026-11-08
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production Temporal Fulfillment Saga Workflow
|
|
3
|
+
*
|
|
4
|
+
* Implements:
|
|
5
|
+
* - Orchestration-based Saga with explicit compensating activities
|
|
6
|
+
* - Reverse compensation order (Shipping -> Inventory -> Payment)
|
|
7
|
+
* - Deterministic event generation for event-sourced projections
|
|
8
|
+
* - Vietnamese carrier label generation (GHN integration)
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface FulfillmentSagaInput {
|
|
12
|
+
orderId: string;
|
|
13
|
+
customerId: string;
|
|
14
|
+
items: Array<{ sku: string; quantity: number }>;
|
|
15
|
+
shippingAddress: {
|
|
16
|
+
name: string;
|
|
17
|
+
phone: string;
|
|
18
|
+
address: string;
|
|
19
|
+
wardCode: string;
|
|
20
|
+
districtId: number;
|
|
21
|
+
};
|
|
22
|
+
totalAmountCents: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface InventoryAllocation {
|
|
26
|
+
allocationId: string;
|
|
27
|
+
orderId: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ShippingLabel {
|
|
31
|
+
trackingCode: string;
|
|
32
|
+
carrierOrderCode: string;
|
|
33
|
+
labelUrl: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Workflow Activities Contract
|
|
37
|
+
export interface FulfillmentActivities {
|
|
38
|
+
allocateInventory(orderId: string, items: Array<{ sku: string; quantity: number }>): Promise<InventoryAllocation>;
|
|
39
|
+
releaseInventory(allocationId: string): Promise<void>;
|
|
40
|
+
createGhnShippingOrder(input: FulfillmentSagaInput): Promise<ShippingLabel>;
|
|
41
|
+
cancelGhnShippingOrder(carrierOrderCode: string): Promise<void>;
|
|
42
|
+
capturePayment(orderId: string, amountCents: number): Promise<{ paymentId: string }>;
|
|
43
|
+
refundPayment(paymentId: string, reason: string): Promise<void>;
|
|
44
|
+
recordOrderEvent(orderId: string, eventType: string, payload: Record<string, unknown>): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function fulfillmentSagaWorkflow(
|
|
48
|
+
input: FulfillmentSagaInput,
|
|
49
|
+
activities: FulfillmentActivities
|
|
50
|
+
): Promise<{ status: 'fulfilled' | 'compensated'; trackingCode?: string; error?: string }> {
|
|
51
|
+
const compensations: Array<() => Promise<void>> = [];
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
// Step 1: Capture Payment (or verify prior capture)
|
|
55
|
+
await activities.recordOrderEvent(input.orderId, 'order_placed', { total: input.totalAmountCents });
|
|
56
|
+
const payment = await activities.capturePayment(input.orderId, input.totalAmountCents);
|
|
57
|
+
compensations.push(async () => {
|
|
58
|
+
await activities.refundPayment(payment.paymentId, 'Fulfillment saga failure compensation');
|
|
59
|
+
await activities.recordOrderEvent(input.orderId, 'payment_refunded', { paymentId: payment.paymentId });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Step 2: Allocate Inventory
|
|
63
|
+
const allocation = await activities.allocateInventory(input.orderId, input.items);
|
|
64
|
+
compensations.push(async () => {
|
|
65
|
+
await activities.releaseInventory(allocation.allocationId);
|
|
66
|
+
await activities.recordOrderEvent(input.orderId, 'inventory_released', { allocationId: allocation.allocationId });
|
|
67
|
+
});
|
|
68
|
+
await activities.recordOrderEvent(input.orderId, 'inventory_allocated', { allocationId: allocation.allocationId });
|
|
69
|
+
|
|
70
|
+
// Step 3: Generate Vietnamese Carrier Label (GHN)
|
|
71
|
+
const shippingLabel = await activities.createGhnShippingOrder(input);
|
|
72
|
+
compensations.push(async () => {
|
|
73
|
+
await activities.cancelGhnShippingOrder(shippingLabel.carrierOrderCode);
|
|
74
|
+
await activities.recordOrderEvent(input.orderId, 'shipping_cancelled', { code: shippingLabel.carrierOrderCode });
|
|
75
|
+
});
|
|
76
|
+
await activities.recordOrderEvent(input.orderId, 'carrier_dispatched', {
|
|
77
|
+
carrier: 'GHN',
|
|
78
|
+
trackingCode: shippingLabel.trackingCode,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
status: 'fulfilled',
|
|
83
|
+
trackingCode: shippingLabel.trackingCode,
|
|
84
|
+
};
|
|
85
|
+
} catch (err: unknown) {
|
|
86
|
+
const errorMsg = err instanceof Error ? err.message : 'Unknown fulfillment failure';
|
|
87
|
+
await activities.recordOrderEvent(input.orderId, 'fulfillment_failed', { error: errorMsg });
|
|
88
|
+
|
|
89
|
+
// Execute compensations in strict reverse order
|
|
90
|
+
while (compensations.length > 0) {
|
|
91
|
+
const compensate = compensations.pop()!;
|
|
92
|
+
try {
|
|
93
|
+
await compensate();
|
|
94
|
+
} catch (compErr) {
|
|
95
|
+
console.error(`[CRITICAL] Compensation failed during rollback for ${input.orderId}:`, compErr);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
status: 'compensated',
|
|
101
|
+
error: errorMsg,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Event-Sourced Order Fulfillment & Carrier Webhook Specifications (2026)
|
|
2
|
+
|
|
3
|
+
## 1. Event-Sourced Order State Machine
|
|
4
|
+
|
|
5
|
+
### 1.1 Append-Only Event Log Architecture
|
|
6
|
+
Direct mutable updates to order status (e.g., `UPDATE orders SET status = 'shipped'`) are strictly prohibited. Order state is modeled as an append-only stream of immutable events:
|
|
7
|
+
1. `order_placed`: Cart confirmed, preliminary reservation recorded.
|
|
8
|
+
2. `payment_captured`: Payment processor confirmed settlement.
|
|
9
|
+
3. `inventory_allocated`: Hard decrement on warehouse bins.
|
|
10
|
+
4. `fulfillment_started`: Picking list generated and dispatched.
|
|
11
|
+
5. `packed`: Box sealed, dimensions and weight verified.
|
|
12
|
+
6. `carrier_dispatched`: Handed off to carrier courier with tracking ID.
|
|
13
|
+
7. `in_transit`: Scanned at regional carrier sorting hub.
|
|
14
|
+
8. `out_for_delivery`: Loaded onto last-mile vehicle.
|
|
15
|
+
9. `delivery_confirmed`: Signed proof of delivery (POD) recorded.
|
|
16
|
+
10. `return_initiated` / `inspection_completed` / `restocked`: Controlled return lifecycle.
|
|
17
|
+
|
|
18
|
+
Current status is computed by applying a deterministic projection function over the event history:
|
|
19
|
+
$$\text{State}_N = \text{Fold}(\text{InitialState}, [E_1, E_2, \dots, E_N])$$
|
|
20
|
+
|
|
21
|
+
### 1.2 Warehouse Restock Inspection Gate
|
|
22
|
+
Returned merchandise must never be automatically restored to sellable inventory upon Return Merchandise Authorization (RMA) generation. The event stream requires:
|
|
23
|
+
$$\text{return\_received} \longrightarrow \text{inspection\_completed (Grade A confirmed)} \longrightarrow \text{restocked}$$
|
|
24
|
+
Merchandise graded below Grade A is routed to liquidation or refurbishment streams.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 2. Orchestration-Based Saga Architecture (Temporal)
|
|
29
|
+
|
|
30
|
+
### 2.1 Forward Actions & Compensations
|
|
31
|
+
Distributed e-commerce fulfillment requires an orchestrator managing compensating transactions in strict reverse order:
|
|
32
|
+
- **Activity 1**: `AllocateInventory` $\longleftrightarrow$ **Compensating Activity**: `ReleaseInventoryAllocation`
|
|
33
|
+
- **Activity 2**: `GenerateCarrierLabel` $\longleftrightarrow$ **Compensating Activity**: `VoidCarrierLabel`
|
|
34
|
+
- **Activity 3**: `CapturePayment` $\longleftrightarrow$ **Compensating Activity**: `IssueStripeRefund`
|
|
35
|
+
|
|
36
|
+
If `GenerateCarrierLabel` encounters an unrecoverable routing error (e.g., remote province embargo), the Saga triggers compensations in reverse:
|
|
37
|
+
1. `VoidCarrierLabel` (if partially allocated).
|
|
38
|
+
2. `ReleaseInventoryAllocation` (restores stock immediately).
|
|
39
|
+
3. `IssueStripeRefund` (credits customer card).
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 3. Vietnamese Last-Mile Carrier Webhook Normalization
|
|
44
|
+
|
|
45
|
+
Carrier webhooks must be verified via HMAC signatures and mapped to normalized internal status milestones:
|
|
46
|
+
|
|
47
|
+
| Carrier | Raw Status Code | Normalized Milestone |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| **GHN** | `ready_to_pick` | `label_created` |
|
|
50
|
+
| **GHN** | `delivering` | `in_transit` |
|
|
51
|
+
| **GHN** | `delivered` | `delivery_confirmed` |
|
|
52
|
+
| **GHTK (G1)** | `1` (Chưa tiếp nhận) | `label_created` |
|
|
53
|
+
| **GHTK (G1)** | `3` (Đang lấy hàng) | `picked_up` |
|
|
54
|
+
| **GHTK (G1)** | `5` (Đang giao hàng) | `out_for_delivery` |
|
|
55
|
+
| **GHTK (G1)** | `6` (Đã giao hàng) | `delivery_confirmed` |
|
|
56
|
+
| **GrabExpress** | `ALLOCATING` | `label_created` |
|
|
57
|
+
| **GrabExpress** | `PICKED_UP` | `picked_up` |
|
|
58
|
+
| **GrabExpress** | `COMPLETED` | `delivery_confirmed` |
|
|
@@ -180,5 +180,7 @@ Clarify before building:
|
|
|
180
180
|
- **build-data-pipeline**: Synchronize product data from ERP, supplier feeds, or PIM systems
|
|
181
181
|
- **add-api-endpoint**: Expose catalog CRUD endpoints for admin and storefront consumers
|
|
182
182
|
- **database-maintenance**: Maintain catalog indexes and handle bulk data operations
|
|
183
|
+
- Companion reference: `references/semantic-vector-catalog-and-graphrag.md`
|
|
184
|
+
- Companion example: `examples/hybrid-search-and-governance-pipeline.ts`
|
|
183
185
|
|
|
184
|
-
Last updated: 2026-
|
|
186
|
+
Last updated: 2026-11-08
|