@oxyhq/core 21.0.1 → 21.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `createOxyCors` over a REAL socket, plus the two halves of the opaque-origin
3
+ * guard.
4
+ *
5
+ * `cors.test.ts` drives the middleware with a fake `Request`/`Response` pair,
6
+ * which is fine for header bookkeeping but cannot answer the question this
7
+ * suite exists for: what a client actually receives. These tests start an
8
+ * Express app on an ephemeral port and read the response headers off the wire.
9
+ *
10
+ * `node:http` rather than `fetch`: `Origin` is a forbidden header name for
11
+ * `fetch`, so the request under test has to be built by hand.
12
+ */
13
+
14
+ import http from 'node:http';
15
+ import type { AddressInfo } from 'node:net';
16
+ import express from 'express';
17
+ import { configureLogger, resetLoggerConfig } from '../../logger';
18
+ import type { LogEntry } from '../../logger';
19
+ import { createOxyCors, matchesAllowedOrigin, normalizeAppOrigins } from '../cors';
20
+ import type { OxyCorsOptions } from '../cors';
21
+
22
+ interface CorsResponse {
23
+ status: number;
24
+ allowOrigin: string | undefined;
25
+ allowCredentials: string | undefined;
26
+ }
27
+
28
+ /** Start an Express app carrying `createOxyCors(options)` on an ephemeral port. */
29
+ async function startServer(options: OxyCorsOptions): Promise<http.Server> {
30
+ const app = express();
31
+ app.use(createOxyCors(options));
32
+ app.get('/catalogue', (_req, res) => {
33
+ res.json({ ok: true });
34
+ });
35
+ const server = http.createServer(app);
36
+ await new Promise<void>((resolve) => {
37
+ server.listen(0, '127.0.0.1', resolve);
38
+ });
39
+ return server;
40
+ }
41
+
42
+ async function stopServer(server: http.Server): Promise<void> {
43
+ await new Promise<void>((resolve, reject) => {
44
+ server.close((error) => (error ? reject(error) : resolve()));
45
+ });
46
+ }
47
+
48
+ /** Issue a real request carrying `Origin` and read the CORS headers back. */
49
+ function requestWithOrigin(
50
+ server: http.Server,
51
+ method: 'GET' | 'OPTIONS',
52
+ origin: string,
53
+ ): Promise<CorsResponse> {
54
+ const { port } = server.address() as AddressInfo;
55
+ return new Promise((resolve, reject) => {
56
+ const req = http.request(
57
+ {
58
+ host: '127.0.0.1',
59
+ port,
60
+ method,
61
+ path: '/catalogue',
62
+ headers: { Origin: origin, 'Access-Control-Request-Method': 'GET' },
63
+ },
64
+ (res) => {
65
+ res.resume();
66
+ res.on('end', () => {
67
+ resolve({
68
+ status: res.statusCode ?? 0,
69
+ allowOrigin: res.headers['access-control-allow-origin'],
70
+ allowCredentials: res.headers['access-control-allow-credentials'],
71
+ });
72
+ });
73
+ res.on('error', reject);
74
+ },
75
+ );
76
+ req.on('error', reject);
77
+ req.end();
78
+ });
79
+ }
80
+
81
+ /**
82
+ * The exact shape that was live: one custom-scheme entry alongside ordinary
83
+ * ones. Every origin below normalizes to the opaque origin, so before the fix
84
+ * the `exp://` entry admitted all of them.
85
+ */
86
+ const CONFIGURED_WITH_OPAQUE_ENTRY = ['https://app.example.com', 'exp://localhost:8150'];
87
+ const OTHER_OPAQUE_SCHEME_ORIGINS = [
88
+ 'vscode-webview://abc123',
89
+ 'capacitor://localhost',
90
+ 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
91
+ 'file://',
92
+ ];
93
+
94
+ describe('createOxyCors over a real socket', () => {
95
+ let server: http.Server;
96
+
97
+ beforeAll(async () => {
98
+ // The dropped entry logs at error level by design; that log is asserted in
99
+ // the configure-side suite below. Swallow it here so this suite's output
100
+ // carries only its own failures.
101
+ configureLogger({ sink: () => undefined });
102
+ server = await startServer({ appOrigins: CONFIGURED_WITH_OPAQUE_ENTRY });
103
+ resetLoggerConfig();
104
+ });
105
+
106
+ afterAll(async () => {
107
+ await stopServer(server);
108
+ });
109
+
110
+ it('POSITIVE CONTROL: a configured https origin gets its headers over the wire', async () => {
111
+ for (const method of ['GET', 'OPTIONS'] as const) {
112
+ const res = await requestWithOrigin(server, method, 'https://app.example.com');
113
+ expect(res.allowOrigin).toBe('https://app.example.com');
114
+ expect(res.allowCredentials).toBe('true');
115
+ }
116
+ });
117
+
118
+ it('POSITIVE CONTROL: the built-in Oxy apex family still gets its headers', async () => {
119
+ const res = await requestWithOrigin(server, 'GET', 'https://auth.oxy.so');
120
+ expect(res.allowOrigin).toBe('https://auth.oxy.so');
121
+ expect(res.allowCredentials).toBe('true');
122
+ });
123
+
124
+ it('a custom-scheme origin is NOT admitted by a custom-scheme allowlist entry', async () => {
125
+ for (const origin of OTHER_OPAQUE_SCHEME_ORIGINS) {
126
+ for (const method of ['GET', 'OPTIONS'] as const) {
127
+ const res = await requestWithOrigin(server, method, origin);
128
+ expect(res.allowOrigin).toBeUndefined();
129
+ expect(res.allowCredentials).toBeUndefined();
130
+ }
131
+ }
132
+ });
133
+
134
+ it('the opaque-origin entry does not admit even ITSELF', async () => {
135
+ const res = await requestWithOrigin(server, 'GET', 'exp://localhost:8150');
136
+ expect(res.allowOrigin).toBeUndefined();
137
+ expect(res.allowCredentials).toBeUndefined();
138
+ });
139
+
140
+ it('NEGATIVE CONTROL: a literal `Origin: null` is refused, as it always was', async () => {
141
+ const res = await requestWithOrigin(server, 'GET', 'null');
142
+ expect(res.allowOrigin).toBeUndefined();
143
+ expect(res.allowCredentials).toBeUndefined();
144
+ });
145
+
146
+ it('NEGATIVE CONTROL: an unrelated https origin is refused', async () => {
147
+ const res = await requestWithOrigin(server, 'GET', 'https://evil.example.com');
148
+ expect(res.allowOrigin).toBeUndefined();
149
+ expect(res.allowCredentials).toBeUndefined();
150
+ });
151
+ });
152
+
153
+ /**
154
+ * The CONFIGURE-SIDE half. Its behavioural effect is masked by the match-side
155
+ * half — with both in place, deleting this one changes no response — so what
156
+ * this suite asserts is the observable the drop-rather-than-throw decision
157
+ * rests on: the entry is named in an error log, and nothing else stops.
158
+ */
159
+ describe('normalizeAppOrigins (configure side)', () => {
160
+ let entries: LogEntry[];
161
+
162
+ beforeEach(() => {
163
+ entries = [];
164
+ configureLogger({ sink: (entry) => entries.push(entry) });
165
+ });
166
+
167
+ afterEach(() => {
168
+ resetLoggerConfig();
169
+ });
170
+
171
+ it('drops an opaque-origin entry from the set and names it in an error log', () => {
172
+ const explicit = normalizeAppOrigins(CONFIGURED_WITH_OPAQUE_ENTRY);
173
+
174
+ expect([...explicit]).toEqual(['https://app.example.com']);
175
+ expect(explicit.has('null')).toBe(false);
176
+
177
+ const dropped = entries.filter((entry) => entry.level === 'error');
178
+ expect(dropped).toHaveLength(1);
179
+ expect(dropped[0]?.context?.entry).toBe('exp://localhost:8150');
180
+ expect(dropped[0]?.message).toContain('no origin to match against');
181
+ });
182
+
183
+ it('drops an entry that is not a URL at all, separately named', () => {
184
+ const explicit = normalizeAppOrigins(['not a url', 'https://app.example.com']);
185
+
186
+ expect([...explicit]).toEqual(['https://app.example.com']);
187
+ const dropped = entries.filter((entry) => entry.level === 'error');
188
+ expect(dropped).toHaveLength(1);
189
+ expect(dropped[0]?.context?.entry).toBe('not a url');
190
+ expect(dropped[0]?.message).toContain('not a URL');
191
+ });
192
+
193
+ it('VACUITY FLOOR: a wholly valid list is dropped from silently', () => {
194
+ const explicit = normalizeAppOrigins(['https://app.example.com', 'http://localhost:3000']);
195
+
196
+ expect([...explicit].sort()).toEqual(['http://localhost:3000', 'https://app.example.com']);
197
+ expect(entries.filter((entry) => entry.level === 'error')).toHaveLength(0);
198
+ });
199
+ });
200
+
201
+ /**
202
+ * The MATCH-SIDE half, driven with the hostile precondition the configure side
203
+ * prevents: a set that already contains the opaque origin. This is the only
204
+ * way to observe this half — through `createOxyCors` it is unreachable, so a
205
+ * test there would measure `normalizeAppOrigins` and report on this.
206
+ */
207
+ describe('matchesAllowedOrigin (match side)', () => {
208
+ const poisoned: ReadonlySet<string> = new Set(['null', 'https://app.example.com']);
209
+
210
+ it('refuses every opaque-scheme origin even against a set containing "null"', () => {
211
+ for (const origin of [...OTHER_OPAQUE_SCHEME_ORIGINS, 'exp://localhost:8150']) {
212
+ expect(matchesAllowedOrigin(poisoned, origin)).toBe(false);
213
+ }
214
+ });
215
+
216
+ it('POSITIVE CONTROL: the same poisoned set still matches its real entry', () => {
217
+ expect(matchesAllowedOrigin(poisoned, 'https://app.example.com')).toBe(true);
218
+ expect(matchesAllowedOrigin(poisoned, 'https://auth.oxy.so')).toBe(true);
219
+ expect(matchesAllowedOrigin(poisoned, 'https://evil.example.com')).toBe(false);
220
+ });
221
+
222
+ it('NEGATIVE CONTROL: a literal `null` never reaches the set lookup either', () => {
223
+ expect(matchesAllowedOrigin(poisoned, 'null')).toBe(false);
224
+ });
225
+ });
@@ -3,7 +3,10 @@ import {
3
3
  buildOxyCspDirectives,
4
4
  buildOxyPagesHeaders,
5
5
  createOxySecurityHeaders,
6
+ cspSourcesFor,
7
+ extractInlineScripts,
6
8
  formatOxyCspPolicy,
9
+ inlineScriptCspHash,
7
10
  OXY_CSP_BASELINE,
8
11
  type OxyCspExtensions,
9
12
  } from '../securityHeaders';
