toiljs 0.0.131 → 0.0.134

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 (53) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/build/backend/security.js +4 -2
  3. package/build/cli/index.js +9 -9
  4. package/build/client/auth.d.ts +14 -0
  5. package/build/client/auth.js +31 -4
  6. package/build/client/components/GoogleSignIn.d.ts +8 -0
  7. package/build/client/components/GoogleSignIn.js +57 -0
  8. package/build/client/index.d.ts +3 -1
  9. package/build/client/index.js +2 -1
  10. package/build/compiler/config.d.ts +3 -1
  11. package/build/compiler/config.js +3 -0
  12. package/build/compiler/security.d.ts +4 -3
  13. package/build/compiler/security.js +8 -7
  14. package/build/compiler/sri.js +2 -2
  15. package/build/compiler/toil-docs.generated.js +3 -1
  16. package/build/compiler/vite.js +1 -1
  17. package/build/devserver/http/runtime.d.ts +1 -1
  18. package/build/devserver/http/runtime.js +5 -5
  19. package/build/devserver/production.js +3 -3
  20. package/build/devserver/runtime/base64.d.ts +2 -0
  21. package/build/devserver/runtime/base64.js +39 -0
  22. package/build/devserver/runtime/crypto.d.ts +1 -1
  23. package/build/devserver/runtime/crypto.js +24 -0
  24. package/build/devserver/runtime/google.d.ts +9 -0
  25. package/build/devserver/runtime/google.js +157 -0
  26. package/build/devserver/runtime/host.js +6 -0
  27. package/build/devserver/runtime/module.d.ts +2 -0
  28. package/build/devserver/runtime/module.js +19 -0
  29. package/build/shared/index.d.ts +2 -1
  30. package/build/shared/index.js +1 -1
  31. package/build/shared/security.d.ts +4 -2
  32. package/build/shared/security.js +6 -2
  33. package/examples/basic/client/routes/google-login.tsx +132 -0
  34. package/package.json +19 -19
  35. package/server/auth/AuthController.ts +201 -61
  36. package/server/auth/AuthMaintenance.ts +1 -1
  37. package/server/auth/AuthRealm.ts +22 -0
  38. package/server/auth/AuthStateDb.ts +14 -0
  39. package/server/auth/AuthStore.ts +4 -0
  40. package/server/auth/Authenticator.ts +93 -0
  41. package/server/auth/FactorSettings.ts +9 -8
  42. package/server/auth/GoogleIdentity.ts +63 -0
  43. package/server/auth/SessionEpochs.ts +54 -12
  44. package/server/globals/auth.ts +51 -20
  45. package/server/globals.d.ts +6 -0
  46. package/server/runtime/envelope.ts +9 -7
  47. package/server/runtime/http/base64.ts +18 -98
  48. package/server/runtime/http/percent.ts +4 -0
  49. package/server/runtime/http/securecookies.ts +1 -1
  50. package/server/runtime/request.ts +3 -0
  51. package/std/server/http/base64.d.ts +2 -18
  52. package/std/server/http/securecookies.d.ts +1 -1
  53. package/std/server/request.d.ts +3 -0
@@ -1,7 +1,14 @@
1
1
  import { AuthReads } from 'toiljs/server/auth/AuthReads';
