toiljs 0.0.126 → 0.0.128

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 (150) hide show
  1. package/CHANGELOG.md +28 -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/routing/Router.js +1 -1
  18. package/build/client/security.d.ts +4 -0
  19. package/build/client/security.js +55 -0
  20. package/build/client/ssr/markers.js +6 -1
  21. package/build/compiler/config.d.ts +2 -0
  22. package/build/compiler/config.js +1 -0
  23. package/build/compiler/generate.d.ts +1 -1
  24. package/build/compiler/generate.js +1 -37
  25. package/build/compiler/index.d.ts +1 -0
  26. package/build/compiler/index.js +54 -1
  27. package/build/compiler/security.d.ts +7 -0
  28. package/build/compiler/security.js +74 -0
  29. package/build/compiler/sri.js +10 -3
  30. package/build/compiler/toil-docs.generated.js +33 -27
  31. package/build/compiler/vite.js +2 -0
  32. package/build/devserver/config/env.d.ts +6 -0
  33. package/build/devserver/config/env.js +10 -2
  34. package/build/devserver/daemon/catalog.d.ts +1 -0
  35. package/build/devserver/daemon/catalog.js +10 -4
  36. package/build/devserver/daemon/host.d.ts +5 -1
  37. package/build/devserver/daemon/host.js +8 -4
  38. package/build/devserver/daemon/http.d.ts +14 -0
  39. package/build/devserver/daemon/http.js +90 -0
  40. package/build/devserver/daemon/index.d.ts +21 -1
  41. package/build/devserver/daemon/index.js +109 -21
  42. package/build/devserver/db/atomic.d.ts +8 -0
  43. package/build/devserver/db/atomic.js +133 -0
  44. package/build/devserver/db/catalog.d.ts +7 -0
  45. package/build/devserver/db/catalog.js +17 -0
  46. package/build/devserver/db/changes.d.ts +5 -0
  47. package/build/devserver/db/changes.js +49 -0
  48. package/build/devserver/db/database.d.ts +7 -0
  49. package/build/devserver/db/database.js +251 -41
  50. package/build/devserver/db/derives.d.ts +4 -5
  51. package/build/devserver/db/derives.js +7 -76
  52. package/build/devserver/db/document-scan.d.ts +2 -0
  53. package/build/devserver/db/document-scan.js +123 -0
  54. package/build/devserver/db/limits.d.ts +16 -0
  55. package/build/devserver/db/limits.js +92 -14
  56. package/build/devserver/db/types.d.ts +15 -0
  57. package/build/devserver/db/types.js +9 -0
  58. package/build/devserver/files/dev.d.ts +3 -0
  59. package/build/devserver/files/dev.js +29 -0
  60. package/build/devserver/files/disk.d.ts +17 -0
  61. package/build/devserver/files/disk.js +369 -0
  62. package/build/devserver/files/signatures.d.ts +16 -0
  63. package/build/devserver/files/signatures.js +151 -0
  64. package/build/devserver/http/proxy.js +11 -3
  65. package/build/devserver/http/runtime.js +36 -9
  66. package/build/devserver/images/index.d.ts +9 -0
  67. package/build/devserver/images/index.js +87 -0
  68. package/build/devserver/images/worker.d.mts +1 -0
  69. package/build/devserver/images/worker.mjs +24 -0
  70. package/build/devserver/index.d.ts +3 -1
  71. package/build/devserver/production.js +5 -3
  72. package/build/devserver/runtime/host.d.ts +4 -0
  73. package/build/devserver/runtime/host.js +6 -2
  74. package/build/devserver/runtime/module.d.ts +15 -0
  75. package/build/devserver/runtime/module.js +105 -7
  76. package/build/devserver/server.js +13 -1
  77. package/build/devserver/stream/host.d.ts +2 -0
  78. package/build/devserver/stream/host.js +2 -1
  79. package/build/devserver/stream/index.js +2 -0
  80. package/build/io/derive-metadata.d.ts +7 -0
  81. package/build/io/derive-metadata.js +44 -0
  82. package/build/io/index.d.ts +1 -0
  83. package/build/io/index.js +1 -0
  84. package/build/shared/index.d.ts +1 -0
  85. package/build/shared/index.js +1 -0
  86. package/build/shared/security.d.ts +5 -0
  87. package/build/shared/security.js +64 -0
  88. package/examples/basic/client/routes/rest.tsx +1 -1
  89. package/examples/basic/server/routes/Guestbook.ts +1 -1
  90. package/package.json +19 -7
  91. package/scripts/build-image-codec.mjs +79 -0
  92. package/scripts/gen-auth-vectors.mjs +132 -0
  93. package/scripts/gen-native-atomic-fixture.mjs +39 -0
  94. package/scripts/gen-native-blob-fixture.mjs +42 -0
  95. package/scripts/gen-native-image-fixture.mjs +65 -0
  96. package/scripts/gen-native-staging-fixture.mjs +41 -0
  97. package/scripts/gen-server-types.mjs +82 -0
  98. package/server/auth/AuthController.ts +15 -234
  99. package/server/auth/AuthMaintenance.ts +177 -0
  100. package/server/auth/AuthStore.ts +198 -0
  101. package/server/auth/SessionEpochs.ts +38 -9
  102. package/server/globals/auth.ts +56 -0
  103. package/server/globals.d.ts +37 -0
  104. package/server/runtime/envelope.ts +2 -1
  105. package/server/runtime/exports/index.ts +2 -1
  106. package/server/runtime/files/blobs.ts +341 -0
  107. package/server/runtime/files/images.ts +36 -0
  108. package/server/runtime/http/percent.ts +5 -4
  109. package/server/runtime/index.ts +5 -0
  110. package/server/runtime/response.ts +20 -0
  111. package/server/runtime/rest/RouteContext.ts +5 -4
  112. package/std/server/abort/abort.d.ts +25 -0
  113. package/std/server/env/Server.d.ts +47 -0
  114. package/std/server/envelope.d.ts +38 -0
  115. package/std/server/exports/index.d.ts +20 -0
  116. package/std/server/exports/render.d.ts +15 -0
  117. package/std/server/files/blobs.d.ts +50 -0
  118. package/std/server/files/images.d.ts +36 -0
  119. package/std/server/handlers/ToilHandler.d.ts +29 -0
  120. package/std/server/http/base64.d.ts +21 -0
  121. package/std/server/http/cookie.d.ts +127 -0
  122. package/std/server/http/cookies.d.ts +56 -0
  123. package/std/server/http/date.d.ts +17 -0
  124. package/std/server/http/percent.d.ts +19 -0
  125. package/std/server/http/securecookies.d.ts +55 -0
  126. package/std/server/index.d.ts +34 -0
  127. package/std/server/lang/Potential.d.ts +6 -0
  128. package/std/server/memory.d.ts +42 -0
  129. package/std/server/request.d.ts +47 -0
  130. package/std/server/response.d.ts +90 -0
  131. package/std/server/rest/Rest.d.ts +23 -0
  132. package/std/server/rest/RestHandler.d.ts +14 -0
  133. package/std/server/rest/RouteContext.d.ts +33 -0
  134. package/std/server/rest/match.d.ts +14 -0
  135. package/std/server/rpc/Rpc.d.ts +37 -0
  136. package/std/server/ssr/Ssr.d.ts +27 -0
  137. package/std/server/ssr/encode.d.ts +26 -0
  138. package/std/server/ssr/escape.d.ts +22 -0
  139. package/std/server/ssr/slots.d.ts +91 -0
  140. package/std/server/time.d.ts +24 -0
  141. package/tsconfig.json +11 -2
  142. package/build/backend/.tsbuildinfo +0 -1
  143. package/build/cli/.tsbuildinfo +0 -1
  144. package/build/client/.tsbuildinfo +0 -1
  145. package/build/compiler/.tsbuildinfo +0 -1
  146. package/build/devserver/.tsbuildinfo +0 -1
  147. package/build/io/.tsbuildinfo +0 -1
  148. package/build/logger/.tsbuildinfo +0 -1
  149. package/build/shared/.tsbuildinfo +0 -1
  150. package/build/testing/.tsbuildinfo +0 -1
