@aooth/user 0.2.4 → 0.2.6

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.
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_federated_identity_store = require("./federated-identity-store-Cbstwl4-.cjs");
2
+ const require_federated_identity_store = require("./federated-identity-store-8G0e79Zc.cjs");
3
3
  let node_crypto = require("node:crypto");
4
4
  // src/atscript-db/federated-identity-store.ts
5
5
  function isConflict$1(err) {
@@ -1,4 +1,4 @@
1
- import { D as UserCredentials, i as NewFederatedIdentity, k as UserStoreUpdate, n as FederatedIdentityStore, o as UserStore, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity } from "./federated-identity-store-Ds7Ye9qJ.cjs";
1
+ import { A as UserStoreUpdate, O as UserCredentials, i as NewFederatedIdentity, n as FederatedIdentityStore, o as UserStore, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity } from "./federated-identity-store-D8BFFhpm.cjs";
2
2
  /**
3
3
  * Structural surface of `AtscriptDbTable` covering exactly the methods this
4
4
  * adapter calls — kept loose so `@aooth/user` doesn't pull `@atscript/db` types
@@ -1,4 +1,4 @@
1
- import { D as UserCredentials, i as NewFederatedIdentity, k as UserStoreUpdate, n as FederatedIdentityStore, o as UserStore, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity } from "./federated-identity-store-Ds7Ye9qJ.mjs";
1
+ import { A as UserStoreUpdate, O as UserCredentials, i as NewFederatedIdentity, n as FederatedIdentityStore, o as UserStore, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity } from "./federated-identity-store-D8BFFhpm.mjs";
2
2
  /**
3
3
  * Structural surface of `AtscriptDbTable` covering exactly the methods this
4
4
  * adapter calls — kept loose so `@aooth/user` doesn't pull `@atscript/db` types
@@ -1,4 +1,4 @@
1
- import { c as setAtPath, l as UserStore, n as pickDefinedProfile, t as FederatedIdentityStore, u as UserAuthError } from "./federated-identity-store-BZRvw9Pz.mjs";
1
+ import { c as setAtPath, f as UserAuthError, l as UserStore, n as pickDefinedProfile, t as FederatedIdentityStore } from "./federated-identity-store-CUjGv4O7.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  // src/atscript-db/federated-identity-store.ts
4
4
  function isConflict$1(err) {
@@ -1,27 +1,62 @@
1
1
  require("node:crypto");
2
2
  // src/errors.ts
3
- const defaultMessages = {
4
- NOT_FOUND: "User not found",
5
- ALREADY_EXISTS: "User already exists",
6
- LOCKED: "Account is locked",
7
- INACTIVE: "Account is not active",
3
+ /**
4
+ * The message code of each `UserAuthError` type — the id its text is
5
+ * registered and translated by, and the `code` of the HTTP error made from it.
6
+ * Message codes share one process-wide id space with every other library, so
7
+ * types with a generic name get an `AOOTH_USER_` code; `NOT_FOUND` and
8
+ * `INVALID_CREDENTIALS` are shared on purpose and keep neutral texts.
9
+ */
10
+ const USER_AUTH_ERROR_CODES = Object.freeze({
11
+ NOT_FOUND: "NOT_FOUND",
12
+ ALREADY_EXISTS: "AOOTH_USER_ALREADY_EXISTS",
13
+ LOCKED: "AOOTH_USER_LOCKED",
14
+ INACTIVE: "AOOTH_USER_INACTIVE",
15
+ INVALID_CREDENTIALS: "INVALID_CREDENTIALS",
16
+ POLICY_VIOLATION: "AOOTH_USER_POLICY_VIOLATION",
17
+ PASSWORDS_MISMATCH: "PASSWORDS_MISMATCH",
18
+ PASSWORD_IN_HISTORY: "PASSWORD_IN_HISTORY",
19
+ MFA_REQUIRED: "MFA_REQUIRED",
20
+ MFA_INVALID: "MFA_INVALID",
21
+ MFA_NOT_CONFIGURED: "MFA_NOT_CONFIGURED",
22
+ CAS_EXHAUSTED: "AOOTH_USER_CAS_EXHAUSTED"
23
+ });
24
+ /**
25
+ * The default English message of each `UserAuthError`, by its message code
26
+ * ({@link USER_AUTH_ERROR_CODES}).
27
+ *
28
+ * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
29
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
30
+ * texts reach the `$i18n` the server sends with form schemas and `/meta`.
31
+ */
32
+ const USER_AUTH_ERROR_MESSAGES = Object.freeze({
33
+ /** Shared on purpose — the same neutral text as other libraries' `NOT_FOUND`. */
34
+ NOT_FOUND: "Not found",
35
+ AOOTH_USER_ALREADY_EXISTS: "User already exists",
36
+ AOOTH_USER_LOCKED: "Account is locked",
37
+ AOOTH_USER_INACTIVE: "Account is not active",
38
+ /** Shared on purpose — also the sign-in workflow's code, with the same text. */
8
39
  INVALID_CREDENTIALS: "Invalid credentials",
9
- POLICY_VIOLATION: "Password does not meet policy requirements",
40
+ AOOTH_USER_POLICY_VIOLATION: "Password does not meet policy requirements",
10
41
  PASSWORDS_MISMATCH: "Passwords do not match",
11
42
  PASSWORD_IN_HISTORY: "Password was recently used",
12
43
  MFA_REQUIRED: "Multi-factor authentication is required",
13
44
  MFA_INVALID: "Invalid MFA code",
14
45
  MFA_NOT_CONFIGURED: "MFA method is not configured",
15
- CAS_EXHAUSTED: "Update conflict — please retry"
16
- };
46
+ AOOTH_USER_CAS_EXHAUSTED: "Update conflict — please retry"
47
+ });
17
48
  var UserAuthError = class extends Error {
18
49
  type;
19
50
  details;
20
51
  name = "UserAuthError";
52
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
53
+ code;
21
54
  constructor(type, message, details) {
22
- super(message ?? defaultMessages[type]);
55
+ const code = USER_AUTH_ERROR_CODES[type];
56
+ super(message ?? USER_AUTH_ERROR_MESSAGES[code]);
23
57
  this.type = type;
24
58
  this.details = details;
59
+ this.code = code;
25
60
  }
26
61
  };
27
62
  // src/store/user-store.ts
@@ -129,6 +164,18 @@ Object.defineProperty(exports, "FederatedIdentityStore", {
129
164
  return FederatedIdentityStore;
130
165
  }
131
166
  });
