@tokenoftrust/storefront-runner 7.6.1 → 7.6.3

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.
@@ -24,8 +24,6 @@
24
24
  */
25
25
  import { SignJWT, importPKCS8, type CryptoKey } from "jose";
26
26
  import { readEnv } from "@/lib/publication/shared/env";
27
- import { AGENT_SUBJECT_RE } from "@/lib/access/auth/session";
28
- import { isCatalogCapabilityId, type CatalogCapabilityId } from "@/lib/access/shared/generated/capabilityCatalog.generated";
29
27
 
30
28
  /** The audience tot20's broker verifier pins. */
31
29
  export const BROKER_AUDIENCE = "tot20-broker";
@@ -153,73 +151,9 @@ export async function mintBrokerAssertion(
153
151
  return mintBrokerAssertionSubject(sub, overrides);
154
152
  }
155
153
 
156
- export { AGENT_SUBJECT_RE };
157
-
158
- /** A delegated (sponsored-agent) assertion's subject and delegation claims. */
159
- export interface DelegatedBrokerAssertionInput {
160
- /** The agent subject, `agent:<id>`. Never the sponsor. */
161
- sub: string;
162
- /** RFC 8693 actor: the SAME agent subject. Required together with `grantId`. */
163
- act?: { sub: string };
164
- /** The agent-sponsorship grant this entry rides on. Required together with `act`. */
165
- grantId?: string;
166
- /** The ONE tenant (appDomain) this assertion may act on, signed. Required. */
167
- tenant: string;
168
- /**
169
- * The ONE catalog capability this assertion asks tot20's authority route to decide,
170
- * signed as `cap`. tot20 refuses an authority answer whose signed `cap` is not the
171
- * row it was asked about. Omit for a store entry (no authority row is decided).
172
- */
173
- cap?: CatalogCapabilityId;
174
- }
175
-
176
- /**
177
- * Mint a DELEGATED broker assertion for a sponsored agent's store entry: `sub` and
178
- * `act.sub` are both the agent (`agent:<id>`), and `grantId` names the grant tot20 checks
179
- * against the tot-mcp grant attestation that travels beside it. The sponsor is never
180
- * the subject: tot20 resolves it only from that attestation.
181
- *
182
- * Fails closed with {@link BrokerAssertionError}: `act` and `grantId` are both-or-neither
183
- * and a delegated assertion needs both; `sub` must match {@link AGENT_SUBJECT_RE};
184
- * `act.sub` must equal `sub`; the tenant is required. One per call (the `jti` burns).
185
- */
186
- export async function mintDelegatedBrokerAssertion(
187
- input: DelegatedBrokerAssertionInput,
188
- overrides: Omit<MintBrokerAssertionOverrides, "tenant"> = {},
189
- ): Promise<string> {
190
- const sub = (input.sub ?? "").trim();
191
- const hasAct = !!input.act && typeof input.act.sub === "string" && input.act.sub.length > 0;
192
- const grantId = typeof input.grantId === "string" ? input.grantId.trim() : "";
193
- if (hasAct !== !!grantId) {
194
- throw new BrokerAssertionError("broker assertion: act and grantId must be sent together");
195
- }
196
- if (!hasAct) {
197
- throw new BrokerAssertionError("broker assertion: a delegated assertion requires act and grantId");
198
- }
199
- if (!AGENT_SUBJECT_RE.test(sub)) {
200
- throw new BrokerAssertionError("broker assertion: a delegated subject must be an agent subject");
201
- }
202
- if (input.act!.sub !== sub) {
203
- throw new BrokerAssertionError("broker assertion: act.sub must name the same agent as sub");
204
- }
205
- const tenant = (input.tenant ?? "").trim();
206
- if (!tenant) {
207
- throw new BrokerAssertionError("broker assertion: a delegated assertion must name its tenant");
208
- }
209
- if (input.cap !== undefined && !isCatalogCapabilityId(input.cap)) {
210
- throw new BrokerAssertionError("broker assertion: cap must be a catalog capability id");
211
- }
212
- return mintBrokerAssertionSubject(sub, { ...overrides, tenant }, {
213
- act: { sub },
214
- grantId,
215
- ...(input.cap !== undefined ? { cap: input.cap } : {}),
216
- });
217
- }
218
-
219
154
  async function mintBrokerAssertionSubject(
220
155
  sub: string,
221
156
  overrides: MintBrokerAssertionOverrides,
222
- delegation?: { act: { sub: string }; grantId: string; cap?: CatalogCapabilityId },
223
157
  ): Promise<string> {
224
158
  const privateKeyB64 = overrides.privateKeyB64 ?? (await readEnv(BROKER_PRIVATE_KEY_ENV));
225
159
  if (!privateKeyB64) {
@@ -234,7 +168,7 @@ async function mintBrokerAssertionSubject(
234
168
 
235
169
  const key = await loadSigningKey(privateKeyB64);
236
170
  const nowSeconds = Math.floor(Date.now() / 1000);
237
- return new SignJWT({ ...(tenant ? { tenant } : {}), ...(delegation ?? {}) })
171
+ return new SignJWT(tenant ? { tenant } : {})
238
172
  .setProtectedHeader({ alg: BROKER_ALG, kid, typ: "JWT" })
239
173
  .setIssuer(issuer)
240
174
  .setSubject(sub)
@@ -15,6 +15,8 @@
15
15
  * host↔resource check.
16
16
  */
17
17
 
18
+ import type { CatalogCapabilityId } from "@/lib/access/shared/generated/capabilityCatalog.generated";
19
+
18
20
  /** The cookie the browser carries; value is an opaque session id (not the record). */
19
21
  export const SESSION_COOKIE = "tot_session";
20
22
 
@@ -71,6 +73,21 @@ export interface AgentActor {
71
73
  mcpOrigin: string;
72
74
  }
73
75
 
76
+ /** In-flight proof for one session-bound operation. The session never persists it. */
77
+ export type AgentGrantPairResult = { assertion: string; attestation: string } | null | "fault";
78
+
79
+ export interface AgentGrantPairRequest {
80
+ grantId: string;
81
+ /** The agent subject, `agent:<id>`. */
82
+ agentId: string;
83
+ /** The trusted MCP origin that introspected the agent's token. */
84
+ mcpOrigin: string;
85
+ tenant: string;
86
+ cap: CatalogCapabilityId;
87
+ }
88
+
89
+ export type AgentGrantPairFetcher = (request: AgentGrantPairRequest) => Promise<AgentGrantPairResult>;
90
+
74
91
  /** An agent session's lifetime ceiling (the grant's own expiry may cut it shorter). */
75
92
  export const AGENT_SESSION_MAX_TTL_SECONDS = 3600;
76
93
 
@@ -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 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.
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 { readEnv } from "@/lib/publication/shared/runtimeEnv";
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: { id: string; lines: readonly CartProposalLine[]; issuedAt: number; status: number; event: string },
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: SUSPENDED_MESSAGE }], "suspended");
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 id = await encodeProposalId({
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
- }, proposalIdKey(gate.signingSecret));
266
- return sessionReply(context, deps, { id, lines: resolved.lines, issuedAt, status: 201, event: "created" });
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
- /** What a proposal id carries: the tenant it was issued for, when, and the reviewed lines. */
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: 1,
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 !== 1 || typeof raw.t !== "string" || raw.t.length === 0 || raw.t.length > SAFE_ID_MAX) return null;
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
- return { tenant: raw.t, issuedAt: raw.i, lines };
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). */