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
@@ -0,0 +1,10 @@
1
+ {
2
+ "sha256": "51061fa3be015ffc4cd86c15d087c6074d0e7f30b5d21b519de609afc1bcc245",
3
+ "maximumMemoryBytes": 805306368,
4
+ "sourceHashes": {
5
+ "Cargo.toml": "ac001ddcd49ac5a86b95133ce11b396c53b1a451feaf4e6e3a29f040a92df3bd",
6
+ "Cargo.lock": "9003201cfaafd595ee51baa47cc0f1b81c86b0522bb2afd13d3e1746ffa64fa0",
7
+ "src/lib.rs": "d05da566f1269a54788a8ed5eeb44beb30754ecc533e4b09f2e751f6107f6549",
8
+ "src/main.rs": "b2c37b8ce166b1cd81260b1c75e575b661ce7d0f527b80d9921686c62a3a43f4"
9
+ }
10
+ }
Binary file
@@ -1,3 +1,4 @@
1
+ export { installSecurityHeaders, sendSecureStaticFile, writeResponseHeader } from './security.js';
1
2
  export interface BackendOptions {
2
3
  readonly root: string;
3
4
  readonly port?: number;
@@ -1,6 +1,8 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { Server, } from '@dacely/hyper-express';
4
+ import { installSecurityHeaders, sendSecureStaticFile } from './security.js';
5
+ export { installSecurityHeaders, sendSecureStaticFile, writeResponseHeader } from './security.js';
4
6
  const DEFAULT_MAX_BODY_LENGTH = 1024 * 1024 * 8;
5
7
  const MAX_BODY_BUFFER = 1024 * 32;
6
8
  const HTTP_IDLE_TIMEOUT = 60;
@@ -47,6 +49,7 @@ export async function startBackend(options) {
47
49
  idle_timeout: HTTP_IDLE_TIMEOUT,
48
50
  response_timeout: HTTP_RESPONSE_TIMEOUT,
49
51
  });
52
+ installSecurityHeaders(app);
50
53
  const clients = new Set();
51
54
  app.set_error_handler((_request, response, _error) => {
52
55
  if (response.completed)
@@ -97,12 +100,14 @@ export async function startBackend(options) {
97
100
  }
98
101
  response.upgrade({});
99
102
  });
100
- app.get('/*', (request, response) => {
103
+ const serveClient = (request, response) => {
101
104
  if (response.completed)
102
105
  return;
103
106
  const file = resolveStaticFile(root, request.path);
104
- response.sendFile(file ?? indexHtml);
105
- });
107
+ sendSecureStaticFile(response, file ?? indexHtml);
108
+ };
109
+ app.get('/*', serveClient);
110
+ app.head('/*', serveClient);
106
111
  await app.listen(port, host);
