@tokenoftrust/storefront-runner 7.6.19 → 7.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.
@@ -42,26 +42,27 @@ const cliInstallSpec = cliVersion ? `@tokenoftrust/cli@${cliVersion}` : "@tokeno
42
42
 
43
43
  // The commit THIS build was cut from, baked in at BUILD time so /health can report
44
44
  // exactly which code is live (see src/lib/observability/shared/health.ts + src/middleware). Prefer a CI-
45
- // provided SHA (Workers Builds / GitHub Actions / CF Pages) so the value is right even
46
- // when the build runs from a shallow/detached checkout; fall back to `git rev-parse`
47
- // for local deploys. deploy.sh's source guard pins HEAD to origin/<deploySourceBranch>,
48
- // so on a clean deploy this SHA equals the pushed umbrella tip. Never throws — a build
49
- // with no git context reports "unknown" rather than failing.
45
+ // Resolve the build's commit SHA: explicit GIT_SHA override first, then the actual
46
+ // checked-out git HEAD (works on shallow, detached, fast-forwarded, and auto-bumped
47
+ // checkouts), falling back to CI trigger env vars only when `.git` is unavailable.
48
+ // Never throws — a build with no git context reports "unknown" rather than failing.
50
49
  const gitSha = (() => {
51
- const fromEnv =
52
- process.env.GIT_SHA ||
53
- process.env.WORKERS_CI_COMMIT_SHA ||
54
- process.env.CF_PAGES_COMMIT_SHA ||
55
- process.env.GITHUB_SHA;
56
- if (fromEnv) return fromEnv.trim();
50
+ if (process.env.GIT_SHA?.trim()) return process.env.GIT_SHA.trim();
57
51
  try {
58
- return execFileSync("git", ["rev-parse", "HEAD"], {
52
+ const head = execFileSync("git", ["rev-parse", "HEAD"], {
59
53
  cwd: fileURLToPath(new URL(".", import.meta.url)),
60
54
  encoding: "utf8",
61
55
  }).trim();
56
+ if (head) return head;
62
57
  } catch {
63
- return "unknown";
58
+ /* fall back to CI env when building outside a git checkout */
64
59
  }
60
+ const fromCiEnv =
61
+ process.env.WORKERS_CI_COMMIT_SHA ||
62
+ process.env.CF_PAGES_COMMIT_SHA ||
63
+ process.env.GITHUB_SHA;
64
+ if (fromCiEnv?.trim()) return fromCiEnv.trim();
65
+ return "unknown";
65
66
  })();
66
67
 
67
68
  import preact from "@astrojs/preact";
@@ -25,6 +25,8 @@ interface Props {
25
25
  const { section, index = 0 } = Astro.props;
26
26
  const { apiBasePath } = Astro.locals;
27
27
  const endpoint = withBase(apiBasePath ?? "", "/api/contact/bulk-quote");
28
+ // Rendered so the publish validator sees the page's dependency on the token route too.
29
+ const tokenEndpoint = withBase(apiBasePath ?? "", "/api/contact/token");
28
30
  const id = `bulk-quote-form-${index}`;
29
31
  const L = BULK_QUOTE_LIMITS;
30
32
  const declared: readonly string[] = Array.isArray(section.units) ? section.units : [];
@@ -37,6 +39,7 @@ const successMessage = section.successMessage ?? "Thanks. We received your quote
37
39
  class="bulk-quote"
38
40
  data-bulk-quote-form
39
41
  data-endpoint={endpoint}
42
+ data-token-endpoint={tokenEndpoint}
40
43
  data-success={successMessage}
41
44
  data-max-items={L.lineItems}
42
45
  aria-labelledby={section.heading ? `${id}-heading` : undefined}
@@ -225,6 +228,7 @@ const successMessage = section.successMessage ?? "Thanks. We received your quote
225
228
  too_large: "That request is too large. Shorten it and try again.",
226
229
  };
227
230
  const GENERIC = "Something went wrong. Your entries are still here; try again.";
231
+ const PREVIEW = "Quote requests are off in preview. Your request was checked but not sent.";
228
232
  const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
229
233
  type Control = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
230
234
 
@@ -236,7 +240,7 @@ const successMessage = section.successMessage ?? "Thanks. We received your quote
236
240
  const add = root.querySelector<HTMLButtonElement>("[data-bulk-quote-add]");
237
241
  const row = root.querySelector<HTMLTemplateElement>("[data-bulk-quote-row]");
238
242
  const endpoint = root.dataset.endpoint;
239
- if (!form || !status || !ref || !list || !add || !row || !endpoint) return;
243
+ if (!form || !status || !ref || !list || !add || !row || !endpoint || !root.dataset.tokenEndpoint) return;
240
244
  const maxItems = Number(root.dataset.maxItems) || 25;
241
245
  // The wire contract appends /api/contact/... itself; hand it the api base.
242
246
  const apiBase = endpoint.replace(/\/api\/contact\/bulk-quote$/, "");
@@ -367,6 +371,12 @@ const successMessage = section.successMessage ?? "Thanks. We received your quote
367
371
  ...optional("notes"),
368
372
  company: top("company")?.value ?? "",
369
373
  });
