@tokenoftrust/storefront-runner 7.6.15 → 7.6.17

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.
@@ -25,8 +25,19 @@
25
25
  * `/dashboard`, `/diag`, `/auth`, the preview review/grant/onboarding pages, and every
26
26
  * non-GET request — is refused 403 by the middleware BEFORE any handler runs.
27
27
  *
28
+ * Before any of that, a stage-bound agent session whose introspected stage is not the stage
29
+ * this Worker serves, or whose record holds neither a stage nor the grant-mode marker, is
30
+ * refused `stage_mismatch` on every agent door it can reach (the control-plane, API and
31
+ * preview-token routes, allowlisted or not). A grant-mode session is not stage-bound and
32
+ * passes this check; every other gate rule still applies to it. The stage lives
33
+ * here, once, so every agent door, present and future, inherits it. It governs the Worker's
34
+ * admin and API paths on both Cloudflare- and CloudFront-served tenants. Public content
35
+ * reads take the no-session path (`agentGate` in the middleware) and are unchanged; a
36
+ * tenant's public pages are served by the CDN and never reach this gate.
37
+ *
28
38
  * Paths here are TENANT-RELATIVE (`renderPath`, prefix already stripped).
29
39
  */
40
+ import { COMMERCE_STAGES } from "@tot/public-runtime";
30
41
  import type { SessionRecord } from "./session.js";
31
42
  import { isAgentSession } from "./session.js";
