toiljs 0.0.127 → 0.0.129

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/assets/image-codec-LICENSES.txt +4599 -0
  3. package/assets/image-codec-build.json +10 -0
  4. package/assets/image-codec.wasm +0 -0
  5. package/build/backend/index.d.ts +1 -0
  6. package/build/backend/index.js +8 -3
  7. package/build/backend/security.d.ts +4 -0
  8. package/build/backend/security.js +31 -0
  9. package/build/cli/index.js +11 -39
  10. package/build/client/components/Script.js +28 -17
  11. package/build/client/files.d.ts +17 -0
  12. package/build/client/files.js +119 -0
  13. package/build/client/html.d.ts +1 -0
  14. package/build/client/html.js +8 -0
  15. package/build/client/index.d.ts +1 -0
  16. package/build/client/index.js +1 -0
  17. package/build/client/security.d.ts +4 -0
  18. package/build/client/security.js +55 -0
  19. package/build/client/ssr/markers.js +6 -1
  20. package/build/compiler/config.d.ts +2 -0
  21. package/build/compiler/config.js +1 -0
  22. package/build/compiler/generate.d.ts +1 -1
  23. package/build/compiler/generate.js +1 -37
  24. package/build/compiler/index.d.ts +1 -0
  25. package/build/compiler/index.js +56 -1
  26. package/build/compiler/security-deployment.d.ts +3 -0
  27. package/build/compiler/security-deployment.js +88 -0
  28. package/build/compiler/security.d.ts +7 -0
  29. package/build/compiler/security.js +74 -0
  30. package/build/compiler/sri.js +10 -3
  31. package/build/compiler/toil-docs.generated.js +35 -28
  32. package/build/compiler/vite.js +2 -0
  33. package/build/devserver/config/env.d.ts +6 -0
  34. package/build/devserver/config/env.js +10 -2
  35. package/build/devserver/daemon/catalog.d.ts +1 -0
  36. package/build/devserver/daemon/catalog.js +10 -4
  37. package/build/devserver/daemon/host.d.ts +5 -1
  38. package/build/devserver/daemon/host.js +8 -4
  39. package/build/devserver/daemon/http.d.ts +14 -0
  40. package/build/devserver/daemon/http.js +90 -0
  41. package/build/devserver/daemon/index.d.ts +21 -1
  42. package/build/devserver/daemon/index.js +109 -21
  43. package/build/devserver/db/atomic.d.ts +8 -0
  44. package/build/devserver/db/atomic.js +133 -0
  45. package/build/devserver/db/catalog.d.ts +7 -0
  46. package/build/devserver/db/catalog.js +17 -0
  47. package/build/devserver/db/changes.d.ts +5 -0
  48. package/build/devserver/db/changes.js +49 -0
  49. package/build/devserver/db/database.d.ts +7 -0
  50. package/build/devserver/db/database.js +251 -41
  51. package/build/devserver/db/derives.d.ts +4 -5
  52. package/build/devserver/db/derives.js +7 -76
  53. package/build/devserver/db/document-scan.d.ts +2 -0
  54. package/build/devserver/db/document-scan.js +123 -0
  55. package/build/devserver/db/limits.d.ts +16 -0
  56. package/build/devserver/db/limits.js +92 -14
  57. package/build/devserver/db/types.d.ts +15 -0
  58. package/build/devserver/db/types.js +9 -0
  59. package/build/devserver/files/dev.d.ts +3 -0
  60. package/build/devserver/files/dev.js +29 -0
  61. package/build/devserver/files/disk.d.ts +17 -0
  62. package/build/devserver/files/disk.js +369 -0
  63. package/build/devserver/files/signatures.d.ts +16 -0
  64. package/build/devserver/files/signatures.js +151 -0
  65. package/build/devserver/http/proxy.js +11 -3
  66. package/build/devserver/http/runtime.js +36 -9
  67. package/build/devserver/images/index.d.ts +9 -0
  68. package/build/devserver/images/index.js +87 -0
  69. package/build/devserver/images/worker.d.mts +1 -0
  70. package/build/devserver/images/worker.mjs +24 -0
  71. package/build/devserver/index.d.ts +3 -1
  72. package/build/devserver/production.js +5 -3
  73. package/build/devserver/runtime/host.d.ts +4 -0
  74. package/build/devserver/runtime/host.js +6 -2
  75. package/build/devserver/runtime/module.d.ts +15 -0
  76. package/build/devserver/runtime/module.js +105 -7
  77. package/build/devserver/server.js +13 -1
  78. package/build/devserver/stream/host.d.ts +2 -0
  79. package/build/devserver/stream/host.js +2 -1
  80. package/build/devserver/stream/index.js +2 -0
  81. package/build/io/derive-metadata.d.ts +7 -0
  82. package/build/io/derive-metadata.js +44 -0
  83. package/build/io/index.d.ts +1 -0
  84. package/build/io/index.js +1 -0
  85. package/build/shared/index.d.ts +1 -0
  86. package/build/shared/index.js +1 -0
  87. package/build/shared/security.d.ts +5 -0
  88. package/build/shared/security.js +80 -0
  89. package/docs/auth/vectors-v1.json +41 -0
  90. package/examples/basic/client/routes/rest.tsx +1 -1
  91. package/examples/basic/server/routes/Guestbook.ts +1 -1
  92. package/package.json +20 -7
  93. package/scripts/build-image-codec.mjs +79 -0
  94. package/scripts/gen-auth-vectors.mjs +132 -0
  95. package/scripts/gen-native-atomic-fixture.mjs +39 -0
  96. package/scripts/gen-native-blob-fixture.mjs +42 -0
  97. package/scripts/gen-native-image-fixture.mjs +65 -0
  98. package/scripts/gen-native-staging-fixture.mjs +41 -0
  99. package/scripts/gen-server-types.mjs +82 -0
  100. package/scripts/gen-toil-docs.mjs +19 -7
  101. package/server/auth/AuthController.ts +15 -234
  102. package/server/auth/AuthMaintenance.ts +177 -0
  103. package/server/auth/AuthStore.ts +198 -0
  104. package/server/auth/SessionEpochs.ts +38 -9
  105. package/server/globals/auth.ts +56 -0
  106. package/server/globals/userid.ts +4 -5
  107. package/server/globals.d.ts +37 -0
  108. package/server/runtime/envelope.ts +2 -1
  109. package/server/runtime/exports/index.ts +2 -1
  110. package/server/runtime/files/blobs.ts +341 -0
  111. package/server/runtime/files/images.ts +36 -0
  112. package/server/runtime/http/percent.ts +5 -4
  113. package/server/runtime/index.ts +5 -0
  114. package/server/runtime/response.ts +20 -0
  115. package/server/runtime/rest/RouteContext.ts +5 -4
  116. package/std/server/abort/abort.d.ts +25 -0
  117. package/std/server/env/Server.d.ts +47 -0
  118. package/std/server/envelope.d.ts +38 -0
  119. package/std/server/exports/index.d.ts +20 -0
  120. package/std/server/exports/render.d.ts +15 -0
  121. package/std/server/files/blobs.d.ts +50 -0
  122. package/std/server/files/images.d.ts +36 -0
  123. package/std/server/handlers/ToilHandler.d.ts +29 -0
  124. package/std/server/http/base64.d.ts +21 -0
  125. package/std/server/http/cookie.d.ts +127 -0
  126. package/std/server/http/cookies.d.ts +56 -0
  127. package/std/server/http/date.d.ts +17 -0
  128. package/std/server/http/percent.d.ts +19 -0
  129. package/std/server/http/securecookies.d.ts +55 -0
  130. package/std/server/index.d.ts +34 -0
  131. package/std/server/lang/Potential.d.ts +6 -0
  132. package/std/server/memory.d.ts +42 -0
  133. package/std/server/request.d.ts +47 -0
  134. package/std/server/response.d.ts +90 -0
  135. package/std/server/rest/Rest.d.ts +23 -0
  136. package/std/server/rest/RestHandler.d.ts +14 -0
  137. package/std/server/rest/RouteContext.d.ts +33 -0
  138. package/std/server/rest/match.d.ts +14 -0
  139. package/std/server/rpc/Rpc.d.ts +37 -0
  140. package/std/server/ssr/Ssr.d.ts +27 -0
  141. package/std/server/ssr/encode.d.ts +26 -0
  142. package/std/server/ssr/escape.d.ts +22 -0
  143. package/std/server/ssr/slots.d.ts +91 -0
  144. package/std/server/time.d.ts +24 -0
  145. package/tsconfig.json +11 -2
