@tokenoftrust/storefront-runner 7.3.0 → 7.3.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/lib/access/auth/agentSessionGate.ts +123 -0
- package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +53 -1
- package/apps/storefront/src/lib/access/auth/session.ts +79 -0
- package/apps/storefront/src/lib/access/dashboard/agentStoreEntry.ts +253 -0
- package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +5 -2
- package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +24 -2
- package/apps/storefront/src/lib/checkout/shared/lazyCheckoutLoader.ts +23 -4
- package/apps/storefront/src/lib/developer-experience/dev/agentGrantAttestation.ts +74 -0
- package/apps/storefront/src/middleware/index.ts +36 -1
- package/package.json +1 -1
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DENY-BY-DEFAULT gate for sponsored-agent sessions (#8500; second design review,
|
|
3
|
+
* 2026-11-17).
|
|
4
|
+
*
|
|
5
|
+
* WHY a central gate: storefront treats a staff selection as capability-agnostic
|
|
6
|
+
* standing (`viewerCanAccess` / `membershipFor`, `sessionHostCapability`, the
|
|
7
|
+
* non-owner path of `adminApiGuard`), so an agent's tot20-decided `read` selection is
|
|
8
|
+
* NOT read-only locally. Until the PII-blind projections land
|
|
9
|
+
* (storefront-agent-pii-blind-projections), an agent session may reach ONLY:
|
|
10
|
+
*
|
|
11
|
+
* - `/api/dev/cli-session` — its own sign-in (GET discovery, POST exchange);
|
|
12
|
+
* - `POST /api/preview/token` — a preview token for its bound store (no revoke);
|
|
13
|
+
* - preview CONTENT: a GET/HEAD render of the store's pages, assets and the preview
|
|
14
|
+
* renderers (`/preview`, `/preview/render|rev|staged|pr/...`).
|
|
15
|
+
*
|
|
16
|
+
* Everything else — every other `/api` route (so no derived credential such as the
|
|
17
|
+
* CLI sign-in code or the activity-ingest token), `/admin`, `/cockpit`, `/dev`,
|
|
18
|
+
* `/dashboard`, `/diag`, `/auth`, the preview review/grant/onboarding pages, and every
|
|
19
|
+
* non-GET request — is refused 403 by the middleware BEFORE any handler runs.
|
|
20
|
+
*
|
|
21
|
+
* pii-blind WIDENS {@link AGENT_ALLOWED_ROUTES}; it must never remove the gate.
|
|
22
|
+
*
|
|
23
|
+
* Paths here are TENANT-RELATIVE (`renderPath`, prefix already stripped).
|
|
24
|
+
*/
|
|
25
|
+
import type { SessionRecord } from "./session.js";
|
|
26
|
+
import { isAgentSession } from "./session.js";
|
|
27
|
+
|
|
28
|
+
/** Exact non-content routes an agent session may reach, by method. */
|
|
29
|
+
export const AGENT_ALLOWED_ROUTES: ReadonlyArray<{ method: string; path: string }> = [
|
|
30
|
+
{ method: "GET", path: "/api/dev/cli-session" },
|
|
31
|
+
{ method: "POST", path: "/api/dev/cli-session" },
|
|
32
|
+
{ method: "POST", path: "/api/preview/token" },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Top-level mounts that are control surfaces, never preview content. A GET under any
|
|
37
|
+
* of them is refused unless {@link AGENT_PREVIEW_CONTENT_PREFIXES} names it.
|
|
38
|
+
*/
|
|
39
|
+
export const AGENT_PRIVILEGED_MOUNTS = [
|
|
40
|
+
"/api",
|
|
41
|
+
"/admin",
|
|
42
|
+
"/cockpit",
|
|
43
|
+
"/dev",
|
|
44
|
+
"/dashboard",
|
|
45
|
+
"/diag",
|
|
46
|
+
"/auth",
|
|
47
|
+
"/preview",
|
|
48
|
+
] as const;
|
|
49
|
+
|
|
50
|
+
/** The preview renderers under `/preview` (content, not the review/grant pages). */
|
|
51
|
+
export const AGENT_PREVIEW_CONTENT_PREFIXES = [
|
|
52
|
+
"/preview/render",
|
|
53
|
+
"/preview/rev",
|
|
54
|
+
"/preview/staged",
|
|
55
|
+
"/preview/pr",
|
|
56
|
+
] as const;
|
|
57
|
+
|
|
58
|
+
function underMount(path: string, mount: string): boolean {
|
|
59
|
+
return path === mount || path.startsWith(`${mount}/`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The path the gate matches on: decoded exactly as Astro decodes before it matches a
|
|
64
|
+
* route (`decodeURI` in astro/dist/core/app/base.js `safeDecodeURI`), then case-folded
|
|
65
|
+
* like the route tier's reserved-mount check. Without the decode `/%61pi/admin/orders`
|
|
66
|
+
* passes the gate as content and Astro still routes it to `/api/admin/orders` (measured
|
|
67
|
+
* 2026-11-17 through the real `onRequest`). Null — deny — when the path is not valid
|
|
68
|
+
* percent-encoding, or when anything encoded survives the decode (`%2F`, `%25`, ...) or
|
|
69
|
+
* a backslash appears: a path the gate cannot read the way the router will is refused.
|
|
70
|
+
*
|
|
71
|
+
* Also null when the decoded path holds an empty segment (`//`) or a `.`/`..` segment.
|
|
72
|
+
* Astro collapses duplicate leading slashes before it matches a route
|
|
73
|
+
* (`collapseDuplicateLeadingSlashes` in `removeBase`), and the route tier normalizes
|
|
74
|
+
* the same way, so `//api/admin/orders` reached the control plane while the gate read
|
|
75
|
+
* it as content (measured 2026-11-17: `//api/admin/orders`, `///admin/orders`,
|
|
76
|
+
* `//cockpit` and `//%61pi/admin/orders` all returned 200 for an agent). Rather than
|
|
77
|
+
* mirror each router's normalization, the gate refuses any path that needs one.
|
|
78
|
+
*/
|
|
79
|
+
function gatePath(renderPath: string): string | null {
|
|
80
|
+
let decoded: string;
|
|
81
|
+
try {
|
|
82
|
+
decoded = decodeURI(renderPath || "/");
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// A malformed escape is refused (deny), never routed; any other failure is not ours to hide.
|
|
85
|
+
if (error instanceof URIError) return null;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (decoded.includes("%") || decoded.includes("\\")) return null;
|
|
89
|
+
if (decoded.includes("//")) return null;
|
|
90
|
+
if (decoded.split("/").some((segment) => segment === "." || segment === "..")) return null;
|
|
91
|
+
return decoded.toLowerCase();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** True when an agent session may reach `method renderPath`. Deny-by-default. */
|
|
95
|
+
export function agentMayReach(method: string, renderPath: string): boolean {
|
|
96
|
+
const verb = (method || "GET").toUpperCase();
|
|
97
|
+
const path = gatePath(renderPath);
|
|
98
|
+
if (path === null) return false;
|
|
99
|
+
if (AGENT_ALLOWED_ROUTES.some((r) => r.method === verb && r.path === path)) return true;
|
|
100
|
+
if (verb !== "GET" && verb !== "HEAD") return false;
|
|
101
|
+
// `/__capabilities` and any other `/__*` console is a control surface.
|
|
102
|
+
if (path.startsWith("/__")) return false;
|
|
103
|
+
if (path === "/preview") return true;
|
|
104
|
+
if (AGENT_PREVIEW_CONTENT_PREFIXES.some((prefix) => underMount(path, prefix))) return true;
|
|
105
|
+
return !AGENT_PRIVILEGED_MOUNTS.some((mount) => underMount(path, mount));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The gate decision: null to proceed, or the 403 to answer. Only an AGENT session is
|
|
110
|
+
* ever refused here; a human session (or none) always proceeds unchanged.
|
|
111
|
+
*/
|
|
112
|
+
export function agentSessionGateRefusal(
|
|
113
|
+
session: Pick<SessionRecord, "actor"> | null | undefined,
|
|
114
|
+
method: string,
|
|
115
|
+
renderPath: string,
|
|
116
|
+
): Response | null {
|
|
117
|
+
if (!isAgentSession(session)) return null;
|
|
118
|
+
if (agentMayReach(method, renderPath)) return null;
|
|
119
|
+
return new Response(
|
|
120
|
+
JSON.stringify({ error: "agent_route_not_allowed", reason: "agentDenied" }),
|
|
121
|
+
{ status: 403, headers: { "content-type": "application/json", "cache-control": "no-store" } },
|
|
122
|
+
);
|
|
123
|
+
}
|
|
@@ -151,9 +151,61 @@ export async function mintBrokerAssertion(
|
|
|
151
151
|
return mintBrokerAssertionSubject(sub, overrides);
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
+
/** The agent subject grammar shared with tot-mcp and tot20: `agent:` + `[A-Za-z0-9._-]+`. */
|
|
155
|
+
export const AGENT_SUBJECT_RE = /^agent:[A-Za-z0-9._-]+$/;
|
|
156
|
+
|
|
157
|
+
/** A delegated (sponsored-agent) assertion's subject and delegation claims. */
|
|
158
|
+
export interface DelegatedBrokerAssertionInput {
|
|
159
|
+
/** The agent subject, `agent:<id>`. Never the sponsor. */
|
|
160
|
+
sub: string;
|
|
161
|
+
/** RFC 8693 actor: the SAME agent subject. Required together with `grantId`. */
|
|
162
|
+
act?: { sub: string };
|
|
163
|
+
/** The agent-sponsorship grant this entry rides on. Required together with `act`. */
|
|
164
|
+
grantId?: string;
|
|
165
|
+
/** The ONE tenant (appDomain) this assertion may act on, signed. Required. */
|
|
166
|
+
tenant: string;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Mint a DELEGATED broker assertion for a sponsored agent's store entry: `sub` and
|
|
171
|
+
* `act.sub` are both the agent (`agent:<id>`), and `grantId` names the grant tot20 checks
|
|
172
|
+
* against the tot-mcp grant attestation that travels beside it. The sponsor is never
|
|
173
|
+
* the subject: tot20 resolves it only from that attestation.
|
|
174
|
+
*
|
|
175
|
+
* Fails closed with {@link BrokerAssertionError}: `act` and `grantId` are both-or-neither
|
|
176
|
+
* and a delegated assertion needs both; `sub` must match {@link AGENT_SUBJECT_RE};
|
|
177
|
+
* `act.sub` must equal `sub`; the tenant is required. One per call (the `jti` burns).
|
|
178
|
+
*/
|
|
179
|
+
export async function mintDelegatedBrokerAssertion(
|
|
180
|
+
input: DelegatedBrokerAssertionInput,
|
|
181
|
+
overrides: Omit<MintBrokerAssertionOverrides, "tenant"> = {},
|
|
182
|
+
): Promise<string> {
|
|
183
|
+
const sub = (input.sub ?? "").trim();
|
|
184
|
+
const hasAct = !!input.act && typeof input.act.sub === "string" && input.act.sub.length > 0;
|
|
185
|
+
const grantId = typeof input.grantId === "string" ? input.grantId.trim() : "";
|
|
186
|
+
if (hasAct !== !!grantId) {
|
|
187
|
+
throw new BrokerAssertionError("broker assertion: act and grantId must be sent together");
|
|
188
|
+
}
|
|
189
|
+
if (!hasAct) {
|
|
190
|
+
throw new BrokerAssertionError("broker assertion: a delegated assertion requires act and grantId");
|
|
191
|
+
}
|
|
192
|
+
if (!AGENT_SUBJECT_RE.test(sub)) {
|
|
193
|
+
throw new BrokerAssertionError("broker assertion: a delegated subject must be an agent subject");
|
|
194
|
+
}
|
|
195
|
+
if (input.act!.sub !== sub) {
|
|
196
|
+
throw new BrokerAssertionError("broker assertion: act.sub must name the same agent as sub");
|
|
197
|
+
}
|
|
198
|
+
const tenant = (input.tenant ?? "").trim();
|
|
199
|
+
if (!tenant) {
|
|
200
|
+
throw new BrokerAssertionError("broker assertion: a delegated assertion must name its tenant");
|
|
201
|
+
}
|
|
202
|
+
return mintBrokerAssertionSubject(sub, { ...overrides, tenant }, { act: { sub }, grantId });
|
|
203
|
+
}
|
|
204
|
+
|
|
154
205
|
async function mintBrokerAssertionSubject(
|
|
155
206
|
sub: string,
|
|
156
207
|
overrides: MintBrokerAssertionOverrides,
|
|
208
|
+
delegation?: { act: { sub: string }; grantId: string },
|
|
157
209
|
): Promise<string> {
|
|
158
210
|
const privateKeyB64 = overrides.privateKeyB64 ?? (await readEnv(BROKER_PRIVATE_KEY_ENV));
|
|
159
211
|
if (!privateKeyB64) {
|
|
@@ -168,7 +220,7 @@ async function mintBrokerAssertionSubject(
|
|
|
168
220
|
|
|
169
221
|
const key = await loadSigningKey(privateKeyB64);
|
|
170
222
|
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
171
|
-
return new SignJWT(tenant ? { tenant } : {})
|
|
223
|
+
return new SignJWT({ ...(tenant ? { tenant } : {}), ...(delegation ?? {}) })
|
|
172
224
|
.setProtectedHeader({ alg: BROKER_ALG, kid, typ: "JWT" })
|
|
173
225
|
.setIssuer(issuer)
|
|
174
226
|
.setSubject(sub)
|
|
@@ -35,6 +35,80 @@ export interface StaffSelection {
|
|
|
35
35
|
capability: string;
|
|
36
36
|
/** Expiry (epoch seconds) — short-lived; re-checked on every gate/guard read. */
|
|
37
37
|
exp: number;
|
|
38
|
+
/**
|
|
39
|
+
* For an AGENT session only: the agent (`actor.id`) and grant (`actor.grantId`) tot20
|
|
40
|
+
* decided this selection for. A selection whose keys do not match the session's own
|
|
41
|
+
* actor is not live for it (see `agentSelectionLive`).
|
|
42
|
+
*/
|
|
43
|
+
agentId?: string;
|
|
44
|
+
grantId?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The principal behind a SPONSORED-AGENT session (#8500 sponsored agents, ADR
|
|
49
|
+
* capabilities-management §11). An agent session holds NO standing of its own: its
|
|
50
|
+
* `email`/`resource` are "", its `tenants`/`staff` are empty, and it never carries
|
|
51
|
+
* `acr`/`authTime`. Its only route to a store is a delegated entry tot20 decides
|
|
52
|
+
* (`enterStoreAsAgent`), which stamps a short `staffSelection` keyed to this actor.
|
|
53
|
+
*
|
|
54
|
+
* Nothing here is a secret: the exchanged bearer and the grant attestation are never
|
|
55
|
+
* stored; the sponsor appears only as a sha256 of its opaque broker subject.
|
|
56
|
+
*/
|
|
57
|
+
export interface AgentActor {
|
|
58
|
+
kind: "agent";
|
|
59
|
+
/** The agent subject, exactly the introspected `act.sub` (`agent:<id>`). */
|
|
60
|
+
id: string;
|
|
61
|
+
/** Hex sha256 of the sponsor's opaque broker subject (never the subject or an email). */
|
|
62
|
+
sponsorSubjectHash: string;
|
|
63
|
+
grantId: string;
|
|
64
|
+
/** The catalog role ids the grant names (informational; tot20 decides standing). */
|
|
65
|
+
roles: string[];
|
|
66
|
+
/** The tenants the grant names, or "*" for any. */
|
|
67
|
+
grantTenants: string[] | "*";
|
|
68
|
+
/** The ONE tenant (appDomain) this session was minted on; it may enter no other. */
|
|
69
|
+
boundTenant: string;
|
|
70
|
+
/** The trusted MCP origin that introspected the token; attestations come only from it. */
|
|
71
|
+
mcpOrigin: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** An agent session's lifetime ceiling (the grant's own expiry may cut it shorter). */
|
|
75
|
+
export const AGENT_SESSION_MAX_TTL_SECONDS = 3600;
|
|
76
|
+
|
|
77
|
+
/** True when the record belongs to a sponsored agent rather than a human viewer. */
|
|
78
|
+
export function isAgentSession(
|
|
79
|
+
record: Pick<SessionRecord, "actor"> | null | undefined,
|
|
80
|
+
): record is SessionRecord & { actor: AgentActor } {
|
|
81
|
+
return !!record && !!record.actor && record.actor.kind === "agent";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The most seconds any credential derived from an AGENT session may live: until its
|
|
86
|
+
* delegated selection or the session itself ends, whichever is first. A bearer token
|
|
87
|
+
* minted off the session must never outlive the grant decision behind it. Null for a
|
|
88
|
+
* human session or none (no cap). Zero or less, including an agent with no selection,
|
|
89
|
+
* means mint nothing.
|
|
90
|
+
*/
|
|
91
|
+
export function agentCredentialTtlCeiling(
|
|
92
|
+
record: Pick<SessionRecord, "actor" | "staffSelection" | "exp"> | null | undefined,
|
|
93
|
+
nowSeconds: number,
|
|
94
|
+
): number | null {
|
|
95
|
+
if (!isAgentSession(record)) return null;
|
|
96
|
+
const selectionExp = record.staffSelection?.exp ?? nowSeconds;
|
|
97
|
+
return Math.min(selectionExp, record.exp) - nowSeconds;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A session-derived credential's lifetime: `requestedSeconds`, cut to the agent ceiling
|
|
102
|
+
* ({@link agentCredentialTtlCeiling}) for an agent session. Null means mint nothing.
|
|
103
|
+
*/
|
|
104
|
+
export function sessionCredentialTtl(
|
|
105
|
+
record: Pick<SessionRecord, "actor" | "staffSelection" | "exp"> | null | undefined,
|
|
106
|
+
requestedSeconds: number,
|
|
107
|
+
nowSeconds: number,
|
|
108
|
+
): number | null {
|
|
109
|
+
const ceiling = agentCredentialTtlCeiling(record, nowSeconds);
|
|
110
|
+
if (ceiling === null) return requestedSeconds;
|
|
111
|
+
return ceiling > 0 ? Math.min(requestedSeconds, ceiling) : null;
|
|
38
112
|
}
|
|
39
113
|
|
|
40
114
|
/** Default session lifetime — a demo viewing session, revocable via KV. */
|
|
@@ -78,6 +152,11 @@ export interface SessionRecord {
|
|
|
78
152
|
acr?: string;
|
|
79
153
|
/** Epoch seconds of the underlying authentication event, when known (step-up path). */
|
|
80
154
|
authTime?: number;
|
|
155
|
+
/**
|
|
156
|
+
* Present ONLY on a sponsored-agent session (see {@link AgentActor}). Absent means a
|
|
157
|
+
* human viewer, whose behaviour is unchanged.
|
|
158
|
+
*/
|
|
159
|
+
actor?: AgentActor;
|
|
81
160
|
/** Issued-at, epoch seconds. */
|
|
82
161
|
createdAt: number;
|
|
83
162
|
/** Expiry, epoch seconds. The store TTL mirrors this; we re-check on read. */
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A SPONSORED AGENT entering a store: the one way an agent session gains any standing
|
|
3
|
+
* on a tenant (#8500 sponsored agents; ADR capabilities-management §11; review X4).
|
|
4
|
+
*
|
|
5
|
+
* An agent session holds nothing locally (`staff []`, `tenants []`, no email). tot20
|
|
6
|
+
* decides every entry, and it decides from proof the storefront cannot forge alone:
|
|
7
|
+
*
|
|
8
|
+
* 1. a FRESH grant attestation, fetched from the trusted MCP that introspected the
|
|
9
|
+
* agent's token (`POST /internal/dev-access/agent-grant-attestation`, bound by the
|
|
10
|
+
* route as `fetchAttestation`). tot-mcp
|
|
11
|
+
* re-reads the grant live and answers `{ attestation: null }` once it is revoked
|
|
12
|
+
* or expired, so a dead grant is refused here (403) without reaching tot20;
|
|
13
|
+
* 2. a DELEGATED broker assertion: `sub` and `act.sub` are the agent, `grantId` the
|
|
14
|
+
* grant, `tenant` the one store. Never a sponsor-email assertion;
|
|
15
|
+
* 3. tot20 `staffVendorAccess`, presented with both. The ONLY capability accepted
|
|
16
|
+
* back is `read`; anything else is refused and nothing is stamped.
|
|
17
|
+
*
|
|
18
|
+
* On success a short selection keyed to `actor.id` + `actor.grantId` is persisted under
|
|
19
|
+
* a fresh, expiry-preserving session id. It lasts at most one staff-selection window
|
|
20
|
+
* (and never past the session), and re-entry repeats all three steps.
|
|
21
|
+
*
|
|
22
|
+
* Every fault fails closed: an MCP or tot20 fault is 503, and nothing falls back to the
|
|
23
|
+
* human path, a sponsor assertion or a cached attestation. The attestation is used in
|
|
24
|
+
* flight for the one tot20 call and is never stored or logged.
|
|
25
|
+
*/
|
|
26
|
+
import type { SessionRecord, SessionStore, StaffSelection } from "@/lib/access/auth/session";
|
|
27
|
+
import { isAgentSession, readSession, rotateSession } from "@/lib/access/auth/session";
|
|
28
|
+
import { STAFF_SELECTION_TTL_SECONDS } from "./staffAdmission";
|
|
29
|
+
import {
|
|
30
|
+
createStaffVendorAccessClient,
|
|
31
|
+
staffAccessFailureMessage,
|
|
32
|
+
staffAccessHttpStatus,
|
|
33
|
+
StaffVendorAccessClientError,
|
|
34
|
+
} from "./staffVendorAccess";
|
|
35
|
+
import { BrokerAssertionError, mintDelegatedBrokerAssertion } from "@/lib/access/auth/brokerAssertion";
|
|
36
|
+
import type { StaffEntryEvent, StaffStoreEntryResult } from "./staffStoreEntry";
|
|
37
|
+
|
|
38
|
+
/** The only capability an agent entry may hold (PII-blind rules arrive separately). */
|
|
39
|
+
export const AGENT_ENTRY_CAPABILITY = "read";
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Fetches a fresh grant attestation from the session's own MCP: the attestation when
|
|
43
|
+
* the grant is live, `null` when it is dead, `"fault"` when that cannot be known
|
|
44
|
+
* (including an untrusted origin). The route binds the tot-mcp seam implementation
|
|
45
|
+
* (`fetchAgentGrantAttestation`).
|
|
46
|
+
*/
|
|
47
|
+
export type AgentGrantAttestationFetcher = (request: {
|
|
48
|
+
grantId: string;
|
|
49
|
+
agentId: string;
|
|
50
|
+
mcpOrigin: string;
|
|
51
|
+
}) => Promise<string | null | "fault">;
|
|
52
|
+
|
|
53
|
+
/** True when the grant names this tenant (by appDomain or tenant id), or any tenant. */
|
|
54
|
+
export function grantNamesTenant(
|
|
55
|
+
grantTenants: readonly string[] | "*",
|
|
56
|
+
tenant: { appDomain?: string; tenant_id?: string } | string,
|
|
57
|
+
): boolean {
|
|
58
|
+
if (grantTenants === "*") return true;
|
|
59
|
+
const names = typeof tenant === "string"
|
|
60
|
+
? [tenant]
|
|
61
|
+
: [tenant.appDomain, tenant.tenant_id];
|
|
62
|
+
const wanted = names.filter((n): n is string => !!n).map((n) => n.trim().toLowerCase());
|
|
63
|
+
return grantTenants.some((t) => typeof t === "string" && wanted.includes(t.trim().toLowerCase()));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* True when the agent session holds a LIVE delegated selection for `resource`: decided
|
|
68
|
+
* for THIS agent and grant, `read` only, unexpired. Anything else is not live, so the
|
|
69
|
+
* caller re-enters (and tot20 decides again).
|
|
70
|
+
*/
|
|
71
|
+
export function agentSelectionLive(
|
|
72
|
+
session: SessionRecord | null | undefined,
|
|
73
|
+
resource: string,
|
|
74
|
+
nowSeconds: number,
|
|
75
|
+
): boolean {
|
|
76
|
+
if (!isAgentSession(session)) return false;
|
|
77
|
+
const selection = session.staffSelection;
|
|
78
|
+
return !!selection &&
|
|
79
|
+
selection.resource === resource &&
|
|
80
|
+
selection.capability === AGENT_ENTRY_CAPABILITY &&
|
|
81
|
+
selection.agentId === session.actor.id &&
|
|
82
|
+
selection.grantId === session.actor.grantId &&
|
|
83
|
+
selection.exp > nowSeconds;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface AgentStoreEntryInput {
|
|
87
|
+
/** The agent session (must carry `actor.kind 'agent'`). */
|
|
88
|
+
session: SessionRecord;
|
|
89
|
+
/** The store to enter, by appDomain. Must be the session's bound tenant. */
|
|
90
|
+
vendorAppDomain: string;
|
|
91
|
+
/** Records each entry outcome; the route binds it to its activity actor. */
|
|
92
|
+
emit: (event: StaffEntryEvent) => void;
|
|
93
|
+
/** The persisted session to stamp the selection on (null id = not yet persisted). */
|
|
94
|
+
sessionHandle: () => Promise<{ store: SessionStore; id: string | null } | null>;
|
|
95
|
+
/** Fetches a fresh grant attestation, pinned to `actor.mcpOrigin`. */
|
|
96
|
+
fetchAttestation: AgentGrantAttestationFetcher;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
type Refusal = Extract<StaffStoreEntryResult, { ok: false }>;
|
|
100
|
+
|
|
101
|
+
/** The closed set of local refusal reasons: a code, never free text. */
|
|
102
|
+
type AgentRefusalReason =
|
|
103
|
+
| "notAgent"
|
|
104
|
+
| "tenantNotGranted"
|
|
105
|
+
| "sessionExpired"
|
|
106
|
+
| "unconfigured"
|
|
107
|
+
| "mcpUnavailable"
|
|
108
|
+
| "grantInactive"
|
|
109
|
+
| "capabilityNotRead"
|
|
110
|
+
| "sessionStoreUnavailable";
|
|
111
|
+
|
|
112
|
+
function refusal(status: number, error: string, reason: AgentRefusalReason): Refusal {
|
|
113
|
+
return { ok: false, status, body: { error, reason } };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Ask tot20 to decide this agent's entry, then persist the `read` selection it grants. */
|
|
117
|
+
export async function enterStoreAsAgent(input: AgentStoreEntryInput): Promise<StaffStoreEntryResult> {
|
|
118
|
+
const { session, emit } = input;
|
|
119
|
+
if (!isAgentSession(session)) {
|
|
120
|
+
return refusal(403, "agent session required", "notAgent");
|
|
121
|
+
}
|
|
122
|
+
const actor = session.actor;
|
|
123
|
+
const vendorAppDomain = input.vendorAppDomain.trim();
|
|
124
|
+
const refused = (errorClass: string, capability?: string): void =>
|
|
125
|
+
emit({
|
|
126
|
+
outcome: { status: "refused", errorClass },
|
|
127
|
+
scope: { tenantId: vendorAppDomain },
|
|
128
|
+
payload: { args: { resource: vendorAppDomain, ...(capability ? { capability } : {}) } },
|
|
129
|
+
});
|
|
130
|
+
const failed = (errorClass: string): void =>
|
|
131
|
+
emit({
|
|
132
|
+
outcome: { status: "failed", errorClass },
|
|
133
|
+
scope: { tenantId: vendorAppDomain },
|
|
134
|
+
payload: { args: { resource: vendorAppDomain, capability: AGENT_ENTRY_CAPABILITY } },
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// One tenant per session: refused locally, so tot20 is never asked about any other
|
|
138
|
+
// store. `boundTenant` was admitted against the grant's tenants when the session was
|
|
139
|
+
// minted (cli-session), and the server-side record cannot change it.
|
|
140
|
+
if (!vendorAppDomain || !actor.boundTenant || vendorAppDomain !== actor.boundTenant) {
|
|
141
|
+
refused("tenant_not_granted");
|
|
142
|
+
return refusal(403, "this agent session is not granted that store", "tenantNotGranted");
|
|
143
|
+
}
|
|
144
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
145
|
+
if (session.exp <= nowSeconds) {
|
|
146
|
+
return refusal(401, "session expired; sign in again", "sessionExpired");
|
|
147
|
+
}
|
|
148
|
+
let client;
|
|
149
|
+
try {
|
|
150
|
+
client = await createStaffVendorAccessClient();
|
|
151
|
+
} catch (err) {
|
|
152
|
+
if (err instanceof StaffVendorAccessClientError) {
|
|
153
|
+
return refusal(503, "staff-access integration not configured", "unconfigured");
|
|
154
|
+
}
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let attestation: string | null | "fault";
|
|
159
|
+
try {
|
|
160
|
+
attestation = await input.fetchAttestation({ grantId: actor.grantId, agentId: actor.id, mcpOrigin: actor.mcpOrigin });
|
|
161
|
+
} catch {
|
|
162
|
+
attestation = "fault";
|
|
163
|
+
}
|
|
164
|
+
if (attestation === "fault") {
|
|
165
|
+
failed("attestation_unavailable");
|
|
166
|
+
return refusal(503, "agent grant authority unavailable; retry shortly", "mcpUnavailable");
|
|
167
|
+
}
|
|
168
|
+
if (attestation === null) {
|
|
169
|
+
refused("grant_inactive");
|
|
170
|
+
return refusal(403, "this agent's grant is not active", "grantInactive");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let assertion: string;
|
|
174
|
+
try {
|
|
175
|
+
assertion = await mintDelegatedBrokerAssertion({
|
|
176
|
+
sub: actor.id,
|
|
177
|
+
act: { sub: actor.id },
|
|
178
|
+
grantId: actor.grantId,
|
|
179
|
+
tenant: vendorAppDomain,
|
|
180
|
+
});
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (err instanceof BrokerAssertionError) {
|
|
183
|
+
return refusal(503, "staff-proof signing not configured", "unconfigured");
|
|
184
|
+
}
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const result = await client.grantStaffAccess(assertion, vendorAppDomain, { grantAttestation: attestation });
|
|
189
|
+
if (!result.ok) {
|
|
190
|
+
refused(result.reason ?? `http_${result.status}`);
|
|
191
|
+
const status = result.reason === "error" ? 503 : staffAccessHttpStatus(result.reason, result.status);
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
status,
|
|
195
|
+
body: { error: staffAccessFailureMessage(result.reason), reason: result.reason, code: result.code },
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
if (result.capability !== AGENT_ENTRY_CAPABILITY) {
|
|
199
|
+
// tot20 is the authority, but an agent entry is read-only by contract: a wider
|
|
200
|
+
// answer is refused rather than stamped.
|
|
201
|
+
refused("capability_not_read", result.capability);
|
|
202
|
+
return refusal(403, "an agent may enter a store read-only", "capabilityNotRead");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const selection: StaffSelection = {
|
|
206
|
+
resource: vendorAppDomain,
|
|
207
|
+
capability: AGENT_ENTRY_CAPABILITY,
|
|
208
|
+
exp: nowSeconds + Math.max(1, Math.min(STAFF_SELECTION_TTL_SECONDS, session.exp - nowSeconds)),
|
|
209
|
+
agentId: actor.id,
|
|
210
|
+
grantId: actor.grantId,
|
|
211
|
+
};
|
|
212
|
+
const handle = await input.sessionHandle();
|
|
213
|
+
if (!handle) {
|
|
214
|
+
failed("session_store_unavailable");
|
|
215
|
+
return refusal(503, "session store unavailable; cannot persist admission", "sessionStoreUnavailable");
|
|
216
|
+
}
|
|
217
|
+
let updated;
|
|
218
|
+
try {
|
|
219
|
+
const current = handle.id ? await readSession(handle.store, handle.id, nowSeconds) : session;
|
|
220
|
+
updated = isAgentSession(current) &&
|
|
221
|
+
current.actor.id === actor.id &&
|
|
222
|
+
current.actor.grantId === actor.grantId &&
|
|
223
|
+
current.actor.boundTenant === actor.boundTenant &&
|
|
224
|
+
current.exp > nowSeconds
|
|
225
|
+
? await rotateSession(handle.store, {
|
|
226
|
+
...current,
|
|
227
|
+
createdAt: session.createdAt,
|
|
228
|
+
exp: Math.min(current.exp, session.exp),
|
|
229
|
+
staffSelection: { ...selection, exp: Math.min(selection.exp, current.exp, session.exp) },
|
|
230
|
+
}, nowSeconds)
|
|
231
|
+
: null;
|
|
232
|
+
} catch {
|
|
233
|
+
failed("session_store_unavailable");
|
|
234
|
+
return refusal(503, "session store unavailable; cannot persist admission", "sessionStoreUnavailable");
|
|
235
|
+
}
|
|
236
|
+
if (!updated) {
|
|
237
|
+
failed("session_expired");
|
|
238
|
+
return refusal(401, "session expired; sign in again", "sessionExpired");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
emit({
|
|
242
|
+
outcome: { status: "succeeded" },
|
|
243
|
+
scope: { tenantId: vendorAppDomain },
|
|
244
|
+
payload: { args: { resource: vendorAppDomain, capability: AGENT_ENTRY_CAPABILITY } },
|
|
245
|
+
});
|
|
246
|
+
return {
|
|
247
|
+
ok: true,
|
|
248
|
+
selection: updated.record.staffSelection ?? selection,
|
|
249
|
+
capability: AGENT_ENTRY_CAPABILITY,
|
|
250
|
+
sessionId: updated.id,
|
|
251
|
+
expiresIn: updated.record.exp - nowSeconds,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* never stored).
|
|
18
18
|
*/
|
|
19
19
|
import type { SessionRecord, SessionStore, StaffSelection } from "@/lib/access/auth/session";
|
|
20
|
-
import { readSession, rotateSession } from "@/lib/access/auth/session";
|
|
20
|
+
import { isAgentSession, readSession, rotateSession } from "@/lib/access/auth/session";
|
|
21
21
|
import { isStaffSession, buildStaffSelection, STAFF_SELECTION_TTL_SECONDS } from "./staffAdmission";
|
|
22
22
|
import {
|
|
23
23
|
createStaffVendorAccessClient,
|
|
@@ -57,7 +57,10 @@ export type StaffStoreEntryResult =
|
|
|
57
57
|
export async function enterStoreAsStaff(input: StaffStoreEntryInput): Promise<StaffStoreEntryResult> {
|
|
58
58
|
const { session, emit } = input;
|
|
59
59
|
const vendorAppDomain = input.vendorAppDomain.trim();
|
|
60
|
-
|
|
60
|
+
// A sponsored agent never enters as staff: it holds no staff standing, and a
|
|
61
|
+
// sponsor-email assertion would hand it the sponsor's capability (review X4). Its
|
|
62
|
+
// only entry is the delegated one tot20 decides (`enterStoreAsAgent`).
|
|
63
|
+
if (isAgentSession(session) || !isStaffSession(session)) {
|
|
61
64
|
return { ok: false, status: 403, body: { error: "staff access required", reason: "notStaff" } };
|
|
62
65
|
}
|
|
63
66
|
|
|
@@ -45,6 +45,19 @@ import { decodeJwt } from "jose";
|
|
|
45
45
|
*/
|
|
46
46
|
const BROKER_ASSERTION_HEADER = "X-ToT-Broker-Assertion";
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* The header carrying tot-mcp's short-lived GRANT ATTESTATION beside a DELEGATED
|
|
50
|
+
* (sponsored-agent) broker assertion. tot20 accepts it only from the pinned tot-mcp
|
|
51
|
+
* broker and resolves the sponsor only from it. Sent only on an agent entry; never
|
|
52
|
+
* stored or logged by the storefront.
|
|
53
|
+
*/
|
|
54
|
+
export const AGENT_GRANT_ATTESTATION_HEADER = "X-ToT-Agent-Grant-Attestation";
|
|
55
|
+
|
|
56
|
+
/** Extra proof an agent entry carries (absent on every human staff entry). */
|
|
57
|
+
export interface StaffVendorAccessOptions {
|
|
58
|
+
grantAttestation?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
48
61
|
/** One vendor hit from a search — the minimum needed to render + select. */
|
|
49
62
|
export interface VendorHit {
|
|
50
63
|
appDomain: string;
|
|
@@ -81,7 +94,11 @@ export interface StaffVendorAccessClient {
|
|
|
81
94
|
* verifies the assertion, writes the audit row, and returns the staffRoles-scoped
|
|
82
95
|
* capability. Called on explicit enter, never a silent per-host grant.
|
|
83
96
|
*/
|
|
84
|
-
grantStaffAccess(
|
|
97
|
+
grantStaffAccess(
|
|
98
|
+
brokerAssertion: string,
|
|
99
|
+
vendorAppDomain: string,
|
|
100
|
+
options?: StaffVendorAccessOptions,
|
|
101
|
+
): Promise<StaffVendorAccessResult>;
|
|
85
102
|
}
|
|
86
103
|
|
|
87
104
|
// --- HTTP transport seam (injected by tests) --------------------------------
|
|
@@ -209,7 +226,11 @@ export class HttpStaffVendorAccessClient implements StaffVendorAccessClient {
|
|
|
209
226
|
return normalizeVendorSearch(res.status, parsed);
|
|
210
227
|
}
|
|
211
228
|
|
|
212
|
-
async grantStaffAccess(
|
|
229
|
+
async grantStaffAccess(
|
|
230
|
+
brokerAssertion: string,
|
|
231
|
+
vendorAppDomain: string,
|
|
232
|
+
options: StaffVendorAccessOptions = {},
|
|
233
|
+
): Promise<StaffVendorAccessResult> {
|
|
213
234
|
const vendor = (vendorAppDomain ?? "").trim();
|
|
214
235
|
if (!vendor) {
|
|
215
236
|
return { ok: false, status: 400, reason: "invalid", message: "a vendor appDomain is required" };
|
|
@@ -218,6 +239,7 @@ export class HttpStaffVendorAccessClient implements StaffVendorAccessClient {
|
|
|
218
239
|
// assertion header — NEVER a plaintext `email` body field.
|
|
219
240
|
const headers: Record<string, string> = {};
|
|
220
241
|
if (brokerAssertion) headers[BROKER_ASSERTION_HEADER] = brokerAssertion;
|
|
242
|
+
if (options.grantAttestation) headers[AGENT_GRANT_ATTESTATION_HEADER] = options.grantAttestation;
|
|
221
243
|
let res: HttpResponseLike;
|
|
222
244
|
try {
|
|
223
245
|
res = await this.transport.post(
|
|
@@ -43,7 +43,10 @@
|
|
|
43
43
|
* same-origin session endpoint (an HttpOnly cookie the browser cannot read) and
|
|
44
44
|
* is applied in the loader's `onLoad`, before the drawer reads its own cookie.
|
|
45
45
|
* Cart links get the same id on the URL. If the session cannot be opened, the
|
|
46
|
-
* cart is not followed.
|
|
46
|
+
* cart is not followed. An add opens a new provider session holding the cart
|
|
47
|
+
* (cartSession.ts), so the confirmation it raises carries that session on its
|
|
48
|
+
* cart link; the loader adopts it, and a drawer already up switches to it through
|
|
49
|
+
* Foxy's own `FC.session.reset`, which re-renders the drawer from that session.
|
|
47
50
|
*
|
|
48
51
|
* On a store that is not public (`storeNotPublic`), a managed add-to-cart is
|
|
49
52
|
* checked before it leaves the page: the checkout route refuses a viewer admitted
|
|
@@ -57,6 +60,7 @@
|
|
|
57
60
|
*/
|
|
58
61
|
import { CHECKOUT_NAVIGATION_REFERRER_POLICY } from "@tot/public-runtime";
|
|
59
62
|
import { CART_UNAVAILABLE_MESSAGE } from "@/lib/checkout/commerce/cartSession";
|
|
63
|
+
import { CART_ADDED_EVENT } from "./cartState";
|
|
60
64
|
|
|
61
65
|
export const LAZY_CHECKOUT_LOADER_IDLE_MS = 8000;
|
|
62
66
|
|
|
@@ -227,8 +231,8 @@ export function lazyCheckoutLoaderJs(options: LazyCheckoutLoaderOptions): string
|
|
|
227
231
|
sessionPromise = null;
|
|
228
232
|
return null;
|
|
229
233
|
}
|
|
230
|
-
sessionId = id;
|
|
231
|
-
return
|
|
234
|
+
if (!sessionId) sessionId = id;
|
|
235
|
+
return sessionId;
|
|
232
236
|
}, function () {
|
|
233
237
|
sessionPromise = null;
|
|
234
238
|
return null;
|
|
@@ -325,7 +329,7 @@ export function lazyCheckoutLoaderJs(options: LazyCheckoutLoaderOptions): string
|
|
|
325
329
|
window.FC = window.FC || {};
|
|
326
330
|
window.FC.onLoad = function () {
|
|
327
331
|
window.FC.settings = window.FC.settings || {};
|
|
328
|
-
window.FC.settings.session_id = id;
|
|
332
|
+
window.FC.settings.session_id = sessionId || id;
|
|
329
333
|
window.FC.settings.cookiepath = cookiePath;
|
|
330
334
|
window.FC.settings.sitedomain = location.hostname;
|
|
331
335
|
};
|
|
@@ -378,6 +382,21 @@ export function lazyCheckoutLoaderJs(options: LazyCheckoutLoaderOptions): string
|
|
|
378
382
|
function arm() { setTimeout(start, ${LAZY_CHECKOUT_LOADER_IDLE_MS}); }
|
|
379
383
|
if (document.readyState === 'complete') arm();
|
|
380
384
|
else window.addEventListener('load', arm);
|
|
385
|
+
window.addEventListener(${literal(CART_ADDED_EVENT)}, function (event) {
|
|
386
|
+
var detail = event.detail || {};
|
|
387
|
+
if (detail.status !== 'added' || typeof detail.cartHref !== 'string') return;
|
|
388
|
+
var id = '';
|
|
389
|
+
try {
|
|
390
|
+
var href = new URL(detail.cartHref);
|
|
391
|
+
if (href.origin === cartOrigin) id = href.searchParams.get('fcsid') || '';
|
|
392
|
+
} catch (e) {}
|
|
393
|
+
if (!/^[a-z0-9]{10,64}$/.test(id) || id === sessionId) return;
|
|
394
|
+
sessionId = id;
|
|
395
|
+
var fc = window.FC;
|
|
396
|
+
if (fc && fc.session && typeof fc.session.reset === 'function' && fc.settings) {
|
|
397
|
+
try { fc.session.reset(id); } catch (e) {}
|
|
398
|
+
}
|
|
399
|
+
});
|
|
381
400
|
function stampAnchor(anchor) {
|
|
382
401
|
if (!sessionId) return;
|
|
383
402
|
try {
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch a FRESH agent-grant attestation from tot-mcp (#8500 sponsored agents; review X4):
|
|
3
|
+
* `POST /internal/dev-access/agent-grant-attestation {grantId, agent}`.
|
|
4
|
+
*
|
|
5
|
+
* tot-mcp re-reads the agent-sponsorship grant live and answers `{ attestation }` (a
|
|
6
|
+
* short-lived JWT tot20 verifies against tot-mcp's broker key) or `{ attestation: null }`
|
|
7
|
+
* once the grant is revoked or expired. The storefront never verifies, stores or logs it:
|
|
8
|
+
* it travels in flight beside one delegated broker assertion.
|
|
9
|
+
*
|
|
10
|
+
* The request is PINNED to the MCP origin that introspected the agent's token: only the
|
|
11
|
+
* code-owned trusted origins are accepted, each reached through its own seam authority,
|
|
12
|
+
* and a request the seam would address anywhere else fails before it leaves.
|
|
13
|
+
*/
|
|
14
|
+
import { callMcpService, type McpServiceTransport } from "@/lib/developer-experience/http/mcpServiceCall";
|
|
15
|
+
import { FetchHttpTransport } from "@/lib/developer-experience/http/fetchTransport";
|
|
16
|
+
|
|
17
|
+
/** `string` when the grant is live, `null` when it is dead, `"fault"` when unknown. */
|
|
18
|
+
export type AgentGrantAttestationResult = string | null | "fault";
|
|
19
|
+
|
|
20
|
+
export interface AgentGrantAttestationRequest {
|
|
21
|
+
grantId: string;
|
|
22
|
+
/** The agent subject, `agent:<id>`. */
|
|
23
|
+
agentId: string;
|
|
24
|
+
/** The trusted MCP origin that introspected the agent's token. */
|
|
25
|
+
mcpOrigin: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The code-owned trusted MCP origins and the seam authority that reaches each: the same
|
|
30
|
+
* pair `/api/dev/cli-session` advertises. Any other origin fails closed.
|
|
31
|
+
*/
|
|
32
|
+
const MCP_AUTHORITY_BY_ORIGIN: ReadonlyMap<string, "grant" | undefined> = new Map([
|
|
33
|
+
["https://mcp.tokenoftrust.com", undefined],
|
|
34
|
+
["https://mcp.qa.tokenoftrust.com", "grant"],
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
function pinnedTransport(inner: McpServiceTransport, origin: string): McpServiceTransport {
|
|
38
|
+
return {
|
|
39
|
+
post: async (url, headers, body) => {
|
|
40
|
+
if (!inner.post || new URL(url).origin !== origin) {
|
|
41
|
+
throw new Error("agent attestation request is not addressed to the session's MCP");
|
|
42
|
+
}
|
|
43
|
+
return inner.post(url, headers, body);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function fetchAgentGrantAttestation(
|
|
49
|
+
request: AgentGrantAttestationRequest,
|
|
50
|
+
transport: McpServiceTransport = new FetchHttpTransport({ timeoutMs: 5000 }),
|
|
51
|
+
): Promise<AgentGrantAttestationResult> {
|
|
52
|
+
if (!MCP_AUTHORITY_BY_ORIGIN.has(request.mcpOrigin)) return "fault";
|
|
53
|
+
let outcome;
|
|
54
|
+
try {
|
|
55
|
+
outcome = await callMcpService({
|
|
56
|
+
method: "POST",
|
|
57
|
+
path: "/internal/dev-access/agent-grant-attestation",
|
|
58
|
+
body: { grantId: request.grantId, agent: request.agentId },
|
|
59
|
+
authority: MCP_AUTHORITY_BY_ORIGIN.get(request.mcpOrigin),
|
|
60
|
+
transport: pinnedTransport(transport, request.mcpOrigin),
|
|
61
|
+
});
|
|
62
|
+
} catch {
|
|
63
|
+
return "fault";
|
|
64
|
+
}
|
|
65
|
+
if (outcome.kind !== "ok") return "fault";
|
|
66
|
+
let payload: unknown;
|
|
67
|
+
try {
|
|
68
|
+
payload = await outcome.json();
|
|
69
|
+
} catch {
|
|
70
|
+
return "fault";
|
|
71
|
+
}
|
|
72
|
+
const attestation = (payload as Record<string, unknown> | null)?.attestation;
|
|
73
|
+
return typeof attestation === "string" && attestation.length > 0 ? attestation : null;
|
|
74
|
+
}
|
|
@@ -58,7 +58,8 @@ import {
|
|
|
58
58
|
} from "@/lib/inventory/publicAvailability";
|
|
59
59
|
import { mirrorBalanceKey, parseMirrorBalances, publicMirrorStage } from "@/lib/inventory/mirrorBalanceProjection";
|
|
60
60
|
import { serveControlPlane } from "./controlPlane.js";
|
|
61
|
-
import { KvSessionStore, SESSION_COOKIE } from "@/lib/access/auth/session";
|
|
61
|
+
import { KvSessionStore, readSession, SESSION_COOKIE } from "@/lib/access/auth/session";
|
|
62
|
+
import { agentMayReach, agentSessionGateRefusal } from "@/lib/access/auth/agentSessionGate";
|
|
62
63
|
import { mintOpaqueBrokerAssertion } from "@/lib/access/auth/brokerAssertion";
|
|
63
64
|
import {
|
|
64
65
|
applyInternalContentResponsePolicy,
|
|
@@ -110,6 +111,29 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|
|
110
111
|
return outer ? withServerTiming(finished, timing) : finished;
|
|
111
112
|
});
|
|
112
113
|
|
|
114
|
+
/**
|
|
115
|
+
* The sponsored-agent gate: null to proceed, or the 403 to answer. A request with no
|
|
116
|
+
* session cookie, or a public/platform request an agent may make anyway, never pays
|
|
117
|
+
* the SESSION read.
|
|
118
|
+
*/
|
|
119
|
+
async function agentGate(
|
|
120
|
+
context: APIContext,
|
|
121
|
+
branch: string,
|
|
122
|
+
renderPath: string,
|
|
123
|
+
): Promise<Response | null> {
|
|
124
|
+
const method = context.request.method;
|
|
125
|
+
if (branch !== "control-plane" && agentMayReach(method, renderPath)) return null;
|
|
126
|
+
// Cookie-less requests (anonymous traffic, the signed sample front door's aliases)
|
|
127
|
+
// never touch the cookie jar: the session cookie can only arrive in this header.
|
|
128
|
+
if (!(context.request.headers.get("cookie") ?? "").includes(`${SESSION_COOKIE}=`)) return null;
|
|
129
|
+
const sid = context.cookies.get(SESSION_COOKIE)?.value ?? null;
|
|
130
|
+
if (!sid) return null;
|
|
131
|
+
const sessionKv = await readKv("SESSION");
|
|
132
|
+
if (!sessionKv) return null;
|
|
133
|
+
const session = await readSession(new KvSessionStore(sessionKv), sid, Math.floor(Date.now() / 1000));
|
|
134
|
+
return agentSessionGateRefusal(session, method, renderPath);
|
|
135
|
+
}
|
|
136
|
+
|
|
113
137
|
async function serveRequest(
|
|
114
138
|
context: APIContext,
|
|
115
139
|
next: MiddlewareNext,
|
|
@@ -230,6 +254,17 @@ async function serveRequest(
|
|
|
230
254
|
locals.routeTier = route;
|
|
231
255
|
locals.publicationRoute = publication;
|
|
232
256
|
|
|
257
|
+
// ---- Sponsored-agent gate (deny-by-default) -------------------------------
|
|
258
|
+
// An agent session reaches only its allowlist (lib/access/auth/agentSessionGate);
|
|
259
|
+
// everything else is refused here, before any availability read, internal-content
|
|
260
|
+
// decision, render or handler. Human sessions are untouched.
|
|
261
|
+
const agentRefusal = await timing.time("agent-gate", () =>
|
|
262
|
+
agentGate(context, branch, renderPath));
|
|
263
|
+
if (agentRefusal) {
|
|
264
|
+
applySecurityHeaders(agentRefusal.headers);
|
|
265
|
+
return agentRefusal;
|
|
266
|
+
}
|
|
267
|
+
|
|
233
268
|
// The availability document (ADR 0043): stored bytes by key, one R2 read, no D1 and no render.
|
|
234
269
|
// On a login-gated host it is served by the control plane, after the gate.
|
|
235
270
|
const availabilityStage = publicAvailabilityStageOf(renderPath);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.3.
|
|
3
|
+
"version": "7.3.2",
|
|
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",
|