|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The conditional-request headers the server's own doors speak must pass the |
| 5 | + * default CORS policy — driven through the real adapter and the real |
| 6 | + * `hono/cors` middleware (`app.request`), never a captured config. |
| 7 | + * |
| 8 | + * The doors: the `/meta` draft save reads `If-Match` and `If-None-Match: *` |
| 9 | + * (`@objectstack/rest`'s `metaSaveRequestOptions`), and the metadata reads |
| 10 | + * answer `ETag` and a bodiless `304` to an `If-None-Match` that names it |
| 11 | + * (`@objectstack/client`'s cached reads send it back). A cross-origin browser |
| 12 | + * client the policy admits must be able to send both conditional headers and |
| 13 | + * read the `ETag`: a preflight that does not allow `If-None-Match` fails the |
| 14 | + * request in the browser with a bare "Failed to fetch" before anything reaches |
| 15 | + * the server, and an `ETag` the policy does not expose reads as `null` in JS. |
| 16 | + * |
| 17 | + * The defaults are {@link DEFAULT_CORS_ALLOW_HEADERS} and |
| 18 | + * {@link DEFAULT_CORS_EXPOSE_HEADERS}; `@objectstack/hono`'s `createHonoApp` |
| 19 | + * applies the same two constants and carries its own pin. |
| 20 | + */ |
| 21 | + |
| 22 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 23 | +import type { PluginContext } from '@objectstack/core'; |
| 24 | + |
| 25 | +import type { HonoCorsOptions } from './adapter'; |
| 26 | +import { HonoServerPlugin } from './hono-plugin'; |
| 27 | + |
| 28 | +const ALLOWED = 'https://app.example.com'; |
| 29 | +const FOREIGN = 'https://other.example'; |
| 30 | + |
| 31 | +/** Every variable the CORS block reads, canonical and legacy spellings. */ |
| 32 | +const CORS_ENV = [ |
| 33 | + 'OS_CORS_ENABLED', 'CORS_ENABLED', |
| 34 | + 'OS_CORS_ORIGIN', 'CORS_ORIGIN', |
| 35 | + 'OS_CORS_CREDENTIALS', 'CORS_CREDENTIALS', |
| 36 | + 'OS_CORS_MAX_AGE', 'CORS_MAX_AGE', |
| 37 | + 'NODE_ENV', |
| 38 | +] as const; |
| 39 | + |
| 40 | +let saved: Record<string, string | undefined> = {}; |
| 41 | + |
| 42 | +beforeEach(() => { |
| 43 | + saved = {}; |
| 44 | + for (const name of CORS_ENV) { |
| 45 | + saved[name] = process.env[name]; |
| 46 | + delete process.env[name]; |
| 47 | + } |
| 48 | + process.env.NODE_ENV = 'production'; |
| 49 | +}); |
| 50 | + |
| 51 | +afterEach(() => { |
| 52 | + for (const name of CORS_ENV) { |
| 53 | + if (saved[name] === undefined) delete process.env[name]; |
| 54 | + else process.env[name] = saved[name]; |
| 55 | + } |
| 56 | +}); |
| 57 | + |
| 58 | +function fakeCtx(): PluginContext { |
| 59 | + const services = new Map<string, unknown>(); |
| 60 | + return { |
| 61 | + logger: { debug() {}, info() {}, warn() {}, error() {} }, |
| 62 | + registerService: (name: string, svc: unknown) => services.set(name, svc), |
| 63 | + getService: (name: string) => services.get(name), |
| 64 | + hook: () => {}, |
| 65 | + getKernel: () => ({}), |
| 66 | + } as unknown as PluginContext; |
| 67 | +} |
| 68 | + |
| 69 | +interface ProbeContext { |
| 70 | + header(name: string, value: string): void; |
| 71 | + json(body: unknown): Response; |
| 72 | +} |
| 73 | + |
| 74 | +interface RawApp { |
| 75 | + get(path: string, handler: (c: ProbeContext) => Response): unknown; |
| 76 | + put(path: string, handler: (c: ProbeContext) => Response): unknown; |
| 77 | + request(path: string, init?: RequestInit): Promise<Response>; |
| 78 | +} |
| 79 | + |
| 80 | +const META_ITEM = '/api/v1/meta/page/zz_cors_probe'; |
| 81 | + |
| 82 | +/** |
| 83 | + * Run the real `init()` with one admitted origin, then mount a stand-in for |
| 84 | + * the metadata item door behind its middleware: the read answers an `ETag`, |
| 85 | + * the draft save answers `200`. |
| 86 | + */ |
| 87 | +async function boot(cors: HonoCorsOptions = {}): Promise<RawApp> { |
| 88 | + const plugin = new HonoServerPlugin({ |
| 89 | + port: 0, |
| 90 | + serverTiming: false, |
| 91 | + cors: { origins: [ALLOWED], ...cors }, |
| 92 | + }); |
| 93 | + await plugin.init(fakeCtx()); |
| 94 | + const rawApp = (plugin as unknown as { server: { getRawApp(): RawApp } }).server.getRawApp(); |
| 95 | + rawApp.get(META_ITEM, (c) => { |
| 96 | + c.header('ETag', '"v1"'); |
| 97 | + return c.json({ name: 'zz_cors_probe' }); |
| 98 | + }); |
| 99 | + rawApp.put(META_ITEM, (c) => c.json({ ok: true })); |
| 100 | + return rawApp; |
| 101 | +} |
| 102 | + |
| 103 | +/** The browser's preflight ahead of the first-draft save `PUT …?mode=draft` + `If-None-Match: *`. */ |
| 104 | +function draftPreflight(app: RawApp, origin: string, requested: string): Promise<Response> { |
| 105 | + return app.request(`${META_ITEM}?mode=draft`, { |
| 106 | + method: 'OPTIONS', |
| 107 | + headers: { |
| 108 | + Origin: origin, |
| 109 | + 'Access-Control-Request-Method': 'PUT', |
| 110 | + 'Access-Control-Request-Headers': requested, |
| 111 | + }, |
| 112 | + }); |
| 113 | +} |
| 114 | + |
| 115 | +/** A comma-separated header value as a lower-cased list. */ |
| 116 | +function listOf(res: Response, name: string): string[] { |
| 117 | + return (res.headers.get(name) ?? '') |
| 118 | + .split(',') |
| 119 | + .map((s) => s.trim().toLowerCase()) |
| 120 | + .filter(Boolean); |
| 121 | +} |
| 122 | + |
| 123 | +describe('the default CORS policy admits the conditional headers the metadata doors speak', () => { |
| 124 | + it('answers a preflight asking If-None-Match with it in Access-Control-Allow-Headers', async () => { |
| 125 | + const app = await boot(); |
| 126 | + const res = await draftPreflight(app, ALLOWED, 'content-type,if-none-match,authorization'); |
| 127 | + expect(res.status).toBe(204); |
| 128 | + expect(res.headers.get('access-control-allow-origin')).toBe(ALLOWED); |
| 129 | + expect(listOf(res, 'access-control-allow-headers')).toContain('if-none-match'); |
| 130 | + }); |
| 131 | + |
| 132 | + it('exposes ETag on a cross-origin metadata read, so cross-origin JS can read the version', async () => { |
| 133 | + const app = await boot(); |
| 134 | + const res = await app.request(META_ITEM, { headers: { Origin: ALLOWED } }); |
| 135 | + expect(res.status).toBe(200); |
| 136 | + expect(res.headers.get('access-control-allow-origin')).toBe(ALLOWED); |
| 137 | + expect(res.headers.get('etag')).toBe('"v1"'); |
| 138 | + expect(listOf(res, 'access-control-expose-headers')).toContain('etag'); |
| 139 | + }); |
| 140 | +}); |
| 141 | + |
| 142 | +describe('controls: what the two entries leave unchanged', () => { |
| 143 | + it('still answers a disallowed origin with no Access-Control-Allow-Origin, on the preflight and on the read', async () => { |
| 144 | + const app = await boot(); |
| 145 | + const preflight = await draftPreflight(app, FOREIGN, 'content-type,if-none-match'); |
| 146 | + expect(preflight.headers.get('access-control-allow-origin')).toBeNull(); |
| 147 | + const read = await app.request(META_ITEM, { headers: { Origin: FOREIGN } }); |
| 148 | + expect(read.headers.get('access-control-allow-origin')).toBeNull(); |
| 149 | + }); |
| 150 | + |
| 151 | + it('keeps If-Match in the allow list and the existing exposed headers in the expose list', async () => { |
| 152 | + const app = await boot(); |
| 153 | + const preflight = await draftPreflight(app, ALLOWED, 'content-type,if-match'); |
| 154 | + expect(listOf(preflight, 'access-control-allow-headers')).toContain('if-match'); |
| 155 | + const read = await app.request(META_ITEM, { headers: { Origin: ALLOWED } }); |
| 156 | + const exposed = listOf(read, 'access-control-expose-headers'); |
| 157 | + expect(exposed).toContain('set-auth-token'); |
| 158 | + expect(exposed).toContain('x-objectstack-dropped-fields'); |
| 159 | + }); |
| 160 | + |
| 161 | + it('lets a custom allowHeaders still replace the default (If-None-Match then only if listed)', async () => { |
| 162 | + const app = await boot({ allowHeaders: ['Content-Type', 'Authorization'] }); |
| 163 | + const res = await draftPreflight(app, ALLOWED, 'content-type,if-none-match'); |
| 164 | + expect(listOf(res, 'access-control-allow-headers')).toEqual(['content-type', 'authorization']); |
| 165 | + }); |
| 166 | +}); |
0 commit comments