toiljs 0.0.135 → 0.0.136

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.
@@ -6,6 +6,7 @@ export declare function daemonEmulationEnabled(nodeMode: string): boolean;
6
6
  export interface DaemonHostOptions {
7
7
  readonly clock?: () => number;
8
8
  readonly httpMock?: DaemonHttpMock;
9
+ readonly logging?: boolean;
9
10
  }
10
11
  export interface DaemonTaskResult {
11
12
  task: string;
@@ -172,7 +172,11 @@ export class DaemonHost {
172
172
  start() {
173
173
  if (this.module === null || this.catalog === null)
174
174
  return;
175
- const ref = { memory: null, now: () => this.now() };
175
+ const ref = {
176
+ memory: null,
177
+ now: () => this.now(),
178
+ logging: this.options.logging,
179
+ };
176
180
  this.state = freshDaemonState();
177
181
  this.state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
178
182
  this.state.db.functionKind = DbFunctionKind.Action;
@@ -4,6 +4,7 @@ export interface DaemonRuntimeOptions {
4
4
  readonly coldWasmFile?: string;
5
5
  readonly nodeMode?: string;
6
6
  readonly daemon?: ResolvedDaemonConfig;
7
+ readonly logging?: boolean;
7
8
  readonly pollMs?: number;
8
9
  }
9
10
  export interface RunningDaemonRuntime {
@@ -7,7 +7,9 @@ export function startDaemonRuntime(options) {
7
7
  options.daemon === undefined) {
8
8
  return null;
9
9
  }
10
- const host = new DaemonHost(options.coldWasmFile, options.daemon, nodeMode);
10
+ const host = new DaemonHost(options.coldWasmFile, options.daemon, nodeMode, undefined, {
11
+ logging: options.logging,
12
+ });
11
13
  const pollDaemon = () => {
12
14
  try {
13
15
  host.refresh();
@@ -9,6 +9,7 @@ export interface BuiltServerOptions {
9
9
  readonly coldWasmFile?: string;
10
10
  readonly nodeMode?: string;
11
11
  readonly daemon?: ResolvedDaemonConfig;
12
+ readonly logging?: boolean;
12
13
  readonly port?: number;
13
14
  readonly host?: string;
14
15
  readonly allowedOrigins?: readonly string[];
@@ -163,7 +163,7 @@ function createBuiltRuntime(options, paths) {
163
163
  process.stdout.write(pc.yellow(' ! ') + pc.dim(`email off: ${emailInit.note}`) + '\n');
164
164
  }
165
165
  const module = options.wasmFile !== undefined && fs.existsSync(options.wasmFile)
166
- ? new WasmServerModule(options.wasmFile)
166
+ ? new WasmServerModule(options.wasmFile, options.logging === true)
167
167
  : null;
168
168
  if (module !== null) {
169
169
  try {
@@ -186,6 +186,7 @@ function startBuiltDaemon(options, paths) {
186
186
  coldWasmFile: options.coldWasmFile,
187
187
  nodeMode: options.nodeMode,
188
188
  daemon: options.daemon,
189
+ logging: options.logging === true,
189
190
  });
190
191
  }
191
192
  async function handleBuiltRuntimeRequest(runtime, request) {
@@ -17,6 +17,7 @@ export interface DispatchState {
17
17
  export declare function freshDispatchState(): DispatchState;
18
18
  export interface MemoryRef {
19
19
  memory: WebAssembly.Memory | null;
20
+ logging?: boolean;
20
21
  now?: () => number;
21
22
  }
22
23
  export declare function readBytes(ref: MemoryRef, ptr: number, len: number): Buffer;
@@ -140,6 +140,8 @@ function buildLogImports(ref, db) {
140
140
  if (!Number.isInteger(level) || level < 0 || level > 2 || len < 0 || len > 4096)
141
141
  throw new Error('server_log: level must be 0..2 and message at most 4096 UTF-8 bytes');
142
142
  const message = new TextDecoder('utf-8', { fatal: true }).decode(readBytes(ref, ptr, len));
143
+ if (ref.logging === false)
144
+ return 0;
143
145
  if (db.logMessages >= 32)
144
146
  return 0;
145
147
  db.logMessages++;
@@ -25,6 +25,7 @@ export interface DispatchInterleaving {
25
25
  }
26
26
  export declare class WasmServerModule {
27
27
  private readonly wasmPath;
28
+ private readonly logging;
28
29
  private module;
29
30
  private usesGoogleVerification;
30
31
  private loadedMtimeMs;
@@ -34,7 +35,7 @@ export declare class WasmServerModule {
34
35
  private derivesDirty;
35
36
  private envelopeWindow;
36
37
  private readonly pendingDerives;
37
- constructor(wasmPath: string);
38
+ constructor(wasmPath: string, logging?: boolean);
38
39
  get available(): boolean;
39
40
  refresh(): boolean;
40
41
  dispatch(req: EnvelopeRequest): WasmDispatchResult;
@@ -122,6 +122,7 @@ const PROVIDED_IMPORTS = new Set([
122
122
  ]);
123
123
  export class WasmServerModule {
124
124
  wasmPath;
125
+ logging;
125
126
  module = null;
126
127
  usesGoogleVerification = false;
127
128
  loadedMtimeMs = -1;
@@ -131,8 +132,9 @@ export class WasmServerModule {
131
132
  derivesDirty = false;
132
133
  envelopeWindow = null;
133
134
  pendingDerives = new Set();
134
- constructor(wasmPath) {
135
+ constructor(wasmPath, logging = true) {
135
136
  this.wasmPath = wasmPath;
137
+ this.logging = logging;
136
138
  }
137
139
  get available() {
138
140
  return this.module !== null;
@@ -260,7 +262,7 @@ export class WasmServerModule {
260
262
  throw new Error(`server wasm not loaded (${this.wasmPath})`);
261
263
  this.rebuildDerivedViewsIfStale();
262
264
  const envelope = this.requestEnvelope(req);
263
- const ref = { memory: null };
265
+ const ref = { memory: null, logging: this.logging };
264
266
  const state = freshDispatchState();
265
267
  state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
266
268
  state.clientIp = req.clientIp ?? '';
@@ -314,7 +316,7 @@ export class WasmServerModule {
314
316
  throw new Error(`server wasm not loaded (${this.wasmPath})`);
315
317
  this.rebuildDerivedViewsIfStale();
316
318
  const envelope = this.requestEnvelope(req);
317
- const ref = { memory: null };
319
+ const ref = { memory: null, logging: this.logging };
318
320
  const state = freshDispatchState();
319
321
  state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
320
322
  state.clientIp = req.clientIp ?? '';
@@ -368,7 +370,7 @@ export class WasmServerModule {
368
370
  runDerive(deriveId, changes = fullRescanFrame()) {
369
371
  if (this.module === null)
370
372
  return;
371
- const ref = { memory: null };
373
+ const ref = { memory: null, logging: this.logging };
372
374
  const state = freshDispatchState();
373
375
  state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
374
376
  state.db.functionKind = DbFunctionKind.Derive;
@@ -11,6 +11,7 @@ export interface DevServerOptions {
11
11
  readonly streamWasmFile?: string;
12
12
  readonly nodeMode?: string;
13
13
  readonly daemon?: ResolvedDaemonConfig;
14
+ readonly logging?: boolean;
14
15
  readonly vite: ViteTarget;
15
16
  readonly maxBodyLength?: number;
16
17
  readonly email?: EmailBackendConfig;
@@ -26,7 +26,7 @@ export async function startDevServer(options) {
26
26
  else if (emailInit.note !== null) {
27
27
  process.stdout.write(pc.yellow(' ! ') + pc.dim(`email off: ${emailInit.note}`) + '\n');
28
28
  }
29
- const module = new WasmServerModule(options.wasmFile);
29
+ const module = new WasmServerModule(options.wasmFile, options.logging ?? true);
30
30
  const ssrRoutes = buildSsrRoutes(options.ssrTemplates ?? []);
31
31
  if (ssrRoutes.length > 0) {
32
32
  process.stdout.write(pc.dim(` edge SSR: ${String(ssrRoutes.length)} route(s) served server-side`) + '\n');
@@ -57,7 +57,7 @@ export async function startDevServer(options) {
57
57
  installSecurityHeaders(app);
58
58
  const nodeMode = options.nodeMode ?? 'all';
59
59
  if (options.streamWasmFile !== undefined && streamEmulationEnabled(nodeMode)) {
60
- wireStreams(app, options.vite, new StreamRouter(options.streamWasmFile));
60
+ wireStreams(app, options.vite, new StreamRouter(options.streamWasmFile, options.logging ?? true));
61
61
  }
62
62
  else {
63
63
  wireWebsocketProxy(app, options.vite);
@@ -67,6 +67,7 @@ export async function startDevServer(options) {
67
67
  coldWasmFile: options.coldWasmFile,
68
68
  nodeMode,
69
69
  daemon: options.daemon,
70
+ logging: options.logging ?? true,
70
71
  });
71
72
  app.any('/*', async (request, response) => {
72
73
  response.removeHeader('uWebSockets');
@@ -20,7 +20,7 @@ export declare class DevStreamBox {
20
20
  private readonly rings;
21
21
  private readonly streamInfo;
22
22
  private constructor();
23
- static load(wasm: Buffer): DevStreamBox;
23
+ static load(wasm: Buffer, logging?: boolean): DevStreamBox;
24
24
  get hasRings(): boolean;
25
25
  get hasConnectBridge(): boolean;
26
26
  onConnect(streamId: bigint, authority: string, path: string): StreamConnectOutcome;
@@ -34,12 +34,12 @@ export class DevStreamBox {
34
34
  this.rings = rings;
35
35
  this.streamInfo = streamInfo;
36
36
  }
37
- static load(wasm) {
37
+ static load(wasm, logging = true) {
38
38
  const surface = parseSurface(wasm);
39
39
  if (surface === 'invalid' || surface.targetMode !== 'hot' || !surface.flags.stream) {
40
40
  throw new Error('stream box requires a hot stream artifact with a valid toil.surface');
41
41
  }
42
- const ref = { memory: null };
42
+ const ref = { memory: null, logging };
43
43
  const state = freshStreamBoxState();
44
44
  const module = new WebAssembly.Module(new Uint8Array(wasm));
45
45
  const instance = new WebAssembly.Instance(module, buildStreamImports(ref, state));
@@ -88,6 +88,7 @@ export class DevStreamBox {
88
88
  }
89
89
  dispatch(eventKind, streamId) {
90
90
  resetImageState(this._state.images);
91
+ this._state.db.logMessages = 0;
91
92
  const lo = Number(streamId & 0xffffffffn) | 0;
92
93
  const hi = Number((streamId >> 32n) & 0xffffffffn) | 0;
93
94
  return this.exports.stream_dispatch(eventKind, lo, hi);
@@ -20,11 +20,12 @@ export type StreamDispatchResult = {
20
20
  };
21
21
  export declare class StreamDevHost {
22
22
  private readonly streamWasmPath;
23
+ private readonly logging;
23
24
  private bytes;
24
25
  private loadedMtimeMs;
25
26
  private readonly conns;
26
27
  private nextStreamId;
27
- constructor(streamWasmPath: string);
28
+ constructor(streamWasmPath: string, logging?: boolean);
28
29
  get activeConnections(): number;
29
30
  has(connId: string): boolean;
30
31
  acceptUpgrade(connId: string, authority: string, path: string): StreamUpgradeOutcome;
@@ -4,12 +4,14 @@ export const STREAM_REJECTED = 0x0208;
4
4
  export const STREAM_HOOK_TRAPPED = 0x0200;
5
5
  export class StreamDevHost {
6
6
  streamWasmPath;
7
+ logging;
7
8
  bytes = null;
8
9
  loadedMtimeMs = -1;
9
10
  conns = new Map();
10
11
  nextStreamId = 1n;
11
- constructor(streamWasmPath) {
12
+ constructor(streamWasmPath, logging = true) {
12
13
  this.streamWasmPath = streamWasmPath;
14
+ this.logging = logging;
13
15
  }
14
16
  get activeConnections() {
15
17
  return this.conns.size;
@@ -25,7 +27,7 @@ export class StreamDevHost {
25
27
  return { kind: 'rejected', code: STREAM_REJECTED, initialEgress: [] };
26
28
  let box;
27
29
  try {
28
- box = DevStreamBox.load(this.bytes);
30
+ box = DevStreamBox.load(this.bytes, this.logging);
29
31
  }
30
32
  catch {
31
33
  return { kind: 'rejected', code: STREAM_REJECTED, initialEgress: [] };
@@ -17,7 +17,7 @@ export declare class StreamRouter {
17
17
  private catalogMtimeMs;
18
18
  private readonly host;
19
19
  private connSeq;
20
- constructor(streamWasmPath: string);
20
+ constructor(streamWasmPath: string, logging?: boolean);
21
21
  get activeConnections(): number;
22
22
  matchRoute(path: string): StreamDef | null;
23
23
  onUpgrade(ws: StreamWs, ctx: StreamUpgradeContext): void;
@@ -8,9 +8,9 @@ export class StreamRouter {
8
8
  catalogMtimeMs = -1;
9
9
  host;
10
10
  connSeq = 0;
11
- constructor(streamWasmPath) {
11
+ constructor(streamWasmPath, logging = true) {
12
12
  this.streamWasmPath = streamWasmPath;
13
- this.host = new StreamDevHost(streamWasmPath);
13
+ this.host = new StreamDevHost(streamWasmPath, logging);
14
14
  this.refreshCatalog();
15
15
  }
16
16
  get activeConnections() {
@@ -4,9 +4,16 @@ export declare enum LogLevel {
4
4
  Warn = "warn",
5
5
  Error = "error"
6
6
  }
7
+ export interface LoggerOptions {
8
+ readonly enabled?: boolean;
9
+ }
7
10
  export declare class Logger {
8
11
  private readonly scope;
9
- constructor(scope?: string);
10
- log(level: LogLevel, message: string): void;
11
- info(message: string): void;
12
+ private readonly options;
13
+ constructor(scope?: string, options?: LoggerOptions);
14
+ log(level: LogLevel, ...values: unknown[]): void;
15
+ debug(...values: unknown[]): void;
16
+ info(...values: unknown[]): void;
17
+ warn(...values: unknown[]): void;
18
+ error(...values: unknown[]): void;
12
19
  }
@@ -7,13 +7,32 @@ export var LogLevel;
7
7
  })(LogLevel || (LogLevel = {}));
8
8
  export class Logger {
9
9
  scope;
10
- constructor(scope = 'toil') {
10
+ options;
11
+ constructor(scope = 'toil', options = {}) {
11
12
  this.scope = scope;
13
+ this.options = options;
12
14
  }
13
- log(level, message) {
14
- console.log(`[${this.scope}] ${level}: ${message}`);
15
+ log(level, ...values) {
16
+ const production = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
17
+ if (!(this.options.enabled ?? !production))
18
+ return;
19
+ const prefix = `[${this.scope}] ${level}:`;
20
+ const [first, ...rest] = values;
21
+ if (typeof first === 'string')
22
+ console[level](`${prefix} ${first}`, ...rest);
23
+ else
24
+ console[level](prefix, ...values);
15
25
  }
16
- info(message) {
17
- this.log(LogLevel.Info, message);
26
+ debug(...values) {
27
+ this.log(LogLevel.Debug, ...values);
28
+ }
29
+ info(...values) {
30
+ this.log(LogLevel.Info, ...values);
31
+ }
32
+ warn(...values) {
33
+ this.log(LogLevel.Warn, ...values);
34
+ }
35
+ error(...values) {
36
+ this.log(LogLevel.Error, ...values);
18
37
  }
19
38
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toiljs",
3
3
  "type": "module",
4
- "version": "0.0.135",
4
+ "version": "0.0.136",
5
5
  "author": "Dacely",
6
6
  "description": "The modern React framework: a file-based React frontend and a ToilScript-compiled WebAssembly backend.",
7
7
  "repository": {
@@ -8,6 +8,17 @@ import { SessionEpochs } from './SessionEpochs';
8
8
  import { Response, RouteContext, base64UrlEncode } from 'toiljs/server/runtime';
9
9
  import { DataReader, DataWriter } from 'data';
10
10
 
11
+ // Direct toilscript consumers retain the default policy without generated authlib.
12
+ // toiljs builds supply constant policies from server.authRoutes, before any action I/O.
13
+ @inline function googleRoutesEnabled(): bool {
14
+ if (isDefined(__toilAuthGoogleEnabled)) return __toilAuthGoogleEnabled();
15
+ return true;
16
+ }
17
+ @inline function twoFactorSetupEnabled(): bool {
18
+ if (isDefined(__toilAuthTwoFactorSetupEnabled)) return __toilAuthTwoFactorSetupEnabled();
19
+ return true;
20
+ }
21
+
11
22
  /**
12
23
  * Built-in Toil PQ-Auth controller: the full post-quantum password-login API
13
24
  * (`/auth/register|login/start|finish`) plus sessions (`/auth/me`, `/auth/logout`),
@@ -412,6 +423,8 @@ class Auth {
412
423
  @ratelimit(RateLimit.SlidingWindow, 10, 60)
413
424
  @post('/google/start')
414
425
  public googleStart(ctx: RouteContext): Response {
426
+ if (!googleRoutesEnabled()) return Response.text('not found\n', 404);
427
+ if (!GoogleIdentity.configured()) return fail();
415
428
  const id = GoogleIdentity.clientId();
416
429
  if (id.length == 0) return fail();
417
430
  const nonce = crypto.toHex(randomBytes(32));
@@ -425,6 +438,8 @@ class Auth {
425
438
  @ratelimit(RateLimit.SlidingWindow, 10, 60)
426
439
  @post('/google/login')
427
440
  public googleLogin(ctx: RouteContext): Response {
441
+ if (!googleRoutesEnabled()) return Response.text('not found\n', 404);
442
+ if (!GoogleIdentity.configured()) return fail();
428
443
  if (ctx.request.body.length > 16388) return fail();
429
444
  const r = new DataReader(ctx.request.body);
430
445
  const token = r.readBytes();
@@ -1179,6 +1194,7 @@ class Auth {
1179
1194
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1180
1195
  @post('/2fa/setup')
1181
1196
  public twoFaSetup(_ctx: RouteContext): Response {
1197
+ if (!twoFactorSetupEnabled()) return Response.text('not found\n', 404);
1182
1198
  if (_ctx.request.body.length > 128) return fail();
1183
1199
  const r = new DataReader(_ctx.request.body);
1184
1200
  const targetMethod = r.readU8();
@@ -1264,6 +1280,7 @@ class Auth {
1264
1280
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1265
1281
  @post('/2fa/setup/verify')
1266
1282
  public twoFaSetupVerify(_ctx: RouteContext): Response {
1283
+ if (!twoFactorSetupEnabled()) return Response.text('not found\n', 404);
1267
1284
  if (_ctx.request.body.length > 128) return fail();
1268
1285
  const r = new DataReader(_ctx.request.body);
1269
1286
  const code = r.readString();
@@ -14,6 +14,10 @@ export class GoogleClaims {
14
14
 
15
15
  /** Browser-bound, short-lived nonce. Startup costs zero database operations. */
16
16
  export class GoogleIdentity {
17
+ static configured(): bool {
18
+ const secret = Environment.getSecure('AUTH_SESSION_SECRET');
19
+ return GoogleIdentity.clientId().length > 0 && secret != null && secret.length >= 32;
20
+ }
17
21
  static clientId(): string {
18
22
  const id = Environment.get('AUTH_GOOGLE_CLIENT_ID');
19
23
  return id == null ? '' : id;
@@ -0,0 +1,48 @@
1
+ // toiljs aliases the ambient Log to this implementation in every server tier.
2
+ // The build flag travels in Wasm, so the native edge uses the same policy as Node.
3
+ @external('env', 'server_log')
4
+ declare function __toilServerLog(level: i32, ptr: usize, len: i32): i32;
5
+
6
+ @global
7
+ export class ToilLog {
8
+ private static format<T>(value: T): string {
9
+ if (isReference<T>() && changetype<usize>(value) == 0) return 'null';
10
+ if (isDefined(value.toJSON)) return value.toJSON().toString();
11
+ if (isArrayLike<T>()) {
12
+ const parts = new Array<string>(value.length);
13
+ for (let i = 0; i < value.length; i++) parts[i] = ToilLog.format<valueof<T>>(value[i]);
14
+ return '[' + parts.join(',') + ']';
15
+ }
16
+ if (isBoolean<T>() || isInteger<T>() || isFloat<T>() || isString<T>())
17
+ return JSON.stringify<T>(value);
18
+ return value.toString();
19
+ }
20
+
21
+ private static write<T>(level: i32, value: T): bool {
22
+ if (isDefined(__TOIL_LOGGING)) {
23
+ if (!__TOIL_LOGGING) return false;
24
+ }
25
+ const message =
26
+ isString<T>() && changetype<usize>(value) != 0
27
+ ? changetype<string>(value)
28
+ : ToilLog.format<T>(value);
29
+ const bytes = Uint8Array.wrap(String.UTF8.encode(message));
30
+ return __toilServerLog(level, bytes.dataStart, bytes.byteLength) == 1;
31
+ }
32
+
33
+ static log<T>(value: T): bool {
34
+ return ToilLog.write<T>(0, value);
35
+ }
36
+ static debug<T>(value: T): bool {
37
+ return ToilLog.write<T>(0, value);
38
+ }
39
+ static info<T>(value: T): bool {
40
+ return ToilLog.write<T>(0, value);
41
+ }
42
+ static warn<T>(value: T): bool {
43
+ return ToilLog.write<T>(1, value);
44
+ }
45
+ static error<T>(value: T): bool {
46
+ return ToilLog.write<T>(2, value);
47
+ }
48
+ }
@@ -20,6 +20,14 @@ type Cookies = import('toiljs/server/runtime/http/cookies').Cookies;
20
20
  declare const SecureCookies: typeof import('toiljs/server/runtime/http/securecookies').SecureCookies;
21
21
  type SecureCookies = import('toiljs/server/runtime/http/securecookies').SecureCookies;
22
22
  declare const Time: typeof import('toiljs/server/runtime/time').Time;
23
+ // Merge generic values and convenience methods into toilscript's ambient Log.
24
+ declare namespace Log {
25
+ function log<T>(value: T): bool;
26
+ function debug<T>(value: T): bool;
27
+ function info<T>(value: T): bool;
28
+ function warn<T>(value: T): bool;
29
+ function error<T>(value: T): bool;
30
+ }
23
31
  // Email, rate-limit, 2FA, and auth globals (server/globals/*), hand-declared
24
32
  // because their AssemblyScript source can't be type-aliased from tsc.
25
33
  declare enum EmailStatus { Sent, Disabled, Budget, RecipientCapped, Deduped, TryLater, BadRecipient, ProviderError }
@@ -4,6 +4,7 @@
4
4
  "module": "ESNext",
5
5
  "target": "ESNext",
6
6
  "moduleResolution": "bundler",
7
+ "types": ["node"],
7
8
  "rootDir": "src/logger",
8
9
  "outDir": "build/logger",
9
10
  "tsBuildInfoFile": "build/logger/.tsbuildinfo"