@jini-ai/user-management 0.6.19 → 0.7.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/core/types.d.ts +5 -0
  3. package/dist/react/auth/Login.js +5 -3
  4. package/dist/react/auth/Passkeys.d.ts +54 -0
  5. package/dist/react/auth/Passkeys.js +77 -0
  6. package/dist/react/auth/TotpSettings.d.ts +32 -0
  7. package/dist/react/auth/TotpSettings.js +93 -0
  8. package/dist/react/auth/hooks/use-login.hooks.d.ts +6 -0
  9. package/dist/react/auth/hooks/use-login.hooks.js +22 -3
  10. package/dist/react/auth/passkey-browser.d.ts +9 -0
  11. package/dist/react/auth/passkey-browser.js +19 -0
  12. package/dist/react/index.d.ts +5 -0
  13. package/dist/react/index.js +3 -0
  14. package/dist/react/ports.d.ts +9 -0
  15. package/dist/server/admin-crud-service.js +2 -0
  16. package/dist/server/auth-service.d.ts +19 -1
  17. package/dist/server/auth-service.js +20 -10
  18. package/dist/server/index.d.ts +11 -0
  19. package/dist/server/index.js +11 -0
  20. package/dist/server/login-providers.d.ts +15 -0
  21. package/dist/server/login-providers.js +67 -0
  22. package/dist/server/login-types.d.ts +41 -0
  23. package/dist/server/login-types.js +10 -0
  24. package/dist/server/mfa/passkey-adapter.d.ts +6 -0
  25. package/dist/server/mfa/passkey-adapter.js +35 -0
  26. package/dist/server/mfa/passkey-ports.d.ts +57 -0
  27. package/dist/server/mfa/passkey-ports.js +2 -0
  28. package/dist/server/mfa/passkey-service.d.ts +56 -0
  29. package/dist/server/mfa/passkey-service.js +156 -0
  30. package/dist/server/mfa/ports.d.ts +61 -0
  31. package/dist/server/mfa/ports.js +2 -0
  32. package/dist/server/mfa/secret-adapter.d.ts +26 -0
  33. package/dist/server/mfa/secret-adapter.js +12 -0
  34. package/dist/server/mfa/service.d.ts +77 -0
  35. package/dist/server/mfa/service.js +146 -0
  36. package/dist/server/mfa/totp-adapter.d.ts +6 -0
  37. package/dist/server/mfa/totp-adapter.js +18 -0
  38. package/dist/server/owner-reset-input.d.ts +23 -0
  39. package/dist/server/owner-reset-input.js +42 -0
  40. package/dist/server/recovery-codes.d.ts +62 -0
  41. package/dist/server/recovery-codes.js +95 -0
  42. package/package.json +24 -21