2
- import { AuthStateDb, FactorKey, FactorRevision, FactorSettings } from './AuthStateDb';
2
+ import { AuthStateDb, FactorKey, FactorRevision, FactorSettings, SessionEpoch } from 'toiljs/server/auth/AuthStateDb';
3
3
  export class FactorRepository {
4
- public static read(host: string, username: string, legacy: u8): FactorSettings {
4
+ public static read(host: string, username: string, legacy: u8, epoch: SessionEpoch): FactorSettings {
5
+ if (epoch.factorHost == host && epoch.factorName == username) {
6
+ const settings = new FactorSettings();
7
+ settings.method = epoch.factorMethod; settings.revision = epoch.factorRevision;
8
+ settings.encryptedSecret = epoch.factorSecret;
9
+ return settings;
10
+ }
11
+ // Read-only compatibility with security state written before atomic epoch commits.
5
12
  let settings = AuthReads.document(AuthStateDb.factorHeads, new FactorKey(host, username));
6
13
  if (settings == null) { settings = new FactorSettings(); settings.method = legacy; }
7
14
  for (let i: i32 = 0; i < 64; i++) {
@@ -11,10 +18,4 @@ export class FactorRepository {
11
18
  }
12
19
  throw new Error('Two-factor settings unavailable');
13
20
  }
14
- public static save(host: string, username: string, method: u8, expected: u64): bool {
15
- const settings = new FactorSettings(); settings.method = method; settings.revision = expected + 1;
16
- if (!AuthStateDb.factorRevisions.claim(new FactorRevision(host, username, settings.revision), settings).claimed) return false;
17
- AuthStateDb.factorHeads.upsert(new FactorKey(host, username), settings);
18
- return true;
19
- }
20
21
  }
@@ -0,0 +1,63 @@
1
+ import { SecureCookies, Cookie, SameSite, RouteContext } from 'toiljs/server/runtime';
2
+ import { DataReader } from 'data';
3
+
4
+ @external('env', 'google_verify')
5
+ declare function googleVerify(tp: usize, tl: i32, ap: usize, al: i32, np: usize, nl: i32, out: usize, cap: i32): i32;
6
+
7
+ export class GoogleClaims {
8
+ sub: string = '';
9
+ email: string = '';
10
+ issuedAt: u64 = 0;
11
+ nonce: string = '';
12
+ emailAuthoritative: bool = false;
13
+ }
14
+
15
+ /** Browser-bound, short-lived nonce. Startup costs zero database operations. */
16
+ export class GoogleIdentity {
17
+ static clientId(): string {
18
+ const id = Environment.get('AUTH_GOOGLE_CLIENT_ID');
19
+ return id == null ? '' : id;
20
+ }
21
+ private static secret(): Uint8Array {
22
+ const secret = Environment.getSecure('AUTH_SESSION_SECRET');
23
+ if (secret == null || secret.length < 32) throw new Error('Google login requires AUTH_SESSION_SECRET');
24
+ return crypto.sha256Text('toil-google-state-v1\x00' + secret);
25
+ }
26
+ private static secure(ctx: RouteContext): bool {
27
+ const url = Environment.get('PUBLIC_BASE_URL');
28
+ return ctx.request.header('x-forwarded-proto') == 'https' || (url != null && url.startsWith('https://'));
29
+ }
30
+ private static name(ctx: RouteContext): string {
31
+ return GoogleIdentity.secure(ctx) ? '__Host-toil_google' : 'toil_google';
32
+ }
33
+ static cookie(ctx: RouteContext, value: string, ttl: i64): Cookie {
34
+ let c = Cookie.create('toil_google', value).httpOnly().sameSite(SameSite.Strict).path('/').maxAge(ttl);
35
+ if (GoogleIdentity.secure(ctx)) c = c.asHostPrefixed();
36
+ return c;
37
+ }
38
+ static start(ctx: RouteContext, realm: string, nonce: string): Cookie {
39
+ const value = realm + '|' + (<u64>(Date.now() / 1000) + 120).toString() + '|' + nonce;
40
+ return GoogleIdentity.cookie(ctx, SecureCookies.signed(GoogleIdentity.secret()).sign(GoogleIdentity.name(ctx), value), 120);
41
+ }
42
+ static verify(ctx: RouteContext, realm: string, token: Uint8Array): GoogleClaims | null {
43
+ if (token.length > 16384) return null;
44
+ const name = GoogleIdentity.name(ctx);
45
+ const cookie = ctx.request.cookie(name);
46
+ if (cookie == null) return null;
47
+ const value = SecureCookies.signed(GoogleIdentity.secret()).unsign(name, cookie);
48
+ if (value == null) return null;
49
+ const parts = value.split('|');
50
+ if (parts.length != 3 || parts[0] != realm || U64.parseInt(parts[1]) <= <u64>(Date.now() / 1000) || parts[2].length != 64) return null;
51
+ const t = token;
52
+ const a = Uint8Array.wrap(String.UTF8.encode(GoogleIdentity.clientId()));
53
+ const n = Uint8Array.wrap(String.UTF8.encode(parts[2]));
54
+ const out = new Uint8Array(1024);
55
+ const len = googleVerify(t.dataStart, t.length, a.dataStart, a.length, n.dataStart, n.length, out.dataStart, out.length);
56
+ if (len < 1 || len > out.length) return null;
57
+ const r = new DataReader(out.subarray(0, len));
58
+ const claims = new GoogleClaims();
59
+ claims.sub = r.readString(); claims.email = r.readString(); claims.issuedAt = r.readU64(); claims.nonce = parts[2];
60
+ claims.emailAuthoritative = r.readU8() == 1;
61
+ return r.ok ? claims : null;
62
+ }
63
+ }
@@ -1,18 +1,19 @@
1
+ import { AuthRealm } from 'toiljs/server/auth/AuthRealm';
1
2
  import { AuthReads } from 'toiljs/server/auth/AuthReads';
2
3
  import { DataReader } from 'data';
3
4
  import { toildbHost } from 'bindings/toildb';
4
- import { AuthStateDb, SessionUserKey, SessionEpochKey, SessionEpoch } from './AuthStateDb';
5
+ import { AuthStateDb, SessionUserKey, SessionEpochKey, SessionEpoch } from 'toiljs/server/auth/AuthStateDb';
5
6
  /** Immutable per-user generations fence sessions and in-flight login challenges without clock assumptions. */
6
7
  export class SessionEpochs {
7
- private static key(userData: Uint8Array): string {
8
+ public static key(userData: Uint8Array): string {
8
9
  const reader = new DataReader(userData);
9
10
  reader.readU32(); // @data message-boundary identifier
10
11
  const id = reader.readBytes();
11
12
  if (!reader.ok || id.length != 32) throw new Error('Invalid session identity');
12
13
  return crypto.toHex(id);
13
14
  }
14
- private static read(id: string): SessionEpoch {
15
- const key = new SessionUserKey(id);
15
+ public static read(id: string, host: string = AuthRealm.current()): SessionEpoch {
16
+ const key = new SessionUserKey('3:' + host + '\x00' + id);
16
17
  const head = AuthStateDb.epochHeads.getCurrentSnapshot(key);
17
18
  if (head == null && Db.lastError() != DbError.None)
18
19
  throw new Error('Session state unavailable');
@@ -23,7 +24,7 @@ export class SessionEpochs {
23
24
  // user out forever when more than one chunk of claims lost their head write.
24
25
  for (let i: i32 = 0; i < 8; i++) {
25
26
  if (epoch.revision == u64.MAX_VALUE) throw new Error('Session generation exhausted');
26
- const next = AuthReads.owner(AuthStateDb.epochRevisions, new SessionEpochKey(id, epoch.revision + 1));
27
+ const next = AuthReads.owner(AuthStateDb.epochRevisions, new SessionEpochKey('3:' + host + '\x00' + id, epoch.revision + 1));
27
28
  if (next == null) {
28
29
  if (epoch.revision != revision && toildbHost.writeAllowed() == 1)
29
30
  AuthStateDb.epochHeads.compareExchangeSnapshot(key, head, epoch);
@@ -41,22 +42,63 @@ export class SessionEpochs {
41
42
  return SessionEpochs.read(SessionEpochs.key(userData)).revision;
42
43
  }
43
44
  public static allowed(userData: Uint8Array, generation: u64): bool {
44
- return generation == SessionEpochs.current(userData);
45
+ return SessionEpochs.allowedId(SessionEpochs.key(userData), generation);
46
+ }
47
+ public static allowedId(id: string, generation: u64): bool {
48
+ return generation == SessionEpochs.read(id).revision;
45
49
  }
46
50
  public static revoke(userData: Uint8Array): void {
47
51
  SessionEpochs.revokeId(SessionEpochs.key(userData));
48
52
  }
53
+ /** Optimistic revocation after an @auth check. A competing advance falls back to a fresh scan. */
54
+ public static revokeVerifiedId(id: string, verified: u64, state: SessionEpoch): void {
55
+ if (id.length != 64) throw new Error('Invalid session identity');
56
+ if (verified == u64.MAX_VALUE) throw new Error('No verified session generation');
57
+ const next = SessionEpochs.successor(state);
58
+ if (state.revision != verified) throw new Error('Invalid verified session state');
59
+ if (AuthStateDb.epochRevisions.claim(new SessionEpochKey('3:' + AuthRealm.current() + '\x00' + id, next.revision), next).claimed) {
60
+ // The immutable claim is authoritative. The next writable verification
61
+ // repairs this one-revision head lag; queries can already see the claim.
62
+ return;
63
+ }
64
+ // The cached generation became stale. Advance AFTER the security change,
65
+ // including sessions minted under the competing generation.
66
+ SessionEpochs.revokeId(id);
67
+ }
68
+ private static successor(epoch: SessionEpoch): SessionEpoch {
69
+ if (epoch.revision == u64.MAX_VALUE) throw new Error('Session generation exhausted');
70
+ const next = new SessionEpoch(); next.revision = epoch.revision + 1;
71
+ next.claimNonce = new Uint8Array(16); crypto.getRandomValues(next.claimNonce);
72
+ next.factorHost = epoch.factorHost; next.factorName = epoch.factorName;
73
+ next.factorMethod = epoch.factorMethod; next.factorRevision = epoch.factorRevision;
74
+ next.factorSecret = epoch.factorSecret;
75
+ return next;
76
+ }
77
+ /** One unique claim commits the factor policy AND invalidates every earlier session. */
78
+ public static changeFactor(id: string, verified: SessionEpoch, host: string, name: string,
79
+ expected: u64, method: u8, secret: Uint8Array): bool {
80
+ let epoch = verified;
81
+ for (let attempt = 0; attempt < 3; attempt++) {
82
+ if (epoch.factorHost == host && epoch.factorName == name && epoch.factorRevision != expected) return false;
83
+ if (expected == u64.MAX_VALUE) throw new Error('Factor revision exhausted');
84
+ const next = SessionEpochs.successor(epoch);
85
+ next.factorHost = host; next.factorName = name; next.factorMethod = method;
86
+ next.factorRevision = expected + 1; next.factorSecret = secret;
87
+ if (AuthStateDb.epochRevisions.claim(new SessionEpochKey('3:' + AuthRealm.current() + '\x00' + id, next.revision), next).claimed) return true;
88
+ epoch = SessionEpochs.read(id);
89
+ }
90
+ throw new Error('Factor change conflicted; retry');
91
+ }
49
92
  /** The stable 32-byte user id as hex; no request or @user encoder needed. */
50
- public static revokeId(id: string): void {
93
+ public static revokeId(id: string, host: string = AuthRealm.current()): void {
51
94
  if (id.length != 64) throw new Error('Invalid session identity');
52
95
  for (let i: i32 = 0; i < 3; i++) {
53
- const epoch = SessionEpochs.read(id);
54
- const next = new SessionEpoch();
55
- next.revision = epoch.revision + 1;
56
- if (!AuthStateDb.epochRevisions.claim(new SessionEpochKey(id, next.revision), next).claimed) continue;
96
+ const epoch = SessionEpochs.read(id, host);
97
+ const next = SessionEpochs.successor(epoch);
98
+ if (!AuthStateDb.epochRevisions.claim(new SessionEpochKey('3:' + host + '\x00' + id, next.revision), next).claimed) continue;
57
99
  // The immutable claim is the revocation commit. A concurrent head
58
100
  // advance must not be undone by this request's delayed write.
59
- const key = new SessionUserKey(id);
101
+ const key = new SessionUserKey('3:' + host + '\x00' + id);
60
102
  const head = AuthStateDb.epochHeads.getCurrentSnapshot(key);
61
103
  if (head == null && Db.lastError() != DbError.None)
62
104
  throw new Error('Session state unavailable');
@@ -1,3 +1,4 @@
1
+ import { AuthRealm } from 'toiljs/server/auth/AuthRealm';
1
2
  import { AuthReads } from 'toiljs/server/auth/AuthReads';
2
3
  // AuthService: the server half of the post-quantum auth primitive, available
3
4
  // as a no-import global (registered via the toilscript `--lib` mechanism, the
@@ -13,7 +14,7 @@ import { AuthReads } from 'toiljs/server/auth/AuthReads';
13
14
  import { DataWriter, DataReader } from 'data';
14
15
  import { SessionEpochs } from 'toiljs/server/auth/SessionEpochs';
15
16
  import { toildbHost } from 'bindings/toildb';
16
- import { AuthStateDb, SessionDigest, RevokedSession } from 'toiljs/server/auth/AuthStateDb';
17
+ import { AuthStateDb, SessionDigest, RevokedSession, SessionEpoch } from 'toiljs/server/auth/AuthStateDb';
17
18
  import { HmacImportParams, HmacParams, ALG_SHA_256, FMT_RAW, USAGE_SIGN, USAGE_VERIFY } from 'crypto';
18
19
 
19
20
  import {
@@ -137,23 +138,7 @@ function __resolveSessionSecretBase(): Uint8Array {
137
138
  * request to one tenant and distinct across tenants. Used to bind a session to
138
139
  * its tenant (below). */
139
140
  function __sessionTenantTag(): string {
140
- const req = Server.currentRequest;
141
- if (req == null) return '';
142
- const raw = req.header('host');
143
- if (raw == null) return '';
144
- let h = raw.toLowerCase();
145
- if (h.startsWith('[')) {
146
- // IPv6 literal `[addr]` optionally + `:port`: keep through the closing
147
- // bracket, drop any port after it. A naive lastIndexOf(':') would slice
148
- // inside the address (`[::1]` -> `[:`), collapsing distinct IPv6 tenants
149
- // to the same tag. Bracket-aware, matching the edge's strip_port.
150
- const close = h.indexOf(']');
151
- if (close >= 0) h = h.slice(0, close + 1);
152
- } else {
153
- const colon = h.lastIndexOf(':');
154
- if (colon > 0) h = h.slice(0, colon); // drop :port (mirrors edge strip_port)
155
- }
156
- return h;
141
+ return AuthRealm.current();
157
142
  }
158
143
 
159
144
  /**
@@ -320,7 +305,7 @@ export namespace AuthService {
320
305
  }
321
306
 
322
307
  /** Session payload format version (first byte of the sealed payload). */
323
- const SESSION_VERSION: u8 = 2;
308
+ const SESSION_VERSION: u8 = 3;
324
309
 
325
310
  /** Default session lifetime if `mintSession` is called without a ttl. */
326
311
  export const DEFAULT_SESSION_TTL_SECS: u64 = 604800; // 7 days
@@ -363,6 +348,9 @@ export namespace AuthService {
363
348
  req.__authChecked = false;
364
349
  req.__authBytes = null;
365
350
  req.__authExpires = 0;
351
+ req.__authGeneration = u64.MAX_VALUE;
352
+ req.__authEpochId = '';
353
+ req.__authEpochData = null;
366
354
  }
367
355
 
368
356
  function verifySession(req: Request): Uint8Array | null {
@@ -387,12 +375,43 @@ export namespace AuthService {
387
375
  if (!r.ok) return null; // truncated/malformed
388
376
 
389
377
  if (Time.nowSeconds() >= exp) return null; // expired
390
- if (!SessionEpochs.allowed(userBytes, generation)) return null;
378
+ const epochId = SessionEpochs.key(userBytes);
379
+ const state = SessionEpochs.read(epochId);
380
+ if (state.revision != generation) return null;
381
+ // Ordinary accounts avoid serialization; factors reuse the verified request snapshot.
382
+ req.__authEpochData = state.factorName.length == 0 ? null : state.encode();
391
383
 
392
384
  req.__authExpires = exp;
385
+ req.__authGeneration = generation;
386
+ req.__authEpochId = epochId;
393
387
  return userBytes;
394
388
  }
395
389
 
390
+ /** @internal Generation already verified on this request; never a process cache. */
391
+ export function __sessionGeneration(): u64 {
392
+ if (getSessionBytes() == null) return u64.MAX_VALUE;
393
+ const req = Server.currentRequest;
394
+ return req == null ? u64.MAX_VALUE : req.__authGeneration;
395
+ }
396
+
397
+ /** @internal Security policy from the same snapshot that authorized this request. */
398
+ export function __sessionState(): SessionEpoch {
399
+ if (getSessionBytes() == null) throw new Error('Verified session required');
400
+ const req = Server.currentRequest!;
401
+ const state = new SessionEpoch();
402
+ if (req.__authEpochData != null) state.decodeInto(req.__authEpochData!);
403
+ else state.revision = req.__authGeneration;
404
+ return state;
405
+ }
406
+
407
+ /** @internal Atomic factor-policy change and session revocation. */
408
+ export function __changeFactor(host: string, name: string, expected: u64, method: u8, secret: Uint8Array): bool {
409
+ const state = __sessionState();
410
+ const id = Server.currentRequest!.__authEpochId;
411
+ invalidateSession();
412
+ return SessionEpochs.changeFactor(id, state, host, name, expected, method, secret);
413
+ }
414
+
396
415
  /** Whether the current request carries a valid, unexpired session. The
397
416
  * toilscript `@auth` guard calls this before running the route. */
398
417
  export function hasSession(): bool {
@@ -481,6 +500,18 @@ export namespace AuthService {
481
500
  SessionEpochs.revoke(userData);
482
501
  }
483
502
 
503
+ /** @internal Revoke the current verified identity after a factor mutation. */
504
+ export function __revokeVerifiedSessions(): void {
505
+ const data = getSessionBytes();
506
+ const req = Server.currentRequest;
507
+ if (data == null || req == null) throw new Error('Verified session required');
508
+ const generation = req.__authGeneration;
509
+ const id = req.__authEpochId;
510
+ const state = __sessionState();
511
+ invalidateSession();
512
+ SessionEpochs.revokeVerifiedId(id, generation, state);
513
+ }
514
+
484
515
  /** Revoke the verified signed payload, including its unpredictable per-login nonce. */
485
516
  export function revokeSession(): void {
486
517
  if (!hasSession()) return;
@@ -33,5 +33,11 @@ declare class TwoFactorChallenge { token: string; status: EmailStatus; construct
33
33
  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; }
34
34
  declare namespace AuthService { function deleteUser(id: ToilUserId, realm?: string): bool; function indexUsers(limit?: i32, cursor?: Uint8Array | null): Uint8Array | null; function onRegistered(handler: (id: ToilUserId, username: string, email: string) => void): void; 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, generation?: u64): Cookie; function clearSession(): Cookie; function revokeSession(): void; 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; }
35
35
  interface __ToilAuthUser { toilUserId: Uint8Array; username: string; }
36
+
37
+ /** Authenticated principal, extended by the compiler's generated @user declarations. */
38
+ type AuthUser = __ToilAuthUser;
36
39
  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; }
37
40
  declare function __toilEncodeAuthUser(toilUserId: Uint8Array, username: string): Uint8Array;
41
+
42
+ /** Resolve a collection name to the host handle used by compiler-generated database bindings. */
43
+ declare function __toildbResolve(name: string): u32;
@@ -27,8 +27,7 @@ import {
27
27
  utf8Length,
28
28
  writeBytes,
29
29
  writeU16,
30
- writeU32,
31
- writeUtf8
30
+ writeU32
32
31
  } from './memory';
33
32
  import { Header, Method, Request } from './request';
34
33
  import { Response, ensureSecurityHeaders } from './response';
@@ -145,11 +144,14 @@ export function encodeResponse(resp: Response, dst_ofs: usize): u32 {
145
144
  if (resp.headers.length > 0xffff) {
146
145
  return encodeFallback500(dst_ofs);
147
146
  }
147
+ const lengths = new Uint32Array(resp.headers.length * 2);
148
148
  for (let i = 0; i < resp.headers.length; i++) {
149
149
  const h = resp.headers[i];
150
- if (utf8Length(h.name) > 0xffff || utf8Length(h.value) > 0xffff) {
150
+ const nameLen = utf8Length(h.name), valLen = utf8Length(h.value);
151
+ if (nameLen > 0xffff || valLen > 0xffff) {
151
152
  return encodeFallback500(dst_ofs);
152
153
  }
154
+ lengths[i * 2] = nameLen; lengths[i * 2 + 1] = valLen;
153
155
  }
154
156
  if (<u64>resp.body.length > <u64>0xffffffff) {
155
157
  return encodeFallback500(dst_ofs);
@@ -165,14 +167,14 @@ export function encodeResponse(resp: Response, dst_ofs: usize): u32 {
165
167
 
166
168
  for (let i = 0; i < resp.headers.length; i++) {
167
169
  const h = resp.headers[i];
168
- const nameLen = utf8Length(h.name);
169
- const valLen = utf8Length(h.value);
170
+ const nameLen = lengths[i * 2];
171
+ const valLen = lengths[i * 2 + 1];
170
172
  writeU16(cur, <u16>nameLen);
171
173
  cur += 2;
172
174
  writeU16(cur, <u16>valLen);
173
175
  cur += 2;
174
- cur += writeUtf8(cur, h.name);
175
- cur += writeUtf8(cur, h.value);
176
+ cur += String.UTF8.encodeUnsafe(changetype<usize>(h.name), h.name.length, cur);
177
+ cur += String.UTF8.encodeUnsafe(changetype<usize>(h.value), h.value.length, cur);
176
178
  }
177
179
 
178
180
  const bodyLen = <u32>resp.body.length;
@@ -1,104 +1,24 @@
1
- /**
2
- * base64url (RFC 4648 §5), unpadded. The toilscript std ships `Encoding.Hex`
3
- * and `Encoding.Varint` but no base64, and `SecureCookies` needs a compact,
4
- * cookie-safe transport for raw bytes (IV ‖ ciphertext ‖ tag, or an HMAC).
5
- *
6
- * base64url is a deliberate fit for cookies: its alphabet
7
- * (`A-Z a-z 0-9 - _`) is entirely within the RFC 6265bis `cookie-octet` set
8
- * and is invariant under percent-encoding, so a sealed value round-trips
9
- * cleanly through the default cookie encoder/decoder untouched.
10
- *
11
- * Internal to the cookie library (not a global).
12
- */
1
+ /** Bounded native base64url for cookies. UTF-16 avoids guest UTF-8 round trips. */
2
+ @external('env', 'codec.base64url_encode')
3
+ declare function encode(ptr: usize, len: i32, out: usize, cap: i32): i32;
4
+ @external('env', 'codec.base64url_decode')
5
+ declare function decode(ptr: usize, chars: i32, out: usize, cap: i32): i32;
13
6
 
14
- const ALPHABET: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
15
-
16
- /** Encode `data` as unpadded base64url. */
7
+ /** Unpadded RFC 4648 base64url; at most 64 KiB of input. */
17
8
  export function base64UrlEncode(data: Uint8Array): string {
18
- const n = data.length;
19
- if (n == 0) return '';
20
-
21
- let out = '';
22
- let i = 0;
23
- while (i + 3 <= n) {
24
- const b0 = <i32>data[i];
25
- const b1 = <i32>data[i + 1];
26
- const b2 = <i32>data[i + 2];
27
- out += ALPHABET.charAt(b0 >> 2);
28
- out += ALPHABET.charAt(((b0 & 3) << 4) | (b1 >> 4));
29
- out += ALPHABET.charAt(((b1 & 15) << 2) | (b2 >> 6));
30
- out += ALPHABET.charAt(b2 & 63);
31
- i += 3;
32
- }
33
-
34
- const rem = n - i;
35
- if (rem == 1) {
36
- const b0 = <i32>data[i];
37
- out += ALPHABET.charAt(b0 >> 2);
38
- out += ALPHABET.charAt((b0 & 3) << 4);
39
- } else if (rem == 2) {
40
- const b0 = <i32>data[i];
41
- const b1 = <i32>data[i + 1];
42
- out += ALPHABET.charAt(b0 >> 2);
43
- out += ALPHABET.charAt(((b0 & 3) << 4) | (b1 >> 4));
44
- out += ALPHABET.charAt((b1 & 15) << 2);
45
- }
46
- return out;
9
+ if (data.length == 0) return '';
10
+ if (data.length > 65536) throw new Error('base64 input exceeds 64 KiB');
11
+ const length = (data.length / 3) * 4 + (data.length % 3 == 0 ? 0 : data.length % 3 + 1);
12
+ const out = new Uint16Array(length);
13
+ if (encode(data.dataStart, data.length, out.dataStart, out.byteLength) != length) throw new Error('base64 encode failed');
14
+ return String.UTF16.decodeUnsafe(out.dataStart, out.byteLength);
47
15
  }
48
16
 
49
- /** Decode a single base64url (or base64) sextet character, or -1 if invalid. */
50
- function sextet(c: i32): i32 {
51
- if (c >= 65 && c <= 90) return c - 65; // A-Z
52
- if (c >= 97 && c <= 122) return c - 97 + 26; // a-z
53
- if (c >= 48 && c <= 57) return c - 48 + 52; // 0-9
54
- if (c == 45 || c == 43) return 62; // '-' (url) or '+' (standard)
55
- if (c == 95 || c == 47) return 63; // '_' (url) or '/' (standard)
56
- return -1;
57
- }
58
-
59
- /**
60
- * Decode unpadded (or padded) base64url/base64 into bytes, or `null` if the
61
- * input contains an invalid character or has an impossible length. `=` padding
62
- * and ASCII whitespace are tolerated and ignored.
63
- */
17
+ /** Accept URL/standard alphabets and ignored padding/ASCII whitespace, as before. */
64
18
  export function base64UrlDecode(s: string): Uint8Array | null {
65
- const vals = new Array<i32>();
66
- for (let i = 0; i < s.length; i++) {
67
- const c = s.charCodeAt(i);
68
- if (c == 61 || c == 32 || c == 9 || c == 10 || c == 13) continue; // '=' or WS
69
- const v = sextet(c);
70
- if (v < 0) return null;
71
- vals.push(v);
72
- }
73
-
74
- const nq = vals.length;
75
- const rem = nq & 3;
76
- if (rem == 1) return null; // a single trailing sextet can't exist
77
-
78
- const outLen = (nq * 6) / 8;
79
- const out = new Uint8Array(outLen);
80
- let oi = 0;
81
- let i = 0;
82
- while (i + 4 <= nq) {
83
- const v0 = vals[i];
84
- const v1 = vals[i + 1];
85
- const v2 = vals[i + 2];
86
- const v3 = vals[i + 3];
87
- out[oi++] = <u8>(((v0 << 2) | (v1 >> 4)) & 0xff);
88
- out[oi++] = <u8>(((v1 << 4) | (v2 >> 2)) & 0xff);
89
- out[oi++] = <u8>(((v2 << 6) | v3) & 0xff);
90
- i += 4;
91
- }
92
- if (rem == 2) {
93
- const v0 = vals[i];
94
- const v1 = vals[i + 1];
95
- out[oi++] = <u8>(((v0 << 2) | (v1 >> 4)) & 0xff);
96
- } else if (rem == 3) {
97
- const v0 = vals[i];
98
- const v1 = vals[i + 1];
99
- const v2 = vals[i + 2];
100
- out[oi++] = <u8>(((v0 << 2) | (v1 >> 4)) & 0xff);
101
- out[oi++] = <u8>(((v1 << 4) | (v2 >> 2)) & 0xff);
102
- }
103
- return out;
19
+ if (s.length > 65536) return null;
20
+ const out = new Uint8Array((s.length * 6) / 8);
21
+ const size = decode(changetype<usize>(s), s.length, out.dataStart, out.length);
22
+ if (size < 0 || size > out.length) return null;
23
+ return size == out.length ? out : out.subarray(0, size);
104
24
  }
@@ -31,6 +31,9 @@ function hexVal(c: i32): i32 {
31
31
 
32
32
  /** Percent-encode `s` (UTF-8) into a cookie-safe value. */
33
33
  export function percentEncode(s: string): string {
34
+ let safe = true;
35
+ for (let i = 0; i < s.length; i++) if (!isUnreserved(s.charCodeAt(i))) { safe = false; break; }
36
+ if (safe) return s;
34
37
  const bytes = Uint8Array.wrap(String.UTF8.encode(s));
35
38
  let out = '';
36
39
  for (let i = 0; i < bytes.length; i++) {
@@ -52,6 +55,7 @@ export function percentEncode(s: string): string {
52
55
  * form-encoded, so `+` is not a space).
53
56
  */
54
57
  export function percentDecode(s: string): string {
58
+ if (s.indexOf('%') < 0) return s;
55
59
  const input = Uint8Array.wrap(String.UTF8.encode(s));
56
60
  const n = input.length;
57
61
  const bytes = new Array<u8>();
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `SecureCookies` — tamper-proof and confidential cookie values, built on the
3
- * ambient `crypto` global (no new host functions).
3
+ * ambient `crypto` global and bounded native base64 codecs.
4
4
  *
5
5
  * - `SecureCookies.signed(key)` — HMAC-SHA256. The value stays readable but is
6
6
  * bound to the cookie name, so it cannot be tampered with or moved to another
@@ -38,6 +38,9 @@ export class Request {
38
38
  __authChecked: bool = false;
39
39
  __authBytes: Uint8Array | null = null;
40
40
  __authExpires: u64 = 0;
41
+ __authGeneration: u64 = u64.MAX_VALUE;
42
+ __authEpochId: string = '';
43
+ __authEpochData: Uint8Array | null = null;
41
44
 
42
45
  // Lazily parsed `Cookie` header, cached for the life of the request.
43
46
  private _cookies: CookieMap | null = null;
@@ -1,21 +1,5 @@
1
1
  // Generated from server/runtime by scripts/gen-server-types.mjs.
2
- /**
3
- * base64url (RFC 4648 §5), unpadded. The toilscript std ships `Encoding.Hex`
4
- * and `Encoding.Varint` but no base64, and `SecureCookies` needs a compact,
5
- * cookie-safe transport for raw bytes (IV ‖ ciphertext ‖ tag, or an HMAC).
6
- *
7
- * base64url is a deliberate fit for cookies: its alphabet
8
- * (`A-Z a-z 0-9 - _`) is entirely within the RFC 6265bis `cookie-octet` set
9
- * and is invariant under percent-encoding, so a sealed value round-trips
10
- * cleanly through the default cookie encoder/decoder untouched.
11
- *
12
- * Internal to the cookie library (not a global).
13
- */
14
- /** Encode `data` as unpadded base64url. */
2
+ /** Unpadded RFC 4648 base64url; at most 64 KiB of input. */
15
3
  export declare function base64UrlEncode(data: Uint8Array): string;
16
- /**
17
- * Decode unpadded (or padded) base64url/base64 into bytes, or `null` if the
18
- * input contains an invalid character or has an impossible length. `=` padding
19
- * and ASCII whitespace are tolerated and ignored.
20
- */
4
+ /** Accept URL/standard alphabets and ignored padding/ASCII whitespace, as before. */
21
5
  export declare function base64UrlDecode(s: string): Uint8Array | null;
@@ -1,7 +1,7 @@
1
1
  // Generated from server/runtime by scripts/gen-server-types.mjs.
2
2
  /**
3
3
  * `SecureCookies` — tamper-proof and confidential cookie values, built on the
4
- * ambient `crypto` global (no new host functions).
4
+ * ambient `crypto` global and bounded native base64 codecs.
5
5
  *
6
6
  * - `SecureCookies.signed(key)` — HMAC-SHA256. The value stays readable but is
7
7
  * bound to the cookie name, so it cannot be tampered with or moved to another
@@ -28,6 +28,9 @@ export declare class Request {
28
28
  __authChecked: bool;
29
29
  __authBytes: Uint8Array | null;
30
30
  __authExpires: u64;
31
+ __authGeneration: u64;
32
+ __authEpochId: string;
33
+ __authEpochData: Uint8Array | null;
31
34
  private _cookies;
32
35
  constructor(method: Method, path: string, headers: Array<Header>, body: Uint8Array);
33
36
  /**