@tokenoftrust/storefront-runner 7.5.0 → 7.5.1

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.
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The agent checkout-session wire shape: every protocol literal and the one serializer that builds
3
+ * a response.
4
+ *
5
+ * Sources, taken verbatim from the published schemas:
6
+ * - UCP shopping checkout, `https://ucp.dev/schemas/shopping/checkout.json`
7
+ * (`dev.ucp.shopping.checkout`), REST binding `POST /checkout-sessions` and
8
+ * `GET /checkout-sessions/{id}`. Status `requires_escalation`, message severities
9
+ * `requires_buyer_review` and `unrecoverable`, `continue_url` "MUST be provided when status is
10
+ * requires_escalation", required response fields `ucp, id, line_items, status, currency, totals, links`.
11
+ * - ACP checkout `CheckoutSessionBase.status` and `MessageError.code` (ACP protocol version
12
+ * `2026-04-17`): the error codes below are members of that closed enum.
13
+ *
14
+ * Every response is built by `serializeSession` or `serializeError` from explicit fields, so no
15
+ * upstream value reaches an agent unlisted. Nothing here names or carries a payment instrument, a
16
+ * payable cart, a completion or an order.
17
+ */
18
+ import type { CartProposalLine, CartProposalReason, ExciseCarrier } from "@tot/public-runtime";
19
+
20
+ /**
21
+ * UCP release this surface follows. The single place the version is stated. The spec does not say in
22
+ * words which release is current; this is the version every example under
23
+ * https://ucp.dev/latest/specification/shopping/checkout/rest/ carries (retrieved 2026-11-21).
24
+ */
25
+ export const UCP_VERSION = "2026-08-25";
26
+ export const UCP_CAPABILITY = "dev.ucp.shopping.checkout";
27
+ export const ACP_VERSION = "2026-04-17";
28
+
29
+ /** UCP `status` enum member: every session this surface opens ends in a buyer-reviewed handoff. */
30
+ export const SESSION_STATUS = "requires_escalation" as const;
31
+ /** UCP message severity: the buyer must review and authorize on the merchant's own screen. */
32
+ export const SEVERITY_REVIEW = "requires_buyer_review" as const;
33
+ /** UCP message severity: no resource exists to act on. */
34
+ export const SEVERITY_UNRECOVERABLE = "unrecoverable" as const;
35
+
36
+ /** ACP `MessageError.code` members this surface emits. */
37
+ export type AcpErrorCode =
38
+ | "missing"
39
+ | "invalid"
40
+ | "out_of_stock"
41
+ | "quantity_exceeded"
42
+ | "maximum_exceeded"
43
+ | "approval_required"
44
+ | "unsupported"
45
+ | "not_found"
46
+ | "conflict"
47
+ | "expired"
48
+ | "intervention_required";
49
+
50
+ /** The ACP code for each stable proposal reason. Exhaustive: a new reason fails the type check. */
51
+ export const ACP_ERROR_CODE: Record<CartProposalReason, AcpErrorCode> = {
52
+ variant_not_found: "not_found",
53
+ invalid_quantity: "invalid",
54
+ quantity_over_limit: "quantity_exceeded",
55
+ variant_unavailable: "out_of_stock",
56
+ currency_mismatch: "invalid",
57
+ forbidden_field: "unsupported",
58
+ unknown_field: "unsupported",
59
+ unknown_assistant: "invalid",
60
+ invalid_request: "invalid",
61
+ no_lines: "missing",
62
+ too_many_lines: "maximum_exceeded",
63
+ list_too_long: "maximum_exceeded",
64
+ no_quantity: "missing",
65
+ no_product_match: "not_found",
66
+ no_variant_match: "not_found",
67
+ ambiguous_match: "invalid",
68
+ proposal_invalid: "invalid",
69
+ proposal_tenant_mismatch: "not_found",
70
+ offer_expired: "expired",
71
+ offer_stale: "conflict",
72
+ cross_origin: "unsupported",
73
+ commerce_unavailable: "intervention_required",
74
+ cart_unavailable: "intervention_required",
75
+ };
76
+
77
+ export type Eligibility = "clear" | "action_required" | "blocked" | "unknown";
78
+
79
+ export interface SessionCompliance {
80
+ eligibility: Eligibility;
81
+ blocks: Array<{ code: string; message: string }>;
82
+ }
83
+
84
+ export interface SessionExcise {
85
+ /** Whether the store's compliance obligations require excise tax collection. */
86
+ required: boolean;
87
+ /** The ExciseCarrier vocabulary. Null when excise is not required. */
88
+ quote: ExciseCarrier | null;
89
+ }
90
+
91
+ /**
92
+ * The response's `agent_attribution` extension. UCP's own top-level `attribution` is a
93
+ * string-valued platform referral object, so this label never reuses that name.
94
+ */
95
+ export interface SessionAttribution {
96
+ /** The validated host of a verified Web Bot Auth agent, or null. */
97
+ agent: string | null;
98
+ verified: boolean;
99
+ }
100
+
101
+ export interface SessionInput {
102
+ id: string;
103
+ currency: string;
104
+ lines: readonly CartProposalLine[];
105
+ compliance: SessionCompliance;
106
+ excise: SessionExcise;
107
+ continueUrl: string;
108
+ expiresAtSeconds: number;
109
+ agentAttribution: SessionAttribution;
110
+ }
111
+
112
+ /** Every key a success body may carry, at any depth. A response carrying another fails the tests. */
113
+ export const SESSION_KEYS = [
114
+ "ucp", "id", "status", "currency", "line_items", "totals", "messages", "links",
115
+ "continue_url", "expires_at", "compliance", "excise", "agent_attribution",
116
+ ] as const;
117
+ export const ERROR_KEYS = ["ucp", "messages", "continue_url"] as const;
118
+
119
+ function minor(amount: number): number {
120
+ return Math.round(amount * 100);
121
+ }
122
+
123
+ function ucpEnvelope(status: "success" | "error"): Record<string, unknown> {
124
+ return status === "success"
125
+ ? {
126
+ version: UCP_VERSION,
127
+ status,
128
+ capabilities: { [UCP_CAPABILITY]: [{ version: UCP_VERSION }] },
129
+ // No payment handler is offered: the buyer pays only after reviewing on the merchant's screen.
130
+ payment_handlers: {},
131
+ }
132
+ : { version: UCP_VERSION, status };
133
+ }
134
+
135
+ /** The success body: a session that always hands the shopper to the merchant's review screen. */
136
+ export function serializeSession(input: SessionInput): Record<string, unknown> {
137
+ const lineItems = input.lines.map((line, index) => ({
138
+ id: `li_${index + 1}`,
139
+ item: { id: line.variantId, title: line.variantTitle && line.variantTitle !== line.productTitle
140
+ ? `${line.productTitle} — ${line.variantTitle}`
141
+ : line.productTitle, price: minor(line.unitPrice) },
142
+ quantity: line.quantity,
143
+ totals: [
144
+ { type: "subtotal", amount: minor(line.lineTotal) },
145
+ { type: "total", amount: minor(line.lineTotal) },
146
+ ],
147
+ }));
148
+ const subtotal = input.lines.reduce((sum, line) => sum + minor(line.lineTotal), 0);
149
+ return {
150
+ ucp: ucpEnvelope("success"),
151
+ id: input.id,
152
+ status: SESSION_STATUS,
153
+ currency: input.currency,
154
+ line_items: lineItems,
155
+ totals: [
156
+ { type: "subtotal", amount: subtotal },
157
+ { type: "total", amount: subtotal },
158
+ ],
159
+ messages: [{
160
+ type: "error",
161
+ code: "approval_required",
162
+ severity: SEVERITY_REVIEW,
163
+ content: "The buyer reviews and confirms this order on the merchant's own review screen.",
164
+ }],
165
+ links: [],
166
+ continue_url: input.continueUrl,
167
+ expires_at: new Date(input.expiresAtSeconds * 1000).toISOString(),
168
+ compliance: {
169
+ eligibility: input.compliance.eligibility,
170
+ blocks: input.compliance.blocks.map((block) => ({ code: block.code, message: block.message })),
171
+ },
172
+ excise: { required: input.excise.required, quote: input.excise.quote },
173
+ agent_attribution: { agent: input.agentAttribution.agent, verified: input.agentAttribution.verified },
174
+ };
175
+ }
176
+
177
+ export interface ErrorInput {
178
+ code: CartProposalReason;
179
+ content: string;
180
+ /** Request line positions the refusal names. */
181
+ paths?: readonly number[];
182
+ }
183
+
184
+ /** The error body: no checkout resource exists, so every message is unrecoverable. */
185
+ export function serializeError(errors: readonly ErrorInput[]): Record<string, unknown> {
186
+ return {
187
+ ucp: ucpEnvelope("error"),
188
+ messages: errors.map((error) => ({
189
+ type: "error",
190
+ code: ACP_ERROR_CODE[error.code],
191
+ severity: SEVERITY_UNRECOVERABLE,
192
+ content: error.content,
193
+ ...(error.paths && error.paths.length > 0 ? { path: `$.line_items[${error.paths[0]}]` } : {}),
194
+ })),
195
+ };
196
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Agent checkout sessions: an external agent proposes a cart and is handed to the merchant's own
3
+ * review screen. The session id is the HMAC-authenticated proposal id the assistant path mints, so
4
+ * the endpoint stores nothing; it only reads the routed store's catalog, runs the store's own
5
+ * compliance preflight and reports what the final-cart authorization would need.
6
+ *
7
+ * Nothing here creates a payment, a payable signed cart or an order, and nothing here attests
8
+ * verification. Every response says `requires_escalation` with a `continue_url` to the review
9
+ * screen, where the shopper alone confirms. Logs carry the tenant, stable reason codes, counts and
10
+ * the signature outcome — never a body, a line, a header value or an id.
11
+ */
12
+ import type { APIContext } from "astro";
13
+ import {
14
+ CART_PROPOSAL_MAX_LINES,
15
+ CART_PROPOSAL_TTL_SECONDS,
16
+ tenantPublicOrigin,
17
+ type CartProposalLine,
18
+ type CartProposalReason,
19
+ type ExciseCarrier,
20
+ } from "@tot/public-runtime";
21
+ import { readEnv } from "@/lib/publication/shared/runtimeEnv";
22
+ import { exciseLinesDigest, exciseRequiredForTenant } from "@/lib/checkout/commerce/sharedStoreAdmission";
23
+ import {
24
+ CART_PROPOSAL_ID_PARAM,
25
+ CART_PROPOSAL_REVIEW_PATH,
26
+ basePrefix,
27
+ jsonReply,
28
+ proposalCatalog,
29
+ readBody,
30
+ type ProposalDeps,
31
+ } from "@/lib/checkout/proposal/proposalRoutes";
32
+ import {
33
+ decodeProposalId,
34
+ encodeProposalId,
35
+ isPlainObject,
36
+ proposalAge,
37
+ proposalIdKey,
38
+ refuseFields,
39
+ resolveProposalLines,
40
+ validateReviewRequest,
41
+ type ProposalCatalog,
42
+ } from "@/lib/checkout/proposal/cartProposal";
43
+ import { CART_UNAVAILABLE_MESSAGE } from "@/lib/checkout/commerce/cartSession";
44
+ import { resolveCartSigning, shopperCartDenialMessage, type CartSigningResolution } from "@/lib/checkout/shared/checkoutCommerce";
45
+ import {
46
+ serializeError,
47
+ serializeSession,
48
+ type Eligibility,
49
+ type ErrorInput,
50
+ type SessionAttribution,
51
+ type SessionCompliance,
52
+ type SessionExcise,
53
+ } from "./checkoutProtocol";
54
+ import { webBotAuth, type SignatureOutcome, type WebBotAuthVerifier } from "./webBotAuth";
55
+
56
+ export const CHECKOUT_SESSIONS_PATH = "/api/commerce/checkout-sessions";
57
+
58
+ /** The SHA-256 of the empty string: a pre-cart quote has no destination to bind. */
59
+ const NO_DESTINATION_DIGEST = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
60
+
61
+ const NO_COMMERCE_MESSAGE = "Checkout is unavailable because this store has no cart configured.";
62
+ const SUSPENDED_MESSAGE = "This store is not accepting agent checkout requests right now.";
63
+ const STALE_MESSAGE = "Prices or availability changed. Open a new checkout session.";
64
+
65
+ export interface AgentCheckoutDeps extends ProposalDeps {
66
+ verifier?: WebBotAuthVerifier;
67
+ /** True when the store has paused agent intake. Read before any other work. */
68
+ intakeSuspended?: (context: APIContext) => Promise<boolean>;
69
+ }
70
+
71
+ /** The store's pause on agent intake: one declared binding, read per request. */
72
+ export async function agentIntakeSuspended(): Promise<boolean> {
73
+ return (await readEnv("AGENT_CHECKOUT_INTAKE")) === "suspended";
74
+ }
75
+
76
+ function logAgent(context: APIContext, event: string, detail: Record<string, string | number | boolean>): void {
77
+ console.info(`[storefront] agent-checkout ${event} ${JSON.stringify({
78
+ tenant: context.locals.tenant.tenant_id,
79
+ stage: context.locals.browserEnvironment?.environment ?? "unknown",
80
+ ...detail,
81
+ })}`);
82
+ }
83
+
84
+ function errorReply(
85
+ context: APIContext,
86
+ status: number,
87
+ errors: readonly ErrorInput[],
88
+ event: string,
89
+ ): Response {
90
+ logAgent(context, event, { code: errors[0]?.code ?? "invalid_request", reasons: errors.length });
91
+ return jsonReply(serializeError(errors), status);
92
+ }
93
+
94
+ function minor(amount: number): number {
95
+ return Math.round(amount * 100);
96
+ }
97
+
98
+ /**
99
+ * The request mapped onto the assistant path's own closed request shape, so the same validation
100
+ * decides what a line may carry. Anything outside `line_items[].item.id` and `quantity` is refused.
101
+ */
102
+ function lineItemsToLines(body: unknown): { ok: true; lines: Array<{ variantId: unknown; quantity: unknown }> } | { ok: false; reasons: Array<{ code: CartProposalReason }> } {
103
+ if (!isPlainObject(body)) return { ok: false, reasons: [{ code: "invalid_request" }] };
104
+ const reasons: Array<{ code: CartProposalReason }> = refuseFields(body, ["line_items"]).map((refusal) => ({ code: refusal.code }));
105
+ const items = body.line_items;
106
+ if (!Array.isArray(items) || items.length === 0) reasons.push({ code: "no_lines" });
107
+ else if (items.length > CART_PROPOSAL_MAX_LINES) reasons.push({ code: "too_many_lines" });
108
+ else {
109
+ for (const entry of items) {
110
+ if (!isPlainObject(entry)) {
111
+ reasons.push({ code: "invalid_request" });
112
+ break;
113
+ }
114
+ reasons.push(...refuseFields(entry, ["item", "quantity"]).map((refusal) => ({ code: refusal.code })));
115
+ if (!isPlainObject(entry.item)) reasons.push({ code: "invalid_request" });
116
+ else reasons.push(...refuseFields(entry.item, ["id"]).map((refusal) => ({ code: refusal.code })));
117
+ }
118
+ }
119
+ if (reasons.length > 0) return { ok: false, reasons };
120
+ return {
121
+ ok: true,
122
+ lines: (items as Array<{ item: { id?: unknown }; quantity?: unknown }>).map((entry) => ({ variantId: entry.item.id, quantity: entry.quantity })),
123
+ };
124
+ }
125
+
126
+ function distinct(reasons: ReadonlyArray<{ code: CartProposalReason }>): ErrorInput[] {
127
+ const seen = new Set<CartProposalReason>();
128
+ const out: ErrorInput[] = [];
129
+ for (const reason of reasons) {
130
+ if (seen.has(reason.code)) continue;
131
+ seen.add(reason.code);
132
+ out.push({ code: reason.code, content: "This checkout request could not be accepted." });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ async function complianceOf(
138
+ context: APIContext,
139
+ lines: readonly CartProposalLine[],
140
+ deps: AgentCheckoutDeps,
141
+ ): Promise<SessionCompliance> {
142
+ if (!deps.preflight) return { eligibility: "unknown", blocks: [] };
143
+ try {
144
+ const result = await deps.preflight(context, lines);
145
+ if (!result) return { eligibility: "unknown", blocks: [] };
146
+ const known: readonly Eligibility[] = ["clear", "action_required", "blocked"];
147
+ const eligibility = known.find((status) => status === result.status) ?? "unknown";
148
+ return { eligibility, blocks: eligibility === "unknown" ? [] : result.blocks };
149
+ } catch {
150
+ return { eligibility: "unknown", blocks: [] };
151
+ }
152
+ }
153
+
154
+ /**
155
+ * The excise quote in the ExciseCarrier vocabulary. No producer prices excise before a cart exists,
156
+ * so a required quote is `not-computed` with a closed reason: it is never estimated here.
157
+ */
158
+ async function exciseOf(context: APIContext, lines: readonly CartProposalLine[]): Promise<SessionExcise> {
159
+ if (!exciseRequiredForTenant(context.locals.tenant)) return { required: false, quote: null };
160
+ const wire = lines.map((line) => ({ sku: line.sku ?? "", quantity: line.quantity, unitMinor: minor(line.unitPrice) }));
161
+ const quote: ExciseCarrier = {
162
+ status: "not-computed",
163
+ reason: lines.some((line) => !line.sku) ? "sku-unregistered" : "no-producer-result",
164
+ linesDigest: await exciseLinesDigest(wire),
165
+ destinationDigest: NO_DESTINATION_DIGEST,
166
+ engineTier: context.locals.customizationEnv === "live" ? "production" : "test",
167
+ };
168
+ return { required: true, quote };
169
+ }
170
+
171
+ function publicOrigin(context: APIContext): string {
172
+ return tenantPublicOrigin(context.locals.tenant, { requestOrigin: context.locals.requestOrigin })
173
+ ?? new URL(context.request.url).origin;
174
+ }
175
+
176
+ function continueUrl(context: APIContext, id: string): string {
177
+ return `${publicOrigin(context)}${basePrefix(context)}${CART_PROPOSAL_REVIEW_PATH}?${CART_PROPOSAL_ID_PARAM}=${encodeURIComponent(id)}`;
178
+ }
179
+
180
+ /** The label for the response's `agent_attribution` field. It is read last and consulted by nothing else. */
181
+ async function attributionOf(context: APIContext, deps: AgentCheckoutDeps): Promise<{ label: SessionAttribution; outcome: SignatureOutcome["outcome"] }> {
182
+ const verifier = deps.verifier ?? webBotAuth;
183
+ const authorities = [new URL(context.request.url).host, new URL(publicOrigin(context)).host];
184
+ const result = await verifier.verify({ request: context.request, authorities });
185
+ return result.outcome === "verified"
186
+ ? { label: { agent: result.agent, verified: true }, outcome: "verified" }
187
+ : { label: { agent: null, verified: false }, outcome: result.outcome };
188
+ }
189
+
190
+ async function sessionReply(
191
+ context: APIContext,
192
+ deps: AgentCheckoutDeps,
193
+ input: { id: string; lines: readonly CartProposalLine[]; issuedAt: number; status: number; event: string },
194
+ ): Promise<Response> {
195
+ const compliance = await complianceOf(context, input.lines, deps);
196
+ const excise = await exciseOf(context, input.lines);
197
+ const { label, outcome } = await attributionOf(context, deps);
198
+ logAgent(context, input.event, { lines: input.lines.length, eligibility: compliance.eligibility, signature: outcome });
199
+ return jsonReply(serializeSession({
200
+ id: input.id,
201
+ currency: context.locals.tenant.currency,
202
+ lines: input.lines,
203
+ compliance,
204
+ excise,
205
+ continueUrl: continueUrl(context, input.id),
206
+ expiresAtSeconds: input.issuedAt + CART_PROPOSAL_TTL_SECONDS,
207
+ agentAttribution: label,
208
+ }), input.status);
209
+ }
210
+
211
+ async function guard(context: APIContext, deps: AgentCheckoutDeps): Promise<Response | { signingSecret: string }> {
212
+ if (await (deps.intakeSuspended ?? agentIntakeSuspended)(context)) {
213
+ return errorReply(context, 503, [{ code: "commerce_unavailable", content: SUSPENDED_MESSAGE }], "suspended");
214
+ }
215
+ const { commerce } = context.locals;
216
+ if (!commerce) {
217
+ return errorReply(context, 409, [{ code: "commerce_unavailable", content: NO_COMMERCE_MESSAGE }], "refused");
218
+ }
219
+ const unavailable = (): Response => errorReply(
220
+ context,
221
+ 503,
222
+ [{ code: "commerce_unavailable", content: shopperCartDenialMessage("signing-unavailable", "") }],
223
+ "refused",
224
+ );
225
+ let signing: CartSigningResolution;
226
+ try {
227
+ signing = await resolveCartSigning(commerce);
228
+ } catch {
229
+ return unavailable();
230
+ }
231
+ return signing.enabled && signing.secret ? { signingSecret: signing.secret } : unavailable();
232
+ }
233
+
234
+ /** POST /api/commerce/checkout-sessions: open a session for the agent's proposed lines. */
235
+ export async function createCheckoutSession(context: APIContext, deps: AgentCheckoutDeps = {}): Promise<Response> {
236
+ const gate = await guard(context, deps);
237
+ if (gate instanceof Response) return gate;
238
+
239
+ const mapped = lineItemsToLines(await readBody(context.request));
240
+ if (!mapped.ok) return errorReply(context, 422, distinct(mapped.reasons), "refused");
241
+ const validated = validateReviewRequest({ assistant: "variants", lines: mapped.lines });
242
+ if (!validated.ok) return errorReply(context, 422, distinct(validated.reasons), "refused");
243
+ if (validated.request.assistant !== "variants") return errorReply(context, 422, distinct([{ code: "invalid_request" }]), "refused");
244
+
245
+ const { tenant } = context.locals;
246
+ let catalog: ProposalCatalog;
247
+ try {
248
+ catalog = await proposalCatalog(context, tenant);
249
+ } catch {
250
+ return errorReply(context, 503, [{ code: "cart_unavailable", content: CART_UNAVAILABLE_MESSAGE }], "refused");
251
+ }
252
+ const resolved = await resolveProposalLines(validated.request.lines, catalog);
253
+ if (resolved.refused.length > 0 || resolved.lines.length === 0) {
254
+ const errors = resolved.refused.length > 0
255
+ ? resolved.refused.map((item) => ({ code: item.reason, content: "This line could not be accepted.", paths: [item.index] }))
256
+ : [{ code: "no_lines" as const, content: "This checkout request could not be accepted." }];
257
+ return errorReply(context, 422, errors, "refused");
258
+ }
259
+
260
+ const issuedAt = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
261
+ const id = await encodeProposalId({
262
+ tenant: tenant.tot_data_scope,
263
+ issuedAt,
264
+ lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
265
+ }, proposalIdKey(gate.signingSecret));
266
+ return sessionReply(context, deps, { id, lines: resolved.lines, issuedAt, status: 201, event: "created" });
267
+ }
268
+
269
+ /** GET /api/commerce/checkout-sessions/{id}: the session an id names, read again from today's catalog. */
270
+ export async function getCheckoutSession(context: APIContext, id: string, deps: AgentCheckoutDeps = {}): Promise<Response> {
271
+ const gate = await guard(context, deps);
272
+ if (gate instanceof Response) return gate;
273
+
274
+ const { tenant } = context.locals;
275
+ const token = await decodeProposalId(id, proposalIdKey(gate.signingSecret));
276
+ if (!token) return errorReply(context, 404, [{ code: "proposal_invalid", content: "This checkout session is not valid." }], "refused");
277
+ if (token.tenant !== tenant.tot_data_scope) {
278
+ return errorReply(context, 404, [{ code: "proposal_tenant_mismatch", content: "This checkout session is not valid." }], "refused");
279
+ }
280
+ const now = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
281
+ const age = proposalAge(token.issuedAt, now);
282
+ if (age === "invalid") return errorReply(context, 404, [{ code: "proposal_invalid", content: "This checkout session is not valid." }], "refused");
283
+ if (age === "expired") return errorReply(context, 410, [{ code: "offer_expired", content: "This checkout session has expired." }], "refused");
284
+
285
+ let catalog: ProposalCatalog;
286
+ try {
287
+ catalog = await proposalCatalog(context, tenant);
288
+ } catch {
289
+ return errorReply(context, 503, [{ code: "cart_unavailable", content: CART_UNAVAILABLE_MESSAGE }], "refused");
290
+ }
291
+ const live = await resolveProposalLines(token.lines, catalog);
292
+ if (live.refused.length > 0 || live.lines.length !== token.lines.length) {
293
+ return errorReply(context, 409, [{ code: "offer_stale", content: STALE_MESSAGE }], "refused");
294
+ }
295
+ return sessionReply(context, deps, { id, lines: live.lines, issuedAt: token.issuedAt, status: 200, event: "read" });
296
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Web Bot Auth recognition (RFC 9421 HTTP Message Signatures, `Signature-Agent` key directory).
3
+ *
4
+ * A verified signature yields an attribution label and nothing else. It is never an authorization:
5
+ * the caller reads the outcome into one response field and no other decision consults it. Any
6
+ * failure — a malformed header, a refused host, a slow, oversize or redirecting directory, a bad
7
+ * signature — is the outcome `invalid`, never an error and never a changed capability.
8
+ *
9
+ * This is the only module of the agent checkout surface that makes an outbound request. The target is
10
+ * derived, never taken as given: the `Signature-Agent` host must pass `agentHost`, and the fetched URL
11
+ * is fixed to `https://<host>/.well-known/http-message-signatures-directory`. The host rule is a
12
+ * string check; it does not claim to know what a hostname resolves to. The bounds (no redirect, a
13
+ * short timeout, a small body, an Ed25519-only key shape, a key cap, per-host caching and a
14
+ * concurrency cap) are what limit a hostile host.
15
+ *
16
+ * Replay is not defended here: a replayed signature at most re-asserts the same attribution label.
17
+ */
18
+
19
+ export type SignatureOutcome =
20
+ | { outcome: "unsigned" }
21
+ | { outcome: "invalid" }
22
+ | { outcome: "verified"; agent: string };
23
+
24
+ export const DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
25
+ export const FETCH_TIMEOUT_MS = 2_000;
26
+ export const MAX_DIRECTORY_BYTES = 16 * 1024;
27
+ export const MAX_DIRECTORY_KEYS = 8;
28
+ export const POSITIVE_TTL_MS = 5 * 60_000;
29
+ export const NEGATIVE_TTL_MS = 60_000;
30
+ export const MAX_CACHE_ENTRIES = 64;
31
+ export const MAX_CONCURRENT_FETCHES = 4;
32
+ export const MAX_SIGNATURE_LIFETIME_SECONDS = 3_600;
33
+ const CLOCK_SKEW_SECONDS = 30;
34
+ const MAX_HEADER_LENGTH = 2_048;
35
+ const FETCH_USER_AGENT = "tot-storefront-web-bot-auth/1";
36
+ const SIGNATURE_TAG = "web-bot-auth";
37
+ const COMPONENTS = new Set(["@authority", "@method", "@target-uri", "@path", "@scheme", "signature-agent"]);
38
+ const REQUIRED_COMPONENTS = ["@authority", "signature-agent"];
39
+ const RESERVED_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home.arpa", ".corp", ".intranet", ".invalid"];
40
+
41
+ /** The validated hostname of a `Signature-Agent` value, or null when it is not an acceptable agent host. */
42
+ export function agentHost(raw: string): string | null {
43
+ let value = raw.trim();
44
+ if (value.length < 3 || value.length > 255) return null;
45
+ if (value.startsWith('"')) {
46
+ if (!value.endsWith('"') || value.length < 3) return null;
47
+ value = value.slice(1, -1);
48
+ }
49
+ if (!/^https:\/\/[^\s/?#@\\]+\/?$/i.test(value)) return null;
50
+ const authority = value.slice("https://".length).replace(/\/$/, "");
51
+ if (authority.includes(":") || authority.includes("[") || authority.endsWith(".")) return null;
52
+ let url: URL;
53
+ try {
54
+ url = new URL(value);
55
+ } catch (error) {
56
+ if (error instanceof TypeError) return null;
57
+ throw error;
58
+ }
59
+ const host = url.hostname.toLowerCase();
60
+ if (url.protocol !== "https:" || url.username || url.password || url.port) return null;
61
+ if (host !== authority.toLowerCase()) return null;
62
+ if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host)) return null;
63
+ if (/^[0-9.]+$/.test(host) || host.split(".").some((label) => label.length === 0 || label.length > 63 || label.startsWith("-") || label.endsWith("-") || label.startsWith("xn--"))) return null;
64
+ if (host === "localhost" || RESERVED_SUFFIXES.some((suffix) => host.endsWith(suffix))) return null;
65
+ return host;
66
+ }
67
+
68
+ interface SignatureInput {
69
+ label: string;
70
+ components: string[];
71
+ params: Map<string, string | number>;
72
+ /** The member text after `label=`, exactly as signed into `@signature-params`. */
73
+ raw: string;
74
+ }
75
+
76
+ function splitMembers(header: string): string[] {
77
+ const members: string[] = [];
78
+ let depth = 0;
79
+ let quoted = false;
80
+ let start = 0;
81
+ for (let i = 0; i < header.length; i += 1) {
82
+ const ch = header[i];
83
+ if (ch === '"') quoted = !quoted;
84
+ else if (!quoted && ch === "(") depth += 1;
85
+ else if (!quoted && ch === ")") depth -= 1;
86
+ else if (!quoted && depth === 0 && ch === ",") {
87
+ members.push(header.slice(start, i).trim());
88
+ start = i + 1;
89
+ }
90
+ }
91
+ members.push(header.slice(start).trim());
92
+ return members.filter((member) => member.length > 0);
93
+ }
94
+
95
+ function parseSignatureInput(header: string): SignatureInput[] {
96
+ const parsed: SignatureInput[] = [];
97
+ for (const member of splitMembers(header)) {
98
+ const match = /^([a-z][a-z0-9_.*-]*)=(\(([^()]*)\)((?:;[a-z][a-z0-9_.*-]*(?:=(?:"[^"\\]*"|[A-Za-z0-9_.*-]+))?)*))$/.exec(member);
99
+ if (!match) continue;
100
+ const components: string[] = [];
101
+ let valid = true;
102
+ for (const part of (match[3] ?? "").split(" ").filter((p) => p.length > 0)) {
103
+ const name = /^"([^"]+)"$/.exec(part)?.[1];
104
+ if (!name || !COMPONENTS.has(name)) {
105
+ valid = false;
106
+ break;
107
+ }
108
+ components.push(name);
109
+ }
110
+ if (!valid) continue;
111
+ const params = new Map<string, string | number>();
112
+ for (const param of (match[4] ?? "").split(";").filter((p) => p.length > 0)) {
113
+ const eq = param.indexOf("=");
114
+ const name = eq === -1 ? param : param.slice(0, eq);
115
+ const value = eq === -1 ? "" : param.slice(eq + 1);
116
+ if (/^-?\d+$/.test(value)) params.set(name, Number(value));
117
+ else params.set(name, value.startsWith('"') ? value.slice(1, -1) : value);
118
+ }
119
+ parsed.push({ label: match[1] as string, components, params, raw: match[2] as string });
120
+ }
121
+ return parsed;
122
+ }
123
+
124
+ function signatureBytes(header: string, label: string): Uint8Array<ArrayBuffer> | null {
125
+ for (const member of splitMembers(header)) {
126
+ const match = /^([a-z][a-z0-9_.*-]*)=:([A-Za-z0-9+/]+={0,2}):$/.exec(member);
127
+ if (match?.[1] === label) return decodeBase64(match[2] as string);
128
+ }
129
+ return null;
130
+ }
131
+
132
+ function decodeBase64(value: string): Uint8Array<ArrayBuffer> | null {
133
+ try {
134
+ const binary = atob(value);
135
+ const out = new Uint8Array(new ArrayBuffer(binary.length));
136
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
137
+ return out;
138
+ } catch (error) {
139
+ if (error instanceof DOMException) return null;
140
+ throw error;
141
+ }
142
+ }
143
+
144
+ function base64Url(bytes: ArrayBuffer): string {
145
+ let binary = "";
146
+ for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
147
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
148
+ }
149
+
150
+ async function thumbprint(x: string): Promise<string> {
151
+ const canonical = `{"crv":"Ed25519","kty":"OKP","x":"${x}"}`;
152
+ return base64Url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical)));
153
+ }
154
+
155
+ interface DirectoryKey {
156
+ x: string;
157
+ keyId: string;
158
+ }
159
+
160
+ /** The Ed25519 keys of a JWKS body, or null when the body is not one. */
161
+ async function readDirectory(text: string): Promise<DirectoryKey[] | null> {
162
+ let body: unknown;
163
+ try {
164
+ body = JSON.parse(text);
165
+ } catch (error) {
166
+ if (error instanceof SyntaxError) return null;
167
+ throw error;
168
+ }
169
+ const keys = (body as { keys?: unknown } | null)?.keys;
170
+ if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_DIRECTORY_KEYS) return null;
171
+ const out: DirectoryKey[] = [];
172
+ for (const key of keys) {
173
+ const jwk = key as { kty?: unknown; crv?: unknown; x?: unknown } | null;
174
+ if (!jwk || jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) return null;
175
+ out.push({ x: jwk.x, keyId: await thumbprint(jwk.x) });
176
+ }
177
+ return out;
178
+ }
179
+
180
+ async function readBounded(response: Response): Promise<string | null> {
181
+ const reader = response.body?.getReader();
182
+ if (!reader) return null;
183
+ const chunks: Uint8Array[] = [];
184
+ let size = 0;
185
+ for (;;) {
186
+ const { done, value } = await reader.read();
187
+ if (done) break;
188
+ size += value.byteLength;
189
+ if (size > MAX_DIRECTORY_BYTES) {
190
+ await reader.cancel();
191
+ return null;
192
+ }
193
+ chunks.push(value);
194
+ }
195
+ const bytes = new Uint8Array(size);
196
+ let offset = 0;
197
+ for (const chunk of chunks) {
198
+ bytes.set(chunk, offset);
199
+ offset += chunk.byteLength;
200
+ }
201
+ return new TextDecoder().decode(bytes);
202
+ }
203
+
204
+ export interface VerifierDeps {
205
+ fetch?: typeof fetch;
206
+ /** Seconds since the epoch. */
207
+ now?: () => number;
208
+ }
209
+
210
+ export interface VerifyRequest {
211
+ request: Request;
212
+ /** Hosts the signature may name as `@authority`: the routed host and the store's public host. */
213
+ authorities: readonly string[];
214
+ }
215
+
216
+ export interface WebBotAuthVerifier {
217
+ verify(input: VerifyRequest): Promise<SignatureOutcome>;
218
+ }
219
+
220
+ /** A verifier with its own directory cache and concurrency counter. */
221
+ export function createWebBotAuthVerifier(deps: VerifierDeps = {}): WebBotAuthVerifier {
222
+ const cache = new Map<string, { keys: DirectoryKey[] | null; until: number }>();
223
+ const inflight = new Map<string, Promise<DirectoryKey[] | null>>();
224
+ const nowSeconds = (): number => deps.now?.() ?? Math.floor(Date.now() / 1000);
225
+
226
+ async function fetchDirectory(host: string): Promise<DirectoryKey[] | null> {
227
+ let response: Response;
228
+ try {
229
+ response = await (deps.fetch ?? fetch)(`https://${host}${DIRECTORY_PATH}`, {
230
+ method: "GET",
231
+ redirect: "manual",
232
+ credentials: "omit",
233
+ headers: { accept: "application/http-message-signatures-directory+json, application/json", "user-agent": FETCH_USER_AGENT },
234
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
235
+ });
236
+ } catch (error) {
237
+ if (error instanceof TypeError || error instanceof DOMException) return null;
238
+ throw error;
239
+ }
240
+ if (response.status !== 200 || response.type === "opaqueredirect") return null;
241
+ const type = (response.headers.get("content-type") ?? "").toLowerCase();
242
+ if (!type.includes("application/http-message-signatures-directory+json") && !type.includes("application/json")) return null;
243
+ let text: string | null;
244
+ try {
245
+ text = await readBounded(response);
246
+ } catch (error) {
247
+ if (error instanceof TypeError || error instanceof DOMException) return null;
248
+ throw error;
249
+ }
250
+ return text === null ? null : readDirectory(text);
251
+ }
252
+
253
+ async function directoryKeys(host: string): Promise<DirectoryKey[] | null> {
254
+ const nowMs = nowSeconds() * 1000;
255
+ const hit = cache.get(host);
256
+ if (hit && hit.until > nowMs) return hit.keys;
257
+ const shared = inflight.get(host);
258
+ if (shared) return shared;
259
+ if (inflight.size >= MAX_CONCURRENT_FETCHES) return null;
260
+ const pending = fetchDirectory(host).then((keys) => {
261
+ for (const [name, entry] of cache) if (entry.until <= nowMs) cache.delete(name);
262
+ while (cache.size >= MAX_CACHE_ENTRIES) {
263
+ const oldest = cache.keys().next().value;
264
+ if (oldest === undefined) break;
265
+ cache.delete(oldest);
266
+ }
267
+ cache.set(host, { keys, until: nowMs + (keys ? POSITIVE_TTL_MS : NEGATIVE_TTL_MS) });
268
+ return keys;
269
+ }).finally(() => {
270
+ inflight.delete(host);
271
+ });
272
+ inflight.set(host, pending);
273
+ return pending;
274
+ }
275
+
276
+ async function verifyUnguarded({ request, authorities }: VerifyRequest): Promise<SignatureOutcome> {
277
+ {
278
+ const signature = request.headers.get("signature");
279
+ const input = request.headers.get("signature-input");
280
+ const agent = request.headers.get("signature-agent");
281
+ if (signature === null && input === null && agent === null) return { outcome: "unsigned" };
282
+ if (signature === null || input === null || agent === null) return { outcome: "invalid" };
283
+ if (signature.length > MAX_HEADER_LENGTH || input.length > MAX_HEADER_LENGTH || agent.length > MAX_HEADER_LENGTH) return { outcome: "invalid" };
284
+ const host = agentHost(agent);
285
+ if (!host) return { outcome: "invalid" };
286
+
287
+ const now = nowSeconds();
288
+ const member = parseSignatureInput(input).find((candidate) => candidate.params.get("tag") === SIGNATURE_TAG);
289
+ if (!member || !REQUIRED_COMPONENTS.every((name) => member.components.includes(name))) return { outcome: "invalid" };
290
+ const created = member.params.get("created");
291
+ const expires = member.params.get("expires");
292
+ const keyId = member.params.get("keyid");
293
+ const alg = member.params.get("alg");
294
+ if (typeof created !== "number" || typeof expires !== "number" || typeof keyId !== "string" || keyId.length === 0) return { outcome: "invalid" };
295
+ if (alg !== undefined && alg !== "ed25519") return { outcome: "invalid" };
296
+ if (created > now + CLOCK_SKEW_SECONDS || expires < now || expires <= created || expires - created > MAX_SIGNATURE_LIFETIME_SECONDS) return { outcome: "invalid" };
297
+ const bytes = signatureBytes(signature, member.label);
298
+ if (!bytes || bytes.length !== 64) return { outcome: "invalid" };
299
+
300
+ const keys = await directoryKeys(host);
301
+ const key = keys?.find((candidate) => candidate.keyId === keyId);
302
+ if (!key) return { outcome: "invalid" };
303
+ let publicKey: CryptoKey;
304
+ try {
305
+ publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x: key.x }, { name: "Ed25519" }, false, ["verify"]);
306
+ } catch (error) {
307
+ if (error instanceof DOMException || error instanceof TypeError) return { outcome: "invalid" };
308
+ throw error;
309
+ }
310
+ const url = new URL(request.url);
311
+ for (const authority of new Set(authorities.map((value) => value.toLowerCase()))) {
312
+ const lines = member.components.map((name) => `"${name}": ${componentValue(name, request, url, authority, agent)}`);
313
+ lines.push(`"@signature-params": ${member.raw}`);
314
+ const valid = await crypto.subtle.verify({ name: "Ed25519" }, publicKey, bytes, new TextEncoder().encode(lines.join("\n")));
315
+ if (valid) return { outcome: "verified", agent: host };
316
+ }
317
+ return { outcome: "invalid" };
318
+ }
319
+ }
320
+
321
+ return {
322
+ async verify(input) {
323
+ try {
324
+ return await verifyUnguarded(input);
325
+ } catch (error) {
326
+ // Recognition is a label, never a gate: whatever goes wrong here is an unverified signature
327
+ // and must not turn into a failed request or a changed capability.
328
+ void error;
329
+ return { outcome: "invalid" };
330
+ }
331
+ },
332
+ };
333
+ }
334
+
335
+ function componentValue(name: string, request: Request, url: URL, authority: string, agent: string): string {
336
+ switch (name) {
337
+ case "@authority": return authority;
338
+ case "@method": return request.method.toUpperCase();
339
+ case "@target-uri": return request.url;
340
+ case "@path": return url.pathname;
341
+ case "@scheme": return "https";
342
+ default: return agent;
343
+ }
344
+ }
345
+
346
+ /** The verifier the route uses: one directory cache per isolate. */
347
+ export const webBotAuth: WebBotAuthVerifier = createWebBotAuthVerifier();
@@ -72,14 +72,17 @@ export interface ConfirmDeps extends ProposalDeps {
72
72
  productPagePath: (context: APIContext, handle: string) => string;
73
73
  }
