|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25077] Every outlet in this package that renders a value into HTML escapes |
| 5 | + * it by the context it lands in — ruling 3C on #25040. |
| 6 | + * |
| 7 | + * ## The rule |
| 8 | + * |
| 9 | + * The burden sits on the OUTLET: the code that places a value into markup. A |
| 10 | + * value reaching an HTML outlet may carry any character, and nothing upstream |
| 11 | + * strips or refuses it, so the outlet escapes it for the context it lands in — |
| 12 | + * element text or a quoted attribute value. This package has exactly one such |
| 13 | + * outlet today: the `GET {base}/docs` viewer in `discovery-routes.ts`, which |
| 14 | + * places the request-derived openapi URL into a `data-url="…"` attribute. |
| 15 | + * |
| 16 | + * ## The list, and the pin on the list itself |
| 17 | + * |
| 18 | + * {@link OUTLETS} names every file of this package that renders a value into |
| 19 | + * HTML, each with a pin that drives its real render path. A per-entry pin |
| 20 | + * cannot see an outlet nobody listed, so the LIST is pinned too: the census |
| 21 | + * walks this package's source and finds every file that touches HTML at all — |
| 22 | + * an identifier or a string naming `html`, or a string carrying an HTML tag — |
| 23 | + * and requires each one to be on {@link OUTLETS} or on {@link NOT_OUTLETS} with |
| 24 | + * the reason it renders nothing. A new file that touches HTML fails here until |
| 25 | + * its author says which it is. A positive control proves the census actually |
| 26 | + * finds the known outlet. |
| 27 | + * |
| 28 | + * ⚠️ LIMIT, stated so it is not read as more: the census reads source text of |
| 29 | + * THIS package. It proves no unlisted file here touches HTML; it does not see |
| 30 | + * another package (each package holding an outlet carries its own list), and it |
| 31 | + * does not prove a listed outlet escapes — that is what the per-entry pin is |
| 32 | + * for. |
| 33 | + */ |
| 34 | + |
| 35 | +import { readFileSync, readdirSync, statSync } from 'node:fs'; |
| 36 | +import { dirname, join, relative, sep } from 'node:path'; |
| 37 | +import { fileURLToPath } from 'node:url'; |
| 38 | + |
| 39 | +import ts from 'typescript'; |
| 40 | +import { describe, it, expect, vi } from 'vitest'; |
| 41 | +import { RestServer } from './rest-server.js'; |
| 42 | + |
| 43 | +/** …/packages/rest/src — this package's whole source tree. */ |
| 44 | +const SRC = dirname(fileURLToPath(import.meta.url)); |
| 45 | + |
| 46 | +/** A file that renders a value into HTML, and the pin that holds it to the rule. */ |
| 47 | +interface OutletEntry { |
| 48 | + /** What it renders. */ |
| 49 | + readonly renders: string; |
| 50 | + /** Registers the pin that drives its real render path — an outlet cannot be listed without one. */ |
| 51 | + readonly pin: () => void; |
| 52 | +} |
| 53 | + |
| 54 | +/** A file that touches HTML without rendering a value into it. */ |
| 55 | +interface NotOutletEntry { |
| 56 | + readonly why: string; |
| 57 | +} |
| 58 | + |
| 59 | +const OUTLETS: Readonly<Record<string, OutletEntry>> = { |
| 60 | + 'discovery-routes.ts': { |
| 61 | + renders: 'the GET {base}/docs Scalar viewer page, which places the request-derived openapi URL into a data-url attribute', |
| 62 | + pin: pinDocsViewer, |
| 63 | + }, |
| 64 | +}; |
| 65 | + |
| 66 | +const NOT_OUTLETS: Readonly<Record<string, NotOutletEntry>> = { |
| 67 | + 'html-escape.ts': { why: 'the escaper the outlet calls; renders nothing itself' }, |
| 68 | + 'import-template.ts': { why: 'names "html" as a sample field-type string in SAMPLE_TEXT_TYPES; renders nothing' }, |
| 69 | + 'rest-route-ledger.ts': { why: 'a route-ledger note describing the docs page in prose; renders nothing' }, |
| 70 | +}; |
| 71 | + |
| 72 | +// ── The census ────────────────────────────────────────────────────────────── |
| 73 | + |
| 74 | +const HTML_WORD = /html/i; |
| 75 | +/** An HTML element opening or closing tag inside a string. */ |
| 76 | +const HTML_TAG = |
| 77 | + /<(?:!doctype|\/?(?:html|head|body|title|meta|style|script|link|p|a|b|i|u|em|strong|small|span|div|br|hr|img|table|thead|tbody|tfoot|tr|td|th|ul|ol|li|h[1-6]|form|input|button|textarea|select|option|label|pre|code|blockquote|section|article|header|footer|nav|main|center|font|iframe|svg|mj-[a-z-]+))(?=[\s>/])/i; |
| 78 | + |
| 79 | +/** Does this source touch HTML in CODE — comments never count. */ |
| 80 | +function touchesHtml(fileName: string, text: string): boolean { |
| 81 | + const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true); |
| 82 | + let hit = false; |
| 83 | + const visit = (node: ts.Node): void => { |
| 84 | + if (hit) return; |
| 85 | + if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { |
| 86 | + if (HTML_WORD.test(node.text)) hit = true; |
| 87 | + } else if ( |
| 88 | + ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) |
| 89 | + || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) |
| 90 | + ) { |
| 91 | + if (HTML_WORD.test(node.text) || HTML_TAG.test(node.text)) hit = true; |
| 92 | + } |
| 93 | + if (!hit) ts.forEachChild(node, visit); |
| 94 | + }; |
| 95 | + visit(source); |
| 96 | + return hit; |
| 97 | +} |
| 98 | + |
| 99 | +/** Every shipped source file, package-relative. Tests and test kits ship nothing. */ |
| 100 | +function shippedSources(dir = SRC): string[] { |
| 101 | + const out: string[] = []; |
| 102 | + for (const entry of readdirSync(dir)) { |
| 103 | + const full = join(dir, entry); |
| 104 | + if (statSync(full).isDirectory()) { |
| 105 | + out.push(...shippedSources(full)); |
| 106 | + continue; |
| 107 | + } |
| 108 | + if (!entry.endsWith('.ts') || entry.endsWith('.d.ts')) continue; |
| 109 | + if (entry.endsWith('.test.ts') || entry.endsWith('.testkit.ts')) continue; |
| 110 | + out.push(relative(SRC, full).split(sep).join('/')); |
| 111 | + } |
| 112 | + return out.sort(); |
| 113 | +} |
| 114 | + |
| 115 | +describe('the outlet list — every file here that touches HTML is classified', () => { |
| 116 | + it('the census reads code, not comments (control)', () => { |
| 117 | + expect(touchesHtml('a.ts', '// renders html\nexport const x = 1;')).toBe(false); |
| 118 | + expect(touchesHtml('a.ts', 'export const x = `<p>${1}</p>`;')).toBe(true); |
| 119 | + expect(touchesHtml('a.ts', 'export const bodyHtml = 1;')).toBe(true); |
| 120 | + expect(touchesHtml('a.ts', "export const t = 'text/html';")).toBe(true); |
| 121 | + }); |
| 122 | + |
| 123 | + it('the census finds the known outlet (positive control)', () => { |
| 124 | + const outlet = 'discovery-routes.ts'; |
| 125 | + expect(Object.keys(OUTLETS)).toContain(outlet); |
| 126 | + expect(touchesHtml(outlet, readFileSync(join(SRC, outlet), 'utf8'))).toBe(true); |
| 127 | + }); |
| 128 | + |
| 129 | + it('the files that touch HTML are exactly the listed outlets and non-outlets', () => { |
| 130 | + const touching = shippedSources().filter((rel) => touchesHtml(rel, readFileSync(join(SRC, rel), 'utf8'))); |
| 131 | + const listed = [...Object.keys(OUTLETS), ...Object.keys(NOT_OUTLETS)].sort(); |
| 132 | + expect(touching).toEqual(listed); |
| 133 | + }); |
| 134 | + |
| 135 | + it('no file is both an outlet and a non-outlet', () => { |
| 136 | + expect(Object.keys(OUTLETS).filter((f) => f in NOT_OUTLETS)).toEqual([]); |
| 137 | + }); |
| 138 | +}); |
| 139 | + |
| 140 | +// ── The per-entry pin ───────────────────────────────────────────────────── |
| 141 | + |
| 142 | +const UNSCOPED = '/api/v1'; |
| 143 | +const SCOPED = '/api/v1/environments/:environmentId'; |
| 144 | + |
| 145 | +/** Mount both bases, a signed-in context, and drive the GET {base}/docs handler. */ |
| 146 | +function makeRest() { |
| 147 | + const httpServer = { |
| 148 | + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), |
| 149 | + use: vi.fn(), listen: vi.fn(), close: vi.fn(), |
| 150 | + } as any; |
| 151 | + const protocol: any = { getMetaItems: vi.fn(async () => ({ items: [] })) }; |
| 152 | + const rest = new RestServer( |
| 153 | + httpServer, protocol, |
| 154 | + { api: { version: 'v1', enableProjectScoping: true, projectResolution: 'auto' } } as any, |
| 155 | + ); |
| 156 | + (rest as any).resolveExecCtx = vi.fn(async () => ({ userId: 'u_docs_reader' })); |
| 157 | + rest.registerRoutes(); |
| 158 | + return rest; |
| 159 | +} |
| 160 | + |
| 161 | +/** The viewer's `data-url` attribute value, as served for a request whose path is `reqPath`. */ |
| 162 | +async function dataUrlFor(rest: RestServer, mountPath: string, reqPath: string, environmentId?: string): Promise<string> { |
| 163 | + const entry = (rest as any).routeManager.get('GET', mountPath); |
| 164 | + expect(entry, `GET ${mountPath} must be mounted`).toBeDefined(); |
| 165 | + let html = ''; |
| 166 | + const res: any = { |
| 167 | + status: () => res, |
| 168 | + json: () => res, |
| 169 | + send: (body: string) => { html = body; return res; }, |
| 170 | + setHeader: () => res, |
| 171 | + header: () => res, |
| 172 | + }; |
| 173 | + await entry.handler({ |
| 174 | + method: 'GET', path: reqPath, url: reqPath, |
| 175 | + params: environmentId ? { environmentId } : {}, query: {}, |
| 176 | + headers: { host: 'example.test' }, |
| 177 | + }, res); |
| 178 | + const m = html.match(/data-url="([^\n]*)"><\/script>/); |
| 179 | + expect(m, 'the viewer page carries a data-url attribute').not.toBeNull(); |
| 180 | + return m![1]; |
| 181 | +} |
| 182 | + |
| 183 | +function pinDocsViewer(): void { |
| 184 | + /** |
| 185 | + * A path segment carrying the characters a quoted HTML attribute interprets. |
| 186 | + * Kept to the minimum the context reads — a quote, an angle bracket, an |
| 187 | + * ampersand, an apostrophe — not an attack string. |
| 188 | + */ |
| 189 | + const SPECIAL_ENV = 'a"<&\'b'; |
| 190 | + const SPECIAL_ENV_ESCAPED = 'a"<&'b'; |
| 191 | + |
| 192 | + it('a value carrying attribute-interpreted characters is escaped for the attribute context', async () => { |
| 193 | + const rest = makeRest(); |
| 194 | + const reqPath = `/api/v1/environments/${SPECIAL_ENV}/docs`; |
| 195 | + const dataUrl = await dataUrlFor(rest, `${SCOPED}/docs`, reqPath, SPECIAL_ENV); |
| 196 | + expect(dataUrl).toBe(`/api/v1/environments/${SPECIAL_ENV_ESCAPED}/openapi.json`); |
| 197 | + // The literal characters do not survive into the served attribute value. |
| 198 | + expect(dataUrl).not.toContain('"'); |
| 199 | + expect(dataUrl).not.toContain('<'); |
| 200 | + }); |
| 201 | + |
| 202 | + it('an ordinary URL is served byte-identical', async () => { |
| 203 | + const rest = makeRest(); |
| 204 | + const unscoped = await dataUrlFor(rest, `${UNSCOPED}/docs`, '/api/v1/docs'); |
| 205 | + expect(unscoped).toBe('/api/v1/openapi.json'); |
| 206 | + const scoped = await dataUrlFor(rest, `${SCOPED}/docs`, '/api/v1/environments/env_1/docs', 'env_1'); |
| 207 | + expect(scoped).toBe('/api/v1/environments/env_1/openapi.json'); |
| 208 | + }); |
| 209 | +} |
| 210 | + |
| 211 | +// Registered last, so every helper above is initialised before the pin reads it. |
| 212 | +for (const [file, entry] of Object.entries(OUTLETS)) { |
| 213 | + describe(`${file} — ${entry.renders}`, entry.pin); |
| 214 | +} |
0 commit comments