@@ -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';
@@ -79,7 +80,14 @@ function serverEntryFiles(root) {
79
80
  return [...result].sort();
80
81
  }
81
82
  function authEntryFiles(root, appHasUser) {
82
- const names = [...(appHasUser ? ['AuthController.ts'] : ['AuthUser.ts', 'AuthController.ts']), 'AuthStateDb.ts', 'SessionEpochs.ts', 'FactorSettings.ts'];
83
+ const names = [
84
+ ...(appHasUser ? ['AuthController.ts'] : ['AuthUser.ts', 'AuthController.ts']),
85
+ 'AuthStore.ts',
86
+ 'AuthMaintenance.ts',
87
+ 'AuthStateDb.ts',
88
+ 'SessionEpochs.ts',
89
+ 'FactorSettings.ts',
90
+ ];
83
91
  const primary = names.map((n) => path.posix.join('node_modules/toiljs/server/auth', n));
84
92
  if (primary.every((rel) => fs.existsSync(path.join(root, rel))))
85
93
  return primary;
@@ -152,6 +160,21 @@ export async function buildServer(root, auth = false) {
152
160
  }
153
161
  const split = splitSurfaceFiles(root, files);
154
162
  assertNoStreamInRequestTier(root, split);
163
+ const editorDir = serverDirs(root)[0] ?? path.join(root, 'server');
164
+ const activeEditorTiers = new Set([
165
+ ...(!split.hasDaemon && !split.hasStream ? ['request'] : []),
166
+ ...(split.hasDaemon ? ['cold'] : []),
167
+ ...(split.hasStream && split.stream.length > 0 ? ['stream'] : []),
168
+ ...((split.hasDaemon || split.hasStream) && split.request.length > 0 ? ['request'] : []),
169
+ ]);
170
+ for (const tier of ['request', 'stream', 'cold']) {
171
+ if (activeEditorTiers.has(tier))
172
+ continue;
173
+ const file = path.join(editorDir, `toilscript.${tier}.generated.d.ts`);
174
+ if (fs.existsSync(file) &&
175
+ fs.readFileSync(file, 'utf8').startsWith('// Generated by toilscript --editorTypes.'))
176
+ fs.unlinkSync(file);
177
+ }
155
178
  if (split.hasDaemon || split.hasStream) {
156
179
  const artifacts = serverArtifacts(root);
157
180
  if (split.hasDaemon)
@@ -176,6 +199,10 @@ export async function buildServer(root, auth = false) {
176
199
  rpcSurfaceFiles: split.hasStream ? split.stream : undefined,
177
200
  authUser: authOn,
178
201
  });
202
+ if (split.request.length > 0)
203
+ validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), split.hasDaemon ? fs.readFileSync(artifacts.cold) : null);
204
+ if (split.hasDaemon)
205
+ validateDeriveContinuationArtifacts(null, fs.readFileSync(artifacts.cold));
179
206
  if (split.hasStream && split.stream.length > 0)