107
112
  return {
108
113
  port,
@@ -0,0 +1,4 @@
1
+ import type { Response, Server } from '@dacely/hyper-express';
2
+ export declare function installSecurityHeaders(app: Server): void;
3
+ export declare function sendSecureStaticFile(response: Response, file: string): void;
4
+ export declare function writeResponseHeader(response: Response, name: string, value: string): void;
@@ -0,0 +1,31 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { builtContentSecurityPolicy, withSecurityHeaders } from 'toiljs/shared';
4
+ export function installSecurityHeaders(app) {
5
+ app.use((_request, response, next) => {
6
+ for (const [name, value] of withSecurityHeaders([]))
7
+ response.header(name, value, true);
8
+ next();
9
+ });
10
+ }
11
+ export function sendSecureStaticFile(response, file) {
12
+ if (/^\.html?$/i.test(path.extname(file))) {
13
+ const body = fs.readFileSync(file);
14
+ const policy = builtContentSecurityPolicy(body.toString('utf8'));
15
+ if (policy !== null)
16
+ response.header('content-security-policy', policy, true);
17
+ response.header('content-type', 'text/html; charset=utf-8', true);
18
+ response.send(body);
19
+ return;
20
+ }
21
+ response.sendFile(file);
22
+ }
23
+ export function writeResponseHeader(response, name, value) {
24
+ const lower = name.toLowerCase();
25
+ if (lower === 'content-security-policy' || lower === 'cross-origin-opener-policy') {
26
+ response.header(name, value, true);
27
+ }
28
+ else {
29
+ response.header(name, value);
30
+ }
31
+ }
@@ -4015,7 +4015,14 @@ import fs3 from "node:fs/promises";
4015
4015
  import path4 from "node:path";
4016
4016
  import { fileURLToPath as fileURLToPath2 } from "node:url";
4017
4017
  var import_picocolors3 = __toESM(require_picocolors(), 1);
4018
- import { AI_HELPER_IDS, AI_HELPERS, aiHelperFiles, TOIL_DOCS, TOIL_ENV_DTS } from "toiljs/compiler";
4018
+ import {
4019
+ AI_HELPER_IDS,
4020
+ AI_HELPERS,
4021
+ aiHelperFiles,
4022
+ TOIL_DOCS,
4023
+ TOIL_ENV_DTS,
4024
+ TOIL_SERVER_ENV_DTS
4025
+ } from "toiljs/compiler";
4019
4026
 
4020
4027
  // src/cli/testing.ts
4021
4028
  var TEST_DEPENDENCIES = {
@@ -4149,7 +4156,7 @@ function scaffold(name, template, features, aiTools, images) {
4149
4156
  oxlint: "^1.87.0",
4150
4157
  "oxlint-tsgolint": "^7.0.2003",
4151
4158
  prettier: "^3.9.9",
4152
- toilscript: ">=0.1.65",
4159
+ toilscript: ">=0.1.66",
4153
4160
  typescript: "^7.0.2"
4154
4161
  };
4155
4162
  for (const dep of requiredPackages(features).sort()) {
@@ -4257,6 +4264,7 @@ function scaffold(name, template, features, aiTools, images) {
4257
4264
  "server/tsconfig.json": JSON.stringify(
4258
4265
  {
4259
4266
  extends: "toilscript/std/assembly.json",
4267
+ compilerOptions: { types: ["assembly", "toiljs/server/globals"] },
4260
4268
  include: ["./**/*.ts"]
4261
4269
  },
4262
4270
  null,
@@ -4321,42 +4329,6 @@ function scaffold(name, template, features, aiTools, images) {
4321
4329
  }
4322
4330
  return files;
4323
4331
  }
4324
- var TOIL_SERVER_ENV_DTS = `// AUTO-GENERATED by toil, do not edit. Editor-only ambient declarations for
4325
- // the toiljs server-runtime globals (Cookie, Cookies, SecureCookies, the
4326
- // cookie enums): @global in the runtime, used with no import. These alias the
4327
- // real runtime types so a global-built Cookie is exactly what Response.setCookie
4328
- // / SecureCookies.seal expect. The toilscript compiler registers them itself.
4329
- declare const SameSite: typeof import('toiljs/server/runtime/http/cookie').SameSite;
4330
- type SameSite = import('toiljs/server/runtime/http/cookie').SameSite;
4331
- declare const CookieEncoding: typeof import('toiljs/server/runtime/http/cookie').CookieEncoding;
4332
- type CookieEncoding = import('toiljs/server/runtime/http/cookie').CookieEncoding;
4333
- declare const CookiePrefix: typeof import('toiljs/server/runtime/http/cookie').CookiePrefix;
4334
- type CookiePrefix = import('toiljs/server/runtime/http/cookie').CookiePrefix;
4335
- declare const CookieValidation: typeof import('toiljs/server/runtime/http/cookie').CookieValidation;
4336
- type CookieValidation = import('toiljs/server/runtime/http/cookie').CookieValidation;
4337
- declare const Cookie: typeof import('toiljs/server/runtime/http/cookie').Cookie;
4338
- type Cookie = import('toiljs/server/runtime/http/cookie').Cookie;
4339
- declare const CookieMap: typeof import('toiljs/server/runtime/http/cookies').CookieMap;
4340
- type CookieMap = import('toiljs/server/runtime/http/cookies').CookieMap;
4341
- declare const Cookies: typeof import('toiljs/server/runtime/http/cookies').Cookies;
4342
- type Cookies = import('toiljs/server/runtime/http/cookies').Cookies;
4343
- declare const SecureCookies: typeof import('toiljs/server/runtime/http/securecookies').SecureCookies;
4344
- type SecureCookies = import('toiljs/server/runtime/http/securecookies').SecureCookies;
4345
- declare const Time: typeof import('toiljs/server/runtime/time').Time;
4346
- // Email, rate-limit, 2FA, and auth globals (server/globals/*), hand-declared
4347
- // because their AssemblyScript source can't be type-aliased from tsc.
4348
- declare enum EmailStatus { Sent, Disabled, Budget, RecipientCapped, Deduped, TryLater, BadRecipient, ProviderError }
4349
- declare namespace EmailService { function send(to: string, subject: string, body: string, purpose?: string, html?: string): EmailStatus; }
4350
- declare class RenderedEmail { subject: string; body: string; html: string; constructor(subject: string, body: string, html: string); }
4351
- declare class EmailTemplate { constructor(subject: string, body: string, html?: string); render(vars: Map<string, string>): RenderedEmail; send(to: string, vars: Map<string, string>, purpose?: string): EmailStatus; }
4352
- declare namespace RateLimitService { function guard(routeId: i32, strategy: i32, limit: i32, window: i32): import('toiljs/server/runtime/response').Response | null; function guardKeyed(routeId: i32, strategy: i32, limit: i32, window: i32, key: string): import('toiljs/server/runtime/response').Response | null; }
4353
- declare namespace Environment { function get(key: string): string | null; function getSecure(key: string): string | null; }
4354
- declare class TwoFactorIssue { code: string; token: string; constructor(code: string, token: string); }
4355
- declare class TwoFactorChallenge { token: string; status: EmailStatus; constructor(token: string, status: EmailStatus); }
4356
- declare namespace TwoFactor { const DEFAULT_TTL_SECS: u64; const DEFAULT_DIGITS: i32; function setSecret(secret: Uint8Array): void; function issue(recipient: string, purpose: string, ttlSecs?: u64, digits?: i32): TwoFactorIssue; function send(recipient: string, purpose: string, ttlSecs?: u64, digits?: i32): TwoFactorChallenge; function verify(token: string, recipient: string, code: string): bool; }
4357
- declare namespace AuthService { const SESSION_COOKIE: string; const USER_COOKIE: string; const LOGIN_CONTEXT: string; const PUBLIC_KEY_LEN: i32; const SIGNATURE_LEN: i32; const DEFAULT_SESSION_TTL_SECS: u64; function setSecret(secret: Uint8Array): void; function hasSession(): bool; function getSessionBytes(): Uint8Array | null; function getUser(): __ToilAuthUser | null; function mintSession(userData: Uint8Array, ttlSecs?: u64): Cookie; function clearSession(): Cookie; function userCookie(userData: Uint8Array, ttlSecs?: u64): Cookie; function clearUserCookie(): Cookie; function buildLoginMessage(sub: string, aud: string, cid: Uint8Array, nonce: Uint8Array, iat: u64, exp: u64): Uint8Array; function verifyLogin(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): bool; }
4358
- interface __ToilAuthUser {}
4359
- `;
4360
4332
  var SERVER_README = "# server/\n\nYour ToilScript backend, compiled to a single WebAssembly module. One folder per concern:\n\n| Folder | What lives here |\n| --- | --- |\n| `main.ts` | The entry point: wires the handler and imports the surface modules. |\n| `core/` | The request handler and shared app logic (state, helpers). |\n| `models/` | `@data` classes, the typed wire model shared by HTTP and RPC. One type per file. |\n| `migrations/` | ToilDB schema migrations: a `<Type>.migration.ts` per evolving `@data` value type, holding the old shapes + the `@migrate` transform. |\n| `routes/` | `@rest` controllers (HTTP). One controller per file, named after its class. |\n| `services/` | `@service` classes and free `@remote` functions (typed RPC). |\n| `scheduled/` | Reserved for scheduled tasks (not shipped yet). |\n\nNew decorated files are picked up automatically by `toiljs build`/`dev`; also add an import\nin `main.ts` so a direct `toilscript` run builds the same server.\n";
4361
4333
  function minimalServer() {
4362
4334
  return {
@@ -5164,7 +5136,7 @@ function checkWasmBuilt(exists) {
5164
5136
  fix: "Run your server build (toilscript) before toiljs start."
5165
5137
  };
5166
5138
  }
5167
- var RPC_TOILSCRIPT_MIN = "0.1.65";
5139
+ var RPC_TOILSCRIPT_MIN = "0.1.66";
5168
5140
  function checkRpcWiring(f) {
5169
5141
  const missing = [];
5170
5142
  if (!f.toilscriptOk) missing.push(`toilscript >=${RPC_TOILSCRIPT_MIN}`);
@@ -1,4 +1,5 @@
1
1
  import { useEffect } from 'react';
2
+ import { isDataScript, setScriptBody, setScriptData, setScriptSource } from '../security.js';
2
3
  const registry = new Map();
3
4
  function inject(props, key) {
4
5
  const { src, type, onLoad, onReady, onError, children } = props;
@@ -6,27 +7,29 @@ function inject(props, key) {
6
7
  el.dataset.toilScript = key;
7
8
  if (type !== undefined)
8
9
  el.type = type;
9
- if (src !== undefined) {
10
- el.src = src;
11
- el.async = true;
12
- el.addEventListener('load', () => {
13
- registry.set(key, 'ready');
14
- onLoad?.();
15
- onReady?.();
16
- });
17
- el.addEventListener('error', (event) => {
18
- registry.delete(key);
19
- onError?.(event);
20
- });
21
- document.head.appendChild(el);
22
- }
23
- else {
24
- el.textContent = children ?? '';
10
+ if (src !== undefined)
11
+ setScriptSource(el, src);
12
+ else if (isDataScript(type ?? '')) {
13
+ setScriptData(el, children ?? '');
25
14
  document.head.appendChild(el);
26
15
  registry.set(key, 'ready');
27
16
  onLoad?.();
28
17
  onReady?.();
18
+ return;
29
19
  }
20
+ else
21
+ setScriptBody(el, children ?? '');
22
+ el.async = true;
23
+ el.addEventListener('load', () => {
24
+ registry.set(key, 'ready');
25
+ onLoad?.();
26
+ onReady?.();
27
+ });
28
+ el.addEventListener('error', (event) => {
29
+ registry.delete(key);
30
+ onError?.(event);
31
+ });
32
+ document.head.appendChild(el);
30
33
  }
31
34
  export function Script(props) {
32
35
  const { src, id, strategy = 'afterInteractive', onReady } = props;
@@ -45,7 +48,15 @@ export function Script(props) {
45
48
  }
46
49
  registry.set(key, 'loading');
47
50
  const run = () => {
48
- inject(props, key);
51
+ try {
52
+ inject(props, key);
53
+ }
54
+ catch (error) {
55
+ registry.delete(key);
56
+ props.onError?.(error);
57
+ if (!props.onError)
58
+ throw error;
59
+ }
49
60
  };
50
61
  if (strategy === 'lazyOnload') {
51
62
  if (document.readyState === 'complete') {
@@ -0,0 +1,17 @@
1
+ export interface BlobUploadTicket {
2
+ url: string;
3
+ fields: readonly {
4
+ name: string;
5
+ value: string;
6
+ }[];
7
+ size: number;
8
+ expiresAt: number;
9
+ }
10
+ export declare function uploadBlob(ticket: BlobUploadTicket, file: Blob, signal?: AbortSignal): Promise<void>;
11
+ export declare function uploadBlobStream(ticket: BlobUploadTicket, source: ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<void>;
12
+ export interface BlobRange {
13
+ start: number;
14
+ end?: number;
15
+ }
16
+ export declare function readBlob(url: string, range?: BlobRange, signal?: AbortSignal): Promise<Response>;
17
+ export declare function deleteBlob(url: string, signal?: AbortSignal): Promise<void>;
@@ -0,0 +1,119 @@
1
+ export async function uploadBlob(ticket, file, signal) {
2
+ if (file.size !== ticket.size)
3
+ throw new Error('Blob size differs from upload ticket');
4
+ const body = new FormData();
5
+ for (const field of ticket.fields)
6
+ body.append(field.name, field.value);
7
+ body.append('file', file, 'blob');
8
+ const result = await fetch(ticket.url, {
9
+ method: 'POST',
10
+ body,
11
+ signal,
12
+ credentials: 'omit',
13
+ redirect: 'error',
14
+ });
15
+ if (!result.ok)
16
+ throw new Error(`Blob upload failed (${result.status})`);
17
+ }
18
+ export async function uploadBlobStream(ticket, source, signal) {
19
+ const boundary = 'toil-' + crypto.randomUUID();
20
+ let prefix = '';
21
+ for (const field of ticket.fields) {
22
+ if (!/^[A-Za-z0-9_-]+$/.test(field.name))
23
+ throw new Error('Invalid blob form field');
24
+ prefix += `--${boundary}\r\nContent-Disposition: form-data; name="${field.name}"\r\n\r\n${field.value}\r\n`;
25
+ }
26
+ prefix += `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="blob"\r\nContent-Type: application/octet-stream\r\n\r\n`;
27
+ const encoder = new TextEncoder(), reader = source.getReader();
28
+ let started = false, complete = false, total = 0;
29
+ const body = new ReadableStream({
30
+ async pull(controller) {
31
+ if (!started) {
32
+ started = true;
33
+ controller.enqueue(encoder.encode(prefix));
34
+ return;
35
+ }
36
+ try {
37
+ const next = await reader.read();
38
+ if (next.done) {
39
+ if (total !== ticket.size)
40
+ throw new Error('Blob stream size differs from upload ticket');
41
+ complete = true;
42
+ controller.enqueue(encoder.encode(`\r\n--${boundary}--\r\n`));
43
+ controller.close();
44
+ reader.releaseLock();
45
+ }
46
+ else {
47
+ total += next.value.byteLength;
48
+ if (total > ticket.size)
49
+ throw new Error('Blob stream exceeds upload ticket');
50
+ controller.enqueue(next.value);
51
+ }
52
+ }
53
+ catch (error) {
54
+ controller.error(error);
55
+ await reader.cancel(error);
56
+ reader.releaseLock();
57
+ }
58
+ },
59
+ async cancel(reason) {
60
+ if (!complete) {
61
+ await reader.cancel(reason);
62
+ reader.releaseLock();
63
+ }
64
+ },
65
+ });
66
+ try {
67
+ const options = {
68
+ method: 'POST',
69
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
70
+ body,
71
+ signal,
72
+ credentials: 'omit',
73
+ redirect: 'error',
74
+ duplex: 'half',
75
+ };
76
+ const result = await fetch(ticket.url, options);
77
+ if (!result.ok)
78
+ throw new Error(`Blob upload failed (${result.status})`);
79
+ }
80
+ finally {
81
+ if (!complete) {
82
+ try {
83
+ await reader.cancel();
84
+ reader.releaseLock();
85
+ }
86
+ catch {
87
+ }
88
+ }
89
+ }
90
+ }
91
+ export async function readBlob(url, range, signal) {
92
+ const headers = {};
93
+ if (range !== undefined) {
94
+ if (!Number.isSafeInteger(range.start) ||
95
+ range.start < 0 ||
96
+ (range.end !== undefined &&
97
+ (!Number.isSafeInteger(range.end) || range.end < range.start)))
98
+ throw new Error('Invalid blob range');
99
+ headers.Range = `bytes=${range.start}-${range.end ?? ''}`;
100
+ }
101
+ const result = await fetch(url, { headers, signal, credentials: 'omit', redirect: 'error' });
102
+ if (!result.ok)
103
+ throw new Error(`Blob download failed (${result.status})`);
104
+ if (range !== undefined && result.status !== 206) {
105
+ await result.body?.cancel();
106
+ throw new Error('Storage did not honor the blob range');
107
+ }
108
+ return result;
109
+ }
110
+ export async function deleteBlob(url, signal) {
111
+ const result = await fetch(url, {
112
+ method: 'DELETE',
113
+ signal,
114
+ credentials: 'omit',
115
+ redirect: 'error',
116
+ });
117
+ if (!result.ok)
118
+ throw new Error(`Blob deletion failed (${result.status})`);
119
+ }
@@ -0,0 +1 @@
1
+ export declare function sanitizeHtml(html: string): string | TrustedHTML;
@@ -0,0 +1,8 @@
1
+ import createDOMPurify from 'dompurify';
2
+ let purifier;
3
+ export function sanitizeHtml(html) {
4
+ if (typeof window === 'undefined')
5
+ throw new Error('sanitizeHtml requires a browser DOM. Sanitize server HTML before rendering.');
6
+ purifier ??= createDOMPurify(window);
7
+ return purifier.sanitize(html, { RETURN_TRUSTED_TYPE: true });
8
+ }
@@ -42,3 +42,4 @@ export { Server } from './rpc.js';
42
42
  export { parseError } from './errors.js';
43
43
  export { Hole, RawHtml, Repeat, Island, attr, __setSsrBuild, __isSsrBuild } from './ssr/markers.js';
44
44
  export type { HoleProps, RawHtmlProps, RepeatProps, IslandProps } from './ssr/markers.js';
45
+ export { sanitizeHtml } from './html.js';
@@ -22,3 +22,4 @@ export { Slot } from './components/Slot.js';
22
22
  export { Server } from './rpc.js';
23
23
  export { parseError } from './errors.js';
24
24
  export { Hole, RawHtml, Repeat, Island, attr, __setSsrBuild, __isSsrBuild } from './ssr/markers.js';
25
+ export { sanitizeHtml } from './html.js';
@@ -33,7 +33,7 @@ function renderMatched(matched, params, pathname, epoch, keyPrefix) {
33
33
  }
34
34
  const chain = matched.layouts ?? [];
35
35
  for (let i = chain.length - 1; i >= 0; i--) {
36
- content = (_jsx(Suspense, { fallback: null, children: _jsx(DataLayout, { load: chain[i], params: params, dataKey: `layout:${String(i)}:${dataKey}`, epoch: epoch, children: content }) }));
36
+ content = (_jsx(Suspense, { fallback: fallback, children: _jsx(DataLayout, { load: chain[i], params: params, dataKey: `layout:${String(i)}:${dataKey}`, epoch: epoch, children: content }) }));
37
37
  }
38
38
  if (matched.errorComponent) {
39
39
  content = (_jsx(ErrorBoundary, { fallback: errorComponent(matched.errorComponent), children: content }));
@@ -0,0 +1,4 @@
1
+ export declare function isDataScript(type: string): boolean;
2
+ export declare function setScriptSource(element: HTMLScriptElement, value: string): void;
3
+ export declare function setScriptBody(element: HTMLScriptElement, value: string): void;
4
+ export declare function setScriptData(element: HTMLScriptElement, value: string): void;
@@ -0,0 +1,55 @@
1
+ let policy;
2
+ const inlineUrls = new Set();
3
+ export function isDataScript(type) {
4
+ const mime = type.toLowerCase().split(';')[0].trim();
5
+ return (mime !== '' &&
6
+ mime !== 'module' &&
7
+ !/^(?:text|application)\/(?:x-)?(?:javascript(?:1\.[0-5])?|ecmascript|jscript|livescript)$/.test(mime));
8
+ }
9
+ function scriptUrl(value) {
10
+ const url = new URL(value, document.baseURI);
11
+ if (url.protocol !== 'http:' && url.protocol !== 'https:' && !inlineUrls.has(url.href)) {
12
+ throw new TypeError('Toil.Script requires an HTTP(S) script URL.');
13
+ }
14
+ return url.href;
15
+ }
16
+ function scriptPolicy() {
17
+ const factory = globalThis
18
+ .trustedTypes;
19
+ if (!factory)
20
+ return undefined;
21
+ return (policy ??= factory.createPolicy('toil-script', {
22
+ createScriptURL: scriptUrl,
23
+ createScript(value, type) {
24
+ if (!isDataScript(type))
25
+ throw new TypeError('Executable scripts must load through a script URL.');
26
+ return value;
27
+ },
28
+ }));
29
+ }
30
+ export function setScriptSource(element, value) {
31
+ const url = scriptUrl(value);
32
+ element.src = (scriptPolicy()?.createScriptURL(url) ?? url);
33
+ }
34
+ export function setScriptBody(element, value) {
35
+ const url = URL.createObjectURL(new Blob([value], { type: 'text/javascript' }));
36
+ inlineUrls.add(url);
37
+ const release = () => {
38
+ URL.revokeObjectURL(url);
39
+ inlineUrls.delete(url);
40
+ };
41
+ element.addEventListener('load', release, { once: true });
42
+ element.addEventListener('error', release, { once: true });
43
+ try {
44
+ setScriptSource(element, url);
45
+ }
46
+ catch (error) {
47
+ release();
48
+ throw error;
49
+ }
50
+ }
51
+ export function setScriptData(element, value) {
52
+ if (!isDataScript(element.type))
53
+ throw new TypeError('Expected an inert script data type.');
54
+ element.text = (scriptPolicy()?.createScript(value, element.type) ?? value);
55
+ }
@@ -1,4 +1,5 @@
1
1
  import { createElement, Fragment, useEffect, useState } from 'react';
2
+ import { sanitizeHtml } from '../html.js';
2
3
  export const SENTINEL_START = String.fromCharCode(0xe000);
3
4
  export const SENTINEL_SEP = String.fromCharCode(0xe001);
4
5
  export const SENTINEL_END = String.fromCharCode(0xe002);
@@ -36,7 +37,11 @@ export function RawHtml(props) {
36
37
  if (ssrBuild) {
37
38
  return createElement(tag, null, token("h", props.id));
38
39
  }
39
- return createElement(tag, { dangerouslySetInnerHTML: { __html: props.html } });
40
+ return createElement(tag, {
41
+ dangerouslySetInnerHTML: {
42
+ __html: typeof window === 'undefined' ? props.html : sanitizeHtml(props.html),
43
+ },
44
+ });
40
45
  }
41
46
  export function Repeat(props) {
42
47
  if (ssrBuild) {
@@ -26,6 +26,7 @@ export interface ClientConfig {
26
26
  readonly host?: string;
27
27
  readonly images?: boolean;
28
28
  readonly fonts?: boolean;
29
+ readonly cspSources?: Readonly<Record<string, readonly string[]>>;
29
30
  readonly viewTransitions?: boolean;
30
31
  readonly transitions?: boolean;
31
32
  readonly devtools?: boolean | DevtoolsConfig;
@@ -76,6 +77,7 @@ export interface ResolvedToilConfig {
76
77
  readonly host: string;
77
78
  readonly images: boolean;
78
79
  readonly fonts: boolean;
80
+ readonly cspSources?: Readonly<Record<string, readonly string[]>>;
79
81
  readonly viewTransitions: boolean;
80
82
  readonly transitions: boolean;
81
83
  readonly devtools: boolean;
@@ -53,6 +53,7 @@ export async function loadConfig(opts = {}) {
53
53
  host: opts.host ?? envHost() ?? client.host ?? '127.0.0.1',
54
54
  images: client.images ?? true,
55
55
  fonts: client.fonts ?? true,
56
+ cspSources: client.cspSources ?? {},
56
57
  viewTransitions: client.viewTransitions ?? false,
57
58
  transitions: client.transitions ?? false,
58
59
  devtools: client.devtools !== false,
@@ -1,7 +1,7 @@
1
1
  import { type ResolvedToilConfig } from './config.js';
2
2
  import { type ScannedRoute } from './routes.js';
3
3
  export declare const TOIL_ENV_DTS: string;
4
- export declare const TOIL_SERVER_ENV_DTS: string;
4
+ export declare const TOIL_SERVER_ENV_DTS = "/// <reference types=\"toiljs/server/globals\" />\n";
5
5
  export declare function findLayout(cfg: ResolvedToilConfig): string | undefined;
6
6
  export declare function findSpecialChain(cfg: ResolvedToilConfig, routeFile: string, base: string, includeClientRoot: boolean): string[];
7
7
  export declare function generate(cfg: ResolvedToilConfig): ScannedRoute[];
@@ -50,43 +50,7 @@ export const TOIL_ENV_DTS = `// AUTO-GENERATED by toil, do not edit.\n` +
50
50
  ` export const slots: Record<string, import('toiljs/client').RouteDef[]>;\n` +
51
51
  ` export const pages: import('toiljs/client').PageMeta[];\n` +
52
52
  `}\n`;
53
- export const TOIL_SERVER_ENV_DTS = `// AUTO-GENERATED by toil, do not edit. Editor-only ambient declarations for\n` +
54
- `// the toiljs server-runtime globals (Cookie, Cookies, SecureCookies, the\n` +
55
- `// cookie enums): @global in the runtime, used with no import. These alias the\n` +
56
- `// real runtime types so a global-built Cookie is exactly what Response.setCookie\n` +
57
- `// / SecureCookies.seal expect. The toilscript compiler registers them itself.\n` +
58
- `declare const SameSite: typeof import('toiljs/server/runtime/http/cookie').SameSite;\n` +
59
- `type SameSite = import('toiljs/server/runtime/http/cookie').SameSite;\n` +
60
- `declare const CookieEncoding: typeof import('toiljs/server/runtime/http/cookie').CookieEncoding;\n` +
61
- `type CookieEncoding = import('toiljs/server/runtime/http/cookie').CookieEncoding;\n` +
62
- `declare const CookiePrefix: typeof import('toiljs/server/runtime/http/cookie').CookiePrefix;\n` +
63
- `type CookiePrefix = import('toiljs/server/runtime/http/cookie').CookiePrefix;\n` +
64
- `declare const CookieValidation: typeof import('toiljs/server/runtime/http/cookie').CookieValidation;\n` +
65
- `type CookieValidation = import('toiljs/server/runtime/http/cookie').CookieValidation;\n` +
66
- `declare const Cookie: typeof import('toiljs/server/runtime/http/cookie').Cookie;\n` +
67
- `type Cookie = import('toiljs/server/runtime/http/cookie').Cookie;\n` +
68
- `declare const CookieMap: typeof import('toiljs/server/runtime/http/cookies').CookieMap;\n` +
69
- `type CookieMap = import('toiljs/server/runtime/http/cookies').CookieMap;\n` +
70
- `declare const Cookies: typeof import('toiljs/server/runtime/http/cookies').Cookies;\n` +
71
- `type Cookies = import('toiljs/server/runtime/http/cookies').Cookies;\n` +
72
- `declare const SecureCookies: typeof import('toiljs/server/runtime/http/securecookies').SecureCookies;\n` +
73
- `type SecureCookies = import('toiljs/server/runtime/http/securecookies').SecureCookies;\n` +
74
- `declare const Time: typeof import('toiljs/server/runtime/time').Time;\n` +
75
- `// Email, rate-limit, 2FA, and auth globals (server/globals/*), hand-declared\n` +
76
- `// because their AssemblyScript source can't be type-aliased from tsc.\n` +
77
- `declare enum EmailStatus { Sent, Disabled, Budget, RecipientCapped, Deduped, TryLater, BadRecipient, ProviderError }\n` +
78
- `declare namespace EmailService { function send(to: string, subject: string, body: string, purpose?: string, html?: string): EmailStatus; }\n` +
79
- `declare class RenderedEmail { subject: string; body: string; html: string; constructor(subject: string, body: string, html: string); }\n` +
80
- `declare class EmailTemplate { constructor(subject: string, body: string, html?: string); render(vars: Map<string, string>): RenderedEmail; send(to: string, vars: Map<string, string>, purpose?: string): EmailStatus; }\n` +
81
- `declare namespace RateLimitService { function guard(routeId: i32, strategy: i32, limit: i32, window: i32): import('toiljs/server/runtime/response').Response | null; function guardKeyed(routeId: i32, strategy: i32, limit: i32, window: i32, key: string): import('toiljs/server/runtime/response').Response | null; }\n` +
82
- `declare namespace Environment { function get(key: string): string | null; function getSecure(key: string): string | null; }\n` +
83
- `declare class TwoFactorIssue { code: string; token: string; constructor(code: string, token: string); }\n` +
84
- `declare class TwoFactorChallenge { token: string; status: EmailStatus; constructor(token: string, status: EmailStatus); }\n` +
85
- `declare namespace TwoFactor { const DEFAULT_TTL_SECS: u64; const DEFAULT_DIGITS: i32; function setSecret(secret: Uint8Array): void; function issue(recipient: string, purpose: string, ttlSecs?: u64, digits?: i32): TwoFactorIssue; function send(recipient: string, purpose: string, ttlSecs?: u64, digits?: i32): TwoFactorChallenge; function verify(token: string, recipient: string, code: string): bool; }\n` +
86
- `declare namespace AuthService { const SESSION_COOKIE: string; const USER_COOKIE: string; const LOGIN_CONTEXT: string; const PUBLIC_KEY_LEN: i32; const SIGNATURE_LEN: i32; const DEFAULT_SESSION_TTL_SECS: u64; function setSecret(secret: Uint8Array): void; function hasSession(): bool; function getSessionBytes(): Uint8Array | null; function getUser(): __ToilAuthUser | null; function userId(): ToilUserId | null; function enable(): void; function mintSession(userData: Uint8Array, ttlSecs?: u64): Cookie; function clearSession(): Cookie; function revokeUserSessions(userData: Uint8Array): void; function userCookie(userData: Uint8Array, ttlSecs?: u64): Cookie; function clearUserCookie(): Cookie; function buildLoginMessage(sub: string, aud: string, cid: Uint8Array, nonce: Uint8Array, iat: u64, exp: u64, ciphertext: Uint8Array, memKiB: u32, iterations: u32, parallelism: u32, serverKemKeyId: Uint8Array): Uint8Array; function verifyLogin(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): bool; const KEM_CIPHERTEXT_LEN: i32; const KEM_SECRET_KEY_LEN: i32; const KEM_PUBLIC_KEY_LEN: i32; const SHARED_SECRET_LEN: i32; const OPRF_ELEMENT_LEN: i32; const OPRF_SEED_LEN: i32; const SESSION_KEY_LABEL: string; const SERVER_CONFIRM_LABEL: string; function setOprfSeed(seed: Uint8Array): void; function setServerKemSecretKey(secretKey: Uint8Array): void; function setServerKemPublicKey(publicKey: Uint8Array): void; function serverKemKeyId(): Uint8Array; function oprfEvaluate(username: string, blinded: Uint8Array): Uint8Array; function mlkemDecapsulate(ciphertext: Uint8Array): Uint8Array; function sha256(data: Uint8Array): Uint8Array; function deriveSessionKey(sharedSecret: Uint8Array, transcriptHash: Uint8Array): Uint8Array; function serverConfirmTag(sessionKey: Uint8Array, transcriptHash: Uint8Array): Uint8Array; const REGISTER_CONTEXT: string; function buildRegisterMessage(username: string, publicKey: Uint8Array): Uint8Array; function verifyRegister(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): bool; }\n` +
87
- `interface __ToilAuthUser {}\n` +
88
- `declare class ToilUserId { w0: u64; w1: u64; w2: u64; w3: u64; constructor(w0?: u64, w1?: u64, w2?: u64, w3?: u64); static derive(mldsaPublicKey: Uint8Array, identifier: string, domain: string): ToilUserId; static fromBytes(b: Uint8Array): ToilUserId; toBytes(): Uint8Array; toHex(): string; isZero(): bool; equals(other: ToilUserId): bool; }\n` +
89
- `declare function __toilEncodeAuthUser(toilUserId: Uint8Array, username: string): Uint8Array;\n`;
53
+ export const TOIL_SERVER_ENV_DTS = '/// <reference types="toiljs/server/globals" />\n';
90
54
  function relFromToil(cfg, abs) {
91
55
  let rel = path
92
56
  .relative(cfg.toilDir, abs)
@@ -2,6 +2,7 @@ import { type ViteDevServer } from 'vite';
2
2
  import type { RunningBackend } from 'toiljs/backend';
3
3
  export declare const SURFACE_DECORATOR: RegExp;
4
4
  export declare function buildServer(root: string, auth?: boolean): Promise<void>;
5
+ export declare function validateDeriveContinuationArtifacts(hot: Buffer | null, cold: Buffer | null): void;
5
6
  interface SurfaceSplit {
6
7
  readonly hasDaemon: boolean;
7
8
  readonly hasStream: boolean;