@agent-native/core 0.84.66 → 0.84.67

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.
@@ -1,5 +1,11 @@
1
1
  # @agent-native/core
2
2
 
3
+ ## 0.84.67
4
+
5
+ ### Patch Changes
6
+
7
+ - 171f6e6: Remove app document CSP headers so hosted Google Tag Manager and framework inline bootstrap scripts are not blocked or reported by a shared policy.
8
+
3
9
  ## 0.84.66
4
10
 
5
11
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.84.66",
3
+ "version": "0.84.67",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {
@@ -42,42 +42,9 @@ function getGaMeasurementId(): string | null {
42
42
  );
43
43
  }
44
44
 
45
- /**
46
- * Script hosts the injected GA loader pulls executable code from. Google Tag
47
- * Manager serves `gtag/js`, and GA4 can lazy-load additional collectors from
48
- * `www.google-analytics.com`. These must be listed in the document `script-src`
49
- * so the CSP reflects the code the framework itself injects (see
50
- * `applyDocumentCsp` in `ssr-handler.ts`).
51
- */
52
- export const GA_CSP_SCRIPT_HOSTS = [
53
- "https://www.googletagmanager.com",
54
- "https://www.google-analytics.com",
55
- ] as const;
56
-
57
- /**
58
- * Network/image hosts used by the GA4 loader when it sends page-view and event
59
- * beacons. These are separate from `script-src`: a stricter deployment CSP with
60
- * `connect-src 'self'` or `img-src 'self'` can load gtag.js but still drop all
61
- * analytics events unless these hosts are present too.
62
- */
63
- export const GA_CSP_CONNECT_HOSTS = [
64
- "https://www.google-analytics.com",
65
- "https://analytics.google.com",
66
- "https://stats.g.doubleclick.net",
67
- "https://region1.google-analytics.com",
68
- ] as const;
69
-
70
- export const GA_CSP_IMG_HOSTS = [
71
- "https://www.google-analytics.com",
72
- "https://www.googletagmanager.com",
73
- "https://stats.g.doubleclick.net",
74
- ] as const;
75
-
76
45
  /**
77
46
  * The exact JS body (no surrounding `<script>` tags) of the inline gtag config
78
- * block injected next to the gtag.js loader. Returned so the SSR handler can
79
- * hash it for the `script-src` CSP directive — the hash must be computed from
80
- * the identical string that `getGaScript()` embeds, so both call this helper.
47
+ * block injected next to the gtag.js loader.
81
48
  * Returns `null` when GA is not configured.
82
49
  */
