@relyon/kit 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +75 -0
- package/CHANGELOG.md +1053 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +239 -0
- package/README.md +117 -2
- package/dist/adapters/express.d.ts +39 -0
- package/dist/adapters/express.js +106 -0
- package/dist/adapters/hono.d.ts +16 -0
- package/dist/adapters/hono.js +15 -0
- package/dist/adapters/next.d.ts +29 -0
- package/dist/adapters/next.js +38 -0
- package/dist/agent-card.d.ts +14 -0
- package/dist/agent-card.js +58 -0
- package/dist/agent-docs.d.ts +36 -0
- package/dist/agent-docs.js +78 -0
- package/dist/agent-hooks.d.ts +66 -0
- package/dist/agent-hooks.js +280 -0
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +120 -0
- package/dist/api-key.d.ts +6 -0
- package/dist/api-key.js +33 -0
- package/dist/cache.d.ts +46 -0
- package/dist/cache.js +86 -0
- package/dist/cart-tokens.d.ts +31 -0
- package/dist/cart-tokens.js +58 -0
- package/dist/cart-transfer.d.ts +95 -0
- package/dist/cart-transfer.js +387 -0
- package/dist/catalog-enrichment.d.ts +6 -0
- package/dist/catalog-enrichment.js +71 -0
- package/dist/catalog-reads.d.ts +126 -0
- package/dist/catalog-reads.js +104 -0
- package/dist/catalog.d.ts +78 -0
- package/dist/catalog.js +288 -0
- package/dist/charge-claims.d.ts +11 -0
- package/dist/charge-claims.js +47 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +152 -0
- package/dist/checklist-manifest.d.ts +72 -0
- package/dist/checklist-manifest.js +341 -0
- package/dist/checkout.d.ts +222 -0
- package/dist/checkout.js +353 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +727 -0
- package/dist/confirmation.d.ts +78 -0
- package/dist/confirmation.js +124 -0
- package/dist/context.d.ts +81 -0
- package/dist/context.js +10 -0
- package/dist/discovery.d.ts +151 -0
- package/dist/discovery.js +346 -0
- package/dist/doctor-cart-transfer.d.ts +33 -0
- package/dist/doctor-cart-transfer.js +186 -0
- package/dist/doctor-catalog.d.ts +8 -0
- package/dist/doctor-catalog.js +47 -0
- package/dist/doctor-evidence.d.ts +22 -0
- package/dist/doctor-evidence.js +57 -0
- package/dist/doctor-merchant.d.ts +48 -0
- package/dist/doctor-merchant.js +74 -0
- package/dist/doctor-source.d.ts +5 -0
- package/dist/doctor-source.js +142 -0
- package/dist/doctor-variants.d.ts +70 -0
- package/dist/doctor-variants.js +102 -0
- package/dist/doctor.d.ts +215 -0
- package/dist/doctor.js +1689 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.js +200 -0
- package/dist/feed-mapping.d.ts +114 -0
- package/dist/feed-mapping.js +152 -0
- package/dist/feed-values.d.ts +13 -0
- package/dist/feed-values.js +40 -0
- package/dist/feeds.d.ts +104 -0
- package/dist/feeds.js +366 -0
- package/dist/identify.d.ts +102 -0
- package/dist/identify.js +124 -0
- package/dist/identity.d.ts +37 -0
- package/dist/identity.js +54 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +41 -0
- package/dist/init.d.ts +157 -0
- package/dist/init.js +912 -0
- package/dist/kit-config.d.ts +19 -0
- package/dist/kit-config.js +43 -0
- package/dist/kit-environment.d.ts +20 -0
- package/dist/kit-environment.js +32 -0
- package/dist/kit-updates.d.ts +47 -0
- package/dist/kit-updates.js +77 -0
- package/dist/kit-version-project.d.ts +18 -0
- package/dist/kit-version-project.js +214 -0
- package/dist/kit-version.d.ts +37 -0
- package/dist/kit-version.js +162 -0
- package/dist/kit.d.ts +516 -0
- package/dist/kit.js +1309 -0
- package/dist/layers/pages.d.ts +3 -0
- package/dist/layers/pages.js +5 -0
- package/dist/layers/payments.d.ts +7 -0
- package/dist/layers/payments.js +9 -0
- package/dist/layers/products.d.ts +10 -0
- package/dist/layers/products.js +13 -0
- package/dist/live.d.ts +13 -0
- package/dist/live.js +52 -0
- package/dist/mcp.d.ts +270 -0
- package/dist/mcp.js +312 -0
- package/dist/next-steps.d.ts +101 -0
- package/dist/next-steps.js +257 -0
- package/dist/order-pending.d.ts +57 -0
- package/dist/order-pending.js +127 -0
- package/dist/orders.d.ts +12 -0
- package/dist/orders.js +21 -0
- package/dist/payments-init.d.ts +19 -0
- package/dist/payments-init.js +70 -0
- package/dist/payments-routes.d.ts +54 -0
- package/dist/payments-routes.js +123 -0
- package/dist/payments.d.ts +165 -0
- package/dist/payments.js +192 -0
- package/dist/pnpm-workspace.d.ts +58 -0
- package/dist/pnpm-workspace.js +250 -0
- package/dist/policies.d.ts +111 -0
- package/dist/policies.js +317 -0
- package/dist/preview-hosts.d.ts +64 -0
- package/dist/preview-hosts.js +175 -0
- package/dist/private-config.d.ts +169 -0
- package/dist/private-config.js +820 -0
- package/dist/progress.d.ts +54 -0
- package/dist/progress.js +153 -0
- package/dist/protocol-inputs.d.ts +22 -0
- package/dist/protocol-inputs.js +151 -0
- package/dist/public-origin.d.ts +50 -0
- package/dist/public-origin.js +180 -0
- package/dist/refusals.d.ts +86 -0
- package/dist/refusals.js +157 -0
- package/dist/relay.d.ts +107 -0
- package/dist/relay.js +655 -0
- package/dist/release-notes.d.ts +2 -0
- package/dist/release-notes.js +290 -0
- package/dist/relyon-cart-tokens.d.ts +101 -0
- package/dist/relyon-cart-tokens.js +521 -0
- package/dist/relyon.d.ts +141 -0
- package/dist/relyon.js +238 -0
- package/dist/robots.d.ts +27 -0
- package/dist/robots.js +127 -0
- package/dist/rules.d.ts +144 -0
- package/dist/rules.js +347 -0
- package/dist/sdk/generated/public-api.d.ts +4816 -0
- package/dist/sdk/generated/public-api.js +1 -0
- package/dist/sdk/index.d.ts +24 -0
- package/dist/sdk/index.js +34 -0
- package/dist/sdk/signatures.d.ts +17 -0
- package/dist/sdk/signatures.js +33 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.js +94 -0
- package/dist/signatures.d.ts +112 -0
- package/dist/signatures.js +443 -0
- package/dist/state.d.ts +185 -0
- package/dist/state.js +96 -0
- package/dist/store-payments.d.ts +48 -0
- package/dist/store-payments.js +143 -0
- package/dist/structured-fields.d.ts +26 -0
- package/dist/structured-fields.js +200 -0
- package/dist/templates.d.ts +19 -0
- package/dist/templates.js +193 -0
- package/dist/test-checkout-command.d.ts +32 -0
- package/dist/test-checkout-command.js +161 -0
- package/dist/test-checkout.d.ts +88 -0
- package/dist/test-checkout.js +292 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +18 -0
- package/dist/ucp-versions.d.ts +57 -0
- package/dist/ucp-versions.js +129 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +68 -0
- package/dist/variants.d.ts +67 -0
- package/dist/variants.js +146 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.js +10 -0
- package/dist/waiting.d.ts +43 -0
- package/dist/waiting.js +57 -0
- package/dist/webhook-command.d.ts +48 -0
- package/dist/webhook-command.js +367 -0
- package/dist/webhook-registration.d.ts +47 -0
- package/dist/webhook-registration.js +69 -0
- package/dist/webmcp-schema.d.ts +14 -0
- package/dist/webmcp-schema.js +140 -0
- package/dist/webmcp-script.d.ts +3 -0
- package/dist/webmcp-script.js +176 -0
- package/dist/webmcp-store.d.ts +102 -0
- package/dist/webmcp-store.js +116 -0
- package/dist/webmcp.d.ts +242 -0
- package/dist/webmcp.js +866 -0
- package/dist/wire-names.d.ts +85 -0
- package/dist/wire-names.js +109 -0
- package/package.json +118 -4
- package/release-notes.json +290 -0
- package/scripts/install-notice.cjs +7 -0
- package/skills/relyon-agents/SKILL.md +327 -0
- package/skills/relyon-catalog/SKILL.md +499 -0
- package/skills/relyon-catalog/references/example-store.md +218 -0
- package/skills/relyon-checkout/SKILL.md +603 -0
- package/skills/relyon-checkout/references/checkout-flow.md +257 -0
- package/skills/relyon-checkout/references/checkout-page.md +315 -0
- package/skills/relyon-go-live/SKILL.md +344 -0
- package/skills/relyon-orders/SKILL.md +191 -0
- package/skills/relyon-orders/references/webhook-receiver.md +113 -0
- package/skills/relyon-payments/SKILL.md +117 -0
- package/skills/relyon-setup/SKILL.md +1061 -0
- package/skills/relyon-setup/references/QUICKSTART.md +239 -0
- package/skills/relyon-setup/references/durable-state.md +209 -0
- package/skills/relyon-setup/references/express-server.md +388 -0
- package/skills/relyon-setup/references/next-app-router.md +251 -0
- package/templates/common/STORE-README.md +67 -0
- package/templates/common/gitignore +8 -0
- package/templates/common/scripts/check-pricing.ts +22 -0
- package/templates/common/scripts/serve.mjs +13 -0
- package/templates/common/server/catalog.ts +79 -0
- package/templates/common/server/checkout-flow.d.ts +34 -0
- package/templates/common/server/pages.ts +184 -0
- package/templates/common/server/storage.ts +114 -0
- package/templates/common/server/store.ts +67 -0
- package/templates/express/server/express.ts +20 -0
- package/templates/express/tsconfig.build.json +6 -0
- package/templates/express/tsconfig.json +9 -0
- package/templates/next/app/[[...path]]/route.ts +24 -0
- package/templates/next/next.config.mjs +19 -0
- package/templates/next/tsconfig.json +12 -0
- package/templates/payments/express.ts +39 -0
- package/templates/payments/next.ts +38 -0
- package/templates/payments/node.ts +39 -0
package/dist/webmcp.js
ADDED
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { AgentRefusedError, PaymentOutcomeUnknownError, PaymentUnavailableError, RelyonRuleRefusalError, paymentIdempotencyKey, } from "./checkout.js";
|
|
3
|
+
import { orderConfirmation, orderRefusal } from "./confirmation.js";
|
|
4
|
+
import { decimalAmount } from "./discovery.js";
|
|
5
|
+
import { requestFacts } from "./events.js";
|
|
6
|
+
import { decide } from "./identify.js";
|
|
7
|
+
import { mergeInputs, ucpInputs } from "./protocol-inputs.js";
|
|
8
|
+
import { RelyonAccountNotReadyError, RelyonProblemError } from "./relyon.js";
|
|
9
|
+
import { StoreRefusal } from "./types.js";
|
|
10
|
+
import { isRecord, jsonResponse, randomId, sha256, textResponse, tryParseJson } from "./util.js";
|
|
11
|
+
import { UPDATE_CHECKOUT_SCHEMA, containsCardData, validateToolInput } from "./webmcp-schema.js";
|
|
12
|
+
import { WEBMCP_TOOL_HEADER, webMcpScript } from "./webmcp-script.js";
|
|
13
|
+
import { MemoryWebMcpCheckoutStore } from "./webmcp-store.js";
|
|
14
|
+
import { describeError } from "./relyon-cart-tokens.js";
|
|
15
|
+
export { MemoryWebMcpCheckoutStore } from "./webmcp-store.js";
|
|
16
|
+
// WebMCP checkout on the store's own checkout page. The tools in the
|
|
17
|
+
// page script call these endpoints on the store's own origin. They use the
|
|
18
|
+
// kit's UCP checkout model locally (UCP-shaped session JSON, the store's
|
|
19
|
+
// priceCart, kit-held state); they don't call Relyon's signed-platform UCP
|
|
20
|
+
// adapter, which a page script can't sign for. Payment is the ordinary
|
|
21
|
+
// final-amount payment with the card fields, so Relyon applies its agent
|
|
22
|
+
// rules and limits on it.
|
|
23
|
+
export const WEBMCP_TOOLS = ["get_checkout", "update_checkout", "complete_checkout"];
|
|
24
|
+
/** The checkout-page session cookie for a checkout (`__Host-`: Secure, Path=/, no Domain). */
|
|
25
|
+
export const webMcpSessionCookieName = (checkoutId) => `__Host-relyon-wmc-${checkoutId}`;
|
|
26
|
+
const SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
|
|
27
|
+
const UNKNOWN_OUTCOME_MESSAGE = "The payment outcome is unknown: the charge may have gone through. Check the order status with get_checkout"
|
|
28
|
+
+ " (or at order_status_url). Calling complete_checkout again reconciles it by resending the original payment request with the same"
|
|
29
|
+
+ " Idempotency-Key and card payload, so it can't charge twice. Don't start a new checkout or re-enter the card.";
|
|
30
|
+
const ORDER_PENDING_MESSAGE = "The payment went through, and the store is placing the order. Call complete_checkout again to finish"
|
|
31
|
+
+ " placing it (it doesn't charge again), or read it with get_checkout. Don't start a new checkout or re-enter the card.";
|
|
32
|
+
const ORDER_PENDING_NOTE = "This checkout's payment already went through and its order is being placed; nothing more is charged."
|
|
33
|
+
+ " Read it with get_checkout, or call complete_checkout again later to finish the order.";
|
|
34
|
+
const CHARGE_NEUTRAL_NOTE = "Check this checkout's status on the store's checkout page before trying again; don't start a new checkout.";
|
|
35
|
+
const APPROVAL_ALREADY_USED_MESSAGE = "This checkout's approval was already used by another request. This request charged nothing."
|
|
36
|
+
+ " Read the checkout with get_checkout for the payment's status; don't approve again or re-enter the card.";
|
|
37
|
+
/** How long an approval token stays usable. */
|
|
38
|
+
export const WEBMCP_APPROVAL_TTL_MS = 10 * 60 * 1000;
|
|
39
|
+
const cartDigest = (cart) => sha256(JSON.stringify(cart));
|
|
40
|
+
const b64url = (bytes) => bytes.toString("base64url");
|
|
41
|
+
function sameText(a, b) {
|
|
42
|
+
const x = Buffer.from(a);
|
|
43
|
+
const y = Buffer.from(b);
|
|
44
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
45
|
+
}
|
|
46
|
+
function cookieValue(request, name) {
|
|
47
|
+
const header = request.headers.get("cookie");
|
|
48
|
+
if (!header)
|
|
49
|
+
return null;
|
|
50
|
+
for (const part of header.split(";")) {
|
|
51
|
+
const index = part.indexOf("=");
|
|
52
|
+
if (index > 0 && part.slice(0, index).trim() === name)
|
|
53
|
+
return part.slice(index + 1).trim();
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
const totalLine = (type, amount) => ({ type, amount });
|
|
58
|
+
export class WebMcpCheckouts {
|
|
59
|
+
ctx;
|
|
60
|
+
hooks;
|
|
61
|
+
options;
|
|
62
|
+
store;
|
|
63
|
+
/** The tail of each checkout's queued steps (see `serialized`). */
|
|
64
|
+
inFlight = new Map();
|
|
65
|
+
constructor(ctx, hooks, options = {}) {
|
|
66
|
+
this.ctx = ctx;
|
|
67
|
+
this.hooks = hooks;
|
|
68
|
+
this.options = options;
|
|
69
|
+
this.store = options.store ?? new MemoryWebMcpCheckoutStore();
|
|
70
|
+
}
|
|
71
|
+
get base() {
|
|
72
|
+
return this.ctx.paths.webmcp;
|
|
73
|
+
}
|
|
74
|
+
/** The script's URL on the store's origin. */
|
|
75
|
+
get scriptPath() {
|
|
76
|
+
return `${this.base}.js`;
|
|
77
|
+
}
|
|
78
|
+
scriptTag(checkoutId) {
|
|
79
|
+
const esc = (v) => v.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
80
|
+
return `<script src="${esc(this.scriptPath)}" data-relyon-checkout="${esc(checkoutId)}" data-relyon-base="${esc(this.base)}" defer></script>`;
|
|
81
|
+
}
|
|
82
|
+
/** Starts a checkout for the store's checkout page: prices it and, when ready, opens card fields for the total. */
|
|
83
|
+
async create(input) {
|
|
84
|
+
const now = this.ctx.now();
|
|
85
|
+
const secret = b64url(randomBytes(32));
|
|
86
|
+
let checkout = {
|
|
87
|
+
id: randomId("wmc_"), orderReference: input.orderReference ?? randomId("wmc-"),
|
|
88
|
+
inputs: { lines: input.lines, address: input.address ?? null, coupons: input.coupons ?? [], shipping_option_id: input.shippingOptionId ?? null },
|
|
89
|
+
cart: null, messages: [], paymentSession: null, status: "incomplete", confirmation: null,
|
|
90
|
+
sessionHash: sha256(secret), approvalKey: b64url(randomBytes(32)), approval: null, paymentAttempt: 0, pendingPayment: null,
|
|
91
|
+
createdAt: now, updatedAt: now,
|
|
92
|
+
};
|
|
93
|
+
checkout = await this.price(checkout, "create");
|
|
94
|
+
const cardFields = await this.ensurePaymentSession(checkout);
|
|
95
|
+
await this.store.put(checkout);
|
|
96
|
+
const sessionCookie = `${webMcpSessionCookieName(checkout.id)}=${secret}; Path=/; Max-Age=${SESSION_MAX_AGE_SECONDS}; Secure; HttpOnly; SameSite=Strict`;
|
|
97
|
+
return { checkout, session: this.session(checkout), scriptTag: this.scriptTag(checkout.id), cardFields, sessionCookie };
|
|
98
|
+
}
|
|
99
|
+
async get(id) {
|
|
100
|
+
return this.store.get(id);
|
|
101
|
+
}
|
|
102
|
+
/** Answers the script and the checkout endpoints; null for other paths. */
|
|
103
|
+
async handle(request, info, path) {
|
|
104
|
+
const method = request.method.toUpperCase();
|
|
105
|
+
if (path === this.scriptPath) {
|
|
106
|
+
if (method !== "GET" && method !== "HEAD")
|
|
107
|
+
return null;
|
|
108
|
+
return textResponse(200, method === "HEAD" ? "" : webMcpScript(), "text/javascript; charset=utf-8", {
|
|
109
|
+
"cache-control": "public, max-age=300", "x-content-type-options": "nosniff",
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const prefix = `${this.base}/checkouts/`;
|
|
113
|
+
if (!path.startsWith(prefix))
|
|
114
|
+
return null;
|
|
115
|
+
const rest = path.slice(prefix.length).split("/");
|
|
116
|
+
// A malformed escape names no checkout; it must not throw past this handler's catch.
|
|
117
|
+
let id = "";
|
|
118
|
+
try {
|
|
119
|
+
id = decodeURIComponent(rest[0] ?? "");
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
id = "";
|
|
123
|
+
}
|
|
124
|
+
const action = rest.length === 2 ? rest[1] : null;
|
|
125
|
+
if (!id || rest.length > 2 || (action !== null && action !== "complete" && action !== "approval")) {
|
|
126
|
+
return this.answer(request, info, 404, { error: { code: "not_found", message: "No such checkout endpoint." } });
|
|
127
|
+
}
|
|
128
|
+
const step = action === "complete" && method === "POST" ? () => this.complete(request, info, id)
|
|
129
|
+
: action === "approval" && method === "POST" ? () => this.approve(request, info, id)
|
|
130
|
+
: action === null && method === "GET" ? () => this.read(request, info, id)
|
|
131
|
+
: action === null && method === "POST" ? () => this.update(request, info, id)
|
|
132
|
+
: null;
|
|
133
|
+
if (!step)
|
|
134
|
+
return this.answer(request, info, 405, { error: { code: "method_not_allowed", message: "Method not allowed." } });
|
|
135
|
+
try {
|
|
136
|
+
return await this.serialized(id, step);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
// An unexpected failure (the checkout store can't be read, say) may hit
|
|
140
|
+
// a paid checkout, so this answer never says nothing was charged and
|
|
141
|
+
// shows nothing about the checkout. The kit's generic error would.
|
|
142
|
+
this.ctx.logger.error("The store kit could not answer a WebMCP checkout step", { checkout: id, error: describeError(error, true) });
|
|
143
|
+
return this.answer(request, info, 500, { error: { code: "internal_error", message: `This checkout step could not be answered. ${CHARGE_NEUTRAL_NOTE}` } });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Runs one checkout's steps one at a time (in this process). This is an
|
|
148
|
+
* extra guard: across servers, the store's atomic approval claim decides
|
|
149
|
+
* which request sends the payment, every later write is compare-and-set on
|
|
150
|
+
* the checkout's version, and Relyon's Idempotency-Key is the backstop (one
|
|
151
|
+
* charge per attempt key).
|
|
152
|
+
*/
|
|
153
|
+
serialized(id, step) {
|
|
154
|
+
const previous = this.inFlight.get(id) ?? Promise.resolve();
|
|
155
|
+
const result = previous.then(step);
|
|
156
|
+
const tail = result.then(() => undefined, () => undefined);
|
|
157
|
+
this.inFlight.set(id, tail);
|
|
158
|
+
void tail.then(() => {
|
|
159
|
+
if (this.inFlight.get(id) === tail)
|
|
160
|
+
this.inFlight.delete(id);
|
|
161
|
+
});
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
/** Records a tool call (when the script marked one) and answers. */
|
|
165
|
+
answer(request, info, status, body) {
|
|
166
|
+
const tool = request.headers.get(WEBMCP_TOOL_HEADER);
|
|
167
|
+
if (tool && WEBMCP_TOOLS.includes(tool)) {
|
|
168
|
+
const facts = requestFacts(request, this.ctx.publicUrl(request), info);
|
|
169
|
+
if (facts)
|
|
170
|
+
this.ctx.events.record({ type: "mcp_tool_call", request: facts, status, mcp_tool: tool, mcp_client: { name: "webmcp" } });
|
|
171
|
+
}
|
|
172
|
+
return jsonResponse(status, body, { "cache-control": "no-store" });
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Fail closed for identified agents; refuse by a named Relyon rule. null
|
|
176
|
+
* when the step may go ahead. A refusal on an order-pending checkout (the
|
|
177
|
+
* payment already went through) never says nothing was charged.
|
|
178
|
+
*/
|
|
179
|
+
async gate(request, info, id) {
|
|
180
|
+
const identity = await this.hooks.identify(request);
|
|
181
|
+
const rules = identity.identified ? await this.ctx.rules.get() : null;
|
|
182
|
+
const decision = decide(identity, rules, { failClosed: this.ctx.failClosed });
|
|
183
|
+
if (decision.outcome === "allow")
|
|
184
|
+
return { response: null, identity };
|
|
185
|
+
const status = decision.outcome === "unavailable" ? 503 : 403;
|
|
186
|
+
const error = { code: decision.code, message: decision.message, ...(decision.outcome === "refuse" ? { rule: decision.rule.label } : {}) };
|
|
187
|
+
const standing = await this.paymentStanding(request, id);
|
|
188
|
+
if (standing.kind === "order_pending") {
|
|
189
|
+
return {
|
|
190
|
+
response: this.answer(request, info, status, { ...this.session(standing.checkout), error: { ...error, message: refusalMessage(decision, ORDER_PENDING_NOTE) } }),
|
|
191
|
+
identity,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
if (standing.kind === "unestablished") {
|
|
195
|
+
// The checkout may be paid (or this caller may not see it): say nothing about charges.
|
|
196
|
+
return { response: this.answer(request, info, status, { error: { ...error, message: refusalMessage(decision, CHARGE_NEUTRAL_NOTE) } }), identity };
|
|
197
|
+
}
|
|
198
|
+
return { response: this.answer(request, info, status, { error }), identity };
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Whether a refusal may say nothing was charged. `unpaid`: no such
|
|
202
|
+
* checkout, or this page session's checkout has no payment sent, pending
|
|
203
|
+
* or succeeded. `order_pending`: this page session's checkout was paid and
|
|
204
|
+
* its order is being placed. Anything else (another caller, a pending or
|
|
205
|
+
* finished payment, a failed read) is `unestablished`.
|
|
206
|
+
*/
|
|
207
|
+
async paymentStanding(request, id) {
|
|
208
|
+
let checkout;
|
|
209
|
+
try {
|
|
210
|
+
checkout = await this.store.get(id);
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
this.ctx.logger.error("The WebMCP checkout store failed to read a checkout for a refusal", { checkout: id, error: describeError(error) });
|
|
214
|
+
return { kind: "unestablished" };
|
|
215
|
+
}
|
|
216
|
+
if (!checkout)
|
|
217
|
+
return { kind: "unpaid" };
|
|
218
|
+
if (!this.ownsSession(request, checkout))
|
|
219
|
+
return { kind: "unestablished" };
|
|
220
|
+
if (checkout.status === "order_pending")
|
|
221
|
+
return { kind: "order_pending", checkout };
|
|
222
|
+
const unpaid = (checkout.status === "incomplete" || checkout.status === "ready_for_complete") && !checkout.pendingPayment;
|
|
223
|
+
return { kind: unpaid ? "unpaid" : "unestablished" };
|
|
224
|
+
}
|
|
225
|
+
ownsSession(request, checkout) {
|
|
226
|
+
const secret = cookieValue(request, webMcpSessionCookieName(checkout.id));
|
|
227
|
+
return Boolean(checkout.sessionHash && secret && sameText(sha256(secret), checkout.sessionHash));
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Loads the checkout for a request from its own checkout page: the page
|
|
231
|
+
* session cookie must match. Anyone else (no cookie, another browser, a
|
|
232
|
+
* direct caller with only the checkout id) is refused and nothing happens.
|
|
233
|
+
*/
|
|
234
|
+
async load(request, info, id) {
|
|
235
|
+
const checkout = await this.store.get(id);
|
|
236
|
+
if (!checkout)
|
|
237
|
+
return { response: this.answer(request, info, 404, { error: { code: "not_found", message: "No such checkout." } }) };
|
|
238
|
+
if (!this.ownsSession(request, checkout)) {
|
|
239
|
+
return {
|
|
240
|
+
response: this.answer(request, info, 403, {
|
|
241
|
+
// Charge-neutral: this caller can't be told whether the checkout was paid.
|
|
242
|
+
error: { code: "checkout_session_required", message: "This checkout can only be used from the store's checkout page in the browser that opened it. Read its status there." },
|
|
243
|
+
}),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
return { checkout };
|
|
247
|
+
}
|
|
248
|
+
async read(request, info, id) {
|
|
249
|
+
const { response } = await this.gate(request, info, id);
|
|
250
|
+
if (response)
|
|
251
|
+
return response;
|
|
252
|
+
const loaded = await this.load(request, info, id);
|
|
253
|
+
if (loaded.response)
|
|
254
|
+
return loaded.response;
|
|
255
|
+
let checkout = loaded.checkout;
|
|
256
|
+
if (checkout.status === "ready_for_complete" && !checkout.paymentSession && !checkout.pendingPayment && this.guardedWrites()) {
|
|
257
|
+
// Card fields after a decline whose replacement session couldn't be opened then.
|
|
258
|
+
const expected = checkout.version ?? 0;
|
|
259
|
+
try {
|
|
260
|
+
if (await this.ensurePaymentSession(checkout)) {
|
|
261
|
+
// Never an unguarded write: it could drop a payment another server just claimed.
|
|
262
|
+
checkout = (await this.store.compareAndSet(checkout, expected)) ?? (await this.store.get(id)) ?? checkout;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (!(error instanceof PaymentUnavailableError))
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return this.answer(request, info, 200, this.session(checkout));
|
|
271
|
+
}
|
|
272
|
+
async update(request, info, id) {
|
|
273
|
+
const { response } = await this.gate(request, info, id);
|
|
274
|
+
if (response)
|
|
275
|
+
return response;
|
|
276
|
+
const body = tryParseJson(await request.text());
|
|
277
|
+
if (containsCardData(body)) {
|
|
278
|
+
return this.answer(request, info, 400, { error: { code: "card_data_refused", message: "No tool accepts card data. Type the card into the card fields on the page." } });
|
|
279
|
+
}
|
|
280
|
+
const invalid = validateToolInput(UPDATE_CHECKOUT_SCHEMA, body, "input");
|
|
281
|
+
if (invalid)
|
|
282
|
+
return this.answer(request, info, 400, { error: { code: "invalid_input", message: invalid } });
|
|
283
|
+
const loaded = await this.load(request, info, id);
|
|
284
|
+
if (loaded.response)
|
|
285
|
+
return loaded.response;
|
|
286
|
+
let checkout = loaded.checkout;
|
|
287
|
+
const expected = checkout.version ?? 0;
|
|
288
|
+
if (checkout.status === "completed")
|
|
289
|
+
return this.answer(request, info, 409, { error: { code: "checkout_completed", message: "This order is already placed." } });
|
|
290
|
+
if (checkout.status === "order_pending")
|
|
291
|
+
return this.orderPending(request, info, checkout, 409);
|
|
292
|
+
if (checkout.pendingPayment)
|
|
293
|
+
return this.unknownOutcome(request, info, checkout, 409);
|
|
294
|
+
if (!this.guardedWrites())
|
|
295
|
+
return this.storeUnavailable(request, info, "unsupported");
|
|
296
|
+
checkout = { ...checkout, inputs: mergeInputs(checkout.inputs, partialUcpInputs(body)), approval: null };
|
|
297
|
+
checkout = await this.price(checkout, "update");
|
|
298
|
+
try {
|
|
299
|
+
await this.ensurePaymentSession(checkout);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
if (error instanceof PaymentUnavailableError)
|
|
303
|
+
return this.answer(request, info, 503, { error: { code: "service_unavailable", message: error.message } });
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
const stored = await this.store.compareAndSet(checkout, expected);
|
|
307
|
+
if (!stored)
|
|
308
|
+
return this.checkoutChanged(request, info, "The update wasn't applied.");
|
|
309
|
+
return this.answer(request, info, 200, this.session(stored));
|
|
310
|
+
}
|
|
311
|
+
/** The MAC input: the token is bound to the checkout, page session, attempt, total, currency and priced cart. */
|
|
312
|
+
approvalMac(checkout, jti, exp) {
|
|
313
|
+
const cart = checkout.cart;
|
|
314
|
+
const bound = [
|
|
315
|
+
checkout.id, checkout.sessionHash, checkout.orderReference, checkout.paymentAttempt ?? 0,
|
|
316
|
+
cart.totals.total, cart.currency, cartDigest(cart), jti, exp,
|
|
317
|
+
].join("|");
|
|
318
|
+
return b64url(createHmac("sha256", Buffer.from(checkout.approvalKey, "base64url")).update(bound).digest());
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Issues the approval token when the person approves on the checkout page.
|
|
322
|
+
* Requires the page session cookie and a same-origin browser request
|
|
323
|
+
* (Sec-Fetch-Site / Origin). The token is single use, expires, and is bound
|
|
324
|
+
* to this checkout, its page session, payment attempt, total, currency and
|
|
325
|
+
* priced cart; `complete` verifies all of it.
|
|
326
|
+
*/
|
|
327
|
+
async approve(request, info, id) {
|
|
328
|
+
const fetchSite = request.headers.get("sec-fetch-site");
|
|
329
|
+
const origin = request.headers.get("origin");
|
|
330
|
+
let fromPage = fetchSite !== null ? fetchSite === "same-origin" : origin !== null;
|
|
331
|
+
if (fromPage && origin !== null) {
|
|
332
|
+
try {
|
|
333
|
+
fromPage = new URL(origin).host === new URL(this.ctx.publicUrl(request)).host;
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
fromPage = false;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (!fromPage) {
|
|
340
|
+
return this.answer(request, info, 403, { error: { code: "approval_requires_checkout_page", message: "Approval is given only on the store's own checkout page." } });
|
|
341
|
+
}
|
|
342
|
+
const { response } = await this.gate(request, info, id);
|
|
343
|
+
if (response)
|
|
344
|
+
return response;
|
|
345
|
+
const loaded = await this.load(request, info, id);
|
|
346
|
+
if (loaded.response)
|
|
347
|
+
return loaded.response;
|
|
348
|
+
const checkout = loaded.checkout;
|
|
349
|
+
// A paid (or maybe paid) checkout is never answered "nothing was charged"
|
|
350
|
+
// (the store-unavailable answer says that), so these come first.
|
|
351
|
+
if (checkout.status === "order_pending")
|
|
352
|
+
return this.orderPending(request, info, checkout, 409);
|
|
353
|
+
if (checkout.status === "completed")
|
|
354
|
+
return this.answer(request, info, 409, { error: { code: "checkout_completed", message: "This order is already placed." } });
|
|
355
|
+
if (checkout.pendingPayment)
|
|
356
|
+
return this.unknownOutcome(request, info, checkout, 409);
|
|
357
|
+
if (!this.guardedWrites())
|
|
358
|
+
return this.storeUnavailable(request, info, "unsupported");
|
|
359
|
+
const body = tryParseJson(await request.text());
|
|
360
|
+
if (!isRecord(body) || Object.keys(body).some((key) => key !== "total") || !Number.isSafeInteger(body.total)) {
|
|
361
|
+
return this.answer(request, info, 400, { error: { code: "invalid_input", message: "total (the amount the person approved, in minor units) is required." } });
|
|
362
|
+
}
|
|
363
|
+
if (checkout.status !== "ready_for_complete" || !checkout.cart || !checkout.approvalKey) {
|
|
364
|
+
return this.answer(request, info, 409, { error: { code: "not_ready", message: "The checkout isn't ready to complete." } });
|
|
365
|
+
}
|
|
366
|
+
if (body.total !== checkout.cart.totals.total) {
|
|
367
|
+
return this.answer(request, info, 409, { error: { code: "total_changed", message: "The approved total doesn't match the checkout total. Read the checkout and approve again." } });
|
|
368
|
+
}
|
|
369
|
+
const jti = b64url(randomBytes(16));
|
|
370
|
+
const exp = Math.floor((this.ctx.now() + WEBMCP_APPROVAL_TTL_MS) / 1000);
|
|
371
|
+
const token = `wmat_${jti}.${exp}.${this.approvalMac(checkout, jti, exp)}`;
|
|
372
|
+
// Issued only if the checkout is still as approved: a token is never handed out for state another server replaced.
|
|
373
|
+
const stored = await this.store.compareAndSet({ ...checkout, approval: { jti, expiresAt: exp * 1000 }, updatedAt: this.ctx.now() }, checkout.version ?? 0);
|
|
374
|
+
if (!stored)
|
|
375
|
+
return this.checkoutChanged(request, info, "Nothing was approved.");
|
|
376
|
+
return this.answer(request, info, 200, { approval_token: token, total: checkout.cart.totals.total, currency: checkout.cart.currency, expires_at: exp });
|
|
377
|
+
}
|
|
378
|
+
/** null when the token is valid for this checkout as it is now; otherwise the refusal code. */
|
|
379
|
+
approvalProblem(checkout, token) {
|
|
380
|
+
if (typeof token !== "string" || token.length > 512)
|
|
381
|
+
return "approval_required";
|
|
382
|
+
const match = /^wmat_([A-Za-z0-9_-]{16,64})\.(\d{1,12})\.([A-Za-z0-9_-]{43})$/.exec(token);
|
|
383
|
+
const outstanding = checkout.approval;
|
|
384
|
+
if (!match || !outstanding || !checkout.cart || !checkout.approvalKey)
|
|
385
|
+
return "approval_invalid";
|
|
386
|
+
const [, jti, expText, mac] = match;
|
|
387
|
+
const exp = Number(expText);
|
|
388
|
+
if (!sameText(jti, outstanding.jti) || exp * 1000 !== outstanding.expiresAt)
|
|
389
|
+
return "approval_invalid";
|
|
390
|
+
if (!sameText(mac, this.approvalMac(checkout, jti, exp)))
|
|
391
|
+
return "approval_invalid";
|
|
392
|
+
if (exp * 1000 <= this.ctx.now())
|
|
393
|
+
return "approval_expired";
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Pays with an approval token. The pre-charge checks (page session, the
|
|
398
|
+
* agent-rules decision, the token) all run before the approval is used;
|
|
399
|
+
* then the store's atomic claim consumes the approval and records the
|
|
400
|
+
* exact payment request in one step, and only the request whose claim
|
|
401
|
+
* succeeded sends it. A store that can't claim refuses, nothing charged.
|
|
402
|
+
*/
|
|
403
|
+
async complete(request, info, id) {
|
|
404
|
+
// The agent-rules decision, read from Relyon (fails closed): before anything is consumed.
|
|
405
|
+
const { response, identity } = await this.gate(request, info, id);
|
|
406
|
+
if (response)
|
|
407
|
+
return response;
|
|
408
|
+
const loaded = await this.load(request, info, id);
|
|
409
|
+
if (loaded.response)
|
|
410
|
+
return loaded.response;
|
|
411
|
+
const checkout = loaded.checkout;
|
|
412
|
+
if (checkout.status === "completed" && checkout.confirmation) {
|
|
413
|
+
return this.answer(request, info, 200, this.session(checkout));
|
|
414
|
+
}
|
|
415
|
+
// The payment went through but the order isn't confirmed created: finish
|
|
416
|
+
// it. No approval, no card, and never another payment.
|
|
417
|
+
if (checkout.status === "order_pending")
|
|
418
|
+
return this.finishOrder(request, info, checkout);
|
|
419
|
+
if (!this.guardedWrites()) {
|
|
420
|
+
// A payment another server sent may have charged: never "nothing was charged" for it,
|
|
421
|
+
// and never a resend from a server that can't record the outcome safely.
|
|
422
|
+
if (checkout.pendingPayment)
|
|
423
|
+
return this.unknownOutcome(request, info, checkout, 409);
|
|
424
|
+
return this.storeUnavailable(request, info, "unsupported");
|
|
425
|
+
}
|
|
426
|
+
if (checkout.pendingPayment) {
|
|
427
|
+
// Another request (on this or another server) is sending this approval's payment now.
|
|
428
|
+
if (this.beingSent(checkout.pendingPayment))
|
|
429
|
+
return this.approvalAlreadyUsed(request, info);
|
|
430
|
+
// Reconcile: resend the original request (same attempt, same encrypted
|
|
431
|
+
// card payload, same Idempotency-Key). The card is never re-read.
|
|
432
|
+
return this.settle(request, info, checkout, checkout.pendingPayment, identity, true);
|
|
433
|
+
}
|
|
434
|
+
const body = tryParseJson(await request.text());
|
|
435
|
+
if (!isRecord(body) || !isRecord(body.payment_method)) {
|
|
436
|
+
return this.answer(request, info, 400, { error: { code: "invalid_input", message: "payment_method (from the card fields) is required." } });
|
|
437
|
+
}
|
|
438
|
+
if (!isHostedCardMethod(body.payment_method)) {
|
|
439
|
+
return this.answer(request, info, 400, { error: { code: "card_data_refused", message: "Only the card fields' tokenized result is accepted. Nothing was charged." } });
|
|
440
|
+
}
|
|
441
|
+
if (checkout.status !== "ready_for_complete" || !checkout.cart || !checkout.paymentSession) {
|
|
442
|
+
return this.answer(request, info, 409, { error: { code: "not_ready", message: "The checkout isn't ready to complete." } });
|
|
443
|
+
}
|
|
444
|
+
const problem = this.approvalProblem(checkout, body.approval_token);
|
|
445
|
+
if (problem) {
|
|
446
|
+
const message = problem === "approval_required"
|
|
447
|
+
? "This checkout's current total hasn't been approved on the checkout page. Nothing was charged."
|
|
448
|
+
: problem === "approval_expired"
|
|
449
|
+
? "The approval expired. Nothing was charged; ask the person to approve again."
|
|
450
|
+
: "The approval isn't valid for this checkout as it is now (it was used, replaced, or the checkout changed). Nothing was charged; approve again.";
|
|
451
|
+
return this.answer(request, info, 409, { error: { code: problem, message } });
|
|
452
|
+
}
|
|
453
|
+
const attempt = checkout.paymentAttempt ?? 0;
|
|
454
|
+
const pending = {
|
|
455
|
+
attempt, idempotencyKey: paymentIdempotencyKey(checkout.orderReference, attempt),
|
|
456
|
+
paymentMethod: { ...body.payment_method }, since: this.ctx.now(), state: "sending",
|
|
457
|
+
};
|
|
458
|
+
// Consume the approval and keep the exact request before charging, in one
|
|
459
|
+
// atomic step, so only one request ever sends it and a lost answer can
|
|
460
|
+
// only be reconciled, never re-approved or re-read.
|
|
461
|
+
let claimed;
|
|
462
|
+
try {
|
|
463
|
+
claimed = await this.store.claimApproval(checkout.id, { jti: checkout.approval.jti, pendingPayment: pending, updatedAt: this.ctx.now() });
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
this.ctx.logger.error("The WebMCP checkout store failed to claim an approval; nothing was charged", { checkout: checkout.id, error: describeError(error) });
|
|
467
|
+
return this.storeUnavailable(request, info, "failed");
|
|
468
|
+
}
|
|
469
|
+
if (!claimed || !claimed.pendingPayment)
|
|
470
|
+
return this.approvalAlreadyUsed(request, info);
|
|
471
|
+
return this.settle(request, info, claimed, claimed.pendingPayment, identity, false);
|
|
472
|
+
}
|
|
473
|
+
/** Sends (or resends) the pending payment and records what Relyon answered. */
|
|
474
|
+
async settle(request, info, checkout, pending, identity, reconciling) {
|
|
475
|
+
const cart = checkout.cart;
|
|
476
|
+
let result;
|
|
477
|
+
try {
|
|
478
|
+
result = await this.hooks.createPayment({
|
|
479
|
+
cart, paymentMethod: pending.paymentMethod, orderReference: checkout.orderReference, attempt: pending.attempt, request, info, channel: "web",
|
|
480
|
+
}, { decidedIdentity: identity, createOrder: false });
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
if (error instanceof PaymentOutcomeUnknownError)
|
|
484
|
+
return this.outcomeUnknown(request, info, checkout, pending);
|
|
485
|
+
// A first send that Relyon refused because this payment (its key or its
|
|
486
|
+
// order) is already another request's: a server whose store claim
|
|
487
|
+
// wasn't atomic. This request charged nothing; the winner's state stays.
|
|
488
|
+
if (!reconciling && error instanceof RelyonProblemError && (error.code === "idempotency_key_reused" || error.code === "checkout_already_final")) {
|
|
489
|
+
return this.approvalAlreadyUsed(request, info);
|
|
490
|
+
}
|
|
491
|
+
// Refused at the store's edge before anything was sent: a first attempt
|
|
492
|
+
// is definitely not charged; a reconcile still doesn't know the outcome.
|
|
493
|
+
const edge = error instanceof AgentRefusedError || error instanceof PaymentUnavailableError;
|
|
494
|
+
// Relyon answered this Idempotency-Key with a final refusal: not charged.
|
|
495
|
+
// 409 can mean "still processing", so it stays unknown.
|
|
496
|
+
// On a reconcile, a refusal of the resend itself (the store's key,
|
|
497
|
+
// permissions, a rate limit) says nothing about the original charge.
|
|
498
|
+
const resendRefused = reconciling && error instanceof RelyonProblemError && !(error instanceof RelyonRuleRefusalError)
|
|
499
|
+
&& (error.status === 401 || error.status === 403 || error.status === 429);
|
|
500
|
+
// The account isn't ready for this mode (processor_not_configured is a
|
|
501
|
+
// 409): a first send was refused before any charge and is never resent.
|
|
502
|
+
const final = (error instanceof RelyonProblemError && error.status !== 409 && error.status < 500 && !resendRefused)
|
|
503
|
+
|| (!reconciling && error instanceof RelyonAccountNotReadyError);
|
|
504
|
+
if ((edge && !reconciling) || final) {
|
|
505
|
+
await this.record(checkout, pending, (base) => ({ ...base, pendingPayment: null, updatedAt: this.ctx.now() }));
|
|
506
|
+
}
|
|
507
|
+
else if (!edge) {
|
|
508
|
+
if (error instanceof RelyonProblemError)
|
|
509
|
+
return this.outcomeUnknown(request, info, checkout, pending);
|
|
510
|
+
throw error;
|
|
511
|
+
}
|
|
512
|
+
const refusal = refusalFor(checkout.orderReference, error);
|
|
513
|
+
if (!refusal)
|
|
514
|
+
throw error;
|
|
515
|
+
return this.answer(request, info, refusal.status, {
|
|
516
|
+
error: { code: refusal.body.code, message: refusal.body.message, rule: refusal.body.rule }, order_refusal: refusal.body,
|
|
517
|
+
...(edge && reconciling ? { payment_outcome: "unknown" } : {}),
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
if (result.payment.status !== "succeeded") {
|
|
521
|
+
const declined = orderRefusal(checkout.orderReference, String(result.payment.failure_code ?? "card_declined"), String(result.payment.failure_message ?? "The card was declined. Nothing was charged."), null, result.payment.id);
|
|
522
|
+
// A confirmed decline: the next card is a new attempt (its own
|
|
523
|
+
// Idempotency-Key and card-field session), approved again.
|
|
524
|
+
const retry = {
|
|
525
|
+
...checkout, approval: null, pendingPayment: null, paymentAttempt: pending.attempt + 1, paymentSession: null, updatedAt: this.ctx.now(),
|
|
526
|
+
};
|
|
527
|
+
try {
|
|
528
|
+
await this.ensurePaymentSession(retry);
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
if (!(error instanceof PaymentUnavailableError))
|
|
532
|
+
throw error;
|
|
533
|
+
}
|
|
534
|
+
let recorded;
|
|
535
|
+
try {
|
|
536
|
+
recorded = await this.record(checkout, pending, (base) => ({
|
|
537
|
+
...base, approval: null, pendingPayment: null, paymentAttempt: pending.attempt + 1, paymentSession: retry.paymentSession, updatedAt: this.ctx.now(),
|
|
538
|
+
}));
|
|
539
|
+
}
|
|
540
|
+
catch (error) {
|
|
541
|
+
return this.unrecorded(request, info, checkout, error);
|
|
542
|
+
}
|
|
543
|
+
const shown = recorded.stored ?? recorded.current ?? retry;
|
|
544
|
+
return this.answer(request, info, 402, { error: { code: declined.code, message: declined.message }, order_refusal: declined, checkout: this.session(shown) });
|
|
545
|
+
}
|
|
546
|
+
const confirmation = orderConfirmation({ cart, orderReference: checkout.orderReference, payment: result.payment, agent: result.agent ?? identity, now: this.ctx.now });
|
|
547
|
+
// First stored as order pending: the succeeded payment and its
|
|
548
|
+
// confirmation are kept and the pending payment is cleared, so nothing
|
|
549
|
+
// can send it again. `completed` is stored (and reported) only once the
|
|
550
|
+
// store's order exists.
|
|
551
|
+
const paid = (base) => ({
|
|
552
|
+
...base, status: "order_pending", confirmation, succeededPayment: result.payment, approval: null, pendingPayment: null, updatedAt: this.ctx.now(),
|
|
553
|
+
});
|
|
554
|
+
let recorded;
|
|
555
|
+
try {
|
|
556
|
+
recorded = await this.record(checkout, pending, paid);
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
return this.unrecorded(request, info, checkout, error);
|
|
560
|
+
}
|
|
561
|
+
const current = recorded.current;
|
|
562
|
+
if (!recorded.stored && (current?.status === "completed" || current?.status === "order_pending")) {
|
|
563
|
+
// Another request recorded this payment first.
|
|
564
|
+
// On a first send, this request's answer was Relyon's replay of that
|
|
565
|
+
// payment (a store claim that wasn't atomic): it charged nothing itself.
|
|
566
|
+
if (!reconciling)
|
|
567
|
+
return this.approvalAlreadyUsed(request, info);
|
|
568
|
+
if (current.status === "completed")
|
|
569
|
+
return this.answer(request, info, 200, this.session(current));
|
|
570
|
+
return this.finishOrder(request, info, current);
|
|
571
|
+
}
|
|
572
|
+
if (!recorded.stored) {
|
|
573
|
+
// Never a completion that isn't stored: no order and no confirmation.
|
|
574
|
+
// The pending payment stays; once its send lease passes, the next
|
|
575
|
+
// complete resends the same request, Relyon replays it, and that
|
|
576
|
+
// request records the completion and creates the order.
|
|
577
|
+
return this.unrecorded(request, info, checkout, new Error(`the checkout changed before payment ${result.payment.id} could be recorded`));
|
|
578
|
+
}
|
|
579
|
+
return this.finishOrder(request, info, recorded.stored);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Creates the order for an order-pending checkout (through the order
|
|
583
|
+
* claim, so once per payment across servers), then stores and reports
|
|
584
|
+
* `completed`. Until both happen the answer is order pending.
|
|
585
|
+
*/
|
|
586
|
+
async finishOrder(request, info, checkout) {
|
|
587
|
+
const payment = checkout.succeededPayment;
|
|
588
|
+
if (!checkout.cart || !payment) {
|
|
589
|
+
this.ctx.logger.error("A WebMCP checkout is order pending without its cart or succeeded payment", { checkout: checkout.id });
|
|
590
|
+
return this.orderPending(request, info, checkout, 202);
|
|
591
|
+
}
|
|
592
|
+
let outcome;
|
|
593
|
+
try {
|
|
594
|
+
outcome = await this.ctx.createOrderOnce(checkout.cart, payment);
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
this.ctx.logger.error("The store's order couldn't be created for a succeeded WebMCP payment", { checkout: checkout.id, payment: payment.id, error: describeError(error) });
|
|
598
|
+
return this.orderPending(request, info, checkout, 202);
|
|
599
|
+
}
|
|
600
|
+
if (outcome.status === "failed" || outcome.status === "in_progress") {
|
|
601
|
+
// Another request is creating it (or createOrder threw): a resend finishes it.
|
|
602
|
+
let latest = null;
|
|
603
|
+
try {
|
|
604
|
+
latest = await this.store.get(checkout.id);
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
// The answer is order pending either way.
|
|
608
|
+
}
|
|
609
|
+
if (latest?.status === "completed")
|
|
610
|
+
return this.answer(request, info, 200, this.session(latest));
|
|
611
|
+
return this.orderPending(request, info, latest?.status === "order_pending" ? latest : checkout, 202);
|
|
612
|
+
}
|
|
613
|
+
// The order exists: store the completion.
|
|
614
|
+
let base = checkout;
|
|
615
|
+
try {
|
|
616
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
617
|
+
const stored = await this.store.compareAndSet({ ...base, status: "completed", updatedAt: this.ctx.now() }, base.version ?? 0);
|
|
618
|
+
if (stored)
|
|
619
|
+
return this.answer(request, info, 200, this.session(stored));
|
|
620
|
+
const current = await this.store.get(checkout.id);
|
|
621
|
+
if (current?.status === "completed")
|
|
622
|
+
return this.answer(request, info, 200, this.session(current));
|
|
623
|
+
if (current?.status !== "order_pending" || current.succeededPayment?.id !== payment.id)
|
|
624
|
+
break;
|
|
625
|
+
base = current;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
this.ctx.logger.error("The WebMCP checkout store failed to record a created order", { checkout: checkout.id, payment: payment.id, error: describeError(error) });
|
|
630
|
+
}
|
|
631
|
+
// The order exists but `completed` isn't stored: a resend sees the claim
|
|
632
|
+
// marked created and stores it then.
|
|
633
|
+
return this.orderPending(request, info, checkout, 202);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Writes the outcome of `pending` with compare-and-set. A newer version
|
|
637
|
+
* that still holds the same payment (same Idempotency-Key) is retried on;
|
|
638
|
+
* anything else means another request already recorded the outcome.
|
|
639
|
+
*/
|
|
640
|
+
async record(checkout, pending, build) {
|
|
641
|
+
let base = checkout;
|
|
642
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
643
|
+
const stored = await this.store.compareAndSet(build(base), base.version ?? 0);
|
|
644
|
+
if (stored)
|
|
645
|
+
return { stored, current: stored };
|
|
646
|
+
const current = await this.store.get(checkout.id);
|
|
647
|
+
if (!current || current.pendingPayment?.idempotencyKey !== pending.idempotencyKey)
|
|
648
|
+
return { stored: null, current };
|
|
649
|
+
base = current;
|
|
650
|
+
}
|
|
651
|
+
return { stored: null, current: base };
|
|
652
|
+
}
|
|
653
|
+
/** The payment's outcome is unknown: keep it pending (now reconcilable) and say so. */
|
|
654
|
+
async outcomeUnknown(request, info, checkout, pending) {
|
|
655
|
+
let shown = checkout;
|
|
656
|
+
if (pending.state !== "unknown") {
|
|
657
|
+
try {
|
|
658
|
+
const recorded = await this.record(checkout, pending, (base) => ({
|
|
659
|
+
...base, pendingPayment: { ...(base.pendingPayment ?? pending), state: "unknown" }, updatedAt: this.ctx.now(),
|
|
660
|
+
}));
|
|
661
|
+
if (recorded.current?.status === "completed")
|
|
662
|
+
return this.answer(request, info, 200, this.session(recorded.current));
|
|
663
|
+
if (recorded.current?.status === "order_pending")
|
|
664
|
+
return this.finishOrder(request, info, recorded.current);
|
|
665
|
+
if (recorded.current?.pendingPayment)
|
|
666
|
+
shown = recorded.current;
|
|
667
|
+
}
|
|
668
|
+
catch (error) {
|
|
669
|
+
this.ctx.logger.error("The WebMCP checkout store failed to mark a payment's outcome unknown", { checkout: checkout.id, error: describeError(error) });
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return this.unknownOutcome(request, info, shown, 202);
|
|
673
|
+
}
|
|
674
|
+
/** Relyon answered, but the store couldn't record it: the next complete reconciles once the send lease passes. */
|
|
675
|
+
unrecorded(request, info, checkout, error) {
|
|
676
|
+
this.ctx.logger.error("The WebMCP checkout store failed to record a payment's outcome", { checkout: checkout.id, error: describeError(error) });
|
|
677
|
+
return this.unknownOutcome(request, info, checkout, 202);
|
|
678
|
+
}
|
|
679
|
+
/** True when the store has the guarded writes (atomic claim, compare-and-set) every write after creation needs. */
|
|
680
|
+
guardedWrites() {
|
|
681
|
+
return typeof this.store.claimApproval === "function" && typeof this.store.compareAndSet === "function";
|
|
682
|
+
}
|
|
683
|
+
/** How long a claimed payment counts as being sent: twice Relyon's timeout, plus a margin. */
|
|
684
|
+
get sendLeaseMs() {
|
|
685
|
+
return this.ctx.gateway.timeoutMs * 2 + 5_000;
|
|
686
|
+
}
|
|
687
|
+
beingSent(pending) {
|
|
688
|
+
return pending.state === "sending" && this.ctx.now() - pending.since < this.sendLeaseMs;
|
|
689
|
+
}
|
|
690
|
+
approvalAlreadyUsed(request, info) {
|
|
691
|
+
return this.answer(request, info, 409, { error: { code: "approval_already_used", message: APPROVAL_ALREADY_USED_MESSAGE } });
|
|
692
|
+
}
|
|
693
|
+
checkoutChanged(request, info, outcome) {
|
|
694
|
+
return this.answer(request, info, 409, {
|
|
695
|
+
error: { code: "checkout_changed", message: `The checkout changed while this request was handled. ${outcome} Read the checkout and try again.` },
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
/** The checkout store can't make (or failed to make) a guarded write. Nothing was charged. */
|
|
699
|
+
storeUnavailable(request, info, reason) {
|
|
700
|
+
const message = reason === "unsupported"
|
|
701
|
+
? "This store's checkout storage can't claim an approval atomically, so the checkout can't be changed or paid. Nothing was charged."
|
|
702
|
+
: "The store couldn't record the approval's use, so nothing was sent for payment and nothing was charged. Try again shortly.";
|
|
703
|
+
return this.answer(request, info, 503, { error: { code: "checkout_store_unavailable", message } });
|
|
704
|
+
}
|
|
705
|
+
/** The payment went through; the store's order is being placed. Never "nothing was charged", never a new approval. */
|
|
706
|
+
orderPending(request, info, checkout, status) {
|
|
707
|
+
return this.answer(request, info, status, {
|
|
708
|
+
...this.session(checkout),
|
|
709
|
+
error: { code: "order_pending", message: ORDER_PENDING_MESSAGE },
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
/** Says the outcome is unknown and where to check the order status. */
|
|
713
|
+
unknownOutcome(request, info, checkout, status) {
|
|
714
|
+
const message = UNKNOWN_OUTCOME_MESSAGE;
|
|
715
|
+
return this.answer(request, info, status, {
|
|
716
|
+
...this.session(checkout),
|
|
717
|
+
error: { code: "payment_outcome_unknown", message },
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
async price(checkout, operation) {
|
|
721
|
+
const messages = [];
|
|
722
|
+
let cart = null;
|
|
723
|
+
const { lines, address, coupons, shipping_option_id } = checkout.inputs;
|
|
724
|
+
if (lines.length > 0) {
|
|
725
|
+
try {
|
|
726
|
+
cart = await this.ctx.hooks.priceCart(lines, address, coupons, { protocol: "web", operation, shippingOptionId: shipping_option_id, agentCheckoutId: null });
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
if (!(error instanceof StoreRefusal))
|
|
730
|
+
throw error;
|
|
731
|
+
messages.push({ type: "error", code: error.code, content: error.message });
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (lines.length === 0)
|
|
735
|
+
messages.push({ type: "info", code: "empty_cart", content: "Add at least one item." });
|
|
736
|
+
if (!address)
|
|
737
|
+
messages.push({ type: "info", code: "missing_address", content: "Add a shipping address." });
|
|
738
|
+
const ready = cart !== null && address !== null && messages.every((m) => m.type !== "error");
|
|
739
|
+
return { ...checkout, cart, messages, status: ready ? "ready_for_complete" : "incomplete", updatedAt: this.ctx.now() };
|
|
740
|
+
}
|
|
741
|
+
/** A card-field session for the current total (sessions have a fixed amount). Mutates `checkout`. */
|
|
742
|
+
async ensurePaymentSession(checkout) {
|
|
743
|
+
if (checkout.status !== "ready_for_complete" || !checkout.cart)
|
|
744
|
+
return null;
|
|
745
|
+
const { total } = checkout.cart.totals;
|
|
746
|
+
const currency = checkout.cart.currency;
|
|
747
|
+
if (checkout.paymentSession && checkout.paymentSession.amount === total && checkout.paymentSession.currency === currency)
|
|
748
|
+
return null;
|
|
749
|
+
const fields = await this.hooks.cardFields({ amount: total, currency, orderReference: checkout.orderReference });
|
|
750
|
+
checkout.paymentSession = { id: fields.session.id, clientToken: fields.session.client_token, amount: total, currency };
|
|
751
|
+
return fields;
|
|
752
|
+
}
|
|
753
|
+
/** The checkout as UCP-shaped session JSON. */
|
|
754
|
+
session(checkout) {
|
|
755
|
+
const cart = checkout.cart;
|
|
756
|
+
const currency = cart?.currency ?? "USD";
|
|
757
|
+
const address = checkout.inputs.address;
|
|
758
|
+
const placed = checkout.status === "completed" && checkout.confirmation ? checkout.confirmation : null;
|
|
759
|
+
const confirmationUrl = placed && this.options.confirmationUrl ? this.options.confirmationUrl(checkout.orderReference) : null;
|
|
760
|
+
const orderPending = checkout.status === "order_pending";
|
|
761
|
+
const unknown = !orderPending && Boolean(checkout.pendingPayment) && checkout.status !== "completed";
|
|
762
|
+
const statusUrl = (unknown || orderPending) && this.options.confirmationUrl ? this.options.confirmationUrl(checkout.orderReference) : null;
|
|
763
|
+
return {
|
|
764
|
+
id: checkout.id,
|
|
765
|
+
status: unknown || orderPending ? "complete_in_progress" : checkout.status,
|
|
766
|
+
...(unknown ? { payment_outcome: "unknown", order_reference: checkout.orderReference, ...(statusUrl ? { order_status_url: statusUrl } : {}) } : {}),
|
|
767
|
+
...(orderPending ? { payment_outcome: "succeeded", order_reference: checkout.orderReference, ...(statusUrl ? { order_status_url: statusUrl } : {}) } : {}),
|
|
768
|
+
currency,
|
|
769
|
+
line_items: (cart?.lines ?? []).map((line, index) => ({
|
|
770
|
+
id: line.id ?? `li_${index + 1}`,
|
|
771
|
+
item: { id: line.merchant_product_id, title: line.title, ...(line.unit_amount !== undefined ? { price: line.unit_amount } : {}) },
|
|
772
|
+
quantity: line.quantity,
|
|
773
|
+
totals: [totalLine("subtotal", line.amount + (line.discount ?? 0)), ...(line.discount ? [totalLine("discount", line.discount)] : []), totalLine("total", line.amount)],
|
|
774
|
+
})),
|
|
775
|
+
fulfillment: {
|
|
776
|
+
methods: [{
|
|
777
|
+
id: "shipping", type: "shipping",
|
|
778
|
+
destinations: address ? [{
|
|
779
|
+
id: "dest_1", name: address.name, street_address: address.line1, ...(address.line2 ? { extended_address: address.line2 } : {}),
|
|
780
|
+
address_locality: address.city, ...(address.region ? { address_region: address.region } : {}), postal_code: address.postal_code, address_country: address.country,
|
|
781
|
+
}] : [],
|
|
782
|
+
...(address ? { selected_destination_id: "dest_1" } : {}),
|
|
783
|
+
groups: [{
|
|
784
|
+
id: "group_1",
|
|
785
|
+
...(cart?.shipping_option_id ?? checkout.inputs.shipping_option_id ? { selected_option_id: cart?.shipping_option_id ?? checkout.inputs.shipping_option_id } : {}),
|
|
786
|
+
options: (cart?.shipping_options ?? []).map((option) => ({ id: option.id, title: option.label, totals: [totalLine("total", option.amount)] })),
|
|
787
|
+
}],
|
|
788
|
+
}],
|
|
789
|
+
},
|
|
790
|
+
discounts: {
|
|
791
|
+
codes: checkout.inputs.coupons,
|
|
792
|
+
applied: (cart?.discounts ?? []).map((discount) => ({ ...(discount.code ? { code: discount.code } : {}), title: discount.label, amount: discount.amount })),
|
|
793
|
+
},
|
|
794
|
+
totals: cart ? [
|
|
795
|
+
totalLine("subtotal", cart.totals.subtotal), totalLine("discount", cart.totals.discount), totalLine("fulfillment", cart.totals.shipping),
|
|
796
|
+
totalLine("tax", cart.totals.tax), totalLine("total", cart.totals.total),
|
|
797
|
+
] : [],
|
|
798
|
+
...(cart ? { display_total: `${decimalAmount(cart.totals.total, currency)} ${currency}` } : {}),
|
|
799
|
+
messages: [
|
|
800
|
+
...checkout.messages.map((m) => ({ type: m.type, code: m.code, content: m.content })),
|
|
801
|
+
...(unknown ? [{ type: "info", code: "payment_outcome_unknown", content: UNKNOWN_OUTCOME_MESSAGE }] : []),
|
|
802
|
+
...(orderPending ? [{ type: "info", code: "order_pending", content: ORDER_PENDING_MESSAGE }] : []),
|
|
803
|
+
],
|
|
804
|
+
payment: {
|
|
805
|
+
handlers: [{
|
|
806
|
+
id: "relyon_card_fields", name: "dev.relyon.card_fields",
|
|
807
|
+
config: {
|
|
808
|
+
element: "relyon-card-fields",
|
|
809
|
+
...(checkout.paymentSession && checkout.status !== "completed" && !orderPending && !unknown ? { client_token: checkout.paymentSession.clientToken, amount: checkout.paymentSession.amount } : {}),
|
|
810
|
+
instructions: "Type the card into the card fields on this page after the last update_checkout. No tool accepts card data.",
|
|
811
|
+
},
|
|
812
|
+
}],
|
|
813
|
+
},
|
|
814
|
+
...(placed ? {
|
|
815
|
+
order: { id: placed.order_reference, ...(confirmationUrl ? { permalink_url: confirmationUrl } : {}) },
|
|
816
|
+
order_confirmation: placed,
|
|
817
|
+
} : {}),
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* update_checkout is a partial update: a fulfillment method that leaves out
|
|
823
|
+
* `destinations` keeps the address, and one that leaves out `groups` keeps
|
|
824
|
+
* the shipping option (UCP's own update replaces both).
|
|
825
|
+
*/
|
|
826
|
+
function partialUcpInputs(body) {
|
|
827
|
+
const patch = ucpInputs(body);
|
|
828
|
+
if (!isRecord(body) || !isRecord(body.fulfillment))
|
|
829
|
+
return patch;
|
|
830
|
+
const methods = body.fulfillment.methods;
|
|
831
|
+
const method = Array.isArray(methods) ? methods.find(isRecord) : undefined;
|
|
832
|
+
if (!method || !("destinations" in method))
|
|
833
|
+
delete patch.address;
|
|
834
|
+
if (!method || !("groups" in method))
|
|
835
|
+
delete patch.shipping_option_id;
|
|
836
|
+
return patch;
|
|
837
|
+
}
|
|
838
|
+
const HOSTED_CARD_KEYS = new Set(["type", "payment_session", "encrypted_data", "key_id"]);
|
|
839
|
+
/** The card fields' `tokenize()` result and nothing else. */
|
|
840
|
+
function isHostedCardMethod(method) {
|
|
841
|
+
if (method.type !== "hosted_card")
|
|
842
|
+
return false;
|
|
843
|
+
return Object.entries(method).every(([key, value]) => HOSTED_CARD_KEYS.has(key) && typeof value === "string" && value.length <= 16_384);
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* A refused or unavailable payment as an order refusal; null for other errors
|
|
847
|
+
* (including `PaymentOutcomeUnknownError`, which is not a refusal).
|
|
848
|
+
*/
|
|
849
|
+
export function refusalFor(orderReference, error) {
|
|
850
|
+
if (error instanceof AgentRefusedError)
|
|
851
|
+
return { status: 403, body: orderRefusal(orderReference, error.code, error.message, error.rule ?? null) };
|
|
852
|
+
if (error instanceof RelyonRuleRefusalError)
|
|
853
|
+
return { status: 403, body: orderRefusal(orderReference, error.code, error.message, error.rule) };
|
|
854
|
+
if (error instanceof PaymentUnavailableError)
|
|
855
|
+
return { status: 503, body: orderRefusal(orderReference, "service_unavailable", error.message) };
|
|
856
|
+
if (error instanceof RelyonProblemError)
|
|
857
|
+
return { status: error.status, body: orderRefusal(orderReference, error.code, error.message) };
|
|
858
|
+
return null;
|
|
859
|
+
}
|
|
860
|
+
/** A refusal's message when it can't say nothing was charged: the rule (or outage), then `note`. */
|
|
861
|
+
function refusalMessage(decision, note) {
|
|
862
|
+
const base = decision.outcome === "refuse"
|
|
863
|
+
? `Refused by Relyon agent rule: ${decision.rule.label}.`
|
|
864
|
+
: "Agent checkout is unavailable: the store can't read its Relyon agent rules right now.";
|
|
865
|
+
return `${base} ${note}`;
|
|
866
|
+
}
|