@tokenoftrust/storefront-runner 7.6.0 → 7.6.2
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/apps/storefront/src/components/checkout/storefront/islands/CartAddedDialog.tsx +8 -0
- package/apps/storefront/src/lib/checkout/agent/checkoutSession.ts +26 -17
- package/apps/storefront/src/lib/checkout/commerce/assistantOrderEvidence.ts +215 -0
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +1 -1
- package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +31 -5
- package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +123 -6
- package/apps/storefront/src/lib/checkout/shared/cartState.ts +45 -1
- package/apps/storefront/src/lib/checkout/shared/intakeSuspend.ts +21 -0
- package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +105 -0
- package/apps/storefront/src/lib/fulfillment/readiness.ts +217 -0
- package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +380 -0
- package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +830 -0
- package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +6 -1
- package/package.json +1 -1
- package/packages/public-runtime/src/checkout-orders.ts +2 -0
|
@@ -117,6 +117,14 @@ export default function CartAddedDialog() {
|
|
|
117
117
|
</dl>
|
|
118
118
|
)}
|
|
119
119
|
<p class="mt-1 text-sm text-[var(--color-muted)]">Quantity: {detail.quantity}</p>
|
|
120
|
+
{detail.appliedCoupon && (
|
|
121
|
+
<p
|
|
122
|
+
data-cart-added-coupon={detail.appliedCoupon}
|
|
123
|
+
class="mt-2 inline-flex items-center rounded-full border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-1 text-xs font-medium text-[var(--color-text)]"
|
|
124
|
+
>
|
|
125
|
+
Promo code applied: {detail.appliedCoupon}
|
|
126
|
+
</p>
|
|
127
|
+
)}
|
|
120
128
|
</div>
|
|
121
129
|
</div>
|
|
122
130
|
) : (
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Agent checkout sessions: an external agent proposes a cart and is handed to the merchant's own
|
|
3
3
|
* review screen. The session id is the HMAC-authenticated proposal id the assistant path mints, so
|
|
4
|
-
* the endpoint
|
|
5
|
-
* compliance preflight
|
|
4
|
+
* the endpoint holds no session; it reads the routed store's catalog, runs the store's own
|
|
5
|
+
* compliance preflight, reports what the final-cart authorization would need and records one
|
|
6
|
+
* attribution event per created session.
|
|
6
7
|
*
|
|
7
8
|
* Nothing here creates a payment, a payable signed cart or an order, and nothing here attests
|
|
8
9
|
* verification. Every response says `requires_escalation` with a `continue_url` to the review
|
|
@@ -18,7 +19,7 @@ import {
|
|
|
18
19
|
type CartProposalReason,
|
|
19
20
|
type ExciseCarrier,
|
|
20
21
|
} from "@tot/public-runtime";
|
|
21
|
-
import {
|
|
22
|
+
import { AGENT_INTAKE_SUSPENDED_MESSAGE, agentIntakeSuspended } from "@/lib/checkout/shared/intakeSuspend";
|
|
22
23
|
import { exciseLinesDigest, exciseRequiredForTenant } from "@/lib/checkout/commerce/sharedStoreAdmission";
|
|
23
24
|
import {
|
|
24
25
|
CART_PROPOSAL_ID_PARAM,
|
|
@@ -27,9 +28,11 @@ import {
|
|
|
27
28
|
jsonReply,
|
|
28
29
|
proposalCatalog,
|
|
29
30
|
readBody,
|
|
31
|
+
recordAttribution,
|
|
30
32
|
type ProposalDeps,
|
|
31
33
|
} from "@/lib/checkout/proposal/proposalRoutes";
|
|
32
34
|
import {
|
|
35
|
+
boundedAgentLabel,
|
|
33
36
|
decodeProposalId,
|
|
34
37
|
encodeProposalId,
|
|
35
38
|
isPlainObject,
|
|
@@ -39,6 +42,7 @@ import {
|
|
|
39
42
|
resolveProposalLines,
|
|
40
43
|
validateReviewRequest,
|
|
41
44
|
type ProposalCatalog,
|
|
45
|
+
type ProposalToken,
|
|
42
46
|
} from "@/lib/checkout/proposal/cartProposal";
|
|
43
47
|
import { CART_UNAVAILABLE_MESSAGE } from "@/lib/checkout/commerce/cartSession";
|
|
44
48
|
import { resolveCartSigning, shopperCartDenialMessage, type CartSigningResolution } from "@/lib/checkout/shared/checkoutCommerce";
|
|
@@ -59,18 +63,10 @@ export const CHECKOUT_SESSIONS_PATH = "/api/commerce/checkout-sessions";
|
|
|
59
63
|
const NO_DESTINATION_DIGEST = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
|
|
60
64
|
|
|
61
65
|
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
66
|
const STALE_MESSAGE = "Prices or availability changed. Open a new checkout session.";
|
|
64
67
|
|
|
65
68
|
export interface AgentCheckoutDeps extends ProposalDeps {
|
|
66
69
|
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
70
|
}
|
|
75
71
|
|
|
76
72
|
function logAgent(context: APIContext, event: string, detail: Record<string, string | number | boolean>): void {
|
|
@@ -190,11 +186,18 @@ async function attributionOf(context: APIContext, deps: AgentCheckoutDeps): Prom
|
|
|
190
186
|
async function sessionReply(
|
|
191
187
|
context: APIContext,
|
|
192
188
|
deps: AgentCheckoutDeps,
|
|
193
|
-
input: {
|
|
189
|
+
input: {
|
|
190
|
+
id: string;
|
|
191
|
+
lines: readonly CartProposalLine[];
|
|
192
|
+
issuedAt: number;
|
|
193
|
+
status: number;
|
|
194
|
+
event: string;
|
|
195
|
+
attribution?: Awaited<ReturnType<typeof attributionOf>>;
|
|
196
|
+
},
|
|
194
197
|
): Promise<Response> {
|
|
195
198
|
const compliance = await complianceOf(context, input.lines, deps);
|
|
196
199
|
const excise = await exciseOf(context, input.lines);
|
|
197
|
-
const { label, outcome } = await attributionOf(context, deps);
|
|
200
|
+
const { label, outcome } = input.attribution ?? await attributionOf(context, deps);
|
|
198
201
|
logAgent(context, input.event, { lines: input.lines.length, eligibility: compliance.eligibility, signature: outcome });
|
|
199
202
|
return jsonReply(serializeSession({
|
|
200
203
|
id: input.id,
|
|
@@ -210,7 +213,7 @@ async function sessionReply(
|
|
|
210
213
|
|
|
211
214
|
async function guard(context: APIContext, deps: AgentCheckoutDeps): Promise<Response | { signingSecret: string }> {
|
|
212
215
|
if (await (deps.intakeSuspended ?? agentIntakeSuspended)(context)) {
|
|
213
|
-
return errorReply(context, 503, [{ code: "commerce_unavailable", content:
|
|
216
|
+
return errorReply(context, 503, [{ code: "commerce_unavailable", content: AGENT_INTAKE_SUSPENDED_MESSAGE }], "suspended");
|
|
214
217
|
}
|
|
215
218
|
const { commerce } = context.locals;
|
|
216
219
|
if (!commerce) {
|
|
@@ -258,12 +261,18 @@ export async function createCheckoutSession(context: APIContext, deps: AgentChec
|
|
|
258
261
|
}
|
|
259
262
|
|
|
260
263
|
const issuedAt = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
|
|
261
|
-
const
|
|
264
|
+
const attribution = await attributionOf(context, deps);
|
|
265
|
+
const agentLabel = attribution.label.verified ? boundedAgentLabel(attribution.label.agent) : undefined;
|
|
266
|
+
const token: ProposalToken = {
|
|
262
267
|
tenant: tenant.tot_data_scope,
|
|
263
268
|
issuedAt,
|
|
264
269
|
lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
|
|
265
|
-
|
|
266
|
-
|
|
270
|
+
source: "agent-protocol",
|
|
271
|
+
...(agentLabel ? { agentLabel } : {}),
|
|
272
|
+
};
|
|
273
|
+
const id = await encodeProposalId(token, proposalIdKey(gate.signingSecret));
|
|
274
|
+
await recordAttribution(context, deps, { metric: "proposals-created", source: "agent-protocol", token, digest: resolved.digest });
|
|
275
|
+
return sessionReply(context, deps, { id, lines: resolved.lines, issuedAt, status: 201, event: "created", attribution });
|
|
267
276
|
}
|
|
268
277
|
|
|
269
278
|
/** GET /api/commerce/checkout-sessions/{id}: the session an id names, read again from today's catalog. */
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-owned evidence for orders that began with an assistant or the agent checkout protocol.
|
|
3
|
+
*
|
|
4
|
+
* Three tables, all keyed by tenant and stage (migration 0033):
|
|
5
|
+
* - an origin binding written when a proposal is confirmed into a provider cart. Its source, agent
|
|
6
|
+
* label and approved-cart digest come from the HMAC-signed proposal token and the tenant's own
|
|
7
|
+
* declaration, never from a request field.
|
|
8
|
+
* - an evidence row written in the batch that binds a paid order to its final-cart admission. It
|
|
9
|
+
* reads the origin through that admission's provider cart, so an order with no assistant origin
|
|
10
|
+
* gets no row. It stores digests only: the verification ref is never kept.
|
|
11
|
+
* - attribution events: one row per proposal created and per checkout started, keyed by the
|
|
12
|
+
* proposal's replay key, so a replay is the same row. Paid orders are the evidence rows.
|
|
13
|
+
*
|
|
14
|
+
* Nothing here carries prompts, list text, line text, buyer data, credentials or payment refs.
|
|
15
|
+
*/
|
|
16
|
+
import type { CommerceAdmissionSnapshot, CommerceStage } from "@tot/public-runtime";
|
|
17
|
+
import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
|
|
18
|
+
|
|
19
|
+
export const ASSISTANT_ORDER_SOURCES = ["assistant", "agent-protocol"] as const;
|
|
20
|
+
export type AssistantOrderSource = (typeof ASSISTANT_ORDER_SOURCES)[number];
|
|
21
|
+
|
|
22
|
+
export const ATTRIBUTION_METRICS = ["proposals-created", "checkouts-started"] as const;
|
|
23
|
+
export type AttributionMetric = (typeof ATTRIBUTION_METRICS)[number];
|
|
24
|
+
|
|
25
|
+
/** Stored when an assistant order carries no verification ref, so the gap is visible in the row. */
|
|
26
|
+
export const ABSENT_VERIFICATION_DIGEST = "absent";
|
|
27
|
+
|
|
28
|
+
const VERIFICATION_REF_DOMAIN = "tot:verification-ref:v1:";
|
|
29
|
+
const PROPOSAL_DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
30
|
+
const EVENT_KEY = /^[a-f0-9]{32}$/;
|
|
31
|
+
|
|
32
|
+
async function sha256Hex(text: string): Promise<string> {
|
|
33
|
+
const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
34
|
+
return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The one-way, domain-separated digest of a verification ref. */
|
|
38
|
+
export async function verificationRefDigest(ref: string): Promise<string> {
|
|
39
|
+
return `sha256:${await sha256Hex(VERIFICATION_REF_DOMAIN + ref)}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isSource(value: unknown): value is AssistantOrderSource {
|
|
43
|
+
return (ASSISTANT_ORDER_SOURCES as readonly unknown[]).includes(value);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isMetric(value: unknown): value is AttributionMetric {
|
|
47
|
+
return (ATTRIBUTION_METRICS as readonly unknown[]).includes(value);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface OriginBindingInput {
|
|
51
|
+
tenantId: string;
|
|
52
|
+
stage: CommerceStage;
|
|
53
|
+
provider: "foxycart";
|
|
54
|
+
providerCartId: string;
|
|
55
|
+
source: AssistantOrderSource;
|
|
56
|
+
agentLabel?: string;
|
|
57
|
+
approvedCartDigest: string;
|
|
58
|
+
adultSignatureRequired: boolean;
|
|
59
|
+
now: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The first confirmation into a provider cart owns its origin; a later write is ignored. */
|
|
63
|
+
export function originBindingStatement(input: OriginBindingInput): QueryStatement {
|
|
64
|
+
if (!isSource(input.source) || !PROPOSAL_DIGEST.test(input.approvedCartDigest) || input.providerCartId === "") {
|
|
65
|
+
throw new Error("invalid-origin-binding");
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
sql: `INSERT INTO assistant_cart_origins
|
|
69
|
+
(tenant_id,stage,provider,provider_cart_id,source,agent_label,approved_cart_digest,adult_signature_required,created_at)
|
|
70
|
+
VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING`,
|
|
71
|
+
params: [
|
|
72
|
+
input.tenantId,
|
|
73
|
+
input.stage,
|
|
74
|
+
input.provider,
|
|
75
|
+
input.providerCartId,
|
|
76
|
+
input.source,
|
|
77
|
+
input.agentLabel ?? null,
|
|
78
|
+
input.approvedCartDigest,
|
|
79
|
+
input.adultSignatureRequired ? 1 : 0,
|
|
80
|
+
input.now,
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface AttributionEventInput {
|
|
86
|
+
tenantId: string;
|
|
87
|
+
stage: CommerceStage;
|
|
88
|
+
metric: AttributionMetric;
|
|
89
|
+
/** The proposal's replay key. */
|
|
90
|
+
eventKey: string;
|
|
91
|
+
source: AssistantOrderSource;
|
|
92
|
+
now: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function attributionEventStatement(input: AttributionEventInput): QueryStatement {
|
|
96
|
+
if (!isMetric(input.metric) || !isSource(input.source) || !EVENT_KEY.test(input.eventKey)) {
|
|
97
|
+
throw new Error("invalid-attribution-event");
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
sql: `INSERT INTO assistant_attribution_events (tenant_id,stage,metric,event_key,source,recorded_at)
|
|
101
|
+
VALUES (?,?,?,?,?,?) ON CONFLICT DO NOTHING`,
|
|
102
|
+
params: [input.tenantId, input.stage, input.metric, input.eventKey, input.source, input.now],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface EvidenceInput {
|
|
107
|
+
tenantId: string;
|
|
108
|
+
stage: CommerceStage;
|
|
109
|
+
/** The ledger's order id: the id the admission is linked to. */
|
|
110
|
+
orderId: string;
|
|
111
|
+
/** The ledger's source for the order (the provider that placed it). */
|
|
112
|
+
orderSource: string;
|
|
113
|
+
sourceOrderId: string;
|
|
114
|
+
admission: CommerceAdmissionSnapshot;
|
|
115
|
+
now: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The evidence insert for one order, run inside the batch that links the order to its admission.
|
|
120
|
+
* Source, agent label, approved-cart digest and the adult-signature requirement are read from the
|
|
121
|
+
* origin row the confirm wrote. The row exists only when the admission is linked to this order and
|
|
122
|
+
* that admission's provider cart has an origin of the same tenant and stage; a replay changes nothing.
|
|
123
|
+
*/
|
|
124
|
+
export async function evidenceInsertStatement(input: EvidenceInput): Promise<QueryStatement> {
|
|
125
|
+
const { admission } = input;
|
|
126
|
+
const ref = admission.verificationRef;
|
|
127
|
+
const digest = ref ? await verificationRefDigest(ref) : ABSENT_VERIFICATION_DIGEST;
|
|
128
|
+
const excise = admission.totals.exciseMinor ?? 0;
|
|
129
|
+
if (!Number.isSafeInteger(excise) || excise < 0) throw new Error("invalid-excise");
|
|
130
|
+
return {
|
|
131
|
+
sql: `INSERT INTO assistant_order_evidence
|
|
132
|
+
(tenant_id,stage,provider,provider_order_id,authorization_id,source,agent_label,verification_ref_digest,
|
|
133
|
+
verification_missing,approved_cart_digest,excise_minor,adult_signature_required,recorded_at)
|
|
134
|
+
SELECT ?,?,?,?,?,o.source,o.agent_label,?,?,o.approved_cart_digest,?,o.adult_signature_required,?
|
|
135
|
+
FROM assistant_cart_origins o
|
|
136
|
+
WHERE o.tenant_id=? AND o.stage=? AND o.provider=? AND o.provider_cart_id=?
|
|
137
|
+
AND EXISTS(SELECT 1 FROM commerce_admission_snapshots
|
|
138
|
+
WHERE tenant_id=? AND stage=? AND authorization_id=? AND linked_order_id=?)
|
|
139
|
+
ON CONFLICT DO NOTHING`,
|
|
140
|
+
params: [
|
|
141
|
+
input.tenantId,
|
|
142
|
+
input.stage,
|
|
143
|
+
input.orderSource,
|
|
144
|
+
input.sourceOrderId,
|
|
145
|
+
admission.authorizationId,
|
|
146
|
+
digest,
|
|
147
|
+
ref ? 0 : 1,
|
|
148
|
+
excise,
|
|
149
|
+
input.now,
|
|
150
|
+
input.tenantId,
|
|
151
|
+
input.stage,
|
|
152
|
+
admission.provider,
|
|
153
|
+
admission.providerCartId,
|
|
154
|
+
input.tenantId,
|
|
155
|
+
input.stage,
|
|
156
|
+
admission.authorizationId,
|
|
157
|
+
input.orderId,
|
|
158
|
+
],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface AttributionCounts {
|
|
163
|
+
source: AssistantOrderSource;
|
|
164
|
+
proposalsCreated: number;
|
|
165
|
+
checkoutsStarted: number;
|
|
166
|
+
paidOrders: number;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Proposals, checkouts and paid orders for one tenant and stage, per source. */
|
|
170
|
+
export async function readAttributionCounts(
|
|
171
|
+
db: Queryable,
|
|
172
|
+
tenantId: string,
|
|
173
|
+
stage: CommerceStage,
|
|
174
|
+
): Promise<AttributionCounts[]> {
|
|
175
|
+
const events = await db.all<{ source: string; metric: string; n: number }>(
|
|
176
|
+
`SELECT source, metric, COUNT(*) n FROM assistant_attribution_events
|
|
177
|
+
WHERE tenant_id=? AND stage=? GROUP BY source, metric`,
|
|
178
|
+
tenantId,
|
|
179
|
+
stage,
|
|
180
|
+
);
|
|
181
|
+
const paid = await db.all<{ source: string; n: number }>(
|
|
182
|
+
`SELECT source, COUNT(*) n FROM assistant_order_evidence
|
|
183
|
+
WHERE tenant_id=? AND stage=? GROUP BY source`,
|
|
184
|
+
tenantId,
|
|
185
|
+
stage,
|
|
186
|
+
);
|
|
187
|
+
return ASSISTANT_ORDER_SOURCES.map((source) => ({
|
|
188
|
+
source,
|
|
189
|
+
proposalsCreated: Number(events.find((row) => row.source === source && row.metric === "proposals-created")?.n ?? 0),
|
|
190
|
+
checkoutsStarted: Number(events.find((row) => row.source === source && row.metric === "checkouts-started")?.n ?? 0),
|
|
191
|
+
paidOrders: Number(paid.find((row) => row.source === source)?.n ?? 0),
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The closed key set an attribution log line may carry. */
|
|
196
|
+
export const ATTRIBUTION_LOG_KEYS = ["tenant", "stage", "source", "metric", "recorded"] as const;
|
|
197
|
+
|
|
198
|
+
export interface AttributionLogFields {
|
|
199
|
+
tenant: string;
|
|
200
|
+
stage: string;
|
|
201
|
+
source: AssistantOrderSource;
|
|
202
|
+
metric: AttributionMetric;
|
|
203
|
+
recorded: boolean;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** One log line for a recorded attribution event: closed values only. */
|
|
207
|
+
export function attributionLogLine(fields: AttributionLogFields): string {
|
|
208
|
+
return `[storefront] assistant-attribution ${JSON.stringify({
|
|
209
|
+
tenant: fields.tenant,
|
|
210
|
+
stage: fields.stage,
|
|
211
|
+
source: fields.source,
|
|
212
|
+
metric: fields.metric,
|
|
213
|
+
recorded: fields.recorded,
|
|
214
|
+
})}`;
|
|
215
|
+
}
|
|
@@ -176,7 +176,7 @@ async function sessionedCartLocation(
|
|
|
176
176
|
return fcsid ? withCartSession(commerce.cartUrl, fcsid) : null;
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
function ledgerStage(env: string | undefined): "preview" | "publication" | null {
|
|
179
|
+
export function ledgerStage(env: string | undefined): "preview" | "publication" | null {
|
|
180
180
|
if (env === "live") return "publication";
|
|
181
181
|
if (env === "test") return "preview";
|
|
182
182
|
return null;
|
|
@@ -175,11 +175,30 @@ export async function resolveProposalLines(
|
|
|
175
175
|
return { lines, refused, digest: await offerDigest(catalog.tenantScope, lines) };
|
|
176
176
|
}
|
|
177
177
|
|
|
178
|
-
/**
|
|
178
|
+
/** Where a proposal began: an assistant's pasted list or reviewed lines, or the agent checkout protocol. */
|
|
179
|
+
export type ProposalSource = "assistant" | "agent-protocol";
|
|
180
|
+
|
|
181
|
+
const SOURCE_CODE = { assistant: "a", "agent-protocol": "g" } as const;
|
|
182
|
+
const SOURCE_BY_CODE: Record<string, ProposalSource> = { a: "assistant", g: "agent-protocol" };
|
|
183
|
+
|
|
184
|
+
/** A verified signed-agent name, kept only in this bounded shape. Attribution, never a decision input. */
|
|
185
|
+
const AGENT_LABEL = /^[A-Za-z0-9._:-]{1,64}$/;
|
|
186
|
+
|
|
187
|
+
export function boundedAgentLabel(value: unknown): string | undefined {
|
|
188
|
+
return typeof value === "string" && AGENT_LABEL.test(value) ? value : undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* What a proposal id carries: the tenant it was issued for, when, the reviewed lines, and the source
|
|
193
|
+
* the server derived when it minted the id. A verified signed-agent label rides only an
|
|
194
|
+
* agent-protocol id.
|
|
195
|
+
*/
|
|
179
196
|
export interface ProposalToken {
|
|
180
197
|
tenant: string;
|
|
181
198
|
issuedAt: number;
|
|
182
199
|
lines: Array<{ variantId: string; quantity: number }>;
|
|
200
|
+
source: ProposalSource;
|
|
201
|
+
agentLabel?: string;
|
|
183
202
|
}
|
|
184
203
|
|
|
185
204
|
function toBase64Url(text: string): string {
|
|
@@ -231,11 +250,14 @@ async function idMacValid(key: string, payload: string, macHex: string): Promise
|
|
|
231
250
|
|
|
232
251
|
/** `<payload>.<mac>`: the reviewed lines and issue time, authenticated so neither can be rewritten. */
|
|
233
252
|
export async function encodeProposalId(token: ProposalToken, key: string): Promise<string> {
|
|
253
|
+
const label = token.source === "agent-protocol" ? boundedAgentLabel(token.agentLabel) : undefined;
|
|
234
254
|
const payload = toBase64Url(JSON.stringify({
|
|
235
|
-
v:
|
|
255
|
+
v: 2,
|
|
236
256
|
t: token.tenant,
|
|
237
257
|
i: token.issuedAt,
|
|
238
258
|
l: token.lines.map((line) => [line.variantId, line.quantity]),
|
|
259
|
+
s: SOURCE_CODE[token.source],
|
|
260
|
+
...(label ? { g: label } : {}),
|
|
239
261
|
}));
|
|
240
262
|
return `${payload}.${await idMac(key, payload)}`;
|
|
241
263
|
}
|
|
@@ -257,8 +279,11 @@ export async function decodeProposalId(id: unknown, key: string): Promise<Propos
|
|
|
257
279
|
throw error;
|
|
258
280
|
}
|
|
259
281
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
260
|
-
const raw = parsed as { v?: unknown; t?: unknown; i?: unknown; l?: unknown };
|
|
261
|
-
if (raw.v !==
|
|
282
|
+
const raw = parsed as { v?: unknown; t?: unknown; i?: unknown; l?: unknown; s?: unknown; g?: unknown };
|
|
283
|
+
if (raw.v !== 2 || typeof raw.t !== "string" || raw.t.length === 0 || raw.t.length > SAFE_ID_MAX) return null;
|
|
284
|
+
const source = typeof raw.s === "string" ? SOURCE_BY_CODE[raw.s] : undefined;
|
|
285
|
+
if (!source) return null;
|
|
286
|
+
if (raw.g !== undefined && (source !== "agent-protocol" || boundedAgentLabel(raw.g) === undefined)) return null;
|
|
262
287
|
if (typeof raw.i !== "number" || !Number.isSafeInteger(raw.i) || raw.i < 0) return null;
|
|
263
288
|
if (!Array.isArray(raw.l) || raw.l.length === 0 || raw.l.length > CART_PROPOSAL_MAX_LINES) return null;
|
|
264
289
|
const lines: ProposalToken["lines"] = [];
|
|
@@ -270,7 +295,8 @@ export async function decodeProposalId(id: unknown, key: string): Promise<Propos
|
|
|
270
295
|
seen.add(variantId);
|
|
271
296
|
lines.push({ variantId, quantity: quantity as number });
|
|
272
297
|
}
|
|
273
|
-
|
|
298
|
+
const agentLabel = boundedAgentLabel(raw.g);
|
|
299
|
+
return { tenant: raw.t, issuedAt: raw.i, lines, source, ...(agentLabel ? { agentLabel } : {}) };
|
|
274
300
|
}
|
|
275
301
|
|
|
276
302
|
/** `valid`, `expired` (needs a fresh review) or `invalid` (issued in the future). */
|
|
@@ -26,8 +26,17 @@ import {
|
|
|
26
26
|
type TenantConfig,
|
|
27
27
|
} from "@tot/public-runtime";
|
|
28
28
|
import { addProposalToBoundCart, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
|
|
29
|
-
import { completeCartFields, ledgerSoldOut, trustedReturnUrl } from "@/lib/checkout/commerce/checkoutHandoffRoute";
|
|
29
|
+
import { completeCartFields, ledgerSoldOut, ledgerStage, trustedReturnUrl } from "@/lib/checkout/commerce/checkoutHandoffRoute";
|
|
30
|
+
import {
|
|
31
|
+
attributionEventStatement,
|
|
32
|
+
attributionLogLine,
|
|
33
|
+
originBindingStatement,
|
|
34
|
+
type AttributionMetric,
|
|
35
|
+
} from "@/lib/checkout/commerce/assistantOrderEvidence";
|
|
30
36
|
import { resolveCartSigning, shopperCartDenialMessage, type CartSigningResolution } from "@/lib/checkout/shared/checkoutCommerce";
|
|
37
|
+
import { ASSISTANT_INTAKE_SUSPENDED_MESSAGE, agentIntakeSuspended } from "@/lib/checkout/shared/intakeSuspend";
|
|
38
|
+
import { fromD1, type Queryable } from "@/lib/catalog/d1/catalog";
|
|
39
|
+
import { readD1 } from "@/lib/publication/shared/env";
|
|
31
40
|
import {
|
|
32
41
|
catalogEntries,
|
|
33
42
|
decodeProposalId,
|
|
@@ -40,6 +49,8 @@ import {
|
|
|
40
49
|
validateReviewRequest,
|
|
41
50
|
type ProposalCatalog,
|
|
42
51
|
type ProposalRequestLine,
|
|
52
|
+
type ProposalSource,
|
|
53
|
+
type ProposalToken,
|
|
43
54
|
} from "./cartProposal";
|
|
44
55
|
import { matchList } from "./listMatcher";
|
|
45
56
|
import { renderPasteForm, renderRefusal, renderReview, type ReviewView } from "./reviewHtml";
|
|
@@ -61,9 +72,15 @@ export interface ProposalDeps {
|
|
|
61
72
|
/** The compliance preflight of the reviewed lines; null when it cannot be evaluated. */
|
|
62
73
|
preflight?: (context: APIContext, lines: readonly CartProposalLine[]) => Promise<ProposalCompliance | null>;
|
|
63
74
|
fetch?: typeof fetch;
|
|
75
|
+
/** True when the store has paused assistant and agent intake. Read before any other work. */
|
|
76
|
+
intakeSuspended?: (context: APIContext) => Promise<boolean>;
|
|
77
|
+
/** The apps database the origin and attribution rows live in; null when it is not bound. */
|
|
78
|
+
attributionDb?: () => Promise<Queryable | null>;
|
|
64
79
|
}
|
|
65
80
|
|
|
66
81
|
export interface ConfirmDeps extends ProposalDeps {
|
|
82
|
+
/** Whether the tenant's own compliance declaration requires an adult signature at delivery. */
|
|
83
|
+
adultSignatureRequired: (context: APIContext) => boolean;
|
|
67
84
|
/**
|
|
68
85
|
* The path of a product's own page in the tenant's declared URL form. Supplied by the route so
|
|
69
86
|
* the checkout capability does not import the content capability's URL rules. Confirm signs it as
|
|
@@ -134,6 +151,93 @@ function refuse(context: APIContext, refusal: Refusal, event: string): Response
|
|
|
134
151
|
return htmlReply(renderRefusal(refusal.code, refusal.message), refusal.status);
|
|
135
152
|
}
|
|
136
153
|
|
|
154
|
+
async function suspendedRefusal(context: APIContext, deps: ProposalDeps, event: string): Promise<Response | null> {
|
|
155
|
+
if (!(await (deps.intakeSuspended ?? agentIntakeSuspended)(context))) return null;
|
|
156
|
+
return refuse(context, { status: 503, code: "commerce_unavailable", message: ASSISTANT_INTAKE_SUSPENDED_MESSAGE }, event);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function appsDatabase(deps: ProposalDeps): Promise<Queryable | null> {
|
|
160
|
+
if (deps.attributionDb) return deps.attributionDb();
|
|
161
|
+
const database = await readD1("STOREFRONT_APPS_DB");
|
|
162
|
+
return database ? fromD1(database) : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Record one proposal-created or checkout-started event. A store with no apps database, or a write
|
|
167
|
+
* that fails, never changes the shopper's response: the failure is logged with a closed code.
|
|
168
|
+
*/
|
|
169
|
+
export async function recordAttribution(
|
|
170
|
+
context: APIContext,
|
|
171
|
+
deps: ProposalDeps,
|
|
172
|
+
input: { metric: AttributionMetric; source: ProposalSource; token: ProposalToken; digest: string },
|
|
173
|
+
): Promise<void> {
|
|
174
|
+
const stage = ledgerStage(context.locals.customizationEnv);
|
|
175
|
+
if (!stage) return;
|
|
176
|
+
try {
|
|
177
|
+
const db = await appsDatabase(deps);
|
|
178
|
+
if (!db) return;
|
|
179
|
+
const now = new Date((deps.now ?? (() => Math.floor(Date.now() / 1000)))() * 1000).toISOString();
|
|
180
|
+
const statement = attributionEventStatement({
|
|
181
|
+
tenantId: commerceTenantId(context.locals.tenant),
|
|
182
|
+
stage,
|
|
183
|
+
metric: input.metric,
|
|
184
|
+
eventKey: await proposalReplayKey(input.token, input.digest),
|
|
185
|
+
source: input.source,
|
|
186
|
+
now,
|
|
187
|
+
});
|
|
188
|
+
await db.run(statement.sql, ...(statement.params ?? []));
|
|
189
|
+
console.info(attributionLogLine({
|
|
190
|
+
tenant: context.locals.tenant.tenant_id,
|
|
191
|
+
stage,
|
|
192
|
+
source: input.source,
|
|
193
|
+
metric: input.metric,
|
|
194
|
+
recorded: true,
|
|
195
|
+
}));
|
|
196
|
+
} catch (error) {
|
|
197
|
+
console.warn(`[storefront] assistant-attribution ${JSON.stringify({
|
|
198
|
+
tenant: context.locals.tenant.tenant_id,
|
|
199
|
+
code: error instanceof Error && error.message.startsWith("invalid-") ? error.message : "write-failed",
|
|
200
|
+
})}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Bind the provider cart a proposal was confirmed into to its origin. Source and agent label come
|
|
206
|
+
* from the signed proposal token, the adult-signature requirement from the tenant's own declaration
|
|
207
|
+
* and the digest from the reviewed offer; nothing comes from the request. A failed write is logged
|
|
208
|
+
* with a closed code and does not change the shopper's response.
|
|
209
|
+
*/
|
|
210
|
+
async function bindOrigin(
|
|
211
|
+
context: APIContext,
|
|
212
|
+
deps: ConfirmDeps,
|
|
213
|
+
input: { token: ProposalToken; digest: string; providerCartId: string },
|
|
214
|
+
): Promise<void> {
|
|
215
|
+
const stage = ledgerStage(context.locals.customizationEnv);
|
|
216
|
+
if (!stage) return;
|
|
217
|
+
try {
|
|
218
|
+
const db = await appsDatabase(deps);
|
|
219
|
+
if (!db) return;
|
|
220
|
+
const now = new Date((deps.now ?? (() => Math.floor(Date.now() / 1000)))() * 1000).toISOString();
|
|
221
|
+
const statement = originBindingStatement({
|
|
222
|
+
tenantId: commerceTenantId(context.locals.tenant),
|
|
223
|
+
stage,
|
|
224
|
+
provider: "foxycart",
|
|
225
|
+
providerCartId: input.providerCartId,
|
|
226
|
+
source: input.token.source,
|
|
227
|
+
...(input.token.agentLabel ? { agentLabel: input.token.agentLabel } : {}),
|
|
228
|
+
approvedCartDigest: input.digest,
|
|
229
|
+
adultSignatureRequired: deps.adultSignatureRequired(context),
|
|
230
|
+
now,
|
|
231
|
+
});
|
|
232
|
+
await db.run(statement.sql, ...(statement.params ?? []));
|
|
233
|
+
} catch (error) {
|
|
234
|
+
console.warn(`[storefront] assistant-origin ${JSON.stringify({
|
|
235
|
+
tenant: context.locals.tenant.tenant_id,
|
|
236
|
+
code: error instanceof Error && error.message.startsWith("invalid-") ? error.message : "write-failed",
|
|
237
|
+
})}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
137
241
|
/** The parsed request body: JSON or a urlencoded form, bounded. `null` is an unreadable body. */
|
|
138
242
|
export async function readBody(request: Request): Promise<Record<string, unknown> | unknown[] | null> {
|
|
139
243
|
const type = request.headers.get("content-type") ?? "";
|
|
@@ -245,6 +349,8 @@ export function cartProposalForm(context: APIContext): Response {
|
|
|
245
349
|
* availability. Reads only: confirming stays the same-origin POST.
|
|
246
350
|
*/
|
|
247
351
|
export async function cartProposalOpen(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
|
|
352
|
+
const suspended = await suspendedRefusal(context, deps, "open-suspended");
|
|
353
|
+
if (suspended) return suspended;
|
|
248
354
|
const id = new URL(context.request.url).searchParams.get(CART_PROPOSAL_ID_PARAM);
|
|
249
355
|
if (id === null) return cartProposalForm(context);
|
|
250
356
|
const { tenant, commerce } = context.locals;
|
|
@@ -311,6 +417,8 @@ export async function cartProposalOpen(context: APIContext, deps: ProposalDeps =
|
|
|
311
417
|
|
|
312
418
|
/** POST: resolve an assistant's lines into a reviewable offer. Reads only; changes no cart. */
|
|
313
419
|
export async function cartProposalReview(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
|
|
420
|
+
const suspended = await suspendedRefusal(context, deps, "review-suspended");
|
|
421
|
+
if (suspended) return suspended;
|
|
314
422
|
const { tenant, commerce } = context.locals;
|
|
315
423
|
if (!commerce) {
|
|
316
424
|
return refuse(context, { status: 409, code: "commerce_unavailable", message: NO_COMMERCE_MESSAGE }, "review-refused");
|
|
@@ -357,13 +465,15 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
357
465
|
...(sourceText ? { text: sourceText[item.index] ?? "" } : {}),
|
|
358
466
|
}));
|
|
359
467
|
const issuedAt = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
|
|
468
|
+
const minted: ProposalToken = {
|
|
469
|
+
tenant: tenant.tot_data_scope,
|
|
470
|
+
issuedAt,
|
|
471
|
+
lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
|
|
472
|
+
source: "assistant",
|
|
473
|
+
};
|
|
360
474
|
const proposal = resolved.lines.length > 0
|
|
361
475
|
? {
|
|
362
|
-
id: await encodeProposalId(
|
|
363
|
-
tenant: tenant.tot_data_scope,
|
|
364
|
-
issuedAt,
|
|
365
|
-
lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
|
|
366
|
-
}, proposalIdKey(signing.secret)),
|
|
476
|
+
id: await encodeProposalId(minted, proposalIdKey(signing.secret)),
|
|
367
477
|
digest: resolved.digest,
|
|
368
478
|
issuedAt,
|
|
369
479
|
expiresAt: issuedAt + CART_PROPOSAL_TTL_SECONDS,
|
|
@@ -388,6 +498,9 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
388
498
|
refused: resolved.refused.length,
|
|
389
499
|
unmatched: unmatched.length,
|
|
390
500
|
});
|
|
501
|
+
if (proposal) {
|
|
502
|
+
await recordAttribution(context, deps, { metric: "proposals-created", source: "assistant", token: minted, digest: proposal.digest });
|
|
503
|
+
}
|
|
391
504
|
|
|
392
505
|
const status = proposal ? 200 : 422;
|
|
393
506
|
if (wantsJson(context.request)) {
|
|
@@ -407,6 +520,8 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
407
520
|
|
|
408
521
|
/** POST: hand a reviewed proposal into the signed cart. Takes only `{proposalId, digest}`. */
|
|
409
522
|
export async function cartProposalConfirm(context: APIContext, deps: ConfirmDeps): Promise<Response> {
|
|
523
|
+
const suspended = await suspendedRefusal(context, deps, "confirm-suspended");
|
|
524
|
+
if (suspended) return suspended;
|
|
410
525
|
const { tenant, commerce } = context.locals;
|
|
411
526
|
if (!sameOrigin(context)) {
|
|
412
527
|
return refuse(context, { status: 403, code: "cross_origin", message: "This request cannot be accepted." }, "confirm-refused");
|
|
@@ -508,6 +623,8 @@ export async function cartProposalConfirm(context: APIContext, deps: ConfirmDeps
|
|
|
508
623
|
if (!added) {
|
|
509
624
|
return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "confirm-refused");
|
|
510
625
|
}
|
|
626
|
+
await bindOrigin(context, deps, { token, digest: validated.digest, providerCartId: added.id });
|
|
627
|
+
await recordAttribution(context, deps, { metric: "checkouts-started", source: token.source, token, digest: validated.digest });
|
|
511
628
|
const location = withCartSession(commerce.cartUrl, added.id);
|
|
512
629
|
logProposal(context, "confirmed", { lines: live.lines.length, replayed: added.replayed });
|
|
513
630
|
if (wantsJson(context.request)) {
|