pico-engine 1.4.0 → 1.5.0
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/README.md +147 -0
- package/dist/auth/AuthService.js +537 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/webauthn.js +97 -0
- package/dist/cli.js +11 -0
- package/dist/index.js +75 -43
- package/dist/oauth/OAuthService.js +356 -0
- package/dist/oauth/acg.js +495 -0
- package/dist/oauth/channelEligibility.js +26 -0
- package/dist/oauth/errors.js +12 -0
- package/dist/oauth/index.js +21 -0
- package/dist/oauth/krlModule.js +27 -0
- package/dist/oauth/meshOAuth.js +43 -0
- package/dist/provisionRoot.js +80 -0
- package/dist/server.js +558 -15
- package/krl/io.picolabs.oauth.krl +48 -0
- package/krl/io.picolabs.wrangler.krl +4 -4
- package/package.json +14 -8
- package/public/pico-engine-ui.css +1 -1
- package/public/pico-engine-ui.js +21 -20
- package/public/pico-labs-logo.png +0 -0
- package/src/auth/AuthService.ts +755 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/webauthn.ts +182 -0
- package/src/cli.ts +11 -0
- package/src/index.ts +115 -52
- package/src/oauth/OAuthService.ts +474 -0
- package/src/oauth/acg.ts +666 -0
- package/src/oauth/channelEligibility.ts +26 -0
- package/src/oauth/errors.ts +10 -0
- package/src/oauth/index.ts +14 -0
- package/src/oauth/krlModule.ts +31 -0
- package/src/oauth/meshOAuth.ts +50 -0
- package/src/provisionRoot.ts +97 -0
- package/src/server.ts +643 -24
|
@@ -0,0 +1,755 @@
|
|
|
1
|
+
import * as crypto from "crypto";
|
|
2
|
+
import type {
|
|
3
|
+
AuthenticationResponseJSON,
|
|
4
|
+
AuthenticatorTransportFuture,
|
|
5
|
+
PublicKeyCredentialCreationOptionsJSON,
|
|
6
|
+
PublicKeyCredentialRequestOptionsJSON,
|
|
7
|
+
RegistrationResponseJSON,
|
|
8
|
+
} from "@simplewebauthn/server";
|
|
9
|
+
import { PicoDb, PicoDbKey } from "pico-framework";
|
|
10
|
+
import { WebAuthnAdapter, WebAuthnCredentialKey } from "./webauthn";
|
|
11
|
+
|
|
12
|
+
const CREDENTIAL_PREFIX = "auth-credential";
|
|
13
|
+
const ACCOUNT_PREFIX = "auth-account";
|
|
14
|
+
const SESSION_PREFIX = "auth-session";
|
|
15
|
+
const INVITE_PREFIX = "auth-invite";
|
|
16
|
+
|
|
17
|
+
const DEFAULT_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
18
|
+
const DEFAULT_INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
19
|
+
const CHALLENGE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
20
|
+
const DEFAULT_RP_NAME = "Pico Engine";
|
|
21
|
+
|
|
22
|
+
export class AuthError extends Error {
|
|
23
|
+
statusCode: number;
|
|
24
|
+
constructor(message: string, statusCode = 400) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "AuthError";
|
|
27
|
+
this.statusCode = statusCode;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface StoredAccount {
|
|
32
|
+
accountId: string;
|
|
33
|
+
rootPicoId: string;
|
|
34
|
+
displayName: string;
|
|
35
|
+
/** Stable WebAuthn `user.name`; legacy accounts omit this (displayName was used). */
|
|
36
|
+
webauthnUserName?: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface StoredCredential {
|
|
41
|
+
credentialID: string;
|
|
42
|
+
accountId: string;
|
|
43
|
+
publicKey: string; // base64url of the COSE key bytes
|
|
44
|
+
counter: number;
|
|
45
|
+
transports: AuthenticatorTransportFuture[];
|
|
46
|
+
label: string;
|
|
47
|
+
createdAt: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Public (safe) view of a credential — never exposes the public key bytes. */
|
|
51
|
+
export interface CredentialInfo {
|
|
52
|
+
credentialID: string;
|
|
53
|
+
label: string;
|
|
54
|
+
transports: AuthenticatorTransportFuture[];
|
|
55
|
+
createdAt: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface InviteInfo {
|
|
59
|
+
token: string;
|
|
60
|
+
label?: string;
|
|
61
|
+
createdAt: string;
|
|
62
|
+
expiresAt: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface InvitePeek {
|
|
66
|
+
valid: boolean;
|
|
67
|
+
label?: string;
|
|
68
|
+
expiresAt?: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface StoredInvite {
|
|
72
|
+
token: string;
|
|
73
|
+
createdByAccountId: string;
|
|
74
|
+
label?: string;
|
|
75
|
+
createdAt: string;
|
|
76
|
+
expiresAt: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface StoredSession {
|
|
80
|
+
token: string;
|
|
81
|
+
accountId: string;
|
|
82
|
+
rootPicoId: string;
|
|
83
|
+
credentialID: string;
|
|
84
|
+
expiry: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
type Ceremony =
|
|
88
|
+
| {
|
|
89
|
+
type: "register";
|
|
90
|
+
challenge: string;
|
|
91
|
+
accountId: string;
|
|
92
|
+
displayName: string;
|
|
93
|
+
inviteToken?: string;
|
|
94
|
+
expiresAt: number;
|
|
95
|
+
}
|
|
96
|
+
| { type: "claim"; challenge: string; accountId: string; displayName: string; rootPicoId: string; expiresAt: number }
|
|
97
|
+
| { type: "login"; challenge: string; expiresAt: number }
|
|
98
|
+
| { type: "addcred"; challenge: string; accountId: string; expiresAt: number };
|
|
99
|
+
|
|
100
|
+
export interface WhoAmI {
|
|
101
|
+
authenticated: boolean;
|
|
102
|
+
accountId?: string;
|
|
103
|
+
rootPicoId?: string;
|
|
104
|
+
displayName?: string;
|
|
105
|
+
uiECI?: string | null;
|
|
106
|
+
credentials?: CredentialInfo[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface AuthServiceDeps {
|
|
110
|
+
db: PicoDb;
|
|
111
|
+
webauthn: WebAuthnAdapter;
|
|
112
|
+
|
|
113
|
+
/** The engine's current base url, used to derive rpID/origin. */
|
|
114
|
+
getBaseUrl: () => string | undefined;
|
|
115
|
+
rpID?: string;
|
|
116
|
+
rpName?: string;
|
|
117
|
+
origin?: string;
|
|
118
|
+
|
|
119
|
+
/** When false, new accounts require bootstrap, legacy claim, or an invite token. */
|
|
120
|
+
allowSelfSignup?: boolean;
|
|
121
|
+
sessionTtlMs?: number;
|
|
122
|
+
inviteTtlMs?: number;
|
|
123
|
+
|
|
124
|
+
/** Mint a brand new root pico (installs base rulesets) for a new account. */
|
|
125
|
+
provisionRoot: (opts?: {
|
|
126
|
+
name?: string;
|
|
127
|
+
}) => Promise<{ rootPicoId: string; uiECI: string }>;
|
|
128
|
+
/** Resolve the ["engine","ui"] ECI for an existing root. */
|
|
129
|
+
getUiECI: (rootPicoId: string) => Promise<string | null> | string | null;
|
|
130
|
+
/** Primary root id from `["root-pico"]`, or null when none. */
|
|
131
|
+
getPrimaryRootPicoId: () => string | null;
|
|
132
|
+
/** Optional hook after legacy claim (e.g. set root display name in UI ruleset). */
|
|
133
|
+
onAccountClaimed?: (rootPicoId: string, displayName: string) => Promise<void>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export class AuthService {
|
|
137
|
+
private deps: AuthServiceDeps;
|
|
138
|
+
private challenges: Map<string, Ceremony> = new Map();
|
|
139
|
+
|
|
140
|
+
constructor(deps: AuthServiceDeps) {
|
|
141
|
+
this.deps = deps;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
get sessionTtlMs(): number {
|
|
145
|
+
return this.deps.sessionTtlMs || DEFAULT_SESSION_TTL_MS;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Resolve the relying-party config from explicit overrides or base_url. */
|
|
149
|
+
rp(): { rpID: string; rpName: string; origin: string } {
|
|
150
|
+
const base = this.deps.getBaseUrl() || "http://localhost:3000";
|
|
151
|
+
let hostname = "localhost";
|
|
152
|
+
let origin = base;
|
|
153
|
+
try {
|
|
154
|
+
const url = new URL(base);
|
|
155
|
+
hostname = url.hostname;
|
|
156
|
+
origin = url.origin;
|
|
157
|
+
} catch (_e) {
|
|
158
|
+
// fall through to defaults
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
rpID: this.deps.rpID || hostname,
|
|
162
|
+
rpName: this.deps.rpName || DEFAULT_RP_NAME,
|
|
163
|
+
origin: this.deps.origin || origin,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
isSecure(): boolean {
|
|
168
|
+
return this.rp().origin.startsWith("https:");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
allowSelfSignup(): boolean {
|
|
172
|
+
return this.deps.allowSelfSignup === true;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Legacy engine: primary root exists but no auth account has been claimed yet. */
|
|
176
|
+
async needsAuthMigration(): Promise<boolean> {
|
|
177
|
+
return (
|
|
178
|
+
(await this.accountCount()) === 0 &&
|
|
179
|
+
this.deps.getPrimaryRootPicoId() !== null
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ---- legacy migration: claim the existing primary root ----
|
|
184
|
+
|
|
185
|
+
async claimPrimaryRootOptions(input: {
|
|
186
|
+
displayName?: string;
|
|
187
|
+
}): Promise<{ options: PublicKeyCredentialCreationOptionsJSON; ceremonyId: string }> {
|
|
188
|
+
const rootPicoId = this.deps.getPrimaryRootPicoId();
|
|
189
|
+
if (!rootPicoId) {
|
|
190
|
+
throw new AuthError("No primary root to claim", 404);
|
|
191
|
+
}
|
|
192
|
+
if ((await this.accountCount()) > 0) {
|
|
193
|
+
throw new AuthError("This engine already has an account", 403);
|
|
194
|
+
}
|
|
195
|
+
const { rpID, rpName } = this.rp();
|
|
196
|
+
const accountId = randomId();
|
|
197
|
+
const displayName = (input.displayName || "").trim() || `pico-${accountId.slice(0, 6)}`;
|
|
198
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
199
|
+
rpID,
|
|
200
|
+
rpName,
|
|
201
|
+
userID: new TextEncoder().encode(accountId),
|
|
202
|
+
userName: accountId,
|
|
203
|
+
userDisplayName: displayName,
|
|
204
|
+
excludeCredentials: [],
|
|
205
|
+
});
|
|
206
|
+
const ceremonyId = this.putCeremony({
|
|
207
|
+
type: "claim",
|
|
208
|
+
challenge: options.challenge,
|
|
209
|
+
accountId,
|
|
210
|
+
displayName,
|
|
211
|
+
rootPicoId,
|
|
212
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
213
|
+
});
|
|
214
|
+
return { options, ceremonyId };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async claimPrimaryRootVerify(input: {
|
|
218
|
+
ceremonyId: string;
|
|
219
|
+
response: RegistrationResponseJSON;
|
|
220
|
+
}): Promise<{ account: StoredAccount; session: StoredSession; uiECI: string }> {
|
|
221
|
+
const cer = this.takeCeremony(input.ceremonyId, "claim");
|
|
222
|
+
if ((await this.accountCount()) > 0) {
|
|
223
|
+
throw new AuthError("This engine already has an account", 403);
|
|
224
|
+
}
|
|
225
|
+
const primaryRootId = this.deps.getPrimaryRootPicoId();
|
|
226
|
+
if (!primaryRootId || primaryRootId !== cer.rootPicoId) {
|
|
227
|
+
throw new AuthError("Primary root is no longer available to claim", 409);
|
|
228
|
+
}
|
|
229
|
+
const { rpID, origin } = this.rp();
|
|
230
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
231
|
+
response: input.response,
|
|
232
|
+
expectedChallenge: cer.challenge,
|
|
233
|
+
expectedOrigin: origin,
|
|
234
|
+
expectedRPID: rpID,
|
|
235
|
+
});
|
|
236
|
+
if (!result.verified || !result.credential) {
|
|
237
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const uiECI = await this.deps.getUiECI(cer.rootPicoId);
|
|
241
|
+
if (!uiECI) {
|
|
242
|
+
throw new AuthError("Primary root has no UI channel", 500);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const account: StoredAccount = {
|
|
246
|
+
accountId: cer.accountId,
|
|
247
|
+
rootPicoId: cer.rootPicoId,
|
|
248
|
+
displayName: cer.displayName,
|
|
249
|
+
webauthnUserName: cer.accountId,
|
|
250
|
+
createdAt: new Date().toISOString(),
|
|
251
|
+
};
|
|
252
|
+
await this.deps.db.put([ACCOUNT_PREFIX, account.accountId], account);
|
|
253
|
+
await this.storeCredential(account.accountId, result.credential, "passkey");
|
|
254
|
+
|
|
255
|
+
if (this.deps.onAccountClaimed) {
|
|
256
|
+
await this.deps.onAccountClaimed(cer.rootPicoId, cer.displayName);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const session = await this.createSession(
|
|
260
|
+
account.accountId,
|
|
261
|
+
account.rootPicoId,
|
|
262
|
+
result.credential.id
|
|
263
|
+
);
|
|
264
|
+
return { account, session, uiECI };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---- registration invites ----
|
|
268
|
+
|
|
269
|
+
async createInvite(input: {
|
|
270
|
+
createdByAccountId: string;
|
|
271
|
+
label?: string;
|
|
272
|
+
}): Promise<InviteInfo> {
|
|
273
|
+
const token = randomToken();
|
|
274
|
+
const now = Date.now();
|
|
275
|
+
const ttl = this.deps.inviteTtlMs ?? DEFAULT_INVITE_TTL_MS;
|
|
276
|
+
const invite: StoredInvite = {
|
|
277
|
+
token,
|
|
278
|
+
createdByAccountId: input.createdByAccountId,
|
|
279
|
+
label: (input.label || "").trim() || undefined,
|
|
280
|
+
createdAt: new Date(now).toISOString(),
|
|
281
|
+
expiresAt: now + ttl,
|
|
282
|
+
};
|
|
283
|
+
await this.deps.db.put([INVITE_PREFIX, token], invite);
|
|
284
|
+
return {
|
|
285
|
+
token: invite.token,
|
|
286
|
+
label: invite.label,
|
|
287
|
+
createdAt: invite.createdAt,
|
|
288
|
+
expiresAt: invite.expiresAt,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async peekInvite(token: string): Promise<InvitePeek> {
|
|
293
|
+
const invite = await this.getInvite(token);
|
|
294
|
+
if (!invite) {
|
|
295
|
+
return { valid: false };
|
|
296
|
+
}
|
|
297
|
+
if (invite.expiresAt < Date.now()) {
|
|
298
|
+
return { valid: false };
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
valid: true,
|
|
302
|
+
label: invite.label,
|
|
303
|
+
expiresAt: invite.expiresAt,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ---- new-account registration (unauthenticated / bootstrap / invited) ----
|
|
308
|
+
|
|
309
|
+
async registerNewAccountOptions(input: {
|
|
310
|
+
displayName?: string;
|
|
311
|
+
invite?: string;
|
|
312
|
+
}): Promise<{ options: PublicKeyCredentialCreationOptionsJSON; ceremonyId: string }> {
|
|
313
|
+
if (await this.needsAuthMigration()) {
|
|
314
|
+
throw new AuthError(
|
|
315
|
+
"This engine has an existing mesh. Claim it with a passkey instead of registering a new root.",
|
|
316
|
+
403
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const inviteToken = (input.invite || "").trim() || undefined;
|
|
320
|
+
await this.assertRegistrationAllowed(inviteToken);
|
|
321
|
+
|
|
322
|
+
const { rpID, rpName } = this.rp();
|
|
323
|
+
const accountId = randomId();
|
|
324
|
+
const displayName = (input.displayName || "").trim() || `pico-${accountId.slice(0, 6)}`;
|
|
325
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
326
|
+
rpID,
|
|
327
|
+
rpName,
|
|
328
|
+
userID: new TextEncoder().encode(accountId),
|
|
329
|
+
userName: accountId,
|
|
330
|
+
userDisplayName: displayName,
|
|
331
|
+
excludeCredentials: [],
|
|
332
|
+
});
|
|
333
|
+
const ceremonyId = this.putCeremony({
|
|
334
|
+
type: "register",
|
|
335
|
+
challenge: options.challenge,
|
|
336
|
+
accountId,
|
|
337
|
+
displayName,
|
|
338
|
+
inviteToken,
|
|
339
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
340
|
+
});
|
|
341
|
+
return { options, ceremonyId };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async registerNewAccountVerify(input: {
|
|
345
|
+
ceremonyId: string;
|
|
346
|
+
response: RegistrationResponseJSON;
|
|
347
|
+
}): Promise<{ account: StoredAccount; session: StoredSession; uiECI: string }> {
|
|
348
|
+
if (await this.needsAuthMigration()) {
|
|
349
|
+
throw new AuthError(
|
|
350
|
+
"This engine has an existing mesh. Claim it with a passkey instead of registering a new root.",
|
|
351
|
+
403
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
const cer = this.takeCeremony(input.ceremonyId, "register");
|
|
355
|
+
await this.assertRegistrationAllowed(cer.inviteToken);
|
|
356
|
+
|
|
357
|
+
const { rpID, origin } = this.rp();
|
|
358
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
359
|
+
response: input.response,
|
|
360
|
+
expectedChallenge: cer.challenge,
|
|
361
|
+
expectedOrigin: origin,
|
|
362
|
+
expectedRPID: rpID,
|
|
363
|
+
});
|
|
364
|
+
if (!result.verified || !result.credential) {
|
|
365
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Provision the account's root only after the ceremony verifies.
|
|
369
|
+
const { rootPicoId, uiECI } = await this.deps.provisionRoot({
|
|
370
|
+
name: cer.displayName,
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
const account: StoredAccount = {
|
|
374
|
+
accountId: cer.accountId,
|
|
375
|
+
rootPicoId,
|
|
376
|
+
displayName: cer.displayName,
|
|
377
|
+
webauthnUserName: cer.accountId,
|
|
378
|
+
createdAt: new Date().toISOString(),
|
|
379
|
+
};
|
|
380
|
+
await this.deps.db.put([ACCOUNT_PREFIX, account.accountId], account);
|
|
381
|
+
await this.storeCredential(account.accountId, result.credential, "passkey");
|
|
382
|
+
|
|
383
|
+
if (cer.inviteToken) {
|
|
384
|
+
await this.consumeInvite(cer.inviteToken);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const session = await this.createSession(
|
|
388
|
+
account.accountId,
|
|
389
|
+
rootPicoId,
|
|
390
|
+
result.credential.id
|
|
391
|
+
);
|
|
392
|
+
return { account, session, uiECI };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ---- usernameless login ----
|
|
396
|
+
|
|
397
|
+
async loginOptions(): Promise<{
|
|
398
|
+
options: PublicKeyCredentialRequestOptionsJSON;
|
|
399
|
+
ceremonyId: string;
|
|
400
|
+
}> {
|
|
401
|
+
const { rpID } = this.rp();
|
|
402
|
+
const options = await this.deps.webauthn.generateAuthenticationOptions({ rpID });
|
|
403
|
+
const ceremonyId = this.putCeremony({
|
|
404
|
+
type: "login",
|
|
405
|
+
challenge: options.challenge,
|
|
406
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
407
|
+
});
|
|
408
|
+
return { options, ceremonyId };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async loginVerify(input: {
|
|
412
|
+
ceremonyId: string;
|
|
413
|
+
response: AuthenticationResponseJSON;
|
|
414
|
+
}): Promise<{ account: StoredAccount; session: StoredSession }> {
|
|
415
|
+
const cer = this.takeCeremony(input.ceremonyId, "login");
|
|
416
|
+
const credentialID = input.response.id;
|
|
417
|
+
const stored = await this.getCredential(credentialID);
|
|
418
|
+
if (!stored) {
|
|
419
|
+
throw new AuthError("Unknown credential", 400);
|
|
420
|
+
}
|
|
421
|
+
const { rpID, origin } = this.rp();
|
|
422
|
+
const result = await this.deps.webauthn.verifyAuthentication({
|
|
423
|
+
response: input.response,
|
|
424
|
+
expectedChallenge: cer.challenge,
|
|
425
|
+
expectedOrigin: origin,
|
|
426
|
+
expectedRPID: rpID,
|
|
427
|
+
credential: storedToKey(stored),
|
|
428
|
+
});
|
|
429
|
+
if (!result.verified) {
|
|
430
|
+
throw new AuthError("Authentication could not be verified", 400);
|
|
431
|
+
}
|
|
432
|
+
stored.counter = result.newCounter;
|
|
433
|
+
await this.deps.db.put([CREDENTIAL_PREFIX, credentialID], stored);
|
|
434
|
+
|
|
435
|
+
const account = await this.getAccount(stored.accountId);
|
|
436
|
+
if (!account) {
|
|
437
|
+
throw new AuthError("Account no longer exists", 400);
|
|
438
|
+
}
|
|
439
|
+
const session = await this.createSession(
|
|
440
|
+
account.accountId,
|
|
441
|
+
account.rootPicoId,
|
|
442
|
+
credentialID
|
|
443
|
+
);
|
|
444
|
+
return { account, session };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ---- add / remove passkeys on an existing account (session-gated) ----
|
|
448
|
+
|
|
449
|
+
async addCredentialOptions(input: {
|
|
450
|
+
accountId: string;
|
|
451
|
+
}): Promise<{ options: PublicKeyCredentialCreationOptionsJSON; ceremonyId: string }> {
|
|
452
|
+
const account = await this.getAccount(input.accountId);
|
|
453
|
+
if (!account) {
|
|
454
|
+
throw new AuthError("Account not found", 404);
|
|
455
|
+
}
|
|
456
|
+
const { rpID, rpName } = this.rp();
|
|
457
|
+
const existing = await this.listStoredCredentials(input.accountId);
|
|
458
|
+
const userName = account.webauthnUserName || account.displayName;
|
|
459
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
460
|
+
rpID,
|
|
461
|
+
rpName,
|
|
462
|
+
userID: new TextEncoder().encode(account.accountId),
|
|
463
|
+
userName,
|
|
464
|
+
userDisplayName: account.displayName,
|
|
465
|
+
excludeCredentials: existing.map((c) => ({
|
|
466
|
+
id: c.credentialID,
|
|
467
|
+
transports: c.transports,
|
|
468
|
+
})),
|
|
469
|
+
additionalPasskey: true,
|
|
470
|
+
});
|
|
471
|
+
const ceremonyId = this.putCeremony({
|
|
472
|
+
type: "addcred",
|
|
473
|
+
challenge: options.challenge,
|
|
474
|
+
accountId: account.accountId,
|
|
475
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
476
|
+
});
|
|
477
|
+
return { options, ceremonyId };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async addCredentialVerify(input: {
|
|
481
|
+
ceremonyId: string;
|
|
482
|
+
accountId: string;
|
|
483
|
+
response: RegistrationResponseJSON;
|
|
484
|
+
label?: string;
|
|
485
|
+
}): Promise<{ credential: CredentialInfo }> {
|
|
486
|
+
const cer = this.takeCeremony(input.ceremonyId, "addcred");
|
|
487
|
+
if (cer.accountId !== input.accountId) {
|
|
488
|
+
throw new AuthError("Ceremony does not match this account", 403);
|
|
489
|
+
}
|
|
490
|
+
const { rpID, origin } = this.rp();
|
|
491
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
492
|
+
response: input.response,
|
|
493
|
+
expectedChallenge: cer.challenge,
|
|
494
|
+
expectedOrigin: origin,
|
|
495
|
+
expectedRPID: rpID,
|
|
496
|
+
});
|
|
497
|
+
if (!result.verified || !result.credential) {
|
|
498
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
499
|
+
}
|
|
500
|
+
const existing = await this.listStoredCredentials(input.accountId);
|
|
501
|
+
if (existing.some((c) => c.credentialID === result.credential!.id)) {
|
|
502
|
+
throw new AuthError(
|
|
503
|
+
"This passkey is already registered for your account. To add another, enroll from a different device or security key.",
|
|
504
|
+
409
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
// Reuses the existing account/user-handle — does NOT create a new root.
|
|
508
|
+
const stored = await this.storeCredential(
|
|
509
|
+
input.accountId,
|
|
510
|
+
result.credential,
|
|
511
|
+
(input.label || "").trim() || "passkey"
|
|
512
|
+
);
|
|
513
|
+
return { credential: toCredentialInfo(stored) };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async deleteCredential(accountId: string, credentialID: string): Promise<void> {
|
|
517
|
+
const creds = await this.listStoredCredentials(accountId);
|
|
518
|
+
if (creds.length <= 1) {
|
|
519
|
+
throw new AuthError("Cannot remove the last passkey for an account", 409);
|
|
520
|
+
}
|
|
521
|
+
const target = creds.find((c) => c.credentialID === credentialID);
|
|
522
|
+
if (!target) {
|
|
523
|
+
throw new AuthError("Credential not found", 404);
|
|
524
|
+
}
|
|
525
|
+
await this.deps.db.del([CREDENTIAL_PREFIX, credentialID]);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async listCredentials(accountId: string): Promise<CredentialInfo[]> {
|
|
529
|
+
const creds = await this.listStoredCredentials(accountId);
|
|
530
|
+
return creds.map(toCredentialInfo);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// ---- sessions ----
|
|
534
|
+
|
|
535
|
+
async createSession(
|
|
536
|
+
accountId: string,
|
|
537
|
+
rootPicoId: string,
|
|
538
|
+
credentialID: string
|
|
539
|
+
): Promise<StoredSession> {
|
|
540
|
+
const session: StoredSession = {
|
|
541
|
+
token: randomToken(),
|
|
542
|
+
accountId,
|
|
543
|
+
rootPicoId,
|
|
544
|
+
credentialID,
|
|
545
|
+
expiry: Date.now() + this.sessionTtlMs,
|
|
546
|
+
};
|
|
547
|
+
await this.deps.db.put([SESSION_PREFIX, session.token], session);
|
|
548
|
+
return session;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async getSession(token: string): Promise<StoredSession | null> {
|
|
552
|
+
if (!token) {
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
const session = await dbGet<StoredSession>(this.deps.db, [SESSION_PREFIX, token]);
|
|
556
|
+
if (!session) {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
if (session.expiry < Date.now()) {
|
|
560
|
+
await this.deps.db.del([SESSION_PREFIX, token]);
|
|
561
|
+
return null;
|
|
562
|
+
}
|
|
563
|
+
return session;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async deleteSession(token: string): Promise<void> {
|
|
567
|
+
if (token) {
|
|
568
|
+
await this.deps.db.del([SESSION_PREFIX, token]);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
async whoami(token: string): Promise<WhoAmI> {
|
|
573
|
+
const session = await this.getSession(token);
|
|
574
|
+
if (!session) {
|
|
575
|
+
return { authenticated: false };
|
|
576
|
+
}
|
|
577
|
+
const account = await this.getAccount(session.accountId);
|
|
578
|
+
if (!account) {
|
|
579
|
+
return { authenticated: false };
|
|
580
|
+
}
|
|
581
|
+
const uiECI = await this.deps.getUiECI(account.rootPicoId);
|
|
582
|
+
const credentials = await this.listCredentials(account.accountId);
|
|
583
|
+
return {
|
|
584
|
+
authenticated: true,
|
|
585
|
+
accountId: account.accountId,
|
|
586
|
+
rootPicoId: account.rootPicoId,
|
|
587
|
+
displayName: account.displayName,
|
|
588
|
+
uiECI,
|
|
589
|
+
credentials,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// ---- stores ----
|
|
594
|
+
|
|
595
|
+
private async assertRegistrationAllowed(inviteToken?: string): Promise<void> {
|
|
596
|
+
const count = await this.accountCount();
|
|
597
|
+
if (count === 0) {
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
if (this.deps.allowSelfSignup === true) {
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const token = (inviteToken || "").trim();
|
|
604
|
+
if (!token) {
|
|
605
|
+
throw new AuthError("Self-signup is disabled on this engine", 403);
|
|
606
|
+
}
|
|
607
|
+
const invite = await this.getInvite(token);
|
|
608
|
+
if (!invite) {
|
|
609
|
+
throw new AuthError("Invalid or expired invite", 403);
|
|
610
|
+
}
|
|
611
|
+
if (invite.expiresAt < Date.now()) {
|
|
612
|
+
throw new AuthError("Invalid or expired invite", 403);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
private async getInvite(token: string): Promise<StoredInvite | null> {
|
|
617
|
+
const trimmed = (token || "").trim();
|
|
618
|
+
if (!trimmed) {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
return dbGet<StoredInvite>(this.deps.db, [INVITE_PREFIX, trimmed]);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
private async consumeInvite(token: string): Promise<void> {
|
|
625
|
+
const trimmed = (token || "").trim();
|
|
626
|
+
if (!trimmed) {
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
await this.deps.db.del([INVITE_PREFIX, trimmed]);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async getAccount(accountId: string): Promise<StoredAccount | null> {
|
|
633
|
+
return dbGet<StoredAccount>(this.deps.db, [ACCOUNT_PREFIX, accountId]);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
private async accountCount(): Promise<number> {
|
|
637
|
+
const rows = await dbList(this.deps.db, [ACCOUNT_PREFIX]);
|
|
638
|
+
return rows.length;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private async getCredential(credentialID: string): Promise<StoredCredential | null> {
|
|
642
|
+
return dbGet<StoredCredential>(this.deps.db, [CREDENTIAL_PREFIX, credentialID]);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
private async listStoredCredentials(accountId: string): Promise<StoredCredential[]> {
|
|
646
|
+
const rows = await dbList<StoredCredential>(this.deps.db, [CREDENTIAL_PREFIX]);
|
|
647
|
+
return rows
|
|
648
|
+
.map((r) => r.value)
|
|
649
|
+
.filter((c) => c && c.accountId === accountId);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
private async storeCredential(
|
|
653
|
+
accountId: string,
|
|
654
|
+
key: WebAuthnCredentialKey,
|
|
655
|
+
label: string
|
|
656
|
+
): Promise<StoredCredential> {
|
|
657
|
+
const stored: StoredCredential = {
|
|
658
|
+
credentialID: key.id,
|
|
659
|
+
accountId,
|
|
660
|
+
publicKey: Buffer.from(key.publicKey).toString("base64url"),
|
|
661
|
+
counter: key.counter,
|
|
662
|
+
transports: key.transports || [],
|
|
663
|
+
label,
|
|
664
|
+
createdAt: new Date().toISOString(),
|
|
665
|
+
};
|
|
666
|
+
await this.deps.db.put([CREDENTIAL_PREFIX, stored.credentialID], stored);
|
|
667
|
+
return stored;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// ---- challenge store (in-memory, per ceremony) ----
|
|
671
|
+
|
|
672
|
+
private putCeremony(cer: Ceremony): string {
|
|
673
|
+
this.pruneCeremonies();
|
|
674
|
+
const ceremonyId = randomId();
|
|
675
|
+
this.challenges.set(ceremonyId, cer);
|
|
676
|
+
return ceremonyId;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
private takeCeremony<T extends Ceremony["type"]>(
|
|
680
|
+
ceremonyId: string,
|
|
681
|
+
type: T
|
|
682
|
+
): Extract<Ceremony, { type: T }> {
|
|
683
|
+
const cer = ceremonyId ? this.challenges.get(ceremonyId) : undefined;
|
|
684
|
+
if (!cer || cer.type !== type) {
|
|
685
|
+
throw new AuthError("Missing or invalid challenge; restart the ceremony", 400);
|
|
686
|
+
}
|
|
687
|
+
this.challenges.delete(ceremonyId);
|
|
688
|
+
if (cer.expiresAt < Date.now()) {
|
|
689
|
+
throw new AuthError("Challenge expired; restart the ceremony", 400);
|
|
690
|
+
}
|
|
691
|
+
return cer as Extract<Ceremony, { type: T }>;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
private pruneCeremonies(): void {
|
|
695
|
+
const now = Date.now();
|
|
696
|
+
for (const [id, cer] of this.challenges) {
|
|
697
|
+
if (cer.expiresAt < now) {
|
|
698
|
+
this.challenges.delete(id);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function toCredentialInfo(c: StoredCredential): CredentialInfo {
|
|
705
|
+
return {
|
|
706
|
+
credentialID: c.credentialID,
|
|
707
|
+
label: c.label,
|
|
708
|
+
transports: c.transports,
|
|
709
|
+
createdAt: c.createdAt,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function storedToKey(c: StoredCredential): WebAuthnCredentialKey {
|
|
714
|
+
return {
|
|
715
|
+
id: c.credentialID,
|
|
716
|
+
publicKey: new Uint8Array(Buffer.from(c.publicKey, "base64url")),
|
|
717
|
+
counter: c.counter,
|
|
718
|
+
transports: c.transports,
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function randomId(): string {
|
|
723
|
+
return crypto.randomBytes(16).toString("base64url");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function randomToken(): string {
|
|
727
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async function dbGet<T>(db: PicoDb, key: PicoDbKey): Promise<T | null> {
|
|
731
|
+
try {
|
|
732
|
+
const value = await db.get(key);
|
|
733
|
+
return value === undefined ? null : (value as T);
|
|
734
|
+
} catch (err: any) {
|
|
735
|
+
if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
|
|
736
|
+
return null;
|
|
737
|
+
}
|
|
738
|
+
throw err;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async function dbList<T = any>(
|
|
743
|
+
db: PicoDb,
|
|
744
|
+
prefix: PicoDbKey
|
|
745
|
+
): Promise<{ key: PicoDbKey; value: T }[]> {
|
|
746
|
+
const out: { key: PicoDbKey; value: T }[] = [];
|
|
747
|
+
const iter = db.iterator({
|
|
748
|
+
gte: prefix,
|
|
749
|
+
lte: prefix.concat([undefined] as any),
|
|
750
|
+
});
|
|
751
|
+
for await (const [key, value] of iter) {
|
|
752
|
+
out.push({ key, value });
|
|
753
|
+
}
|
|
754
|
+
return out;
|
|
755
|
+
}
|