@tokenoftrust/storefront-runner 6.6.0 → 6.7.0
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/adminLanding.ts +3 -5
- package/apps/storefront/src/lib/access/auth/gatePage.ts +4 -2
- package/apps/storefront/src/lib/access/auth/loginGate.ts +71 -2
- package/apps/storefront/src/lib/access/auth/route.ts +1 -50
- package/apps/storefront/src/lib/access/auth/safeNext.ts +56 -0
- package/apps/storefront/src/middleware/controlPlane.ts +33 -30
- package/apps/storefront/src/middleware/index.ts +31 -7
- package/apps/storefront/src/middleware/previewContext.ts +71 -0
- package/apps/storefront/src/middleware/renderChain.ts +35 -21
- package/package.json +1 -1
- package/packages/public-runtime/src/customization-preview.ts +114 -0
|
@@ -23,8 +23,7 @@
|
|
|
23
23
|
* drift on "does this viewer belong to this tenant". Unit-testable in isolation.
|
|
24
24
|
*/
|
|
25
25
|
import type { SessionRecord } from "./session.js";
|
|
26
|
-
import { sessionAdmitsHost } from "./loginGate.js";
|
|
27
|
-
import { safeNext } from "./route.js";
|
|
26
|
+
import { loginRedirectLocation, sessionAdmitsHost } from "./loginGate.js";
|
|
28
27
|
import { selectTenant } from "@/lib/access/dashboard/tenantSelection";
|
|
29
28
|
|
|
30
29
|
/** The tenant-selection surface, in both host-routed and tenant-first path forms. */
|
|
@@ -55,7 +54,7 @@ export interface AdminLandingInput {
|
|
|
55
54
|
routedTenant: string;
|
|
56
55
|
/** locals.basePath: "" (host-form) or "/<domain>" (tenant-first path form). */
|
|
57
56
|
basePath: string;
|
|
58
|
-
/** The intended admin destination
|
|
57
|
+
/** The intended admin destination; only its sanitized pathname becomes `next`. */
|
|
59
58
|
intended: string;
|
|
60
59
|
/** Epoch seconds, for the staff-selection expiry check. */
|
|
61
60
|
nowSeconds: number;
|
|
@@ -65,8 +64,7 @@ export function resolveAdminLanding(input: AdminLandingInput): AdminLanding {
|
|
|
65
64
|
const { record, routedTenant, basePath, intended, nowSeconds } = input;
|
|
66
65
|
|
|
67
66
|
if (!record) {
|
|
68
|
-
|
|
69
|
-
return { action: "login", location: `/auth/login?next=${next}` };
|
|
67
|
+
return { action: "login", location: loginRedirectLocation(intended) };
|
|
70
68
|
}
|
|
71
69
|
|
|
72
70
|
// Member/owner of the routed tenant, or a ToT-staff viewer → this IS their
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import { GATE_REMEDY, type GateReason } from "@/lib/access/shared/publicAccess";
|
|
15
|
+
import { safeLoginHref } from "./loginGate.js";
|
|
15
16
|
|
|
16
17
|
/** Escape a string for safe interpolation into an HTML attribute value. */
|
|
17
18
|
function escapeAttr(s: string): string {
|
|
@@ -23,7 +24,8 @@ function escapeAttr(s: string): string {
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
export function gatedHoldingHtml(loginHref: string): string {
|
|
26
|
-
|
|
27
|
+
// Sink sanitization: the link carries a local pathname only, never a query.
|
|
28
|
+
const href = escapeAttr(safeLoginHref(loginHref));
|
|
27
29
|
return `<!doctype html>
|
|
28
30
|
<html lang="en">
|
|
29
31
|
<head>
|
|
@@ -130,7 +132,7 @@ export function gatedApiResponse(loginHref: string, request: Request, reason: Ga
|
|
|
130
132
|
reason,
|
|
131
133
|
remedy: GATE_REMEDY[reason],
|
|
132
134
|
docs: GATE_DOCS,
|
|
133
|
-
signIn: loginHref,
|
|
135
|
+
signIn: safeLoginHref(loginHref),
|
|
134
136
|
}),
|
|
135
137
|
{ status: 401, headers: { ...headers, "content-type": "application/json; charset=utf-8" } },
|
|
136
138
|
);
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import { hostInGateList } from "@/lib/access/shared/demoGate";
|
|
17
17
|
import { normalizeMemberships, staffAdmits } from "@/lib/access/dashboard/tenantSelection";
|
|
18
18
|
import type { SessionRecord } from "./session.js";
|
|
19
|
+
import { safeNext } from "./safeNext.js";
|
|
19
20
|
|
|
20
21
|
export type GateMode = "password" | "login";
|
|
21
22
|
|
|
@@ -318,6 +319,66 @@ export function isSignInRedirectPath(pathname: string): boolean {
|
|
|
318
319
|
return /^\/[^/]+\/dev(?:\/|$)/.test(pathname);
|
|
319
320
|
}
|
|
320
321
|
|
|
322
|
+
/**
|
|
323
|
+
* The one return-target sanitizer for every sign-in and gate redirect sink: a
|
|
324
|
+
* same-origin PATHNAME, with every query and fragment dropped, passed through
|
|
325
|
+
* {@link safeNext}. A query can carry a preview capability or any other credential, so
|
|
326
|
+
* no sink may reflect one, and no key list decides what is safe to keep. Anything
|
|
327
|
+
* `safeNext` refuses collapses to "/".
|
|
328
|
+
*/
|
|
329
|
+
export function safeReturnPathname(target: string | null | undefined): string {
|
|
330
|
+
const raw = target ?? "";
|
|
331
|
+
const cut = raw.search(/[?#]/);
|
|
332
|
+
return safeNext(cut < 0 ? raw : raw.slice(0, cut));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The sign-in location for a return target, sanitized by {@link safeReturnPathname}. */
|
|
336
|
+
export function loginRedirectLocation(target: string | null | undefined): string {
|
|
337
|
+
return `/auth/login?next=${encodeURIComponent(safeReturnPathname(target))}`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Re-derive a sign-in href at a response sink: its `next` goes back through
|
|
342
|
+
* {@link loginRedirectLocation}, and anything that is not a local `/auth/login` href
|
|
343
|
+
* becomes the fixed sign-in location.
|
|
344
|
+
*/
|
|
345
|
+
export function safeLoginHref(href: string | null | undefined): string {
|
|
346
|
+
let parsed: URL;
|
|
347
|
+
try {
|
|
348
|
+
parsed = new URL(href ?? "", "https://gate.invalid");
|
|
349
|
+
} catch {
|
|
350
|
+
return loginRedirectLocation("/");
|
|
351
|
+
}
|
|
352
|
+
if (parsed.origin !== "https://gate.invalid" || parsed.pathname !== "/auth/login") {
|
|
353
|
+
return loginRedirectLocation("/");
|
|
354
|
+
}
|
|
355
|
+
const next = parsed.searchParams.getAll("next");
|
|
356
|
+
return loginRedirectLocation(next.length === 1 ? next[0] : "/");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* The fulfillment app's preview bootstrap: the only method and tenant-relative
|
|
361
|
+
* render-path pairs a verified preview token lets reach their own handlers on a
|
|
362
|
+
* withheld host. Reachability only: each handler still requires its own Bearer,
|
|
363
|
+
* live install, scope, assignment and consent. `renderPath` is the publication
|
|
364
|
+
* render path (`publicationRenderPath`), never the raw request path, so host,
|
|
365
|
+
* tenant-prefixed and authenticated-CDN routing all reach the same pair, and a
|
|
366
|
+
* repeated, encoded or dot segment, a trailing slash or an extra suffix matches
|
|
367
|
+
* nothing.
|
|
368
|
+
*/
|
|
369
|
+
const PREVIEW_APP_ORDER_SEGMENT = "(?!\\.{1,2}/)[A-Za-z0-9._~-]+";
|
|
370
|
+
const PREVIEW_APP_ROUTES: ReadonlyArray<{ method: string; path: RegExp }> = [
|
|
371
|
+
{ method: "POST", path: /^\/api\/apps\/oauth\/token$/ },
|
|
372
|
+
{ method: "GET", path: /^\/api\/apps\/v1\/fulfillment\/assignments$/ },
|
|
373
|
+
{ method: "GET", path: new RegExp(`^/api/apps/v1/fulfillment/orders/${PREVIEW_APP_ORDER_SEGMENT}/recipient$`) },
|
|
374
|
+
{ method: "POST", path: new RegExp(`^/api/apps/v1/fulfillment/orders/${PREVIEW_APP_ORDER_SEGMENT}/shipment-evidence$`) },
|
|
375
|
+
];
|
|
376
|
+
|
|
377
|
+
export function isPreviewAppBootstrapRoute(method: string | undefined, renderPath: string | undefined): boolean {
|
|
378
|
+
if (!method || renderPath === undefined) return false;
|
|
379
|
+
return PREVIEW_APP_ROUTES.some((route) => route.method === method && route.path.test(renderPath));
|
|
380
|
+
}
|
|
381
|
+
|
|
321
382
|
export type LoginGateDecision =
|
|
322
383
|
| { action: "pass" }
|
|
323
384
|
| { action: "redirect"; location: string };
|
|
@@ -361,6 +422,10 @@ export interface LoginGateInput {
|
|
|
361
422
|
previewTokenValid?: boolean;
|
|
362
423
|
/** A verified, tenant-bound candidate content pin admits public content only. */
|
|
363
424
|
candidatePinValid?: boolean;
|
|
425
|
+
/** The request method, for {@link isPreviewAppBootstrapRoute}. */
|
|
426
|
+
method?: string;
|
|
427
|
+
/** The publication render path (tenant-relative), for {@link isPreviewAppBootstrapRoute}. */
|
|
428
|
+
renderPath?: string;
|
|
364
429
|
}
|
|
365
430
|
|
|
366
431
|
/**
|
|
@@ -394,7 +459,11 @@ export function evaluateLoginGate(input: LoginGateInput): LoginGateDecision {
|
|
|
394
459
|
) {
|
|
395
460
|
return { action: "pass" };
|
|
396
461
|
}
|
|
462
|
+
// The fulfillment app's preview bootstrap: a verified preview token (never a
|
|
463
|
+
// candidate content pin) lets exactly these pairs reach their own authorizers.
|
|
464
|
+
if (input.previewTokenValid && isPreviewAppBootstrapRoute(input.method, input.renderPath)) {
|
|
465
|
+
return { action: "pass" };
|
|
466
|
+
}
|
|
397
467
|
if (input.hasValidSession) return { action: "pass" };
|
|
398
|
-
|
|
399
|
-
return { action: "redirect", location: `/auth/login?next=${encodeURIComponent(next)}` };
|
|
468
|
+
return { action: "redirect", location: loginRedirectLocation(input.pathname) };
|
|
400
469
|
}
|
|
@@ -120,56 +120,7 @@ export function clearSessionCookie(context: APIContext): void {
|
|
|
120
120
|
context.cookies.delete(SESSION_COOKIE, { path: "/" });
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
|
|
124
|
-
* included, so a `next` value can never smuggle a header break or NUL. Written as
|
|
125
|
-
* a charCode scan (not a control-char regex literal) so the source stays printable. */
|
|
126
|
-
function hasControlChar(s: string): boolean {
|
|
127
|
-
for (let i = 0; i < s.length; i++) {
|
|
128
|
-
const c = s.charCodeAt(i);
|
|
129
|
-
if (c <= 0x1f || c === 0x7f) return true;
|
|
130
|
-
}
|
|
131
|
-
return false;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Sanitize a post-sign-in `next`/returnTo redirect target to a same-origin,
|
|
136
|
-
* path-only reference — the single open-redirect chokepoint for the whole sign-in
|
|
137
|
-
* surface (the login gate, verify, and the shared `pr/<N>` reviewer link all funnel
|
|
138
|
-
* through here). Anything that could resolve off-origin falls back to "/".
|
|
139
|
-
*
|
|
140
|
-
* Rejected, because a browser would treat each as an ABSOLUTE/off-origin URL:
|
|
141
|
-
* - a scheme or bare host ("https://evil.com", "evil.com")
|
|
142
|
-
* - protocol-relative ("//evil.com")
|
|
143
|
-
* - backslash-smuggled ("/\evil.com", "\\evil.com") — browsers normalize
|
|
144
|
-
* "\" → "/", so "/\evil.com" resolves as "//evil.com"
|
|
145
|
-
* - encoded slash/backslash ("/%2F%2Fevil.com", "/%5Cevil.com") that DECODES
|
|
146
|
-
* to a protocol-relative form
|
|
147
|
-
* - control chars / newlines (header-injection belt-and-suspenders)
|
|
148
|
-
* - malformed percent-encoding (refuse rather than guess)
|
|
149
|
-
*
|
|
150
|
-
* The ORIGINAL (still-encoded) value is returned on success — decoding is only for
|
|
151
|
-
* the safety check, never for the redirect target.
|
|
152
|
-
*/
|
|
153
|
-
export function safeNext(next: string | null | undefined): string {
|
|
154
|
-
if (!next) return "/";
|
|
155
|
-
if (!next.startsWith("/")) return "/";
|
|
156
|
-
// No control chars / CR / LF anywhere (header-injection belt-and-suspenders).
|
|
157
|
-
if (hasControlChar(next)) return "/";
|
|
158
|
-
// Normalize backslashes to slashes the way a browser would, then reject any
|
|
159
|
-
// protocol-relative ("//host") form — raw or backslash-smuggled.
|
|
160
|
-
if (next.replace(/\\/g, "/").startsWith("//")) return "/";
|
|
161
|
-
// Defeat encoded slash/backslash smuggling: decode once and re-check that it is
|
|
162
|
-
// still a single-slash, same-origin path. Malformed encoding → refuse.
|
|
163
|
-
let decoded: string;
|
|
164
|
-
try {
|
|
165
|
-
decoded = decodeURIComponent(next);
|
|
166
|
-
} catch {
|
|
167
|
-
return "/";
|
|
168
|
-
}
|
|
169
|
-
const decodedNormalized = decoded.replace(/\\/g, "/");
|
|
170
|
-
if (!decodedNormalized.startsWith("/") || decodedNormalized.startsWith("//")) return "/";
|
|
171
|
-
return next;
|
|
172
|
-
}
|
|
123
|
+
export { safeNext } from "./safeNext.js";
|
|
173
124
|
|
|
174
125
|
/**
|
|
175
126
|
* The address being signed in, carried between the login steps. It rides an HttpOnly
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The post-sign-in redirect guard, in a module with no runtime imports so every
|
|
3
|
+
* layer that builds a sign-in location (including the public render chain, which may
|
|
4
|
+
* not reach the D1 accessor that `route.ts` imports) uses this one copy.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** True if `s` contains any C0 control char (0x00–0x1F) or DEL (0x7F) — CR/LF
|
|
8
|
+
* included, so a `next` value can never smuggle a header break or NUL. Written as
|
|
9
|
+
* a charCode scan (not a control-char regex literal) so the source stays printable. */
|
|
10
|
+
function hasControlChar(s: string): boolean {
|
|
11
|
+
for (let i = 0; i < s.length; i++) {
|
|
12
|
+
const c = s.charCodeAt(i);
|
|
13
|
+
if (c <= 0x1f || c === 0x7f) return true;
|
|
14
|
+
}
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Sanitize a post-sign-in `next`/returnTo redirect target to a same-origin,
|
|
20
|
+
* path-only reference — the single open-redirect chokepoint for the whole sign-in
|
|
21
|
+
* surface (the login gate, verify, and the shared `pr/<N>` reviewer link all funnel
|
|
22
|
+
* through here). Anything that could resolve off-origin falls back to "/".
|
|
23
|
+
*
|
|
24
|
+
* Rejected, because a browser would treat each as an ABSOLUTE/off-origin URL:
|
|
25
|
+
* - a scheme or bare host ("https://evil.com", "evil.com")
|
|
26
|
+
* - protocol-relative ("//evil.com")
|
|
27
|
+
* - backslash-smuggled ("/\evil.com", "\\evil.com") — browsers normalize
|
|
28
|
+
* "\" → "/", so "/\evil.com" resolves as "//evil.com"
|
|
29
|
+
* - encoded slash/backslash ("/%2F%2Fevil.com", "/%5Cevil.com") that DECODES
|
|
30
|
+
* to a protocol-relative form
|
|
31
|
+
* - control chars / newlines (header-injection belt-and-suspenders)
|
|
32
|
+
* - malformed percent-encoding (refuse rather than guess)
|
|
33
|
+
*
|
|
34
|
+
* The ORIGINAL (still-encoded) value is returned on success — decoding is only for
|
|
35
|
+
* the safety check, never for the redirect target.
|
|
36
|
+
*/
|
|
37
|
+
export function safeNext(next: string | null | undefined): string {
|
|
38
|
+
if (!next) return "/";
|
|
39
|
+
if (!next.startsWith("/")) return "/";
|
|
40
|
+
// No control chars / CR / LF anywhere (header-injection belt-and-suspenders).
|
|
41
|
+
if (hasControlChar(next)) return "/";
|
|
42
|
+
// Normalize backslashes to slashes the way a browser would, then reject any
|
|
43
|
+
// protocol-relative ("//host") form — raw or backslash-smuggled.
|
|
44
|
+
if (next.replace(/\\/g, "/").startsWith("//")) return "/";
|
|
45
|
+
// Defeat encoded slash/backslash smuggling: decode once and re-check that it is
|
|
46
|
+
// still a single-slash, same-origin path. Malformed encoding → refuse.
|
|
47
|
+
let decoded: string;
|
|
48
|
+
try {
|
|
49
|
+
decoded = decodeURIComponent(next);
|
|
50
|
+
} catch {
|
|
51
|
+
return "/";
|
|
52
|
+
}
|
|
53
|
+
const decodedNormalized = decoded.replace(/\\/g, "/");
|
|
54
|
+
if (!decodedNormalized.startsWith("/") || decodedNormalized.startsWith("//")) return "/";
|
|
55
|
+
return next;
|
|
56
|
+
}
|
|
@@ -12,7 +12,7 @@ import { readEnv, readD1, readKv } from "@/lib/publication/shared/env";
|
|
|
12
12
|
import { fromD1, type D1Like } from "@/lib/catalog/d1/catalog";
|
|
13
13
|
import { readCurrentTenantConsentConfig } from "@/lib/measurement/consent/consentConfigRead";
|
|
14
14
|
import { loadActiveManagedInstallDeclarations } from "@/lib/integrations/integration/managedInstallDeclarations";
|
|
15
|
-
import { buildTenantConsentBroker, commerceTenantId,
|
|
15
|
+
import { buildTenantConsentBroker, commerceTenantId, previewContextRefusalResponse, storefrontModeRequiresSignIn } from "@tot/public-runtime";
|
|
16
16
|
import { MIRROR_LOCATION_UNSPECIFIED, readMirrorBalances as readLedgerBalances } from "@/lib/inventory/mirrorStock";
|
|
17
17
|
import { tenantIsDeclaredPublic } from "@/config/tenants";
|
|
18
18
|
import type {
|
|
@@ -29,6 +29,8 @@ import {
|
|
|
29
29
|
isAuthPath,
|
|
30
30
|
isAdminPath,
|
|
31
31
|
isSignInRedirectPath,
|
|
32
|
+
safeLoginHref,
|
|
33
|
+
safeReturnPathname,
|
|
32
34
|
sessionAdmitsHost,
|
|
33
35
|
sessionHostCapability,
|
|
34
36
|
type GateMode,
|
|
@@ -39,6 +41,7 @@ import { gatedApiResponse, gatedHoldingResponse } from "@/lib/access/auth/gatePa
|
|
|
39
41
|
import { readSession, KvSessionStore, SESSION_COOKIE } from "@/lib/access/auth/session";
|
|
40
42
|
import { runRenderChain } from "./renderChain.js";
|
|
41
43
|
import { resolveCandidateContentPin } from "./candidatePin.js";
|
|
44
|
+
import { resolveRequestPreviewContext } from "./previewContext.js";
|
|
42
45
|
import { timed } from "@/lib/observability/shared/serverTiming";
|
|
43
46
|
import type { InternalContentGrant } from "@/lib/access/auth/internalContentAuthority";
|
|
44
47
|
|
|
@@ -68,6 +71,20 @@ export interface ControlPlaneInput {
|
|
|
68
71
|
export async function serveControlPlane(input: ControlPlaneInput): Promise<Response> {
|
|
69
72
|
const { context, next, host, url, tenant, basePath, renderPath, cache, kv } = input;
|
|
70
73
|
const { request, locals } = context;
|
|
74
|
+
// A presented preview context verifies before the gate, the admin landing, the
|
|
75
|
+
// /dev redirect, or the render chain, or the request is refused here.
|
|
76
|
+
const preview = await resolveRequestPreviewContext({
|
|
77
|
+
url,
|
|
78
|
+
request,
|
|
79
|
+
cookies: context.cookies,
|
|
80
|
+
renderPath,
|
|
81
|
+
tenantId: tenant.tenant_id,
|
|
82
|
+
secret: await readEnv("CUSTOMIZATION_PREVIEW_SECRET"),
|
|
83
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
84
|
+
});
|
|
85
|
+
if (preview.context.status === "refused") {
|
|
86
|
+
return previewContextRefusalResponse(preview.context.httpStatus);
|
|
87
|
+
}
|
|
71
88
|
// A pinned route rewrite arrives here without the outer preview route's
|
|
72
89
|
// session. Verify its tenant-bound grant before the host login gate runs.
|
|
73
90
|
const candidatePin = input.hostLoginGated
|
|
@@ -115,30 +132,13 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
|
|
|
115
132
|
const qaBypass =
|
|
116
133
|
!!bypassToken && request.headers.get("x-demo-gate-bypass") === bypassToken;
|
|
117
134
|
|
|
118
|
-
// Customization-preview admission, available to EVERY tenant:
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
//
|
|
124
|
-
|
|
125
|
-
// and an absent CUSTOMIZATION_PREVIEW_SECRET leaves it false (fail-closed).
|
|
126
|
-
// The admin/cockpit/api exclusion is enforced in evaluateLoginGate.
|
|
127
|
-
const gatePreviewSecret = await readEnv("CUSTOMIZATION_PREVIEW_SECRET");
|
|
128
|
-
const gatePreviewToken =
|
|
129
|
-
url.searchParams.get("__preview") ??
|
|
130
|
-
context.cookies.get("tot_preview")?.value ??
|
|
131
|
-
null;
|
|
132
|
-
let previewTokenValid = false;
|
|
133
|
-
if (gatePreviewSecret && gatePreviewToken) {
|
|
134
|
-
const verifiedPreview = await verifyPreviewToken(
|
|
135
|
-
gatePreviewSecret,
|
|
136
|
-
gatePreviewToken,
|
|
137
|
-
nowSeconds,
|
|
138
|
-
);
|
|
139
|
-
previewTokenValid =
|
|
140
|
-
verifiedPreview.ok && verifiedPreview.claims.tenantId === tenant.tenant_id;
|
|
141
|
-
}
|
|
135
|
+
// Customization-preview admission, available to EVERY tenant: the strictly
|
|
136
|
+
// verified preview context above (one signed, unexpired, tenant-bound token)
|
|
137
|
+
// admits the viewer to that tenant's public content, and lets the fulfillment
|
|
138
|
+
// app's preview bootstrap pairs reach their own authorizers. An absent
|
|
139
|
+
// CUSTOMIZATION_PREVIEW_SECRET never yields a valid context (fail-closed). The
|
|
140
|
+
// admin/cockpit/api exclusion is enforced in evaluateLoginGate.
|
|
141
|
+
const previewTokenValid = preview.context.status === "valid";
|
|
142
142
|
|
|
143
143
|
// Canonical admin tenant landing: an AUTHENTICATED viewer who is not a
|
|
144
144
|
// member/staff of THIS host's tenant must be routed to their OWN tenant
|
|
@@ -181,6 +181,9 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
|
|
|
181
181
|
qaBypass,
|
|
182
182
|
previewTokenValid,
|
|
183
183
|
candidatePinValid: !!candidatePin,
|
|
184
|
+
method: request.method,
|
|
185
|
+
// The publication render path, never the raw request path.
|
|
186
|
+
renderPath,
|
|
184
187
|
});
|
|
185
188
|
if (decision.action === "redirect") {
|
|
186
189
|
// Admin and the cockpit hard-redirect to sign-in rather than rendering the
|
|
@@ -193,7 +196,7 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
|
|
|
193
196
|
// already carries `?next=` so the visitor returns to exactly where they were
|
|
194
197
|
// headed.
|
|
195
198
|
if (isSignInRedirectPath(url.pathname)) {
|
|
196
|
-
return context.redirect(decision.location, 303);
|
|
199
|
+
return context.redirect(safeLoginHref(decision.location), 303);
|
|
197
200
|
}
|
|
198
201
|
// An API caller gets an honest 401, never a 200 page it would read as success.
|
|
199
202
|
const gateReason = storefrontModeRequiresSignIn(tenant.storefront?.mode)
|
|
@@ -241,12 +244,12 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
|
|
|
241
244
|
}
|
|
242
245
|
}
|
|
243
246
|
|
|
244
|
-
// /dev
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
+
// /dev is the old name of /cockpit. 302-redirect any /dev link — host-routed (/dev)
|
|
248
|
+
// or path-routed (/<vendor>/dev) — to the cockpit, keeping the tenant prefix. The
|
|
249
|
+
// target is a sanitized pathname: the request query never reaches the Location.
|
|
247
250
|
if (renderPath === "/dev" || renderPath.startsWith("/dev/")) {
|
|
248
251
|
const rest = renderPath.slice("/dev".length); // "" or "/sub…"
|
|
249
|
-
return Response.redirect(`${url.origin}${basePath}/cockpit${rest}
|
|
252
|
+
return Response.redirect(`${url.origin}${safeReturnPathname(`${basePath}/cockpit${rest}`)}`, 302);
|
|
250
253
|
}
|
|
251
254
|
|
|
252
255
|
// Active managed installs share the same declaration/resolver/CSP/broker/cache
|
|
@@ -35,6 +35,7 @@ import { applySecurityHeaders } from "@/lib/access/shared/securityHeaders";
|
|
|
35
35
|
import { visitorRegionFor, withVisitorRegionCookie } from "@/lib/compliance/shared/visitorRegionCookie";
|
|
36
36
|
import { tryServeStaticBundle } from "./staticBundle.js";
|
|
37
37
|
import { resolveCandidateContentPin } from "./candidatePin.js";
|
|
38
|
+
import { resolveRequestPreviewContext } from "./previewContext.js";
|
|
38
39
|
import { parseGateMode } from "@/lib/access/auth/loginGate";
|
|
39
40
|
import { evaluateDemoGate, hostInGateList } from "@/lib/access/shared/demoGate";
|
|
40
41
|
import { isMaintenanceOn, maintenanceResponse } from "@/lib/access/shared/maintenance";
|
|
@@ -311,17 +312,30 @@ async function serveRequest(
|
|
|
311
312
|
// document markup, never asset bytes, so this stays a D1-free path.
|
|
312
313
|
if (branch === "static-passthrough") {
|
|
313
314
|
const candidatePin = await resolveCandidateContentPin(url, tenant.tenant_id);
|
|
315
|
+
// Platform bytes never refuse, but only a strictly verified preview token selects
|
|
316
|
+
// a preview revision or environment.
|
|
317
|
+
const previewSecret = await readEnv("CUSTOMIZATION_PREVIEW_SECRET");
|
|
318
|
+
const preview = await resolveRequestPreviewContext({
|
|
319
|
+
url,
|
|
320
|
+
request,
|
|
321
|
+
cookies: context.cookies,
|
|
322
|
+
renderPath: publicationRenderPath,
|
|
323
|
+
tenantId: tenant.tenant_id,
|
|
324
|
+
secret: previewSecret,
|
|
325
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
326
|
+
});
|
|
327
|
+
const verifiedPreview = preview.context.status === "valid" ? preview.context : null;
|
|
314
328
|
const { resolvePreviewVersionFromCookies } = await import("@/lib/assets/preview-version-cookie");
|
|
315
329
|
const cookieRevision = await resolvePreviewVersionFromCookies({
|
|
316
330
|
tenantId: tenant.tenant_id,
|
|
317
331
|
previewVersionCookie: context.cookies.get("tot_preview_version")?.value,
|
|
318
|
-
previewTokenCookie:
|
|
319
|
-
secret:
|
|
332
|
+
previewTokenCookie: verifiedPreview ? preview.cookieValue ?? undefined : undefined,
|
|
333
|
+
secret: previewSecret,
|
|
320
334
|
});
|
|
321
335
|
const captureEnvironment = await resolveCustomizationEnv({
|
|
322
336
|
isPreviewHost: host.toLowerCase().startsWith("preview."), tenantId: tenant.tenant_id,
|
|
323
|
-
token:
|
|
324
|
-
secret:
|
|
337
|
+
token: verifiedPreview?.token,
|
|
338
|
+
secret: previewSecret, pathname: url.pathname,
|
|
325
339
|
nowSeconds: Math.floor(Date.now() / 1000),
|
|
326
340
|
});
|
|
327
341
|
const capturedRevisionId = renderPath.startsWith("/_a/") && !captureEnvironment.reject
|
|
@@ -340,8 +354,7 @@ async function serveRequest(
|
|
|
340
354
|
cache,
|
|
341
355
|
kv,
|
|
342
356
|
isPreviewHost: host.toLowerCase().startsWith("preview."),
|
|
343
|
-
hasPreviewToken:
|
|
344
|
-
url.searchParams.has("__preview") || !!context.cookies.get("tot_preview")?.value,
|
|
357
|
+
hasPreviewToken: preview.presented,
|
|
345
358
|
hasCandidatePin: !!candidatePin,
|
|
346
359
|
hasDraftCookie: !!context.cookies.get(DEV_DRAFT_COOKIE)?.value,
|
|
347
360
|
hasManagedInstalls: false,
|
|
@@ -380,9 +393,20 @@ async function serveRequest(
|
|
|
380
393
|
const publicationSourcePath = discoveryRoot?.action === "render" ? "/" : renderPath;
|
|
381
394
|
|
|
382
395
|
if (branch === "public-render") {
|
|
396
|
+
// Only a strictly verified token selects the preview mirror stage; a presented
|
|
397
|
+
// but invalid context is refused by the render chain.
|
|
398
|
+
const preview = await resolveRequestPreviewContext({
|
|
399
|
+
url,
|
|
400
|
+
request,
|
|
401
|
+
cookies: context.cookies,
|
|
402
|
+
renderPath: publicationRenderPath,
|
|
403
|
+
tenantId: tenant.tenant_id,
|
|
404
|
+
secret: await readEnv("CUSTOMIZATION_PREVIEW_SECRET"),
|
|
405
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
406
|
+
});
|
|
383
407
|
const mirrorStage = publicMirrorStage({
|
|
384
408
|
previewHost: host.toLowerCase().startsWith("preview."),
|
|
385
|
-
previewToken:
|
|
409
|
+
previewToken: preview.context.status === "valid",
|
|
386
410
|
});
|
|
387
411
|
let mirrorBalances: ReturnType<typeof parseMirrorBalances> = null;
|
|
388
412
|
if (kv) {
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one strict read of a request's preview context (`__preview` query values and
|
|
3
|
+
* `tot_preview` cookies), shared by every middleware layer that consults it: the
|
|
4
|
+
* front door's static passthrough and mirror stage, the control-plane gate, and the
|
|
5
|
+
* render chain. A presented context is verified by `requireValidPreviewToken` and
|
|
6
|
+
* never degrades to "absent"; the control plane and the render chain refuse it with
|
|
7
|
+
* `previewContextRefusalResponse` before any publication, page-cache, rewrite-target
|
|
8
|
+
* or source resolution.
|
|
9
|
+
*
|
|
10
|
+
* Two paths read a refused context as absent instead: the preview token dispenser
|
|
11
|
+
* (`isPreviewDispatcherPath`, the page that hands out a fresh token) and the sign-in
|
|
12
|
+
* surface (`isAuthPath`). Refusing there would lock a viewer holding a stale or
|
|
13
|
+
* foreign cookie out of the only routes that can replace it, and neither renders
|
|
14
|
+
* preview content.
|
|
15
|
+
*/
|
|
16
|
+
import type { AstroCookies } from "astro";
|
|
17
|
+
import {
|
|
18
|
+
PREVIEW_COOKIE,
|
|
19
|
+
PREVIEW_QUERY_PARAM,
|
|
20
|
+
isPreviewDispatcherPath,
|
|
21
|
+
previewCookieValues,
|
|
22
|
+
requireValidPreviewToken,
|
|
23
|
+
type PreviewContext,
|
|
24
|
+
} from "@tot/public-runtime";
|
|
25
|
+
import { isAuthPath } from "@/lib/access/auth/loginGate";
|
|
26
|
+
|
|
27
|
+
export interface RequestPreviewContextInput {
|
|
28
|
+
url: URL;
|
|
29
|
+
request: Request;
|
|
30
|
+
cookies: Pick<AstroCookies, "get">;
|
|
31
|
+
/** Tenant-relative render path. */
|
|
32
|
+
renderPath: string;
|
|
33
|
+
tenantId: string;
|
|
34
|
+
secret: string | null | undefined;
|
|
35
|
+
nowSeconds: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface RequestPreviewContext {
|
|
39
|
+
context: PreviewContext;
|
|
40
|
+
/** True when any `__preview` value or `tot_preview` cookie was presented. */
|
|
41
|
+
presented: boolean;
|
|
42
|
+
/** The single `tot_preview` cookie value, when there is exactly one. */
|
|
43
|
+
cookieValue: string | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function resolveRequestPreviewContext(
|
|
47
|
+
input: RequestPreviewContextInput,
|
|
48
|
+
): Promise<RequestPreviewContext> {
|
|
49
|
+
const queryValues = input.url.searchParams.getAll(PREVIEW_QUERY_PARAM);
|
|
50
|
+
// The raw header sees a second, conflicting cookie the jar collapses. With one or
|
|
51
|
+
// none, the jar's value wins, so a cookie this request already replaced is read.
|
|
52
|
+
const raw = previewCookieValues(input.request.headers.get("cookie"));
|
|
53
|
+
const jar = input.cookies.get(PREVIEW_COOKIE)?.value;
|
|
54
|
+
const cookieValues = raw.length > 1 ? raw : jar !== undefined ? [jar] : raw;
|
|
55
|
+
const presented = queryValues.length > 0 || cookieValues.length > 0;
|
|
56
|
+
const cookieValue = cookieValues.length === 1 ? cookieValues[0]! : null;
|
|
57
|
+
const context = await requireValidPreviewToken({
|
|
58
|
+
queryValues,
|
|
59
|
+
cookieValues,
|
|
60
|
+
tenantId: input.tenantId,
|
|
61
|
+
secret: input.secret,
|
|
62
|
+
nowSeconds: input.nowSeconds,
|
|
63
|
+
});
|
|
64
|
+
if (
|
|
65
|
+
context.status === "refused" &&
|
|
66
|
+
(isPreviewDispatcherPath(input.url.pathname) || isAuthPath(input.renderPath))
|
|
67
|
+
) {
|
|
68
|
+
return { context: { status: "absent" }, presented, cookieValue: null };
|
|
69
|
+
}
|
|
70
|
+
return { context, presented, cookieValue };
|
|
71
|
+
}
|
|
@@ -71,8 +71,10 @@ import {
|
|
|
71
71
|
MATERIALIZE_MODE_BINDING,
|
|
72
72
|
verifyConsentSnapshotSig,
|
|
73
73
|
resolveNativeGa4SandboxUrl,
|
|
74
|
-
|
|
74
|
+
previewContextRefusalResponse,
|
|
75
75
|
} from "@tot/public-runtime";
|
|
76
|
+
import { resolveRequestPreviewContext } from "./previewContext.js";
|
|
77
|
+
import { safeReturnPathname } from "@/lib/access/auth/loginGate";
|
|
76
78
|
import { readBakedManagedInstalls } from "@/lib/integrations/integration/bakedManagedInstalls";
|
|
77
79
|
import { readWithImagePreviewRewriteOverlay } from "@tot/public-runtime/image-preview-rewrite-overlay";
|
|
78
80
|
import { publicationRecoveryActiveV1, publicationRecoveryKeyV1 } from "@tot/public-runtime/publication-recovery";
|
|
@@ -202,9 +204,29 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
202
204
|
|
|
203
205
|
// Preview/test detection (also reused for the customization env below). A
|
|
204
206
|
// production read is one with no preview host, query token, or preview cookie.
|
|
207
|
+
// A presented preview context must verify before anything below reads a
|
|
208
|
+
// publication source, the page cache, or builds a rewrite target; otherwise the
|
|
209
|
+
// request is refused, never served as publication.
|
|
205
210
|
const isPreviewHost = host.toLowerCase().startsWith("preview.");
|
|
206
|
-
const
|
|
207
|
-
const
|
|
211
|
+
const previewSecret = (await readEnv("CUSTOMIZATION_PREVIEW_SECRET")) ?? null;
|
|
212
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
213
|
+
const preview = await resolveRequestPreviewContext({
|
|
214
|
+
url,
|
|
215
|
+
request,
|
|
216
|
+
cookies: context.cookies,
|
|
217
|
+
renderPath,
|
|
218
|
+
tenantId: tenantRecord.tenant_id,
|
|
219
|
+
secret: previewSecret,
|
|
220
|
+
nowSeconds,
|
|
221
|
+
});
|
|
222
|
+
if (preview.context.status === "refused") {
|
|
223
|
+
return previewContextRefusalResponse(preview.context.httpStatus);
|
|
224
|
+
}
|
|
225
|
+
const verifiedPreview = preview.context.status === "valid" ? preview.context : null;
|
|
226
|
+
const queryToken = verifiedPreview?.source === "query" ? verifiedPreview.token : null;
|
|
227
|
+
// The cookie itself, when the context verified: the revision cookie below checks
|
|
228
|
+
// its own binding against it.
|
|
229
|
+
const cookieToken = verifiedPreview ? preview.cookieValue : null;
|
|
208
230
|
|
|
209
231
|
// Candidate-render CONTENT PIN (`__tot_candidate_pin`): a signed, tenant- and
|
|
210
232
|
// expiry-bound token minted ONLY by the control-plane candidate/revision
|
|
@@ -229,9 +251,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
229
251
|
// Resolve preview/live once before any publication source, static-bundle, or
|
|
230
252
|
// page-cache read. An exact publication selection is therefore authoritative
|
|
231
253
|
// for the whole request and can scope every downstream cache decision.
|
|
232
|
-
const previewToken =
|
|
233
|
-
const previewSecret = (await readEnv("CUSTOMIZATION_PREVIEW_SECRET")) ?? null;
|
|
234
|
-
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
254
|
+
const previewToken = verifiedPreview?.token ?? null;
|
|
235
255
|
const customization = await resolveCustomizationEnv({
|
|
236
256
|
isPreviewHost,
|
|
237
257
|
tenantId: tenantRecord.tenant_id,
|
|
@@ -273,20 +293,15 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
273
293
|
if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
|
|
274
294
|
return response;
|
|
275
295
|
}
|
|
276
|
-
// The owning space's content-declared redirects answer before anything renders
|
|
277
|
-
//
|
|
278
|
-
//
|
|
279
|
-
// A pinned render (staged/candidate revision) redirects
|
|
280
|
-
//
|
|
296
|
+
// The owning space's content-declared redirects answer before anything renders: a same-origin
|
|
297
|
+
// target keeps the path-routing prefix and goes through the shared return-path sanitizer, so no
|
|
298
|
+
// request query (a preview capability, a pin token) reaches the Location; an off-site target (the
|
|
299
|
+
// root space only) is sent as declared. A pinned render (staged/candidate revision) redirects
|
|
300
|
+
// inside the revision it reviews.
|
|
281
301
|
const declaredRedirectHeaders = (location: string): HeadersInit => {
|
|
282
302
|
if (!location.startsWith("/")) return { location };
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const query = new URLSearchParams(url.search);
|
|
286
|
-
query.delete(CANDIDATE_CONTENT_PIN_PARAM);
|
|
287
|
-
search = query.toString() ? `?${query.toString()}` : "";
|
|
288
|
-
}
|
|
289
|
-
return { location: `${url.origin}${candidatePin ? candidatePin.basePath : basePath}${location}${search}` };
|
|
303
|
+
const prefix = candidatePin ? candidatePin.basePath : basePath;
|
|
304
|
+
return { location: `${url.origin}${safeReturnPathname(`${prefix}${location}`)}` };
|
|
290
305
|
};
|
|
291
306
|
if (publicationSource.status === "selected") {
|
|
292
307
|
const location = publicationContentRedirectLocationV1(publicationSource.artifact, input.publicationRequestPath);
|
|
@@ -416,7 +431,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
416
431
|
cache,
|
|
417
432
|
kv,
|
|
418
433
|
isPreviewHost,
|
|
419
|
-
hasPreviewToken:
|
|
434
|
+
hasPreviewToken: preview.presented,
|
|
420
435
|
hasCandidatePin: !!candidatePin,
|
|
421
436
|
hasDraftCookie: !!draftCookie,
|
|
422
437
|
hasManagedInstalls: managedIntegrationDeclarations.length > 0,
|
|
@@ -543,8 +558,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
543
558
|
!import.meta.env.DEV &&
|
|
544
559
|
request.method.toUpperCase() === "GET" &&
|
|
545
560
|
!isPreviewHost &&
|
|
546
|
-
!
|
|
547
|
-
!cookieToken &&
|
|
561
|
+
!preview.presented &&
|
|
548
562
|
!candidatePin &&
|
|
549
563
|
!draftCookie &&
|
|
550
564
|
!isInternalPublication &&
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.7.0",
|
|
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",
|
|
@@ -231,6 +231,120 @@ export async function verifyContentPinToken(
|
|
|
231
231
|
return { ok: true, claims };
|
|
232
232
|
}
|
|
233
233
|
|
|
234
|
+
/** Query parameter that presents a preview capability. */
|
|
235
|
+
export const PREVIEW_QUERY_PARAM = "__preview";
|
|
236
|
+
/** Cookie a verified query capability persists as. */
|
|
237
|
+
export const PREVIEW_COOKIE = "tot_preview";
|
|
238
|
+
/**
|
|
239
|
+
* The stable code every preview-context refusal carries. A client recognises it and
|
|
240
|
+
* never retries the request into publication or another stage.
|
|
241
|
+
*/
|
|
242
|
+
export const PREVIEW_CONTEXT_REFUSED = "preview_context_refused";
|
|
243
|
+
|
|
244
|
+
export type PreviewContextRefusalReason =
|
|
245
|
+
| "empty"
|
|
246
|
+
| "duplicate"
|
|
247
|
+
| "ambiguous"
|
|
248
|
+
| "malformed"
|
|
249
|
+
| "bad-signature"
|
|
250
|
+
| "expired"
|
|
251
|
+
| "wrong-tenant"
|
|
252
|
+
| "unavailable";
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* The preview context a request presents.
|
|
256
|
+
* - `absent`: no `__preview` parameter and no `tot_preview` cookie.
|
|
257
|
+
* - `valid`: exactly one token, signature, expiry and tenant verified.
|
|
258
|
+
* - `refused`: anything else. A presented context never degrades to absent.
|
|
259
|
+
*/
|
|
260
|
+
export type PreviewContext =
|
|
261
|
+
| { status: "absent" }
|
|
262
|
+
| { status: "valid"; token: string; source: "query" | "cookie" }
|
|
263
|
+
| { status: "refused"; httpStatus: 401 | 403 | 503; reason: PreviewContextRefusalReason };
|
|
264
|
+
|
|
265
|
+
export interface PreviewContextInput {
|
|
266
|
+
/** Every `__preview` value in the query, in order (`URLSearchParams.getAll`). */
|
|
267
|
+
queryValues: readonly string[];
|
|
268
|
+
/** Every `tot_preview` value in the Cookie header (see {@link previewCookieValues}). */
|
|
269
|
+
cookieValues: readonly string[];
|
|
270
|
+
/** The tenant resolved for this request. */
|
|
271
|
+
tenantId: string;
|
|
272
|
+
/** Platform preview-signing secret; absent means the verifier is unavailable. */
|
|
273
|
+
secret: string | null | undefined;
|
|
274
|
+
nowSeconds: number;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Every `tot_preview` value in a raw Cookie header. A runtime cookie jar keeps one
|
|
279
|
+
* value per name, so it cannot see a second, conflicting cookie; this can.
|
|
280
|
+
*/
|
|
281
|
+
export function previewCookieValues(cookieHeader: string | null | undefined): string[] {
|
|
282
|
+
const values: string[] = [];
|
|
283
|
+
for (const part of (cookieHeader ?? "").split(";")) {
|
|
284
|
+
const eq = part.indexOf("=");
|
|
285
|
+
if (eq < 0 || part.slice(0, eq).trim() !== PREVIEW_COOKIE) continue;
|
|
286
|
+
const raw = part.slice(eq + 1).trim();
|
|
287
|
+
try {
|
|
288
|
+
values.push(decodeURIComponent(raw));
|
|
289
|
+
} catch {
|
|
290
|
+
values.push(raw);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return values;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Strict, single-value verification of a presented preview context. The query
|
|
298
|
+
* takes precedence over the cookie, but an empty query beside a cookie is
|
|
299
|
+
* ambiguous rather than absent.
|
|
300
|
+
*
|
|
301
|
+
* Status pin (deliberate): structural and signature failures are 401, an expired or
|
|
302
|
+
* wrong-tenant token is 403 (a real capability, refused for this request), and only
|
|
303
|
+
* an unavailable verifier is 503.
|
|
304
|
+
*/
|
|
305
|
+
export async function requireValidPreviewToken(input: PreviewContextInput): Promise<PreviewContext> {
|
|
306
|
+
const { queryValues, cookieValues } = input;
|
|
307
|
+
if (queryValues.length === 0 && cookieValues.length === 0) return { status: "absent" };
|
|
308
|
+
if (queryValues.length > 1 || cookieValues.length > 1) {
|
|
309
|
+
return { status: "refused", httpStatus: 401, reason: "duplicate" };
|
|
310
|
+
}
|
|
311
|
+
const source: "query" | "cookie" = queryValues.length === 1 ? "query" : "cookie";
|
|
312
|
+
const token = source === "query" ? queryValues[0]! : cookieValues[0]!;
|
|
313
|
+
if (token.trim() === "") {
|
|
314
|
+
const reason = source === "query" && cookieValues.length > 0 ? "ambiguous" : "empty";
|
|
315
|
+
return { status: "refused", httpStatus: 401, reason };
|
|
316
|
+
}
|
|
317
|
+
if (!input.secret) return { status: "refused", httpStatus: 503, reason: "unavailable" };
|
|
318
|
+
const verified = await verifyPreviewToken(input.secret, token, input.nowSeconds);
|
|
319
|
+
if (!verified.ok) {
|
|
320
|
+
return verified.reason === "expired"
|
|
321
|
+
? { status: "refused", httpStatus: 403, reason: "expired" }
|
|
322
|
+
: { status: "refused", httpStatus: 401, reason: verified.reason };
|
|
323
|
+
}
|
|
324
|
+
if (verified.claims.tenantId !== input.tenantId) {
|
|
325
|
+
return { status: "refused", httpStatus: 403, reason: "wrong-tenant" };
|
|
326
|
+
}
|
|
327
|
+
return { status: "valid", token, source };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The one refusal for a presented preview context: fixed, no-store JSON carrying
|
|
332
|
+
* {@link PREVIEW_CONTEXT_REFUSED} and nothing derived from the request.
|
|
333
|
+
*/
|
|
334
|
+
export function previewContextRefusalResponse(status: 401 | 403 | 503): Response {
|
|
335
|
+
return new Response(
|
|
336
|
+
JSON.stringify({ ok: false, error: PREVIEW_CONTEXT_REFUSED, code: PREVIEW_CONTEXT_REFUSED }),
|
|
337
|
+
{
|
|
338
|
+
status,
|
|
339
|
+
headers: {
|
|
340
|
+
"content-type": "application/json; charset=utf-8",
|
|
341
|
+
"cache-control": "no-store",
|
|
342
|
+
"x-robots-tag": "noindex, nofollow",
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
234
348
|
export type CustomizationEnv = "live" | "test";
|
|
235
349
|
|
|
236
350
|
export interface EnvResolutionInput {
|