@tokenoftrust/storefront-runner 7.6.20 → 7.7.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.
@@ -16,6 +16,14 @@ export const ORDERS_FULFIL_BY_ID_ROLE = "orders:fulfil-by-id" as const satisfies
16
16
  export const PROPOSALS_WRITE_ROLE = "proposals:write" as const satisfies AgentRoleId;
17
17
  export const ORDERS_READ_HOLDS_ROLE = "orders:read-holds" as const satisfies AgentRoleId;
18
18
 
19
+ /** The role under which an agent files a `coupon.create` proposal; not yet in the vendored catalog. */
20
+ export const COUPONS_PROPOSE_ROLE = "coupons:propose";
21
+
22
+ /** True when `role` is in the vendored catalog and the grant names it exactly. */
23
+ export function agentHoldsVendoredRole(roles: readonly string[] | null | undefined, role: string): boolean {
24
+ return isAgentRoleId(role) && Array.isArray(roles) && roles.includes(role);
25
+ }
26
+
19
27
  /** True when the catalog permits the role and the grant names it exactly. */
20
28
  export function agentHoldsRole(roles: readonly string[] | null | undefined, role: CatalogCapabilityId): boolean {
21
29
  return isAgentRoleId(role) && Array.isArray(roles) && roles.includes(role);
@@ -40,9 +40,12 @@
40
40
  import { COMMERCE_STAGES } from "@tot/public-runtime";
41
41
  import type { SessionRecord } from "./session.js";
42
42
  import { isAgentSession } from "./session.js";
43
+ import { isAgentRoleId } from "@/lib/access/shared/generated/capabilityCatalog.generated";
43
44
  import {
44
45
  ADMIN_READ_ROLE,
45
46
  agentHoldsRole,
47
+ agentHoldsVendoredRole,
48
+ COUPONS_PROPOSE_ROLE,
46
49
  ORDERS_FULFIL_BY_ID_ROLE,
47
50
  ORDERS_READ_HOLDS_ROLE,
48
51
  PROPOSALS_WRITE_ROLE,
@@ -76,6 +79,23 @@ export const AGENT_ROLE_ROUTES: ReadonlyArray<{ method: string; path: string; ro
76
79
  { method: "GET", path: "/api/admin/hold-reasons", role: ORDERS_READ_HOLDS_ROLE },
77
80
  ];
78
81
 
82
+ /**
83
+ * Exact filing doors under a role the platform has not vendored yet. The role is not a catalog id, so
84
+ * no grant can hold it: until it is vendored the gate answers the door 501 `not_configured` itself, and
85
+ * no handler is reached. Once the catalog carries the role, a grant naming it is admitted to the handler,
86
+ * which verifies the grant.
87
+ */
88
+ export const AGENT_FILING_ROUTES: ReadonlyArray<{ method: string; path: string; role: string }> = [
89
+ { method: "POST", path: "/api/admin/coupon-operations", role: COUPONS_PROPOSE_ROLE },
90
+ ];
91
+
92
+ /** True when `method renderPath` is a filing door whose role is not in the vendored catalog. */
93
+ export function agentFilingDoorUnvendored(method: string, renderPath: string): boolean {
94
+ const verb = (method || "GET").toUpperCase();
95
+ const path = gatePath(renderPath);
96
+ return path !== null && AGENT_FILING_ROUTES.some((r) => r.method === verb && r.path === path && !isAgentRoleId(r.role));
97
+ }
98
+
79
99
  function routeMatches(pattern: string, path: string): boolean {
80
100
  if (!pattern.endsWith("/:id")) return pattern === path;
81
101
  const base = pattern.slice(0, -"/:id".length);
@@ -153,6 +173,7 @@ export function agentMayReach(method: string, renderPath: string, roles: readonl
153
173
  if (path === null) return false;
154
174
  if (AGENT_ALLOWED_ROUTES.some((r) => r.method === verb && r.path === path)) return true;
155
175
  if (AGENT_ROLE_ROUTES.some((r) => r.method === verb && routeMatches(r.path, path) && agentHoldsRole(roles, r.role))) return true;
176
+ if (AGENT_FILING_ROUTES.some((r) => r.method === verb && r.path === path && agentHoldsVendoredRole(roles, r.role))) return true;
156
177
  if (verb !== "GET" && verb !== "HEAD") return false;
157
178
  // `/__capabilities` and any other `/__*` console is a control surface.
158
179
  if (path.startsWith("/__")) return false;
@@ -228,6 +249,12 @@ export function agentSessionGateRefusal(
228
249
  );
229
250
  }
230
251
  if (agentMayReach(method, renderPath, session.actor.roles)) return null;
252
+ if (agentFilingDoorUnvendored(method, renderPath)) {
253
+ return new Response(JSON.stringify({ error: "not_configured" }), {
254
+ status: 501,
255
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
256
+ });
257
+ }
231
258
  return new Response(
232
259
  JSON.stringify({ error: "agent_route_not_allowed", reason: "agentDenied" }),
233
260
  { status: 403, headers: { "content-type": "application/json", "cache-control": "no-store" } },
@@ -248,12 +248,9 @@ export function isStaticBundleUploadPath(pathname: string): boolean {
248
248
  export function isCandidatePreviewPath(pathname: string): boolean {
249
249
  if (pathname.startsWith("/preview/render/")) return true;
250
250
  if (pathname === "/preview/change" || pathname.startsWith("/preview/change/")) return true;
251
- // /<tenant>/preview/pr and /<tenant>/preview/pr/<n> — the PR-number alias.
252
- if (/^\/[^/]+\/preview\/pr(?:\/|$)/.test(pathname)) return true;
253
- if (/^\/[^/]+\/preview\/staged(?:\/|$)/.test(pathname)) return true;
254
- // /<tenant>/preview/rev/<sha> and /<tenant>/preview/rev/<sha>/<path...> — the
255
- // immutable per-revision alias.
256
- return /^\/[^/]+\/preview\/rev(?:\/|$)/.test(pathname);
251
+ // Both bare host-routed (`/preview/pr|staged|rev`) and tenant-first (`/<tenant>/preview/...`).
252
+ if (/^\/preview\/(?:pr|staged|rev)(?:\/|$)/.test(pathname)) return true;
253
+ return /^\/[^/]+\/preview\/(?:pr|staged|rev)(?:\/|$)/.test(pathname);
257
254
  }
258
255
 
259
256
  /**
@@ -60,6 +60,21 @@ export async function getSessionStore(): Promise<SessionStore | null> {
60
60
  return kv ? new KvSessionStore(kv) : null;
61
61
  }
62
62
 
63
+ const inRequestViewerSessions = new WeakMap<Request, SessionRecord>();
64
+
65
+ /**
66
+ * Bind an in-request rotated session (e.g. after `enterStoreAsStaff` rotates the
67
+ * cookie) so downstream readers on the same request (`resolveRequestPrincipal`)
68
+ * see the new `staffSelection` without depending on incoming cookie headers or
69
+ * KV read-after-write timing.
70
+ */
71
+ export function rememberRequestViewerSession(
72
+ context: { request?: Request },
73
+ session: SessionRecord,
74
+ ): void {
75
+ if (context.request) inRequestViewerSessions.set(context.request, session);
76
+ }
77
+
63
78
  /**
64
79
  * Read the signed-in viewer's FULL session (email + all tenant memberships), or
65
80
  * null when there's no valid session. Unlike the gate's read, this is NOT scoped
@@ -68,8 +83,12 @@ export async function getSessionStore(): Promise<SessionStore | null> {
68
83
  * against the SELECTED vendor. Returns null in runtimes without the SESSION KV.
69
84
  */
70
85
  export async function readViewerSession(
71
- context: { cookies: APIContext["cookies"] },
86
+ context: { cookies: APIContext["cookies"]; request?: Request },
72
87
  ): Promise<SessionRecord | null> {
88
+ if (context.request) {
89
+ const remembered = inRequestViewerSessions.get(context.request);
90
+ if (remembered) return remembered;
91
+ }
73
92
  const store = await getSessionStore();
74
93
  if (!store) return null;
75
94
  const sid = context.cookies.get(SESSION_COOKIE)?.value ?? null;
@@ -127,6 +127,27 @@ export async function resolveTenantRouting(
127
127
  // the dev loop, the admin preview links and the post-deploy chrome canary.
128
128
  const byHost = await resolver.resolveStrict(host);
129
129
  if (byHost && !byHost.pathPrefixTenants) {
130
+ // A tenant host NEVER dispatches another tenant by path prefix, but a redundant
131
+ // self-prefix on a preview link (`/<own-domain>/preview/...`) on the tenant's own
132
+ // host resolves to that same tenant's preview route instead of 404ing.
133
+ const hostSegments = pathname.replace(/^\/+/, "").split("/");
134
+ let hostFirst = hostSegments[0] ?? "";
135
+ try {
136
+ hostFirst = decodeURIComponent(hostFirst);
137
+ } catch {
138
+ /* leave as-is if it isn't valid percent-encoding */
139
+ }
140
+ const selfMatch =
141
+ looksLikeHost(hostFirst) &&
142
+ (hostFirst.toLowerCase() === (byHost.appDomain ?? "").toLowerCase() ||
143
+ hostFirst.toLowerCase() === byHost.tenant_id.toLowerCase());
144
+ if (selfMatch && hostSegments[1] === "preview") {
145
+ return {
146
+ tenant: byHost,
147
+ basePath: `/${hostFirst}`,
148
+ renderPath: normalizePath(hostSegments.slice(1).join("/")),
149
+ };
150
+ }
130
151
  return { tenant: byHost, basePath: "", renderPath: normalizePath(pathname) };
131
152
  }
132
153
 
@@ -249,13 +249,15 @@ export function movementEventStatements(input: {
249
249
  source: string;
250
250
  sourceEventId: string;
251
251
  now: string;
252
+ eventPrefix?: string;
252
253
  }): SqlStatement[] {
253
254
  const { tenantId, stage } = input;
255
+ const tag = input.eventPrefix ?? "inv.";
254
256
  const prefix = `${input.sourceEventId}.`;
255
257
  return [
256
258
  {
257
259
  sql: `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
258
- SELECT 'inv.' || m.source_event_id, m.tenant_id, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}',
260
+ SELECT ? || m.source_event_id, m.tenant_id, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}',
259
261
  json_object('sku', m.sku, 'locationId', m.location_id,
260
262
  'balance', ${locationBalanceSql("m.sku", "m.location_id")},
261
263
  'available', ${availableSql("m.sku")}, 'asOf', m.as_of), m.as_of
@@ -263,17 +265,19 @@ export function movementEventStatements(input: {
263
265
  WHERE m.tenant_id = ? AND m.stage = ? AND m.source = ?
264
266
  AND ${idMatchSql("m.source_event_id")}
265
267
  AND m.quantity_delta != 0
266
- AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = 'inv.' || m.source_event_id)`,
268
+ AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = ? || m.source_event_id)`,
267
269
  params: [
270
+ tag,
268
271
  ...twice(tenantId, stage),
269
272
  ...twice(tenantId, stage),
270
273
  tenantId,
271
274
  stage,
272
275
  input.source,
273
276
  ...idMatchParams(input.sourceEventId, prefix),
277
+ tag,
274
278
  ],
275
279
  },
276
- deliveryStatement({ tenantId, stage, now: input.now, idEquals: `inv.${input.sourceEventId}`, idPrefix: `inv.${prefix}` }),
280
+ deliveryStatement({ tenantId, stage, now: input.now, idEquals: `${tag}${input.sourceEventId}`, idPrefix: `${tag}${prefix}` }),
277
281
  ];
278
282
  }
279
283
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.6.20",
3
+ "version": "7.7.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",
@@ -44,3 +44,43 @@ export function dependenciesForScanFinding(
44
44
  const group = indexDependenciesByFindingId(scan.dependencies).get(`${artifactIndex}:${groupOrdinal}`);
45
45
  return group ? [...group] : [];
46
46
  }
47
+
48
+ /**
49
+ * Every unresolved finding implied by `scan.dependencies`, without the pre-capture
50
+ * `MAX_VISIBLE_FINDINGS` display slice. Falls back to `scan.findings` when a caller
51
+ * supplied findings without raw dependencies (e.g. unit-test fixtures).
52
+ */
53
+ export function allUnresolvedImageFindings(
54
+ scan: Pick<ImageDependencyScan, "dependencies" | "findings"> & { warningBatch?: { omittedFindings?: number } | null },
55
+ ): ImageDependencyFinding[] {
56
+ const omitted = (scan.warningBatch?.omittedFindings ?? 0) > 0;
57
+ if (!scan.dependencies || scan.dependencies.length === 0 || (!omitted && scan.findings.length < 100)) {
58
+ return [...scan.findings];
59
+ }
60
+ const byId = new Map(scan.findings.map((finding) => [finding.id, finding]));
61
+ const out: ImageDependencyFinding[] = [...scan.findings];
62
+ for (const [key, group] of indexDependenciesByFindingId(scan.dependencies)) {
63
+ const dep = group[0];
64
+ if (!dep || !dep.reason) continue;
65
+ const [artifactRaw, ordinalRaw] = key.split(":");
66
+ const id = `image-dependency-${String(Number(artifactRaw) + 1).padStart(6, "0")}-${String(Number(ordinalRaw)).padStart(6, "0")}`;
67
+ if (byId.has(id)) continue;
68
+ const security = dep.disposition === "security-error";
69
+ const deferred = dep.disposition === "deferred";
70
+ out.push({
71
+ id,
72
+ code: security ? "image-reference-security" : deferred ? "image-reference-deferred" : "image-capture-required",
73
+ reason: dep.reason,
74
+ occurrences: group.length,
75
+ authoring: security ? "non-overridable-security-error" : "warning",
76
+ hostedPreview: security ? "non-overridable-security-error" : "overridable-quality-error",
77
+ overridable: !security,
78
+ message: security
79
+ ? "Image reference requires a security fix before preview or publish."
80
+ : deferred
81
+ ? "Image reference could not be statically resolved."
82
+ : "Image reference requires hosted capture.",
83
+ });
84
+ }
85
+ return out;
86
+ }