83
50
  export function getGaInlineConfigScriptBody(): string | null {
@@ -30,18 +30,11 @@ import {
30
30
  AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,
31
31
  withAgentNativeSocialImageCacheBuster,
32
32
  } from "../shared/social-meta.js";
33
- import {
34
- GA_CSP_CONNECT_HOSTS,
35
- GA_CSP_IMG_HOSTS,
36
- GA_CSP_SCRIPT_HOSTS,
37
- getGaInlineConfigScriptBody,
38
- } from "./analytics.js";
39
33
  import {
40
34
  getAppBasePathFromViteEnv,
41
35
  stripAppBasePath as canonicalStripAppBasePath,
42
36
  } from "./app-base-path.js";
43
37
  import { runWithRequestContext } from "./request-context.js";
44
- import { computeInlineScriptHash } from "./security-headers.js";
45
38
  import { getSentryClientConfigScript } from "./sentry-config.js";
46
39
 
47
40
  export {
@@ -258,376 +251,17 @@ function applyDefaultSpeculationRulesHeader(
258
251
  }
259
252
 
260
253
  /**
261
- * Extract the plain JS body from a `<script ...>body</script>` string.
262
- * Returns `null` if the input is falsy or has no recognisable `</script>` end.
263
- * Used to compute the sha256 hash of framework-injected inline scripts so the
264
- * hash can be listed in app-owned `script-src` CSP directives.
265
- */
266
- function extractScriptBody(scriptTag: string | null): string | null {
267
- if (!scriptTag) return null;
268
- const start = scriptTag.indexOf(">") + 1;
269
- const end = scriptTag.lastIndexOf("</script>");
270
- if (start <= 0 || end < start) return null;
271
- return scriptTag.slice(start, end);
272
- }
273
-
274
- type CspDirective = {
275
- name: string;
276
- tokens: string[];
277
- };
278
-
279
- const CSP_DIRECTIVES_WITH_VALUE_TOKENS = new Set([
280
- "base-uri",
281
- "block-all-mixed-content",
282
- "child-src",
283
- "connect-src",
284
- "default-src",
285
- "fenced-frame-src",
286
- "font-src",
287
- "form-action",
288
- "frame-ancestors",
289
- "frame-src",
290
- "img-src",
291
- "manifest-src",
292
- "media-src",
293
- "navigate-to",
294
- "object-src",
295
- "plugin-types",
296
- "prefetch-src",
297
- "referrer",
298
- "reflected-xss",
299
- "require-sri-for",
300
- "require-trusted-types-for",
301
- "report-to",
302
- "report-uri",
303
- "sandbox",
304
- "script-src",
305
- "script-src-attr",
306
- "script-src-elem",
307
- "style-src",
308
- "style-src-attr",
309
- "style-src-elem",
310
- "trusted-types",
311
- "upgrade-insecure-requests",
312
- "webrtc",
313
- "worker-src",
314
- ]);
315
-
316
- function hasCommaJoinedCspPolicies(policy: string): boolean {
317
- let commaIndex = policy.indexOf(",");
318
- while (commaIndex !== -1) {
319
- const afterComma = policy.slice(commaIndex + 1);
320
- const directive = /^\s+([a-z][a-z0-9-]*)(?=\s|;|$)/i.exec(afterComma)?.[1];
321
- if (
322
- directive &&
323
- CSP_DIRECTIVES_WITH_VALUE_TOKENS.has(directive.toLowerCase())
324
- ) {
325
- return true;
326
- }
327
- commaIndex = policy.indexOf(",", commaIndex + 1);
328
- }
329
- return false;
330
- }
331
-
332
- function parseCsp(policy: string): CspDirective[] {
333
- return policy
334
- .split(";")
335
- .map((part) => part.trim())
336
- .filter(Boolean)
337
- .map((part) => {
338
- const [name = "", ...tokens] = part.split(/\s+/);
339
- return { name: name.toLowerCase(), tokens };
340
- })
341
- .filter((directive) => directive.name);
342
- }
343
-
344
- function serializeCsp(directives: CspDirective[]): string {
345
- return directives
346
- .map((directive) =>
347
- [directive.name, ...directive.tokens].filter(Boolean).join(" "),
348
- )
349
- .join("; ");
350
- }
351
-
352
- function appendCspTokens(
353
- tokens: string[],
354
- additions: readonly string[],
355
- ): string[] {
356
- if (!additions.length) return tokens;
357
- const next = tokens.filter((token) => token !== "'none'");
358
- const seen = new Set(next);
359
- for (const token of additions) {
360
- if (!token || seen.has(token)) continue;
361
- next.push(token);
362
- seen.add(token);
363
- }
364
- return next;
365
- }
366
-
367
- function findCspDirective(
368
- directives: CspDirective[],
369
- name: string,
370
- ): CspDirective | undefined {
371
- return directives.find((directive) => directive.name === name);
372
- }
373
-
374
- function appendToExistingOrDefaultCspDirective(
375
- directives: CspDirective[],
376
- name: string,
377
- additions: readonly string[],
378
- ): void {
379
- if (!additions.length) return;
380
- const existing = findCspDirective(directives, name);
381
- if (existing) {
382
- existing.tokens = appendCspTokens(existing.tokens, additions);
383
- return;
384
- }
385
-
386
- const defaultSrc = findCspDirective(directives, "default-src");
387
- if (!defaultSrc) return;
388
- directives.push({
389
- name,
390
- tokens: appendCspTokens([...defaultSrc.tokens], additions),
391
- });
392
- }
393
-
394
- function appendToExistingCspDirective(
395
- directives: CspDirective[],
396
- name: string,
397
- additions: readonly string[],
398
- ): void {
399
- const existing = findCspDirective(directives, name);
400
- if (!existing) return;
401
- existing.tokens = appendCspTokens(existing.tokens, additions);
402
- }
403
-
404
- function ensureCspDirective(
405
- directives: CspDirective[],
406
- name: string,
407
- tokens: readonly string[],
408
- ): void {
409
- if (findCspDirective(directives, name)) return;
410
- directives.push({ name, tokens: [...tokens] });
411
- }
412
-
413
- function hasStrictNonceScriptPolicy(tokens: readonly string[]): boolean {
414
- return tokens.some(
415
- (token) => token === "'strict-dynamic'" || token.startsWith("'nonce-"),
416
- );
417
- }
418
-
419
- function appendToScriptCspDirective(
420
- directives: CspDirective[],
421
- name: string,
422
- additions: readonly string[],
423
- ): boolean {
424
- const existing = findCspDirective(directives, name);
425
- if (existing) {
426
- if (hasStrictNonceScriptPolicy(existing.tokens)) return false;
427
- existing.tokens = appendCspTokens(existing.tokens, additions);
428
- return true;
429
- }
430
-
431
- const defaultSrc = findCspDirective(directives, "default-src");
432
- if (!defaultSrc || hasStrictNonceScriptPolicy(defaultSrc.tokens)) {
433
- return false;
434
- }
435
- directives.push({
436
- name,
437
- tokens: appendCspTokens([...defaultSrc.tokens], additions),
438
- });
439
- return true;
440
- }
441
-
442
- function appendToEffectiveScriptElementCspDirective(
443
- directives: CspDirective[],
444
- additions: readonly string[],
445
- ): boolean {
446
- const scriptSrcElem = findCspDirective(directives, "script-src-elem");
447
- if (scriptSrcElem) {
448
- if (hasStrictNonceScriptPolicy(scriptSrcElem.tokens)) return false;
449
- scriptSrcElem.tokens = appendCspTokens(scriptSrcElem.tokens, additions);
450
- return true;
451
- }
452
-
453
- return appendToScriptCspDirective(directives, "script-src", additions);
454
- }
455
-
456
- function augmentExistingEnforcedCspForFrameworkScripts(
457
- policy: string,
458
- options: {
459
- gaScriptSrcTokens: readonly string[];
460
- gaEnabled: boolean;
461
- },
462
- ): string {
463
- // Multiple CSP headers are surfaced by Headers.get() as one comma-joined
464
- // string. CSP is not a comma-list header, so serializing a parsed combined
465
- // value would turn two policies into one invalid policy. Leave those headers
466
- // app-owned; a comma inside a source/report URL is still safe to parse.
467
- if (hasCommaJoinedCspPolicies(policy)) return policy;
468
-
469
- const directives = parseCsp(policy);
470
- if (!directives.length) return policy;
471
-
472
- if (options.gaEnabled) {
473
- const addedScriptElement = appendToEffectiveScriptElementCspDirective(
474
- directives,
475
- options.gaScriptSrcTokens,
476
- );
477
- if (addedScriptElement) {
478
- appendToExistingOrDefaultCspDirective(
479
- directives,
480
- "connect-src",
481
- GA_CSP_CONNECT_HOSTS,
482
- );
483
- appendToExistingOrDefaultCspDirective(
484
- directives,
485
- "img-src",
486
- GA_CSP_IMG_HOSTS,
487
- );
488
- }
489
- }
490
-
491
- ensureCspDirective(directives, "object-src", ["'none'"]);
492
- ensureCspDirective(directives, "base-uri", ["'self'"]);
493
-
494
- return serializeCsp(directives);
495
- }
496
-
497
- function augmentExistingReportOnlyCspForFrameworkScripts(
498
- policy: string,
499
- options: {
500
- scriptSrcTokens: readonly string[];
501
- gaEnabled: boolean;
502
- },
503
- ): string {
504
- if (hasCommaJoinedCspPolicies(policy)) return policy;
505
-
506
- const directives = parseCsp(policy);
507
- if (!directives.length) return policy;
508
-
509
- appendToExistingOrDefaultCspDirective(
510
- directives,
511
- "script-src",
512
- options.scriptSrcTokens,
513
- );
514
- appendToExistingCspDirective(
515
- directives,
516
- "script-src-elem",
517
- options.scriptSrcTokens,
518
- );
519
-
520
- if (options.gaEnabled) {
521
- appendToExistingOrDefaultCspDirective(
522
- directives,
523
- "connect-src",
524
- GA_CSP_CONNECT_HOSTS,
525
- );
526
- appendToExistingOrDefaultCspDirective(
527
- directives,
528
- "img-src",
529
- GA_CSP_IMG_HOSTS,
530
- );
531
- }
532
-
533
- return serializeCsp(directives);
534
- }
535
-
536
- /**
537
- * Apply a Content-Security-Policy header to HTML document responses.
254
+ * Strip document-level CSP from app HTML responses.
538
255
  *
539
- * Two directives are always enforced in production:
540
- *
541
- * - `object-src 'none'` — disables Flash / Java / PDF plugin execution,
542
- * which are a reliable code-execution vector even in modern browsers.
543
- * - `base-uri 'self'` — prevents a `<base href="...">` injection from
544
- * hijacking all relative URLs in the document (a common attack target when
545
- * user-controlled content reaches the HTML).
546
- *
547
- * A third directive, `script-src`, is emitted via `Content-Security-Policy-
548
- * Report-Only` rather than enforced when the app has no existing document CSP.
549
- * The framework injects inline scripts for analytics, Sentry, and template
550
- * setup, and hosted apps need Google Tag Manager to load without noisy CSP
551
- * diagnostics. The report-only policy is intentionally permissive for scripts:
552
- * it includes `'unsafe-inline'` plus the known GA/GTM loader hosts.
553
- *
554
- * If an app or host already sends an enforced CSP with `script-src`,
555
- * `script-src-elem`, `connect-src`, `img-src`, or `default-src`, we merge only
556
- * GA-specific allowances into existing host/hash policies. Strict nonce or
557
- * `strict-dynamic` script policies stay app-owned because blindly appending
558
- * hashes or hosts would widen the policy without reliably loading our injected
559
- * scripts.
560
- *
561
- * Templates additionally render a theme-init inline script whose exact content
562
- * varies by template (default theme param, custom docs variant, etc.) and which
563
- * is rendered by React Router, not this handler, so its hash is not available
564
- * here. Shipping script-src as Report-Only surfaces the remaining violations
565
- * without breaking template customisations; teams can graduate to enforcement
566
- * once their hashes are enumerated.
567
- *
568
- * Skipped in development (`NODE_ENV !== 'production'`) so HMR eval and Vite
569
- * dev-server injects are never blocked. Set `AGENT_NATIVE_DISABLE_DOC_CSP=1`
570
- * to opt out in production for a template with exotic needs.
256
+ * Hosted templates inject framework bootstrap scripts, analytics, Sentry config,
257
+ * and app-owned inline scripts whose exact bytes vary by build/template. Any
258
+ * shared CSP header, even Report-Only, can block or noisily report Google Tag
259
+ * Manager and those bootstraps. Extension iframes and webviews keep their own
260
+ * route-specific sandboxes; normal app documents deliberately do not emit CSP.
571
261
  */
572
- function applyDocumentCsp(headers: Headers, sentryScript: string | null): void {
573
- if (process.env.NODE_ENV !== "production") return;
574
- if (process.env.AGENT_NATIVE_DISABLE_DOC_CSP === "1") return;
575
-
576
- // script-src as Report-Only: keep this deliberately loose so the framework's
577
- // injected analytics and template bootstrap scripts do not look blocked in
578
- // browser diagnostics.
579
- const sentryBody = extractScriptBody(sentryScript);
580
- const sentryHash = sentryBody ? computeInlineScriptHash(sentryBody) : null;
581
- const gaInlineBody = getGaInlineConfigScriptBody();
582
- const gaHash = gaInlineBody ? computeInlineScriptHash(gaInlineBody) : null;
583
- const gaHosts = gaInlineBody ? [...GA_CSP_SCRIPT_HOSTS] : [];
584
- const gaScriptSrcTokens = [
585
- "'unsafe-inline'",
586
- ...(gaHash ? [gaHash] : []),
587
- ...gaHosts,
588
- ];
589
- const scriptSrcTokens = [
590
- "'self'",
591
- "'unsafe-inline'",
592
- ...(sentryHash ? [sentryHash] : []),
593
- ...(gaHash ? [gaHash] : []),
594
- ...gaHosts,
595
- ];
596
-
597
- const cspAugmentOptions = {
598
- scriptSrcTokens,
599
- gaScriptSrcTokens,
600
- gaEnabled: Boolean(gaInlineBody),
601
- };
602
- const existing = headers.get("content-security-policy") ?? "";
603
- if (!existing) {
604
- headers.set(
605
- "content-security-policy",
606
- "object-src 'none'; base-uri 'self'",
607
- );
608
- } else {
609
- headers.set(
610
- "content-security-policy",
611
- augmentExistingEnforcedCspForFrameworkScripts(
612
- existing,
613
- cspAugmentOptions,
614
- ),
615
- );
616
- }
617
-
618
- const scriptSrc = `script-src ${scriptSrcTokens.join(" ")}`;
619
- const existingRo = headers.get("content-security-policy-report-only") ?? "";
620
- if (!existingRo) {
621
- headers.set("content-security-policy-report-only", scriptSrc);
622
- } else {
623
- headers.set(
624
- "content-security-policy-report-only",
625
- augmentExistingReportOnlyCspForFrameworkScripts(
626
- existingRo,
627
- cspAugmentOptions,
628
- ),
629
- );
630
- }
262
+ function removeDocumentCsp(headers: Headers): void {
263
+ headers.delete("content-security-policy");
264
+ headers.delete("content-security-policy-report-only");
631
265
  }
632
266
 
633
267
  function isFrameworkOrAssetPath(pathname: string): boolean {
@@ -665,7 +299,15 @@ async function rewriteMountedResponse(
665
299
  }
666
300
 
667
301
  const contentType = headers.get("content-type") ?? "";
668
- if (!contentType.toLowerCase().includes("text/html") || !response.body) {
302
+ if (!contentType.toLowerCase().includes("text/html")) {
303
+ return new Response(response.body, {
304
+ status: response.status,
305
+ statusText: response.statusText,
306
+ headers,
307
+ });
308
+ }
309
+ removeDocumentCsp(headers);
310
+ if (!response.body) {
669
311
  return new Response(response.body, {
670
312
  status: response.status,
671
313
  statusText: response.statusText,
@@ -675,7 +317,6 @@ async function rewriteMountedResponse(
675
317
 
676
318
  const html = await response.text();
677
319
  headers.delete("content-length");
678
- applyDocumentCsp(headers, sentryClientConfigScript);
679
320
  return new Response(
680
321
  injectHeadScript(
681
322
  injectDefaultSocialImageMeta(
@@ -349,8 +349,6 @@ function loomEmbedResponse(embedUrl: string): Response {
349
349
  "Cache-Control": "private, max-age=0, no-store",
350
350
  "Referrer-Policy": "no-referrer",
351
351
  "X-Content-Type-Options": "nosniff",
352
- "Content-Security-Policy":
353
- "default-src 'none'; frame-src https://www.loom.com; style-src 'unsafe-inline'",
354
352
  },
355
353
  });
356
354
  }
@@ -279,7 +279,6 @@ export async function renderPublicForm(event: H3Event) {
279
279
 
280
280
  const headers: Record<string, string> = {
281
281
  "Content-Type": "text/html; charset=utf-8",
282
- "Content-Security-Policy": "frame-ancestors *",
283
282
  };
284
283
  if (status === 200) {
285
284
  // Public form SSR is anonymous HTML and follows the same framework-level
@@ -26,8 +26,8 @@ export declare const getCollabState: import("h3").EventHandlerWithFetch<import("
26
26
  * Body: { update: string (base64), requestSource?: string }
27
27
  */
28
28
  export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
29
- error: string;
30
29
  ok?: undefined;
30
+ error: string;
31
31
  } | {
32
32
  error?: undefined;
33
33
  ok: boolean;
@@ -42,8 +42,8 @@ export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import
42
42
  */
43
43
  export declare const postCollabText: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
44
44
  ok?: undefined;
45
- error: string;
46
45
  text?: undefined;
46
+ error: string;
47
47
  } | {
48
48
  error?: undefined;
49
49
  ok: boolean;
@@ -28,7 +28,7 @@ export declare function createNotificationsHandler(): import("h3").EventHandlerW
28
28
  } | {
29
29
  count?: undefined;
30
30
  updated?: undefined;
31
- error?: undefined;
32
31
  ok: boolean;
32
+ error?: undefined;
33
33
  }>>;
34
34
  //# sourceMappingURL=routes.d.ts.map
@@ -42,22 +42,22 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
42
42
  avgEvalScore: number;
43
43
  } | {
44
44
  error?: undefined;
45
- ok?: undefined;
46
45
  summary: import("./types.js").TraceSummary;
47
46
  spans: import("./types.js").TraceSpan[];
48
47
  id?: undefined;
48
+ ok?: undefined;
49
49
  } | {
50
50
  error?: undefined;
51
- ok?: undefined;
52
51
  summary?: undefined;
53
52
  spans?: undefined;
54
53
  id: string;
55
- } | {
56
54
  ok?: undefined;
55
+ } | {
57
56
  summary?: undefined;
58
57
  spans?: undefined;
59
58
  id?: undefined;
60
59
  error: any;
60
+ ok?: undefined;
61
61
  } | {
62
62
  error?: undefined;
63
63
  summary?: undefined;
@@ -15,7 +15,7 @@ export declare function createProgressHandler(): import("h3").EventHandlerWithFe
15
15
  error: string;
16
16
  ok?: undefined;
17
17
  } | {
18
- ok: boolean;
19
18
  error?: undefined;
19
+ ok: boolean;
20
20
  }>>;
21
21
  //# sourceMappingURL=routes.d.ts.map
@@ -49,11 +49,11 @@ export declare function handleUpdateResource(event: any): Promise<import("./stor
49
49
  }>;
50
50
  /** DELETE /_agent-native/resources/:id — delete a resource */
51
51
  export declare function handleDeleteResource(event: any): Promise<{
52
- error: string;
53
52
  ok?: undefined;
53
+ error: string;
54
54
  } | {
55
- ok: boolean;
56
55
  error?: undefined;
56
+ ok: boolean;
57
57
  }>;
58
58
  /** POST /_agent-native/resources/upload — upload a file as a resource */
59
59
  export declare function handleUploadResource(event: any): Promise<import("./store.js").Resource | {
@@ -73,9 +73,9 @@ export declare function handleUploadResource(event: any): Promise<import("./stor
73
73
  runId: string | null;
74
74
  expiresAt: number | null;
75
75
  metadata: string | null;
76
+ error?: undefined;
76
77
  url: string;
77
78
  provider: string;
78
- error?: undefined;
79
79
  }>;
80
80
  export {};
81
81
  //# sourceMappingURL=handlers.d.ts.map
@@ -20,27 +20,9 @@
20
20
  * return new Response(wrapWithAnalytics(body), { ... });
21
21
  * ```
22
22
  */
23
- /**
24
- * Script hosts the injected GA loader pulls executable code from. Google Tag
25
- * Manager serves `gtag/js`, and GA4 can lazy-load additional collectors from
26
- * `www.google-analytics.com`. These must be listed in the document `script-src`
27
- * so the CSP reflects the code the framework itself injects (see
28
- * `applyDocumentCsp` in `ssr-handler.ts`).
29
- */
30
- export declare const GA_CSP_SCRIPT_HOSTS: readonly ["https://www.googletagmanager.com", "https://www.google-analytics.com"];
31
- /**
32
- * Network/image hosts used by the GA4 loader when it sends page-view and event
33
- * beacons. These are separate from `script-src`: a stricter deployment CSP with
34
- * `connect-src 'self'` or `img-src 'self'` can load gtag.js but still drop all
35
- * analytics events unless these hosts are present too.
36
- */
37
- export declare const GA_CSP_CONNECT_HOSTS: readonly ["https://www.google-analytics.com", "https://analytics.google.com", "https://stats.g.doubleclick.net", "https://region1.google-analytics.com"];
38
- export declare const GA_CSP_IMG_HOSTS: readonly ["https://www.google-analytics.com", "https://www.googletagmanager.com", "https://stats.g.doubleclick.net"];
39
23
  /**
40
24
  * The exact JS body (no surrounding `<script>` tags) of the inline gtag config
41
- * block injected next to the gtag.js loader. Returned so the SSR handler can
42
- * hash it for the `script-src` CSP directive — the hash must be computed from
43
- * the identical string that `getGaScript()` embeds, so both call this helper.
25
+ * block injected next to the gtag.js loader.
44
26
  * Returns `null` when GA is not configured.
45
27
  */
46
28
  export declare function getGaInlineConfigScriptBody(): string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../src/server/analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAuBH;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,YAC9B,kCAAkC,EAClC,kCAAkC,CAC1B,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,YAC/B,kCAAkC,EAClC,8BAA8B,EAC9B,iCAAiC,EACjC,sCAAsC,CAC9B,CAAC;AAEX,eAAO,MAAM,gBAAgB,YAC3B,kCAAkC,EAClC,kCAAkC,EAClC,iCAAiC,CACzB,CAAC;AAEX;;;;;;GAMG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,GAAG,IAAI,CAc3D;AAaD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,cAAc,GAAG,cAAc,CA4BtE"}
1
+ {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../src/server/analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAuBH;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,GAAG,IAAI,CAc3D;AAaD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,cAAc,GAAG,cAAc,CA4BtE"}
@@ -34,39 +34,9 @@ function getGaMeasurementId() {
34
34
  normalizeMeasurementId(process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID) ||
35
35
  normalizeMeasurementId(getViteBakedGaMeasurementId()));
36
36
  }
37
- /**
38
- * Script hosts the injected GA loader pulls executable code from. Google Tag
39
- * Manager serves `gtag/js`, and GA4 can lazy-load additional collectors from
40
- * `www.google-analytics.com`. These must be listed in the document `script-src`
41
- * so the CSP reflects the code the framework itself injects (see
42
- * `applyDocumentCsp` in `ssr-handler.ts`).
43
- */
44
- export const GA_CSP_SCRIPT_HOSTS = [
45
- "https://www.googletagmanager.com",
46
- "https://www.google-analytics.com",
47
- ];
48
- /**
49
- * Network/image hosts used by the GA4 loader when it sends page-view and event
50
- * beacons. These are separate from `script-src`: a stricter deployment CSP with
51
- * `connect-src 'self'` or `img-src 'self'` can load gtag.js but still drop all
52
- * analytics events unless these hosts are present too.
53
- */
54
- export const GA_CSP_CONNECT_HOSTS = [
55
- "https://www.google-analytics.com",
56
- "https://analytics.google.com",
57
- "https://stats.g.doubleclick.net",
58
- "https://region1.google-analytics.com",
59
- ];
60
- export const GA_CSP_IMG_HOSTS = [
61
- "https://www.google-analytics.com",
62
- "https://www.googletagmanager.com",
63
- "https://stats.g.doubleclick.net",
64
- ];
65
37
  /**
66
38
  * The exact JS body (no surrounding `<script>` tags) of the inline gtag config
67
- * block injected next to the gtag.js loader. Returned so the SSR handler can
68
- * hash it for the `script-src` CSP directive — the hash must be computed from
69
- * the identical string that `getGaScript()` embeds, so both call this helper.
39
+ * block injected next to the gtag.js loader.
70
40
  * Returns `null` when GA is not configured.
71
41
  */
72
42
  export function getGaInlineConfigScriptBody() {
@@ -1 +1 @@
1
- {"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../src/server/analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAIH,SAAS,sBAAsB,CAAC,KAAyB;IACvD,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,OAAO,CAAC,CAAC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CAAC;KACF,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Opt-in analytics injection for SSR streams.\n * Supported environment variables:\n * - `GA_MEASUREMENT_ID` — Google Analytics 4 measurement ID\n *\n * Netlify configuration-file env vars are build-time only for serverless\n * functions, so the Vite/Nitro build paths also bake this public value into\n * SSR bundles.\n *\n * Amplitude and Sentry are initialized client-side via their npm packages\n * (see `packages/core/src/client/analytics.ts`). Only GA requires script\n * tag injection because the gtag.js loader must be a `<script src>`.\n *\n * When set, the corresponding script tags are injected before `</head>`.\n * When not set, the stream passes through untouched (zero overhead).\n *\n * Usage in entry.server.tsx:\n * ```ts\n * import { wrapWithAnalytics } from \"@agent-native/core/server\";\n * return new Response(wrapWithAnalytics(body), { ... });\n * ```\n */\n\ndeclare const __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__: string | undefined;\n\nfunction normalizeMeasurementId(value: string | undefined): string | null {\n const trimmed = value?.trim();\n return trimmed ? trimmed : null;\n}\n\nfunction getViteBakedGaMeasurementId(): string | undefined {\n return typeof __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__ === \"string\"\n ? __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__\n : undefined;\n}\n\nfunction getGaMeasurementId(): string | null {\n return (\n normalizeMeasurementId(process.env.GA_MEASUREMENT_ID) ||\n normalizeMeasurementId(process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID) ||\n normalizeMeasurementId(getViteBakedGaMeasurementId())\n );\n}\n\n/**\n * Script hosts the injected GA loader pulls executable code from. Google Tag\n * Manager serves `gtag/js`, and GA4 can lazy-load additional collectors from\n * `www.google-analytics.com`. These must be listed in the document `script-src`\n * so the CSP reflects the code the framework itself injects (see\n * `applyDocumentCsp` in `ssr-handler.ts`).\n */\nexport const GA_CSP_SCRIPT_HOSTS = [\n \"https://www.googletagmanager.com\",\n \"https://www.google-analytics.com\",\n] as const;\n\n/**\n * Network/image hosts used by the GA4 loader when it sends page-view and event\n * beacons. These are separate from `script-src`: a stricter deployment CSP with\n * `connect-src 'self'` or `img-src 'self'` can load gtag.js but still drop all\n * analytics events unless these hosts are present too.\n */\nexport const GA_CSP_CONNECT_HOSTS = [\n \"https://www.google-analytics.com\",\n \"https://analytics.google.com\",\n \"https://stats.g.doubleclick.net\",\n \"https://region1.google-analytics.com\",\n] as const;\n\nexport const GA_CSP_IMG_HOSTS = [\n \"https://www.google-analytics.com\",\n \"https://www.googletagmanager.com\",\n \"https://stats.g.doubleclick.net\",\n] as const;\n\n/**\n * The exact JS body (no surrounding `<script>` tags) of the inline gtag config\n * block injected next to the gtag.js loader. Returned so the SSR handler can\n * hash it for the `script-src` CSP directive — the hash must be computed from\n * the identical string that `getGaScript()` embeds, so both call this helper.\n * Returns `null` when GA is not configured.\n */\nexport function getGaInlineConfigScriptBody(): string | null {\n const id = getGaMeasurementId();\n if (!id) return null;\n const jsId = JSON.stringify(id);\n return (\n `window.dataLayer=window.dataLayer||[];` +\n `function gtag(){dataLayer.push(arguments);}` +\n `gtag('js',new Date());` +\n `gtag('config',${jsId});` +\n `if(typeof sessionStorage!=='undefined'&&sessionStorage.getItem('__an_signin')){` +\n `sessionStorage.removeItem('__an_signin');` +\n `gtag('event','sign_in');` +\n `}`\n );\n}\n\nfunction getGaScript(): string | null {\n const id = getGaMeasurementId();\n if (!id) return null;\n const srcId = encodeURIComponent(id);\n const inlineBody = getGaInlineConfigScriptBody();\n return (\n `<script async src=\"https://www.googletagmanager.com/gtag/js?id=${srcId}\"></script>` +\n `<script>${inlineBody}</script>`\n );\n}\n\nexport function wrapWithAnalytics(body: ReadableStream): ReadableStream {\n const scripts = [getGaScript()].filter(Boolean).join(\"\");\n if (!scripts) return body;\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let injected = false;\n\n return body.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (injected) {\n controller.enqueue(chunk);\n return;\n }\n const text = decoder.decode(chunk, { stream: true });\n const headCloseIdx = text.indexOf(\"</head>\");\n if (headCloseIdx !== -1) {\n const modified =\n text.slice(0, headCloseIdx) + scripts + text.slice(headCloseIdx);\n controller.enqueue(encoder.encode(modified));\n injected = true;\n } else {\n controller.enqueue(chunk);\n }\n },\n }),\n );\n}\n"]}
1
+ {"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../src/server/analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAIH,SAAS,sBAAsB,CAAC,KAAyB;IACvD,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AAClC,CAAC;AAED,SAAS,2BAA2B;IAClC,OAAO,OAAO,wCAAwC,KAAK,QAAQ;QACjE,CAAC,CAAC,wCAAwC;QAC1C,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,kBAAkB;IACzB,OAAO,CACL,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;QACrD,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC;QACxE,sBAAsB,CAAC,2BAA2B,EAAE,CAAC,CACtD,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,2BAA2B;IACzC,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;IAChC,IAAI,CAAC,EAAE;QAAE,OAAO,IAAI,CAAC;IACrB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAChC,OAAO,CACL,wCAAwC;QACxC,6CAA6C;QAC7C,wBAAwB;QACxB,iBAAiB,IAAI,IAAI;QACzB,iFAAiF;QACjF,2CAA2C;QAC3C,0BAA0B;QAC1B,GAAG,CACJ,CAAC;AACJ,CAAC;AAED,SAAS,WAAW;IAClB,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;IAChC,IAAI,CAAC,EAAE;QAAE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,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;KACF,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Opt-in analytics injection for SSR streams.\n * Supported environment variables:\n * - `GA_MEASUREMENT_ID` — Google Analytics 4 measurement ID\n *\n * Netlify configuration-file env vars are build-time only for serverless\n * functions, so the Vite/Nitro build paths also bake this public value into\n * SSR bundles.\n *\n * Amplitude and Sentry are initialized client-side via their npm packages\n * (see `packages/core/src/client/analytics.ts`). Only GA requires script\n * tag injection because the gtag.js loader must be a `<script src>`.\n *\n * When set, the corresponding script tags are injected before `</head>`.\n * When not set, the stream passes through untouched (zero overhead).\n *\n * Usage in entry.server.tsx:\n * ```ts\n * import { wrapWithAnalytics } from \"@agent-native/core/server\";\n * return new Response(wrapWithAnalytics(body), { ... });\n * ```\n */\n\ndeclare const __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__: string | undefined;\n\nfunction normalizeMeasurementId(value: string | undefined): string | null {\n const trimmed = value?.trim();\n return trimmed ? trimmed : null;\n}\n\nfunction getViteBakedGaMeasurementId(): string | undefined {\n return typeof __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__ === \"string\"\n ? __AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID__\n : undefined;\n}\n\nfunction getGaMeasurementId(): string | null {\n return (\n normalizeMeasurementId(process.env.GA_MEASUREMENT_ID) ||\n normalizeMeasurementId(process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID) ||\n normalizeMeasurementId(getViteBakedGaMeasurementId())\n );\n}\n\n/**\n * The exact JS body (no surrounding `<script>` tags) of the inline gtag config\n * block injected next to the gtag.js loader.\n * Returns `null` when GA is not configured.\n */\nexport function getGaInlineConfigScriptBody(): string | null {\n const id = getGaMeasurementId();\n if (!id) return null;\n const jsId = JSON.stringify(id);\n return (\n `window.dataLayer=window.dataLayer||[];` +\n `function gtag(){dataLayer.push(arguments);}` +\n `gtag('js',new Date());` +\n `gtag('config',${jsId});` +\n `if(typeof sessionStorage!=='undefined'&&sessionStorage.getItem('__an_signin')){` +\n `sessionStorage.removeItem('__an_signin');` +\n `gtag('event','sign_in');` +\n `}`\n );\n}\n\nfunction getGaScript(): string | null {\n const id = getGaMeasurementId();\n if (!id) return null;\n const srcId = encodeURIComponent(id);\n const inlineBody = getGaInlineConfigScriptBody();\n return (\n `<script async src=\"https://www.googletagmanager.com/gtag/js?id=${srcId}\"></script>` +\n `<script>${inlineBody}</script>`\n );\n}\n\nexport function wrapWithAnalytics(body: ReadableStream): ReadableStream {\n const scripts = [getGaScript()].filter(Boolean).join(\"\");\n if (!scripts) return body;\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let injected = false;\n\n return body.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (injected) {\n controller.enqueue(chunk);\n return;\n }\n const text = decoder.decode(chunk, { stream: true });\n const headCloseIdx = text.indexOf(\"</head>\");\n if (headCloseIdx !== -1) {\n const modified =\n text.slice(0, headCloseIdx) + scripts + text.slice(headCloseIdx);\n controller.enqueue(encoder.encode(modified));\n injected = true;\n } else {\n controller.enqueue(chunk);\n }\n },\n }),\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AA8CA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAooBpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAgE5E"}
1
+ {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAuCA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAoSpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAgE5E"}
@@ -19,10 +19,8 @@ import { defineEventHandler } from "h3";
19
19
  import { createRequestHandler } from "react-router";
20
20
  import { DEFAULT_SSR_CACHE_HEADERS, DEFAULT_SPECULATION_RULES_PATH, } from "../shared/cache-control.js";
21
21
  import { AGENT_NATIVE_SOCIAL_IMAGE_ALT, AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT, AGENT_NATIVE_SOCIAL_IMAGE_PATH, AGENT_NATIVE_SOCIAL_IMAGE_TYPE, AGENT_NATIVE_SOCIAL_IMAGE_WIDTH, withAgentNativeSocialImageCacheBuster, } from "../shared/social-meta.js";
22
- import { GA_CSP_CONNECT_HOSTS, GA_CSP_IMG_HOSTS, GA_CSP_SCRIPT_HOSTS, getGaInlineConfigScriptBody, } from "./analytics.js";
23
22
  import { getAppBasePathFromViteEnv, stripAppBasePath as canonicalStripAppBasePath, } from "./app-base-path.js";
24
23
  import { runWithRequestContext } from "./request-context.js";
25
- import { computeInlineScriptHash } from "./security-headers.js";
26
24
  import { getSentryClientConfigScript } from "./sentry-config.js";
27
25
  export { DEFAULT_SSR_CACHE_HEADERS, DEFAULT_SPECULATION_RULES_HEADER, DEFAULT_SSR_CACHE_CONTROL, } from "../shared/cache-control.js";
28
26
  function getAppBasePath() {
@@ -192,275 +190,17 @@ function applyDefaultSpeculationRulesHeader(headers, status, basePath) {
192
190
  headers.set("speculation-rules", `"${rulesPath}"`);
193
191
  }
194
192
  /**
195
- * Extract the plain JS body from a `<script ...>body</script>` string.
196
- * Returns `null` if the input is falsy or has no recognisable `</script>` end.
197
- * Used to compute the sha256 hash of framework-injected inline scripts so the
198
- * hash can be listed in app-owned `script-src` CSP directives.
199
- */
200
- function extractScriptBody(scriptTag) {
201
- if (!scriptTag)
202
- return null;
203
- const start = scriptTag.indexOf(">") + 1;
204
- const end = scriptTag.lastIndexOf("</script>");
205
- if (start <= 0 || end < start)
206
- return null;
207
- return scriptTag.slice(start, end);
208
- }
209
- const CSP_DIRECTIVES_WITH_VALUE_TOKENS = new Set([
210
- "base-uri",
211
- "block-all-mixed-content",
212
- "child-src",
213
- "connect-src",
214
- "default-src",
215
- "fenced-frame-src",
216
- "font-src",
217
- "form-action",
218
- "frame-ancestors",
219
- "frame-src",
220
- "img-src",
221
- "manifest-src",
222
- "media-src",
223
- "navigate-to",
224
- "object-src",
225
- "plugin-types",
226
- "prefetch-src",
227
- "referrer",
228
- "reflected-xss",
229
- "require-sri-for",
230
- "require-trusted-types-for",
231
- "report-to",
232
- "report-uri",
233
- "sandbox",
234
- "script-src",
235
- "script-src-attr",
236
- "script-src-elem",
237
- "style-src",
238
- "style-src-attr",
239
- "style-src-elem",
240
- "trusted-types",
241
- "upgrade-insecure-requests",
242
- "webrtc",
243
- "worker-src",
244
- ]);
245
- function hasCommaJoinedCspPolicies(policy) {
246
- let commaIndex = policy.indexOf(",");
247
- while (commaIndex !== -1) {
248
- const afterComma = policy.slice(commaIndex + 1);
249
- const directive = /^\s+([a-z][a-z0-9-]*)(?=\s|;|$)/i.exec(afterComma)?.[1];
250
- if (directive &&
251
- CSP_DIRECTIVES_WITH_VALUE_TOKENS.has(directive.toLowerCase())) {
252
- return true;
253
- }
254
- commaIndex = policy.indexOf(",", commaIndex + 1);
255
- }
256
- return false;
257
- }
258
- function parseCsp(policy) {
259
- return policy
260
- .split(";")
261
- .map((part) => part.trim())
262
- .filter(Boolean)
263
- .map((part) => {
264
- const [name = "", ...tokens] = part.split(/\s+/);
265
- return { name: name.toLowerCase(), tokens };
266
- })
267
- .filter((directive) => directive.name);
268
- }
269
- function serializeCsp(directives) {
270
- return directives
271
- .map((directive) => [directive.name, ...directive.tokens].filter(Boolean).join(" "))
272
- .join("; ");
273
- }
274
- function appendCspTokens(tokens, additions) {
275
- if (!additions.length)
276
- return tokens;
277
- const next = tokens.filter((token) => token !== "'none'");
278
- const seen = new Set(next);
279
- for (const token of additions) {
280
- if (!token || seen.has(token))
281
- continue;
282
- next.push(token);
283
- seen.add(token);
284
- }
285
- return next;
286
- }
287
- function findCspDirective(directives, name) {
288
- return directives.find((directive) => directive.name === name);
289
- }
290
- function appendToExistingOrDefaultCspDirective(directives, name, additions) {
291
- if (!additions.length)
292
- return;
293
- const existing = findCspDirective(directives, name);
294
- if (existing) {
295
- existing.tokens = appendCspTokens(existing.tokens, additions);
296
- return;
297
- }
298
- const defaultSrc = findCspDirective(directives, "default-src");
299
- if (!defaultSrc)
300
- return;
301
- directives.push({
302
- name,
303
- tokens: appendCspTokens([...defaultSrc.tokens], additions),
304
- });
305
- }
306
- function appendToExistingCspDirective(directives, name, additions) {
307
- const existing = findCspDirective(directives, name);
308
- if (!existing)
309
- return;
310
- existing.tokens = appendCspTokens(existing.tokens, additions);
311
- }
312
- function ensureCspDirective(directives, name, tokens) {
313
- if (findCspDirective(directives, name))
314
- return;
315
- directives.push({ name, tokens: [...tokens] });
316
- }
317
- function hasStrictNonceScriptPolicy(tokens) {
318
- return tokens.some((token) => token === "'strict-dynamic'" || token.startsWith("'nonce-"));
319
- }
320
- function appendToScriptCspDirective(directives, name, additions) {
321
- const existing = findCspDirective(directives, name);
322
- if (existing) {
323
- if (hasStrictNonceScriptPolicy(existing.tokens))
324
- return false;
325
- existing.tokens = appendCspTokens(existing.tokens, additions);
326
- return true;
327
- }
328
- const defaultSrc = findCspDirective(directives, "default-src");
329
- if (!defaultSrc || hasStrictNonceScriptPolicy(defaultSrc.tokens)) {
330
- return false;
331
- }
332
- directives.push({
333
- name,
334
- tokens: appendCspTokens([...defaultSrc.tokens], additions),
335
- });
336
- return true;
337
- }
338
- function appendToEffectiveScriptElementCspDirective(directives, additions) {
339
- const scriptSrcElem = findCspDirective(directives, "script-src-elem");
340
- if (scriptSrcElem) {
341
- if (hasStrictNonceScriptPolicy(scriptSrcElem.tokens))
342
- return false;
343
- scriptSrcElem.tokens = appendCspTokens(scriptSrcElem.tokens, additions);
344
- return true;
345
- }
346
- return appendToScriptCspDirective(directives, "script-src", additions);
347
- }
348
- function augmentExistingEnforcedCspForFrameworkScripts(policy, options) {
349
- // Multiple CSP headers are surfaced by Headers.get() as one comma-joined
350
- // string. CSP is not a comma-list header, so serializing a parsed combined
351
- // value would turn two policies into one invalid policy. Leave those headers
352
- // app-owned; a comma inside a source/report URL is still safe to parse.
353
- if (hasCommaJoinedCspPolicies(policy))
354
- return policy;
355
- const directives = parseCsp(policy);
356
- if (!directives.length)
357
- return policy;
358
- if (options.gaEnabled) {
359
- const addedScriptElement = appendToEffectiveScriptElementCspDirective(directives, options.gaScriptSrcTokens);
360
- if (addedScriptElement) {
361
- appendToExistingOrDefaultCspDirective(directives, "connect-src", GA_CSP_CONNECT_HOSTS);
362
- appendToExistingOrDefaultCspDirective(directives, "img-src", GA_CSP_IMG_HOSTS);
363
- }
364
- }
365
- ensureCspDirective(directives, "object-src", ["'none'"]);
366
- ensureCspDirective(directives, "base-uri", ["'self'"]);
367
- return serializeCsp(directives);
368
- }
369
- function augmentExistingReportOnlyCspForFrameworkScripts(policy, options) {
370
- if (hasCommaJoinedCspPolicies(policy))
371
- return policy;
372
- const directives = parseCsp(policy);
373
- if (!directives.length)
374
- return policy;
375
- appendToExistingOrDefaultCspDirective(directives, "script-src", options.scriptSrcTokens);
376
- appendToExistingCspDirective(directives, "script-src-elem", options.scriptSrcTokens);
377
- if (options.gaEnabled) {
378
- appendToExistingOrDefaultCspDirective(directives, "connect-src", GA_CSP_CONNECT_HOSTS);
379
- appendToExistingOrDefaultCspDirective(directives, "img-src", GA_CSP_IMG_HOSTS);
380
- }
381
- return serializeCsp(directives);
382
- }
383
- /**
384
- * Apply a Content-Security-Policy header to HTML document responses.
385
- *
386
- * Two directives are always enforced in production:
387
- *
388
- * - `object-src 'none'` — disables Flash / Java / PDF plugin execution,
389
- * which are a reliable code-execution vector even in modern browsers.
390
- * - `base-uri 'self'` — prevents a `<base href="...">` injection from
391
- * hijacking all relative URLs in the document (a common attack target when
392
- * user-controlled content reaches the HTML).
393
- *
394
- * A third directive, `script-src`, is emitted via `Content-Security-Policy-
395
- * Report-Only` rather than enforced when the app has no existing document CSP.
396
- * The framework injects inline scripts for analytics, Sentry, and template
397
- * setup, and hosted apps need Google Tag Manager to load without noisy CSP
398
- * diagnostics. The report-only policy is intentionally permissive for scripts:
399
- * it includes `'unsafe-inline'` plus the known GA/GTM loader hosts.
400
- *
401
- * If an app or host already sends an enforced CSP with `script-src`,
402
- * `script-src-elem`, `connect-src`, `img-src`, or `default-src`, we merge only
403
- * GA-specific allowances into existing host/hash policies. Strict nonce or
404
- * `strict-dynamic` script policies stay app-owned because blindly appending
405
- * hashes or hosts would widen the policy without reliably loading our injected
406
- * scripts.
407
- *
408
- * Templates additionally render a theme-init inline script whose exact content
409
- * varies by template (default theme param, custom docs variant, etc.) and which
410
- * is rendered by React Router, not this handler, so its hash is not available
411
- * here. Shipping script-src as Report-Only surfaces the remaining violations
412
- * without breaking template customisations; teams can graduate to enforcement
413
- * once their hashes are enumerated.
193
+ * Strip document-level CSP from app HTML responses.
414
194
  *
415
- * Skipped in development (`NODE_ENV !== 'production'`) so HMR eval and Vite
416
- * dev-server injects are never blocked. Set `AGENT_NATIVE_DISABLE_DOC_CSP=1`
417
- * to opt out in production for a template with exotic needs.
195
+ * Hosted templates inject framework bootstrap scripts, analytics, Sentry config,
196
+ * and app-owned inline scripts whose exact bytes vary by build/template. Any
197
+ * shared CSP header, even Report-Only, can block or noisily report Google Tag
198
+ * Manager and those bootstraps. Extension iframes and webviews keep their own
199
+ * route-specific sandboxes; normal app documents deliberately do not emit CSP.
418
200
  */
419
- function applyDocumentCsp(headers, sentryScript) {
420
- if (process.env.NODE_ENV !== "production")
421
- return;
422
- if (process.env.AGENT_NATIVE_DISABLE_DOC_CSP === "1")
423
- return;
424
- // script-src as Report-Only: keep this deliberately loose so the framework's
425
- // injected analytics and template bootstrap scripts do not look blocked in
426
- // browser diagnostics.
427
- const sentryBody = extractScriptBody(sentryScript);
428
- const sentryHash = sentryBody ? computeInlineScriptHash(sentryBody) : null;
429
- const gaInlineBody = getGaInlineConfigScriptBody();
430
- const gaHash = gaInlineBody ? computeInlineScriptHash(gaInlineBody) : null;
431
- const gaHosts = gaInlineBody ? [...GA_CSP_SCRIPT_HOSTS] : [];
432
- const gaScriptSrcTokens = [
433
- "'unsafe-inline'",
434
- ...(gaHash ? [gaHash] : []),
435
- ...gaHosts,
436
- ];
437
- const scriptSrcTokens = [
438
- "'self'",
439
- "'unsafe-inline'",
440
- ...(sentryHash ? [sentryHash] : []),
441
- ...(gaHash ? [gaHash] : []),
442
- ...gaHosts,
443
- ];
444
- const cspAugmentOptions = {
445
- scriptSrcTokens,
446
- gaScriptSrcTokens,
447
- gaEnabled: Boolean(gaInlineBody),
448
- };
449
- const existing = headers.get("content-security-policy") ?? "";
450
- if (!existing) {
451
- headers.set("content-security-policy", "object-src 'none'; base-uri 'self'");
452
- }
453
- else {
454
- headers.set("content-security-policy", augmentExistingEnforcedCspForFrameworkScripts(existing, cspAugmentOptions));
455
- }
456
- const scriptSrc = `script-src ${scriptSrcTokens.join(" ")}`;
457
- const existingRo = headers.get("content-security-policy-report-only") ?? "";
458
- if (!existingRo) {
459
- headers.set("content-security-policy-report-only", scriptSrc);
460
- }
461
- else {
462
- headers.set("content-security-policy-report-only", augmentExistingReportOnlyCspForFrameworkScripts(existingRo, cspAugmentOptions));
463
- }
201
+ function removeDocumentCsp(headers) {
202
+ headers.delete("content-security-policy");
203
+ headers.delete("content-security-policy-report-only");
464
204
  }
465
205
  function isFrameworkOrAssetPath(pathname) {
466
206
  return (pathname.startsWith("/.well-known/") ||
@@ -487,7 +227,15 @@ async function rewriteMountedResponse(response, basePath, pathname, requestUrl)
487
227
  headers.set("location", prefixMountedPath(location, basePath));
488
228
  }
489
229
  const contentType = headers.get("content-type") ?? "";
490
- if (!contentType.toLowerCase().includes("text/html") || !response.body) {
230
+ if (!contentType.toLowerCase().includes("text/html")) {
231
+ return new Response(response.body, {
232
+ status: response.status,
233
+ statusText: response.statusText,
234
+ headers,
235
+ });
236
+ }
237
+ removeDocumentCsp(headers);
238
+ if (!response.body) {
491
239
  return new Response(response.body, {
492
240
  status: response.status,
493
241
  statusText: response.statusText,
@@ -496,7 +244,6 @@ async function rewriteMountedResponse(response, basePath, pathname, requestUrl)
496
244
  }
497
245
  const html = await response.text();
498
246
  headers.delete("content-length");
499
- applyDocumentCsp(headers, sentryClientConfigScript);
500
247
  return new Response(injectHeadScript(injectDefaultSocialImageMeta(prefixMountedHtml(html, basePath), defaultSocialImageUrl(requestUrl, basePath)), sentryClientConfigScript), {
501
248
  status: response.status,
502
249
  statusText: response.statusText,
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-handler.js","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AACxC;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,+BAA+B,EAC/B,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,EACnB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,yBAAyB,EACzB,gBAAgB,IAAI,yBAAyB,GAC9C,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,M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CAAC;YACJ,CAAC;YACD,OAAO,MAAM,sBAAsB,CACjC,MAAM,qBAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,EACxD,QAAQ,EACR,CAAC,EACD,OAAO,CAAC,GAAG,CACZ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,mEAAmE;YACnE,uEAAuE;YACvE,sEAAsE;YACtE,oEAAoE;YACpE,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,CAAC,CAAC;YAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC;YACrD,MAAM,IAAI,GAAG,MAAM;gBACjB,CAAC,CAAC,uBAAuB;gBACzB,CAAC,CAAC,0BAA2B,GAAa,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC;YAC/D,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;gBACxB,MAAM,EAAE,GAAG;gBACX,OAAO,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { defineEventHandler } from \"h3\";\n/**\n * Shared SSR catch-all handler for React Router framework mode.\n *\n * Templates wire this up via:\n *\n * // server/routes/[...page].get.ts\n * import { createH3SSRHandler } from \"@agent-native/core/server/ssr-handler\";\n * export default createH3SSRHandler(\n * () => import(\"virtual:react-router/server-build\"),\n * );\n *\n * The `getBuild` callback MUST live in the template's own source so Vite's\n * @react-router/dev plugin can resolve the `virtual:` module. Pulling the\n * import into core (e.g. via a re-export) puts it in node_modules where\n * Vite's SSR externalizer leaves it untouched and Node's ESM loader rejects\n * the unknown scheme — silently 302'ing every request to \"/\".\n */\nimport { createRequestHandler } from \"react-router\";\n\nimport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_PATH,\n} from \"../shared/cache-control.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n withAgentNativeSocialImageCacheBuster,\n} from \"../shared/social-meta.js\";\nimport {\n GA_CSP_CONNECT_HOSTS,\n GA_CSP_IMG_HOSTS,\n GA_CSP_SCRIPT_HOSTS,\n getGaInlineConfigScriptBody,\n} from \"./analytics.js\";\nimport {\n getAppBasePathFromViteEnv,\n stripAppBasePath as canonicalStripAppBasePath,\n} from \"./app-base-path.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport { computeInlineScriptHash } from \"./security-headers.js\";\nimport { getSentryClientConfigScript } from \"./sentry-config.js\";\n\nexport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_HEADER,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\n\nfunction getAppBasePath(): string {\n return getAppBasePathFromViteEnv();\n}\n\nfunction stripAppBasePath(pathname: string): string {\n return canonicalStripAppBasePath(pathname, getAppBasePath());\n}\n\nfunction stripBasePath(pathname: string, basePath: string): string {\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction requestWithPathname(\n request: Request,\n pathname: string,\n basePath: string,\n): Request {\n const url = new URL(request.url);\n let changed = false;\n if (basePath && pathname === \"/__manifest\") {\n const paths = url.searchParams.get(\"paths\");\n if (paths) {\n const strippedPaths = paths\n .split(\",\")\n .map((path) => stripBasePath(path, basePath))\n .join(\",\");\n if (strippedPaths !== paths) {\n url.searchParams.set(\"paths\", strippedPaths);\n changed = true;\n }\n }\n }\n if (url.pathname !== pathname) {\n url.pathname = pathname;\n changed = true;\n }\n if (!changed) return request;\n const init: RequestInit & { duplex?: \"half\" } = {\n method: request.method,\n headers: request.headers,\n signal: request.signal,\n };\n if (request.body && ![\"GET\", \"HEAD\"].includes(request.method.toUpperCase())) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n return new Request(url, init);\n}\n\nfunction prefixMountedPath(path: string, basePath: string): string {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(`${basePath}/`)) return path;\n return `${basePath}${path}`;\n}\n\nfunction prefixMountedHtml(html: string, basePath: string): string {\n if (!basePath) return html;\n return html\n .replace(\n /\\b(href|src|action|formaction|poster)=([\"'])(\\/(?!\\/)[^\"']*)\\2/g,\n (_match, attr: string, quote: string, path: string) =>\n `${attr}=${quote}${prefixMountedPath(path, basePath)}${quote}`,\n )\n .replace(/url\\(([\"']?)(\\/(?!\\/)[^)'\" ]+)\\1\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return `url(${q}${prefixMountedPath(path, basePath)}${q})`;\n });\n}\n\nfunction injectHeadScript(html: string, script: string | null): string {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=([\"'])og:image\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:card\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:image\\1)[^>]*>/i;\n\nfunction defaultSocialImageUrl(requestUrl: string, basePath: string): string {\n return withAgentNativeSocialImageCacheBuster(\n new URL(\n prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath),\n requestUrl,\n ).toString(),\n );\n}\n\nfunction injectDefaultSocialImageMeta(html: string, imageUrl: string): string {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags: string[] = [];\n\n if (!hasAnySocialImage) {\n tags.push(`<meta property=\"og:image\" content=\"${imageUrl}\">`);\n tags.push(`<meta property=\"og:image:secure_url\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta property=\"og:image:type\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_TYPE}\">`,\n );\n tags.push(\n `<meta property=\"og:image:width\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_WIDTH}\">`,\n );\n tags.push(\n `<meta property=\"og:image:height\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT}\">`,\n );\n tags.push(\n `<meta property=\"og:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push(`<meta name=\"twitter:card\" content=\"summary_large_image\">`);\n }\n if (!hasAnySocialImage) {\n tags.push(`<meta name=\"twitter:image\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta name=\"twitter:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(\n headers: Headers,\n status: number,\n pathname: string,\n): boolean {\n if (status < 200 || status >= 400) return false;\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * ┌──────────────────────────────────────────────────────────────────────────┐\n * │ SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE. │\n * │ │\n * │ Every SSR HTML / React Router `.data` response gets the same public │\n * │ stale-while-revalidate policy for ALL visitors, authenticated or not, so │\n * │ the edge serves one shared copy and never stampedes origin. │\n * │ │\n * │ DO NOT reintroduce per-user / cookie-based cache variation here (no │\n * │ `private`, no `no-store`, no `Vary: Cookie`, no \"authenticated → don't │\n * │ cache\" branch). That makes pages uncacheable for every logged-in visitor, │\n * │ which is slow and expensive — exactly the regression this guardrail │\n * │ prevents. The reason it is SAFE to hard-cache is that the SSR response is │\n * │ impersonal: `createH3SSRHandler` renders without reading the request's │\n * │ session/cookies, so there is no per-user data baked into the HTML. ALL │\n * │ per-user state (who's logged in, private records, access checks) is │\n * │ resolved CLIENT-SIDE after load. Keep it that way: if you need the SSR │\n * │ output to differ per user, the fix is to move that work client-side, not │\n * │ to disable caching here. │\n * └──────────────────────────────────────────────────────────────────────────┘\n */\nfunction applyDefaultSsrCacheHeader(\n headers: Headers,\n status: number,\n pathname: string,\n) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n // Netlify Functions/proxies are not cached by default. Set all three cache\n // headers: Cache-Control for browsers, CDN-Cache-Control for generic CDNs,\n // and Netlify-CDN-Cache-Control (with durable) so Netlify's shared cache\n // actually serves SSR HTML/.data from the edge instead of forwarding every\n // request to origin — for every visitor, authenticated or not.\n for (const [name, value] of Object.entries(DEFAULT_SSR_CACHE_HEADERS)) {\n headers.set(name, value);\n }\n}\n\nfunction applyDefaultSpeculationRulesHeader(\n headers: Headers,\n status: number,\n basePath: string,\n) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects its own Speculation-Rules header when the\n // origin omits one. Those browser prefetches carry `Sec-Purpose: prefetch`,\n // and Cloudflare refuses cache-ineligible dynamic pages with a 503 before\n // the request can reach Netlify/origin. We publish an explicit no-op ruleset\n // by default so Cloudflare does not inject its edge prefetch rules. Preserve\n // an app-provided Speculation-Rules header above if a template deliberately\n // owns this behavior.\n const rulesPath = prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath);\n headers.set(\"speculation-rules\", `\"${rulesPath}\"`);\n}\n\n/**\n * Extract the plain JS body from a `<script ...>body</script>` string.\n * Returns `null` if the input is falsy or has no recognisable `</script>` end.\n * Used to compute the sha256 hash of framework-injected inline scripts so the\n * hash can be listed in app-owned `script-src` CSP directives.\n */\nfunction extractScriptBody(scriptTag: string | null): string | null {\n if (!scriptTag) return null;\n const start = scriptTag.indexOf(\">\") + 1;\n const end = scriptTag.lastIndexOf(\"</script>\");\n if (start <= 0 || end < start) return null;\n return scriptTag.slice(start, end);\n}\n\ntype CspDirective = {\n name: string;\n tokens: string[];\n};\n\nconst CSP_DIRECTIVES_WITH_VALUE_TOKENS = new Set([\n \"base-uri\",\n \"block-all-mixed-content\",\n \"child-src\",\n \"connect-src\",\n \"default-src\",\n \"fenced-frame-src\",\n \"font-src\",\n \"form-action\",\n \"frame-ancestors\",\n \"frame-src\",\n \"img-src\",\n \"manifest-src\",\n \"media-src\",\n \"navigate-to\",\n \"object-src\",\n \"plugin-types\",\n \"prefetch-src\",\n \"referrer\",\n \"reflected-xss\",\n \"require-sri-for\",\n \"require-trusted-types-for\",\n \"report-to\",\n \"report-uri\",\n \"sandbox\",\n \"script-src\",\n \"script-src-attr\",\n \"script-src-elem\",\n \"style-src\",\n \"style-src-attr\",\n \"style-src-elem\",\n \"trusted-types\",\n \"upgrade-insecure-requests\",\n \"webrtc\",\n \"worker-src\",\n]);\n\nfunction hasCommaJoinedCspPolicies(policy: string): boolean {\n let commaIndex = policy.indexOf(\",\");\n while (commaIndex !== -1) {\n const afterComma = policy.slice(commaIndex + 1);\n const directive = /^\\s+([a-z][a-z0-9-]*)(?=\\s|;|$)/i.exec(afterComma)?.[1];\n if (\n directive &&\n CSP_DIRECTIVES_WITH_VALUE_TOKENS.has(directive.toLowerCase())\n ) {\n return true;\n }\n commaIndex = policy.indexOf(\",\", commaIndex + 1);\n }\n return false;\n}\n\nfunction parseCsp(policy: string): CspDirective[] {\n return policy\n .split(\";\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const [name = \"\", ...tokens] = part.split(/\\s+/);\n return { name: name.toLowerCase(), tokens };\n })\n .filter((directive) => directive.name);\n}\n\nfunction serializeCsp(directives: CspDirective[]): string {\n return directives\n .map((directive) =>\n [directive.name, ...directive.tokens].filter(Boolean).join(\" \"),\n )\n .join(\"; \");\n}\n\nfunction appendCspTokens(\n tokens: string[],\n additions: readonly string[],\n): string[] {\n if (!additions.length) return tokens;\n const next = tokens.filter((token) => token !== \"'none'\");\n const seen = new Set(next);\n for (const token of additions) {\n if (!token || seen.has(token)) continue;\n next.push(token);\n seen.add(token);\n }\n return next;\n}\n\nfunction findCspDirective(\n directives: CspDirective[],\n name: string,\n): CspDirective | undefined {\n return directives.find((directive) => directive.name === name);\n}\n\nfunction appendToExistingOrDefaultCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n if (!additions.length) return;\n const existing = findCspDirective(directives, name);\n if (existing) {\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc) return;\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n}\n\nfunction appendToExistingCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n const existing = findCspDirective(directives, name);\n if (!existing) return;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n}\n\nfunction ensureCspDirective(\n directives: CspDirective[],\n name: string,\n tokens: readonly string[],\n): void {\n if (findCspDirective(directives, name)) return;\n directives.push({ name, tokens: [...tokens] });\n}\n\nfunction hasStrictNonceScriptPolicy(tokens: readonly string[]): boolean {\n return tokens.some(\n (token) => token === \"'strict-dynamic'\" || token.startsWith(\"'nonce-\"),\n );\n}\n\nfunction appendToScriptCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): boolean {\n const existing = findCspDirective(directives, name);\n if (existing) {\n if (hasStrictNonceScriptPolicy(existing.tokens)) return false;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return true;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc || hasStrictNonceScriptPolicy(defaultSrc.tokens)) {\n return false;\n }\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n return true;\n}\n\nfunction appendToEffectiveScriptElementCspDirective(\n directives: CspDirective[],\n additions: readonly string[],\n): boolean {\n const scriptSrcElem = findCspDirective(directives, \"script-src-elem\");\n if (scriptSrcElem) {\n if (hasStrictNonceScriptPolicy(scriptSrcElem.tokens)) return false;\n scriptSrcElem.tokens = appendCspTokens(scriptSrcElem.tokens, additions);\n return true;\n }\n\n return appendToScriptCspDirective(directives, \"script-src\", additions);\n}\n\nfunction augmentExistingEnforcedCspForFrameworkScripts(\n policy: string,\n options: {\n gaScriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n // Multiple CSP headers are surfaced by Headers.get() as one comma-joined\n // string. CSP is not a comma-list header, so serializing a parsed combined\n // value would turn two policies into one invalid policy. Leave those headers\n // app-owned; a comma inside a source/report URL is still safe to parse.\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n if (options.gaEnabled) {\n const addedScriptElement = appendToEffectiveScriptElementCspDirective(\n directives,\n options.gaScriptSrcTokens,\n );\n if (addedScriptElement) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n }\n\n ensureCspDirective(directives, \"object-src\", [\"'none'\"]);\n ensureCspDirective(directives, \"base-uri\", [\"'self'\"]);\n\n return serializeCsp(directives);\n}\n\nfunction augmentExistingReportOnlyCspForFrameworkScripts(\n policy: string,\n options: {\n scriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n appendToExistingOrDefaultCspDirective(\n directives,\n \"script-src\",\n options.scriptSrcTokens,\n );\n appendToExistingCspDirective(\n directives,\n \"script-src-elem\",\n options.scriptSrcTokens,\n );\n\n if (options.gaEnabled) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n\n return serializeCsp(directives);\n}\n\n/**\n * Apply a Content-Security-Policy header to HTML document responses.\n *\n * Two directives are always enforced in production:\n *\n * - `object-src 'none'` — disables Flash / Java / PDF plugin execution,\n * which are a reliable code-execution vector even in modern browsers.\n * - `base-uri 'self'` — prevents a `<base href=\"...\">` injection from\n * hijacking all relative URLs in the document (a common attack target when\n * user-controlled content reaches the HTML).\n *\n * A third directive, `script-src`, is emitted via `Content-Security-Policy-\n * Report-Only` rather than enforced when the app has no existing document CSP.\n * The framework injects inline scripts for analytics, Sentry, and template\n * setup, and hosted apps need Google Tag Manager to load without noisy CSP\n * diagnostics. The report-only policy is intentionally permissive for scripts:\n * it includes `'unsafe-inline'` plus the known GA/GTM loader hosts.\n *\n * If an app or host already sends an enforced CSP with `script-src`,\n * `script-src-elem`, `connect-src`, `img-src`, or `default-src`, we merge only\n * GA-specific allowances into existing host/hash policies. Strict nonce or\n * `strict-dynamic` script policies stay app-owned because blindly appending\n * hashes or hosts would widen the policy without reliably loading our injected\n * scripts.\n *\n * Templates additionally render a theme-init inline script whose exact content\n * varies by template (default theme param, custom docs variant, etc.) and which\n * is rendered by React Router, not this handler, so its hash is not available\n * here. Shipping script-src as Report-Only surfaces the remaining violations\n * without breaking template customisations; teams can graduate to enforcement\n * once their hashes are enumerated.\n *\n * Skipped in development (`NODE_ENV !== 'production'`) so HMR eval and Vite\n * dev-server injects are never blocked. Set `AGENT_NATIVE_DISABLE_DOC_CSP=1`\n * to opt out in production for a template with exotic needs.\n */\nfunction applyDocumentCsp(headers: Headers, sentryScript: string | null): void {\n if (process.env.NODE_ENV !== \"production\") return;\n if (process.env.AGENT_NATIVE_DISABLE_DOC_CSP === \"1\") return;\n\n // script-src as Report-Only: keep this deliberately loose so the framework's\n // injected analytics and template bootstrap scripts do not look blocked in\n // browser diagnostics.\n const sentryBody = extractScriptBody(sentryScript);\n const sentryHash = sentryBody ? computeInlineScriptHash(sentryBody) : null;\n const gaInlineBody = getGaInlineConfigScriptBody();\n const gaHash = gaInlineBody ? computeInlineScriptHash(gaInlineBody) : null;\n const gaHosts = gaInlineBody ? [...GA_CSP_SCRIPT_HOSTS] : [];\n const gaScriptSrcTokens = [\n \"'unsafe-inline'\",\n ...(gaHash ? [gaHash] : []),\n ...gaHosts,\n ];\n const scriptSrcTokens = [\n \"'self'\",\n \"'unsafe-inline'\",\n ...(sentryHash ? [sentryHash] : []),\n ...(gaHash ? [gaHash] : []),\n ...gaHosts,\n ];\n\n const cspAugmentOptions = {\n scriptSrcTokens,\n gaScriptSrcTokens,\n gaEnabled: Boolean(gaInlineBody),\n };\n const existing = headers.get(\"content-security-policy\") ?? \"\";\n if (!existing) {\n headers.set(\n \"content-security-policy\",\n \"object-src 'none'; base-uri 'self'\",\n );\n } else {\n headers.set(\n \"content-security-policy\",\n augmentExistingEnforcedCspForFrameworkScripts(\n existing,\n cspAugmentOptions,\n ),\n );\n }\n\n const scriptSrc = `script-src ${scriptSrcTokens.join(\" \")}`;\n const existingRo = headers.get(\"content-security-policy-report-only\") ?? \"\";\n if (!existingRo) {\n headers.set(\"content-security-policy-report-only\", scriptSrc);\n } else {\n headers.set(\n \"content-security-policy-report-only\",\n augmentExistingReportOnlyCspForFrameworkScripts(\n existingRo,\n cspAugmentOptions,\n ),\n );\n }\n}\n\nfunction isFrameworkOrAssetPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/.well-known/\") ||\n pathname.startsWith(\"/_agent_native/\") ||\n pathname.startsWith(\"/_agent-native/\") ||\n pathname.startsWith(\"/api/\") ||\n pathname.startsWith(\"/@vite/\") ||\n pathname.startsWith(\"/@id/\") ||\n pathname.startsWith(\"/@fs/\") ||\n pathname === \"/@react-refresh\" ||\n pathname === \"/__vite_ping\" ||\n pathname === \"/__open-in-editor\" ||\n pathname === \"/favicon.ico\" ||\n pathname === \"/favicon.png\" ||\n (/\\.\\w+$/.test(pathname) && !pathname.endsWith(\".data\"))\n );\n}\n\nasync function rewriteMountedResponse(\n response: Response,\n basePath: string,\n pathname: string,\n requestUrl: string,\n): Promise<Response> {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") ?? \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n applyDocumentCsp(headers, sentryClientConfigScript);\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(requestUrl, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\n/**\n * Create an h3 catch-all that hands page routes to React Router and\n * returns 404 for framework / asset paths that React Router doesn't own.\n */\nexport function createH3SSRHandler(getBuild: () => Promise<unknown> | unknown) {\n const handler = createRequestHandler(getBuild as any);\n return defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(event.url.pathname);\n if (isFrameworkOrAssetPath(p)) {\n return new Response(null, { status: 404 });\n }\n try {\n const request = requestWithPathname(event.req as Request, p, basePath);\n // SSR renders an IMPERSONAL public shell — we deliberately do NOT read the\n // request's session/cookies here, and pin an explicitly anonymous request\n // context. That keeps the SSR HTML/.data identical for every visitor so it\n // can be hard-cached at the CDN for everyone (see applyDefaultSsrCacheHeader).\n //\n // Consequence: SSR loaders that call `getRequestUserEmail()` / `accessFilter()`\n // always see the unauthenticated branch and render public content only. Any\n // per-user view (private records, share-grant access, who's logged in) MUST\n // be resolved CLIENT-SIDE after load, never baked into SSR. Do not re-pin the\n // session here to \"fix\" a per-user page — that silently makes the page\n // uncacheable and/or leaks one user's data into another's cached copy.\n const ctx = { userEmail: undefined, orgId: undefined };\n if (request.method === \"HEAD\") {\n const getRequest = new Request(request.url, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n const response = await runWithRequestContext(ctx, () =>\n handler(getRequest),\n );\n return await rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request.url,\n );\n }\n return await rewriteMountedResponse(\n await runWithRequestContext(ctx, () => handler(request)),\n basePath,\n p,\n request.url,\n );\n } catch (err) {\n // Log the full stack server-side, but never leak it to the client.\n // Stack traces expose file paths, library versions, and code structure\n // that aid reconnaissance attacks. In dev we surface the message text\n // so devtools shows something useful; in prod we return a bare 500.\n console.error(\"[ssr-handler] SSR error:\", err);\n const isProd = process.env.NODE_ENV === \"production\";\n const body = isProd\n ? \"Internal Server Error\"\n : `Internal Server Error: ${(err as Error)?.message ?? err}`;\n return new Response(body, {\n status: 500,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"ssr-handler.js","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AACxC;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cA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B,GAAa,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC;YAC/D,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;gBACxB,MAAM,EAAE,GAAG;gBACX,OAAO,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { defineEventHandler } from \"h3\";\n/**\n * Shared SSR catch-all handler for React Router framework mode.\n *\n * Templates wire this up via:\n *\n * // server/routes/[...page].get.ts\n * import { createH3SSRHandler } from \"@agent-native/core/server/ssr-handler\";\n * export default createH3SSRHandler(\n * () => import(\"virtual:react-router/server-build\"),\n * );\n *\n * The `getBuild` callback MUST live in the template's own source so Vite's\n * @react-router/dev plugin can resolve the `virtual:` module. Pulling the\n * import into core (e.g. via a re-export) puts it in node_modules where\n * Vite's SSR externalizer leaves it untouched and Node's ESM loader rejects\n * the unknown scheme — silently 302'ing every request to \"/\".\n */\nimport { createRequestHandler } from \"react-router\";\n\nimport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_PATH,\n} from \"../shared/cache-control.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n withAgentNativeSocialImageCacheBuster,\n} from \"../shared/social-meta.js\";\nimport {\n getAppBasePathFromViteEnv,\n stripAppBasePath as canonicalStripAppBasePath,\n} from \"./app-base-path.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport { getSentryClientConfigScript } from \"./sentry-config.js\";\n\nexport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_HEADER,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\n\nfunction getAppBasePath(): string {\n return getAppBasePathFromViteEnv();\n}\n\nfunction stripAppBasePath(pathname: string): string {\n return canonicalStripAppBasePath(pathname, getAppBasePath());\n}\n\nfunction stripBasePath(pathname: string, basePath: string): string {\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction requestWithPathname(\n request: Request,\n pathname: string,\n basePath: string,\n): Request {\n const url = new URL(request.url);\n let changed = false;\n if (basePath && pathname === \"/__manifest\") {\n const paths = url.searchParams.get(\"paths\");\n if (paths) {\n const strippedPaths = paths\n .split(\",\")\n .map((path) => stripBasePath(path, basePath))\n .join(\",\");\n if (strippedPaths !== paths) {\n url.searchParams.set(\"paths\", strippedPaths);\n changed = true;\n }\n }\n }\n if (url.pathname !== pathname) {\n url.pathname = pathname;\n changed = true;\n }\n if (!changed) return request;\n const init: RequestInit & { duplex?: \"half\" } = {\n method: request.method,\n headers: request.headers,\n signal: request.signal,\n };\n if (request.body && ![\"GET\", \"HEAD\"].includes(request.method.toUpperCase())) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n return new Request(url, init);\n}\n\nfunction prefixMountedPath(path: string, basePath: string): string {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(`${basePath}/`)) return path;\n return `${basePath}${path}`;\n}\n\nfunction prefixMountedHtml(html: string, basePath: string): string {\n if (!basePath) return html;\n return html\n .replace(\n /\\b(href|src|action|formaction|poster)=([\"'])(\\/(?!\\/)[^\"']*)\\2/g,\n (_match, attr: string, quote: string, path: string) =>\n `${attr}=${quote}${prefixMountedPath(path, basePath)}${quote}`,\n )\n .replace(/url\\(([\"']?)(\\/(?!\\/)[^)'\" ]+)\\1\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return `url(${q}${prefixMountedPath(path, basePath)}${q})`;\n });\n}\n\nfunction injectHeadScript(html: string, script: string | null): string {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=([\"'])og:image\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:card\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:image\\1)[^>]*>/i;\n\nfunction defaultSocialImageUrl(requestUrl: string, basePath: string): string {\n return withAgentNativeSocialImageCacheBuster(\n new URL(\n prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath),\n requestUrl,\n ).toString(),\n );\n}\n\nfunction injectDefaultSocialImageMeta(html: string, imageUrl: string): string {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags: string[] = [];\n\n if (!hasAnySocialImage) {\n tags.push(`<meta property=\"og:image\" content=\"${imageUrl}\">`);\n tags.push(`<meta property=\"og:image:secure_url\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta property=\"og:image:type\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_TYPE}\">`,\n );\n tags.push(\n `<meta property=\"og:image:width\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_WIDTH}\">`,\n );\n tags.push(\n `<meta property=\"og:image:height\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT}\">`,\n );\n tags.push(\n `<meta property=\"og:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push(`<meta name=\"twitter:card\" content=\"summary_large_image\">`);\n }\n if (!hasAnySocialImage) {\n tags.push(`<meta name=\"twitter:image\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta name=\"twitter:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(\n headers: Headers,\n status: number,\n pathname: string,\n): boolean {\n if (status < 200 || status >= 400) return false;\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * ┌──────────────────────────────────────────────────────────────────────────┐\n * │ SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE. │\n * │ │\n * │ Every SSR HTML / React Router `.data` response gets the same public │\n * │ stale-while-revalidate policy for ALL visitors, authenticated or not, so │\n * │ the edge serves one shared copy and never stampedes origin. │\n * │ │\n * │ DO NOT reintroduce per-user / cookie-based cache variation here (no │\n * │ `private`, no `no-store`, no `Vary: Cookie`, no \"authenticated → don't │\n * │ cache\" branch). That makes pages uncacheable for every logged-in visitor, │\n * │ which is slow and expensive — exactly the regression this guardrail │\n * │ prevents. The reason it is SAFE to hard-cache is that the SSR response is │\n * │ impersonal: `createH3SSRHandler` renders without reading the request's │\n * │ session/cookies, so there is no per-user data baked into the HTML. ALL │\n * │ per-user state (who's logged in, private records, access checks) is │\n * │ resolved CLIENT-SIDE after load. Keep it that way: if you need the SSR │\n * │ output to differ per user, the fix is to move that work client-side, not │\n * │ to disable caching here. │\n * └──────────────────────────────────────────────────────────────────────────┘\n */\nfunction applyDefaultSsrCacheHeader(\n headers: Headers,\n status: number,\n pathname: string,\n) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n // Netlify Functions/proxies are not cached by default. Set all three cache\n // headers: Cache-Control for browsers, CDN-Cache-Control for generic CDNs,\n // and Netlify-CDN-Cache-Control (with durable) so Netlify's shared cache\n // actually serves SSR HTML/.data from the edge instead of forwarding every\n // request to origin — for every visitor, authenticated or not.\n for (const [name, value] of Object.entries(DEFAULT_SSR_CACHE_HEADERS)) {\n headers.set(name, value);\n }\n}\n\nfunction applyDefaultSpeculationRulesHeader(\n headers: Headers,\n status: number,\n basePath: string,\n) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects its own Speculation-Rules header when the\n // origin omits one. Those browser prefetches carry `Sec-Purpose: prefetch`,\n // and Cloudflare refuses cache-ineligible dynamic pages with a 503 before\n // the request can reach Netlify/origin. We publish an explicit no-op ruleset\n // by default so Cloudflare does not inject its edge prefetch rules. Preserve\n // an app-provided Speculation-Rules header above if a template deliberately\n // owns this behavior.\n const rulesPath = prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath);\n headers.set(\"speculation-rules\", `\"${rulesPath}\"`);\n}\n\n/**\n * Strip document-level CSP from app HTML responses.\n *\n * Hosted templates inject framework bootstrap scripts, analytics, Sentry config,\n * and app-owned inline scripts whose exact bytes vary by build/template. Any\n * shared CSP header, even Report-Only, can block or noisily report Google Tag\n * Manager and those bootstraps. Extension iframes and webviews keep their own\n * route-specific sandboxes; normal app documents deliberately do not emit CSP.\n */\nfunction removeDocumentCsp(headers: Headers): void {\n headers.delete(\"content-security-policy\");\n headers.delete(\"content-security-policy-report-only\");\n}\n\nfunction isFrameworkOrAssetPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/.well-known/\") ||\n pathname.startsWith(\"/_agent_native/\") ||\n pathname.startsWith(\"/_agent-native/\") ||\n pathname.startsWith(\"/api/\") ||\n pathname.startsWith(\"/@vite/\") ||\n pathname.startsWith(\"/@id/\") ||\n pathname.startsWith(\"/@fs/\") ||\n pathname === \"/@react-refresh\" ||\n pathname === \"/__vite_ping\" ||\n pathname === \"/__open-in-editor\" ||\n pathname === \"/favicon.ico\" ||\n pathname === \"/favicon.png\" ||\n (/\\.\\w+$/.test(pathname) && !pathname.endsWith(\".data\"))\n );\n}\n\nasync function rewriteMountedResponse(\n response: Response,\n basePath: string,\n pathname: string,\n requestUrl: string,\n): Promise<Response> {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") ?? \"\";\n if (!contentType.toLowerCase().includes(\"text/html\")) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n removeDocumentCsp(headers);\n if (!response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(requestUrl, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\n/**\n * Create an h3 catch-all that hands page routes to React Router and\n * returns 404 for framework / asset paths that React Router doesn't own.\n */\nexport function createH3SSRHandler(getBuild: () => Promise<unknown> | unknown) {\n const handler = createRequestHandler(getBuild as any);\n return defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(event.url.pathname);\n if (isFrameworkOrAssetPath(p)) {\n return new Response(null, { status: 404 });\n }\n try {\n const request = requestWithPathname(event.req as Request, p, basePath);\n // SSR renders an IMPERSONAL public shell — we deliberately do NOT read the\n // request's session/cookies here, and pin an explicitly anonymous request\n // context. That keeps the SSR HTML/.data identical for every visitor so it\n // can be hard-cached at the CDN for everyone (see applyDefaultSsrCacheHeader).\n //\n // Consequence: SSR loaders that call `getRequestUserEmail()` / `accessFilter()`\n // always see the unauthenticated branch and render public content only. Any\n // per-user view (private records, share-grant access, who's logged in) MUST\n // be resolved CLIENT-SIDE after load, never baked into SSR. Do not re-pin the\n // session here to \"fix\" a per-user page — that silently makes the page\n // uncacheable and/or leaks one user's data into another's cached copy.\n const ctx = { userEmail: undefined, orgId: undefined };\n if (request.method === \"HEAD\") {\n const getRequest = new Request(request.url, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n const response = await runWithRequestContext(ctx, () =>\n handler(getRequest),\n );\n return await rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request.url,\n );\n }\n return await rewriteMountedResponse(\n await runWithRequestContext(ctx, () => handler(request)),\n basePath,\n p,\n request.url,\n );\n } catch (err) {\n // Log the full stack server-side, but never leak it to the client.\n // Stack traces expose file paths, library versions, and code structure\n // that aid reconnaissance attacks. In dev we surface the message text\n // so devtools shows something useful; in prod we return a bare 500.\n console.error(\"[ssr-handler] SSR error:\", err);\n const isProd = process.env.NODE_ENV === \"production\";\n const body = isProd\n ? \"Internal Server Error\"\n : `Internal Server Error: ${(err as Error)?.message ?? err}`;\n return new Response(body, {\n status: 500,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n });\n}\n"]}
@@ -20,7 +20,7 @@ export declare function createTranscribeVoiceHandler(): import("h3").EventHandle
20
20
  error: string;
21
21
  text?: undefined;
22
22
  } | {
23
- text: string;
24
23
  error?: undefined;
24
+ text: string;
25
25
  }>>;
26
26
  //# sourceMappingURL=transcribe-voice.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.84.66",
3
+ "version": "0.84.67",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {