File size: 8,134 Bytes
6cda6d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env node
/**

 * Emit the HTTP security headers for the isolated /renderer origin.

 *

 * A meta CSP in the shared index.html cannot constrain an external module worker's

 * own connect-src and cannot express frame-ancestors. Deploy the output of this

 * script as real HTTP response headers for the whole renderer directory, including

 * every worker JavaScript response.

 *

 * The main application origin is required for an allowlist policy and must be one

 * concrete HTTP(S) origin. There is deliberately no wildcard fallback. Deny mode

 * (`--deny` / `securityHeaders(null, { deny: true })`) emits frame-ancestors 'none'

 * and is the safe default for a build without a deployment origin.

 *

 * This origin must be dedicated: no application cookies, localStorage, tokens or

 * private same-origin APIs. The renderer needs script execution, WASM and Pyodide

 * network access limited to its own origin. Deploying these headers is an operator

 * action; this script does not deploy, configure DNS or claim that HTML metadata

 * alone sandboxes Python network access.

 *

 * Usage:

 *   node scripts/browser-rendering/security-headers.mjs \

 *     --main-origin https://app.example.com --out frontend/dist-browser-renderer/_headers

 *   node scripts/browser-rendering/security-headers.mjs \

 *     --deny --out frontend/dist-browser-renderer/_headers

 */

import { writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = fileURLToPath(new URL('.', import.meta.url));
const REPO_ROOT = resolve(HERE, '..', '..');

function concreteOrigin(raw) {
  let url;
  try {
    url = new URL(raw);
  } catch {
    throw new Error(`--main-origin is not a valid URL: ${raw}`);
  }
  if (url.protocol !== 'https:' && url.protocol !== 'http:') {
    throw new Error('--main-origin must use HTTP(S)');
  }
  if (url.username || url.password) {
    throw new Error('--main-origin must not contain credentials');
  }
  const local =
    url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
  if (url.protocol === 'http:' && !local) {
    throw new Error('--main-origin must use HTTPS outside localhost');
  }
  if (url.pathname !== '/' || url.search || url.hash) {
    throw new Error('--main-origin must be an origin without a path, query or fragment');
  }
  if (url.hostname === '*') throw new Error('--main-origin cannot be a wildcard');
  return url.origin;
}

function policy(frameAncestors) {
  return [
    "default-src 'none'",
    "script-src 'self' 'wasm-unsafe-eval' blob:",
    "worker-src 'self' blob:",
    "connect-src 'self'",
    "img-src 'self' data: blob:",
    "media-src 'self' blob:",
    "style-src 'self' 'unsafe-inline'",
    "font-src 'self'",
    "object-src 'none'",
    "base-uri 'none'",
    "form-action 'none'",
    "frame-src 'none'",
    `frame-ancestors ${frameAncestors}`,
  ].join('; ');
}

const COMMON_HEADERS = [
  'X-Content-Type-Options: nosniff',
  'Referrer-Policy: no-referrer',
  'Cross-Origin-Opener-Policy: same-origin',
  'Cross-Origin-Resource-Policy: same-origin',
  'Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()',
];

/** Headers as a plain object for a Vite dev server or another Node host. */
export function securityHeaderRecord(mainOriginRaw, options = {}) {
  const result = securityHeaders(mainOriginRaw, options);
  return {
    'Content-Security-Policy': result.csp,
    'X-Content-Type-Options': 'nosniff',
    'Referrer-Policy': 'no-referrer',
    'Cross-Origin-Opener-Policy': 'same-origin',
    'Cross-Origin-Resource-Policy': 'same-origin',
    'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
    'Cache-Control': 'no-store',
  };
}

export function securityHeaders(mainOriginRaw, { deny = false } = {}) {
  if (deny && mainOriginRaw) {
    throw new Error('--main-origin cannot be combined with deny mode');
  }
  if (!deny && !mainOriginRaw) {
    throw new Error('an allowlist main origin or explicit deny mode is required');
  }
  const mainOrigin = deny ? null : concreteOrigin(mainOriginRaw);
  const frameAncestors = deny ? "'none'" : mainOrigin;
  const csp = policy(frameAncestors);
  return {
    mode: deny ? 'deny' : 'allowlist',
    mainOrigin,
    csp,
    headersFile: [
      '# Generated by scripts/browser-rendering/security-headers.mjs.',
      `# frame-ancestors: ${frameAncestors}`,
      '# The renderer deployment is a separate origin. This file must never be copied',
      '# into the main application deployment; the main site keeps its own CSP.',
      '# The HTML route is /renderer (index.html); the same policy covers its modules,',
      '# workers and WASM responses.',
      '/*',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
      '# Explicit worker/module rules: some hosts match the most specific block.',
      '/renderer',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
      '/index.html',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
      '/assets/*.js',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
      '/assets/*.mjs',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
      '/browser-rendering/*',
      `  Content-Security-Policy: ${csp}`,
      ...COMMON_HEADERS.map((line) => `  ${line}`),
      '',
    ].join('\n'),
    nginx: [
      '# Put these inside the renderer origin server/location block.',
      `add_header Content-Security-Policy "${csp}" always;`,
      ...COMMON_HEADERS.map((line) => {
        const colon = line.indexOf(':');
        return `add_header ${line.slice(0, colon)} "${line.slice(colon + 1).trim()}" always;`;
      }),
      '',
    ].join('\n'),
  };
}

function parseArgs(argv) {
  const out = { mainOrigin: null, deny: false, format: 'headers', destination: null };
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    if (arg === '--main-origin') out.mainOrigin = argv[++index] ?? null;
    else if (arg === '--deny') out.deny = true;
    else if (arg === '--format') out.format = argv[++index] ?? 'headers';
    else if (arg === '--out') out.destination = argv[++index] ?? null;
    else if (arg === '--help' || arg === '-h') out.help = true;
    else throw new Error(`Unknown argument: ${arg}`);
  }
  return out;
}

async function main() {
  const args = parseArgs(process.argv.slice(2));
  if (args.help) {
    console.log(
      'Usage: security-headers.mjs (--main-origin <https://app.example> | --deny) [--format headers|nginx] [--out <file>]',
    );
    return;
  }
  if (args.deny && args.mainOrigin) {
    throw new Error('--main-origin cannot be combined with --deny');
  }
  if (!args.deny && !args.mainOrigin) {
    throw new Error(
      '--main-origin or --deny is required; frame-ancestors is never emitted with a wildcard fallback',
    );
  }
  if (args.format !== 'headers' && args.format !== 'nginx') {
    throw new Error('--format must be "headers" or "nginx"');
  }
  const result = securityHeaders(args.mainOrigin, { deny: args.deny });
  const text = args.format === 'headers' ? result.headersFile : result.nginx;
  if (args.destination) {
    const target = resolve(REPO_ROOT, args.destination);
    await writeFile(target, text, 'utf8');
    console.log(`wrote ${target}`);
    console.log(`frame-ancestors: ${result.mode === 'deny' ? "'none'" : result.mainOrigin}`);
  } else {
    process.stdout.write(text);
  }
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  main().catch((error) => {
    console.error(error instanceof Error ? error.message : String(error));
    process.exitCode = 1;
  });
}