@@ -1,3 +1,4 @@
1
+ import { readDeriveCatalog, deriveIdentity } from 'toiljs/io';
1
2
  import { spawn } from 'node:child_process';
2
3
  import fs from 'node:fs';
3
4
  import { createRequire } from 'node:module';
@@ -13,6 +14,7 @@ import { generate, TOIL_SERVER_ENV_DTS } from './generate.js';
13
14
  import { prerenderStaticParams } from './ssg.js';
14
15
  import { extractDevSsrTemplates, extractServerSlots, extractTemplates, } from './template-build.js';
15
16
  import { createViteConfig } from './vite.js';
17
+ import { logSecurityDeployment } from './security-deployment.js';
16
18
  export const SURFACE_DECORATOR = /^[ \t]*@(data|rest|service|remote|stream|daemon|scheduled)\b/m;
17
19
  function toilconfigEntries(root) {
18
20
  try {
@@ -79,7 +81,14 @@ function serverEntryFiles(root) {
79
81
  return [...result].sort();
80
82
  }
81
83
  function authEntryFiles(root, appHasUser) {
82
- const names = [...(appHasUser ? ['AuthController.ts'] : ['AuthUser.ts', 'AuthController.ts']), 'AuthStateDb.ts', 'SessionEpochs.ts', 'FactorSettings.ts'];
84
+ const names = [
85
+ ...(appHasUser ? ['AuthController.ts'] : ['AuthUser.ts', 'AuthController.ts']),
86
+ 'AuthStore.ts',
87
+ 'AuthMaintenance.ts',
88
+ 'AuthStateDb.ts',
89
+ 'SessionEpochs.ts',
90
+ 'FactorSettings.ts',
91
+ ];
83
92
  const primary = names.map((n) => path.posix.join('node_modules/toiljs/server/auth', n));
84
93
  if (primary.every((rel) => fs.existsSync(path.join(root, rel))))
85
94
  return primary;
@@ -152,6 +161,21 @@ export async function buildServer(root, auth = false) {
152
161
  }
153
162
  const split = splitSurfaceFiles(root, files);
154
163
  assertNoStreamInRequestTier(root, split);
164
+ const editorDir = serverDirs(root)[0] ?? path.join(root, 'server');
165
+ const activeEditorTiers = new Set([
166
+ ...(!split.hasDaemon && !split.hasStream ? ['request'] : []),
167
+ ...(split.hasDaemon ? ['cold'] : []),
168
+ ...(split.hasStream && split.stream.length > 0 ? ['stream'] : []),
169
+ ...((split.hasDaemon || split.hasStream) && split.request.length > 0 ? ['request'] : []),
170
+ ]);
171
+ for (const tier of ['request', 'stream', 'cold']) {
172
+ if (activeEditorTiers.has(tier))
173
+ continue;
174
+ const file = path.join(editorDir, `toilscript.${tier}.generated.d.ts`);
175
+ if (fs.existsSync(file) &&
176
+ fs.readFileSync(file, 'utf8').startsWith('// Generated by toilscript --editorTypes.'))
177
+ fs.unlinkSync(file);
178
+ }
155
179
  if (split.hasDaemon || split.hasStream) {
156
180
  const artifacts = serverArtifacts(root);
157
181
  if (split.hasDaemon)
@@ -176,6 +200,10 @@ export async function buildServer(root, auth = false) {
176
200
  rpcSurfaceFiles: split.hasStream ? split.stream : undefined,
177
201
  authUser: authOn,
178
202
  });
203
+ if (split.request.length > 0)
204
+ validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), split.hasDaemon ? fs.readFileSync(artifacts.cold) : null);
205
+ if (split.hasDaemon)
206
+ validateDeriveContinuationArtifacts(null, fs.readFileSync(artifacts.cold));
179
207
  if (split.hasStream && split.stream.length > 0)
180
208
  emitStreamClientSurface(root, artifacts.stream, split.stream);
181
209
  return;
@@ -186,6 +214,29 @@ export async function buildServer(root, auth = false) {
186
214
  withRpc: true,
187
215
  authUser: authOn,
188
216
  });
