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.
- package/CHANGELOG.md +29 -0
- package/assets/image-codec-LICENSES.txt +4599 -0
- package/assets/image-codec-build.json +10 -0
- package/assets/image-codec.wasm +0 -0
- package/build/backend/index.d.ts +1 -0
- package/build/backend/index.js +8 -3
- package/build/backend/security.d.ts +4 -0
- package/build/backend/security.js +31 -0
- package/build/cli/index.js +11 -39
- package/build/client/components/Script.js +28 -17
- package/build/client/files.d.ts +17 -0
- package/build/client/files.js +119 -0
- package/build/client/html.d.ts +1 -0
- package/build/client/html.js +8 -0
- package/build/client/index.d.ts +1 -0
- package/build/client/index.js +1 -0
- package/build/client/security.d.ts +4 -0
- package/build/client/security.js +55 -0
- package/build/client/ssr/markers.js +6 -1
- package/build/compiler/config.d.ts +2 -0
- package/build/compiler/config.js +1 -0
- package/build/compiler/generate.d.ts +1 -1
- package/build/compiler/generate.js +1 -37
- package/build/compiler/index.d.ts +1 -0
- package/build/compiler/index.js +56 -1
- package/build/compiler/security-deployment.d.ts +3 -0
- package/build/compiler/security-deployment.js +88 -0
- package/build/compiler/security.d.ts +7 -0
- package/build/compiler/security.js +74 -0
- package/build/compiler/sri.js +10 -3
- package/build/compiler/toil-docs.generated.js +35 -28
- package/build/compiler/vite.js +2 -0
- package/build/devserver/config/env.d.ts +6 -0
- package/build/devserver/config/env.js +10 -2
- package/build/devserver/daemon/catalog.d.ts +1 -0
- package/build/devserver/daemon/catalog.js +10 -4
- package/build/devserver/daemon/host.d.ts +5 -1
- package/build/devserver/daemon/host.js +8 -4
- package/build/devserver/daemon/http.d.ts +14 -0
- package/build/devserver/daemon/http.js +90 -0
- package/build/devserver/daemon/index.d.ts +21 -1
- package/build/devserver/daemon/index.js +109 -21
- package/build/devserver/db/atomic.d.ts +8 -0
- package/build/devserver/db/atomic.js +133 -0
- package/build/devserver/db/catalog.d.ts +7 -0
- package/build/devserver/db/catalog.js +17 -0
- package/build/devserver/db/changes.d.ts +5 -0
- package/build/devserver/db/changes.js +49 -0
- package/build/devserver/db/database.d.ts +7 -0
- package/build/devserver/db/database.js +251 -41
- package/build/devserver/db/derives.d.ts +4 -5
- package/build/devserver/db/derives.js +7 -76
- package/build/devserver/db/document-scan.d.ts +2 -0
- package/build/devserver/db/document-scan.js +123 -0
- package/build/devserver/db/limits.d.ts +16 -0
- package/build/devserver/db/limits.js +92 -14
- package/build/devserver/db/types.d.ts +15 -0
- package/build/devserver/db/types.js +9 -0
- package/build/devserver/files/dev.d.ts +3 -0
- package/build/devserver/files/dev.js +29 -0
- package/build/devserver/files/disk.d.ts +17 -0
- package/build/devserver/files/disk.js +369 -0
- package/build/devserver/files/signatures.d.ts +16 -0
- package/build/devserver/files/signatures.js +151 -0
- package/build/devserver/http/proxy.js +11 -3
- package/build/devserver/http/runtime.js +36 -9
- package/build/devserver/images/index.d.ts +9 -0
- package/build/devserver/images/index.js +87 -0
- package/build/devserver/images/worker.d.mts +1 -0
- package/build/devserver/images/worker.mjs +24 -0
- package/build/devserver/index.d.ts +3 -1
- package/build/devserver/production.js +5 -3
- package/build/devserver/runtime/host.d.ts +4 -0
- package/build/devserver/runtime/host.js +6 -2
- package/build/devserver/runtime/module.d.ts +15 -0
- package/build/devserver/runtime/module.js +105 -7
- package/build/devserver/server.js +13 -1
- package/build/devserver/stream/host.d.ts +2 -0
- package/build/devserver/stream/host.js +2 -1
- package/build/devserver/stream/index.js +2 -0
- package/build/io/derive-metadata.d.ts +7 -0
- package/build/io/derive-metadata.js +44 -0
- package/build/io/index.d.ts +1 -0
- package/build/io/index.js +1 -0
- package/build/shared/index.d.ts +1 -0
- package/build/shared/index.js +1 -0
- package/build/shared/security.d.ts +5 -0
- package/build/shared/security.js +80 -0
- package/docs/auth/vectors-v1.json +41 -0
- package/examples/basic/client/routes/rest.tsx +1 -1
- package/examples/basic/server/routes/Guestbook.ts +1 -1
- package/package.json +20 -7
- package/scripts/build-image-codec.mjs +79 -0
- package/scripts/gen-auth-vectors.mjs +132 -0
- package/scripts/gen-native-atomic-fixture.mjs +39 -0
- package/scripts/gen-native-blob-fixture.mjs +42 -0
- package/scripts/gen-native-image-fixture.mjs +65 -0
- package/scripts/gen-native-staging-fixture.mjs +41 -0
- package/scripts/gen-server-types.mjs +82 -0
- package/scripts/gen-toil-docs.mjs +19 -7
- package/server/auth/AuthController.ts +15 -234
- package/server/auth/AuthMaintenance.ts +177 -0
- package/server/auth/AuthStore.ts +198 -0
- package/server/auth/SessionEpochs.ts +38 -9
- package/server/globals/auth.ts +56 -0
- package/server/globals/userid.ts +4 -5
- package/server/globals.d.ts +37 -0
- package/server/runtime/envelope.ts +2 -1
- package/server/runtime/exports/index.ts +2 -1
- package/server/runtime/files/blobs.ts +341 -0
- package/server/runtime/files/images.ts +36 -0
- package/server/runtime/http/percent.ts +5 -4
- package/server/runtime/index.ts +5 -0
- package/server/runtime/response.ts +20 -0
- package/server/runtime/rest/RouteContext.ts +5 -4
- package/std/server/abort/abort.d.ts +25 -0
- package/std/server/env/Server.d.ts +47 -0
- package/std/server/envelope.d.ts +38 -0
- package/std/server/exports/index.d.ts +20 -0
- package/std/server/exports/render.d.ts +15 -0
- package/std/server/files/blobs.d.ts +50 -0
- package/std/server/files/images.d.ts +36 -0
- package/std/server/handlers/ToilHandler.d.ts +29 -0
- package/std/server/http/base64.d.ts +21 -0
- package/std/server/http/cookie.d.ts +127 -0
- package/std/server/http/cookies.d.ts +56 -0
- package/std/server/http/date.d.ts +17 -0
- package/std/server/http/percent.d.ts +19 -0
- package/std/server/http/securecookies.d.ts +55 -0
- package/std/server/index.d.ts +34 -0
- package/std/server/lang/Potential.d.ts +6 -0
- package/std/server/memory.d.ts +42 -0
- package/std/server/request.d.ts +47 -0
- package/std/server/response.d.ts +90 -0
- package/std/server/rest/Rest.d.ts +23 -0
- package/std/server/rest/RestHandler.d.ts +14 -0
- package/std/server/rest/RouteContext.d.ts +33 -0
- package/std/server/rest/match.d.ts +14 -0
- package/std/server/rpc/Rpc.d.ts +37 -0
- package/std/server/ssr/Ssr.d.ts +27 -0
- package/std/server/ssr/encode.d.ts +26 -0
- package/std/server/ssr/escape.d.ts +22 -0
- package/std/server/ssr/slots.d.ts +91 -0
- package/std/server/time.d.ts +24 -0
- package/tsconfig.json +11 -2
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { DbFunctionKind } from '../db/types.js';
|
|
4
|
+
export const freshImageState = () => ({ result: null, calls: 0 });
|
|
5
|
+
export function resetImageState(state) {
|
|
6
|
+
state.result?.fill(0);
|
|
7
|
+
state.result = null;
|
|
8
|
+
state.calls = 0;
|
|
9
|
+
}
|
|
10
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
function memory(ref) {
|
|
12
|
+
if (ref.memory === null)
|
|
13
|
+
throw new Error('image: memory not bound');
|
|
14
|
+
return Buffer.from(ref.memory.buffer);
|
|
15
|
+
}
|
|
16
|
+
export function buildImageImports(ref, state, kind) {
|
|
17
|
+
return {
|
|
18
|
+
'image.process': (ptr, len, mode, width, height, quality) => {
|
|
19
|
+
state.result?.fill(0);
|
|
20
|
+
state.result = null;
|
|
21
|
+
if (![DbFunctionKind.Action, DbFunctionKind.Job, DbFunctionKind.Derive].includes(kind()))
|
|
22
|
+
return -9;
|
|
23
|
+
if (state.calls++ !== 0)
|
|
24
|
+
return -10;
|
|
25
|
+
if (len < 0 || len > MAX_BYTES)
|
|
26
|
+
return -4;
|
|
27
|
+
if (mode < 0 ||
|
|
28
|
+
mode > 2 ||
|
|
29
|
+
quality < 1 ||
|
|
30
|
+
quality > 100 ||
|
|
31
|
+
(mode === 0 && (width !== 0 || height !== 0)) ||
|
|
32
|
+
(mode !== 0 && (width < 1 || height < 1 || width > 4096 || height > 4096)))
|
|
33
|
+
return -8;
|
|
34
|
+
const mem = memory(ref);
|
|
35
|
+
if (ptr < 0 || ptr > mem.length || len > mem.length - ptr)
|
|
36
|
+
throw new Error('image.process: input out of bounds');
|
|
37
|
+
const header = Buffer.alloc(24);
|
|
38
|
+
header[0] = 1;
|
|
39
|
+
header[1] = mode;
|
|
40
|
+
header[2] = quality;
|
|
41
|
+
header.writeUInt32LE(width, 4);
|
|
42
|
+
header.writeUInt32LE(height, 8);
|
|
43
|
+
header.writeUInt32LE(len, 20);
|
|
44
|
+
const result = spawnSync(process.execPath, [
|
|
45
|
+
'--no-warnings',
|
|
46
|
+
'--max-old-space-size=128',
|
|
47
|
+
fileURLToPath(new URL('./worker.mjs', import.meta.url)),
|
|
48
|
+
], {
|
|
49
|
+
input: Buffer.concat([header, mem.subarray(ptr, ptr + len)]),
|
|
50
|
+
timeout: 5000,
|
|
51
|
+
maxBuffer: MAX_BYTES + 19,
|
|
52
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
53
|
+
});
|
|
54
|
+
if (result.error !== undefined)
|
|
55
|
+
return 'code' in result.error && result.error.code === 'ETIMEDOUT' ? -6 : -7;
|
|
56
|
+
const bytes = result.stdout;
|
|
57
|
+
if (result.status !== 0 || bytes.length < 4 || bytes.length > MAX_BYTES + 18)
|
|
58
|
+
return -7;
|
|
59
|
+
const status = bytes.readInt32LE();
|
|
60
|
+
if (status < 0)
|
|
61
|
+
return status;
|
|
62
|
+
const frame = bytes.subarray(4);
|
|
63
|
+
if (status !== 0 ||
|
|
64
|
+
frame.length < 14 ||
|
|
65
|
+
frame[0] !== 1 ||
|
|
66
|
+
![1, 2].includes(frame[9]) ||
|
|
67
|
+
frame.readUInt32LE(10) !== frame.length - 14)
|
|
68
|
+
return -7;
|
|
69
|
+
state.result = Buffer.from(frame);
|
|
70
|
+
return frame.length;
|
|
71
|
+
},
|
|
72
|
+
'image.take_result': (ptr, cap) => {
|
|
73
|
+
const result = state.result ?? Buffer.alloc(0), mem = memory(ref);
|
|
74
|
+
if (ptr < 0 ||
|
|
75
|
+
cap < 0 ||
|
|
76
|
+
ptr > mem.length ||
|
|
77
|
+
Math.min(cap, result.length) > mem.length - ptr)
|
|
78
|
+
throw new Error('image.take_result: output out of bounds');
|
|
79
|
+
if (cap < result.length)
|
|
80
|
+
return -1;
|
|
81
|
+
result.copy(mem, ptr);
|
|
82
|
+
result.fill(0);
|
|
83
|
+
state.result = null;
|
|
84
|
+
return result.length;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { WASI } from 'node:wasi';
|
|
3
|
+
try {
|
|
4
|
+
const module = await WebAssembly.compile(readFileSync(new URL('../../../assets/image-codec.wasm', import.meta.url)));
|
|
5
|
+
const wasi = new WASI({
|
|
6
|
+
version: 'preview1',
|
|
7
|
+
args: [],
|
|
8
|
+
env: {},
|
|
9
|
+
preopens: {},
|
|
10
|
+
returnOnExit: true,
|
|
11
|
+
});
|
|
12
|
+
const instance = await WebAssembly.instantiate(module, wasi.getImportObject());
|
|
13
|
+
const code = wasi.start(instance);
|
|
14
|
+
if (code !== 0) {
|
|
15
|
+
const error = Buffer.alloc(4);
|
|
16
|
+
error.writeInt32LE(-4);
|
|
17
|
+
process.stdout.write(error);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
const status = Buffer.alloc(4);
|
|
22
|
+
status.writeInt32LE(error instanceof WebAssembly.RuntimeError ? -4 : -7);
|
|
23
|
+
process.stdout.write(status);
|
|
24
|
+
}
|
|
@@ -5,11 +5,13 @@ export type { BuiltServerOptions, RunningBuiltServer } from './production.js';
|
|
|
5
5
|
export { METHOD_CODES, encodeRequestEnvelope, decodeResponseEnvelope, unpackHandleResult, } from './http/envelope.js';
|
|
6
6
|
export type { EnvelopeRequest, EnvelopeResponse } from './http/envelope.js';
|
|
7
7
|
export { WasmServerModule, WasmAbortError, UNHANDLED_HEADER } from './runtime/module.js';
|
|
8
|
-
export type { WasmDispatchResult } from './runtime/module.js';
|
|
8
|
+
export type { WasmDispatchResult, DatabaseInterleavingPoint, DispatchInterleaving, } from './runtime/module.js';
|
|
9
9
|
export { buildHostImports, freshDispatchState } from './runtime/host.js';
|
|
10
10
|
export type { DispatchState, MemoryRef } from './runtime/host.js';
|
|
11
11
|
export type { ViteTarget } from './http/proxy.js';
|
|
12
12
|
export { DaemonHost, daemonEmulationEnabled } from './daemon/index.js';
|
|
13
|
+
export type { DaemonHostOptions, DaemonTaskResult } from './daemon/index.js';
|
|
14
|
+
export type { DaemonHttpMock, DaemonHttpRequest, DaemonHttpResponse } from './daemon/http.js';
|
|
13
15
|
export { parseDaemonCatalog } from './daemon/catalog.js';
|
|
14
16
|
export type { DaemonCatalog, ScheduledTask, CronMasks } from './daemon/catalog.js';
|
|
15
17
|
export { buildDaemonImports, freshDaemonState } from './daemon/host.js';
|
|
@@ -5,6 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { Server, } from '@dacely/hyper-express';
|
|
7
7
|
import pc from 'picocolors';
|
|
8
|
+
import { installSecurityHeaders, sendSecureStaticFile, writeResponseHeader } from 'toiljs/backend';
|
|
8
9
|
import { startDaemonRuntime } from './daemon/runtime.js';
|
|
9
10
|
import { configureDbPersistence } from './db/index.js';
|
|
10
11
|
import { initEmailService } from './email/index.js';
|
|
@@ -72,7 +73,7 @@ function sendThreadedReply(response, reply) {
|
|
|
72
73
|
return false;
|
|
73
74
|
response.status(reply.status);
|
|
74
75
|
for (const [name, value] of reply.headers)
|
|
75
|
-
response
|
|
76
|
+
writeResponseHeader(response, name, value);
|
|
76
77
|
if (reply.sendfile !== null) {
|
|
77
78
|
response.sendFile(reply.sendfile);
|
|
78
79
|
return true;
|
|
@@ -238,6 +239,7 @@ function handleBuiltRuntimeRequest(runtime, request) {
|
|
|
238
239
|
async function startBuiltHttpServer(options, paths, dynamicHandler, runtimeOptions = {}) {
|
|
239
240
|
const cors = paths.cors;
|
|
240
241
|
const app = new Server(runtimeServerOptions(options));
|
|
242
|
+
installSecurityHeaders(app);
|
|
241
243
|
const clients = new Set();
|
|
242
244
|
installRuntimeErrorHandler(app);
|
|
243
245
|
if (cors) {
|
|
@@ -289,7 +291,7 @@ async function startBuiltHttpServer(options, paths, dynamicHandler, runtimeOptio
|
|
|
289
291
|
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
290
292
|
const file = resolveStaticFile(paths.staticRoot, request.path);
|
|
291
293
|
if (file !== null) {
|
|
292
|
-
response
|
|
294
|
+
sendSecureStaticFile(response, file);
|
|
293
295
|
return;
|
|
294
296
|
}
|
|
295
297
|
}
|
|
@@ -298,7 +300,7 @@ async function startBuiltHttpServer(options, paths, dynamicHandler, runtimeOptio
|
|
|
298
300
|
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
299
301
|
const routeHtml = resolveStaticFile(paths.staticRoot, `${request.path}/index.html`);
|
|
300
302
|
const dynHtml = routeHtml === null ? resolveDynamicFile(paths.staticRoot, request.path) : null;
|
|
301
|
-
response
|
|
303
|
+
sendSecureStaticFile(response, routeHtml ?? dynHtml ?? paths.indexHtml);
|
|
302
304
|
return;
|
|
303
305
|
}
|
|
304
306
|
response.status(404).send('not found\n');
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ImageDevState } from '../images/index.js';
|
|
1
2
|
import { type DbDevState } from '../db/index.js';
|
|
2
3
|
import { type CryptoState } from './crypto.js';
|
|
3
4
|
export declare class WasmAbortError extends Error {
|
|
@@ -11,15 +12,18 @@ export interface DispatchState {
|
|
|
11
12
|
clientIp: string;
|
|
12
13
|
crypto: CryptoState;
|
|
13
14
|
db: DbDevState;
|
|
15
|
+
images: ImageDevState;
|
|
14
16
|
}
|
|
15
17
|
export declare function freshDispatchState(): DispatchState;
|
|
16
18
|
export interface MemoryRef {
|
|
17
19
|
memory: WebAssembly.Memory | null;
|
|
20
|
+
now?: () => number;
|
|
18
21
|
}
|
|
19
22
|
export declare function readBytes(ref: MemoryRef, ptr: number, len: number): Buffer;
|
|
20
23
|
export declare function writeBytesOut(ref: MemoryRef, bytes: Buffer, outPtr: number, outCap: number): number;
|
|
21
24
|
export declare function buildEnvImports(ref: MemoryRef, _state: {
|
|
22
25
|
crypto: CryptoState;
|
|
23
26
|
db: DbDevState;
|
|
27
|
+
images: ImageDevState;
|
|
24
28
|
}): Record<string, (...a: never[]) => unknown>;
|
|
25
29
|
export declare function buildHostImports(ref: MemoryRef, state: DispatchState): WebAssembly.Imports;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { buildImageImports, freshImageState } from '../images/index.js';
|
|
1
2
|
import { devEnvGet, devEnvGetSecure } from '../config/env.js';
|
|
2
3
|
import { ratelimitCheck } from '../config/ratelimit.js';
|
|
3
4
|
import { buildAnalyticsImports } from '../analytics/index.js';
|
|
@@ -27,6 +28,7 @@ export function freshDispatchState() {
|
|
|
27
28
|
clientIp: '',
|
|
28
29
|
crypto: freshCryptoState(),
|
|
29
30
|
db: freshDbState(),
|
|
31
|
+
images: freshImageState(),
|
|
30
32
|
};
|
|
31
33
|
}
|
|
32
34
|
function mem(ref) {
|
|
@@ -148,13 +150,14 @@ function buildLogImports(ref, db) {
|
|
|
148
150
|
export function buildEnvImports(ref, _state) {
|
|
149
151
|
return {
|
|
150
152
|
...buildLogImports(ref, _state.db),
|
|
153
|
+
...buildImageImports(ref, _state.images, () => _state.db.functionKind),
|
|
151
154
|
abort: (msgPtr, filePtr, line, col) => {
|
|
152
155
|
throw new WasmAbortError(readGuestString(ref, msgPtr), readGuestString(ref, filePtr), line, col);
|
|
153
156
|
},
|
|
154
157
|
env_get: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, false),
|
|
155
158
|
env_get_secure: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, true),
|
|
156
159
|
thread_spawn: (_startArg) => -1,
|
|
157
|
-
'Date.now': () => BigInt(Date.now()),
|
|
160
|
+
'Date.now': () => BigInt(ref.now?.() ?? Date.now()),
|
|
158
161
|
email_send: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
159
162
|
email_send_detached: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
160
163
|
};
|
|
@@ -163,6 +166,7 @@ export function buildHostImports(ref, state) {
|
|
|
163
166
|
return {
|
|
164
167
|
env: {
|
|
165
168
|
...buildLogImports(ref, state.db),
|
|
169
|
+
...buildImageImports(ref, state.images, () => state.db.functionKind),
|
|
166
170
|
abort: (msgPtr, filePtr, line, col) => {
|
|
167
171
|
throw new WasmAbortError(readGuestString(ref, msgPtr), readGuestString(ref, filePtr), line, col);
|
|
168
172
|
},
|
|
@@ -215,7 +219,7 @@ export function buildHostImports(ref, state) {
|
|
|
215
219
|
env_get: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, false),
|
|
216
220
|
env_get_secure: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, true),
|
|
217
221
|
thread_spawn: (_startArg) => -1,
|
|
218
|
-
'Date.now': () => BigInt(Date.now()),
|
|
222
|
+
'Date.now': () => BigInt(ref.now?.() ?? Date.now()),
|
|
219
223
|
...buildCryptoImports(ref, state.crypto),
|
|
220
224
|
...buildDatabaseImports(ref, state.db),
|
|
221
225
|
...buildAnalyticsImports(ref, state.db),
|
|
@@ -11,6 +11,18 @@ export interface WasmDispatchResult {
|
|
|
11
11
|
readonly sendfile: string | null;
|
|
12
12
|
readonly unhandled: boolean;
|
|
13
13
|
}
|
|
14
|
+
export interface DatabaseInterleavingPoint {
|
|
15
|
+
readonly request: EnvelopeRequest;
|
|
16
|
+
readonly operation: string;
|
|
17
|
+
readonly collection: string | null;
|
|
18
|
+
readonly key: Uint8Array | null;
|
|
19
|
+
}
|
|
20
|
+
export interface DispatchInterleaving {
|
|
21
|
+
beforeDatabaseOperation?(point: DatabaseInterleavingPoint): void | Promise<void>;
|
|
22
|
+
afterDatabaseOperation?(point: DatabaseInterleavingPoint & {
|
|
23
|
+
readonly result: number | bigint;
|
|
24
|
+
}): void | Promise<void>;
|
|
25
|
+
}
|
|
14
26
|
export declare class WasmServerModule {
|
|
15
27
|
private readonly wasmPath;
|
|
16
28
|
private module;
|
|
@@ -25,6 +37,9 @@ export declare class WasmServerModule {
|
|
|
25
37
|
get available(): boolean;
|
|
26
38
|
refresh(): boolean;
|
|
27
39
|
dispatch(req: EnvelopeRequest): WasmDispatchResult;
|
|
40
|
+
dispatchAsync(req: EnvelopeRequest, hooks?: DispatchInterleaving): Promise<WasmDispatchResult>;
|
|
41
|
+
private prepareDispatch;
|
|
42
|
+
private finishDispatch;
|
|
28
43
|
dispatchRender(req: EnvelopeRequest): Uint8Array;
|
|
29
44
|
private runAffectedDerives;
|
|
30
45
|
private rebuildDerivedViewsIfStale;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { deriveChangesFrame, fullRescanFrame } from '../db/changes.js';
|
|
2
|
+
import { deriveContinuationKey, deriveCheckpointKey } from '../db/derives.js';
|
|
1
3
|
import fs from 'node:fs';
|
|
2
4
|
import { commitDeriveCheckpoints, DbFunctionKind, derivesForWrites, parseDerives, persistDb, setDbCatalog, } from '../db/index.js';
|
|
3
5
|
import { parseRouteKinds, parseRpcKinds, routeKindForRequest, rpcKindForId, } from '../db/routeKinds.js';
|
|
@@ -77,6 +79,11 @@ const PROVIDED_IMPORTS = new Set([
|
|
|
77
79
|
'data.membership_remove',
|
|
78
80
|
'data.membership_list',
|
|
79
81
|
'data.membership_page',
|
|
82
|
+
'data.documents_scan',
|
|
83
|
+
'data.atomic_get',
|
|
84
|
+
'data.atomic_batch',
|
|
85
|
+
'image.process',
|
|
86
|
+
'image.take_result',
|
|
80
87
|
'data.counter_get',
|
|
81
88
|
'data.counter_add',
|
|
82
89
|
'data.append',
|
|
@@ -100,6 +107,12 @@ const PROVIDED_IMPORTS = new Set([
|
|
|
100
107
|
'data.take_result',
|
|
101
108
|
'data.result_schema_version',
|
|
102
109
|
'data.write_allowed',
|
|
110
|
+
'data.job_allowed',
|
|
111
|
+
'data.budget',
|
|
112
|
+
'data.changes',
|
|
113
|
+
'data.begin_derive',
|
|
114
|
+
'data.end_derive',
|
|
115
|
+
'data.continue_derive',
|
|
103
116
|
]);
|
|
104
117
|
export class WasmServerModule {
|
|
105
118
|
wasmPath;
|
|
@@ -157,12 +170,80 @@ export class WasmServerModule {
|
|
|
157
170
|
return true;
|
|
158
171
|
}
|
|
159
172
|
dispatch(req) {
|
|
173
|
+
try {
|
|
174
|
+
const context = this.prepareDispatch(req);
|
|
175
|
+
const packed = context.exports.handle(context.reqOfs, context.length);
|
|
176
|
+
return this.finishDispatch(context.exports, context.state, packed);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
persistDb();
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async dispatchAsync(req, hooks = {}) {
|
|
184
|
+
const jspi = WebAssembly;
|
|
185
|
+
if (typeof jspi.Suspending !== 'function' || typeof jspi.promising !== 'function')
|
|
186
|
+
throw new Error('dispatchAsync requires WebAssembly JSPI (Suspending/promising); use a Node release with JSPI enabled');
|
|
187
|
+
const context = this.prepareDispatch(req, (imports, ref, state) => {
|
|
188
|
+
const env = imports.env;
|
|
189
|
+
for (const [operation, value] of Object.entries(env)) {
|
|
190
|
+
if (!operation.startsWith('data.') ||
|
|
191
|
+
typeof value !== 'function' ||
|
|
192
|
+
[
|
|
193
|
+
'data.resolve_collection',
|
|
194
|
+
'data.take_result',
|
|
195
|
+
'data.budget',
|
|
196
|
+
'data.changes',
|
|
197
|
+
'data.begin_derive',
|
|
198
|
+
'data.end_derive',
|
|
199
|
+
'data.continue_derive',
|
|
200
|
+
'data.result_schema_version',
|
|
201
|
+
'data.write_allowed',
|
|
202
|
+
'data.job_allowed',
|
|
203
|
+
].includes(operation))
|
|
204
|
+
continue;
|
|
205
|
+
const implementation = value;
|
|
206
|
+
env[operation] = new jspi.Suspending(async (...args) => {
|
|
207
|
+
const memory = ref.memory;
|
|
208
|
+
const [handle, ptr, len] = args;
|
|
209
|
+
const key = memory !== null &&
|
|
210
|
+
ptr >= 0 &&
|
|
211
|
+
len >= 0 &&
|
|
212
|
+
len <= 4096 &&
|
|
213
|
+
ptr <= memory.buffer.byteLength &&
|
|
214
|
+
len <= memory.buffer.byteLength - ptr
|
|
215
|
+
? new Uint8Array(memory.buffer, ptr, len).slice()
|
|
216
|
+
: null;
|
|
217
|
+
const point = {
|
|
218
|
+
request: req,
|
|
219
|
+
operation,
|
|
220
|
+
collection: state.db.handles[handle]?.name ?? null,
|
|
221
|
+
key,
|
|
222
|
+
};
|
|
223
|
+
await hooks.beforeDatabaseOperation?.(point);
|
|
224
|
+
const result = implementation(...args);
|
|
225
|
+
await hooks.afterDatabaseOperation?.({ ...point, result });
|
|
226
|
+
return result;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
try {
|
|
231
|
+
const packed = await jspi.promising(context.exports.handle)(context.reqOfs, context.length);
|
|
232
|
+
return this.finishDispatch(context.exports, context.state, packed);
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
persistDb();
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
prepareDispatch(req, wrap) {
|
|
160
240
|
if (this.module === null)
|
|
161
241
|
throw new Error(`server wasm not loaded (${this.wasmPath})`);
|
|
162
242
|
this.rebuildDerivedViewsIfStale();
|
|
163
243
|
const envelope = this.requestEnvelope(req);
|
|
164
244
|
const ref = { memory: null };
|
|
165
245
|
const state = freshDispatchState();
|
|
246
|
+
state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
|
|
166
247
|
state.clientIp = req.clientIp ?? '';
|
|
167
248
|
const rpcPath = req.path.split('?')[0] ?? req.path;
|
|
168
249
|
const rpcMethod = req.method.toUpperCase();
|
|
@@ -181,11 +262,16 @@ export class WasmServerModule {
|
|
|
181
262
|
else {
|
|
182
263
|
state.db.functionKind = dbFunctionKindForRequest(this.routeKinds, req.method, req.path);
|
|
183
264
|
}
|
|
184
|
-
const
|
|
265
|
+
const imports = buildHostImports(ref, state);
|
|
266
|
+
if (wrap !== undefined)
|
|
267
|
+
wrap(imports, ref, state);
|
|
268
|
+
const instance = new WebAssembly.Instance(this.module, imports);
|
|
185
269
|
const exports = instance.exports;
|
|
186
270
|
ref.memory = exports.memory;
|
|
187
271
|
const reqOfs = this.writeRequestEnvelope(exports.memory, envelope);
|
|
188
|
-
|
|
272
|
+
return { exports, state, reqOfs, length: envelope.length };
|
|
273
|
+
}
|
|
274
|
+
finishDispatch(exports, state, packed) {
|
|
189
275
|
const { ptr, len } = unpackHandleResult(packed);
|
|
190
276
|
const memSize = exports.memory.buffer.byteLength;
|
|
191
277
|
if (len > memSize || ptr + len > memSize)
|
|
@@ -194,7 +280,7 @@ export class WasmServerModule {
|
|
|
194
280
|
const headers = [...resp.headers, ...state.headers];
|
|
195
281
|
const status = state.status ?? resp.status;
|
|
196
282
|
const unhandled = headers.some(([n]) => n.toLowerCase() === UNHANDLED_HEADER);
|
|
197
|
-
this.runAffectedDerives(state.db.writtenCollections);
|
|
283
|
+
this.runAffectedDerives(state.db.writtenCollections, state.db);
|
|
198
284
|
persistDb();
|
|
199
285
|
return {
|
|
200
286
|
status,
|
|
@@ -211,6 +297,7 @@ export class WasmServerModule {
|
|
|
211
297
|
const envelope = this.requestEnvelope(req);
|
|
212
298
|
const ref = { memory: null };
|
|
213
299
|
const state = freshDispatchState();
|
|
300
|
+
state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
|
|
214
301
|
state.clientIp = req.clientIp ?? '';
|
|
215
302
|
state.db.functionKind = DbFunctionKind.Query;
|
|
216
303
|
const instance = new WebAssembly.Instance(this.module, buildHostImports(ref, state));
|
|
@@ -226,15 +313,18 @@ export class WasmServerModule {
|
|
|
226
313
|
throw new Error(`guest returned out-of-bounds values: ptr=${String(ptr)} len=${String(len)}`);
|
|
227
314
|
return new Uint8Array(exports.memory.buffer, ptr, len).slice();
|
|
228
315
|
}
|
|
229
|
-
runAffectedDerives(written) {
|
|
316
|
+
runAffectedDerives(written, source) {
|
|
230
317
|
if (this.module === null)
|
|
231
318
|
return;
|
|
319
|
+
const retrying = new Set(this.pendingDerives);
|
|
232
320
|
const affected = derivesForWrites(this.derives, written);
|
|
233
321
|
for (const derive of affected)
|
|
234
322
|
this.pendingDerives.add(derive.deriveId);
|
|
235
323
|
for (const derive of this.derives.filter((d) => this.pendingDerives.has(d.deriveId))) {
|
|
236
324
|
try {
|
|
237
|
-
this.runDerive(derive.deriveId
|
|
325
|
+
this.runDerive(derive.deriveId, source === undefined
|
|
326
|
+
? fullRescanFrame()
|
|
327
|
+
: deriveChangesFrame(source, derive.dbName, retrying.has(derive.deriveId)));
|
|
238
328
|
this.pendingDerives.delete(derive.deriveId);
|
|
239
329
|
}
|
|
240
330
|
catch (err) {
|
|
@@ -256,19 +346,27 @@ export class WasmServerModule {
|
|
|
256
346
|
}
|
|
257
347
|
}
|
|
258
348
|
}
|
|
259
|
-
runDerive(deriveId) {
|
|
349
|
+
runDerive(deriveId, changes = fullRescanFrame()) {
|
|
260
350
|
if (this.module === null)
|
|
261
351
|
return;
|
|
262
352
|
const ref = { memory: null };
|
|
263
353
|
const state = freshDispatchState();
|
|
354
|
+
state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
|
|
264
355
|
state.db.functionKind = DbFunctionKind.Derive;
|
|
265
356
|
state.db.deriveId = deriveId;
|
|
357
|
+
state.db.deriveChanges = changes;
|
|
358
|
+
const entry = this.derives.find((derive) => derive.deriveId === deriveId);
|
|
359
|
+
if (entry === undefined)
|
|
360
|
+
throw new Error('Unknown derive identity');
|
|
361
|
+
state.db.deriveKey = deriveCheckpointKey(entry);
|
|
266
362
|
const instance = new WebAssembly.Instance(this.module, buildHostImports(ref, state));
|
|
267
363
|
const exports = instance.exports;
|
|
268
364
|
ref.memory = exports.memory;
|
|
269
365
|
if (typeof exports.derive_run !== 'function')
|
|
270
366
|
return;
|
|
271
|
-
exports.derive_run(deriveId);
|
|
367
|
+
const rc = exports.derive_run(deriveId);
|
|
368
|
+
if (rc !== 0n)
|
|
369
|
+
throw new Error(`derive_run returned ${String(rc)}`);
|
|
272
370
|
commitDeriveCheckpoints(state.db);
|
|
273
371
|
}
|
|
274
372
|
requestEnvelope(req) {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { startDevBlobStorage } from './files/dev.js';
|
|
1
2
|
import path from 'node:path';
|
|
2
3
|
import { Server } from '@dacely/hyper-express';
|
|
3
4
|
import pc from 'picocolors';
|
|
5
|
+
import { installSecurityHeaders } from 'toiljs/backend';
|
|
4
6
|
import { startDaemonRuntime } from './daemon/runtime.js';
|
|
5
7
|
import { configureDbPersistence } from './db/index.js';
|
|
6
8
|
import { initEmailService } from './email/index.js';
|
|
@@ -52,6 +54,7 @@ export async function startDevServer(options) {
|
|
|
52
54
|
refresh();
|
|
53
55
|
const app = new Server(runtimeServerOptions(options));
|
|
54
56
|
installRuntimeErrorHandler(app);
|
|
57
|
+
installSecurityHeaders(app);
|
|
55
58
|
const nodeMode = options.nodeMode ?? 'all';
|
|
56
59
|
if (options.streamWasmFile !== undefined && streamEmulationEnabled(nodeMode)) {
|
|
57
60
|
wireStreams(app, options.vite, new StreamRouter(options.streamWasmFile));
|
|
@@ -59,6 +62,7 @@ export async function startDevServer(options) {
|
|
|
59
62
|
else {
|
|
60
63
|
wireWebsocketProxy(app, options.vite);
|
|
61
64
|
}
|
|
65
|
+
const blobs = await startDevBlobStorage(root);
|
|
62
66
|
const daemon = startDaemonRuntime({
|
|
63
67
|
coldWasmFile: options.coldWasmFile,
|
|
64
68
|
nodeMode,
|
|
@@ -100,12 +104,20 @@ export async function startDevServer(options) {
|
|
|
100
104
|
}
|
|
101
105
|
await proxyToVite(request, response, options.vite);
|
|
102
106
|
});
|
|
103
|
-
|
|
107
|
+
try {
|
|
108
|
+
await app.listen(options.port, host);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
daemon?.close();
|
|
112
|
+
await blobs?.close();
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
104
115
|
return {
|
|
105
116
|
port: options.port,
|
|
106
117
|
host,
|
|
107
118
|
close: async () => {
|
|
108
119
|
daemon?.close();
|
|
120
|
+
await blobs?.close();
|
|
109
121
|
await app.shutdown();
|
|
110
122
|
},
|
|
111
123
|
};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { type ImageDevState } from '../images/index.js';
|
|
1
2
|
import { type DbDevState } from '../db/index.js';
|
|
2
3
|
import { type CryptoState } from '../runtime/crypto.js';
|
|
3
4
|
import { type MemoryRef } from '../runtime/host.js';
|
|
4
5
|
export interface StreamBoxState {
|
|
5
6
|
crypto: CryptoState;
|
|
6
7
|
db: DbDevState;
|
|
8
|
+
images: ImageDevState;
|
|
7
9
|
}
|
|
8
10
|
export declare function freshStreamBoxState(): StreamBoxState;
|
|
9
11
|
export declare function buildStreamImports(ref: MemoryRef, state: StreamBoxState): WebAssembly.Imports;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { freshImageState } from '../images/index.js';
|
|
1
2
|
import { buildDatabaseImports, freshDbState } from '../db/index.js';
|
|
2
3
|
import { buildCryptoImports, freshCryptoState } from '../runtime/crypto.js';
|
|
3
4
|
import { buildEnvImports } from '../runtime/host.js';
|
|
4
5
|
export function freshStreamBoxState() {
|
|
5
|
-
return { crypto: freshCryptoState(), db: freshDbState() };
|
|
6
|
+
return { crypto: freshCryptoState(), db: freshDbState(), images: freshImageState() };
|
|
6
7
|
}
|
|
7
8
|
export function buildStreamImports(ref, state) {
|
|
8
9
|
return {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resetImageState } from '../images/index.js';
|
|
1
2
|
import { parseSurface } from '../wasm/surface.js';
|
|
2
3
|
import { buildStreamImports, freshStreamBoxState } from './host.js';
|
|
3
4
|
const EVENT_CONNECT = 1;
|
|
@@ -86,6 +87,7 @@ export class DevStreamBox {
|
|
|
86
87
|
return { kind: 'reply', frames: this.egressDrain() };
|
|
87
88
|
}
|
|
88
89
|
dispatch(eventKind, streamId) {
|
|
90
|
+
resetImageState(this._state.images);
|
|
89
91
|
const lo = Number(streamId & 0xffffffffn) | 0;
|
|
90
92
|
const hi = Number((streamId >> 32n) & 0xffffffffn) | 0;
|
|
91
93
|
return this.exports.stream_dispatch(eventKind, lo, hi);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface DeriveMetadata {
|
|
2
|
+
readonly deriveId: number;
|
|
3
|
+
readonly dbName: string;
|
|
4
|
+
readonly methodName: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function deriveIdentity(entry: Pick<DeriveMetadata, 'dbName' | 'methodName'>): string;
|
|
7
|
+
export declare function readDeriveCatalog(section: Uint8Array): readonly DeriveMetadata[] | null;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { DataReader } from './codec.js';
|
|
2
|
+
export function deriveIdentity(entry) {
|
|
3
|
+
return `${new TextEncoder().encode(entry.dbName).length}:${entry.dbName}${entry.methodName}`;
|
|
4
|
+
}
|
|
5
|
+
export function readDeriveCatalog(section) {
|
|
6
|
+
if (section.length > 128 * 1024)
|
|
7
|
+
return null;
|
|
8
|
+
const r = new DataReader(section);
|
|
9
|
+
if (r.readU16() !== 1)
|
|
10
|
+
return null;
|
|
11
|
+
const count = r.readU16();
|
|
12
|
+
if (!r.ok || count > 1024)
|
|
13
|
+
return null;
|
|
14
|
+
const entries = [];
|
|
15
|
+
const ids = new Set(), names = new Set();
|
|
16
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
17
|
+
try {
|
|
18
|
+
for (let i = 0; i < count; i++) {
|
|
19
|
+
const deriveId = r.readU16();
|
|
20
|
+
const db = r.readBytes(), method = r.readBytes();
|
|
21
|
+
if (!r.ok ||
|
|
22
|
+
db.length === 0 ||
|
|
23
|
+
db.length > 1024 ||
|
|
24
|
+
method.length === 0 ||
|
|
25
|
+
method.length > 1024)
|
|
26
|
+
return null;
|
|
27
|
+
const entry = {
|
|
28
|
+
deriveId,
|
|
29
|
+
dbName: decoder.decode(db),
|
|
30
|
+
methodName: decoder.decode(method),
|
|
31
|
+
};
|
|
32
|
+
const identity = deriveIdentity(entry);
|
|
33
|
+
if (ids.has(deriveId) || names.has(identity))
|
|
34
|
+
return null;
|
|
35
|
+
ids.add(deriveId);
|
|
36
|
+
names.add(identity);
|
|
37
|
+
entries.push(entry);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
return r.ok && r.remaining() === 0 ? entries : null;
|
|
44
|
+
}
|
package/build/io/index.d.ts
CHANGED
|
@@ -3,3 +3,4 @@ export { FastSet } from './FastSet.js';
|
|
|
3
3
|
export { DataWriter, DataReader } from './codec.js';
|
|
4
4
|
export type { PropertyExtendedKey, FastRecord, IndexKey } from './FastMap.js';
|
|
5
5
|
export type { i8, i16, i32, i64, u8, u16, u32, u64, Selector, BufferLike } from './types.js';
|
|
6
|
+
export { readDeriveCatalog, deriveIdentity, type DeriveMetadata } from './derive-metadata.js';
|
package/build/io/index.js
CHANGED
package/build/shared/index.d.ts
CHANGED
package/build/shared/index.js
CHANGED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const DEFAULT_COOP = "same-origin";
|
|
2
|
+
export declare function contentSecurityPolicy(scriptSources?: readonly string[], dev?: boolean, extraSources?: Readonly<Record<string, readonly string[]>>): string;
|
|
3
|
+
export declare const DEFAULT_CSP: string;
|
|
4
|
+
export declare function builtContentSecurityPolicy(html: string): string | null;
|
|
5
|
+
export declare function withSecurityHeaders(headers: readonly (readonly [string, string])[], policy?: string): (readonly [string, string])[];
|