singularity-core 0.17.3 → 0.17.4

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.
@@ -0,0 +1,53 @@
1
+ import { type ContentSecurityPolicyOptions } from "../security/index.js";
2
+ /** An AdSense publisher id as the ad code takes it: `ca-pub-` and 16 digits. */
3
+ export declare const ADSENSE_CLIENT_PATTERN: RegExp;
4
+ /** True for an AdSense publisher id (`ca-pub-` and 16 digits). */
5
+ export declare function isAdSenseClient(value: string | undefined): value is string;
6
+ /** AdSense's loader script for a publisher. */
7
+ export declare function adSenseScriptSrc(client: string): string;
8
+ /**
9
+ * Head `meta` entry that tells AdSense the site belongs to the publisher,
10
+ * one of the ways it verifies a site. Put it on the domain's home page. Empty
11
+ * without a publisher id, like `umamiHeadScripts`.
12
+ */
13
+ export declare function adSenseAccountMeta(client: string | undefined): {
14
+ name: string;
15
+ content: string;
16
+ }[];
17
+ /**
18
+ * CSP sources a page with AdSense ads adds to the defaults, as
19
+ * `extraSources`. Its scripts come in through the nonce and
20
+ * `'strict-dynamic'`, the strict policy Google supports. Its ads render in
21
+ * frames from hosts Google changes without notice, so any https frame.
22
+ */
23
+ export declare const ADSENSE_CSP_SOURCES: NonNullable<ContentSecurityPolicyOptions["extraSources"]>;
24
+ /**
25
+ * Adds AdSense's loader to the page once, with the request's CSP nonce, as
26
+ * Google asks. Browser only: call it from an effect. The loader also shows
27
+ * Google's consent message where the publisher set one up (Privacy &
28
+ * messaging), and places Auto ads if they are on for the site, so keep Auto
29
+ * ads off where the page places its own units.
30
+ */
31
+ export declare function loadAdSense(client: string): void;
32
+ /**
33
+ * Asks AdSense to fill one `<ins class="adsbygoogle">` that is already in the
34
+ * page. Only once per element, so an effect that runs twice (StrictMode)
35
+ * does not queue a second request, which AdSense rejects. Before the loader
36
+ * has run, the request waits in `window.adsbygoogle`.
37
+ */
38
+ export declare function fillAdSenseSlot(slot: Element): void;
39
+ /** One ads.txt line: an ad system allowed to sell the site's ad space. */
40
+ export type AdsTxtRecord = {
41
+ /** The ad system's domain, e.g. `google.com`. */
42
+ domain: string;
43
+ /** The site's account there, e.g. `pub-0000000000000000`. */
44
+ accountId: string;
45
+ /** `DIRECT` when the site's owner holds the account. */
46
+ relationship: "DIRECT" | "RESELLER";
47
+ /** The ad system's TAG id, when it has one. */
48
+ certificationAuthorityId?: string;
49
+ };
50
+ /** The ads.txt file (IAB Tech Lab) for the given sellers. Serve with `plainTextResponse`. */
51
+ export declare function buildAdsTxt(records: AdsTxtRecord[]): string;
52
+ /** The ads.txt line for an AdSense publisher, from its ad code id (`ca-pub-…`). */
53
+ export declare function adSenseAdsTxtRecord(client: string): AdsTxtRecord;
@@ -0,0 +1,90 @@
1
+ import { getCspNonce, } from "../security/index.js";
2
+ /** An AdSense publisher id as the ad code takes it: `ca-pub-` and 16 digits. */
3
+ export const ADSENSE_CLIENT_PATTERN = /^ca-pub-\d{16}$/;
4
+ /** True for an AdSense publisher id (`ca-pub-` and 16 digits). */
5
+ export function isAdSenseClient(value) {
6
+ return value !== undefined && ADSENSE_CLIENT_PATTERN.test(value);
7
+ }
8
+ /** AdSense's loader script for a publisher. */
9
+ export function adSenseScriptSrc(client) {
10
+ return `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(client)}`;
11
+ }
12
+ /**
13
+ * Head `meta` entry that tells AdSense the site belongs to the publisher,
14
+ * one of the ways it verifies a site. Put it on the domain's home page. Empty
15
+ * without a publisher id, like `umamiHeadScripts`.
16
+ */
17
+ export function adSenseAccountMeta(client) {
18
+ return client ? [{ name: "google-adsense-account", content: client }] : [];
19
+ }
20
+ /**
21
+ * CSP sources a page with AdSense ads adds to the defaults, as
22
+ * `extraSources`. Its scripts come in through the nonce and
23
+ * `'strict-dynamic'`, the strict policy Google supports. Its ads render in
24
+ * frames from hosts Google changes without notice, so any https frame.
25
+ */
26
+ export const ADSENSE_CSP_SOURCES = {
27
+ "frame-src": ["https:"],
28
+ };
29
+ /**
30
+ * Adds AdSense's loader to the page once, with the request's CSP nonce, as
31
+ * Google asks. Browser only: call it from an effect. The loader also shows
32
+ * Google's consent message where the publisher set one up (Privacy &
33
+ * messaging), and places Auto ads if they are on for the site, so keep Auto
34
+ * ads off where the page places its own units.
35
+ */
36
+ export function loadAdSense(client) {
37
+ if (typeof document === "undefined") {
38
+ return;
39
+ }
40
+ const src = adSenseScriptSrc(client);
41
+ if (Array.from(document.scripts).some((script) => script.src === src)) {
42
+ return;
43
+ }
44
+ const script = document.createElement("script");
45
+ script.async = true;
46
+ script.src = src;
47
+ script.crossOrigin = "anonymous";
48
+ const nonce = getCspNonce();
49
+ if (nonce) {
50
+ script.nonce = nonce;
51
+ }
52
+ document.head.append(script);
53
+ }
54
+ const requested = new WeakSet();
55
+ /**
56
+ * Asks AdSense to fill one `<ins class="adsbygoogle">` that is already in the
57
+ * page. Only once per element, so an effect that runs twice (StrictMode)
58
+ * does not queue a second request, which AdSense rejects. Before the loader
59
+ * has run, the request waits in `window.adsbygoogle`.
60
+ */
61
+ export function fillAdSenseSlot(slot) {
62
+ if (requested.has(slot) || slot.hasAttribute("data-adsbygoogle-status")) {
63
+ return;
64
+ }
65
+ requested.add(slot);
66
+ const page = globalThis;
67
+ const queue = page.adsbygoogle ?? [];
68
+ page.adsbygoogle = queue;
69
+ queue.push({});
70
+ }
71
+ /** The ads.txt file (IAB Tech Lab) for the given sellers. Serve with `plainTextResponse`. */
72
+ export function buildAdsTxt(records) {
73
+ return records
74
+ .map(({ domain, accountId, relationship, certificationAuthorityId }) => [domain, accountId, relationship, certificationAuthorityId]
75
+ .filter(Boolean)
76
+ .join(", "))
77
+ .map((line) => `${line}\n`)
78
+ .join("");
79
+ }
80
+ /** Google's TAG certification authority id, the fourth field of its ads.txt line. */
81
+ const GOOGLE_TAG_ID = "f08c47fec0942fa0";
82
+ /** The ads.txt line for an AdSense publisher, from its ad code id (`ca-pub-…`). */
83
+ export function adSenseAdsTxtRecord(client) {
84
+ return {
85
+ domain: "google.com",
86
+ accountId: client.replace(/^ca-/, ""),
87
+ relationship: "DIRECT",
88
+ certificationAuthorityId: GOOGLE_TAG_ID,
89
+ };
90
+ }
@@ -28,6 +28,14 @@ export type ContentSecurityPolicyOptions = {
28
28
  * Frames and workers come from this origin unless the app adds a source.
29
29
  */
30
30
  export declare function buildContentSecurityPolicy({ nonce, dev, extraSources, }: ContentSecurityPolicyOptions): string;
31
+ export type SecurityHeadersOptions = {
32
+ /**
33
+ * `credentialless` (the default) keeps the page cross-origin isolated.
34
+ * `unsafe-none` lets it frame cross-origin content that does not opt in,
35
+ * such as ads: Google's ad tags do not support COEP.
36
+ */
37
+ crossOriginEmbedderPolicy?: "credentialless" | "unsafe-none";
38
+ };
31
39
  /**
32
40
  * Response headers every page should send: HSTS, framing, sniffing,
33
41
  * referrer, permissions and cross-origin isolation, plus the CSP when one
@@ -43,8 +51,9 @@ export declare function buildContentSecurityPolicy({ nonce, dev, extraSources, }
43
51
  * OpenStreetMap tiles and the QR code images send no
44
52
  * Cross-Origin-Resource-Policy, so `require-corp` would block them, while
45
53
  * `credentialless` loads them without cookies and still isolates the page.
54
+ * A page with ads passes `crossOriginEmbedderPolicy: "unsafe-none"`.
46
55
  */
47
- export declare function securityHeaders(contentSecurityPolicy?: string): Record<string, string>;
56
+ export declare function securityHeaders(contentSecurityPolicy?: string, { crossOriginEmbedderPolicy }?: SecurityHeadersOptions): Record<string, string>;
48
57
  /** A fresh nonce for one request's CSP: 16 random bytes, base64. */
49
58
  export declare function generateCspNonce(): string;
50
59
  /**
@@ -62,5 +71,5 @@ export declare function getCspNonce(): string | undefined;
62
71
  * browser asks again each time. An app that wants `no-store` spreads this
63
72
  * and sets its own.
64
73
  */
65
- export declare function requestSecurityHeaders(options: Omit<ContentSecurityPolicyOptions, "nonce">): Record<string, string>;
74
+ export declare function requestSecurityHeaders({ crossOriginEmbedderPolicy, ...cspOptions }: Omit<ContentSecurityPolicyOptions, "nonce"> & SecurityHeadersOptions): Record<string, string>;
66
75
  export {};
@@ -91,8 +91,9 @@ const DISABLED_FEATURES = [
91
91
  * OpenStreetMap tiles and the QR code images send no
92
92
  * Cross-Origin-Resource-Policy, so `require-corp` would block them, while
93
93
  * `credentialless` loads them without cookies and still isolates the page.
94
+ * A page with ads passes `crossOriginEmbedderPolicy: "unsafe-none"`.
94
95
  */
95
- export function securityHeaders(contentSecurityPolicy) {
96
+ export function securityHeaders(contentSecurityPolicy, { crossOriginEmbedderPolicy = "credentialless" } = {}) {
96
97
  return {
97
98
  "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
98
99
  "X-Frame-Options": "SAMEORIGIN",
@@ -101,7 +102,7 @@ export function securityHeaders(contentSecurityPolicy) {
101
102
  "Referrer-Policy": "strict-origin-when-cross-origin",
102
103
  "Permissions-Policy": DISABLED_FEATURES.map((feature) => `${feature}=()`).join(", "),
103
104
  "Cross-Origin-Opener-Policy": "same-origin",
104
- "Cross-Origin-Embedder-Policy": "credentialless",
105
+ "Cross-Origin-Embedder-Policy": crossOriginEmbedderPolicy,
105
106
  ...(contentSecurityPolicy
106
107
  ? { "Content-Security-Policy": contentSecurityPolicy }
107
108
  : {}),
@@ -140,10 +141,10 @@ export function getCspNonce() {
140
141
  * browser asks again each time. An app that wants `no-store` spreads this
141
142
  * and sets its own.
142
143
  */
143
- export function requestSecurityHeaders(options) {
144
+ export function requestSecurityHeaders({ crossOriginEmbedderPolicy, ...cspOptions }) {
144
145
  const nonce = getCspNonce();
145
146
  return {
146
- ...securityHeaders(nonce ? buildContentSecurityPolicy({ nonce, ...options }) : undefined),
147
+ ...securityHeaders(nonce ? buildContentSecurityPolicy({ nonce, ...cspOptions }) : undefined, { crossOriginEmbedderPolicy }),
147
148
  "Cache-Control": "private, no-cache",
148
149
  };
149
150
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "singularity-core",
3
- "version": "0.17.3",
4
- "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, route data, images, formatting, HTTP helpers, theme, cookie notice, SEO, security headers and telemetry.",
3
+ "version": "0.17.4",
4
+ "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, route data, images, formatting, HTTP helpers, theme, cookie notice, SEO, security headers, telemetry and ads.",
5
5
  "type": "module",
6
6
  "author": "Filip",
7
7
  "license": "MIT",
@@ -94,6 +94,10 @@
94
94
  "types": "./dist/http/index.d.ts",
95
95
  "import": "./dist/http/index.js"
96
96
  },
97
+ "./ads": {
98
+ "types": "./dist/ads/index.d.ts",
99
+ "import": "./dist/ads/index.js"
100
+ },
97
101
  "./biome": "./config/biome-app.json",
98
102
  "./package.json": "./package.json"
99
103
  },