@@ -27,14 +30,11 @@ function renderPolicy(options: Parameters<typeof createOxySecurityHeaders>[0]):
27
30
  return headers['Content-Security-Policy'] ?? '';
28
31
  }
29
32
 
30
- /** The sources of one directive, parsed back out of the rendered header. */
31
- function policySources(policy: string, directive: string): string[] {
32
- const found = policy
33
- .split(';')
34
- .map((segment) => segment.trim())
35
- .find((segment) => segment === directive || segment.startsWith(`${directive} `));
36
- if (found === undefined) return [];
37
- return found.split(/\s+/).slice(1);
33
+ /** The CSP value parsed back out of a Cloudflare Pages `_headers` block. */
34
+ function cspOf(block: string): string {
35
+ const line = block.split('\n').find((entry) => entry.trim().startsWith('Content-Security-Policy:'));
36
+ if (line === undefined) throw new Error('no Content-Security-Policy line in _headers block');
37
+ return line.trim().slice('Content-Security-Policy:'.length).trim();
38
38
  }
39
39
 
40
40
  describe('@oxyhq/core/server buildOxyCspDirectives', () => {
@@ -179,12 +179,116 @@ describe('@oxyhq/core/server buildOxyPagesHeaders', () => {
179
179
  });
180
180
  });
181
181
 
182
+ /**
183
+ * The inline script Expo Router's static export emits, verbatim, and the hash
184
+ * `accounts.oxy.so` was measured rejecting on 2026-08-21. Pinned as a LITERAL
185
+ * rather than recomputed: a test that derives the expected value the same way
186
+ * the code does would pass against any hashing bug they share.
187
+ */
188
+ const EXPO_HYDRATE_SCRIPT = 'globalThis.__EXPO_ROUTER_HYDRATE__=true;';
189
+ const EXPO_HYDRATE_SHA256 = "'sha256-67fhrP0+BkBqmgGGXTtgiVO/9EQs3QruYNU/7fnRkI8='";
190
+
191
+ /** A static Expo export's HTML, reduced to the parts that decide the policy. */
192
+ function expoExportHtml(body = EXPO_HYDRATE_SCRIPT): string {
193
+ return [
194
+ '<!DOCTYPE html><html><head>',
195
+ '<script src="/_expo/static/js/web/entry-abc.js" defer></script>',
196
+ `<script type="module">${body}</script>`,
197
+ '</head><body><div id="root"></div></body></html>',
198
+ ].join('');
199
+ }
200
+
201
+ describe('@oxyhq/core/server extractInlineScripts', () => {
202
+ it('returns inline bodies and skips external scripts', () => {
203
+ expect(extractInlineScripts(expoExportHtml())).toEqual([EXPO_HYDRATE_SCRIPT]);
204
+ });
205
+
206
+ it('does not let a ">" inside an attribute value truncate an inline tag', () => {
207
+ // Truncating here does not throw: the body window shifts right and the hash
208
+ // is taken over `b'>globalThis…`, which allows nothing. Note the attribute
209
+ // must precede the body for this to discriminate — an EXTERNAL script whose
210
+ // `src` comes first is skipped either way, which is why the beacon shape is
211
+ // not the case under test here.
212
+ const html = `<script type="module" data-x='a>b'>${EXPO_HYDRATE_SCRIPT}</script>`;
213
+ expect(extractInlineScripts(html)).toEqual([EXPO_HYDRATE_SCRIPT]);
214
+ });
215
+
216
+ it('still recognizes a src that follows a ">"-bearing attribute', () => {
217
+ // The mirror failure: truncation hides `src` from the attribute slice, so
218
+ // an external script is mistaken for an inline one and contributes a hash
219
+ // over a fragment of its own tag.
220
+ expect(extractInlineScripts(`<script data-x='a>b' src="/entry.js"></script>`)).toEqual([]);
221
+ });
222
+
223
+ it('hashes the exact bytes, so whitespace changes the source', () => {
224
+ expect(inlineScriptCspHash(EXPO_HYDRATE_SCRIPT)).toBe(EXPO_HYDRATE_SHA256);
225
+ expect(inlineScriptCspHash(` ${EXPO_HYDRATE_SCRIPT}`)).not.toBe(EXPO_HYDRATE_SHA256);
226
+ });
227
+ });
228
+
229
+ describe('@oxyhq/core/server buildOxyPagesHeaders inline-script hashes', () => {
230
+ it('allows the built HTML\'s inline script by hash', () => {
231
+ const block = buildOxyPagesHeaders({ html: [expoExportHtml()] });
232
+ expect(cspSourcesFor(cspOf(block), 'script-src')).toEqual([
233
+ "'self'",
234
+ CLOUDFLARE_SCRIPT_HOST,
235
+ EXPO_HYDRATE_SHA256,
236
+ ]);
237
+ });
238
+
239
+ it('emits no hash at all when the build has no inline script', () => {
240
+ // Negative control for the assertion above: without it, "contains a
241
+ // sha256-" would be satisfied by a builder that hashed unconditionally.
242
+ const block = buildOxyPagesHeaders({ html: ['<html><body>nothing inline</body></html>'] });
243
+ expect(cspOf(block)).not.toContain('sha256-');
244
+ expect(cspSourcesFor(cspOf(block), 'script-src')).toEqual(["'self'", CLOUDFLARE_SCRIPT_HOST]);
245
+ });
246
+
247
+ it('dedupes one route-per-file export down to a single hash', () => {
248
+ const block = buildOxyPagesHeaders({
249
+ html: [expoExportHtml(), expoExportHtml(), expoExportHtml()],
250
+ });
251
+ expect(cspOf(block).match(/sha256-/g)).toHaveLength(1);
252
+ });
253
+
254
+ it('keeps per-app extensions and the baseline alongside the hash', () => {
255
+ const block = buildOxyPagesHeaders({
256
+ csp: { imgSrc: ['blob:'], connectSrc: ['blob:'] },
257
+ html: [expoExportHtml()],
258
+ });
259
+ expect(cspSourcesFor(cspOf(block), 'img-src')).toContain('blob:');
260
+ expect(cspSourcesFor(cspOf(block), 'script-src')).toContain(EXPO_HYDRATE_SHA256);
261
+ expect(cspSourcesFor(cspOf(block), 'script-src')).toContain("'self'");
262
+ });
263
+
264
+ it('never hashes styles, which would disable style-src unsafe-inline', () => {
265
+ // A style hash would neutralize 'unsafe-inline' and render every
266
+ // react-native-web app unstyled — the one directive that must stay open.
267
+ const block = buildOxyPagesHeaders({
268
+ html: ['<html><head><style>.a{color:red}</style></head></html>'],
269
+ });
270
+ expect(cspSourcesFor(cspOf(block), 'style-src')).toEqual(["'self'", "'unsafe-inline'"]);
271
+ expect(cspOf(block)).not.toContain('sha256-');
272
+ });
273
+
274
+ it('refuses a build whose inline scripts vary per route', () => {
275
+ // An Expo route loader emits `__EXPO_ROUTER_LOADER_DATA__` with different
276
+ // bytes per route. The hashes would still be correct; the policy would grow
277
+ // with the route count. That has to be a decision, so it fails loudly.
278
+ const perRoute = Array.from({ length: 9 }, (_, index) =>
279
+ expoExportHtml(`globalThis.__EXPO_ROUTER_LOADER_DATA__={"r":${index}};`),
280
+ );
281
+ expect(() => buildOxyPagesHeaders({ html: perRoute })).toThrow(RangeError);
282
+ expect(() => buildOxyPagesHeaders({ html: perRoute.slice(0, 8) })).not.toThrow();
283
+ });
284
+ });
285
+
182
286
  describe('@oxyhq/core/server createOxySecurityHeaders', () => {
183
287
  it('sends the resolved baseline as a real Content-Security-Policy header', () => {
184
288
  const policy = renderPolicy({});
185
289
 
186
- expect(policySources(policy, 'script-src')).toEqual(["'self'", CLOUDFLARE_SCRIPT_HOST]);
187
- expect(policySources(policy, 'connect-src')).toEqual([
290
+ expect(cspSourcesFor(policy, 'script-src')).toEqual(["'self'", CLOUDFLARE_SCRIPT_HOST]);
291
+ expect(cspSourcesFor(policy, 'connect-src')).toEqual([
188
292
  "'self'",
189
293
  CLOUDFLARE_REPORT_HOST,
190
294
  'https://api.oxy.so',
@@ -202,7 +306,7 @@ describe('@oxyhq/core/server createOxySecurityHeaders', () => {
202
306
  },
203
307
  });
204
308
 
205
- expect(policySources(policy, 'connect-src')).toEqual([
309
+ expect(cspSourcesFor(policy, 'connect-src')).toEqual([
206
310
  "'self'",
207
311
  CLOUDFLARE_REPORT_HOST,
208
312
  'https://api.oxy.so',
@@ -211,7 +315,7 @@ describe('@oxyhq/core/server createOxySecurityHeaders', () => {
211
315
  'https://api.mention.earth',
212
316
  'wss://api.mention.earth',
213
317
  ]);
214
- expect(policySources(policy, 'frame-src')).toEqual([
318
+ expect(cspSourcesFor(policy, 'frame-src')).toEqual([
215
319
  "'self'",
216
320
  'https://www.youtube-nocookie.com',
217
321
  ]);
@@ -15,6 +15,7 @@
15
15
  * one-label subdomains such as `auth.oxy.so`, `api.oxy.so`,
16
16
  * `accounts.oxy.so`, `console.oxy.so`, and `inbox.oxy.so`,
17
17
  * - allows the caller's explicit `appOrigins`,
18
+ * - REFUSES the opaque origin on both sides (see `OPAQUE_ORIGIN`),
18
19
  * - DENIES everything else (no reflection, never a wildcard with credentials),
19
20
  * - echoes back the EXACT matched origin (so credentialed requests work) and
20
21
  * sets `Vary: Origin` for correct caching,
@@ -24,8 +25,11 @@
24
25
  */
25
26
 
26
27
  import type { NextFunction, Request, RequestHandler, Response } from 'express';
28
+ import { createLogger } from '../logger';
27
29
  import { CENTRAL_IDP_APEX } from '../utils/authWebUrl';
28
30
 
31
+ const log = createLogger('OxyCors');
32
+
29
33
  /** Default HTTP methods allowed across origins. */
30
34
  const DEFAULT_ALLOWED_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'];
31
35
 
@@ -52,6 +56,11 @@ export interface OxyCorsOptions {
52
56
  * `https://app.example.com`, `http://localhost:3000`). These are allowed IN
53
57
  * ADDITION TO the built-in HTTPS Oxy apex origin family. Each is normalized
54
58
  * via `new URL().origin`.
59
+ *
60
+ * An entry that is not a URL, or whose origin is the opaque origin
61
+ * (`exp://…`, `capacitor://…`, `chrome-extension://…`, `file:`, `data:`), is
62
+ * DROPPED with an error log rather than admitted — see `OPAQUE_ORIGIN` for
63
+ * why one such entry would otherwise admit every other one.
55
64
  */
56
65
  appOrigins?: string[];
57
66
  /**
@@ -94,6 +103,30 @@ function isOxyFamilyOrigin(candidate: string): boolean {
94
103
  }
95
104
  }
96
105
 
106
+ /**
107
+ * The URL standard's serialization of an OPAQUE origin: the literal string
108
+ * `"null"`, which `new URL(x).origin` returns for every scheme that has no
109
+ * origin to speak of — `exp:`, `capacitor:`, `chrome-extension:`,
110
+ * `vscode-webview:`, and also `file:`, `data:` and `about:`.
111
+ *
112
+ * This value is why an allowlist may never store it. Every such scheme
113
+ * normalizes to the SAME `"null"`, so a set built by normalization cannot tell
114
+ * them apart: ONE opaque entry admits ALL of them. With credentials on and the
115
+ * raw header echoed back, a single `myapp://` in `appOrigins` turned this
116
+ * helper into "allow any custom-scheme browsing context" — measured live, an
117
+ * `exp://localhost:8150` entry answered `Origin: vscode-webview://…` with
118
+ * `access-control-allow-origin: vscode-webview://…` and
119
+ * `access-control-allow-credentials: true`.
120
+ *
121
+ * There is deliberately no escape hatch that matches such an origin by raw
122
+ * string instead. Admitting a custom-scheme browsing context to a CREDENTIALED
123
+ * allowlist is a distinct decision with its own threat model, and it must not
124
+ * arrive as a side effect of someone adding one line to `appOrigins`. Note
125
+ * also that a native client is not subject to CORS at all — React Native sends
126
+ * no `Origin` header — so a mobile app never needs an entry here.
127
+ */
128
+ const OPAQUE_ORIGIN = 'null';
129
+
97
130
  /** Normalize a raw origin string to its canonical `scheme://host[:port]` form. */
98
131
  function normalizeOrigin(raw: string): string | null {
99
132
  try {
@@ -104,21 +137,63 @@ function normalizeOrigin(raw: string): string | null {
104
137
  }
105
138
 
106
139
  /**
107
- * Build the origin-matching predicate: true iff `origin` is in the built-in
108
- * HTTPS Oxy apex family OR exactly matches one of the configured app origins.
140
+ * Normalize the configured `appOrigins` into the exact-match set the
141
+ * CONFIGURE-SIDE half of the opaque-origin guard.
142
+ *
143
+ * An entry that is not a URL, or whose origin is opaque, is dropped and named
144
+ * in an error log. Dropped rather than thrown on because `appOrigins` is
145
+ * deployment configuration — at least one Oxy backend reads it from the
146
+ * environment — and a typo there must cost that one origin its CORS headers,
147
+ * never the whole service its boot. Both failure modes are equally SAFE (the
148
+ * entry is absent from the set either way), so the choice is purely about
149
+ * blast radius, and dropping keeps it to one origin whose requests then fail
150
+ * visibly in the browser.
151
+ *
152
+ * Exported for `__tests__/cors.socket.test.ts` and NOT re-exported from
153
+ * `server/index.ts`, so it is not part of the package's public surface. The
154
+ * two halves of the guard are separately exported because they are separately
155
+ * testable only that way: with this half in place the match-side half is
156
+ * unreachable through `createOxyCors`, so a test driving the public API alone
157
+ * would measure this function twice and the other one never.
109
158
  */
110
- function buildOriginAllowed(appOrigins: string[]): (origin: string) => boolean {
159
+ export function normalizeAppOrigins(appOrigins: string[]): Set<string> {
111
160
  const explicit = new Set<string>();
112
161
  for (const raw of appOrigins) {
113
162
  const normalized = normalizeOrigin(raw);
114
- if (normalized) explicit.add(normalized);
163
+ if (normalized === null) {
164
+ log.error('CORS allowlist entry ignored: it is not a URL', undefined, { entry: raw });
165
+ continue;
166
+ }
167
+ if (normalized === OPAQUE_ORIGIN) {
168
+ log.error('CORS allowlist entry ignored: it has no origin to match against', undefined, {
169
+ entry: raw,
170
+ });
171
+ continue;
172
+ }
173
+ explicit.add(normalized);
115
174
  }
116
- return (origin: string): boolean => {
117
- const normalized = normalizeOrigin(origin);
118
- if (normalized === null) return false;
119
- if (explicit.has(normalized)) return true;
120
- return isOxyFamilyOrigin(normalized);
121
- };
175
+ return explicit;
176
+ }
177
+
178
+ /**
179
+ * Whether `origin` may be echoed back: it is in the built-in HTTPS Oxy apex
180
+ * family, or it exactly matches one of the configured app origins.
181
+ *
182
+ * The opaque-origin refusal here is the MATCH-SIDE half of the guard, and it
183
+ * is what makes the property hold regardless of how `explicit` was built — a
184
+ * set that somehow contains `"null"` still matches nothing, because no
185
+ * incoming origin ever normalizes past this line. `normalizeAppOrigins` is
186
+ * what stops such a set existing today; this is what stops it mattering.
187
+ *
188
+ * Exported for the same reason as `normalizeAppOrigins`, and likewise absent
189
+ * from `server/index.ts`.
190
+ */
191
+ export function matchesAllowedOrigin(explicit: ReadonlySet<string>, origin: string): boolean {
192
+ const normalized = normalizeOrigin(origin);
193
+ if (normalized === null) return false;
194
+ if (normalized === OPAQUE_ORIGIN) return false;
195
+ if (explicit.has(normalized)) return true;
196
+ return isOxyFamilyOrigin(normalized);
122
197
  }
123
198
 
124
199
  /**
@@ -139,7 +214,7 @@ export function createOxyCors(options: OxyCorsOptions = {}): RequestHandler {
139
214
  maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS,
140
215
  } = options;
141
216
 
142
- const isOriginAllowed = buildOriginAllowed(appOrigins);
217
+ const explicitOrigins = normalizeAppOrigins(appOrigins);
143
218
  const methodsHeader = methods.join(', ');
144
219
  const allowedHeadersHeader = allowedHeaders.join(', ');
145
220
  const exposedHeadersHeader = exposedHeaders.join(', ');
@@ -161,7 +236,7 @@ export function createOxyCors(options: OxyCorsOptions = {}): RequestHandler {
161
236
  // Origin is present. Caching correctness: this response varies by Origin.
162
237
  res.setHeader('Vary', 'Origin');
163
238
 
164
- if (!isOriginAllowed(origin)) {
239
+ if (!matchesAllowedOrigin(explicitOrigins, origin)) {
165
240
  // DENY: do NOT reflect the origin, do NOT emit a wildcard. The browser
166
241
  // will block the cross-origin read. Preflights for denied origins get a
167
242
  // 204 with no CORS headers (the actual request then fails CORS).
@@ -71,11 +71,20 @@ export type { OxyCorsOptions } from './cors';
71
71
 
72
72
  // Shared Helmet + Content-Security-Policy baseline (Cloudflare Insights beacon,
73
73
  // Oxy API/CDN origins) with additive, per-app extensions.
74
+ //
75
+ // `extractInlineScripts` / `inlineScriptCspHash` / `cspSourcesFor` are exported
76
+ // so a post-deploy gate can ask the SERVED document and the SERVED policy the
77
+ // same questions `buildOxyPagesHeaders` asked the built ones. A gate that
78
+ // re-implemented the scan or the parse would be testing its own copy, and would
79
+ // agree with a broken original.
74
80
  export {
75
81
  buildOxyCspDirectives,
76
82
  buildOxyPagesHeaders,
77
83
  createOxySecurityHeaders,
84
+ cspSourcesFor,
85
+ extractInlineScripts,
78
86
  formatOxyCspPolicy,
87
+ inlineScriptCspHash,
79
88
  OXY_CSP_BASELINE,
80
89
  } from './securityHeaders';
81
90
  export type {