@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.
Files changed (40) hide show
  1. package/CHANGELOG.md +27 -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 +9 -0
  19. package/dist/server/index.js +9 -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/recovery-codes.d.ts +3 -0
  39. package/dist/server/recovery-codes.js +7 -0
  40. 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
@@ -1,3 +1,4 @@
1
+ import type { OwnerMfaDeps } from './mfa/ports.js';
1
2
  import type { AuthServiceDeps } from './auth-service.js';
2
3
  type OwnerScope = {
3
4
  workspaceId: string;
@@ -14,6 +15,7 @@ export interface RecoveryCodeStore {
14
15
  clear(input: OwnerScope): Promise<void>;
15
16
  }
16
17
  export interface OwnerRecoveryDeps {
18
+ mfa?: OwnerMfaDeps;
17
19
  auth: AuthServiceDeps;
18
20
  codes: RecoveryCodeStore;
19
21
  seededOwnerPrincipalId: string;
@@ -29,6 +31,7 @@ type Options = Record<string, never>;
29
31
  */
30
32
  export declare function issueRecoveryCodes(required: Required<OwnerScope & {
31
33
  password: string;
34
+ code?: string;
32
35
  }>, _options?: Options): Promise<{
33
36
  codes: string[];
34
37
  }>;
@@ -1,3 +1,4 @@
1
+ import { requireOwnerFactor } from './mfa/service.js';
1
2
  import { resetUserPassword } from './admin-crud-service.js';
2
3
  import { inIdentityTransaction } from './identity-transaction.js';
3
4
  import { IdentityValidationError, OwnerRequiredError } from '../core/types.js';
@@ -32,6 +33,11 @@ export async function issueRecoveryCodes(required, _options = {}) {
32
33
  if (!input.password || !await deps.auth.hasher.verify({ hash: user.passwordHash, password: input.password })) {
33
34
  throw new IdentityValidationError({ message: 'The current password was not accepted. Enter your current owner password and try again.' });
34
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
+ }
35
41
  const codes = Array.from({ length: 10 }, () => deps.auth.tokens.newToken({}));
36
42
  if (new Set(codes).size !== 10 || codes.some(code => !/^[a-f0-9]{64}$/.test(code))) {
37
43
  throw new Error('Recovery code generation failed. Try again after the host operator checks the entropy source. Details: recovery-entropy');
@@ -54,6 +60,7 @@ export async function resetOwnerPassword(required, _options = {}) {
54
60
  if (!fresh || !await deps.auth.hasher.verify({ hash: fresh.passwordHash, password: input.password })) {
55
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');
56
62
  }
63
+ await deps.auth.mfaStore?.clear({ workspaceId: input.workspaceId, principalId: input.principalId });
57
64
  await deps.codes.clear({ workspaceId: input.workspaceId, principalId: input.principalId });
58
65
  } });
59
66
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/user-management",
3
- "version": "0.6.22",
3
+ "version": "0.7.1",
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.22"
99
+ "@simplewebauthn/browser": "14.0.0",
100
+ "@simplewebauthn/server": "14.0.3",
101
+ "otplib": "13.6.0",
102
+ "@jini-ai/core": "^0.7.1"
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/ui": "0.6.22",
124
- "@jini-ai/admin": "0.6.22",
125
- "@jini-ai/cms": "0.6.22",
126
- "@jini-ai/agentic": "0.6.19",
127
- "@jini-ai/ui-kit": "^0.6.19",
128
- "@jini-ai/core": "^0.6.22"
122
+ "react": "^19.2.0",
123
+ "react-dom": "^19.2.0",
124
+ "typescript": "^5.6.0",
125
+ "vitest": "^2.1.0",
126
+ "@jini-ai/agentic": "0.7.1",
127
+ "@jini-ai/cms": "0.7.1",
128
+ "@jini-ai/core": "^0.7.1",
129
+ "@jini-ai/admin": "0.7.1",
130
+ "@jini-ai/ui": "0.7.1",
131
+ "@jini-ai/ui-kit": "^0.7.1"
129
132
  },
130
133
  "peerDependenciesMeta": {
131
134
  "argon2": {