217
+ validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), null);
218
+ }
219
+ export function validateDeriveContinuationArtifacts(hot, cold) {
220
+ const moduleOf = (bytes) => new WebAssembly.Module(Uint8Array.from(bytes));
221
+ const parseDerives = (bytes) => {
222
+ const sections = WebAssembly.Module.customSections(moduleOf(bytes), 'toildb.derives');
223
+ return sections.length === 1 ? (readDeriveCatalog(new Uint8Array(sections[0])) ?? []) : [];
224
+ };
225
+ const needsQueue = (bytes) => WebAssembly.Module.imports(moduleOf(bytes)).some((entry) => entry.module === 'env' && entry.name === 'data.continue_derive');
226
+ const resident = cold !== null &&
227
+ WebAssembly.Module.customSections(moduleOf(cold), 'toildaemon.catalog').length === 1;
228
+ if (hot !== null && needsQueue(hot)) {
229
+ if (!resident || cold === null)
230
+ throw new Error('Db.continueDerive requires a resident @daemon cold artifact; put its @database declarations in shared source files.');
231
+ const available = new Set(parseDerives(cold).map(deriveIdentity));
232
+ const missing = parseDerives(hot).filter((entry) => !available.has(deriveIdentity(entry)));
233
+ if (missing.length > 0)
234
+ throw new Error('The cold artifact is missing materializers required for continuation: ' +
235
+ missing.map((entry) => entry.dbName + '.' + entry.methodName).join(', ') +
236
+ '. Move the databases into shared source files.');
237
+ }
238
+ if (cold !== null && needsQueue(cold) && parseDerives(cold).length === 0)
239
+ throw new Error('Db.continueDerive requires a deployed @derive method in the cold artifact.');
189
240
  }