32
43
  import {
@@ -150,16 +161,72 @@ export function agentMayReach(method: string, renderPath: string, roles: readonl
150
161
  return !AGENT_PRIVILEGED_MOUNTS.some((mount) => underMount(path, mount));
151
162
  }
152
163
 
164
+ /**
165
+ * True only when the session's introspected stage is a known commerce stage AND equals
166
+ * the stage this Worker deployment serves. An absent or unknown session stage, or a
167
+ * serving stage that is unset or unknown, is false: the comparison fails closed.
168
+ */
169
+ export function agentStageMatches(sessionStage: unknown, servingStage: unknown): boolean {
170
+ return (COMMERCE_STAGES as readonly unknown[]).includes(sessionStage) && sessionStage === servingStage;
171
+ }
172
+
173
+ /**
174
+ * Whether an agent session may act on the stage this Worker serves. A stage-bound
175
+ * session must match it. A session positively introspected as grant-mode
176
+ * (`stageUnbound`) is not stage-bound and passes. Everything else, including a record
177
+ * with no stage and no `stageUnbound`, is refused.
178
+ */
179
+ export function agentStageAdmits(
180
+ binding: { stage?: unknown; stageUnbound?: unknown },
181
+ servingStage: unknown,
182
+ ): boolean {
183
+ if (binding.stage !== undefined) return agentStageMatches(binding.stage, servingStage);
184
+ return binding.stageUnbound === true;
185
+ }
186
+
187
+ /**
188
+ * The answer for a hold-reasons read that carries both a Bearer credential and a session
189
+ * cookie: 400 `mixed_credentials`, in the error shape the hold-reasons door answers with.
190
+ * It is built here so the sponsored-agent gate can refuse before any session lookup
191
+ * without reaching the orders read path.
192
+ */
193
+ export function holdReadMixedCredentialsRefusal(): Response {
194
+ return new Response(
195
+ JSON.stringify({ error: "mixed_credentials", code: "mixed_credentials" }),
196
+ {
197
+ status: 400,
198
+ headers: {
199
+ "content-type": "application/json; charset=utf-8",
200
+ "cache-control": "no-store",
201
+ "x-robots-tag": "noindex, nofollow",
202
+ },
203
+ },
204
+ );
205
+ }
206
+
153
207
  /**
154
208
  * The gate decision: null to proceed, or the 403 to answer. Only an AGENT session is
155
209
  * ever refused here; a human session (or none) always proceeds unchanged.
210
+ *
211
+ * `servingStage` is the stage this Worker serves, from its per-environment config
212
+ * (`COMMERCE_STAGE`), never the request host. An agent session minted for a different
213
+ * stage is refused on every route this function sees, allowlisted or not, with
214
+ * `stage_mismatch`. The middleware calls it for control-plane requests and any path an
215
+ * agent may not reach as public content; public content GETs never read the session.
156
216
  */
157
217
  export function agentSessionGateRefusal(
158
218
  session: Pick<SessionRecord, "actor"> | null | undefined,
159
219
  method: string,
160
220
  renderPath: string,
221
+ servingStage: string | null | undefined,
161
222
  ): Response | null {
162
223
  if (!isAgentSession(session)) return null;
224
+ if (!agentStageAdmits(session.actor, servingStage)) {
225
+ return new Response(
226
+ JSON.stringify({ error: "stage_mismatch", reason: "agentStageMismatch" }),
227
+ { status: 403, headers: { "content-type": "application/json", "cache-control": "no-store" } },
228
+ );
229
+ }
163
230
  if (agentMayReach(method, renderPath, session.actor.roles)) return null;
164
231
  return new Response(
165
232
  JSON.stringify({ error: "agent_route_not_allowed", reason: "agentDenied" }),
@@ -447,6 +447,29 @@ export function isAppCredentialRequest(input: AppCredentialRequest): boolean {
447
447
  return APP_V1_PATH.test(renderPath) && /^Bearer\s+\S/.test(authorization);
448
448
  }
449
449
 
450
+ const HOLD_READS_PATH = "/api/admin/hold-reasons";
451
+
452
+ export interface HoldReadBearerRequest {
453
+ method: string | undefined;
454
+ /** The publication render path (tenant-relative), never the raw request path. */
455
+ renderPath: string | undefined;
456
+ /** The request's `Authorization` header. */
457
+ authorization: string | null | undefined;
458
+ }
459
+
460
+ /**
461
+ * A `GET` of the hold-reasons read carrying a `Bearer` credential: the only admin API that
462
+ * reaches its handler with no session. Presence only: the handler authorizes the credential live
463
+ * (grant authority, tenant, role, stage, expiry) and refuses everything else. `renderPath` is the
464
+ * tenant-relative publication path, so the host and tenant-prefixed routes match and a neighbor
465
+ * admin API, another method, a suffix or a trailing slash matches nothing.
466
+ */
467
+ export function isHoldReadBearerRequest(input: HoldReadBearerRequest): boolean {
468
+ return input.method === "GET"
469
+ && input.renderPath === HOLD_READS_PATH
470
+ && /^Bearer\s+\S/i.test(input.authorization?.trim() ?? "");
471
+ }
472
+
450
473
  /** The render path is the app token endpoint, whose form body {@link isAppCredentialRequest} reads. */
451
474
  export function isAppTokenPath(renderPath: string | undefined): boolean {
452
475
  return renderPath === APP_TOKEN_PATH;
@@ -505,6 +528,11 @@ export interface LoginGateInput {
505
528
  * which authenticates the credential for this tenant's preview stage.
506
529
  */
507
530
  appCredential?: boolean;
531
+ /**
532
+ * True when the request is an {@link isHoldReadBearerRequest} on a preview surface. It reaches
533
+ * its handler, which authorizes the credential live for this tenant and stage.
534
+ */
535
+ holdReadBearer?: boolean;
508
536
  }
509
537
 
510
538
  /**
@@ -547,6 +575,8 @@ export function evaluateLoginGate(input: LoginGateInput): LoginGateDecision {
547
575
  // An app's own credential on an app-gateway route reaches the handler, which is
548
576
  // the authority for its tenant and install env (preview stage, `test` installs).
549
577
  if (input.appCredential) return { action: "pass" };
578
+ // The hold-reasons read's own bearer reaches its handler, the authority for the credential.
579
+ if (input.holdReadBearer) return { action: "pass" };
550
580
  if (input.hasValidSession) return { action: "pass" };
551
581
  return { action: "redirect", location: loginRedirectLocation(input.pathname) };
552
582
  }
@@ -15,6 +15,7 @@
15
15
  * host↔resource check.
16
16
  */
17
17
 
18
+ import type { CommerceStage } from "@tot/public-runtime";
18
19
  import type { CatalogCapabilityId } from "@/lib/access/shared/generated/capabilityCatalog.generated";
19
20
 
20
21
  /** The cookie the browser carries; value is an opaque session id (not the record). */
@@ -71,6 +72,17 @@ export interface AgentActor {
71
72
  boundTenant: string;
72
73
  /** The trusted MCP origin that introspected the token; attestations come only from it. */
73
74
  mcpOrigin: string;
75
+ /**
76
+ * The commerce stage tot-mcp bound the token to, as introspected. The gate refuses the
77
+ * session on every request unless it equals the stage this Worker serves.
78
+ */
79
+ stage?: CommerceStage;
80
+ /**
81
+ * Set only when tot-mcp introspected the token as a grant-mode session, which holds its
82
+ * grant's full scope and is not stage-bound. A record with neither `stage` nor this flag
83
+ * is refused.
84
+ */
85
+ stageUnbound?: true;
74
86
  }
75
87
 
76
88
  /** In-flight proof for one session-bound operation. The session never persists it. */
@@ -34,6 +34,7 @@ import {
34
34
  evaluateLoginGate,
35
35
  isApiPath,
36
36
  isAppCredentialRequest,
37
+ isHoldReadBearerRequest,
37
38
  isAppTokenPath,
38
39
  isAuthPath,
39
40
  isAdminPath,
@@ -124,6 +125,7 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
124
125
  // a Sign-in button (auth paths are exempt so sign-in itself is reachable). The
125
126
  // grant `resource` is the tenant's appDomain — never input.
126
127
  let appTestStage = false;
128
+ let holdReadBearer = false;
127
129
  if (input.hostLoginGated && !input.internalContentGrant) {
128
130
  // From the platform registry by id, NOT off `tenant` — that object resolves
129
131
  // from TENANT_CACHE KV first, so a record written before this field existed
@@ -187,6 +189,11 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
187
189
  authorization: request.headers.get("authorization"),
188
190
  formGrantType,
189
191
  });
192
+ holdReadBearer = isHoldReadBearerRequest({
193
+ method: request.method,
194
+ renderPath,
195
+ authorization: request.headers.get("authorization"),
196
+ });
190
197
  }
191
198
 
192
199
  // Canonical admin tenant landing: an AUTHENTICATED viewer who is not a
@@ -234,6 +241,7 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
234
241
  // The publication render path, never the raw request path.
235
242
  renderPath,
236
243
  appCredential: appTestStage,
244
+ holdReadBearer,
237
245
  });
238
246
  if (decision.action === "redirect") {
239
247
  // Admin and the cockpit hard-redirect to sign-in rather than rendering the
@@ -36,7 +36,7 @@ import { visitorRegionFor, withVisitorRegionCookie } from "@/lib/compliance/shar
36
36
  import { tryServeStaticBundle } from "./staticBundle.js";
37
37
  import { resolveCandidateContentPin } from "./candidatePin.js";
38
38
  import { resolveRequestPreviewContext } from "./previewContext.js";
39
- import { parseGateMode } from "@/lib/access/auth/loginGate";
39
+ import { isHoldReadBearerRequest, parseGateMode } from "@/lib/access/auth/loginGate";
40
40
  import { evaluateDemoGate, hostInGateList } from "@/lib/access/shared/demoGate";
41
41
  import { isMaintenanceOn, maintenanceResponse } from "@/lib/access/shared/maintenance";
42
42
  import { HEALTH_PATH, healthResponse } from "@/lib/observability/shared/health";
@@ -59,7 +59,7 @@ import {
59
59
  import { mirrorBalanceKey, parseMirrorBalances, publicMirrorStage } from "@/lib/inventory/mirrorBalanceProjection";
60
60
  import { serveControlPlane } from "./controlPlane.js";
61
61
  import { KvSessionStore, readSession, SESSION_COOKIE } from "@/lib/access/auth/session";
62
- import { agentMayReach, agentSessionGateRefusal } from "@/lib/access/auth/agentSessionGate";
62
+ import { agentMayReach, agentSessionGateRefusal, holdReadMixedCredentialsRefusal } from "@/lib/access/auth/agentSessionGate";
63
63
  import { mintOpaqueBrokerAssertion } from "@/lib/access/auth/brokerAssertion";
64
64
  import {
65
65
  applyInternalContentResponsePolicy,
@@ -132,10 +132,15 @@ async function agentGate(
132
132
  if (!context.request.headers.get("cookie")) return null;
133
133
  const sid = context.cookies.get(SESSION_COOKIE)?.value ?? null;
134
134
  if (!sid) return null;
135
+ // The hold-reasons read takes a bearer or a cookie session, never both: this combination is
136
+ // refused before the cookie's session is looked up, so the cookie cannot decide the outcome.
137
+ if (isHoldReadBearerRequest({ method, renderPath, authorization: context.request.headers.get("authorization") })) {
138
+ return holdReadMixedCredentialsRefusal();
139
+ }
135
140
  const sessionKv = await readKv("SESSION");
136
141
  if (!sessionKv) return null;
137
142
  const session = await readSession(new KvSessionStore(sessionKv), sid, Math.floor(Date.now() / 1000));
138
- return agentSessionGateRefusal(session, method, renderPath);
143
+ return agentSessionGateRefusal(session, method, renderPath, await readEnv("COMMERCE_STAGE"));
139
144
  }
140
145
 
141
146
  async function serveRequest(
@@ -51,10 +51,25 @@ async function readReaction(request: Request): Promise<string | null> {
51
51
  }
52
52
  }
53
53
 
54
+ function resolveBlogReactParams(context: Parameters<APIRoute>[0]): { collection?: string; slug?: string } {
55
+ const fromCollection = context.params?.collection?.trim();
56
+ const fromSlug = context.params?.slug?.trim();
57
+ if (fromCollection && fromSlug) return { collection: fromCollection, slug: fromSlug };
58
+ try {
59
+ const match = /\/api\/blog\/([^/]+)\/([^/]+)\/react\/?$/.exec(new URL(context.request.url).pathname);
60
+ if (!match?.[1] || !match?.[2]) return { collection: fromCollection, slug: fromSlug };
61
+ return {
62
+ collection: fromCollection || decodeURIComponent(match[1]).trim() || undefined,
63
+ slug: fromSlug || decodeURIComponent(match[2]).trim() || undefined,
64
+ };
65
+ } catch {
66
+ return { collection: fromCollection, slug: fromSlug };
67
+ }
68
+ }
69
+
54
70
  export const POST: APIRoute = async (context) => {
55
71
  const tenantId = context.locals?.tenant?.tenant_id;
56
- const collection = context.params.collection;
57
- const slug = context.params.slug;
72
+ const { collection, slug } = resolveBlogReactParams(context);
58
73
  if (!tenantId || !collection || !slug) {
59
74
  return json({ ok: false, error: "not_found", counts: {} as Record<Reaction, number> }, 404);
60
75
  }
@@ -5,5 +5,16 @@ import { proposalPreflight } from "../../cart-proposal/review.js";
5
5
 
6
6
  export const prerender = false;
7
7
 
8
+ function resolveCheckoutSessionId(context: APIContext): string {
9
+ const fromParam = context.params?.id?.trim();
10
+ if (fromParam) return fromParam;
11
+ try {
12
+ const match = /\/api\/commerce\/checkout-sessions\/([^/]+)\/?$/.exec(new URL(context.request.url).pathname);
13
+ return match?.[1] ? decodeURIComponent(match[1]).trim() : "";
14
+ } catch {
15
+ return "";
16
+ }
17
+ }
18
+
8
19
  export const GET = (context: APIContext): Promise<Response> =>
9
- getCheckoutSession(context, context.params.id ?? "", { preflight: proposalPreflight });
20
+ getCheckoutSession(context, resolveCheckoutSessionId(context), { preflight: proposalPreflight });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.6.15",
3
+ "version": "7.6.17",
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",