167
+ Object.defineProperty(exports, "USER_AUTH_ERROR_CODES", {
168
+ enumerable: true,
169
+ get: function() {
170
+ return USER_AUTH_ERROR_CODES;
171
+ }
172
+ });
173
+ Object.defineProperty(exports, "USER_AUTH_ERROR_MESSAGES", {
174
+ enumerable: true,
175
+ get: function() {
176
+ return USER_AUTH_ERROR_MESSAGES;
177
+ }
178
+ });
132
179
  Object.defineProperty(exports, "UserAuthError", {
133
180
  enumerable: true,
134
181
  get: function() {
@@ -1,27 +1,62 @@
1
1
  import "node:crypto";
2
2
  // src/errors.ts
3
- const defaultMessages = {
4
- NOT_FOUND: "User not found",
5
- ALREADY_EXISTS: "User already exists",
6
- LOCKED: "Account is locked",
7
- INACTIVE: "Account is not active",
3
+ /**
4
+ * The message code of each `UserAuthError` type — the id its text is
5
+ * registered and translated by, and the `code` of the HTTP error made from it.
6
+ * Message codes share one process-wide id space with every other library, so
7
+ * types with a generic name get an `AOOTH_USER_` code; `NOT_FOUND` and
8
+ * `INVALID_CREDENTIALS` are shared on purpose and keep neutral texts.
9
+ */
10
+ const USER_AUTH_ERROR_CODES = Object.freeze({
11
+ NOT_FOUND: "NOT_FOUND",
12
+ ALREADY_EXISTS: "AOOTH_USER_ALREADY_EXISTS",
13
+ LOCKED: "AOOTH_USER_LOCKED",
14
+ INACTIVE: "AOOTH_USER_INACTIVE",
15
+ INVALID_CREDENTIALS: "INVALID_CREDENTIALS",
16
+ POLICY_VIOLATION: "AOOTH_USER_POLICY_VIOLATION",
17
+ PASSWORDS_MISMATCH: "PASSWORDS_MISMATCH",
18
+ PASSWORD_IN_HISTORY: "PASSWORD_IN_HISTORY",
19
+ MFA_REQUIRED: "MFA_REQUIRED",
20
+ MFA_INVALID: "MFA_INVALID",
21
+ MFA_NOT_CONFIGURED: "MFA_NOT_CONFIGURED",
22
+ CAS_EXHAUSTED: "AOOTH_USER_CAS_EXHAUSTED"
23
+ });
24
+ /**
25
+ * The default English message of each `UserAuthError`, by its message code
26
+ * ({@link USER_AUTH_ERROR_CODES}).
27
+ *
28
+ * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
29
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
30
+ * texts reach the `$i18n` the server sends with form schemas and `/meta`.
31
+ */
32
+ const USER_AUTH_ERROR_MESSAGES = Object.freeze({
33
+ /** Shared on purpose — the same neutral text as other libraries' `NOT_FOUND`. */
34
+ NOT_FOUND: "Not found",
35
+ AOOTH_USER_ALREADY_EXISTS: "User already exists",
36
+ AOOTH_USER_LOCKED: "Account is locked",
37
+ AOOTH_USER_INACTIVE: "Account is not active",
38
+ /** Shared on purpose — also the sign-in workflow's code, with the same text. */
8
39
  INVALID_CREDENTIALS: "Invalid credentials",
9
- POLICY_VIOLATION: "Password does not meet policy requirements",
40
+ AOOTH_USER_POLICY_VIOLATION: "Password does not meet policy requirements",
10
41
  PASSWORDS_MISMATCH: "Passwords do not match",
11
42
  PASSWORD_IN_HISTORY: "Password was recently used",
12
43
  MFA_REQUIRED: "Multi-factor authentication is required",
13
44
  MFA_INVALID: "Invalid MFA code",
14
45
  MFA_NOT_CONFIGURED: "MFA method is not configured",
15
- CAS_EXHAUSTED: "Update conflict — please retry"
16
- };
46
+ AOOTH_USER_CAS_EXHAUSTED: "Update conflict — please retry"
47
+ });
17
48
  var UserAuthError = class extends Error {
18
49
  type;
19
50
  details;
20
51
  name = "UserAuthError";
52
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
53
+ code;
21
54
  constructor(type, message, details) {
22
- super(message ?? defaultMessages[type]);
55
+ const code = USER_AUTH_ERROR_CODES[type];
56
+ super(message ?? USER_AUTH_ERROR_MESSAGES[code]);
23
57
  this.type = type;
24
58
  this.details = details;
59
+ this.code = code;
25
60
  }
26
61
  };
27
62
  // src/store/user-store.ts
@@ -123,4 +158,4 @@ function pickDefinedProfile(src) {
123
158
  * keeps the federated-login core (`@aooth/idp`, phase 2) storage-agnostic.
124
159
  */
125
160
  var FederatedIdentityStore = class {};
126
- export { maskEmail as a, setAtPath as c, incrementAtPath as i, UserStore as l, pickDefinedProfile as n, maskMfaValue as o, deepMerge as r, maskPhone as s, FederatedIdentityStore as t, UserAuthError as u };
161
+ export { maskEmail as a, setAtPath as c, USER_AUTH_ERROR_MESSAGES as d, UserAuthError as f, incrementAtPath as i, UserStore as l, pickDefinedProfile as n, maskMfaValue as o, deepMerge as r, maskPhone as s, FederatedIdentityStore as t, USER_AUTH_ERROR_CODES as u };
@@ -177,7 +177,18 @@ interface PasswordPolicyDef {
177
177
  serialized?: string;
178
178
  description?: string;
179
179
  errorMessage?: string;
180
+ /**
181
+ * Message code of the policy's texts, for translation: `errorMessage` is
182
+ * translated by `code`, `description` by `${code}_DESCRIPTION`, both with
183
+ * `params` — the English texts are the fallback. The built-in `pp*`
184
+ * policies carry `PP_*` codes (`PASSWORD_POLICY_MESSAGES`).
185
+ */
186
+ code?: string;
187
+ /** Values of the code's `{name}` placeholders (e.g. `{ min: 8 }`). */
188
+ params?: PasswordPolicyParams;
180
189
  }
190
+ /** Values of a password policy's message placeholders. */
191
+ type PasswordPolicyParams = Readonly<Record<string, string | number>>;
181
192
  type PasswordPolicyEvalFn = (password: string, context?: PasswordPolicyContext) => boolean | Promise<boolean>;
182
193
  interface PasswordPolicyContext {
183
194
  passwordData?: PasswordData;
@@ -217,9 +228,14 @@ interface LockStatus {
217
228
  }
218
229
  interface PolicyCheckResult {
219
230
  passed: boolean;
231
+ /** Every policy and its result, with its texts and (when set) message `code` + `params`. */
220
232
  policies: {
221
233
  description: string;
222
234
  passed: boolean;
235
+ /** The policy's failure text (always set by `checkPolicies`). */
236
+ errorMessage?: string;
237
+ code?: string;
238
+ params?: PasswordPolicyParams;
223
239
  }[];
224
240
  errors: string[];
225
241
  }
@@ -227,6 +243,10 @@ interface TransferablePolicy {
227
243
  rule: string;
228
244
  description?: string;
229
245
  errorMessage?: string;
246
+ /** The policy's message code ({@link PasswordPolicyDef.code}). */
247
+ code?: string;
248
+ /** The code's placeholder values ({@link PasswordPolicyDef.params}). */
249
+ params?: PasswordPolicyParams;
230
250
  }
231
251
  interface MfaMethodInfo {
232
252
  name: string;
@@ -405,4 +425,4 @@ declare abstract class FederatedIdentityStore {
405
425
  */
406
426
  abstract deleteAllForUser(userId: string): Promise<number>;
407
427
  }
408
- export { TotpConfig as C, UserCredentials as D, UserAuthErrorType as E, UserServiceConfig as O, PolicyCheckResult as S, TrustedDeviceRecord as T, PasswordData as _, pickDefinedProfile as a, PasswordPolicyEvalFn as b, AccountData as c, LockoutConfig as d, LoginResult as f, PasswordConfig as g, MfaMethodInfo as h, NewFederatedIdentity as i, UserStoreUpdate as k, DeepPartial as l, MfaMethod as m, FederatedIdentityStore as n, UserStore as o, MfaData as p, FederatedProfileSnapshot as r, WithCasOptions as s, FederatedIdentity as t, LockStatus as u, PasswordPolicyContext as v, TransferablePolicy as w, PasswordPolicyInstance as x, PasswordPolicyDef as y };
428
+ export { UserStoreUpdate as A, PolicyCheckResult as C, UserAuthErrorType as D, TrustedDeviceRecord as E, UserCredentials as O, PasswordPolicyParams as S, TransferablePolicy as T, PasswordData as _, pickDefinedProfile as a, PasswordPolicyEvalFn as b, AccountData as c, LockoutConfig as d, LoginResult as f, PasswordConfig as g, MfaMethodInfo as h, NewFederatedIdentity as i, UserServiceConfig as k, DeepPartial as l, MfaMethod as m, FederatedIdentityStore as n, UserStore as o, MfaData as p, FederatedProfileSnapshot as r, WithCasOptions as s, FederatedIdentity as t, LockStatus as u, PasswordPolicyContext as v, TotpConfig as w, PasswordPolicyInstance as x, PasswordPolicyDef as y };
@@ -177,7 +177,18 @@ interface PasswordPolicyDef {
177
177
  serialized?: string;
178
178
  description?: string;
179
179
  errorMessage?: string;
180
+ /**
181
+ * Message code of the policy's texts, for translation: `errorMessage` is
182
+ * translated by `code`, `description` by `${code}_DESCRIPTION`, both with
183
+ * `params` — the English texts are the fallback. The built-in `pp*`
184
+ * policies carry `PP_*` codes (`PASSWORD_POLICY_MESSAGES`).
185
+ */
186
+ code?: string;
187
+ /** Values of the code's `{name}` placeholders (e.g. `{ min: 8 }`). */
188
+ params?: PasswordPolicyParams;
180
189
  }
190
+ /** Values of a password policy's message placeholders. */
191
+ type PasswordPolicyParams = Readonly<Record<string, string | number>>;
181
192
  type PasswordPolicyEvalFn = (password: string, context?: PasswordPolicyContext) => boolean | Promise<boolean>;
182
193
  interface PasswordPolicyContext {
183
194
  passwordData?: PasswordData;
@@ -217,9 +228,14 @@ interface LockStatus {
217
228
  }
218
229
  interface PolicyCheckResult {
219
230
  passed: boolean;
231
+ /** Every policy and its result, with its texts and (when set) message `code` + `params`. */
220
232
  policies: {
221
233
  description: string;
222
234
  passed: boolean;
235
+ /** The policy's failure text (always set by `checkPolicies`). */
236
+ errorMessage?: string;
237
+ code?: string;
238
+ params?: PasswordPolicyParams;
223
239
  }[];
224
240
  errors: string[];
225
241
  }
@@ -227,6 +243,10 @@ interface TransferablePolicy {
227
243
  rule: string;
228
244
  description?: string;
229
245
  errorMessage?: string;
246
+ /** The policy's message code ({@link PasswordPolicyDef.code}). */
247
+ code?: string;
248
+ /** The code's placeholder values ({@link PasswordPolicyDef.params}). */
249
+ params?: PasswordPolicyParams;
230
250
  }
231
251
  interface MfaMethodInfo {
232
252
  name: string;
@@ -405,4 +425,4 @@ declare abstract class FederatedIdentityStore {
405
425
  */
406
426
  abstract deleteAllForUser(userId: string): Promise<number>;
407
427
  }
408
- export { TotpConfig as C, UserCredentials as D, UserAuthErrorType as E, UserServiceConfig as O, PolicyCheckResult as S, TrustedDeviceRecord as T, PasswordData as _, pickDefinedProfile as a, PasswordPolicyEvalFn as b, AccountData as c, LockoutConfig as d, LoginResult as f, PasswordConfig as g, MfaMethodInfo as h, NewFederatedIdentity as i, UserStoreUpdate as k, DeepPartial as l, MfaMethod as m, FederatedIdentityStore as n, UserStore as o, MfaData as p, FederatedProfileSnapshot as r, WithCasOptions as s, FederatedIdentity as t, LockStatus as u, PasswordPolicyContext as v, TransferablePolicy as w, PasswordPolicyInstance as x, PasswordPolicyDef as y };
428
+ export { UserStoreUpdate as A, PolicyCheckResult as C, UserAuthErrorType as D, TrustedDeviceRecord as E, UserCredentials as O, PasswordPolicyParams as S, TransferablePolicy as T, PasswordData as _, pickDefinedProfile as a, PasswordPolicyEvalFn as b, AccountData as c, LockoutConfig as d, LoginResult as f, PasswordConfig as g, MfaMethodInfo as h, NewFederatedIdentity as i, UserServiceConfig as k, DeepPartial as l, MfaMethod as m, FederatedIdentityStore as n, UserStore as o, MfaData as p, FederatedProfileSnapshot as r, WithCasOptions as s, FederatedIdentity as t, LockStatus as u, PasswordPolicyContext as v, TotpConfig as w, PasswordPolicyInstance as x, PasswordPolicyDef as y };
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_federated_identity_store = require("./federated-identity-store-Cbstwl4-.cjs");
2
+ const require_federated_identity_store = require("./federated-identity-store-8G0e79Zc.cjs");
3
3
  let node_crypto = require("node:crypto");
4
4
  // src/base-x/base32.ts
5
5
  /**
@@ -252,7 +252,7 @@ function normalizePolicies(policies) {
252
252
  * and only the server check enforces the rule.
253
253
  */
254
254
  function definePasswordPolicy(opts) {
255
- const { rule, args, description, errorMessage } = opts;
255
+ const { rule, args, description, errorMessage, code, params } = opts;
256
256
  const def = { rule: args ? (v) => rule(v, ...args) : (v) => rule(v, ...[]) };
257
257
  if (args) {
258
258
  const argList = args.map((a) => JSON.stringify(a)).join(", ");
@@ -260,6 +260,8 @@ function definePasswordPolicy(opts) {
260
260
  }
261
261
  if (description !== void 0) def.description = description;
262
262
  if (errorMessage !== void 0) def.errorMessage = errorMessage;
263
+ if (code !== void 0) def.code = code;
264
+ if (params !== void 0) def.params = params;
263
265
  return def;
264
266
  }
265
267
  var PasswordPolicy = class {
@@ -267,11 +269,15 @@ var PasswordPolicy = class {
267
269
  serialized;
268
270
  description;
269
271
  errorMessage;
272
+ code;
273
+ params;
270
274
  constructor(config) {
271
275
  this.rule = config.rule;
272
276
  if (config.serialized !== void 0) this.serialized = config.serialized;
273
277
  this.description = config.description || "";
274
278
  this.errorMessage = config.errorMessage || "";
279
+ if (config.code !== void 0) this.code = config.code;
280
+ if (config.params !== void 0) this.params = config.params;
275
281
  }
276
282
  evaluate(password, context) {
277
283
  return this.rule(password, context);
@@ -503,6 +509,18 @@ var UserService = class {
503
509
  return this.incrementAndMaybeLock(user.id, user.account, "INVALID_CREDENTIALS", lockoutOverride);
504
510
  }
505
511
  /**
512
+ * The account checks `login` runs before the password, without one — for a
513
+ * sign-in that proves the first factor another way (a magic link): throws
514
+ * `NOT_FOUND`, `INACTIVE` (incl. a pending invitation) or `LOCKED`, and
515
+ * lifts an expired lock like `login` does. Returns the fresh row.
516
+ */
517
+ async assertCanSignIn(id) {
518
+ const user = await this.getUser(id);
519
+ if (!user.account.active) throw new require_federated_identity_store.UserAuthError("INACTIVE");
520
+ await this.ensureNotLockedOrThrow(user.id, user.account);
521
+ return user;
522
+ }
523
+ /**
506
524
  * Stamp a successful login on the user record: `account.lastLogin = now` and
507
525
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
508
526
  *
@@ -681,7 +699,9 @@ var UserService = class {
681
699
  result.passed = result.passed && passed;
682
700
  result.policies.push({
683
701
  description: policy.description,
684
- passed
702
+ passed,
703
+ errorMessage: policy.errorMessage,
704
+ ...policyCodeOf(policy)
685
705
  });
686
706
  if (!passed) result.errors.push(policy.errorMessage);
687
707
  }
@@ -691,7 +711,8 @@ var UserService = class {
691
711
  return this.config.password.policies.filter((p) => p.transferable).map((p) => ({
692
712
  rule: p.serialized,
693
713
  description: p.description,
694
- errorMessage: p.errorMessage
714
+ errorMessage: p.errorMessage,
715
+ ...policyCodeOf(p)
695
716
  }));
696
717
  }
697
718
  async addMfaMethod(id, method) {
@@ -747,9 +768,7 @@ var UserService = class {
747
768
  * total tries across BOTH factors, not `2 * threshold`.
748
769
  */
749
770
  async verifyMfa(id, code, config, lockoutOverride) {
750
- const user = await this.getUser(id);
751
- if (!user.account.active) throw new require_federated_identity_store.UserAuthError("INACTIVE");
752
- await this.ensureNotLockedOrThrow(id, user.account);
771
+ const user = await this.assertCanSignIn(id);
753
772
  const totp = user.mfa.methods.find((m) => m.name === "totp" && m.confirmed);
754
773
  if (!totp) throw new require_federated_identity_store.UserAuthError("MFA_NOT_CONFIGURED");
755
774
  const matchedCounter = verifyTotpCode(totp.value, code, config);
@@ -1134,6 +1153,13 @@ function observeWrites(store, hooks) {
1134
1153
  return fn;
1135
1154
  } });
1136
1155
  }
1156
+ /** A policy's message `code` / `params`, when it has them. */
1157
+ function policyCodeOf({ code, params }) {
1158
+ return {
1159
+ ...code !== void 0 && { code },
1160
+ ...params !== void 0 && { params }
1161
+ };
1162
+ }
1137
1163
  // src/store/memory.ts
1138
1164
  var UserStoreMemory = class extends require_federated_identity_store.UserStore {
1139
1165
  /** Keyed by the stable surrogate `id` (the token subject). */
@@ -1310,41 +1336,77 @@ function compositeKey(provider, subject) {
1310
1336
  return `${provider}${subject}`;
1311
1337
  }
1312
1338
  // src/password/policies.ts
1339
+ /**
1340
+ * English templates of the built-in password policies' texts, by code: the
1341
+ * failure (`PP_*`, a policy's `errorMessage`) and the rule
1342
+ * (`PP_*_DESCRIPTION`, its `description`). Placeholders: `{min}`, `{max}`,
1343
+ * `{count}`. The templates are the plural forms; the policies' own English
1344
+ * texts are singular / plural-correct and are the fallback a translator
1345
+ * replaces. On a moost server `@aooth/auth-moost` registers them with
1346
+ * `registerMessages` on import.
1347
+ */
1348
+ const PASSWORD_POLICY_MESSAGES = {
1349
+ PP_MIN_LENGTH: "Password must be at least {min} characters long",
1350
+ PP_MIN_LENGTH_DESCRIPTION: "Minimum length {min}",
1351
+ PP_UPPERCASE: "Password must include at least {count} uppercase characters",
1352
+ PP_UPPERCASE_DESCRIPTION: "At least {count} uppercase characters",
1353
+ PP_LOWERCASE: "Password must include at least {count} lowercase characters",
1354
+ PP_LOWERCASE_DESCRIPTION: "At least {count} lowercase characters",
1355
+ PP_NUMBER: "Password must include at least {count} numbers",
1356
+ PP_NUMBER_DESCRIPTION: "At least {count} numbers",
1357
+ PP_SPECIAL_CHAR: "Password must include at least {count} special characters",
1358
+ PP_SPECIAL_CHAR_DESCRIPTION: "At least {count} special characters",
1359
+ PP_MAX_REPEATED: "Password must not have more than {max} consecutive repeated characters",
1360
+ PP_MAX_REPEATED_DESCRIPTION: "No more than {max} consecutive repeated characters"
1361
+ };
1362
+ const plural = (n) => n === 1 ? "" : "s";
1313
1363
  const ppHasMinLength = (min = 8) => definePasswordPolicy({
1314
1364
  rule: (v, min) => v.length >= min,
1315
1365
  args: [min],
1316
1366
  description: `Minimum length ${min}`,
1317
- errorMessage: `Password must be at least ${min} characters long`
1367
+ errorMessage: `Password must be at least ${min} characters long`,
1368
+ code: "PP_MIN_LENGTH",
1369
+ params: { min }
1318
1370
  });
1319
1371
  const ppHasUpperCase = (n = 1) => definePasswordPolicy({
1320
1372
  rule: (v, n) => (v.match(/[A-Z]/g) || []).length >= n,
1321
1373
  args: [n],
1322
- description: `At least ${n} uppercase character${n === 1 ? "" : "s"}`,
1323
- errorMessage: `Password must include at least ${n} uppercase character${n === 1 ? "" : "s"}`
1374
+ description: `At least ${n} uppercase character${plural(n)}`,
1375
+ errorMessage: `Password must include at least ${n} uppercase character${plural(n)}`,
1376
+ code: "PP_UPPERCASE",
1377
+ params: { count: n }
1324
1378
  });
1325
1379
  const ppHasLowerCase = (n = 1) => definePasswordPolicy({
1326
1380
  rule: (v, n) => (v.match(/[a-z]/g) || []).length >= n,
1327
1381
  args: [n],
1328
- description: `At least ${n} lowercase character${n === 1 ? "" : "s"}`,
1329
- errorMessage: `Password must include at least ${n} lowercase character${n === 1 ? "" : "s"}`
1382
+ description: `At least ${n} lowercase character${plural(n)}`,
1383
+ errorMessage: `Password must include at least ${n} lowercase character${plural(n)}`,
1384
+ code: "PP_LOWERCASE",
1385
+ params: { count: n }
1330
1386
  });
1331
1387
  const ppHasNumber = (n = 1) => definePasswordPolicy({
1332
1388
  rule: (v, n) => (v.match(/\d/g) || []).length >= n,
1333
1389
  args: [n],
1334
- description: `At least ${n} number${n === 1 ? "" : "s"}`,
1335
- errorMessage: `Password must include at least ${n} number${n === 1 ? "" : "s"}`
1390
+ description: `At least ${n} number${plural(n)}`,
1391
+ errorMessage: `Password must include at least ${n} number${plural(n)}`,
1392
+ code: "PP_NUMBER",
1393
+ params: { count: n }
1336
1394
  });
1337
1395
  const ppHasSpecialChar = (n = 1) => definePasswordPolicy({
1338
1396
  rule: (v, n) => (v.match(/[^A-Za-z0-9]/g) || []).length >= n,
1339
1397
  args: [n],
1340
- description: `At least ${n} special character${n === 1 ? "" : "s"}`,
1341
- errorMessage: `Password must include at least ${n} special character${n === 1 ? "" : "s"}`
1398
+ description: `At least ${n} special character${plural(n)}`,
1399
+ errorMessage: `Password must include at least ${n} special character${plural(n)}`,
1400
+ code: "PP_SPECIAL_CHAR",
1401
+ params: { count: n }
1342
1402
  });
1343
1403
  const ppMaxRepeatedChars = (maxRepeated = 2) => definePasswordPolicy({
1344
1404
  rule: (v, maxRepeated) => !new RegExp(`(.)\\1{${maxRepeated},}`).test(v),
1345
1405
  args: [maxRepeated],
1346
1406
  description: `No more than ${maxRepeated} consecutive repeated characters`,
1347
- errorMessage: `Password must not have more than ${maxRepeated} consecutive repeated characters`
1407
+ errorMessage: `Password must not have more than ${maxRepeated} consecutive repeated characters`,
1408
+ code: "PP_MAX_REPEATED",
1409
+ params: { max: maxRepeated }
1348
1410
  });
1349
1411
  // src/mfa/codes.ts
1350
1412
  /**
@@ -1373,9 +1435,12 @@ function verifyMfaCode(submitted, expectedHash) {
1373
1435
  }
1374
1436
  exports.FederatedIdentityStore = require_federated_identity_store.FederatedIdentityStore;
1375
1437
  exports.FederatedIdentityStoreMemory = FederatedIdentityStoreMemory;
1438
+ exports.PASSWORD_POLICY_MESSAGES = PASSWORD_POLICY_MESSAGES;
1376
1439
  exports.PasswordHasher = PasswordHasher;
1377
1440
  exports.PasswordPolicy = PasswordPolicy;
1378
1441
  exports.SEEN_DEVICES_DEFAULT_CAP = SEEN_DEVICES_DEFAULT_CAP;
1442
+ exports.USER_AUTH_ERROR_CODES = require_federated_identity_store.USER_AUTH_ERROR_CODES;
1443
+ exports.USER_AUTH_ERROR_MESSAGES = require_federated_identity_store.USER_AUTH_ERROR_MESSAGES;
1379
1444
  exports.UserAuthError = require_federated_identity_store.UserAuthError;
1380
1445
  exports.UserService = UserService;
1381
1446
  exports.UserStore = require_federated_identity_store.UserStore;
package/dist/index.d.cts CHANGED
@@ -1,8 +1,42 @@
1
- import { C as TotpConfig, D as UserCredentials, E as UserAuthErrorType, O as UserServiceConfig, S as PolicyCheckResult, T as TrustedDeviceRecord, _ as PasswordData, a as pickDefinedProfile, b as PasswordPolicyEvalFn, c as AccountData, d as LockoutConfig, f as LoginResult, g as PasswordConfig, h as MfaMethodInfo, i as NewFederatedIdentity, k as UserStoreUpdate, l as DeepPartial, m as MfaMethod, n as FederatedIdentityStore, o as UserStore, p as MfaData, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity, u as LockStatus, v as PasswordPolicyContext, w as TransferablePolicy, x as PasswordPolicyInstance, y as PasswordPolicyDef } from "./federated-identity-store-Ds7Ye9qJ.cjs";
1
+ import { A as UserStoreUpdate, C as PolicyCheckResult, D as UserAuthErrorType, E as TrustedDeviceRecord, O as UserCredentials, S as PasswordPolicyParams, T as TransferablePolicy, _ as PasswordData, a as pickDefinedProfile, b as PasswordPolicyEvalFn, c as AccountData, d as LockoutConfig, f as LoginResult, g as PasswordConfig, h as MfaMethodInfo, i as NewFederatedIdentity, k as UserServiceConfig, l as DeepPartial, m as MfaMethod, n as FederatedIdentityStore, o as UserStore, p as MfaData, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity, u as LockStatus, v as PasswordPolicyContext, w as TotpConfig, x as PasswordPolicyInstance, y as PasswordPolicyDef } from "./federated-identity-store-D8BFFhpm.cjs";
2
+ /**
3
+ * The message code of each `UserAuthError` type — the id its text is
4
+ * registered and translated by, and the `code` of the HTTP error made from it.
5
+ * Message codes share one process-wide id space with every other library, so
6
+ * types with a generic name get an `AOOTH_USER_` code; `NOT_FOUND` and
7
+ * `INVALID_CREDENTIALS` are shared on purpose and keep neutral texts.
8
+ */
9
+ export declare const USER_AUTH_ERROR_CODES: Readonly<{
10
+ readonly NOT_FOUND: "NOT_FOUND";
11
+ readonly ALREADY_EXISTS: "AOOTH_USER_ALREADY_EXISTS";
12
+ readonly LOCKED: "AOOTH_USER_LOCKED";
13
+ readonly INACTIVE: "AOOTH_USER_INACTIVE";
14
+ readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
15
+ readonly POLICY_VIOLATION: "AOOTH_USER_POLICY_VIOLATION";
16
+ readonly PASSWORDS_MISMATCH: "PASSWORDS_MISMATCH";
17
+ readonly PASSWORD_IN_HISTORY: "PASSWORD_IN_HISTORY";
18
+ readonly MFA_REQUIRED: "MFA_REQUIRED";
19
+ readonly MFA_INVALID: "MFA_INVALID";
20
+ readonly MFA_NOT_CONFIGURED: "MFA_NOT_CONFIGURED";
21
+ readonly CAS_EXHAUSTED: "AOOTH_USER_CAS_EXHAUSTED";
22
+ }>;
23
+ /** A message code of a `UserAuthError` — see {@link USER_AUTH_ERROR_CODES}. */
24
+ type UserAuthErrorCode = (typeof USER_AUTH_ERROR_CODES)[UserAuthErrorType];
25
+ /**
26
+ * The default English message of each `UserAuthError`, by its message code
27
+ * ({@link USER_AUTH_ERROR_CODES}).
28
+ *
29
+ * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
30
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
31
+ * texts reach the `$i18n` the server sends with form schemas and `/meta`.
32
+ */
33
+ export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorCode, string>>;
2
34
  export declare class UserAuthError extends Error {
3
35
  readonly type: UserAuthErrorType;
4
36
  readonly details?: Record<string, unknown> | undefined;
5
37
  readonly name = "UserAuthError";
38
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
39
+ readonly code: UserAuthErrorCode;
6
40
  constructor(type: UserAuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
7
41
  }
8
42
  export declare class PasswordHasher {
@@ -43,12 +77,18 @@ export declare function definePasswordPolicy<A extends readonly unknown[]>(opts:
43
77
  args?: A;
44
78
  description?: string;
45
79
  errorMessage?: string;
80
+ /** Message code of the texts (see {@link PasswordPolicyDef.code}). */
81
+ code?: string;
82
+ /** Values of the code's `{name}` placeholders. */
83
+ params?: PasswordPolicyParams;
46
84
  }): PasswordPolicyDef;
47
85
  export declare class PasswordPolicy implements PasswordPolicyInstance {
48
86
  readonly rule: PasswordPolicyEvalFn;
49
87
  readonly serialized?: string;
50
88
  readonly description: string;
51
89
  readonly errorMessage: string;
90
+ readonly code?: string;
91
+ readonly params?: PasswordPolicyParams;
52
92
  constructor(config: PasswordPolicyDef);
53
93
  evaluate(password: string, context?: PasswordPolicyContext): boolean | Promise<boolean>;
54
94
  get transferable(): boolean;
@@ -141,6 +181,13 @@ export declare class UserService<T extends object = object> {
141
181
  */
142
182
  findByIdentifier(value: string): Promise<(UserCredentials & T) | null>;
143
183
  login(handle: string, password: string, lockoutOverride?: Partial<LockoutConfig>): Promise<LoginResult<T>>;
184
+ /**
185
+ * The account checks `login` runs before the password, without one — for a
186
+ * sign-in that proves the first factor another way (a magic link): throws
187
+ * `NOT_FOUND`, `INACTIVE` (incl. a pending invitation) or `LOCKED`, and
188
+ * lifts an expired lock like `login` does. Returns the fresh row.
189
+ */
190
+ assertCanSignIn(id: string): Promise<UserCredentials & T>;
144
191
  /**
145
192
  * Stamp a successful login on the user record: `account.lastLogin = now` and
146
193
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
@@ -460,6 +507,31 @@ export declare class FederatedIdentityStoreMemory extends FederatedIdentityStore
460
507
  touchLogin(provider: string, subject: string, profile?: FederatedProfileSnapshot): Promise<void>;
461
508
  deleteAllForUser(userId: string): Promise<number>;
462
509
  }
510
+ /**
511
+ * English templates of the built-in password policies' texts, by code: the
512
+ * failure (`PP_*`, a policy's `errorMessage`) and the rule
513
+ * (`PP_*_DESCRIPTION`, its `description`). Placeholders: `{min}`, `{max}`,
514
+ * `{count}`. The templates are the plural forms; the policies' own English
515
+ * texts are singular / plural-correct and are the fallback a translator
516
+ * replaces. On a moost server `@aooth/auth-moost` registers them with
517
+ * `registerMessages` on import.
518
+ */
519
+ export declare const PASSWORD_POLICY_MESSAGES: {
520
+ readonly PP_MIN_LENGTH: "Password must be at least {min} characters long";
521
+ readonly PP_MIN_LENGTH_DESCRIPTION: "Minimum length {min}";
522
+ readonly PP_UPPERCASE: "Password must include at least {count} uppercase characters";
523
+ readonly PP_UPPERCASE_DESCRIPTION: "At least {count} uppercase characters";
524
+ readonly PP_LOWERCASE: "Password must include at least {count} lowercase characters";
525
+ readonly PP_LOWERCASE_DESCRIPTION: "At least {count} lowercase characters";
526
+ readonly PP_NUMBER: "Password must include at least {count} numbers";
527
+ readonly PP_NUMBER_DESCRIPTION: "At least {count} numbers";
528
+ readonly PP_SPECIAL_CHAR: "Password must include at least {count} special characters";
529
+ readonly PP_SPECIAL_CHAR_DESCRIPTION: "At least {count} special characters";
530
+ readonly PP_MAX_REPEATED: "Password must not have more than {max} consecutive repeated characters";
531
+ readonly PP_MAX_REPEATED_DESCRIPTION: "No more than {max} consecutive repeated characters";
532
+ };
533
+ /** A code of {@link PASSWORD_POLICY_MESSAGES}. */
534
+ type PasswordPolicyMessageCode = keyof typeof PASSWORD_POLICY_MESSAGES;
463
535
  export declare const ppHasMinLength: (min?: number) => PasswordPolicyDef;
464
536
  export declare const ppHasUpperCase: (n?: number) => PasswordPolicyDef;
465
537
  export declare const ppHasLowerCase: (n?: number) => PasswordPolicyDef;
@@ -496,4 +568,4 @@ export declare function maskEmail(email: string): string;
496
568
  export declare function maskPhone(phone: string): string;
497
569
  export declare function maskMfaValue(method: MfaMethod): string;
498
570
  export declare function setAtPath(obj: object, path: string, value: unknown): void;
499
- export { type AccountData, type DeepPartial, type FederatedIdentity, FederatedIdentityStore, type FederatedIdentityStoreMemoryOptions, type FederatedProfileSnapshot, type LockStatus, type LockoutConfig, type LoginResult, type MfaData, type MfaMethod, type MfaMethodInfo, type NewFederatedIdentity, type PasswordConfig, type PasswordData, type PasswordPolicyContext, type PasswordPolicyDef, type PasswordPolicyEvalFn, type PasswordPolicyInstance, type PolicyCheckResult, type TotpConfig, type TransferablePolicy, type TrustedDeviceRecord, type UserAuthErrorType, type UserCredentials, type UserServiceConfig, UserStore, type UserStoreUpdate, pickDefinedProfile };
571
+ export { type AccountData, type DeepPartial, type FederatedIdentity, FederatedIdentityStore, type FederatedIdentityStoreMemoryOptions, type FederatedProfileSnapshot, type LockStatus, type LockoutConfig, type LoginResult, type MfaData, type MfaMethod, type MfaMethodInfo, type NewFederatedIdentity, type PasswordConfig, type PasswordData, type PasswordPolicyContext, type PasswordPolicyDef, type PasswordPolicyEvalFn, type PasswordPolicyInstance, type PasswordPolicyMessageCode, type PasswordPolicyParams, type PolicyCheckResult, type TotpConfig, type TransferablePolicy, type TrustedDeviceRecord, type UserAuthErrorCode, type UserAuthErrorType, type UserCredentials, type UserServiceConfig, UserStore, type UserStoreUpdate, pickDefinedProfile };
package/dist/index.d.mts CHANGED
@@ -1,8 +1,42 @@
1
- import { C as TotpConfig, D as UserCredentials, E as UserAuthErrorType, O as UserServiceConfig, S as PolicyCheckResult, T as TrustedDeviceRecord, _ as PasswordData, a as pickDefinedProfile, b as PasswordPolicyEvalFn, c as AccountData, d as LockoutConfig, f as LoginResult, g as PasswordConfig, h as MfaMethodInfo, i as NewFederatedIdentity, k as UserStoreUpdate, l as DeepPartial, m as MfaMethod, n as FederatedIdentityStore, o as UserStore, p as MfaData, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity, u as LockStatus, v as PasswordPolicyContext, w as TransferablePolicy, x as PasswordPolicyInstance, y as PasswordPolicyDef } from "./federated-identity-store-Ds7Ye9qJ.mjs";
1
+ import { A as UserStoreUpdate, C as PolicyCheckResult, D as UserAuthErrorType, E as TrustedDeviceRecord, O as UserCredentials, S as PasswordPolicyParams, T as TransferablePolicy, _ as PasswordData, a as pickDefinedProfile, b as PasswordPolicyEvalFn, c as AccountData, d as LockoutConfig, f as LoginResult, g as PasswordConfig, h as MfaMethodInfo, i as NewFederatedIdentity, k as UserServiceConfig, l as DeepPartial, m as MfaMethod, n as FederatedIdentityStore, o as UserStore, p as MfaData, r as FederatedProfileSnapshot, s as WithCasOptions, t as FederatedIdentity, u as LockStatus, v as PasswordPolicyContext, w as TotpConfig, x as PasswordPolicyInstance, y as PasswordPolicyDef } from "./federated-identity-store-D8BFFhpm.mjs";
2
+ /**
3
+ * The message code of each `UserAuthError` type — the id its text is
4
+ * registered and translated by, and the `code` of the HTTP error made from it.
5
+ * Message codes share one process-wide id space with every other library, so
6
+ * types with a generic name get an `AOOTH_USER_` code; `NOT_FOUND` and
7
+ * `INVALID_CREDENTIALS` are shared on purpose and keep neutral texts.
8
+ */
9
+ export declare const USER_AUTH_ERROR_CODES: Readonly<{
10
+ readonly NOT_FOUND: "NOT_FOUND";
11
+ readonly ALREADY_EXISTS: "AOOTH_USER_ALREADY_EXISTS";
12
+ readonly LOCKED: "AOOTH_USER_LOCKED";
13
+ readonly INACTIVE: "AOOTH_USER_INACTIVE";
14
+ readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
15
+ readonly POLICY_VIOLATION: "AOOTH_USER_POLICY_VIOLATION";
16
+ readonly PASSWORDS_MISMATCH: "PASSWORDS_MISMATCH";
17
+ readonly PASSWORD_IN_HISTORY: "PASSWORD_IN_HISTORY";
18
+ readonly MFA_REQUIRED: "MFA_REQUIRED";
19
+ readonly MFA_INVALID: "MFA_INVALID";
20
+ readonly MFA_NOT_CONFIGURED: "MFA_NOT_CONFIGURED";
21
+ readonly CAS_EXHAUSTED: "AOOTH_USER_CAS_EXHAUSTED";
22
+ }>;
23
+ /** A message code of a `UserAuthError` — see {@link USER_AUTH_ERROR_CODES}. */
24
+ type UserAuthErrorCode = (typeof USER_AUTH_ERROR_CODES)[UserAuthErrorType];
25
+ /**
26
+ * The default English message of each `UserAuthError`, by its message code
27
+ * ({@link USER_AUTH_ERROR_CODES}).
28
+ *
29
+ * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
30
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
31
+ * texts reach the `$i18n` the server sends with form schemas and `/meta`.
32
+ */
33
+ export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorCode, string>>;
2
34
  export declare class UserAuthError extends Error {
3
35
  readonly type: UserAuthErrorType;
4
36
  readonly details?: Record<string, unknown> | undefined;
5
37
  readonly name = "UserAuthError";
38
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
39
+ readonly code: UserAuthErrorCode;
6
40
  constructor(type: UserAuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
7
41
  }
8
42
  export declare class PasswordHasher {
@@ -43,12 +77,18 @@ export declare function definePasswordPolicy<A extends readonly unknown[]>(opts:
43
77
  args?: A;
44
78
  description?: string;
45
79
  errorMessage?: string;
80
+ /** Message code of the texts (see {@link PasswordPolicyDef.code}). */
81
+ code?: string;
82
+ /** Values of the code's `{name}` placeholders. */
83
+ params?: PasswordPolicyParams;
46
84
  }): PasswordPolicyDef;
47
85
  export declare class PasswordPolicy implements PasswordPolicyInstance {
48
86
  readonly rule: PasswordPolicyEvalFn;
49
87
  readonly serialized?: string;
50
88
  readonly description: string;
51
89
  readonly errorMessage: string;
90
+ readonly code?: string;
91
+ readonly params?: PasswordPolicyParams;
52
92
  constructor(config: PasswordPolicyDef);
53
93
  evaluate(password: string, context?: PasswordPolicyContext): boolean | Promise<boolean>;
54
94
  get transferable(): boolean;
@@ -141,6 +181,13 @@ export declare class UserService<T extends object = object> {
141
181
  */
142
182
  findByIdentifier(value: string): Promise<(UserCredentials & T) | null>;
143
183
  login(handle: string, password: string, lockoutOverride?: Partial<LockoutConfig>): Promise<LoginResult<T>>;
184
+ /**
185
+ * The account checks `login` runs before the password, without one — for a
186
+ * sign-in that proves the first factor another way (a magic link): throws
187
+ * `NOT_FOUND`, `INACTIVE` (incl. a pending invitation) or `LOCKED`, and
188
+ * lifts an expired lock like `login` does. Returns the fresh row.
189
+ */
190
+ assertCanSignIn(id: string): Promise<UserCredentials & T>;
144
191
  /**
145
192
  * Stamp a successful login on the user record: `account.lastLogin = now` and
146
193
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
@@ -460,6 +507,31 @@ export declare class FederatedIdentityStoreMemory extends FederatedIdentityStore
460
507
  touchLogin(provider: string, subject: string, profile?: FederatedProfileSnapshot): Promise<void>;
461
508
  deleteAllForUser(userId: string): Promise<number>;
462
509
  }
510
+ /**
511
+ * English templates of the built-in password policies' texts, by code: the
512
+ * failure (`PP_*`, a policy's `errorMessage`) and the rule
513
+ * (`PP_*_DESCRIPTION`, its `description`). Placeholders: `{min}`, `{max}`,
514
+ * `{count}`. The templates are the plural forms; the policies' own English
515
+ * texts are singular / plural-correct and are the fallback a translator
516
+ * replaces. On a moost server `@aooth/auth-moost` registers them with
517
+ * `registerMessages` on import.
518
+ */
519
+ export declare const PASSWORD_POLICY_MESSAGES: {
520
+ readonly PP_MIN_LENGTH: "Password must be at least {min} characters long";
521
+ readonly PP_MIN_LENGTH_DESCRIPTION: "Minimum length {min}";
522
+ readonly PP_UPPERCASE: "Password must include at least {count} uppercase characters";
523
+ readonly PP_UPPERCASE_DESCRIPTION: "At least {count} uppercase characters";
524
+ readonly PP_LOWERCASE: "Password must include at least {count} lowercase characters";
525
+ readonly PP_LOWERCASE_DESCRIPTION: "At least {count} lowercase characters";
526
+ readonly PP_NUMBER: "Password must include at least {count} numbers";
527
+ readonly PP_NUMBER_DESCRIPTION: "At least {count} numbers";
528
+ readonly PP_SPECIAL_CHAR: "Password must include at least {count} special characters";
529
+ readonly PP_SPECIAL_CHAR_DESCRIPTION: "At least {count} special characters";
530
+ readonly PP_MAX_REPEATED: "Password must not have more than {max} consecutive repeated characters";
531
+ readonly PP_MAX_REPEATED_DESCRIPTION: "No more than {max} consecutive repeated characters";
532
+ };
533
+ /** A code of {@link PASSWORD_POLICY_MESSAGES}. */
534
+ type PasswordPolicyMessageCode = keyof typeof PASSWORD_POLICY_MESSAGES;
463
535
  export declare const ppHasMinLength: (min?: number) => PasswordPolicyDef;
464
536
  export declare const ppHasUpperCase: (n?: number) => PasswordPolicyDef;
465
537
  export declare const ppHasLowerCase: (n?: number) => PasswordPolicyDef;
@@ -496,4 +568,4 @@ export declare function maskEmail(email: string): string;
496
568
  export declare function maskPhone(phone: string): string;
497
569
  export declare function maskMfaValue(method: MfaMethod): string;
498
570
  export declare function setAtPath(obj: object, path: string, value: unknown): void;
499
- export { type AccountData, type DeepPartial, type FederatedIdentity, FederatedIdentityStore, type FederatedIdentityStoreMemoryOptions, type FederatedProfileSnapshot, type LockStatus, type LockoutConfig, type LoginResult, type MfaData, type MfaMethod, type MfaMethodInfo, type NewFederatedIdentity, type PasswordConfig, type PasswordData, type PasswordPolicyContext, type PasswordPolicyDef, type PasswordPolicyEvalFn, type PasswordPolicyInstance, type PolicyCheckResult, type TotpConfig, type TransferablePolicy, type TrustedDeviceRecord, type UserAuthErrorType, type UserCredentials, type UserServiceConfig, UserStore, type UserStoreUpdate, pickDefinedProfile };
571
+ export { type AccountData, type DeepPartial, type FederatedIdentity, FederatedIdentityStore, type FederatedIdentityStoreMemoryOptions, type FederatedProfileSnapshot, type LockStatus, type LockoutConfig, type LoginResult, type MfaData, type MfaMethod, type MfaMethodInfo, type NewFederatedIdentity, type PasswordConfig, type PasswordData, type PasswordPolicyContext, type PasswordPolicyDef, type PasswordPolicyEvalFn, type PasswordPolicyInstance, type PasswordPolicyMessageCode, type PasswordPolicyParams, type PolicyCheckResult, type TotpConfig, type TransferablePolicy, type TrustedDeviceRecord, type UserAuthErrorCode, type UserAuthErrorType, type UserCredentials, type UserServiceConfig, UserStore, type UserStoreUpdate, pickDefinedProfile };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as maskEmail, c as setAtPath, i as incrementAtPath, l as UserStore, n as pickDefinedProfile, o as maskMfaValue, r as deepMerge, s as maskPhone, t as FederatedIdentityStore, u as UserAuthError } from "./federated-identity-store-BZRvw9Pz.mjs";
1
+ import { a as maskEmail, c as setAtPath, d as USER_AUTH_ERROR_MESSAGES, f as UserAuthError, i as incrementAtPath, l as UserStore, n as pickDefinedProfile, o as maskMfaValue, r as deepMerge, s as maskPhone, t as FederatedIdentityStore, u as USER_AUTH_ERROR_CODES } from "./federated-identity-store-CUjGv4O7.mjs";
2
2
  import { createHash, createHmac, randomBytes, randomInt, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
3
3
  // src/base-x/base32.ts
4
4
  /**
@@ -251,7 +251,7 @@ function normalizePolicies(policies) {
251
251
  * and only the server check enforces the rule.
252
252
  */
253
253
  function definePasswordPolicy(opts) {
254
- const { rule, args, description, errorMessage } = opts;
254
+ const { rule, args, description, errorMessage, code, params } = opts;
255
255
  const def = { rule: args ? (v) => rule(v, ...args) : (v) => rule(v, ...[]) };
256
256
  if (args) {
257
257
  const argList = args.map((a) => JSON.stringify(a)).join(", ");
@@ -259,6 +259,8 @@ function definePasswordPolicy(opts) {
259
259
  }
260
260
  if (description !== void 0) def.description = description;
261
261
  if (errorMessage !== void 0) def.errorMessage = errorMessage;
262
+ if (code !== void 0) def.code = code;
263
+ if (params !== void 0) def.params = params;
262
264
  return def;
263
265
  }
264
266
  var PasswordPolicy = class {
@@ -266,11 +268,15 @@ var PasswordPolicy = class {
266
268
  serialized;
267
269
  description;
268
270
  errorMessage;
271
+ code;
272
+ params;
269
273
  constructor(config) {
270
274
  this.rule = config.rule;
271
275
  if (config.serialized !== void 0) this.serialized = config.serialized;
272
276
  this.description = config.description || "";
273
277
  this.errorMessage = config.errorMessage || "";
278
+ if (config.code !== void 0) this.code = config.code;
279
+ if (config.params !== void 0) this.params = config.params;
274
280
  }
275
281
  evaluate(password, context) {
276
282
  return this.rule(password, context);
@@ -502,6 +508,18 @@ var UserService = class {
502
508
  return this.incrementAndMaybeLock(user.id, user.account, "INVALID_CREDENTIALS", lockoutOverride);
503
509
  }
504
510
  /**
511
+ * The account checks `login` runs before the password, without one — for a
512
+ * sign-in that proves the first factor another way (a magic link): throws
513
+ * `NOT_FOUND`, `INACTIVE` (incl. a pending invitation) or `LOCKED`, and
514
+ * lifts an expired lock like `login` does. Returns the fresh row.
515
+ */
516
+ async assertCanSignIn(id) {
517
+ const user = await this.getUser(id);
518
+ if (!user.account.active) throw new UserAuthError("INACTIVE");
519
+ await this.ensureNotLockedOrThrow(user.id, user.account);
520
+ return user;
521
+ }
522
+ /**
505
523
  * Stamp a successful login on the user record: `account.lastLogin = now` and
506
524
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
507
525
  *
@@ -680,7 +698,9 @@ var UserService = class {
680
698
  result.passed = result.passed && passed;
681
699
  result.policies.push({
682
700
  description: policy.description,
683
- passed
701
+ passed,
702
+ errorMessage: policy.errorMessage,
703
+ ...policyCodeOf(policy)
684
704
  });
685
705
  if (!passed) result.errors.push(policy.errorMessage);
686
706
  }
@@ -690,7 +710,8 @@ var UserService = class {
690
710
  return this.config.password.policies.filter((p) => p.transferable).map((p) => ({
691
711
  rule: p.serialized,
692
712
  description: p.description,
693
- errorMessage: p.errorMessage
713
+ errorMessage: p.errorMessage,
714
+ ...policyCodeOf(p)
694
715
  }));
695
716
  }
696
717
  async addMfaMethod(id, method) {
@@ -746,9 +767,7 @@ var UserService = class {
746
767
  * total tries across BOTH factors, not `2 * threshold`.
747
768
  */
748
769
  async verifyMfa(id, code, config, lockoutOverride) {
749
- const user = await this.getUser(id);
750
- if (!user.account.active) throw new UserAuthError("INACTIVE");
751
- await this.ensureNotLockedOrThrow(id, user.account);
770
+ const user = await this.assertCanSignIn(id);
752
771
  const totp = user.mfa.methods.find((m) => m.name === "totp" && m.confirmed);
753
772
  if (!totp) throw new UserAuthError("MFA_NOT_CONFIGURED");
754
773
  const matchedCounter = verifyTotpCode(totp.value, code, config);
@@ -1133,6 +1152,13 @@ function observeWrites(store, hooks) {
1133
1152
  return fn;
1134
1153
  } });
1135
1154
  }
1155
+ /** A policy's message `code` / `params`, when it has them. */
1156
+ function policyCodeOf({ code, params }) {
1157
+ return {
1158
+ ...code !== void 0 && { code },
1159
+ ...params !== void 0 && { params }
1160
+ };
1161
+ }
1136
1162
  // src/store/memory.ts
1137
1163
  var UserStoreMemory = class extends UserStore {
1138
1164
  /** Keyed by the stable surrogate `id` (the token subject). */
@@ -1309,41 +1335,77 @@ function compositeKey(provider, subject) {
1309
1335
  return `${provider}${subject}`;
1310
1336
  }
1311
1337
  // src/password/policies.ts
1338
+ /**
1339
+ * English templates of the built-in password policies' texts, by code: the
1340
+ * failure (`PP_*`, a policy's `errorMessage`) and the rule
1341
+ * (`PP_*_DESCRIPTION`, its `description`). Placeholders: `{min}`, `{max}`,
1342
+ * `{count}`. The templates are the plural forms; the policies' own English
1343
+ * texts are singular / plural-correct and are the fallback a translator
1344
+ * replaces. On a moost server `@aooth/auth-moost` registers them with
1345
+ * `registerMessages` on import.
1346
+ */
1347
+ const PASSWORD_POLICY_MESSAGES = {
1348
+ PP_MIN_LENGTH: "Password must be at least {min} characters long",
1349
+ PP_MIN_LENGTH_DESCRIPTION: "Minimum length {min}",
1350
+ PP_UPPERCASE: "Password must include at least {count} uppercase characters",
1351
+ PP_UPPERCASE_DESCRIPTION: "At least {count} uppercase characters",
1352
+ PP_LOWERCASE: "Password must include at least {count} lowercase characters",
1353
+ PP_LOWERCASE_DESCRIPTION: "At least {count} lowercase characters",
1354
+ PP_NUMBER: "Password must include at least {count} numbers",
1355
+ PP_NUMBER_DESCRIPTION: "At least {count} numbers",
1356
+ PP_SPECIAL_CHAR: "Password must include at least {count} special characters",
1357
+ PP_SPECIAL_CHAR_DESCRIPTION: "At least {count} special characters",
1358
+ PP_MAX_REPEATED: "Password must not have more than {max} consecutive repeated characters",
1359
+ PP_MAX_REPEATED_DESCRIPTION: "No more than {max} consecutive repeated characters"
1360
+ };
1361
+ const plural = (n) => n === 1 ? "" : "s";
1312
1362
  const ppHasMinLength = (min = 8) => definePasswordPolicy({
1313
1363
  rule: (v, min) => v.length >= min,
1314
1364
  args: [min],
1315
1365
  description: `Minimum length ${min}`,
1316
- errorMessage: `Password must be at least ${min} characters long`
1366
+ errorMessage: `Password must be at least ${min} characters long`,
1367
+ code: "PP_MIN_LENGTH",
1368
+ params: { min }
1317
1369
  });
1318
1370
  const ppHasUpperCase = (n = 1) => definePasswordPolicy({
1319
1371
  rule: (v, n) => (v.match(/[A-Z]/g) || []).length >= n,
1320
1372
  args: [n],
1321
- description: `At least ${n} uppercase character${n === 1 ? "" : "s"}`,
1322
- errorMessage: `Password must include at least ${n} uppercase character${n === 1 ? "" : "s"}`
1373
+ description: `At least ${n} uppercase character${plural(n)}`,
1374
+ errorMessage: `Password must include at least ${n} uppercase character${plural(n)}`,
1375
+ code: "PP_UPPERCASE",
1376
+ params: { count: n }
1323
1377
  });
1324
1378
  const ppHasLowerCase = (n = 1) => definePasswordPolicy({
1325
1379
  rule: (v, n) => (v.match(/[a-z]/g) || []).length >= n,
1326
1380
  args: [n],
1327
- description: `At least ${n} lowercase character${n === 1 ? "" : "s"}`,
1328
- errorMessage: `Password must include at least ${n} lowercase character${n === 1 ? "" : "s"}`
1381
+ description: `At least ${n} lowercase character${plural(n)}`,
1382
+ errorMessage: `Password must include at least ${n} lowercase character${plural(n)}`,
1383
+ code: "PP_LOWERCASE",
1384
+ params: { count: n }
1329
1385
  });
1330
1386
  const ppHasNumber = (n = 1) => definePasswordPolicy({
1331
1387
  rule: (v, n) => (v.match(/\d/g) || []).length >= n,
1332
1388
  args: [n],
1333
- description: `At least ${n} number${n === 1 ? "" : "s"}`,
1334
- errorMessage: `Password must include at least ${n} number${n === 1 ? "" : "s"}`
1389
+ description: `At least ${n} number${plural(n)}`,
1390
+ errorMessage: `Password must include at least ${n} number${plural(n)}`,
1391
+ code: "PP_NUMBER",
1392
+ params: { count: n }
1335
1393
  });
1336
1394
  const ppHasSpecialChar = (n = 1) => definePasswordPolicy({
1337
1395
  rule: (v, n) => (v.match(/[^A-Za-z0-9]/g) || []).length >= n,
1338
1396
  args: [n],
1339
- description: `At least ${n} special character${n === 1 ? "" : "s"}`,
1340
- errorMessage: `Password must include at least ${n} special character${n === 1 ? "" : "s"}`
1397
+ description: `At least ${n} special character${plural(n)}`,
1398
+ errorMessage: `Password must include at least ${n} special character${plural(n)}`,
1399
+ code: "PP_SPECIAL_CHAR",
1400
+ params: { count: n }
1341
1401
  });
1342
1402
  const ppMaxRepeatedChars = (maxRepeated = 2) => definePasswordPolicy({
1343
1403
  rule: (v, maxRepeated) => !new RegExp(`(.)\\1{${maxRepeated},}`).test(v),
1344
1404
  args: [maxRepeated],
1345
1405
  description: `No more than ${maxRepeated} consecutive repeated characters`,
1346
- errorMessage: `Password must not have more than ${maxRepeated} consecutive repeated characters`
1406
+ errorMessage: `Password must not have more than ${maxRepeated} consecutive repeated characters`,
1407
+ code: "PP_MAX_REPEATED",
1408
+ params: { max: maxRepeated }
1347
1409
  });
1348
1410
  // src/mfa/codes.ts
1349
1411
  /**
@@ -1370,4 +1432,4 @@ function verifyMfaCode(submitted, expectedHash) {
1370
1432
  if (a.length !== b.length) return false;
1371
1433
  return timingSafeEqual(a, b);
1372
1434
  }
1373
- export { FederatedIdentityStore, FederatedIdentityStoreMemory, PasswordHasher, PasswordPolicy, SEEN_DEVICES_DEFAULT_CAP, UserAuthError, UserService, UserStore, UserStoreMemory, definePasswordPolicy, generateMfaCode, generateTotpCode, generateTotpSecret, generateTotpUri, hashMfaCode, maskEmail, maskMfaValue, maskPhone, normalizePolicies, pickDefinedProfile, ppHasLowerCase, ppHasMinLength, ppHasNumber, ppHasSpecialChar, ppHasUpperCase, ppMaxRepeatedChars, setAtPath, verifyMfaCode, verifyTotpCode };
1435
+ export { FederatedIdentityStore, FederatedIdentityStoreMemory, PASSWORD_POLICY_MESSAGES, PasswordHasher, PasswordPolicy, SEEN_DEVICES_DEFAULT_CAP, USER_AUTH_ERROR_CODES, USER_AUTH_ERROR_MESSAGES, UserAuthError, UserService, UserStore, UserStoreMemory, definePasswordPolicy, generateMfaCode, generateTotpCode, generateTotpSecret, generateTotpUri, hashMfaCode, maskEmail, maskMfaValue, maskPhone, normalizePolicies, pickDefinedProfile, ppHasLowerCase, ppHasMinLength, ppHasNumber, ppHasSpecialChar, ppHasUpperCase, ppMaxRepeatedChars, setAtPath, verifyMfaCode, verifyTotpCode };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aooth/user",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "User credential primitives for aoothjs",
5
5
  "keywords": [
6
6
  "aoothjs",
@@ -60,18 +60,18 @@
60
60
  "access": "public"
61
61
  },
62
62
  "devDependencies": {
63
- "@atscript/core": "^0.2.4",
64
- "@atscript/db": "^0.1.169",
65
- "@atscript/db-sql-tools": "^0.1.169",
66
- "@atscript/db-sqlite": "^0.1.169",
67
- "@atscript/typescript": "^0.2.4",
63
+ "@atscript/core": "^0.2.9",
64
+ "@atscript/db": "^0.1.174",
65
+ "@atscript/db-sql-tools": "^0.1.174",
66
+ "@atscript/db-sqlite": "^0.1.174",
67
+ "@atscript/typescript": "^0.2.9",
68
68
  "@types/better-sqlite3": "^7.6.13",
69
- "@uniqu/core": "^0.2.0",
69
+ "@uniqu/core": "^0.2.1",
70
70
  "better-sqlite3": "^12.6.2",
71
- "unplugin-atscript": "^0.2.4"
71
+ "unplugin-atscript": "^0.2.9"
72
72
  },
73
73
  "peerDependencies": {
74
- "@atscript/db": "^0.1.169"
74
+ "@atscript/db": "^0.1.174"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "@atscript/db": {