190
241
  function resolveToilscriptBin(root) {
191
242
  const require = createRequire(path.join(root, 'package.json'));
@@ -334,6 +385,9 @@ export function assertNoStreamInRequestTier(root, split) {
334
385
  }
335
386
  async function runToilscriptPass(root, binJs, files, opts) {
336
387
  const args = [binJs, ...files, '--target', 'release'];
388
+ const editorTier = opts.mode === 'cold' ? 'cold' : opts.withRpc ? 'request' : 'stream';
389
+ const editorDir = serverDirs(root)[0] ?? path.join(root, 'server');
390
+ args.push('--editorTypes', path.join(editorDir, `toilscript.${editorTier}.generated.d.ts`));
337
391
  if (opts.mode !== null)
338
392
  args.push('--targetMode', opts.mode);
339
393
  if (opts.mode === 'cold')
@@ -695,6 +749,7 @@ export async function build(opts = {}) {
695
749
  process.stdout.write(pc.dim(' SSR template changed; recompiling the server with the new hash…') + '\n');
696
750
  await buildServer(cfg.root, cfg.auth);
697
751
  }
752
+ logSecurityDeployment(cfg);
698
753
  }
699
754
  export async function start(opts = {}) {
700
755
  const cfg = await loadConfig(opts);
@@ -0,0 +1,3 @@
1
+ import type { ResolvedToilConfig } from './config.js';
2
+ export declare function securityDeploymentInstructions(headers: string, siteUrl?: string): string | null;
3
+ export declare function logSecurityDeployment(cfg: ResolvedToilConfig): void;
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ function headerRules(source) {
4
+ const rules = [];
5
+ let current;
6
+ for (const line of source.split(/\r?\n/)) {
7
+ const text = line.trim();
8
+ if (!text || text.startsWith('#'))
9
+ continue;
10
+ if (!/^\s/.test(line)) {
11
+ current = { pattern: text, headers: [] };
12
+ rules.push(current);
13
+ continue;
14
+ }
15
+ if (current === undefined)
16
+ continue;
17
+ const removal = /^!\s+([^\s:]+)$/.exec(text);
18
+ if (removal) {
19
+ current.headers.push({ name: removal[1], value: null });
20
+ continue;
21
+ }
22
+ const header = /^([^\s:]+):\s*(.*)$/.exec(text);
23
+ if (header)
24
+ current.headers.push({ name: header[1], value: header[2] });
25
+ }
26
+ return rules.filter((rule) => rule.headers.length > 0);
27
+ }
28
+ function match(field, pattern) {
29
+ return `${field} ${pattern.includes('*') ? 'strict wildcard' : 'eq'} ${JSON.stringify(pattern)}`;
30
+ }
31
+ function expression(pattern, hostname) {
32
+ const absolute = /^https:\/\/([^/]+)(\/.*)?$/.exec(pattern);
33
+ const host = absolute?.[1] ?? hostname;
34
+ const pathname = absolute ? (absolute[2] ?? '/') : pattern;
35
+ if (!pathname.startsWith('/') || /:[A-Za-z_]\w*/.test(pathname))
36
+ return null;
37
+ const pathMatch = match('http.request.uri.path', pathname);
38
+ return host ? `(${match('http.host', host)}) and (${pathMatch})` : pathMatch;
39
+ }
40
+ export function securityDeploymentInstructions(headers, siteUrl) {
41
+ const rules = headerRules(headers);
42
+ if (!rules.some((rule) => rule.headers.some((header) => /^(content-security-policy|cross-origin-opener-policy)(-report-only)?$/i.test(header.name) &&
43
+ header.value !== null &&
44
+ header.value !== '')))
45
+ return null;
46
+ const site = siteUrl && URL.canParse(siteUrl) ? new URL(siteUrl) : undefined;
47
+ const hostname = site && ['https:', 'http:'].includes(site.protocol) ? site.hostname : undefined;
48
+ const lines = [
49
+ '\nBrowser security deployment setup',
50
+ 'Cloudflare Pages static hosting: deploy the generated _headers with the client output.',
51
+ 'Other hosts must send the generated response headers; uploading _headers alone does not apply them.',
52
+ 'toiljs start applies the framework headers automatically. Pages Functions / Workers must set headers in their handlers.',
53
+ '',
54
+ 'Cloudflare: Rules > Transform Rules > Modify Response Header > Create rule.',
55
+ 'Create the following rules in order using Custom filter expression > Edit expression.',
56
+ 'Choose Set static for each header value, or Remove where indicated, then Deploy.',
57
+ ];
58
+ if (!hostname)
59
+ lines.push('No site hostname configured in client.seo.url: scope these expressions to your deployment hostname if needed.');
60
+ for (const [index, rule] of rules.entries()) {
61
+ lines.push('', `${index + 1}. ${rule.pattern}`);
62
+ const filter = expression(rule.pattern, hostname);
63
+ if (filter === null ||
64
+ rule.headers.some((header) => /:[A-Za-z_]\w*/.test(header.value ?? ''))) {
65
+ lines.push('This rule uses a pattern or placeholder requiring configuration at the origin or in a Worker.', rule.pattern, ...rule.headers.map((header) => header.value === null
66
+ ? ` ! ${header.name}`
67
+ : ` ${header.name}: ${header.value}`));
68
+ continue;
69
+ }
70
+ lines.push('Expression:', filter);
71
+ for (const header of rule.headers) {
72
+ if (header.value === null)
73
+ lines.push(`Remove: ${header.name}`);
74
+ else
75
+ lines.push(`Set static: ${header.name}`, 'Value:', header.value);
76
+ }
77
+ }
78
+ lines.push('', 'Keep the generated HTML CSP meta policy, import map, and integrity attributes when deploying.', '');
79
+ return lines.join('\n');
80
+ }
81
+ export function logSecurityDeployment(cfg) {
82
+ const file = path.resolve(cfg.root, cfg.outDir, '_headers');
83
+ if (!fs.existsSync(file))
84
+ return;
85
+ const instructions = securityDeploymentInstructions(fs.readFileSync(file, 'utf8'), cfg.seo?.url);
86
+ if (instructions !== null)
87
+ process.stdout.write(instructions + '\n');
88
+ }
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare function injectSecurityPolicy(html: string, policy: string): string;
3
+ export declare function secureBuiltHtml(html: string, extraSources?: Readonly<Record<string, readonly string[]>>): {
4
+ html: string;
5
+ policy: string;
6
+ };
7
+ export declare function devSecurityPlugin(extraSources?: Readonly<Record<string, readonly string[]>>): Plugin;
@@ -0,0 +1,74 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { contentSecurityPolicy, DEFAULT_COOP } from 'toiljs/shared';
4
+ function escapeAttr(value) {
5
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
6
+ }
7
+ export function injectSecurityPolicy(html, policy) {
8
+ const tags = `<meta name="toil-csp" content="${escapeAttr(policy)}">\n` +
9
+ `<meta http-equiv="Content-Security-Policy" content="${escapeAttr(policy.replace(/frame-ancestors [^;]+; /, ''))}">`;
10
+ const head = /<head\b[^>]*>/i.exec(html);
11
+ const charset = head
12
+ ? /<meta\s+charset\s*=[^>]+>/i.exec(html.slice(head.index + head[0].length))
13
+ : null;
14
+ const at = charset && head
15
+ ? head.index + head[0].length + charset.index + charset[0].length
16
+ : head
17
+ ? head.index + head[0].length
18
+ : 0;
19
+ return html.slice(0, at) + '\n' + tags + html.slice(at);
20
+ }
21
+ export function secureBuiltHtml(html, extraSources = {}) {
22
+ const sources = new Set();
23
+ for (const match of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
24
+ const attrs = match[1];
25
+ if (/(?<![\w-])src\s*=/i.test(attrs)) {
26
+ const integrity = /(?<![\w-])integrity\s*=\s*["']([^"']+)["']/i.exec(attrs)?.[1];
27
+ for (const token of integrity?.split(/\s+/) ?? []) {
28
+ if (/^sha(256|384|512)-[A-Za-z0-9+/]+=*$/.test(token))
29
+ sources.add(`'${token}'`);
30
+ }
31
+ }
32
+ else {
33
+ if (/\btype\s*=\s*["']importmap["']/i.test(attrs)) {
34
+ const map = JSON.parse(match[2]);
35
+ for (const value of Object.values(map.integrity ?? {})) {
36
+ for (const token of value.split(/\s+/)) {
37
+ if (/^sha(256|384|512)-[A-Za-z0-9+/]+=*$/.test(token))
38
+ sources.add(`'${token}'`);
39
+ }
40
+ }
41
+ }
42
+ const body = match[2].replace(/\r\n?/g, '\n');
43
+ sources.add(`'sha384-${createHash('sha384').update(body).digest('base64')}'`);
44
+ }
45
+ }
46
+ const policy = contentSecurityPolicy([...sources], false, extraSources);
47
+ return { html: injectSecurityPolicy(html, policy), policy };
48
+ }
49
+ export function devSecurityPlugin(extraSources = {}) {
50
+ const requestNonce = new AsyncLocalStorage();
51
+ return {
52
+ name: 'toil:security-dev',
53
+ apply: 'serve',
54
+ configureServer(server) {
55
+ server.middlewares.use((_request, response, next) => {
56
+ const nonce = randomBytes(24).toString('base64');
57
+ response.setHeader('Content-Security-Policy', contentSecurityPolicy([`'nonce-${nonce}'`], true, extraSources));
58
+ response.setHeader('Cross-Origin-Opener-Policy', DEFAULT_COOP);
59
+ requestNonce.run(nonce, next);
60
+ });
61
+ },
62
+ transformIndexHtml: {
63
+ order: 'post',
64
+ handler(html) {
65
+ const nonce = requestNonce.getStore() ?? randomBytes(24).toString('base64');
66
+ const out = html.replace(/<script\b([^>]*)>/gi, (_tag, attrs) => {
67
+ const clean = attrs.replace(/\snonce(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?/gi, '');
68
+ return `<script nonce="${nonce}"${clean}>`;
69
+ });
70
+ return injectSecurityPolicy(out, contentSecurityPolicy([`'nonce-${nonce}'`], true, extraSources));
71
+ },
72
+ },
73
+ };
74
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { secureBuiltHtml } from './security.js';
4
5
  function computeSri(absPath, cache) {
5
6
  const cached = cache.get(absPath);
6
7
  if (cached !== undefined)
@@ -53,7 +54,9 @@ export function injectSri(html, outDir, base) {
53
54
  const sri = computeSri(path.join(outDir, rel), cache);
54
55
  if (sri === null)
55
56
  return full;
56
- const cross = /(?<![\w-])crossorigin(?![\w-])/i.test(attrs) ? '' : ' crossorigin="anonymous"';
57
+ const cross = /(?<![\w-])crossorigin(?![\w-])/i.test(attrs)
58
+ ? ''
59
+ : ' crossorigin="anonymous"';
57
60
  return `<${tag}${attrs} integrity="${sri}"${cross}${selfClose ? ' /' : ''}>`;
58
61
  });
59
62
  }
@@ -105,8 +108,12 @@ export function sriPlugin(cfg) {
105
108
  const importMap = buildImportMapIntegrity(outDir, cfg.base, cache);
106
109
  if (importMap !== null)
107
110
  out = injectImportMap(out, importMap);
108
- if (out !== html)
109
- fs.writeFileSync(shell, out);
111
+ const secured = secureBuiltHtml(out, cfg.cspSources);
112
+ fs.writeFileSync(shell, secured.html);
113
+ const headersFile = path.join(outDir, '_headers');
114
+ const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf8') : '';
115
+ fs.writeFileSync(headersFile, existing +
116
+ `\n/*\n Content-Security-Policy: ${secured.policy}\n Cross-Origin-Opener-Policy: same-origin\n`);
110
117
  },
111
118
  };
112
119
  }