@oxyhq/core 21.0.1 → 21.0.2

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.
@@ -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,
@@ -29,6 +30,11 @@ export interface OxyCorsOptions {
29
30
  * `https://app.example.com`, `http://localhost:3000`). These are allowed IN
30
31
  * ADDITION TO the built-in HTTPS Oxy apex origin family. Each is normalized
31
32
  * via `new URL().origin`.
33
+ *
34
+ * An entry that is not a URL, or whose origin is the opaque origin
35
+ * (`exp://…`, `capacitor://…`, `chrome-extension://…`, `file:`, `data:`), is
36
+ * DROPPED with an error log rather than admitted — see `OPAQUE_ORIGIN` for
37
+ * why one such entry would otherwise admit every other one.
32
38
  */
33
39
  appOrigins?: string[];
34
40
  /**
@@ -46,6 +52,41 @@ export interface OxyCorsOptions {
46
52
  /** Preflight cache lifetime in seconds. Default 86400 (24h). */
47
53
  maxAgeSeconds?: number;
48
54
  }
55
+ /**
56
+ * Normalize the configured `appOrigins` into the exact-match set — the
57
+ * CONFIGURE-SIDE half of the opaque-origin guard.
58
+ *
59
+ * An entry that is not a URL, or whose origin is opaque, is dropped and named
60
+ * in an error log. Dropped rather than thrown on because `appOrigins` is
61
+ * deployment configuration — at least one Oxy backend reads it from the
62
+ * environment — and a typo there must cost that one origin its CORS headers,
63
+ * never the whole service its boot. Both failure modes are equally SAFE (the
64
+ * entry is absent from the set either way), so the choice is purely about
65
+ * blast radius, and dropping keeps it to one origin whose requests then fail
66
+ * visibly in the browser.
67
+ *
68
+ * Exported for `__tests__/cors.socket.test.ts` and NOT re-exported from
69
+ * `server/index.ts`, so it is not part of the package's public surface. The
70
+ * two halves of the guard are separately exported because they are separately
71
+ * testable only that way: with this half in place the match-side half is
72
+ * unreachable through `createOxyCors`, so a test driving the public API alone
73
+ * would measure this function twice and the other one never.
74
+ */
75
+ export declare function normalizeAppOrigins(appOrigins: string[]): Set<string>;
76
+ /**
77
+ * Whether `origin` may be echoed back: it is in the built-in HTTPS Oxy apex
78
+ * family, or it exactly matches one of the configured app origins.
79
+ *
80
+ * The opaque-origin refusal here is the MATCH-SIDE half of the guard, and it
81
+ * is what makes the property hold regardless of how `explicit` was built — a
82
+ * set that somehow contains `"null"` still matches nothing, because no
83
+ * incoming origin ever normalizes past this line. `normalizeAppOrigins` is
84
+ * what stops such a set existing today; this is what stops it mattering.
85
+ *
86
+ * Exported for the same reason as `normalizeAppOrigins`, and likewise absent
87
+ * from `server/index.ts`.
88
+ */
89
+ export declare function matchesAllowedOrigin(explicit: ReadonlySet<string>, origin: string): boolean;
49
90
  /**
50
91
  * Create a strict Oxy CORS middleware. See module docs.
51
92
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxyhq/core",
3
- "version": "21.0.1",
3
+ "version": "21.0.2",
4
4
  "description": "OxyHQ SDK Foundation — API client, authentication, cryptographic identity, and shared utilities",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -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
+ });
@@ -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).