180
207
  emitStreamClientSurface(root, artifacts.stream, split.stream);
181
208
  return;
@@ -186,6 +213,29 @@ export async function buildServer(root, auth = false) {
186
213
  withRpc: true,
187
214
  authUser: authOn,
188
215
  });
216
+ validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), null);
217
+ }
218
+ export function validateDeriveContinuationArtifacts(hot, cold) {
219
+ const moduleOf = (bytes) => new WebAssembly.Module(Uint8Array.from(bytes));
220
+ const parseDerives = (bytes) => {
221
+ const sections = WebAssembly.Module.customSections(moduleOf(bytes), 'toildb.derives');
222
+ return sections.length === 1 ? (readDeriveCatalog(new Uint8Array(sections[0])) ?? []) : [];
223
+ };
224
+ const needsQueue = (bytes) => WebAssembly.Module.imports(moduleOf(bytes)).some((entry) => entry.module === 'env' && entry.name === 'data.continue_derive');
225
+ const resident = cold !== null &&
226
+ WebAssembly.Module.customSections(moduleOf(cold), 'toildaemon.catalog').length === 1;
227
+ if (hot !== null && needsQueue(hot)) {
228
+ if (!resident || cold === null)
229
+ throw new Error('Db.continueDerive requires a resident @daemon cold artifact; put its @database declarations in shared source files.');
230
+ const available = new Set(parseDerives(cold).map(deriveIdentity));
231
+ const missing = parseDerives(hot).filter((entry) => !available.has(deriveIdentity(entry)));
232
+ if (missing.length > 0)
233
+ throw new Error('The cold artifact is missing materializers required for continuation: ' +
234
+ missing.map((entry) => entry.dbName + '.' + entry.methodName).join(', ') +
235
+ '. Move the databases into shared source files.');
236
+ }
237
+ if (cold !== null && needsQueue(cold) && parseDerives(cold).length === 0)
238
+ throw new Error('Db.continueDerive requires a deployed @derive method in the cold artifact.');
189
239
  }
190
240
  function resolveToilscriptBin(root) {
191
241
  const require = createRequire(path.join(root, 'package.json'));
@@ -334,6 +384,9 @@ export function assertNoStreamInRequestTier(root, split) {
334
384
  }
335
385
  async function runToilscriptPass(root, binJs, files, opts) {
336
386
  const args = [binJs, ...files, '--target', 'release'];
387
+ const editorTier = opts.mode === 'cold' ? 'cold' : opts.withRpc ? 'request' : 'stream';
388
+ const editorDir = serverDirs(root)[0] ?? path.join(root, 'server');
389
+ args.push('--editorTypes', path.join(editorDir, `toilscript.${editorTier}.generated.d.ts`));
337
390
  if (opts.mode !== null)
338
391
  args.push('--targetMode', opts.mode);
339
392
  if (opts.mode === 'cold')
@@ -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
  }