toiljs 0.0.136 → 0.0.138

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,79 @@
1
+ import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ function digest(value) {
6
+ return createHash('sha256').update(value).digest('hex');
7
+ }
8
+ function libraryEntries(dir) {
9
+ try {
10
+ return fs
11
+ .readdirSync(dir)
12
+ .filter((name) => name.endsWith('.ts') && !name.endsWith('.d.ts'))
13
+ .sort();
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ async function compile() {
20
+ const [bin, staging, ...args] = process.argv.slice(2);
21
+ if (!bin || !staging)
22
+ throw new Error('Missing compiler worker arguments');
23
+ const inputs = new Map();
24
+ const directories = new Map();
25
+ const outputs = new Map();
26
+ let stable = true;
27
+ const api = (await import(pathToFileURL(path.resolve(path.dirname(bin), '../dist/cli.js')).href));
28
+ const result = await api.main(args, {
29
+ stdout: process.stdout,
30
+ stderr: process.stderr,
31
+ async readFile(file, base) {
32
+ const full = path.resolve(base, file);
33
+ let content;
34
+ try {
35
+ content = await fs.promises.readFile(full, 'utf8');
36
+ }
37
+ catch {
38
+ content = null;
39
+ }
40
+ const hash = content === null ? null : digest(content);
41
+ if (inputs.has(full) && inputs.get(full) !== hash)
42
+ stable = false;
43
+ inputs.set(full, hash);
44
+ return content;
45
+ },
46
+ listFiles(dir, base) {
47
+ const full = path.resolve(base, dir);
48
+ const entries = libraryEntries(full);
49
+ if (directories.has(full) &&
50
+ JSON.stringify(directories.get(full)) !== JSON.stringify(entries))
51
+ stable = false;
52
+ directories.set(full, entries);
53
+ return entries;
54
+ },
55
+ async writeFile(file, contents, base) {
56
+ const full = path.resolve(base, file);
57
+ const staged = path.join(staging, digest(full));
58
+ await fs.promises.writeFile(staged, contents);
59
+ outputs.set(full, { path: full, staged, hash: digest(contents) });
60
+ return true;
61
+ },
62
+ });
63
+ if (result.error) {
64
+ process.exitCode = 1;
65
+ return;
66
+ }
67
+ const manifest = {
68
+ key: '',
69
+ stable,
70
+ inputs: [...inputs].map(([file, hash]) => ({ path: file, hash })),
71
+ directories: [...directories].map(([dir, entries]) => ({ path: dir, entries })),
72
+ outputs: [...outputs.values()],
73
+ };
74
+ await fs.promises.writeFile(path.join(staging, 'manifest.json'), JSON.stringify(manifest));
75
+ }
76
+ await compile().catch((error) => {
77
+ process.stderr.write(`toiljs compiler worker: ${String(error)}\n`);
78
+ process.exitCode = 1;
79
+ });
@@ -1,6 +1,7 @@
1
1
  export declare const STRATEGY_FIXED = 0;
2
2
  export declare const STRATEGY_SLIDING = 1;
3
3
  export declare const STRATEGY_TOKEN_BUCKET = 2;
4
+ export declare const STRATEGY_TRAILING = 3;
4
5
  export declare function __resetRatelimitForTests(): void;
5
6
  export interface DevDecision {
6
7
  allowed: boolean;
@@ -1,6 +1,7 @@
1
1
  export const STRATEGY_FIXED = 0;
2
2
  export const STRATEGY_SLIDING = 1;
3
3
  export const STRATEGY_TOKEN_BUCKET = 2;
4
+ export const STRATEGY_TRAILING = 3;
4
5
  const registry = new Map();
5
6
  export function __resetRatelimitForTests() {
6
7
  registry.clear();
@@ -11,6 +12,8 @@ export function ratelimitCheck(routeId, strategy, limit, window, identity, now)
11
12
  rl = { strategy, a: Math.max(1, limit), b: Math.max(1, window), keys: new Map() };
12
13
  registry.set(routeId, rl);
13
14
  }
15
+ if (rl.strategy === STRATEGY_TRAILING)
16
+ return checkTrailing(rl, identity, now);
14
17
  if (rl.strategy === STRATEGY_TOKEN_BUCKET)
15
18
  return checkBucket(rl, identity, now);
16
19
  return checkWindow(rl, identity, now, rl.strategy === STRATEGY_SLIDING);
@@ -65,3 +68,29 @@ function checkWindow(rl, key, now, sliding) {
65
68
  const waitMs = windowMs - posInWindow;
66
69
  return { allowed: false, retryAfterSecs: Math.max(1, Math.ceil(waitMs / 1000)) };
67
70
  }
71
+ function checkTrailing(rl, key, now) {
72
+ let st = rl.keys.get(key);
73
+ if (st === undefined) {
74
+ st = { tokensMilli: 0, window: 0, cur: 0, prev: 0, lastMs: now, events: [], first: 0 };
75
+ rl.keys.set(key, st);
76
+ }
77
+ now = Math.max(now, st.lastMs);
78
+ st.lastMs = now;
79
+ const events = st.events ?? (st.events = []);
80
+ let first = st.first ?? 0;
81
+ const windowMs = rl.b * 1000;
82
+ while (first < events.length && events[first] <= now - windowMs)
83
+ first++;
84
+ if (first > 0 && first * 2 >= events.length) {
85
+ events.splice(0, first);
86
+ first = 0;
87
+ }
88
+ st.first = first;
89
+ if (events.length - first >= rl.a)
90
+ return {
91
+ allowed: false,
92
+ retryAfterSecs: Math.max(1, Math.ceil((events[first] + windowMs - now) / 1000)),
93
+ };
94
+ events.push(now);
95
+ return { allowed: true, retryAfterSecs: 0 };
96
+ }
@@ -338,6 +338,7 @@ export class DaemonHost {
338
338
  this.state.db.changesOverflow = false;
339
339
  const startedAt = performance.now();
340
340
  try {
341
+ this.exports.__collect?.();
341
342
  result.returnCode = this.exports.scheduled_tick(task.taskIndex);
342
343
  if (result.returnCode < 0n) {
343
344
  result.status = 'failed';
@@ -387,6 +388,7 @@ export class DaemonHost {
387
388
  resetDbLimits(db);
388
389
  db.pendingCheckpoints.clear();
389
390
  try {
391
+ this.exports.__collect?.();
390
392
  const rc = this.exports.derive_run(derive.deriveId);
391
393
  if (rc !== 0n)
392
394
  throw new Error(`derive_run returned ${String(rc)}`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toiljs",
3
3
  "type": "module",
4
- "version": "0.0.136",
4
+ "version": "0.0.138",
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": {
@@ -166,7 +166,7 @@
166
166
  "picocolors": "^1.1.1",
167
167
  "semver": "^7.8.5",
168
168
  "sharp": "^0.35.5",
169
- "toilscript": ">=0.1.66",
169
+ "toilscript": ">=0.1.67",
170
170
  "vite": "^8.3.5",
171
171
  "vite-imagetools": "^12.0.1",
172
172
  "vite-plugin-node-polyfills": "^0.28.0"
@@ -175,7 +175,7 @@
175
175
  "prettier": ">=3.0.0",
176
176
  "react": "^19.3.1",
177
177
  "react-dom": "^19.3.1",
178
- "toilscript": ">=0.1.66",
178
+ "toilscript": ">=0.1.67",
179
179
  "vitest": "^5.0.5",
180
180
  "@vitest/browser-webdriverio": "^5.0.0",
181
181
  "@vitest/coverage-v8": "^5.0.5",
@@ -19,6 +19,11 @@ import { DataReader, DataWriter } from 'data';
19
19
  return true;
20
20
  }
21
21
 
22
+ @inline function deleteAccountEnabled(): bool {
23
+ if (isDefined(__toilAuthDeleteAccountEnabled)) return __toilAuthDeleteAccountEnabled();
24
+ return true;
25
+ }
26
+
22
27
  /**
23
28
  * Built-in Toil PQ-Auth controller: the full post-quantum password-login API
24
29
  * (`/auth/register|login/start|finish`) plus sessions (`/auth/me`, `/auth/logout`),
@@ -469,6 +474,7 @@ class Auth {
469
474
  AuthDb.accounts.compareDeleteSnapshot(key, observed);
470
475
  return fail();
471
476
  }
477
+ SessionEpochs.activate(crypto.toHex(acct.toilUserId), h);
472
478
  AuthMaintenance.index(h, acct);
473
479
  AuthService.__initializeRegistration(ToilUserId.fromBytes(acct.toilUserId), username, acct.email);
474
480
  acct.registering = false;
@@ -614,6 +620,7 @@ class Auth {
614
620
  return Response.bytes(new DataWriter().writeU8(ST_EMAIL_TAKEN).toBytes());
615
621
  }
616
622
 
623
+ SessionEpochs.activate(crypto.toHex(a.toilUserId), h);
617
624
  AuthMaintenance.index(h, a);
618
625
  AuthService.__initializeRegistration(ToilUserId.fromBytes(a.toilUserId), username, email);
619
626
  a.registering = false;
@@ -1044,6 +1051,7 @@ class Auth {
1044
1051
  @auth
1045
1052
  @post('/delete')
1046
1053
  public deleteAccount(ctx: RouteContext): Response {
1054
+ if (!deleteAccountEnabled()) return Response.text('not found\n', 404);
1047
1055
  const user = AuthService.getUser();
1048
1056
  if (user == null) return fail();
1049
1057
  const h = realm(ctx);
@@ -1194,10 +1202,11 @@ class Auth {
1194
1202
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1195
1203
  @post('/2fa/setup')
1196
1204
  public twoFaSetup(_ctx: RouteContext): Response {
1197
- if (!twoFactorSetupEnabled()) return Response.text('not found\n', 404);
1198
1205
  if (_ctx.request.body.length > 128) return fail();
1199
1206
  const r = new DataReader(_ctx.request.body);
1200
1207
  const targetMethod = r.readU8();
1208
+ if (!twoFactorSetupEnabled() && (!r.ok || targetMethod != TWOFA_NONE))
1209
+ return Response.text('not found\n', 404);
1201
1210
  if (!r.ok) return fail();
1202
1211
  if (!isKnownTwoFaMethod(targetMethod)) return fail();
1203
1212
  const u = AuthService.getUser();
@@ -1280,7 +1289,6 @@ class Auth {
1280
1289
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1281
1290
  @post('/2fa/setup/verify')
1282
1291
  public twoFaSetupVerify(_ctx: RouteContext): Response {
1283
- if (!twoFactorSetupEnabled()) return Response.text('not found\n', 404);
1284
1292
  if (_ctx.request.body.length > 128) return fail();
1285
1293
  const r = new DataReader(_ctx.request.body);
1286
1294
  const code = r.readString();
@@ -1289,6 +1297,15 @@ class Auth {
1289
1297
  if (u == null) return fail();
1290
1298
  const h = realm(_ctx);
1291
1299
 
1300
+ const accountKey = new Username(h, u.username);
1301
+ const current = this.account(accountKey);
1302
+ if (current == null) return fail();
1303
+ const key = this.secondaryKey(h, current);
1304
+ const observed = AuthDb.twoFaSetup.getCurrentSnapshot(key);
1305
+ if (observed == null) return twoFactorSetupEnabled() ? fail() : Response.text('not found\n', 404);
1306
+ const ch = observed.value;
1307
+ if (!twoFactorSetupEnabled() && ch.targetMethod != TWOFA_NONE)
1308
+ return Response.text('not found\n', 404);
1292
1309
  // RACE-FREE attempt cap for the setup challenge (same rationale as
1293
1310
  // /2fa/verify): an atomic host-side limiter keyed on the session user, so
1294
1311
  // the `ch.attempts` get+patch below cannot be out-raced by concurrent
@@ -1302,13 +1319,6 @@ class Auth {
1302
1319
  );
1303
1320
  if (srl != null) return srl;
1304
1321
 
1305
- const accountKey = new Username(h, u.username);
1306
- const current = this.account(accountKey);
1307
- if (current == null) return fail();
1308
- const key = this.secondaryKey(h, current);
1309
- const observed = AuthDb.twoFaSetup.getCurrentSnapshot(key);
1310
- if (observed == null) return fail();
1311
- const ch = observed.value;
1312
1322
  if (ch.sessionVersion != 3 || AuthService.__sessionGeneration() != ch.sessionEpoch) return fail();
1313
1323
  if (nowSecs() >= ch.exp || ch.attempts >= TWOFA_MAX_ATTEMPTS) {
1314
1324
  AuthDb.twoFaSetup.compareDeleteSnapshot(key, observed);
@@ -1,7 +1,23 @@
1
1
  import { AuthDb, AuthAccount, Username, EmailKey, DeletedAccountKey, DeletedAccountMarker,
2
2
  AuthUserKey, AuthUserAccount, AuthUserAccounts } from './AuthStore';
3
+ import { AuthStateDb, SessionEpochKey, SessionEpoch, FactorKey, FactorRevision, FactorSettings } from './AuthStateDb';
4
+ import { AuthReads } from './AuthReads';
5
+ import { Authenticator } from './Authenticator';
6
+ import { __toildbResolve } from 'toildb';
7
+ import { base64UrlEncode } from 'toiljs/server/runtime';
3
8
  import { SessionEpochs } from './SessionEpochs';
4
9
 
10
+ @lazy let epochHandle: u32 = u32.MAX_VALUE;
11
+ @lazy let factorHandle: u32 = u32.MAX_VALUE;
12
+ function epochHistoryHandle(): u32 {
13
+ if (epochHandle == u32.MAX_VALUE) epochHandle = __toildbResolve('AuthStateDb/epochRevisions');
14
+ return epochHandle;
15
+ }
16
+ function factorHistoryHandle(): u32 {
17
+ if (factorHandle == u32.MAX_VALUE) factorHandle = __toildbResolve('AuthStateDb/factorRevisions');
18
+ return factorHandle;
19
+ }
20
+
5
21
  function sameBytes(a: Uint8Array, b: Uint8Array): bool {
6
22
  if (a.length != b.length) return false;
7
23
  let different: i32 = 0;
@@ -128,6 +144,109 @@ export class AuthMaintenance {
128
144
  }
129
145
  return page.cursor;
130
146
  }
147
+ /** Bounded, restartable erasure. Only opaque progress and generation fences
148
+ * survive; immutable epoch history must not retain old names or secrets. */
149
+ private static eraseFactors(key: Username, acct: AuthAccount, uid: Uint8Array,
150
+ markerKey: DeletedAccountKey): void {
151
+ let marker = AuthDb.deletedAccounts.getCurrentSnapshot(markerKey);
152
+ if (marker == null) throw new Error('Account deletion marker unavailable');
153
+ if (marker.value.factorsErased) return;
154
+ const epoch = SessionEpochs.beginDeletion(crypto.toHex(uid), key.host);
155
+ const progress = marker.value;
156
+ // Publish progress on any budget boundary. Replaying a partially erased
157
+ // entry is safe: counters are deleted before the containing revision.
158
+ let steps: i32 = 0;
159
+ while (progress.epochCursor < epoch.revision) {
160
+ const budget = Db.budget();
161
+ if (budget.remainingOps < 28 || budget.remainingWrites < 20 || steps++ >= 128) {
162
+ if (!AuthDb.deletedAccounts.compareExchangeSnapshot(markerKey, marker, progress))
163
+ throw new Error('Account cleanup conflicted; retry');
164
+ throw new Error('Account cleanup incomplete; retry deletion');
165
+ }
166
+ const revisionKey = new SessionEpochKey('3:' + key.host + '\x00' + crypto.toHex(uid), progress.epochCursor);
167
+ const previous = AuthReads.ownerSnapshot<SessionEpochKey, SessionEpoch>(epochHistoryHandle(), revisionKey);
168
+ if (previous != null && previous.value.factorHost.length == 0 && previous.value.factorName.length == 0 &&
169
+ previous.value.factorMethod == 0 && previous.value.factorRevision == 0 && previous.value.factorSecret.length == 0) {
170
+ // Keep an existing anonymous owner occupied, including when a
171
+ // concurrent cleanup still has an older progress snapshot.
172
+ progress.epochCursor++;
173
+ continue;
174
+ }
175
+ if (previous != null) {
176
+ Authenticator.eraseCounter(previous.value.factorHost, previous.value.factorSecret);
177
+ AuthReads.releaseSnapshot(epochHistoryHandle(), revisionKey, previous);
178
+ }
179
+ // Keep an anonymous owner at every old revision. A delayed claim
180
+ // must not repopulate a released slot with an old sealed factor.
181
+ const erased = new SessionEpoch();
182
+ erased.revision = progress.epochCursor; erased.factorFence = epoch.factorFence;
183
+ erased.deleting = true; erased.deletionGeneration = epoch.deletionGeneration;
184
+ if (!AuthStateDb.epochRevisions.claim(revisionKey, erased).claimed)
185
+ throw new Error('Factor history cleanup conflicted; retry deletion');
186
+ progress.epochCursor++;
187
+ }
188
+ const currentName = acct.googleSubject.length != 0 ? 'google:' + base64UrlEncode(acct.accountId) :
189
+ acct.accountId.length == 0 || acct.legacyFactors ? acct.username : acct.username + '\x00' + crypto.toHex(acct.accountId);
190
+ while (progress.factorPhase < 2) {
191
+ const name = progress.factorPhase == 0 ? currentName : acct.username;
192
+ if (progress.factorPhase == 1 && name == currentName) { progress.factorPhase++; continue; }
193
+ const factorKey = new FactorKey(key.host, name);
194
+ if (!progress.factorPrepared) {
195
+ if (!progress.factorDiscovering) {
196
+ const head = AuthStateDb.factorHeads.getCurrentSnapshot(factorKey);
197
+ if (head == null && Db.lastError() != DbError.None) throw new Error('Factor cleanup unavailable');
198
+ progress.factorMax = head == null ? 0 : head.value.revision;
199
+ progress.factorDiscovering = true;
200
+ }
201
+ // Discover unpublished legacy revisions in bounded slices too.
202
+ while (true) {
203
+ const budget = Db.budget();
204
+ if (budget.remainingOps < 28 || budget.remainingWrites < 20 || steps++ >= 128) {
205
+ if (!AuthDb.deletedAccounts.compareExchangeSnapshot(markerKey, marker, progress))
206
+ throw new Error('Account cleanup conflicted; retry');
207
+ throw new Error('Account cleanup incomplete; retry deletion');
208
+ }
209
+ if (progress.factorMax == u64.MAX_VALUE) throw new Error('Factor revision exhausted');
210
+ const next = AuthReads.owner(AuthStateDb.factorRevisions,
211
+ new FactorRevision(key.host, name, progress.factorMax + 1));
212
+ if (next == null) break;
213
+ progress.factorMax++;
214
+ }
215
+ progress.factorPrepared = true;
216
+ // Save the bound before deleting the head that supplied it.
217
+ if (!AuthDb.deletedAccounts.compareExchangeSnapshot(markerKey, marker, progress))
218
+ throw new Error('Account cleanup conflicted; retry');
219
+ marker = new DocumentSnapshot<DeletedAccountMarker>(progress, progress.encode());
220
+
221
+ }
222
+ const remainingHead = AuthStateDb.factorHeads.getCurrentSnapshot(factorKey);
223
+ if (remainingHead == null && Db.lastError() != DbError.None) throw new Error('Factor cleanup unavailable');
224
+ if (remainingHead != null) {
225
+ Authenticator.eraseCounter(key.host, remainingHead.value.encryptedSecret);
226
+ AuthStateDb.factorHeads.delete(factorKey);
227
+ }
228
+ while (progress.factorCursor <= progress.factorMax) {
229
+ const budget = Db.budget();
230
+ if (budget.remainingOps < 28 || budget.remainingWrites < 20 || steps++ >= 128) {
231
+ if (!AuthDb.deletedAccounts.compareExchangeSnapshot(markerKey, marker, progress))
232
+ throw new Error('Account cleanup conflicted; retry');
233
+ throw new Error('Account cleanup incomplete; retry deletion');
234
+ }
235
+ const revisionKey = new FactorRevision(key.host, name, progress.factorCursor);
236
+ const previous = AuthReads.ownerSnapshot<FactorRevision, FactorSettings>(factorHistoryHandle(), revisionKey);
237
+ if (previous != null) {
238
+ Authenticator.eraseCounter(key.host, previous.value.encryptedSecret);
239
+ AuthReads.releaseSnapshot(factorHistoryHandle(), revisionKey, previous);
240
+ }
241
+ progress.factorCursor++;
242
+ }
243
+ progress.factorPhase++; progress.factorPrepared = false; progress.factorDiscovering = false;
244
+ progress.factorCursor = 1; progress.factorMax = 0;
245
+ }
246
+ progress.factorsErased = true;
247
+ if (!AuthDb.deletedAccounts.compareExchangeSnapshot(markerKey, marker, progress))
248
+ throw new Error('Account cleanup conflicted; retry');
249
+ }
131
250
  static finishDeletion(key: Username, observed: DocumentSnapshot<AuthAccount>, uid: Uint8Array): bool {
132
251
  const acct = observed.value;
133
252
  if (!acct.deleting) return false;
@@ -141,6 +260,7 @@ export class AuthMaintenance {
141
260
  if (legacy == null) throw new Error('Legacy deletion state temporarily unavailable');
142
261
  }
143
262
  }
263
+ AuthMaintenance.eraseFactors(key, acct, uid, deletedKey);
144
264
  const emailKey = new EmailKey(key.host, acct.email);
145
265
  const email = AuthDb.emails.getCurrentSnapshot(emailKey);
146
266
  if (email == null && Db.lastError() != DbError.None) throw new Error('Email index temporarily unavailable');
@@ -155,6 +275,9 @@ export class AuthMaintenance {
155
275
  const reset = AuthDb.resetTokenOf.getDelete(secondary);
156
276
  if (reset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
157
277
  if (reset != null) AuthDb.resetTokens.delete(reset);
278
+ const pendingFactor = AuthDb.twoFaSetup.getCurrentSnapshot(secondary);
279
+ if (pendingFactor == null && Db.lastError() != DbError.None) throw new Error('Factor setup cleanup unavailable');
280
+ if (pendingFactor != null) Authenticator.eraseCounter(key.host, pendingFactor.value.encryptedSecret);
158
281
  AuthDb.twoFaSetup.delete(secondary);
159
282
  // Pre-incarnation heads use the plain username. New accounts never use
160
283
  // these keys, so cleaning them cannot touch a later registration.
@@ -165,6 +288,9 @@ export class AuthMaintenance {
165
288
  const legacyReset = AuthDb.resetTokenOf.getDelete(legacy);
166
289
  if (legacyReset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
167
290
  if (legacyReset != null) AuthDb.resetTokens.delete(legacyReset);
291
+ const legacyFactor = AuthDb.twoFaSetup.getCurrentSnapshot(legacy);
292
+ if (legacyFactor == null && Db.lastError() != DbError.None) throw new Error('Legacy factor cleanup unavailable');
293
+ if (legacyFactor != null) Authenticator.eraseCounter(key.host, legacyFactor.value.encryptedSecret);
168
294
  AuthDb.twoFaSetup.delete(legacy);
169
295
  // Security epochs intentionally remain so copied cookies and in-flight
170
296
  // logins cannot become valid when the same identity signs up again.
@@ -1,5 +1,24 @@
1
+ import { toildbHost } from 'bindings/toildb';
1
2
  /** An unavailable security record must never be mistaken for an absent restriction. */
2
3
  export class AuthReads {
4
+ /** Keep original owner bytes: append-only schema decoding can otherwise
5
+ * re-encode an old claim differently and make its release fail forever. */
6
+ public static ownerSnapshot<K, V>(handle: u32, key: K): DocumentSnapshot<V> | null {
7
+ const encodedKey = key.encode();
8
+ const size = toildbHost.uniqueLookup(handle, encodedKey.dataStart, encodedKey.length);
9
+ if (size == -2) return null;
10
+ if (size < 0) throw new Error('Authentication history unavailable (status ' + size.toString() + ')');
11
+ const encoded = new Uint8Array(size);
12
+ if (toildbHost.takeResult(encoded.dataStart, size) != size) throw new Error('Authentication history read failed');
13
+ const value = instantiate<V>(); value.decodeInto(encoded);
14
+ return new DocumentSnapshot<V>(value, encoded);
15
+ }
16
+ public static releaseSnapshot<K, V>(handle: u32, key: K, observed: DocumentSnapshot<V>): void {
17
+ const encodedKey = key.encode(), encoded = observed.encoded;
18
+ const status = toildbHost.uniqueRelease(handle, encodedKey.dataStart, encodedKey.length,
19
+ encoded.dataStart, encoded.length, 0);
20
+ if (status < 0) throw new Error('Authentication history release failed (status ' + status.toString() + ')');
21
+ }
3
22
  public static document<K, V>(collection: Documents<K, V>, key: K): V | null {
4
23
  const value = collection.get(key);
5
24
  if (value == null && Db.lastError() != DbError.None)
@@ -20,6 +20,10 @@ export class SessionEpoch {
20
20
  factorMethod: u8 = 0;
21
21
  factorRevision: u64 = 0;
22
22
  factorSecret: Uint8Array = new Uint8Array(0);
23
+ // Append-only deletion fence; retained across account recreation.
24
+ factorFence: u64 = 0;
25
+ deleting: bool = false;
26
+ deletionGeneration: u64 = 0;
23
27
  }
24
28
  @data
25
29
  export class FactorKey {
@@ -152,6 +152,13 @@ export class DeletedAccountKey {
152
152
  @data
153
153
  export class DeletedAccountMarker {
154
154
  deleted: bool = true;
155
+ epochCursor: u64 = 1;
156
+ factorPhase: u8 = 0;
157
+ factorCursor: u64 = 1;
158
+ factorMax: u64 = 0;
159
+ factorPrepared: bool = false;
160
+ factorDiscovering: bool = false;
161
+ factorsErased: bool = false;
155
162
  }
156
163
 
157
164
  @database
@@ -71,6 +71,12 @@ export class Authenticator {
71
71
  // An authenticated, randomized 256-bit ciphertext prefix identifies the enrollment.
72
72
  // No extra hash or per-verification token row is needed.
73
73
 
74
+ /** Idempotent erasure of an enrollment's replay counter. */
75
+ static eraseCounter(host: string, sealed: Uint8Array): void {
76
+ if (sealed.length != 48) return;
77
+ AuthStateDb.totpCounters.delete(new FactorKey(host, base64UrlEncode(sealed.subarray(12, 44))));
78
+ }
79
+
74
80
  /** Fresh randomized enrollment ciphertext: reserve its first step without a preceding read. */
75
81
  static initialize(host: string, sealed: Uint8Array, step: u64): bool {
76
82
  if (step == 0) return false;
@@ -72,13 +72,16 @@ export class SessionEpochs {
72
72
  next.factorHost = epoch.factorHost; next.factorName = epoch.factorName;
73
73
  next.factorMethod = epoch.factorMethod; next.factorRevision = epoch.factorRevision;
74
74
  next.factorSecret = epoch.factorSecret;
75
+ next.factorFence = epoch.factorFence; next.deleting = epoch.deleting;
76
+ next.deletionGeneration = epoch.deletionGeneration;
75
77
  return next;
76
78
  }
77
79
  /** One unique claim commits the factor policy AND invalidates every earlier session. */
78
80
  public static changeFactor(id: string, verified: SessionEpoch, host: string, name: string,
79
81
  expected: u64, method: u8, secret: Uint8Array): bool {
80
- let epoch = verified;
82
+ let epoch = SessionEpochs.read(id);
81
83
  for (let attempt = 0; attempt < 3; attempt++) {
84
+ if (epoch.deleting || epoch.factorFence != verified.factorFence) return false;
82
85
  if (epoch.factorHost == host && epoch.factorName == name && epoch.factorRevision != expected) return false;
83
86
  if (expected == u64.MAX_VALUE) throw new Error('Factor revision exhausted');
84
87
  const next = SessionEpochs.successor(epoch);
@@ -89,6 +92,46 @@ export class SessionEpochs {
89
92
  }
90
93
  throw new Error('Factor change conflicted; retry');
91
94
  }
95
+ /** Commit an empty factor policy before erasing history. A competing factor
96
+ * claim either precedes this fence (and is erased) or observes the fence. */
97
+ public static beginDeletion(id: string, host: string): SessionEpoch {
98
+ for (let attempt = 0; attempt < 3; attempt++) {
99
+ const epoch = SessionEpochs.read(id, host);
100
+ if (epoch.deleting) { SessionEpochs.publishDeletion(id, host, epoch); return epoch; }
101
+ const next = new SessionEpoch();
102
+ if (epoch.revision == u64.MAX_VALUE || epoch.factorFence == u64.MAX_VALUE)
103
+ throw new Error('Session generation exhausted');
104
+ next.revision = epoch.revision + 1;
105
+ next.factorFence = epoch.factorFence + 1;
106
+ next.deleting = true; next.deletionGeneration = epoch.revision;
107
+ next.claimNonce = new Uint8Array(16); crypto.getRandomValues(next.claimNonce);
108
+ if (!AuthStateDb.epochRevisions.claim(new SessionEpochKey('3:' + host + '\x00' + id, next.revision), next).claimed) continue;
109
+ SessionEpochs.publishDeletion(id, host, next);
110
+ return next;
111
+ }
112
+ throw new Error('Account deletion conflicted; retry');
113
+ }
114
+ private static publishDeletion(id: string, host: string, epoch: SessionEpoch): void {
115
+ const key = new SessionUserKey('3:' + host + '\x00' + id);
116
+ for (let i = 0; i < 3; i++) {
117
+ const head = AuthStateDb.epochHeads.getCurrentSnapshot(key);
118
+ if (head == null && Db.lastError() != DbError.None) throw new Error('Session state unavailable');
119
+ if (head != null && head.value.revision >= epoch.revision) return;
120
+ if (AuthStateDb.epochHeads.compareExchangeSnapshot(key, head, epoch)) return;
121
+ }
122
+ throw new Error('Session cleanup head conflicted; retry');
123
+ }
124
+ /** A new incarnation keeps the deletion fence but cannot accept old cookies. */
125
+ public static activate(id: string, host: string): void {
126
+ for (let attempt = 0; attempt < 3; attempt++) {
127
+ const epoch = SessionEpochs.read(id, host);
128
+ if (!epoch.deleting) return;
129
+ const next = SessionEpochs.successor(epoch);
130
+ next.deleting = false; next.deletionGeneration = 0;
131
+ if (AuthStateDb.epochRevisions.claim(new SessionEpochKey('3:' + host + '\x00' + id, next.revision), next).claimed) return;
132
+ }
133
+ throw new Error('Account activation conflicted; retry');
134
+ }
92
135
  /** The stable 32-byte user id as hex; no request or @user encoder needed. */
93
136
  public static revokeId(id: string, host: string = AuthRealm.current()): void {
94
137
  if (id.length != 64) throw new Error('Invalid session identity');
@@ -20,6 +20,7 @@ import { HmacImportParams, HmacParams, ALG_SHA_256, FMT_RAW, USAGE_SIGN, USAGE_V
20
20
  import {
21
21
  Server,
22
22
  Request,
23
+ Method,
23
24
  SecureCookies,
24
25
  Cookie,
25
26
  SameSite,
@@ -377,9 +378,13 @@ export namespace AuthService {
377
378
  if (Time.nowSeconds() >= exp) return null; // expired
378
379
  const epochId = SessionEpochs.key(userBytes);
379
380
  const state = SessionEpochs.read(epochId);
380
- if (state.revision != generation) return null;
381
+ if (state.deleting) {
382
+ // Only the session generation that authorized deletion can resume
383
+ // cleanup, only on this endpoint, while that incarnation is fenced.
384
+ if (req.method != Method.POST || req.path != '/auth/delete' || generation != state.deletionGeneration) return null;
385
+ } else if (state.revision != generation) return null;
381
386
  // Ordinary accounts avoid serialization; factors reuse the verified request snapshot.
382
- req.__authEpochData = state.factorName.length == 0 ? null : state.encode();
387
+ req.__authEpochData = state.factorName.length == 0 && state.factorFence == 0 ? null : state.encode();
383
388
 
384
389
  req.__authExpires = exp;
385
390
  req.__authGeneration = generation;
@@ -48,6 +48,8 @@ export enum RateLimit {
48
48
  FixedWindow = 0,
49
49
  SlidingWindow = 1,
50
50
  TokenBucket = 2,
51
+ /** Exact trailing interval (now - window, now], storing accepted timestamps. */
52
+ TrailingWindow = 3,
51
53
  }
52
54
 
53
55
  export namespace RateLimitService {