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,177 @@
|
|
|
1
|
+
import { AuthDb, AuthAccount, Username, EmailKey, DeletedAccountKey, DeletedAccountMarker,
|
|
2
|
+
AuthUserKey, AuthUserAccount, AuthUserAccounts } from './AuthStore';
|
|
3
|
+
import { SessionEpochs } from './SessionEpochs';
|
|
4
|
+
|
|
5
|
+
function sameBytes(a: Uint8Array, b: Uint8Array): bool {
|
|
6
|
+
if (a.length != b.length) return false;
|
|
7
|
+
let different: i32 = 0;
|
|
8
|
+
for (let i = 0; i < a.length; i++) different |= a[i] ^ b[i];
|
|
9
|
+
return different == 0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Shared request/daemon account lifecycle. Storage types keep their original
|
|
13
|
+
* names and field order when moved out of the REST-only entry. */
|
|
14
|
+
export class AuthMaintenance {
|
|
15
|
+
static incarnation(acct: AuthAccount): Uint8Array {
|
|
16
|
+
return acct.accountId.length != 0 ? acct.accountId :
|
|
17
|
+
crypto.sha256Text(crypto.toHex(acct.salt) + ':' + crypto.toHex(acct.publicKey));
|
|
18
|
+
}
|
|
19
|
+
static wasDeleted(host: string, acct: AuthAccount): bool {
|
|
20
|
+
const marker = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, crypto.toHex(AuthMaintenance.incarnation(acct))));
|
|
21
|
+
if (marker == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
|
|
22
|
+
if (marker != null) return true;
|
|
23
|
+
if (acct.accountId.length == 0 || acct.legacyFactors) {
|
|
24
|
+
const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt))));
|
|
25
|
+
if (legacy == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
|
|
26
|
+
return legacy != null;
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
static index(host: string, acct: AuthAccount): void {
|
|
31
|
+
if (acct.toilUserId.length != 32) throw new Error('Invalid account identity');
|
|
32
|
+
const key = new AuthUserKey(crypto.toHex(acct.toilUserId));
|
|
33
|
+
const incarnation = AuthMaintenance.incarnation(acct);
|
|
34
|
+
for (let attempt: i32 = 0; attempt < 4; attempt++) {
|
|
35
|
+
const observed = AuthDb.userAccounts.getCurrentSnapshot(key);
|
|
36
|
+
if (observed == null && Db.lastError() != DbError.None) throw new Error('Account index unavailable');
|
|
37
|
+
const next = observed == null ? new AuthUserAccounts() : observed.value;
|
|
38
|
+
let found = false;
|
|
39
|
+
for (let i = 0; i < next.accounts.length; i++) {
|
|
40
|
+
const owner = next.accounts[i];
|
|
41
|
+
if (owner.host != host || owner.username != acct.username) continue;
|
|
42
|
+
if (sameBytes(owner.accountId, incarnation)) return;
|
|
43
|
+
// Replacing an index pointer needs proof that its incarnation
|
|
44
|
+
// no longer owns the authoritative account row.
|
|
45
|
+
const current = AuthDb.accounts.getCurrentSnapshot(new Username(host, acct.username));
|
|
46
|
+
if (current == null && Db.lastError() != DbError.None) throw new Error('Account owner unavailable');
|
|
47
|
+
if (current == null || !sameBytes(AuthMaintenance.incarnation(current.value), incarnation))
|
|
48
|
+
throw new Error('Account index changed; retry');
|
|
49
|
+
next.accounts[i] = new AuthUserAccount(host, acct.username, incarnation);
|
|
50
|
+
found = true;
|
|
51
|
+
}
|
|
52
|
+
if (!found) {
|
|
53
|
+
if (next.accounts.length >= 16) throw new Error('Account identity has too many realms');
|
|
54
|
+
next.accounts.push(new AuthUserAccount(host, acct.username, incarnation));
|
|
55
|
+
}
|
|
56
|
+
if (AuthDb.userAccounts.compareExchangeSnapshot(key, observed, next)) return;
|
|
57
|
+
}
|
|
58
|
+
throw new Error('Account index conflicted; retry');
|
|
59
|
+
}
|
|
60
|
+
static deleteUser(id: ToilUserId, realm: string): bool {
|
|
61
|
+
const uid = id.toBytes();
|
|
62
|
+
const index = AuthDb.userAccounts.getCurrentSnapshot(new AuthUserKey(crypto.toHex(uid)));
|
|
63
|
+
if (index == null) {
|
|
64
|
+
if (Db.lastError() != DbError.None) throw new Error('Account index unavailable');
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
let selected: AuthUserAccount | null = null;
|
|
68
|
+
for (let i = 0; i < index.value.accounts.length; i++) {
|
|
69
|
+
const owner = index.value.accounts[i];
|
|
70
|
+
if (realm.length != 0 && owner.host != realm) continue;
|
|
71
|
+
if (selected != null) throw new Error('Ambiguous account realm; pass its normalized realm');
|
|
72
|
+
selected = owner;
|
|
73
|
+
}
|
|
74
|
+
if (selected == null) return false;
|
|
75
|
+
const key = new Username(selected.host, selected.username);
|
|
76
|
+
let observed = AuthDb.accounts.getCurrentSnapshot(key);
|
|
77
|
+
if (observed == null) {
|
|
78
|
+
if (Db.lastError() != DbError.None) throw new Error('Account unavailable');
|
|
79
|
+
AuthMaintenance.unindex(uid, selected.host, selected.username, selected.accountId);
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (!sameBytes(observed.value.toilUserId, uid) ||
|
|
83
|
+
!sameBytes(AuthMaintenance.incarnation(observed.value), selected.accountId)) {
|
|
84
|
+
AuthMaintenance.unindex(uid, selected.host, selected.username, selected.accountId);
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
if (!observed.value.deleting) {
|
|
88
|
+
observed.value.deleting = true;
|
|
89
|
+
if (!AuthDb.accounts.compareExchangeSnapshot(key, observed, observed.value)) throw new Error('Account changed; retry deletion');
|
|
90
|
+
observed = new DocumentSnapshot<AuthAccount>(observed.value, observed.value.encode());
|
|
91
|
+
}
|
|
92
|
+
if (!AuthMaintenance.finishDeletion(key, observed, uid)) throw new Error('Account changed; retry deletion');
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
private static unindex(uid: Uint8Array, host: string, username: string, incarnation: Uint8Array): void {
|
|
96
|
+
const key = new AuthUserKey(crypto.toHex(uid));
|
|
97
|
+
for (let attempt: i32 = 0; attempt < 4; attempt++) {
|
|
98
|
+
const observed = AuthDb.userAccounts.getCurrentSnapshot(key);
|
|
99
|
+
if (observed == null) {
|
|
100
|
+
if (Db.lastError() != DbError.None) throw new Error('Account index unavailable');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const next = new AuthUserAccounts();
|
|
104
|
+
for (let i = 0; i < observed.value.accounts.length; i++) {
|
|
105
|
+
const owner = observed.value.accounts[i];
|
|
106
|
+
if (owner.host != host || owner.username != username || !sameBytes(owner.accountId, incarnation)) next.accounts.push(owner);
|
|
107
|
+
}
|
|
108
|
+
if (next.accounts.length == observed.value.accounts.length) return;
|
|
109
|
+
if (next.accounts.length == 0 ? AuthDb.userAccounts.compareDeleteSnapshot(key, observed) :
|
|
110
|
+
AuthDb.userAccounts.compareExchangeSnapshot(key, observed, next)) return;
|
|
111
|
+
}
|
|
112
|
+
throw new Error('Account index cleanup conflicted; retry');
|
|
113
|
+
}
|
|
114
|
+
static indexUsers(limit: i32, cursor: Uint8Array | null): Uint8Array | null {
|
|
115
|
+
if (limit < 1 || limit > 8) throw new Error('indexUsers limit must be 1..8');
|
|
116
|
+
const page = AuthDb.accounts.scan(limit, cursor);
|
|
117
|
+
for (let i = 0; i < page.entries.length; i++) {
|
|
118
|
+
const entry = page.entries[i];
|
|
119
|
+
const account = entry.value;
|
|
120
|
+
if (account.deleting || account.registering || AuthMaintenance.wasDeleted(entry.key.host, account)) continue;
|
|
121
|
+
if (account.toilUserId.length == 0) {
|
|
122
|
+
const domain = Environment.getSecure('TOIL_AUTH_DOMAIN');
|
|
123
|
+
if (domain == null || domain.length == 0) throw new Error('Legacy identity backfill requires the original TOIL_AUTH_DOMAIN');
|
|
124
|
+
account.toilUserId = ToilUserId.derive(account.publicKey, account.username, domain).toBytes();
|
|
125
|
+
if (!AuthDb.accounts.compareExchangeSnapshot(entry.key, entry.snapshot, account)) throw new Error('Account changed during backfill; retry this page');
|
|
126
|
+
}
|
|
127
|
+
AuthMaintenance.index(entry.key.host, account);
|
|
128
|
+
}
|
|
129
|
+
return page.cursor;
|
|
130
|
+
}
|
|
131
|
+
static finishDeletion(key: Username, observed: DocumentSnapshot<AuthAccount>, uid: Uint8Array): bool {
|
|
132
|
+
const acct = observed.value;
|
|
133
|
+
if (!acct.deleting) return false;
|
|
134
|
+
const deletedKey = new DeletedAccountKey(key.host, crypto.toHex(AuthMaintenance.incarnation(acct)));
|
|
135
|
+
if (!AuthDb.deletedAccounts.compareExchange(deletedKey, null, new DeletedAccountMarker()) && !AuthMaintenance.wasDeleted(key.host, acct))
|
|
136
|
+
throw new Error('Account deletion state temporarily unavailable');
|
|
137
|
+
if (acct.accountId.length == 0 || acct.legacyFactors) {
|
|
138
|
+
const legacyKey = new DeletedAccountKey(key.host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt)));
|
|
139
|
+
if (!AuthDb.deletedAccounts.compareExchange(legacyKey, null, new DeletedAccountMarker())) {
|
|
140
|
+
const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(legacyKey);
|
|
141
|
+
if (legacy == null) throw new Error('Legacy deletion state temporarily unavailable');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const emailKey = new EmailKey(key.host, acct.email);
|
|
145
|
+
const email = AuthDb.emails.getCurrentSnapshot(emailKey);
|
|
146
|
+
if (email == null && Db.lastError() != DbError.None) throw new Error('Email index temporarily unavailable');
|
|
147
|
+
if (email != null && email.value.username == acct.username &&
|
|
148
|
+
(email.value.accountId.length == 0 || sameBytes(email.value.accountId, AuthMaintenance.incarnation(acct)))) {
|
|
149
|
+
AuthDb.emails.compareDeleteSnapshot(emailKey, email);
|
|
150
|
+
}
|
|
151
|
+
const secondary = new Username(key.host, acct.username + '\x00' + crypto.toHex(AuthMaintenance.incarnation(acct)));
|
|
152
|
+
const confirm = AuthDb.confirmTokenOf.getDelete(secondary);
|
|
153
|
+
if (confirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
|
|
154
|
+
if (confirm != null) AuthDb.confirmTokens.delete(confirm);
|
|
155
|
+
const reset = AuthDb.resetTokenOf.getDelete(secondary);
|
|
156
|
+
if (reset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
|
|
157
|
+
if (reset != null) AuthDb.resetTokens.delete(reset);
|
|
158
|
+
AuthDb.twoFaSetup.delete(secondary);
|
|
159
|
+
// Pre-incarnation heads use the plain username. New accounts never use
|
|
160
|
+
// these keys, so cleaning them cannot touch a later registration.
|
|
161
|
+
const legacy = new Username(key.host, acct.username);
|
|
162
|
+
const legacyConfirm = AuthDb.confirmTokenOf.getDelete(legacy);
|
|
163
|
+
if (legacyConfirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
|
|
164
|
+
if (legacyConfirm != null) AuthDb.confirmTokens.delete(legacyConfirm);
|
|
165
|
+
const legacyReset = AuthDb.resetTokenOf.getDelete(legacy);
|
|
166
|
+
if (legacyReset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
|
|
167
|
+
if (legacyReset != null) AuthDb.resetTokens.delete(legacyReset);
|
|
168
|
+
AuthDb.twoFaSetup.delete(legacy);
|
|
169
|
+
// Security epochs intentionally remain so copied cookies and in-flight
|
|
170
|
+
// logins cannot become valid when the same identity signs up again.
|
|
171
|
+
SessionEpochs.revokeId(crypto.toHex(uid));
|
|
172
|
+
if (!AuthDb.accounts.compareDeleteSnapshot(key, observed)) return false;
|
|
173
|
+
AuthMaintenance.unindex(uid, key.host, acct.username, AuthMaintenance.incarnation(acct));
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
AuthService.__installMaintenance(AuthMaintenance.deleteUser, AuthMaintenance.indexUsers);
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Every lookup KEY carries the tenant `host` (realm) as its FIRST field, so the
|
|
2
|
+
// physical key includes the domain and the SAME logical name/email/id addresses a
|
|
3
|
+
// DIFFERENT row per host (cross-domain isolation, on top of toildb's per-tenant
|
|
4
|
+
// scoping). `host` is populated from `realm(ctx)` at every call site.
|
|
5
|
+
@data
|
|
6
|
+
export class Username {
|
|
7
|
+
host: string = '';
|
|
8
|
+
name: string = '';
|
|
9
|
+
constructor(host: string = '', name: string = '') {
|
|
10
|
+
this.host = host;
|
|
11
|
+
this.name = name;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
@data
|
|
16
|
+
export class EmailKey {
|
|
17
|
+
host: string = '';
|
|
18
|
+
email: string = '';
|
|
19
|
+
constructor(host: string = '', email: string = '') {
|
|
20
|
+
this.host = host;
|
|
21
|
+
this.email = email;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@data
|
|
26
|
+
export class EmailOwner {
|
|
27
|
+
username: string = '';
|
|
28
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
29
|
+
constructor(username: string = '', accountId: Uint8Array = new Uint8Array(0)) {
|
|
30
|
+
this.username = username;
|
|
31
|
+
this.accountId = accountId;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
@data
|
|
36
|
+
export class TokenId {
|
|
37
|
+
hash: Uint8Array = new Uint8Array(0);
|
|
38
|
+
constructor(hash: Uint8Array = new Uint8Array(0)) {
|
|
39
|
+
this.hash = hash;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A one-time confirm/reset token record: which account it authorizes + its
|
|
44
|
+
* absolute expiry (unix secs). Consumed with `getDelete`. */
|
|
45
|
+
@data
|
|
46
|
+
export class TokenRec {
|
|
47
|
+
username: string = '';
|
|
48
|
+
exp: u64 = 0;
|
|
49
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
@data
|
|
53
|
+
export class ChallengeId {
|
|
54
|
+
host: string = '';
|
|
55
|
+
cid: Uint8Array = new Uint8Array(0);
|
|
56
|
+
constructor(host: string = '', cid: Uint8Array = new Uint8Array(0)) {
|
|
57
|
+
this.host = host;
|
|
58
|
+
this.cid = cid;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
@data
|
|
63
|
+
export class AuthAccount {
|
|
64
|
+
// The original credential fields keep their byte positions; `email` +
|
|
65
|
+
// `emailConfirmed` are APPENDED so this is a forward-compatible, append-only
|
|
66
|
+
// @data change (an old row decodes with emailConfirmed=false, the strict/safe
|
|
67
|
+
// default) rather than a breaking mid-struct reorder the deploy gate rejects.
|
|
68
|
+
username: string = '';
|
|
69
|
+
salt: Uint8Array = new Uint8Array(0);
|
|
70
|
+
publicKey: Uint8Array = new Uint8Array(0);
|
|
71
|
+
memKiB: u32 = 0;
|
|
72
|
+
iterations: u32 = 0;
|
|
73
|
+
parallelism: u32 = 0;
|
|
74
|
+
email: string = '';
|
|
75
|
+
emailConfirmed: bool = false;
|
|
76
|
+
// APPENDED (append-only, forward-compatible like `email` above): the account's
|
|
77
|
+
// second-factor method (see the TWOFA_* enum). An old row decodes as 0 =
|
|
78
|
+
// TWOFA_NONE (2FA off), the safe default, so existing accounts stay logged in
|
|
79
|
+
// by password alone until they opt in via /auth/2fa/setup.
|
|
80
|
+
twoFactorMethod: u8 = 0;
|
|
81
|
+
// Append-only: the STABLE ToilUserId, derived once at registration. Reset rotates
|
|
82
|
+
// publicKey but leaves this, so the id is stable across a reset.
|
|
83
|
+
toilUserId: Uint8Array = new Uint8Array(0);
|
|
84
|
+
// Account incarnation: never reused, even when username/password are reused.
|
|
85
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
86
|
+
deleting: bool = false;
|
|
87
|
+
registering: bool = false;
|
|
88
|
+
legacyFactors: bool = false;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
@data
|
|
92
|
+
export class Challenge {
|
|
93
|
+
cid: Uint8Array = new Uint8Array(0);
|
|
94
|
+
username: string = '';
|
|
95
|
+
nonce: Uint8Array = new Uint8Array(0);
|
|
96
|
+
iat: u64 = 0;
|
|
97
|
+
exp: u64 = 0;
|
|
98
|
+
sessionEpoch: u64 = 0;
|
|
99
|
+
sessionVersion: u8 = 0;
|
|
100
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The lookup key for a login 2FA challenge: 16 random bytes minted per login.
|
|
104
|
+
* Lives in its OWN collection (twoFaLogins), a SEPARATE NAMESPACE from
|
|
105
|
+
* confirm/reset TokenId, so a confirm/reset token can never resolve here. */
|
|
106
|
+
@data
|
|
107
|
+
export class TwoFaId {
|
|
108
|
+
host: string = '';
|
|
109
|
+
id: Uint8Array = new Uint8Array(0);
|
|
110
|
+
constructor(host: string = '', id: Uint8Array = new Uint8Array(0)) {
|
|
111
|
+
this.host = host;
|
|
112
|
+
this.id = id;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A pending second-factor challenge (login OR setup). METHOD-AGNOSTIC lifecycle
|
|
118
|
+
* fields (username / exp / attempts) plus the per-method `codeHash`; `method` is
|
|
119
|
+
* which factor was delivered and `targetMethod` is used ONLY by the setup flow
|
|
120
|
+
* (what to set `account.twoFactorMethod` to on success). Login challenges leave
|
|
121
|
+
* `targetMethod` at 0. `codeHash = SHA-256(username || 0x00 || code)`; the
|
|
122
|
+
* plaintext code is never stored.
|
|
123
|
+
*/
|
|
124
|
+
@data
|
|
125
|
+
export class TwoFaChallenge {
|
|
126
|
+
username: string = '';
|
|
127
|
+
method: u8 = 0;
|
|
128
|
+
codeHash: Uint8Array = new Uint8Array(0);
|
|
129
|
+
exp: u64 = 0;
|
|
130
|
+
attempts: u32 = 0;
|
|
131
|
+
targetMethod: u8 = 0;
|
|
132
|
+
sessionEpoch: u64 = 0;
|
|
133
|
+
sessionVersion: u8 = 0;
|
|
134
|
+
settingsRevision: u64 = 0;
|
|
135
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
@data
|
|
139
|
+
export class DeletedAccountKey {
|
|
140
|
+
host: string = '';
|
|
141
|
+
incarnation: string = '';
|
|
142
|
+
constructor(host: string = '', incarnation: string = '') {
|
|
143
|
+
this.host = host;
|
|
144
|
+
this.incarnation = incarnation;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
@data
|
|
149
|
+
export class DeletedAccountMarker {
|
|
150
|
+
deleted: bool = true;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
@database
|
|
154
|
+
export class AuthDb {
|
|
155
|
+
@collection static userAccounts: Documents<AuthUserKey, AuthUserAccounts>;
|
|
156
|
+
@collection static accounts: Documents<Username, AuthAccount>;
|
|
157
|
+
// Permanent opaque incarnation guards prevent a late replica/snapshot replay
|
|
158
|
+
// of an old account row from enabling that deleted account again.
|
|
159
|
+
@collection static deletedAccounts: Documents<DeletedAccountKey, DeletedAccountMarker>;
|
|
160
|
+
@collection static emails: Documents<EmailKey, EmailOwner>; // email -> username (uniqueness index)
|
|
161
|
+
@collection static challenges: Documents<ChallengeId, Challenge>;
|
|
162
|
+
@collection static confirmTokens: Documents<TokenId, TokenRec>;
|
|
163
|
+
@collection static resetTokens: Documents<TokenId, TokenRec>;
|
|
164
|
+
// username -> its CURRENT outstanding confirm/reset token id, so minting a new
|
|
165
|
+
// one can invalidate the previous: outstanding tokens stay bounded at one per
|
|
166
|
+
// user per kind (O(users)), not one per request (unbounded storage-griefing).
|
|
167
|
+
@collection static confirmTokenOf: Documents<Username, TokenId>;
|
|
168
|
+
@collection static resetTokenOf: Documents<Username, TokenId>;
|
|
169
|
+
// SECOND-FACTOR challenges live in their OWN collections, a namespace fully
|
|
170
|
+
// disjoint from confirm/reset tokens (above). A reset/confirm token looked up
|
|
171
|
+
// here finds nothing (wrong collection); a 2FA code/id looked up in the token
|
|
172
|
+
// collections finds nothing. The separation is STRUCTURAL, not a purpose
|
|
173
|
+
// string. `twoFaLogins` is keyed by a random per-login id; `twoFaSetup` is
|
|
174
|
+
// keyed by username = one outstanding setup challenge per user.
|
|
175
|
+
@collection static twoFaLogins: Documents<TwoFaId, TwoFaChallenge>;
|
|
176
|
+
@collection static twoFaSetup: Documents<Username, TwoFaChallenge>;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
@data
|
|
180
|
+
export class AuthUserKey {
|
|
181
|
+
id: string = '';
|
|
182
|
+
constructor(id: string = '') { this.id = id; }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
@data
|
|
186
|
+
export class AuthUserAccount {
|
|
187
|
+
host: string = '';
|
|
188
|
+
username: string = '';
|
|
189
|
+
accountId: Uint8Array = new Uint8Array(0);
|
|
190
|
+
constructor(host: string = '', username: string = '', accountId: Uint8Array = new Uint8Array(0)) {
|
|
191
|
+
this.host = host; this.username = username; this.accountId = accountId;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
@data
|
|
196
|
+
export class AuthUserAccounts {
|
|
197
|
+
accounts: AuthUserAccount[] = new Array<AuthUserAccount>();
|
|
198
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AuthReads } from 'toiljs/server/auth/AuthReads';
|
|
2
2
|
import { DataReader } from 'data';
|
|
3
|
+
import { toildbHost } from 'bindings/toildb';
|
|
3
4
|
import { AuthStateDb, SessionUserKey, SessionEpochKey, SessionEpoch } from './AuthStateDb';
|
|
4
5
|
/** Immutable per-user generations fence sessions and in-flight login challenges without clock assumptions. */
|
|
5
6
|
export class SessionEpochs {
|
|
@@ -11,14 +12,30 @@ export class SessionEpochs {
|
|
|
11
12
|
return crypto.toHex(id);
|
|
12
13
|
}
|
|
13
14
|
private static read(id: string): SessionEpoch {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
const key = new SessionUserKey(id);
|
|
16
|
+
const head = AuthStateDb.epochHeads.getCurrentSnapshot(key);
|
|
17
|
+
if (head == null && Db.lastError() != DbError.None)
|
|
18
|
+
throw new Error('Session state unavailable');
|
|
19
|
+
let epoch = head == null ? new SessionEpoch() : head.value;
|
|
20
|
+
const revision = epoch.revision;
|
|
21
|
+
// Leave room for authentication, application work and three revoke attempts.
|
|
22
|
+
// Repair even a partial scan: retries then converge instead of locking a
|
|
23
|
+
// user out forever when more than one chunk of claims lost their head write.
|
|
24
|
+
for (let i: i32 = 0; i < 8; i++) {
|
|
25
|
+
if (epoch.revision == u64.MAX_VALUE) throw new Error('Session generation exhausted');
|
|
17
26
|
const next = AuthReads.owner(AuthStateDb.epochRevisions, new SessionEpochKey(id, epoch.revision + 1));
|
|
18
|
-
if (next == null)
|
|
27
|
+
if (next == null) {
|
|
28
|
+
if (epoch.revision != revision && toildbHost.writeAllowed() == 1)
|
|
29
|
+
AuthStateDb.epochHeads.compareExchangeSnapshot(key, head, epoch);
|
|
30
|
+
return epoch;
|
|
31
|
+
}
|
|
19
32
|
epoch = next;
|
|
20
33
|
}
|
|
21
|
-
|
|
34
|
+
// CAS prevents a delayed repair from overwriting a newer head. Query
|
|
35
|
+
// verification is read-only; sign-in/revocation requests do the repair.
|
|
36
|
+
if (toildbHost.writeAllowed() == 1)
|
|
37
|
+
AuthStateDb.epochHeads.compareExchangeSnapshot(key, head, epoch);
|
|
38
|
+
throw new Error('Session state recovering; retry');
|
|
22
39
|
}
|
|
23
40
|
public static current(userData: Uint8Array): u64 {
|
|
24
41
|
return SessionEpochs.read(SessionEpochs.key(userData)).revision;
|
|
@@ -27,12 +44,24 @@ export class SessionEpochs {
|
|
|
27
44
|
return generation == SessionEpochs.current(userData);
|
|
28
45
|
}
|
|
29
46
|
public static revoke(userData: Uint8Array): void {
|
|
30
|
-
|
|
47
|
+
SessionEpochs.revokeId(SessionEpochs.key(userData));
|
|
48
|
+
}
|
|
49
|
+
/** The stable 32-byte user id as hex; no request or @user encoder needed. */
|
|
50
|
+
public static revokeId(id: string): void {
|
|
51
|
+
if (id.length != 64) throw new Error('Invalid session identity');
|
|
31
52
|
for (let i: i32 = 0; i < 3; i++) {
|
|
32
53
|
const epoch = SessionEpochs.read(id);
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
AuthStateDb.
|
|
54
|
+
const next = new SessionEpoch();
|
|
55
|
+
next.revision = epoch.revision + 1;
|
|
56
|
+
if (!AuthStateDb.epochRevisions.claim(new SessionEpochKey(id, next.revision), next).claimed) continue;
|
|
57
|
+
// The immutable claim is the revocation commit. A concurrent head
|
|
58
|
+
// advance must not be undone by this request's delayed write.
|
|
59
|
+
const key = new SessionUserKey(id);
|
|
60
|
+
const head = AuthStateDb.epochHeads.getCurrentSnapshot(key);
|
|
61
|
+
if (head == null && Db.lastError() != DbError.None)
|
|
62
|
+
throw new Error('Session state unavailable');
|
|
63
|
+
if (head == null || head.value.revision < next.revision)
|
|
64
|
+
AuthStateDb.epochHeads.compareExchangeSnapshot(key, head, next);
|
|
36
65
|
return;
|
|
37
66
|
}
|
|
38
67
|
throw new Error('Session revocation conflicted; retry');
|
package/server/globals/auth.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { AuthReads } from 'toiljs/server/auth/AuthReads';
|
|
|
12
12
|
|
|
13
13
|
import { DataWriter, DataReader } from 'data';
|
|
14
14
|
import { SessionEpochs } from 'toiljs/server/auth/SessionEpochs';
|
|
15
|
+
import { toildbHost } from 'bindings/toildb';
|
|
15
16
|
import { AuthStateDb, SessionDigest, RevokedSession } from 'toiljs/server/auth/AuthStateDb';
|
|
16
17
|
import { HmacImportParams, HmacParams, ALG_SHA_256, FMT_RAW, USAGE_SIGN, USAGE_VERIFY } from 'crypto';
|
|
17
18
|
|
|
@@ -244,7 +245,62 @@ function __reqIsSecure(): bool {
|
|
|
244
245
|
return base != null && base.startsWith('https://');
|
|
245
246
|
}
|
|
246
247
|
|
|
248
|
+
/** Standard identity prefix when a plain compiler entry has no custom @user. */
|
|
249
|
+
@global
|
|
250
|
+
class __ToilBuiltinAuthUser {
|
|
251
|
+
toilUserId: Uint8Array = new Uint8Array(0);
|
|
252
|
+
username: string = '';
|
|
253
|
+
}
|
|
254
|
+
@global
|
|
255
|
+
function __toilDecodeBuiltinAuthUser(bytes: Uint8Array): __ToilBuiltinAuthUser {
|
|
256
|
+
const reader = new DataReader(bytes);
|
|
257
|
+
reader.readU32(); // The signed payload's application-specific @data tag.
|
|
258
|
+
const result = new __ToilBuiltinAuthUser();
|
|
259
|
+
result.toilUserId = reader.readBytes();
|
|
260
|
+
result.username = reader.readString();
|
|
261
|
+
if (!reader.ok || result.toilUserId.length != 32) throw new Error('Invalid session identity');
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
@lazy let __registrationHook: ((id: ToilUserId, username: string, email: string) => void) | null = null;
|
|
266
|
+
@lazy let __deleteUser: ((id: ToilUserId, realm: string) => bool) | null = null;
|
|
267
|
+
@lazy let __indexUsers: ((limit: i32, cursor: Uint8Array | null) => Uint8Array | null) | null = null;
|
|
268
|
+
|
|
247
269
|
export namespace AuthService {
|
|
270
|
+
/** Delete an auth account after app-owned data has been cleaned. Job only.
|
|
271
|
+
* Returns false if absent; concurrent changes throw so the Job can retry. */
|
|
272
|
+
export function deleteUser(id: ToilUserId, realm: string = ''): bool {
|
|
273
|
+
if (toildbHost.jobAllowed() != 1) throw new Error('deleteUser requires a Job');
|
|
274
|
+
const handler = __deleteUser;
|
|
275
|
+
if (handler == null) throw new Error('Built-in auth maintenance is not installed');
|
|
276
|
+
return handler(id, realm);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Bounded legacy-account index backfill. Keep invoking with the returned
|
|
280
|
+
* cursor until null; pages may be empty. Job only. */
|
|
281
|
+
export function indexUsers(limit: i32 = 8, cursor: Uint8Array | null = null): Uint8Array | null {
|
|
282
|
+
if (toildbHost.jobAllowed() != 1) throw new Error('indexUsers requires a Job');
|
|
283
|
+
const handler = __indexUsers;
|
|
284
|
+
if (handler == null) throw new Error('Built-in auth maintenance is not installed');
|
|
285
|
+
return handler(limit, cursor);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function __installMaintenance(remove: (id: ToilUserId, realm: string) => bool,
|
|
289
|
+
index: (limit: i32, cursor: Uint8Array | null) => Uint8Array | null): void {
|
|
290
|
+
__deleteUser = remove; __indexUsers = index;
|
|
291
|
+
}
|
|
292
|
+
/** Register an idempotent initializer in the server entry point. It runs
|
|
293
|
+
* after identity/email reservation and before the account becomes active.
|
|
294
|
+
* A trapped initializer leaves registration pending for a verified retry. */
|
|
295
|
+
export function onRegistered(handler: (id: ToilUserId, username: string, email: string) => void): void {
|
|
296
|
+
__registrationHook = handler;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Framework registration seam; applications register with onRegistered. */
|
|
300
|
+
export function __initializeRegistration(id: ToilUserId, username: string, email: string): void {
|
|
301
|
+
const hook = __registrationHook;
|
|
302
|
+
if (hook != null) hook(id, username, email);
|
|
303
|
+
}
|
|
248
304
|
/** Signed session cookie name (the HTTPS form). `__Host-` pairs with
|
|
249
305
|
* `asHostPrefixed()` (Secure, Path=/, no Domain) for the strongest browser
|
|
250
306
|
* scoping; over plain HTTP the unprefixed `toil_sess` is used instead. */
|
package/server/globals/userid.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `ToilUserId` — the stable, tenant-scoped 256-bit user identity.
|
|
3
3
|
*
|
|
4
|
-
* Derived once
|
|
4
|
+
* Derived once by SHA-256 over length-framed context, public key, identifier, and domain fields, so the SAME user (same ML-DSA login
|
|
5
5
|
* public key + the same email/username) on the SAME tenant domain always maps to the SAME id — independent
|
|
6
6
|
* of session, cookie, or device. It is opaque and one-way (a hash), so it is safe to store, log, or use as
|
|
7
7
|
* a stable database key without leaking the underlying key or address.
|
|
@@ -24,10 +24,9 @@ export class ToilUserId {
|
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Derive the id from the user's ML-DSA public key, their identifier (email or username), and the
|
|
27
|
-
* tenant `domain` (the site on dacely). Deterministic: identical inputs → identical id.
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* unambiguous, and `domain` is the trusted tail supplied by the host, not the user.
|
|
27
|
+
* tenant `domain` (the site on dacely). Deterministic: identical inputs → identical id.
|
|
28
|
+
* SHA-256 hashes four fields in order: UTF-8 `toil.userid.v1`, the public key,
|
|
29
|
+
* UTF-8 identifier, and UTF-8 domain. Each field has a u32 little-endian byte-length prefix.
|
|
31
30
|
*/
|
|
32
31
|
static derive(mldsaPublicKey: Uint8Array, identifier: string, domain: string): ToilUserId {
|
|
33
32
|
// Length-framed, domain-separated preimage: a u32 length prefix on every
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Static editor declarations for
|
|
2
|
+
// the toiljs server-runtime globals (Cookie, Cookies, SecureCookies, the
|
|
3
|
+
// cookie enums): @global in the runtime, used with no import. These alias the
|
|
4
|
+
// real runtime types so a global-built Cookie is exactly what Response.setCookie
|
|
5
|
+
// / SecureCookies.seal expect. The toilscript compiler registers them itself.
|
|
6
|
+
declare const SameSite: typeof import('toiljs/server/runtime/http/cookie').SameSite;
|
|
7
|
+
type SameSite = import('toiljs/server/runtime/http/cookie').SameSite;
|
|
8
|
+
declare const CookieEncoding: typeof import('toiljs/server/runtime/http/cookie').CookieEncoding;
|
|
9
|
+
type CookieEncoding = import('toiljs/server/runtime/http/cookie').CookieEncoding;
|
|
10
|
+
declare const CookiePrefix: typeof import('toiljs/server/runtime/http/cookie').CookiePrefix;
|
|
11
|
+
type CookiePrefix = import('toiljs/server/runtime/http/cookie').CookiePrefix;
|
|
12
|
+
declare const CookieValidation: typeof import('toiljs/server/runtime/http/cookie').CookieValidation;
|
|
13
|
+
type CookieValidation = import('toiljs/server/runtime/http/cookie').CookieValidation;
|
|
14
|
+
declare const Cookie: typeof import('toiljs/server/runtime/http/cookie').Cookie;
|
|
15
|
+
type Cookie = import('toiljs/server/runtime/http/cookie').Cookie;
|
|
16
|
+
declare const CookieMap: typeof import('toiljs/server/runtime/http/cookies').CookieMap;
|
|
17
|
+
type CookieMap = import('toiljs/server/runtime/http/cookies').CookieMap;
|
|
18
|
+
declare const Cookies: typeof import('toiljs/server/runtime/http/cookies').Cookies;
|
|
19
|
+
type Cookies = import('toiljs/server/runtime/http/cookies').Cookies;
|
|
20
|
+
declare const SecureCookies: typeof import('toiljs/server/runtime/http/securecookies').SecureCookies;
|
|
21
|
+
type SecureCookies = import('toiljs/server/runtime/http/securecookies').SecureCookies;
|
|
22
|
+
declare const Time: typeof import('toiljs/server/runtime/time').Time;
|
|
23
|
+
// Email, rate-limit, 2FA, and auth globals (server/globals/*), hand-declared
|
|
24
|
+
// because their AssemblyScript source can't be type-aliased from tsc.
|
|
25
|
+
declare enum EmailStatus { Sent, Disabled, Budget, RecipientCapped, Deduped, TryLater, BadRecipient, ProviderError }
|
|
26
|
+
declare namespace EmailService { function send(to: string, subject: string, body: string, purpose?: string, html?: string): EmailStatus; function sendDetached(to: string, subject: string, body: string, purpose?: string, html?: string): EmailStatus; }
|
|
27
|
+
declare class RenderedEmail { subject: string; body: string; html: string; constructor(subject: string, body: string, html: string); }
|
|
28
|
+
declare class EmailTemplate { constructor(subject: string, body: string, html?: string); render(vars: Map<string, string>): RenderedEmail; send(to: string, vars: Map<string, string>, purpose?: string): EmailStatus; }
|
|
29
|
+
declare namespace RateLimitService { function guard(routeId: i32, strategy: i32, limit: i32, window: i32): import('toiljs/server/runtime/response').Response | null; function guardKeyed(routeId: i32, strategy: i32, limit: i32, window: i32, key: string): import('toiljs/server/runtime/response').Response | null; }
|
|
30
|
+
declare namespace Environment { function get(key: string): string | null; function getSecure(key: string): string | null; }
|
|
31
|
+
declare class TwoFactorIssue { code: string; token: string; constructor(code: string, token: string); }
|
|
32
|
+
declare class TwoFactorChallenge { token: string; status: EmailStatus; constructor(token: string, status: EmailStatus); }
|
|
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
|
+
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
|
+
interface __ToilAuthUser { toilUserId: Uint8Array; username: string; }
|
|
36
|
+
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
|
+
declare function __toilEncodeAuthUser(toilUserId: Uint8Array, username: string): Uint8Array;
|
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
writeUtf8
|
|
32
32
|
} from './memory';
|
|
33
33
|
import { Header, Method, Request } from './request';
|
|
34
|
-
import { Response } from './response';
|
|
34
|
+
import { Response, ensureSecurityHeaders } from './response';
|
|
35
35
|
|
|
36
36
|
class DecodeCursor {
|
|
37
37
|
base: usize;
|
|
@@ -140,6 +140,7 @@ export function decodeRequest(req_ofs: usize, req_len: usize): Request | null {
|
|
|
140
140
|
* encoder fault.
|
|
141
141
|
*/
|
|
142
142
|
export function encodeResponse(resp: Response, dst_ofs: usize): u32 {
|
|
143
|
+
ensureSecurityHeaders(resp);
|
|
143
144
|
// Validate fits-in-u16/u32 limits up front so we never half-write.
|
|
144
145
|
if (resp.headers.length > 0xffff) {
|
|
145
146
|
return encodeFallback500(dst_ofs);
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import { Server } from '../env/Server';
|
|
17
17
|
import { decodeRequest, encodeResponse } from '../envelope';
|
|
18
|
-
import { Response } from '../response';
|
|
18
|
+
import { Response, ensureSecurityHeaders } from '../response';
|
|
19
19
|
import { Rpc } from '../rpc/Rpc';
|
|
20
20
|
|
|
21
21
|
// Ensure the cookie library is in every build so its `@global` types
|
|
@@ -79,6 +79,7 @@ export function handle(req_ofs: i32, req_len: i32): i64 {
|
|
|
79
79
|
// and the soft guard tightens to it automatically. Encode runs AFTER decode,
|
|
80
80
|
// so it can never clobber the request; the max() keeps it clear of an
|
|
81
81
|
// oversized request envelope regardless.
|
|
82
|
+
ensureSecurityHeaders(resp);
|
|
82
83
|
let bound: usize = 512 + <usize>resp.body.length;
|
|
83
84
|
for (let i = 0, n = resp.headers.length; i < n; i++) {
|
|
84
85
|
const h = resp.headers[i];
|