@@ -0,0 +1,146 @@
1
+ import { IdentityValidationError, OwnerRequiredError } from '../../core/types.js';
2
+ import { createSessionForPrincipal, verifyCredentials } from '../auth-service.js';
3
+ import { defaultUserManagementMessages } from '../messages.js';
4
+ import { inIdentityTransaction } from '../identity-transaction.js';
5
+ const refused = () => new IdentityValidationError({ message: 'The authenticator code was not accepted or has expired. Enter a fresh code, or sign in again to start a new attempt.' });
6
+ const transaction = (deps, workspaceId, execute) => inIdentityTransaction({ transactions: deps.auth.repos.transactions, workspaceId, execute });
7
+ /** Prove the server-selected owner, never a staff/member identity. O(1), two identity reads. */
8
+ async function owner(deps, scope) {
9
+ const principal = await deps.auth.repos.principals.findById({ workspaceId: scope.workspaceId, id: scope.principalId });
10
+ const user = await deps.auth.repos.users.findByPrincipalId({ workspaceId: scope.workspaceId, principalId: scope.principalId });
11
+ if (scope.principalId !== deps.seededOwnerPrincipalId || principal?.kind !== 'user' || principal.status !== 'active' || !user) {
12
+ throw new OwnerRequiredError({ message: 'Only the active site owner can change this authenticator. Sign in as the owner and try again.' });
13
+ }
14
+ return { principal, user };
15
+ }
16
+ /** Verify and spend an existing factor in the caller's identity transaction. O(1) bounded I/O. */
17
+ export async function requireOwnerFactor(required, _options = {}) {
18
+ const { deps, input } = required;
19
+ const factor = await deps.store.factor(input);
20
+ if (!factor)
21
+ return;
22
+ const secret = await deps.secrets.open(factor);
23
+ const step = await deps.totp.verify({ secret, code: input.code ?? '', nowMs: deps.auth.clock.nowMs() });
24
+ if (step === null || step <= factor.lastStep)
25
+ throw refused();
26
+ await deps.store.saveFactor({ ...factor, lastStep: step });
27
+ }
28
+ /** Password is checked afresh for every management action; sessions alone are insufficient. */
29
+ export async function requireRecentOwnerAuthentication(required) {
30
+ const { user } = await owner(required.deps, required.input);
31
+ if (!required.input.password || !await required.deps.auth.hasher.verify({ hash: user.passwordHash, password: required.input.password })) {
32
+ throw new IdentityValidationError({ message: 'The current owner password was not accepted. Enter your current password and try again.' });
33
+ }
34
+ await requireOwnerFactor(required);
35
+ }
36
+ /** Replace expired/same-purpose proofs instead of growing an unbounded challenge history. */
37
+ async function pending(deps, scope, purpose, sealedSecret) {
38
+ const pendingToken = deps.auth.tokens.newToken({});
39
+ await deps.store.savePending({ ...scope, purpose, tokenHash: deps.auth.tokens.hashToken({ rawToken: pendingToken }),
40
+ expiresAt: deps.auth.clock.nowMs() + 300000, attempts: 0, ...(sealedSecret === undefined ? {} : { sealedSecret }) });
41
+ return { mfaRequired: true, pendingToken };
42
+ }
43
+ /** Credential verification happens before this trusted-principal boundary (including launcher proof).
44
+ * O(1): one factor read and one pending/session write; no polling.
45
+ */
46
+ export async function beginPrincipalSignIn(required, options = {}) {
47
+ const { deps, input } = required;
48
+ return transaction(deps, input.workspaceId, async () => {
49
+ const principal = await deps.auth.repos.principals.findById({ workspaceId: input.workspaceId, id: input.principalId });
50
+ if (!principal || principal.status !== 'active' || principal.kind !== 'user')
51
+ throw refused();
52
+ if (input.principalId === deps.seededOwnerPrincipalId && await deps.store.factor(input))
53
+ return pending(deps, input, 'login');
54
+ return { principal, ...await createSessionForPrincipal({ deps: deps.auth, input }, options) };
55
+ });
56
+ }
57
+ /** Password proof alone never mints an enrolled owner's session. O(1) identity reads/writes. */
58
+ export async function beginOwnerLogin(required, options = {}) {
59
+ const { deps, input } = required;
60
+ return transaction(deps, input.workspaceId, async () => {
61
+ const { userRow, principal } = await verifyCredentials({ deps: deps.auth, input, invalidCredentialsMessage: defaultUserManagementMessages.invalidCredentials });
62
+ const result = await beginPrincipalSignIn({ deps, input: { workspaceId: input.workspaceId, principalId: principal.id } }, options);
63
+ if ('session' in result)
64
+ await deps.auth.repos.users.save({ ...userRow, lastLoginAt: result.session.createdAt });
65
+ return result;
66
+ });
67
+ }
68
+ /** Pure eligibility check shared by proof consumption; expired/exhausted/wrong-purpose proofs grant nothing. */
69
+ function usableProof(proof, purpose, nowMs) {
70
+ return proof !== null && proof.purpose === purpose && proof.expiresAt > nowMs && proof.attempts < 5;
71
+ }
72
+ /** Spend failed attempts without throwing inside the transaction (throwing would refund them).
73
+ * O(1), one proof read/write and one factor/library verification. Session writes share rollback.
74
+ */
75
+ async function useProof(required, purpose, complete) {
76
+ const { deps, input } = required;
77
+ const result = await transaction(deps, input.workspaceId, async () => {
78
+ const proof = await deps.store.pending({ workspaceId: input.workspaceId, tokenHash: deps.auth.tokens.hashToken({ rawToken: input.pendingToken }) });
79
+ if (!usableProof(proof, purpose, deps.auth.clock.nowMs()))
80
+ return { ok: false };
81
+ await deps.store.savePending({ ...proof, attempts: proof.attempts + 1 });
82
+ const identity = await owner(deps, proof);
83
+ const factor = purpose === 'login' ? await deps.store.factor(proof) : null;
84
+ const sealedSecret = factor?.sealedSecret ?? proof.sealedSecret;
85
+ if (!sealedSecret)
86
+ return { ok: false };
87
+ const secret = await deps.secrets.open({ ...proof, sealedSecret });
88
+ const step = await deps.totp.verify({ secret, code: input.code, nowMs: deps.auth.clock.nowMs() });
89
+ if (step === null || (factor !== null && step <= factor.lastStep))
90
+ return { ok: false };
91
+ return { ok: true, value: await complete(proof, step, { ...identity, factor }) };
92
+ });
93
+ if (!result.ok)
94
+ throw refused();
95
+ return result.value;
96
+ }
97
+ /** Atomically advance timestep, consume proofs and mint the only authorized session. O(1). */
98
+ export async function completeOwnerLogin(required, options = {}) {
99
+ const { deps } = required;
100
+ return useProof(required, 'login', async (proof, step, { factor, principal, user }) => {
101
+ if (!factor)
102
+ throw refused();
103
+ await deps.store.saveFactor({ ...factor, lastStep: step });
104
+ await deps.store.clearPending(proof);
105
+ const result = await createSessionForPrincipal({ deps: deps.auth, input: proof }, options);
106
+ await deps.auth.repos.users.save({ ...user, lastLoginAt: result.session.createdAt });
107
+ return { principal, ...result };
108
+ });
109
+ }
110
+ /** Activation requires a later proof; the new secret is sealed with principal/workspace AAD. O(1). */
111
+ export async function beginOwnerEnrollment(required, _options = {}) {
112
+ const { deps, input } = required;
113
+ return transaction(deps, input.workspaceId, async () => {
114
+ await requireRecentOwnerAuthentication(required);
115
+ const secret = deps.totp.generate();
116
+ const sealedSecret = await deps.secrets.seal({ ...input, secret });
117
+ const result = await pending(deps, input, 'enroll', sealedSecret);
118
+ return { pendingToken: result.pendingToken, secret, uri: deps.totp.uri({ secret, label: input.label, issuer: input.issuer }) };
119
+ });
120
+ }
121
+ /** Revoke existing owner sessions after factor changes. O(s), existing bounded owner sessions. */
122
+ async function revokeSessions(deps, scope) {
123
+ const sessions = await deps.auth.repos.sessions.listByPrincipalId({ workspaceId: scope.workspaceId, principalId: scope.principalId });
124
+ for (const session of sessions)
125
+ await deps.auth.repos.sessions.revoke({ workspaceId: scope.workspaceId, id: session.id, revokedAt: new Date(deps.auth.clock.nowMs()).toISOString() });
126
+ }
127
+ /** Same-owner confirmation activates once and invalidates pending logins and older sessions. */
128
+ export async function confirmOwnerEnrollment(required, _options = {}) {
129
+ await useProof(required, 'enroll', async (proof, step) => {
130
+ if (proof.principalId !== required.input.principalId || !proof.sealedSecret)
131
+ throw refused();
132
+ await required.deps.store.saveFactor({ workspaceId: proof.workspaceId, principalId: proof.principalId, sealedSecret: proof.sealedSecret, lastStep: step });
133
+ await required.deps.store.clearPending(proof);
134
+ await revokeSessions(required.deps, proof);
135
+ });
136
+ }
137
+ /** Removal needs both current factors, and revokes sessions/proofs atomically. O(s). */
138
+ export async function removeOwnerFactor(required, _options = {}) {
139
+ const { deps, input } = required;
140
+ await transaction(deps, input.workspaceId, async () => {
141
+ await requireRecentOwnerAuthentication(required);
142
+ await deps.store.clear(input);
143
+ await revokeSessions(deps, input);
144
+ });
145
+ }
146
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1,6 @@
1
+ import type { TotpPort } from './ports.js';
2
+ /** RFC 6238 via otplib, SHA-1/six digits/30 seconds; one adjacent step allowed for clock drift.
3
+ * @complexity O(1): at most three library HMAC verifications; no I/O or retained secrets.
4
+ */
5
+ export declare function createOtplibTotp(_required: Record<string, never>, _options?: Record<string, never>): TotpPort;
6
+ //# sourceMappingURL=totp-adapter.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { generateSecret, generateURI, verify } from 'otplib';
2
+ /** RFC 6238 via otplib, SHA-1/six digits/30 seconds; one adjacent step allowed for clock drift.
3
+ * @complexity O(1): at most three library HMAC verifications; no I/O or retained secrets.
4
+ */
5
+ export function createOtplibTotp(_required, _options = {}) {
6
+ return {
7
+ generate: () => generateSecret(),
8
+ uri: input => generateURI({ ...input, algorithm: 'sha1', digits: 6, period: 30 }),
9
+ async verify(input) {
10
+ if (!/^\d{6}$/.test(input.code))
11
+ return null;
12
+ const result = await verify({ secret: input.secret, token: input.code, epoch: Math.floor(input.nowMs / 1000),
13
+ algorithm: 'sha1', digits: 6, period: 30, epochTolerance: 30 });
14
+ return result.valid && 'timeStep' in result ? result.timeStep : null;
15
+ },
16
+ };
17
+ }
18
+ //# sourceMappingURL=totp-adapter.js.map
@@ -0,0 +1,23 @@
1
+ /** Read one terminal secret through a muted readline output; never print input or accept argv.
2
+ * @throws On a nonterminal, EOF, Ctrl-C, or input error. Always closes readline to restore raw mode.
3
+ * @complexity O(p) memory/time for p entered characters; password policy bounds the accepted result.
4
+ */
5
+ export declare function readHiddenPassword({ prompt }: {
6
+ prompt: string;
7
+ }, { input, output }?: {
8
+ input?: NodeJS.ReadableStream & {
9
+ isTTY?: boolean;
10
+ };
11
+ output?: Pick<NodeJS.WritableStream, 'write'>;
12
+ }): Promise<string>;
13
+ /** Resolve the host-secret fallback or two hidden prompts; validate before opening a writable store.
14
+ * @throws On mismatch or invalid password. Passwords are preserved exactly as entered.
15
+ * @complexity O(p) for password validation; at most two terminal reads, no database I/O.
16
+ */
17
+ export declare function ownerResetPassword({ env, passwordEnvKey }: {
18
+ env: Readonly<Record<string, string | undefined>>;
19
+ passwordEnvKey: string;
20
+ }, { prompt }?: {
21
+ prompt?: (label: string) => Promise<string>;
22
+ }): Promise<string>;
23
+ //# sourceMappingURL=owner-reset-input.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { Writable } from 'node:stream';
3
+ import { validatePasswordPolicy } from './password-policy.js';
4
+ /** Read one terminal secret through a muted readline output; never print input or accept argv.
5
+ * @throws On a nonterminal, EOF, Ctrl-C, or input error. Always closes readline to restore raw mode.
6
+ * @complexity O(p) memory/time for p entered characters; password policy bounds the accepted result.
7
+ */
8
+ export async function readHiddenPassword({ prompt }, { input = process.stdin, output = process.stderr } = {}) {
9
+ if (!input.isTTY)
10
+ throw new Error('Password input needs a terminal. Run interactively or set the owner reset password in the host secret environment. Details: owner-reset-terminal');
11
+ const muted = new Writable({ write: (_chunk, _encoding, done) => done() });
12
+ const rl = createInterface({ input, output: muted, terminal: true });
13
+ output.write(prompt);
14
+ try {
15
+ return await new Promise((resolve, reject) => {
16
+ const cancelled = () => reject(new Error('Password entry was cancelled. Run the reset command again. Details: owner-reset-input'));
17
+ rl.once('line', resolve);
18
+ rl.once('close', cancelled);
19
+ rl.once('SIGINT', cancelled);
20
+ rl.once('error', reject);
21
+ });
22
+ }
23
+ finally {
24
+ rl.close();
25
+ output.write('\n');
26
+ }
27
+ }
28
+ /** Resolve the host-secret fallback or two hidden prompts; validate before opening a writable store.
29
+ * @throws On mismatch or invalid password. Passwords are preserved exactly as entered.
30
+ * @complexity O(p) for password validation; at most two terminal reads, no database I/O.
31
+ */
32
+ export async function ownerResetPassword({ env, passwordEnvKey }, { prompt = (label) => readHiddenPassword({ prompt: label }) } = {}) {
33
+ const password = env[passwordEnvKey] ?? await prompt('New owner password (not shown): ');
34
+ if (env[passwordEnvKey] === undefined && password !== await prompt('Confirm owner password (not shown): ')) {
35
+ throw new Error('The passwords do not match. Run the reset command again. Details: owner-reset-confirmation');
36
+ }
37
+ const error = validatePasswordPolicy({ password });
38
+ if (error)
39
+ throw new Error(`${error} Run the reset command again. Details: owner-reset-password`);
40
+ return password;
41
+ }
42
+ //# sourceMappingURL=owner-reset-input.js.map
@@ -0,0 +1,62 @@
1
+ import type { OwnerMfaDeps } from './mfa/ports.js';
2
+ import type { AuthServiceDeps } from './auth-service.js';
3
+ type OwnerScope = {
4
+ workspaceId: string;
5
+ principalId: string;
6
+ };
7
+ /** Storage must join auth's identity transaction, including rollback and workspace serialization. */
8
+ export interface RecoveryCodeStore {
9
+ replace(input: OwnerScope & {
10
+ hashes: string[];
11
+ }): Promise<void>;
12
+ contains(input: OwnerScope & {
13
+ hash: string;
14
+ }): Promise<boolean>;
15
+ clear(input: OwnerScope): Promise<void>;
16
+ }
17
+ export interface OwnerRecoveryDeps {
18
+ mfa?: OwnerMfaDeps;
19
+ auth: AuthServiceDeps;
20
+ codes: RecoveryCodeStore;
21
+ seededOwnerPrincipalId: string;
22
+ }
23
+ type Required<Input> = {
24
+ deps: OwnerRecoveryDeps;
25
+ input: Input;
26
+ };
27
+ type Options = Record<string, never>;
28
+ /** Rotate ten 256-bit codes after checking the current password; raw codes leave only in this result.
29
+ * @throws OwnerRequiredError or IdentityValidationError; storage errors roll back the rotation.
30
+ * @complexity O(1): ten entropy/digest operations and one bounded replacement per explicit rotation.
31
+ */
32
+ export declare function issueRecoveryCodes(required: Required<OwnerScope & {
33
+ password: string;
34
+ code?: string;
35
+ }>, _options?: Options): Promise<{
36
+ codes: string[];
37
+ }>;
38
+ /** Trusted host/desktop entry: use only after proving host ownership or an authenticated owner session.
39
+ * Reuses the password transition and proves its write before clearing the kit in the same transaction.
40
+ * @throws OwnerRequiredError or IdentityValidationError; any failure rolls back all writes.
41
+ * @complexity O(s) time/space for the existing reset transition's s owner sessions, plus one kit delete.
42
+ */
43
+ export declare function resetOwnerPassword(required: Required<OwnerScope & {
44
+ password: string;
45
+ }>, _options?: Options): Promise<void>;
46
+ /** Redeem only in its owner/workspace transaction; concurrent redemptions have exactly one winner.
47
+ * @throws IdentityValidationError for an unavailable code; reset failures roll back code consumption.
48
+ * @complexity O(s) for owner sessions; one indexed hash read and at most ten deleted code rows.
49
+ */
50
+ export declare function recoverOwner(required: Required<OwnerScope & {
51
+ code: string;
52
+ password: string;
53
+ }>, _options?: Options): Promise<void>;
54
+ /** Resolve host recovery by the seeded identity, never a default username or a delegated account.
55
+ * @throws OwnerRequiredError for another requested username or an unavailable owner.
56
+ * @complexity O(1), two scoped identity reads; constant memory.
57
+ */
58
+ export declare function resolveOwnerResetTarget(required: Required<OwnerScope & {
59
+ username?: string;
60
+ }>, _options?: Options): Promise<import("../core/types.js").UserRecord>;
61
+ export {};
62
+ //# sourceMappingURL=recovery-codes.d.ts.map
@@ -0,0 +1,95 @@
1
+ import { requireOwnerFactor } from './mfa/service.js';
2
+ import { resetUserPassword } from './admin-crud-service.js';
3
+ import { inIdentityTransaction } from './identity-transaction.js';
4
+ import { IdentityValidationError, OwnerRequiredError } from '../core/types.js';
5
+ /** Refuse staff and inactive identities before any recovery write; never assigns roles.
6
+ * @complexity O(1), two scoped identity reads, constant memory.
7
+ */
8
+ async function requireOwner({ deps, input }) {
9
+ if (input.principalId !== deps.seededOwnerPrincipalId) {
10
+ throw new OwnerRequiredError({ message: 'Only the site owner can recover this account. Sign in as the owner and try again.' });
11
+ }
12
+ const principal = await deps.auth.repos.principals.findById({ workspaceId: input.workspaceId, id: input.principalId });
13
+ const user = await deps.auth.repos.users.findByPrincipalId({ workspaceId: input.workspaceId, principalId: input.principalId });
14
+ if (principal?.kind !== 'user' || principal.status !== 'active' || !user) {
15
+ throw new OwnerRequiredError({ message: 'The owner account is unavailable. Ask the host operator to check the owner account.' });
16
+ }
17
+ return user;
18
+ }
19
+ /** Domain separation prevents a stored digest being useful for another owner, workspace or session.
20
+ * @complexity O(1), bounded code and identity fields; no I/O.
21
+ */
22
+ function codeHash({ deps, input }) {
23
+ return deps.auth.tokens.hashToken({ rawToken: JSON.stringify(['owner-recovery-v1', input.workspaceId, input.principalId, input.code]) });
24
+ }
25
+ /** Rotate ten 256-bit codes after checking the current password; raw codes leave only in this result.
26
+ * @throws OwnerRequiredError or IdentityValidationError; storage errors roll back the rotation.
27
+ * @complexity O(1): ten entropy/digest operations and one bounded replacement per explicit rotation.
28
+ */
29
+ export async function issueRecoveryCodes(required, _options = {}) {
30
+ const { deps, input } = required;
31
+ return inIdentityTransaction({ transactions: deps.auth.repos.transactions, workspaceId: input.workspaceId, execute: async () => {
32
+ const user = await requireOwner(required);
33
+ if (!input.password || !await deps.auth.hasher.verify({ hash: user.passwordHash, password: input.password })) {
34
+ throw new IdentityValidationError({ message: 'The current password was not accepted. Enter your current owner password and try again.' });
35
+ }
36
+ if (await deps.auth.mfaStore?.factor(input)) {
37
+ if (!deps.mfa)
38
+ throw new IdentityValidationError({ message: 'Authenticator verification is unavailable. Reopen the owner security settings and try again.' });
39
+ await requireOwnerFactor({ deps: deps.mfa, input }, {});
40
+ }
41
+ const codes = Array.from({ length: 10 }, () => deps.auth.tokens.newToken({}));
42
+ if (new Set(codes).size !== 10 || codes.some(code => !/^[a-f0-9]{64}$/.test(code))) {
43
+ throw new Error('Recovery code generation failed. Try again after the host operator checks the entropy source. Details: recovery-entropy');
44
+ }
45
+ await deps.codes.replace({ workspaceId: input.workspaceId, principalId: input.principalId, hashes: codes.map(code => codeHash({ deps, input: { ...input, code } })) });
46
+ return { codes };
47
+ } });
48
+ }
49
+ /** Trusted host/desktop entry: use only after proving host ownership or an authenticated owner session.
50
+ * Reuses the password transition and proves its write before clearing the kit in the same transaction.
51
+ * @throws OwnerRequiredError or IdentityValidationError; any failure rolls back all writes.
52
+ * @complexity O(s) time/space for the existing reset transition's s owner sessions, plus one kit delete.
53
+ */
54
+ export async function resetOwnerPassword(required, _options = {}) {
55
+ const { deps, input } = required;
56
+ await inIdentityTransaction({ transactions: deps.auth.repos.transactions, workspaceId: input.workspaceId, execute: async () => {
57
+ await requireOwner(required);
58
+ await resetUserPassword({ deps: deps.auth, input: { ...input, callerPrincipalId: input.principalId, seededOwnerPrincipalId: deps.seededOwnerPrincipalId } });
59
+ const fresh = await deps.auth.repos.users.findByPrincipalId({ workspaceId: input.workspaceId, principalId: input.principalId });
60
+ if (!fresh || !await deps.auth.hasher.verify({ hash: fresh.passwordHash, password: input.password })) {
61
+ throw new Error('The new owner password could not be verified. No recovery changes were saved. Ask the host operator to check password hashing. Details: owner-reset-verification');
62
+ }
63
+ await deps.auth.mfaStore?.clear({ workspaceId: input.workspaceId, principalId: input.principalId });
64
+ await deps.codes.clear({ workspaceId: input.workspaceId, principalId: input.principalId });
65
+ } });
66
+ }
67
+ /** Redeem only in its owner/workspace transaction; concurrent redemptions have exactly one winner.
68
+ * @throws IdentityValidationError for an unavailable code; reset failures roll back code consumption.
69
+ * @complexity O(s) for owner sessions; one indexed hash read and at most ten deleted code rows.
70
+ */
71
+ export async function recoverOwner(required, _options = {}) {
72
+ const { deps, input } = required;
73
+ if (!/^[a-f0-9]{64}$/.test(input.code)) {
74
+ throw new IdentityValidationError({ message: 'The recovery code was not accepted. Use an unused code from your latest download.' });
75
+ }
76
+ await inIdentityTransaction({ transactions: deps.auth.repos.transactions, workspaceId: input.workspaceId, execute: async () => {
77
+ await requireOwner(required);
78
+ if (!await deps.codes.contains({ workspaceId: input.workspaceId, principalId: input.principalId, hash: codeHash(required) })) {
79
+ throw new IdentityValidationError({ message: 'The recovery code was not accepted. Use an unused code from your latest download.' });
80
+ }
81
+ await resetOwnerPassword(required, {});
82
+ } });
83
+ }
84
+ /** Resolve host recovery by the seeded identity, never a default username or a delegated account.
85
+ * @throws OwnerRequiredError for another requested username or an unavailable owner.
86
+ * @complexity O(1), two scoped identity reads; constant memory.
87
+ */
88
+ export async function resolveOwnerResetTarget(required, _options = {}) {
89
+ const owner = await requireOwner(required);
90
+ if (required.input.username !== undefined && required.input.username !== owner.username) {
91
+ throw new OwnerRequiredError({ message: 'That username is not the site owner. Omit the username to recover the current owner account.' });
92
+ }
93
+ return owner;
94
+ }
95
+ //# sourceMappingURL=recovery-codes.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/user-management",
3
- "version": "0.6.19",
3
+ "version": "0.7.0",
4
4
  "description": "Runtime-separated user management contracts and Node authentication, authorization, and administration services.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -96,36 +96,39 @@