374
+ if (result.body.ok && "preview" in result.body) {
375
+ token = null;
376
+ say(PREVIEW, "ok");
377
+ loadToken().catch(() => {});
378
+ return;
379
+ }
370
380
  if (result.body.ok) {
371
381
  const quoteId = result.body.quoteId;
372
382
  form.reset();
@@ -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
  /**
@@ -301,7 +298,9 @@ export function isBypassPrivilegedPath(pathname: string): boolean {
301
298
  * tenant's own pages whose route has NO effect on a store that is not public. A
302
299
  * reviewer on a copy-preview link submits them and gets the route's own answer
303
300
  * instead of the holding page; the route reads `locals.storeNotPublic` and records
304
- * nothing (the footer/homepage newsletter form confirms "off in preview").
301
+ * nothing (the footer/homepage newsletter form confirms "off in preview", the bulk
302
+ * quote form answers `preview: true`). `/api/contact/token` only signs a submit token
303
+ * and writes nothing, so the bulk quote form can be exercised end to end in preview.
305
304
  *
306
305
  * The preview feedback bridge (`/api/preview/feedback` and its `/context` renewal) is the
307
306
  * one member with an effect: it forwards a reviewer's anonymous annotation to tot-mcp and
@@ -319,6 +318,8 @@ export function isBypassPrivilegedPath(pathname: string): boolean {
319
318
  * Exact paths, in BOTH addressing forms (the gate sees the PRE-STRIP path).
320
319
  */
321
320
  export const PREVIEW_VISITOR_API_PATHS = [
321
+ "/api/contact/bulk-quote",
322
+ "/api/contact/token",
322
323
  "/api/newsletter",
323
324
  "/api/preview/feedback",
324
325
  "/api/preview/feedback/context",
@@ -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
 
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * HOW IT GETS HERE. Workers have no filesystem/git at runtime, so the SHA is
11
11
  * baked in at BUILD time: astro.config.mjs's Vite `define` replaces the
12
- * `__GIT_SHA__` token with a string literal of the build's commit (CI-provided
13
- * `GIT_SHA`/`WORKERS_CI_COMMIT_SHA`/`GITHUB_SHA`, else local `git rev-parse`,
12
+ * `__GIT_SHA__` token with a string literal of the build's commit (`GIT_SHA`,
13
+ * else `git rev-parse HEAD`, else CI fallback `WORKERS_CI_COMMIT_SHA`/`GITHUB_SHA`,
14
14
  * else "unknown"). This is the SAME source /health already reports (lib/observability/shared/health.ts)
15
15
  * — we read it through the identical `typeof` guard so both agree by construction,
16
16
  * and so the value is safe under vitest (where the define isn't applied → "unknown").
@@ -471,6 +471,8 @@ export type BulkQuoteErrorCode =
471
471
 
472
472
  export type BulkQuoteSubmitResponse =
473
473
  | { ok: true; quoteId: string }
474
+ /** The store is not public (a preview): the request passed every check and nothing was stored. */
475
+ | { ok: true; preview: true }
474
476
  | { ok: false; error: BulkQuoteErrorCode; field?: BulkQuoteField; index?: number };
475
477
 
476
478
  export interface BulkQuoteClientResult {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.6.19",
3
+ "version": "7.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",
@@ -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
+ }