@jini-ai/user-management 0.6.22 → 0.7.1
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 +27 -0
- package/dist/core/types.d.ts +5 -0
- package/dist/react/auth/Login.js +5 -3
- package/dist/react/auth/Passkeys.d.ts +54 -0
- package/dist/react/auth/Passkeys.js +77 -0
- package/dist/react/auth/TotpSettings.d.ts +32 -0
- package/dist/react/auth/TotpSettings.js +93 -0
- package/dist/react/auth/hooks/use-login.hooks.d.ts +6 -0
- package/dist/react/auth/hooks/use-login.hooks.js +22 -3
- package/dist/react/auth/passkey-browser.d.ts +9 -0
- package/dist/react/auth/passkey-browser.js +19 -0
- package/dist/react/index.d.ts +5 -0
- package/dist/react/index.js +3 -0
- package/dist/react/ports.d.ts +9 -0
- package/dist/server/admin-crud-service.js +2 -0
- package/dist/server/auth-service.d.ts +19 -1
- package/dist/server/auth-service.js +20 -10
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.js +9 -0
- package/dist/server/login-providers.d.ts +15 -0
- package/dist/server/login-providers.js +67 -0
- package/dist/server/login-types.d.ts +41 -0
- package/dist/server/login-types.js +10 -0
- package/dist/server/mfa/passkey-adapter.d.ts +6 -0
- package/dist/server/mfa/passkey-adapter.js +35 -0
- package/dist/server/mfa/passkey-ports.d.ts +57 -0
- package/dist/server/mfa/passkey-ports.js +2 -0
- package/dist/server/mfa/passkey-service.d.ts +56 -0
- package/dist/server/mfa/passkey-service.js +156 -0
- package/dist/server/mfa/ports.d.ts +61 -0
- package/dist/server/mfa/ports.js +2 -0
- package/dist/server/mfa/secret-adapter.d.ts +26 -0
- package/dist/server/mfa/secret-adapter.js +12 -0
- package/dist/server/mfa/service.d.ts +77 -0
- package/dist/server/mfa/service.js +146 -0
- package/dist/server/mfa/totp-adapter.d.ts +6 -0
- package/dist/server/mfa/totp-adapter.js +18 -0
- package/dist/server/recovery-codes.d.ts +3 -0
- package/dist/server/recovery-codes.js +7 -0
- package/package.json +24 -21
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Pure parser for a plugin's member login-provider preset file. Loading, admission and pinning stay with the host. */
|
|
2
|
+
import { MemberLoginError } from "./login-types.js";
|
|
3
|
+
const ID = /^[a-z][a-z0-9-]{0,63}$/;
|
|
4
|
+
const DOMAIN = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
5
|
+
function text(value) {
|
|
6
|
+
if (typeof value !== "string" || !value.trim() || value.length > 2048)
|
|
7
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
function httpsUrl(value) {
|
|
11
|
+
const raw = text(value);
|
|
12
|
+
const url = new URL(raw);
|
|
13
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash)
|
|
14
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
15
|
+
return raw;
|
|
16
|
+
}
|
|
17
|
+
function emailAuthority(value) {
|
|
18
|
+
const domains = value.authoritativeEmailDomains ?? [];
|
|
19
|
+
if (!Array.isArray(domains) || domains.length > 16)
|
|
20
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
21
|
+
if (!domains.every(domain => typeof domain === "string" && DOMAIN.test(domain)))
|
|
22
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
23
|
+
const claim = value.hostedDomainClaim;
|
|
24
|
+
if (claim !== undefined && !/^[a-z][a-z0-9_]{0,63}$/.test(text(claim)))
|
|
25
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
26
|
+
return { authoritativeEmailDomains: domains, ...(claim === undefined ? {} : { hostedDomainClaim: claim }) };
|
|
27
|
+
}
|
|
28
|
+
function scopes(value) {
|
|
29
|
+
if (!Array.isArray(value) || value.length !== 3 || new Set(value).size !== 3)
|
|
30
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
31
|
+
if (!value.every(scope => ["openid", "email", "profile"].includes(scope)))
|
|
32
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
function preset(value) {
|
|
36
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
37
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
38
|
+
const row = value;
|
|
39
|
+
const id = text(row.id);
|
|
40
|
+
if (!ID.test(id))
|
|
41
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
42
|
+
if (row.signingAlgorithm !== "RS256" || row.clientAuthentication !== "client_secret_post")
|
|
43
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
44
|
+
if (row.pkce !== "S256")
|
|
45
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
46
|
+
return { id, label: text(row.label), issuer: httpsUrl(row.issuer), authorizationEndpoint: httpsUrl(row.authorizationEndpoint),
|
|
47
|
+
tokenEndpoint: httpsUrl(row.tokenEndpoint), jwksUri: httpsUrl(row.jwksUri), scopes: scopes(row.scopes),
|
|
48
|
+
signingAlgorithm: "RS256", clientAuthentication: "client_secret_post", pkce: "S256", credentialLabel: text(row.credentialLabel),
|
|
49
|
+
credentialCardTarget: text(row.credentialCardTarget), ...emailAuthority(row) };
|
|
50
|
+
}
|
|
51
|
+
/** Parse a bounded v1 preset file. Failure exposes a fixed code, never raw plugin JSON.
|
|
52
|
+
* @complexity O(bytes + p), bounded to 32 KiB and eight providers per package.
|
|
53
|
+
*/
|
|
54
|
+
export function parseLoginProviders(required, _options = {}) {
|
|
55
|
+
try {
|
|
56
|
+
if (required.raw.length > 32768)
|
|
57
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
58
|
+
const file = JSON.parse(required.raw);
|
|
59
|
+
if (file.schemaVersion !== 1 || !Array.isArray(file.providers) || file.providers.length > 8)
|
|
60
|
+
throw new MemberLoginError({ code: "LOGIN_UNAVAILABLE" });
|
|
61
|
+
return { ok: true, descriptors: file.providers.map(preset) };
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return { ok: false, reason: "LOGIN_PROVIDER_INVALID" };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=login-providers.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Member-login preset and identity types: what a login-provider contribution declares and what a verified login yields. */
|
|
2
|
+
import type { OAuthClientAuthMethod, OidcSigningAlgorithm } from "@jini-ai/core/contracts/oauth";
|
|
3
|
+
/** Immutable, bundled preset. Never construct one from callback claims or site-local plugins. */
|
|
4
|
+
export interface LoginProviderPreset {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly label: string;
|
|
7
|
+
readonly issuer: string;
|
|
8
|
+
readonly authorizationEndpoint: string;
|
|
9
|
+
readonly tokenEndpoint: string;
|
|
10
|
+
readonly jwksUri: string;
|
|
11
|
+
readonly scopes: readonly string[];
|
|
12
|
+
readonly signingAlgorithm: OidcSigningAlgorithm;
|
|
13
|
+
readonly clientAuthentication: OAuthClientAuthMethod;
|
|
14
|
+
readonly credentialLabel: string;
|
|
15
|
+
readonly credentialCardTarget: string;
|
|
16
|
+
readonly pkce: "S256";
|
|
17
|
+
readonly authoritativeEmailDomains?: readonly string[];
|
|
18
|
+
readonly hostedDomainClaim?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface LoginProvider extends LoginProviderPreset {
|
|
21
|
+
readonly pluginId: string;
|
|
22
|
+
/** Fingerprint binds an in-flight redirect to the current preset and client. */
|
|
23
|
+
readonly configurationVersion: string;
|
|
24
|
+
}
|
|
25
|
+
/** Only completeOidcLogin creates this result after cryptographic verification. No raw tokens. */
|
|
26
|
+
export interface VerifiedLoginIdentity {
|
|
27
|
+
readonly providerId: string;
|
|
28
|
+
readonly issuer: string;
|
|
29
|
+
readonly subject: string;
|
|
30
|
+
readonly email: string;
|
|
31
|
+
readonly emailAuthoritative: boolean;
|
|
32
|
+
}
|
|
33
|
+
export type MemberLoginOutcomeCode = "LOGIN_UNAVAILABLE" | "LOGIN_INVALID" | "LOGIN_BLOCKED" | "LOGIN_CONFLICT";
|
|
34
|
+
/** Fixed codes are safe for routes/logging; upstream OAuth exceptions can contain sensitive data. */
|
|
35
|
+
export declare class MemberLoginError extends Error {
|
|
36
|
+
readonly code: MemberLoginOutcomeCode;
|
|
37
|
+
constructor(required: {
|
|
38
|
+
code: MemberLoginOutcomeCode;
|
|
39
|
+
}, _options?: Record<string, never>);
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=login-types.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Fixed codes are safe for routes/logging; upstream OAuth exceptions can contain sensitive data. */
|
|
2
|
+
export class MemberLoginError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(required, _options = {}) {
|
|
5
|
+
super(required.code);
|
|
6
|
+
this.code = required.code;
|
|
7
|
+
this.name = "MemberLoginError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=login-types.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { PasskeyPort } from './passkey-ports.js';
|
|
2
|
+
/** SimpleWebAuthn owns RP/origin/signature/UV and authenticator-counter validation.
|
|
3
|
+
* @complexity O(n) option generation for at most five credentials; bounded verification payloads.
|
|
4
|
+
*/
|
|
5
|
+
export declare function createSimpleWebAuthnPasskeys(_required: Record<string, never>, _options?: Record<string, never>): PasskeyPort;
|
|
6
|
+
//# sourceMappingURL=passkey-adapter.d.ts.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { generateRegistrationOptions, generateAuthenticationOptions, verifyRegistrationResponse, verifyAuthenticationResponse } from '@simplewebauthn/server';
|
|
3
|
+
/** SimpleWebAuthn owns RP/origin/signature/UV and authenticator-counter validation.
|
|
4
|
+
* @complexity O(n) option generation for at most five credentials; bounded verification payloads.
|
|
5
|
+
*/
|
|
6
|
+
export function createSimpleWebAuthnPasskeys(_required, _options = {}) {
|
|
7
|
+
return {
|
|
8
|
+
registration: async ({ site, scope, credentials }) => ({ ...await generateRegistrationOptions({
|
|
9
|
+
rpName: site.name, rpID: site.rpId, userName: 'Owner',
|
|
10
|
+
userID: new Uint8Array(createHash('sha256').update(JSON.stringify([scope.workspaceId, scope.principalId])).digest()),
|
|
11
|
+
attestationType: 'none', excludeCredentials: credentials.map(({ id }) => ({ id })),
|
|
12
|
+
authenticatorSelection: { userVerification: 'required', residentKey: 'discouraged' },
|
|
13
|
+
}) }),
|
|
14
|
+
authentication: async ({ site, credentials }) => ({ ...await generateAuthenticationOptions({
|
|
15
|
+
rpID: site.rpId, userVerification: 'required', allowCredentials: credentials.map(({ id }) => ({ id })),
|
|
16
|
+
}) }),
|
|
17
|
+
register: async ({ site, response, challenge }) => {
|
|
18
|
+
const result = await verifyRegistrationResponse({ response: response,
|
|
19
|
+
expectedChallenge: challenge, expectedOrigin: site.origin, expectedRPID: site.rpId, requireUserVerification: true });
|
|
20
|
+
if (!result.verified || !result.registrationInfo)
|
|
21
|
+
throw new Error('Passkey registration was not verified');
|
|
22
|
+
const { credential } = result.registrationInfo;
|
|
23
|
+
return { id: credential.id, publicKey: Buffer.from(credential.publicKey).toString('base64url'), counter: credential.counter };
|
|
24
|
+
},
|
|
25
|
+
authenticate: async ({ site, response, challenge, credential }) => {
|
|
26
|
+
const result = await verifyAuthenticationResponse({ response: response,
|
|
27
|
+
expectedChallenge: challenge, expectedOrigin: site.origin, expectedRPID: site.rpId, requireUserVerification: true,
|
|
28
|
+
credential: { id: credential.id, publicKey: new Uint8Array(Buffer.from(credential.publicKey, 'base64url')), counter: credential.counter } });
|
|
29
|
+
if (!result.verified)
|
|
30
|
+
throw new Error('Passkey assertion was not verified');
|
|
31
|
+
return result.authenticationInfo.newCounter;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=passkey-adapter.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { MfaScope, OwnerMfaDeps } from './ports.js';
|
|
2
|
+
import type { PasskeyOptions } from '../../core/types.js';
|
|
3
|
+
export type { PasskeyOptions } from '../../core/types.js';
|
|
4
|
+
export type PasskeyCredential = MfaScope & {
|
|
5
|
+
id: string;
|
|
6
|
+
publicKey: string;
|
|
7
|
+
counter: number;
|
|
8
|
+
rpId: string;
|
|
9
|
+
};
|
|
10
|
+
/** Methods join the same serialized identity transaction as MFA/session writes. */
|
|
11
|
+
export interface PasskeyStore {
|
|
12
|
+
list(scope: MfaScope): Promise<PasskeyCredential[]>;
|
|
13
|
+
save(credential: PasskeyCredential): Promise<void>;
|
|
14
|
+
remove(input: MfaScope & {
|
|
15
|
+
id: string;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
clear(scope: MfaScope): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export type PasskeySite = {
|
|
20
|
+
origin: string;
|
|
21
|
+
rpId: string;
|
|
22
|
+
name: string;
|
|
23
|
+
};
|
|
24
|
+
/** Protocol verification belongs to a maintained WebAuthn implementation, never the service. */
|
|
25
|
+
export interface PasskeyPort {
|
|
26
|
+
registration(input: {
|
|
27
|
+
site: PasskeySite;
|
|
28
|
+
scope: MfaScope;
|
|
29
|
+
credentials: PasskeyCredential[];
|
|
30
|
+
}): Promise<PasskeyOptions>;
|
|
31
|
+
authentication(input: {
|
|
32
|
+
site: PasskeySite;
|
|
33
|
+
credentials: PasskeyCredential[];
|
|
34
|
+
}): Promise<PasskeyOptions>;
|
|
35
|
+
register(input: {
|
|
36
|
+
site: PasskeySite;
|
|
37
|
+
response: unknown;
|
|
38
|
+
challenge: string;
|
|
39
|
+
}): Promise<{
|
|
40
|
+
id: string;
|
|
41
|
+
publicKey: string;
|
|
42
|
+
counter: number;
|
|
43
|
+
}>;
|
|
44
|
+
authenticate(input: {
|
|
45
|
+
site: PasskeySite;
|
|
46
|
+
response: unknown;
|
|
47
|
+
challenge: string;
|
|
48
|
+
credential: PasskeyCredential;
|
|
49
|
+
}): Promise<number>;
|
|
50
|
+
}
|
|
51
|
+
export type OwnerPasskeyDeps = {
|
|
52
|
+
mfa: OwnerMfaDeps;
|
|
53
|
+
credentials: PasskeyStore;
|
|
54
|
+
webauthn: PasskeyPort;
|
|
55
|
+
site: PasskeySite;
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=passkey-ports.d.ts.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { MfaScope } from './ports.js';
|
|
2
|
+
import type { OwnerPasskeyDeps } from './passkey-ports.js';
|
|
3
|
+
type Required<T> = {
|
|
4
|
+
deps: OwnerPasskeyDeps;
|
|
5
|
+
input: T;
|
|
6
|
+
};
|
|
7
|
+
type Empty = Record<string, never>;
|
|
8
|
+
/** Registration requires a fresh owner password and existing TOTP factor; fallback stays available.
|
|
9
|
+
* @complexity O(n), n <= 5 stored credentials; one challenge write, no polling.
|
|
10
|
+
*/
|
|
11
|
+
export declare function beginOwnerPasskeyEnrollment(required: Required<MfaScope & {
|
|
12
|
+
password: string;
|
|
13
|
+
code: string;
|
|
14
|
+
}>, _options?: Empty): Promise<{
|
|
15
|
+
pendingToken: string;
|
|
16
|
+
options: import("./passkey-ports.js").PasskeyOptions;
|
|
17
|
+
}>;
|
|
18
|
+
/** Complete a same-owner registration once; a failed library proof writes no credential. O(1). */
|
|
19
|
+
export declare function confirmOwnerPasskeyEnrollment(required: Required<MfaScope & {
|
|
20
|
+
pendingToken: string;
|
|
21
|
+
response: unknown;
|
|
22
|
+
}>, _options?: Empty): Promise<void>;
|
|
23
|
+
/** Begin an alternative second factor, preserving the original TOTP proof for cancellation/fallback.
|
|
24
|
+
* @complexity O(n), n <= 5 credentials; one added pending write per explicit attempt.
|
|
25
|
+
*/
|
|
26
|
+
export declare function beginOwnerPasskeyLogin(required: Required<{
|
|
27
|
+
workspaceId: string;
|
|
28
|
+
pendingToken: string;
|
|
29
|
+
}>, _options?: Empty): Promise<{
|
|
30
|
+
pendingToken: string;
|
|
31
|
+
options: import("./passkey-ports.js").PasskeyOptions;
|
|
32
|
+
}>;
|
|
33
|
+
/** Counter, challenge consumption and session mint share one transaction; rollback grants nothing.
|
|
34
|
+
* @complexity O(n), n <= 5 credentials; fixed identity reads/writes plus existing session persistence.
|
|
35
|
+
*/
|
|
36
|
+
export declare function completeOwnerPasskeyLogin(required: Required<{
|
|
37
|
+
workspaceId: string;
|
|
38
|
+
pendingToken: string;
|
|
39
|
+
response: unknown;
|
|
40
|
+
}>, options?: {
|
|
41
|
+
sessionTtlMs?: number;
|
|
42
|
+
ip?: string;
|
|
43
|
+
userAgent?: string;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
session: import("../../core/types.js").SessionRecord;
|
|
46
|
+
rawToken: string;
|
|
47
|
+
principal: import("../../core/types.js").PrincipalRecord;
|
|
48
|
+
}>;
|
|
49
|
+
/** Removing a key requires current owner password and TOTP; sessions cannot authorize it alone. O(1). */
|
|
50
|
+
export declare function removeOwnerPasskey(required: Required<MfaScope & {
|
|
51
|
+
id: string;
|
|
52
|
+
password: string;
|
|
53
|
+
code: string;
|
|
54
|
+
}>, _options?: Empty): Promise<void>;
|
|
55
|
+
export {};
|
|
56
|
+
//# sourceMappingURL=passkey-service.d.ts.map
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { IdentityValidationError } from '../../core/types.js';
|
|
2
|
+
import { createSessionForPrincipal } from '../auth-service.js';
|
|
3
|
+
import { inIdentityTransaction } from '../identity-transaction.js';
|
|
4
|
+
import { requireRecentOwnerAuthentication } from './service.js';
|
|
5
|
+
const refused = () => new IdentityValidationError({ message: 'This passkey attempt was not accepted or has expired. Start a new attempt, or use your authenticator app or recovery code.' });
|
|
6
|
+
const transaction = (deps, workspaceId, execute) => inIdentityTransaction({ transactions: deps.mfa.auth.repos.transactions, workspaceId, execute });
|
|
7
|
+
const hash = (deps, token) => deps.mfa.auth.tokens.hashToken({ rawToken: token });
|
|
8
|
+
/** Persist a purpose-bound, sealed challenge in the existing bounded pending-proof store. O(1). */
|
|
9
|
+
async function saveChallenge(deps, scope, purpose, data) {
|
|
10
|
+
const pendingToken = deps.mfa.auth.tokens.newToken({});
|
|
11
|
+
const sealedSecret = await deps.mfa.secrets.seal({ ...scope, secret: JSON.stringify(data) });
|
|
12
|
+
await deps.mfa.store.savePending({ ...scope, purpose, sealedSecret, tokenHash: hash(deps, pendingToken),
|
|
13
|
+
expiresAt: deps.mfa.auth.clock.nowMs() + 300000, attempts: 0 });
|
|
14
|
+
return pendingToken;
|
|
15
|
+
}
|
|
16
|
+
/** Spend once before protocol verification; failed ceremonies stay spent after commit. O(1). */
|
|
17
|
+
async function claim(deps, input, purpose) {
|
|
18
|
+
const proof = await deps.mfa.store.pending({ workspaceId: input.workspaceId, tokenHash: hash(deps, input.pendingToken) });
|
|
19
|
+
if (!proof || proof.purpose !== purpose || !proof.sealedSecret)
|
|
20
|
+
return null;
|
|
21
|
+
if (proof.expiresAt <= deps.mfa.auth.clock.nowMs() || proof.attempts !== 0)
|
|
22
|
+
return null;
|
|
23
|
+
await deps.mfa.store.savePending({ ...proof, attempts: 5 });
|
|
24
|
+
const data = JSON.parse(await deps.mfa.secrets.open({ ...proof, sealedSecret: proof.sealedSecret }));
|
|
25
|
+
if (data.origin !== deps.site.origin || data.rpId !== deps.site.rpId)
|
|
26
|
+
return null;
|
|
27
|
+
return { proof, data };
|
|
28
|
+
}
|
|
29
|
+
/** Registration requires a fresh owner password and existing TOTP factor; fallback stays available.
|
|
30
|
+
* @complexity O(n), n <= 5 stored credentials; one challenge write, no polling.
|
|
31
|
+
*/
|
|
32
|
+
export async function beginOwnerPasskeyEnrollment(required, _options = {}) {
|
|
33
|
+
const { deps, input } = required;
|
|
34
|
+
return transaction(deps, input.workspaceId, async () => {
|
|
35
|
+
await requireRecentOwnerAuthentication({ deps: deps.mfa, input });
|
|
36
|
+
if (!await deps.mfa.store.factor(input))
|
|
37
|
+
throw new IdentityValidationError({ message: 'Set up your authenticator app before adding a passkey so you retain a sign-in fallback.' });
|
|
38
|
+
const credentials = await deps.credentials.list(input);
|
|
39
|
+
if (credentials.length >= 5)
|
|
40
|
+
throw new IdentityValidationError({ message: 'Five passkeys are already registered. Remove one before adding another.' });
|
|
41
|
+
const options = await deps.webauthn.registration({ site: deps.site, scope: input, credentials });
|
|
42
|
+
const pendingToken = await saveChallenge(deps, input, 'passkey-enroll', { challenge: options.challenge, origin: deps.site.origin, rpId: deps.site.rpId });
|
|
43
|
+
return { pendingToken, options };
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** Complete a same-owner registration once; a failed library proof writes no credential. O(1). */
|
|
47
|
+
export async function confirmOwnerPasskeyEnrollment(required, _options = {}) {
|
|
48
|
+
const { deps, input } = required;
|
|
49
|
+
const accepted = await transaction(deps, input.workspaceId, async () => {
|
|
50
|
+
const claimed = await claim(deps, input, 'passkey-enroll');
|
|
51
|
+
if (!claimed || claimed.proof.principalId !== input.principalId)
|
|
52
|
+
return false;
|
|
53
|
+
if (!await deps.mfa.store.factor(input))
|
|
54
|
+
return false;
|
|
55
|
+
const credentials = await deps.credentials.list(input);
|
|
56
|
+
if (credentials.length >= 5)
|
|
57
|
+
return false;
|
|
58
|
+
let credential;
|
|
59
|
+
try {
|
|
60
|
+
credential = await deps.webauthn.register({ site: deps.site, response: input.response, challenge: claimed.data.challenge });
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
// Exclusion hints are not a server-side ownership/counter guard: refuse re-registration.
|
|
66
|
+
if (credentials.some(existing => existing.id === credential.id))
|
|
67
|
+
return false;
|
|
68
|
+
await deps.credentials.save({ workspaceId: input.workspaceId, principalId: input.principalId, ...credential, rpId: deps.site.rpId });
|
|
69
|
+
return true;
|
|
70
|
+
});
|
|
71
|
+
if (!accepted)
|
|
72
|
+
throw refused();
|
|
73
|
+
}
|
|
74
|
+
/** Accept only the password-created owner login proof; never discover accounts from passkeys. O(1). */
|
|
75
|
+
async function loginProof(deps, workspaceId, tokenHash) {
|
|
76
|
+
if (!tokenHash)
|
|
77
|
+
return null;
|
|
78
|
+
const proof = await deps.mfa.store.pending({ workspaceId, tokenHash });
|
|
79
|
+
if (!proof || proof.purpose !== 'login' || proof.principalId !== deps.mfa.seededOwnerPrincipalId)
|
|
80
|
+
return null;
|
|
81
|
+
if (proof.expiresAt <= deps.mfa.auth.clock.nowMs() || proof.attempts >= 5)
|
|
82
|
+
return null;
|
|
83
|
+
return proof;
|
|
84
|
+
}
|
|
85
|
+
/** Begin an alternative second factor, preserving the original TOTP proof for cancellation/fallback.
|
|
86
|
+
* @complexity O(n), n <= 5 credentials; one added pending write per explicit attempt.
|
|
87
|
+
*/
|
|
88
|
+
export async function beginOwnerPasskeyLogin(required, _options = {}) {
|
|
89
|
+
const { deps, input } = required;
|
|
90
|
+
return transaction(deps, input.workspaceId, async () => {
|
|
91
|
+
const proof = await loginProof(deps, input.workspaceId, hash(deps, input.pendingToken));
|
|
92
|
+
if (!proof)
|
|
93
|
+
throw refused();
|
|
94
|
+
const credentials = (await deps.credentials.list(proof)).filter(c => c.rpId === deps.site.rpId);
|
|
95
|
+
if (!credentials.length)
|
|
96
|
+
throw new IdentityValidationError({ message: 'No passkey is registered for this site. Use your authenticator app or recovery code.' });
|
|
97
|
+
const options = await deps.webauthn.authentication({ site: deps.site, credentials });
|
|
98
|
+
const pendingToken = await saveChallenge(deps, proof, 'passkey-login', { challenge: options.challenge,
|
|
99
|
+
origin: deps.site.origin, rpId: deps.site.rpId, loginHash: proof.tokenHash });
|
|
100
|
+
return { pendingToken, options };
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** Verify only a credential owned by this exact site/owner; library handles zero/nonzero counters. */
|
|
104
|
+
async function verifyAssertion(deps, proof, data, response) {
|
|
105
|
+
const credentialId = response?.id;
|
|
106
|
+
const credential = (await deps.credentials.list(proof)).find(c => c.id === credentialId && c.rpId === deps.site.rpId);
|
|
107
|
+
if (!credential)
|
|
108
|
+
return null;
|
|
109
|
+
try {
|
|
110
|
+
return { credential, counter: await deps.webauthn.authenticate({ site: deps.site, response, challenge: data.challenge, credential }) };
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Counter, challenge consumption and session mint share one transaction; rollback grants nothing.
|
|
117
|
+
* @complexity O(n), n <= 5 credentials; fixed identity reads/writes plus existing session persistence.
|
|
118
|
+
*/
|
|
119
|
+
export async function completeOwnerPasskeyLogin(required, options = {}) {
|
|
120
|
+
const { deps, input } = required;
|
|
121
|
+
const result = await transaction(deps, input.workspaceId, async () => {
|
|
122
|
+
const claimed = await claim(deps, input, 'passkey-login');
|
|
123
|
+
if (!claimed)
|
|
124
|
+
return null;
|
|
125
|
+
const proof = await loginProof(deps, input.workspaceId, claimed.data.loginHash);
|
|
126
|
+
if (!proof || proof.principalId !== claimed.proof.principalId)
|
|
127
|
+
return null;
|
|
128
|
+
const principal = await deps.mfa.auth.repos.principals.findById({ workspaceId: proof.workspaceId, id: proof.principalId });
|
|
129
|
+
if (principal?.kind !== 'user' || principal.status !== 'active')
|
|
130
|
+
return null;
|
|
131
|
+
const user = await deps.mfa.auth.repos.users.findByPrincipalId({ workspaceId: proof.workspaceId, principalId: proof.principalId });
|
|
132
|
+
if (!user)
|
|
133
|
+
return null;
|
|
134
|
+
const verified = await verifyAssertion(deps, proof, claimed.data, input.response);
|
|
135
|
+
if (!verified)
|
|
136
|
+
return null;
|
|
137
|
+
await deps.credentials.save({ ...verified.credential, counter: verified.counter });
|
|
138
|
+
await deps.mfa.store.clearPending(proof);
|
|
139
|
+
const session = await createSessionForPrincipal({ deps: deps.mfa.auth, input: proof }, options);
|
|
140
|
+
await deps.mfa.auth.repos.users.save({ ...user, lastLoginAt: session.session.createdAt });
|
|
141
|
+
return { principal, ...session };
|
|
142
|
+
});
|
|
143
|
+
if (!result)
|
|
144
|
+
throw refused();
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
/** Removing a key requires current owner password and TOTP; sessions cannot authorize it alone. O(1). */
|
|
148
|
+
export async function removeOwnerPasskey(required, _options = {}) {
|
|
149
|
+
const { deps, input } = required;
|
|
150
|
+
await transaction(deps, input.workspaceId, async () => {
|
|
151
|
+
await requireRecentOwnerAuthentication({ deps: deps.mfa, input });
|
|
152
|
+
await deps.credentials.remove(input);
|
|
153
|
+
await deps.mfa.store.clearPending(input);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=passkey-service.js.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { AuthServiceDeps } from '../auth-service.js';
|
|
2
|
+
export type MfaScope = {
|
|
3
|
+
workspaceId: string;
|
|
4
|
+
principalId: string;
|
|
5
|
+
};
|
|
6
|
+
export type MfaFactor = MfaScope & {
|
|
7
|
+
sealedSecret: string;
|
|
8
|
+
lastStep: number;
|
|
9
|
+
};
|
|
10
|
+
export type MfaPending = MfaScope & {
|
|
11
|
+
purpose: 'login' | 'enroll' | 'passkey-enroll' | 'passkey-login';
|
|
12
|
+
tokenHash: string;
|
|
13
|
+
expiresAt: number;
|
|
14
|
+
attempts: number;
|
|
15
|
+
sealedSecret?: string;
|
|
16
|
+
};
|
|
17
|
+
/** All methods join auth.repos.transactions; at most one pending row per scope/purpose.
|
|
18
|
+
* Mutations and guard reads must serialize with all other identity writers.
|
|
19
|
+
*/
|
|
20
|
+
export interface MfaStore {
|
|
21
|
+
factor(scope: MfaScope): Promise<MfaFactor | null>;
|
|
22
|
+
saveFactor(factor: MfaFactor): Promise<void>;
|
|
23
|
+
pending(input: {
|
|
24
|
+
workspaceId: string;
|
|
25
|
+
tokenHash: string;
|
|
26
|
+
}): Promise<MfaPending | null>;
|
|
27
|
+
savePending(pending: MfaPending): Promise<void>;
|
|
28
|
+
clearPending(scope: MfaScope): Promise<void>;
|
|
29
|
+
clear(scope: MfaScope): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/** A library adapter implements protocol crypto; accepted step enables replay prevention. */
|
|
32
|
+
export interface TotpPort {
|
|
33
|
+
generate(): string;
|
|
34
|
+
uri(input: {
|
|
35
|
+
secret: string;
|
|
36
|
+
label: string;
|
|
37
|
+
issuer: string;
|
|
38
|
+
}): string;
|
|
39
|
+
verify(input: {
|
|
40
|
+
secret: string;
|
|
41
|
+
code: string;
|
|
42
|
+
nowMs: number;
|
|
43
|
+
}): Promise<number | null>;
|
|
44
|
+
}
|
|
45
|
+
/** Sealing adapters MUST authenticate the supplied workspace/principal context as AAD. */
|
|
46
|
+
export interface MfaSecretPort {
|
|
47
|
+
seal(input: MfaScope & {
|
|
48
|
+
secret: string;
|
|
49
|
+
}): Promise<string>;
|
|
50
|
+
open(input: MfaScope & {
|
|
51
|
+
sealedSecret: string;
|
|
52
|
+
}): Promise<string>;
|
|
53
|
+
}
|
|
54
|
+
export interface OwnerMfaDeps {
|
|
55
|
+
auth: AuthServiceDeps;
|
|
56
|
+
store: MfaStore;
|
|
57
|
+
totp: TotpPort;
|
|
58
|
+
secrets: MfaSecretPort;
|
|
59
|
+
seededOwnerPrincipalId: string;
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=ports.d.ts.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { MfaSecretPort } from './ports.js';
|
|
2
|
+
type Key = {
|
|
3
|
+
readonly keyId: string;
|
|
4
|
+
};
|
|
5
|
+
/** Reuse a host's authenticated sealer; never derive or store a separate MFA key.
|
|
6
|
+
* @complexity O(1), one key lookup/seal or open per explicit action; bounded secret envelopes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createSealedMfaSecrets<Envelope>(required: {
|
|
9
|
+
keyring: {
|
|
10
|
+
activeKey(input: Record<string, never>): Promise<Key>;
|
|
11
|
+
};
|
|
12
|
+
sealer: {
|
|
13
|
+
seal(input: {
|
|
14
|
+
plaintext: string;
|
|
15
|
+
key: Key;
|
|
16
|
+
aad: string;
|
|
17
|
+
}): Promise<Envelope>;
|
|
18
|
+
open(input: {
|
|
19
|
+
sealed: Envelope;
|
|
20
|
+
}, options: {
|
|
21
|
+
aad: string;
|
|
22
|
+
}): Promise<string>;
|
|
23
|
+
};
|
|
24
|
+
}, _options?: Record<string, never>): MfaSecretPort;
|
|
25
|
+
export {};
|
|
26
|
+
//# sourceMappingURL=secret-adapter.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Reuse a host's authenticated sealer; never derive or store a separate MFA key.
|
|
2
|
+
* @complexity O(1), one key lookup/seal or open per explicit action; bounded secret envelopes.
|
|
3
|
+
*/
|
|
4
|
+
export function createSealedMfaSecrets(required, _options = {}) {
|
|
5
|
+
const aad = (scope) => JSON.stringify(['owner-totp-v1', scope.workspaceId, scope.principalId]);
|
|
6
|
+
return {
|
|
7
|
+
seal: async (input) => JSON.stringify(await required.sealer.seal({ plaintext: input.secret,
|
|
8
|
+
key: await required.keyring.activeKey({}), aad: aad(input) })),
|
|
9
|
+
open: input => required.sealer.open({ sealed: JSON.parse(input.sealedSecret) }, { aad: aad(input) }),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=secret-adapter.js.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { MfaScope, OwnerMfaDeps } from './ports.js';
|
|
2
|
+
type Required<T> = {
|
|
3
|
+
deps: OwnerMfaDeps;
|
|
4
|
+
input: T;
|
|
5
|
+
};
|
|
6
|
+
type Options = Record<string, never>;
|
|
7
|
+
type SessionOptions = {
|
|
8
|
+
ip?: string | undefined;
|
|
9
|
+
userAgent?: string | undefined;
|
|
10
|
+
sessionTtlMs?: number | undefined;
|
|
11
|
+
};
|
|
12
|
+
/** Verify and spend an existing factor in the caller's identity transaction. O(1) bounded I/O. */
|
|
13
|
+
export declare function requireOwnerFactor(required: Required<MfaScope & {
|
|
14
|
+
code?: string;
|
|
15
|
+
}>, _options?: Options): Promise<void>;
|
|
16
|
+
/** Password is checked afresh for every management action; sessions alone are insufficient. */
|
|
17
|
+
export declare function requireRecentOwnerAuthentication(required: Required<MfaScope & {
|
|
18
|
+
password: string;
|
|
19
|
+
code?: string;
|
|
20
|
+
}>): Promise<void>;
|
|
21
|
+
/** Credential verification happens before this trusted-principal boundary (including launcher proof).
|
|
22
|
+
* O(1): one factor read and one pending/session write; no polling.
|
|
23
|
+
*/
|
|
24
|
+
export declare function beginPrincipalSignIn(required: Required<MfaScope>, options?: SessionOptions): Promise<{
|
|
25
|
+
mfaRequired: true;
|
|
26
|
+
pendingToken: string;
|
|
27
|
+
} | {
|
|
28
|
+
session: import("../../core/types.js").SessionRecord;
|
|
29
|
+
rawToken: string;
|
|
30
|
+
principal: import("../../core/types.js").PrincipalRecord;
|
|
31
|
+
}>;
|
|
32
|
+
/** Password proof alone never mints an enrolled owner's session. O(1) identity reads/writes. */
|
|
33
|
+
export declare function beginOwnerLogin(required: Required<{
|
|
34
|
+
workspaceId: string;
|
|
35
|
+
username: string;
|
|
36
|
+
password: string;
|
|
37
|
+
}>, options?: SessionOptions): Promise<{
|
|
38
|
+
mfaRequired: true;
|
|
39
|
+
pendingToken: string;
|
|
40
|
+
} | {
|
|
41
|
+
session: import("../../core/types.js").SessionRecord;
|
|
42
|
+
rawToken: string;
|
|
43
|
+
principal: import("../../core/types.js").PrincipalRecord;
|
|
44
|
+
}>;
|
|
45
|
+
/** Atomically advance timestep, consume proofs and mint the only authorized session. O(1). */
|
|
46
|
+
export declare function completeOwnerLogin(required: Required<{
|
|
47
|
+
workspaceId: string;
|
|
48
|
+
pendingToken: string;
|
|
49
|
+
code: string;
|
|
50
|
+
}>, options?: SessionOptions): Promise<{
|
|
51
|
+
session: import("../../core/types.js").SessionRecord;
|
|
52
|
+
rawToken: string;
|
|
53
|
+
principal: import("../../core/types.js").PrincipalRecord;
|
|
54
|
+
}>;
|
|
55
|
+
/** Activation requires a later proof; the new secret is sealed with principal/workspace AAD. O(1). */
|
|
56
|
+
export declare function beginOwnerEnrollment(required: Required<MfaScope & {
|
|
57
|
+
password: string;
|
|
58
|
+
code?: string;
|
|
59
|
+
label: string;
|
|
60
|
+
issuer: string;
|
|
61
|
+
}>, _options?: Options): Promise<{
|
|
62
|
+
pendingToken: string;
|
|
63
|
+
secret: string;
|
|
64
|
+
uri: string;
|
|
65
|
+
}>;
|
|
66
|
+
/** Same-owner confirmation activates once and invalidates pending logins and older sessions. */
|
|
67
|
+
export declare function confirmOwnerEnrollment(required: Required<MfaScope & {
|
|
68
|
+
pendingToken: string;
|
|
69
|
+
code: string;
|
|
70
|
+
}>, _options?: Options): Promise<void>;
|
|
71
|
+
/** Removal needs both current factors, and revokes sessions/proofs atomically. O(s). */
|
|
72
|
+
export declare function removeOwnerFactor(required: Required<MfaScope & {
|
|
73
|
+
password: string;
|
|
74
|
+
code: string;
|
|
75
|
+
}>, _options?: Options): Promise<void>;
|
|
76
|
+
export {};
|
|
77
|
+
//# sourceMappingURL=service.d.ts.map
|