96
96
  "registry": "https://registry.npmjs.org"
97
97
  },
98
98
  "dependencies": {
99
- "@jini-ai/core": "^0.6.19"
99
+ "@simplewebauthn/browser": "14.0.0",
100
+ "@simplewebauthn/server": "14.0.3",
101
+ "otplib": "13.6.0",
102
+ "@jini-ai/core": "^0.7.0"
100
103
  },
101
104
  "peerDependencies": {
105
+ "@jini-ai/admin": "^0.7.0",
106
+ "@jini-ai/agentic": "^0.7.0",
107
+ "@jini-ai/ui": "^0.7.0",
108
+ "@jini-ai/ui-kit": "^0.7.0",
102
109
  "argon2": "^0.44.0",
103
110
  "react": "^18.3.0 || ^19.0.0",
104
- "react-dom": "^18.3.0 || ^19.0.0",
105
- "@jini-ai/ui": "^0.6.10",
106
- "@jini-ai/admin": "^0.6.10",
107
- "@jini-ai/agentic": "^0.6.10",
108
- "@jini-ai/ui-kit": "^0.6.10"
111
+ "react-dom": "^18.3.0 || ^19.0.0"
109
112
  },
110
113
  "devDependencies": {
111
- "vitest": "^2.1.0",
112
- "typescript": "^5.6.0",
114
+ "@testing-library/jest-dom": "^6.6.3",
115
+ "@testing-library/react": "^16.3.0",
116
+ "@testing-library/user-event": "^14.5.0",
113
117
  "@types/node": "^24.0.0",
114
- "argon2": "^0.44.0",
115
- "react": "^19.2.0",
116
- "react-dom": "^19.2.0",
117
118
  "@types/react": "^19.2.0",
118
119
  "@types/react-dom": "^19.2.0",
119
- "@testing-library/react": "^16.3.0",
120
- "@testing-library/user-event": "^14.5.0",
121
- "@testing-library/jest-dom": "^6.6.3",
120
+ "argon2": "^0.44.0",
122
121
  "jsdom": "^25.0.1",
123
- "@jini-ai/cms": "0.6.19",
124
- "@jini-ai/admin": "0.6.19",
125
- "@jini-ai/core": "^0.6.19",
126
- "@jini-ai/agentic": "0.6.19",
127
- "@jini-ai/ui": "0.6.19",
128
- "@jini-ai/ui-kit": "^0.6.19"
122
+ "react": "^19.2.0",
123
+ "react-dom": "^19.2.0",
124
+ "typescript": "^5.6.0",
125
+ "vitest": "^2.1.0",
126
+ "@jini-ai/core": "^0.7.0",
127
+ "@jini-ai/ui": "0.7.0",
128
+ "@jini-ai/cms": "0.7.0",
129
+ "@jini-ai/ui-kit": "^0.7.0",
130
+ "@jini-ai/admin": "0.7.0",
131
+ "@jini-ai/agentic": "0.7.0"
129
132
  },
130
133
  "peerDependenciesMeta": {
131
134
  "argon2": {