74
74
 
75
- const SECURITY_HEADERS = {
75
+ export const SECURITY_HEADERS = {
76
76
  "cache-control": "private, no-store",
77
77
  "x-robots-tag": "noindex, nofollow",
78
78
  "referrer-policy": "no-referrer",
79
79
  "x-tot-payment-authorized": "false",
80
80
  } as const;
81
81
 
82
- function jsonReply(body: unknown, status: number, extra: Record<string, string> = {}): Response {
82
+ /** The query parameter that carries a reviewed proposal's id to the review screen. */
83
+ export const CART_PROPOSAL_ID_PARAM = "proposalId";
84
+
85
+ export function jsonReply(body: unknown, status: number, extra: Record<string, string> = {}): Response {
83
86
  return new Response(JSON.stringify(body), {
84
87
  status,
85
88
  headers: { "content-type": "application/json; charset=utf-8", ...SECURITY_HEADERS, ...extra },
@@ -100,7 +103,7 @@ function wantsJson(request: Request): boolean {
100
103
  return (request.headers.get("content-type") ?? "").includes("application/json");
101
104
  }
102
105
 
103
- function basePrefix(context: APIContext): string {
106
+ export function basePrefix(context: APIContext): string {
104
107
  return (context.locals.apiBasePath ?? context.locals.basePath ?? "").replace(/\/+$/, "");
105
108
  }
106
109
 
@@ -132,7 +135,7 @@ function refuse(context: APIContext, refusal: Refusal, event: string): Response
132
135
  }
133
136
 
134
137
  /** The parsed request body: JSON or a urlencoded form, bounded. `null` is an unreadable body. */
135
- async function readBody(request: Request): Promise<Record<string, unknown> | unknown[] | null> {
138
+ export async function readBody(request: Request): Promise<Record<string, unknown> | unknown[] | null> {
136
139
  const type = request.headers.get("content-type") ?? "";
137
140
  const declared = Number(request.headers.get("content-length") ?? "0");
138
141
  if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return null;
@@ -189,7 +192,7 @@ function sameOrigin(context: APIContext): boolean {
189
192
  return allowed.includes(host);
190
193
  }
191
194
 
192
- async function proposalCatalog(context: APIContext, tenant: TenantConfig): Promise<ProposalCatalog> {
195
+ export async function proposalCatalog(context: APIContext, tenant: TenantConfig): Promise<ProposalCatalog> {
193
196
  return {
194
197
  tenantScope: tenant.tot_data_scope,
195
198
  currency: tenant.currency,
@@ -199,7 +202,7 @@ async function proposalCatalog(context: APIContext, tenant: TenantConfig): Promi
199
202
  }
200
203
 
201
204
  /** The cart-signing resolution, or the refusal to return when this store cannot sign carts. */
202
- async function proposalSigning(
205
+ export async function proposalSigning(
203
206
  context: APIContext,
204
207
  commerce: NonNullable<APIContext["locals"]["commerce"]>,
205
208
  event: string,
@@ -224,7 +227,7 @@ async function proposalSigning(
224
227
  return signing;
225
228
  }
226
229
 
227
- function total(lines: readonly CartProposalLine[]): number {
230
+ export function proposalTotal(lines: readonly CartProposalLine[]): number {
228
231
  return lines.reduce((sum, line) => sum + Math.round(line.lineTotal * 100), 0) / 100;
229
232
  }
230
233
 
@@ -234,6 +237,78 @@ export function cartProposalForm(context: APIContext): Response {
234
237
  return htmlReply(renderPasteForm(`${prefix}${CART_PROPOSAL_REVIEW_PATH}`), 200);
235
238
  }
236
239
 
240
+ /**
241
+ * GET: the paste form, or with a proposal id the shopper's review of that proposal. The id is the
242
+ * HMAC-authenticated token a review mints; it is verified before anything is read from it, and
243
+ * another store's id, an expired one and a malformed one are each refused. The lines are resolved
244
+ * again against the routed store's own catalog, so what the shopper reads is today's price and
245
+ * availability. Reads only: confirming stays the same-origin POST.
246
+ */
247
+ export async function cartProposalOpen(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
248
+ const id = new URL(context.request.url).searchParams.get(CART_PROPOSAL_ID_PARAM);
249
+ if (id === null) return cartProposalForm(context);
250
+ const { tenant, commerce } = context.locals;
251
+ if (!commerce) {
252
+ return refuse(context, { status: 409, code: "commerce_unavailable", message: NO_COMMERCE_MESSAGE }, "open-refused");
253
+ }
254
+ const signing = await proposalSigning(context, commerce, "open-refused");
255
+ if (signing instanceof Response) return signing;
256
+
257
+ const token = await decodeProposalId(id, proposalIdKey(signing.secret));
258
+ if (!token) {
259
+ return refuse(context, { status: 422, code: "proposal_invalid", message: "This order review is not valid. Review your order again." }, "open-refused");
260
+ }
261
+ if (token.tenant !== tenant.tot_data_scope) {
262
+ return refuse(context, { status: 422, code: "proposal_tenant_mismatch", message: "This order review is not valid for this store. Review your order again." }, "open-refused");
263
+ }
264
+ const now = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
265
+ const age = proposalAge(token.issuedAt, now);
266
+ if (age === "invalid") {
267
+ return refuse(context, { status: 422, code: "proposal_invalid", message: "This order review is not valid. Review your order again." }, "open-refused");
268
+ }
269
+ if (age === "expired") {
270
+ return refuse(context, { status: 409, code: "offer_expired", message: "This order review has expired. Review your order again." }, "open-refused");
271
+ }
272
+
273
+ let catalog: ProposalCatalog;
274
+ try {
275
+ catalog = await proposalCatalog(context, tenant);
276
+ } catch {
277
+ return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "open-refused");
278
+ }
279
+ const live = await resolveProposalLines(token.lines, catalog);
280
+ if (live.refused.length > 0 || live.lines.length !== token.lines.length) {
281
+ return refuse(context, { status: 409, code: "offer_stale", message: "Prices or availability changed. Review your order again." }, "open-refused");
282
+ }
283
+
284
+ let compliance: ProposalCompliance | null = null;
285
+ if (deps.preflight) {
286
+ try {
287
+ compliance = await deps.preflight(context, live.lines);
288
+ } catch {
289
+ compliance = null;
290
+ }
291
+ }
292
+ logProposal(context, "opened", { lines: live.lines.length });
293
+ const prefix = basePrefix(context);
294
+ const view: ReviewView = {
295
+ confirmAction: `${prefix}${CART_PROPOSAL_CONFIRM_PATH}`,
296
+ reviewAction: `${prefix}${CART_PROPOSAL_REVIEW_PATH}`,
297
+ proposal: {
298
+ id,
299
+ digest: live.digest,
300
+ expiresAt: token.issuedAt + CART_PROPOSAL_TTL_SECONDS,
301
+ currency: tenant.currency,
302
+ total: proposalTotal(live.lines),
303
+ lines: live.lines,
304
+ },
305
+ refused: [],
306
+ unmatched: [],
307
+ compliance,
308
+ };
309
+ return htmlReply(renderReview(view), 200);
310
+ }
311
+
237
312
  /** POST: resolve an assistant's lines into a reviewable offer. Reads only; changes no cart. */
238
313
  export async function cartProposalReview(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
239
314
  const { tenant, commerce } = context.locals;
@@ -293,7 +368,7 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
293
368
  issuedAt,
294
369
  expiresAt: issuedAt + CART_PROPOSAL_TTL_SECONDS,
295
370
  currency: tenant.currency,
296
- total: total(resolved.lines),
371
+ total: proposalTotal(resolved.lines),
297
372
  lines: resolved.lines,
298
373
  }
299
374
  : null;
@@ -1,14 +1,14 @@
1
1
  /** Worker-served review of an assistant's cart proposal. Reads the catalog; changes no cart. */
2
2
  import type { APIContext } from "astro";
3
3
  import type { CartProposalLine } from "@tot/public-runtime";
4
- import { cartProposalForm, cartProposalReview, type ProposalCompliance } from "@/lib/checkout/proposal/proposalRoutes";
4
+ import { cartProposalOpen, cartProposalReview, type ProposalCompliance } from "@/lib/checkout/proposal/proposalRoutes";
5
5
  import { sharedStorePolicy } from "@/lib/checkout/commerce/sharedStoreAdmission";
6
6
  import { evaluatePreflight } from "../compliance/preflight.js";
7
7
 
8
8
  export const prerender = false;
9
9
 
10
10
  /** The compliance status of the reviewed lines. It carries no verification, shopper or destination. */
11
- async function preflight(context: APIContext, lines: readonly CartProposalLine[]): Promise<ProposalCompliance> {
11
+ export async function proposalPreflight(context: APIContext, lines: readonly CartProposalLine[]): Promise<ProposalCompliance> {
12
12
  const { tenant, commerce, customizationEnv } = context.locals;
13
13
  const policy = await sharedStorePolicy(tenant, commerce, customizationEnv);
14
14
  const { decision } = await evaluatePreflight(
@@ -22,5 +22,5 @@ async function preflight(context: APIContext, lines: readonly CartProposalLine[]
22
22
  };
23
23
  }
24
24
 
25
- export const GET = (context: APIContext): Response => cartProposalForm(context);
26
- export const POST = (context: APIContext): Promise<Response> => cartProposalReview(context, { preflight });
25
+ export const GET = (context: APIContext): Promise<Response> => cartProposalOpen(context, { preflight: proposalPreflight });
26
+ export const POST = (context: APIContext): Promise<Response> => cartProposalReview(context, { preflight: proposalPreflight });
@@ -0,0 +1,9 @@
1
+ /** Worker API: read an agent checkout session again from today's catalog. */
2
+ import type { APIContext } from "astro";
3
+ import { getCheckoutSession } from "@/lib/checkout/agent/checkoutSession";
4
+ import { proposalPreflight } from "../../cart-proposal/review.js";
5
+
6
+ export const prerender = false;
7
+
8
+ export const GET = (context: APIContext): Promise<Response> =>
9
+ getCheckoutSession(context, context.params.id ?? "", { preflight: proposalPreflight });
@@ -0,0 +1,8 @@
1
+ /** Worker API: an external agent opens a checkout session that hands off to the merchant's review screen. */
2
+ import type { APIContext } from "astro";
3
+ import { createCheckoutSession } from "@/lib/checkout/agent/checkoutSession";
4
+ import { proposalPreflight } from "../cart-proposal/review.js";
5
+
6
+ export const prerender = false;
7
+
8
+ export const POST = (context: APIContext): Promise<Response> => createCheckoutSession(context, { preflight: proposalPreflight });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.5.0",
3
+ "version": "7.5.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",