@aooth/user 0.2.5 → 0.2.7

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,10 +1,26 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_federated_identity_store = require("./federated-identity-store-DL0He6X_.cjs");
2
+ const require_federated_identity_store = require("./federated-identity-store-BjGt6Kny.cjs");
3
3
  let node_crypto = require("node:crypto");
4
4
  // src/atscript-db/federated-identity-store.ts
5
5
  function isConflict$1(err) {
6
6
  return typeof err === "object" && err !== null && err.code === "CONFLICT";
7
7
  }
8
+ /** Optional row fields (see {@link fromRow}). */
9
+ const OPTIONAL_FIELDS = [
10
+ "email",
11
+ "emailVerified",
12
+ "displayName",
13
+ "avatarUrl",
14
+ "lastLoginAt"
15
+ ];
16
+ /**
17
+ * The DB returns an unset optional column as `null` on SQL engines; drop it so
18
+ * a row matches the memory store + the `field?` contract.
19
+ */
20
+ function fromRow$1(row) {
21
+ require_federated_identity_store.dropNullFields(row, OPTIONAL_FIELDS);
22
+ return row;
23
+ }
8
24
  /**
9
25
  * `@atscript/db`-backed {@link FederatedIdentityStore}. Pass the resolved table
10
26
  * for the `AoothFederatedIdentity` model shipped at
@@ -23,13 +39,14 @@ var FederatedIdentityStoreAtscriptDb = class extends require_federated_identity_
23
39
  this.clock = opts.clock ?? Date.now;
24
40
  }
25
41
  async find(provider, subject) {
26
- return this.table.findOne({ filter: {
42
+ const row = await this.table.findOne({ filter: {
27
43
  provider,
28
44
  subject
29
45
  } });
46
+ return row && fromRow$1(row);
30
47
  }
31
48
  async listForUser(userId) {
32
- return (await this.table.findMany({ filter: { userId } })).toSorted((a, b) => a.linkedAt - b.linkedAt);
49
+ return (await this.table.findMany({ filter: { userId } })).map(fromRow$1).toSorted((a, b) => a.linkedAt - b.linkedAt);
33
50
  }
34
51
  async link(rec) {
35
52
  const row = {
@@ -75,6 +92,26 @@ var FederatedIdentityStoreAtscriptDb = class extends require_federated_identity_
75
92
  function isConflict(err) {
76
93
  return typeof err === "object" && err !== null && err.code === "CONFLICT";
77
94
  }
95
+ /** Optional aooth-owned `account.*` fields (see {@link fromRow}). */
96
+ const OPTIONAL_ACCOUNT_FIELDS = [
97
+ "pendingInvitation",
98
+ "invitedBy",
99
+ "inviteNonce",
100
+ "verifiedEmail"
101
+ ];
102
+ /** Optional aooth-owned root fields (see {@link fromRow}). */
103
+ const OPTIONAL_ROOT_FIELDS = ["trustedDevices", "seenDevices"];
104
+ /**
105
+ * The DB returns an unset optional column as `null` on SQL engines (Mongo
106
+ * omits the key); drop `null` from the optional aooth-owned paths so a row
107
+ * matches the memory store + the `field?` contract — a NULL `inviteNonce` on a
108
+ * pre-0.2 invite must read as absent, not as a different nonce.
109
+ */
110
+ function fromRow(row) {
111
+ if (row.account) require_federated_identity_store.dropNullFields(row.account, OPTIONAL_ACCOUNT_FIELDS);
112
+ require_federated_identity_store.dropNullFields(row, OPTIONAL_ROOT_FIELDS);
113
+ return row;
114
+ }
78
115
  /**
79
116
  * `@atscript/db`-backed `UserStore`. Pass the resolved table for the
80
117
  * `AoothUserCredentials` (or a `.as` interface extending it) shipped at the
@@ -94,22 +131,25 @@ var UsersStoreAtscriptDb = class extends require_federated_identity_store.UserSt
94
131
  async exists(handle) {
95
132
  return await this.table.count({ filter: { username: handle } }) > 0;
96
133
  }
134
+ /** The one row read every finder goes through — normalized by {@link fromRow}. */
135
+ async findRow(filter) {
136
+ const row = await this.table.findOne({ filter });
137
+ return row && fromRow(row);
138
+ }
97
139
  async findById(id) {
98
- return await this.table.findOne({ filter: { id } });
140
+ return this.findRow({ id });
99
141
  }
100
142
  async findByHandle(handle) {
101
- const byUsername = await this.table.findOne({ filter: { username: handle } });
143
+ const byUsername = await this.findRow({ username: handle });
102
144
  if (byUsername) return byUsername;
103
145
  for (const field of this.handleFields) {
104
- const byHandle = await this.table.findOne({ filter: { [field]: handle } });
146
+ const byHandle = await this.findRow({ [field]: handle });
105
147
  if (byHandle) return byHandle;
106
148
  }
107
149
  return null;
108
150
  }
109
151
  async findByIdentifier(value) {
110
- const byId = await this.table.findOne({ filter: { id: value } });
111
- if (byId) return byId;
112
- return this.findByHandle(value);
152
+ return await this.findRow({ id: value }) ?? this.findByHandle(value);
113
153
  }
114
154
  async create(data) {
115
155
  try {
@@ -108,6 +108,8 @@ export declare class UsersStoreAtscriptDb<TUserCustom extends object = object> e
108
108
  protected readonly handleFields: string[];
109
109
  constructor(opts: UsersStoreAtscriptDbOptions<TUserCustom>);
110
110
  exists(handle: string): Promise<boolean>;
111
+ /** The one row read every finder goes through — normalized by {@link fromRow}. */
112
+ private findRow;
111
113
  findById(id: string): Promise<(UserCredentials & TUserCustom) | null>;
112
114
  findByHandle(handle: string): Promise<(UserCredentials & TUserCustom) | null>;
113
115
  findByIdentifier(value: string): Promise<(UserCredentials & TUserCustom) | null>;
@@ -108,6 +108,8 @@ export declare class UsersStoreAtscriptDb<TUserCustom extends object = object> e
108
108
  protected readonly handleFields: string[];
109
109
  constructor(opts: UsersStoreAtscriptDbOptions<TUserCustom>);
110
110
  exists(handle: string): Promise<boolean>;
111
+ /** The one row read every finder goes through — normalized by {@link fromRow}. */
112
+ private findRow;
111
113
  findById(id: string): Promise<(UserCredentials & TUserCustom) | null>;
112
114
  findByHandle(handle: string): Promise<(UserCredentials & TUserCustom) | null>;
113
115
  findByIdentifier(value: string): Promise<(UserCredentials & TUserCustom) | null>;
@@ -1,9 +1,25 @@
1
- import { c as setAtPath, d as UserAuthError, l as UserStore, n as pickDefinedProfile, t as FederatedIdentityStore } from "./federated-identity-store-B1J4lMeN.mjs";
1
+ import { i as dropNullFields, l as setAtPath, n as pickDefinedProfile, p as UserAuthError, t as FederatedIdentityStore, u as UserStore } from "./federated-identity-store-fEO9MIyH.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  // src/atscript-db/federated-identity-store.ts
4
4
  function isConflict$1(err) {
5
5
  return typeof err === "object" && err !== null && err.code === "CONFLICT";
6
6
  }
7
+ /** Optional row fields (see {@link fromRow}). */
8
+ const OPTIONAL_FIELDS = [
9
+ "email",
10
+ "emailVerified",
11
+ "displayName",
12
+ "avatarUrl",
13
+ "lastLoginAt"
14
+ ];
15
+ /**
16
+ * The DB returns an unset optional column as `null` on SQL engines; drop it so
17
+ * a row matches the memory store + the `field?` contract.
18
+ */
19
+ function fromRow$1(row) {
20
+ dropNullFields(row, OPTIONAL_FIELDS);
21
+ return row;
22
+ }
7
23
  /**
8
24
  * `@atscript/db`-backed {@link FederatedIdentityStore}. Pass the resolved table
9
25
  * for the `AoothFederatedIdentity` model shipped at
@@ -22,13 +38,14 @@ var FederatedIdentityStoreAtscriptDb = class extends FederatedIdentityStore {
22
38
  this.clock = opts.clock ?? Date.now;
23
39
  }
24
40
  async find(provider, subject) {
25
- return this.table.findOne({ filter: {
41
+ const row = await this.table.findOne({ filter: {
26
42
  provider,
27
43
  subject
28
44
  } });
45
+ return row && fromRow$1(row);
29
46
  }
30
47
  async listForUser(userId) {
31
- return (await this.table.findMany({ filter: { userId } })).toSorted((a, b) => a.linkedAt - b.linkedAt);
48
+ return (await this.table.findMany({ filter: { userId } })).map(fromRow$1).toSorted((a, b) => a.linkedAt - b.linkedAt);
32
49
  }
33
50
  async link(rec) {
34
51
  const row = {
@@ -74,6 +91,26 @@ var FederatedIdentityStoreAtscriptDb = class extends FederatedIdentityStore {
74
91
  function isConflict(err) {
75
92
  return typeof err === "object" && err !== null && err.code === "CONFLICT";
76
93
  }
94
+ /** Optional aooth-owned `account.*` fields (see {@link fromRow}). */
95
+ const OPTIONAL_ACCOUNT_FIELDS = [
96
+ "pendingInvitation",
97
+ "invitedBy",
98
+ "inviteNonce",
99
+ "verifiedEmail"
100
+ ];
101
+ /** Optional aooth-owned root fields (see {@link fromRow}). */
102
+ const OPTIONAL_ROOT_FIELDS = ["trustedDevices", "seenDevices"];
103
+ /**
104
+ * The DB returns an unset optional column as `null` on SQL engines (Mongo
105
+ * omits the key); drop `null` from the optional aooth-owned paths so a row
106
+ * matches the memory store + the `field?` contract — a NULL `inviteNonce` on a
107
+ * pre-0.2 invite must read as absent, not as a different nonce.
108
+ */
109
+ function fromRow(row) {
110
+ if (row.account) dropNullFields(row.account, OPTIONAL_ACCOUNT_FIELDS);
111
+ dropNullFields(row, OPTIONAL_ROOT_FIELDS);
112
+ return row;
113
+ }
77
114
  /**
78
115
  * `@atscript/db`-backed `UserStore`. Pass the resolved table for the
79
116
  * `AoothUserCredentials` (or a `.as` interface extending it) shipped at the
@@ -93,22 +130,25 @@ var UsersStoreAtscriptDb = class extends UserStore {
93
130
  async exists(handle) {
94
131
  return await this.table.count({ filter: { username: handle } }) > 0;
95
132
  }
133
+ /** The one row read every finder goes through — normalized by {@link fromRow}. */
134
+ async findRow(filter) {
135
+ const row = await this.table.findOne({ filter });
136
+ return row && fromRow(row);
137
+ }
96
138
  async findById(id) {
97
- return await this.table.findOne({ filter: { id } });
139
+ return this.findRow({ id });
98
140
  }
99
141
  async findByHandle(handle) {
100
- const byUsername = await this.table.findOne({ filter: { username: handle } });
142
+ const byUsername = await this.findRow({ username: handle });
101
143
  if (byUsername) return byUsername;
102
144
  for (const field of this.handleFields) {
103
- const byHandle = await this.table.findOne({ filter: { [field]: handle } });
145
+ const byHandle = await this.findRow({ [field]: handle });
104
146
  if (byHandle) return byHandle;
105
147
  }
106
148
  return null;
107
149
  }
108
150
  async findByIdentifier(value) {
109
- const byId = await this.table.findOne({ filter: { id: value } });
110
- if (byId) return byId;
111
- return this.findByHandle(value);
151
+ return await this.findRow({ id: value }) ?? this.findByHandle(value);
112
152
  }
113
153
  async create(data) {
114
154
  try {
@@ -1,35 +1,62 @@
1
1
  require("node:crypto");
2
2
  // src/errors.ts
3
3
  /**
4
- * The default English message of each `UserAuthError` type — the error's
5
- * `type` is its message code.
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}).
6
27
  *
7
28
  * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
8
- * translator (`setTranslator`) translates a `UserAuthError` by its type and the
29
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
9
30
  * texts reach the `$i18n` the server sends with form schemas and `/meta`.
10
31
  */
11
32
  const USER_AUTH_ERROR_MESSAGES = Object.freeze({
12
- NOT_FOUND: "User not found",
13
- ALREADY_EXISTS: "User already exists",
14
- LOCKED: "Account is locked",
15
- INACTIVE: "Account is not active",
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. */
16
39
  INVALID_CREDENTIALS: "Invalid credentials",
17
- POLICY_VIOLATION: "Password does not meet policy requirements",
40
+ AOOTH_USER_POLICY_VIOLATION: "Password does not meet policy requirements",
18
41
  PASSWORDS_MISMATCH: "Passwords do not match",
19
42
  PASSWORD_IN_HISTORY: "Password was recently used",
20
43
  MFA_REQUIRED: "Multi-factor authentication is required",
21
44
  MFA_INVALID: "Invalid MFA code",
22
45
  MFA_NOT_CONFIGURED: "MFA method is not configured",
23
- CAS_EXHAUSTED: "Update conflict — please retry"
46
+ AOOTH_USER_CAS_EXHAUSTED: "Update conflict — please retry"
24
47
  });
25
48
  var UserAuthError = class extends Error {
26
49
  type;
27
50
  details;
28
51
  name = "UserAuthError";
52
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
53
+ code;
29
54
  constructor(type, message, details) {
30
- super(message ?? USER_AUTH_ERROR_MESSAGES[type]);
55
+ const code = USER_AUTH_ERROR_CODES[type];
56
+ super(message ?? USER_AUTH_ERROR_MESSAGES[code]);
31
57
  this.type = type;
32
58
  this.details = details;
59
+ this.code = code;
33
60
  }
34
61
  };
35
62
  // src/store/user-store.ts
@@ -79,6 +106,11 @@ function deepMerge(target, source) {
79
106
  else t[key] = sv;
80
107
  }
81
108
  }
109
+ /** Delete each of `fields` whose value on `obj` is `null` (in place). */
110
+ function dropNullFields(obj, fields) {
111
+ const o = obj;
112
+ for (const field of fields) if (o[field] === null) delete o[field];
113
+ }
82
114
  function setAtPath(obj, path, value) {
83
115
  const parts = path.split(".");
84
116
  let current = obj;
@@ -137,6 +169,12 @@ Object.defineProperty(exports, "FederatedIdentityStore", {
137
169
  return FederatedIdentityStore;
138
170
  }
139
171
  });
172
+ Object.defineProperty(exports, "USER_AUTH_ERROR_CODES", {
173
+ enumerable: true,
174
+ get: function() {
175
+ return USER_AUTH_ERROR_CODES;
176
+ }
177
+ });
140
178
  Object.defineProperty(exports, "USER_AUTH_ERROR_MESSAGES", {
141
179
  enumerable: true,
142
180
  get: function() {
@@ -161,6 +199,12 @@ Object.defineProperty(exports, "deepMerge", {
161
199
  return deepMerge;
162
200
  }
163
201
  });
202
+ Object.defineProperty(exports, "dropNullFields", {
203
+ enumerable: true,
204
+ get: function() {
205
+ return dropNullFields;
206
+ }
207
+ });
164
208
  Object.defineProperty(exports, "incrementAtPath", {
165
209
  enumerable: true,
166
210
  get: function() {
@@ -1,35 +1,62 @@
1
1
  import "node:crypto";
2
2
  // src/errors.ts
3
3
  /**
4
- * The default English message of each `UserAuthError` type — the error's
5
- * `type` is its message code.
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}).
6
27
  *
7
28
  * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
8
- * translator (`setTranslator`) translates a `UserAuthError` by its type and the
29
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
9
30
  * texts reach the `$i18n` the server sends with form schemas and `/meta`.
10
31
  */
11
32
  const USER_AUTH_ERROR_MESSAGES = Object.freeze({
12
- NOT_FOUND: "User not found",
13
- ALREADY_EXISTS: "User already exists",
14
- LOCKED: "Account is locked",
15
- INACTIVE: "Account is not active",
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. */
16
39
  INVALID_CREDENTIALS: "Invalid credentials",
17
- POLICY_VIOLATION: "Password does not meet policy requirements",
40
+ AOOTH_USER_POLICY_VIOLATION: "Password does not meet policy requirements",
18
41
  PASSWORDS_MISMATCH: "Passwords do not match",
19
42
  PASSWORD_IN_HISTORY: "Password was recently used",
20
43
  MFA_REQUIRED: "Multi-factor authentication is required",
21
44
  MFA_INVALID: "Invalid MFA code",
22
45
  MFA_NOT_CONFIGURED: "MFA method is not configured",
23
- CAS_EXHAUSTED: "Update conflict — please retry"
46
+ AOOTH_USER_CAS_EXHAUSTED: "Update conflict — please retry"
24
47
  });
25
48
  var UserAuthError = class extends Error {
26
49
  type;
27
50
  details;
28
51
  name = "UserAuthError";
52
+ /** The message code — the id the error's text is translated by ({@link USER_AUTH_ERROR_CODES}). */
53
+ code;
29
54
  constructor(type, message, details) {
30
- super(message ?? USER_AUTH_ERROR_MESSAGES[type]);
55
+ const code = USER_AUTH_ERROR_CODES[type];
56
+ super(message ?? USER_AUTH_ERROR_MESSAGES[code]);
31
57
  this.type = type;
32
58
  this.details = details;
59
+ this.code = code;
33
60
  }
34
61
  };
35
62
  // src/store/user-store.ts
@@ -79,6 +106,11 @@ function deepMerge(target, source) {
79
106
  else t[key] = sv;
80
107
  }
81
108
  }
109
+ /** Delete each of `fields` whose value on `obj` is `null` (in place). */
110
+ function dropNullFields(obj, fields) {
111
+ const o = obj;
112
+ for (const field of fields) if (o[field] === null) delete o[field];
113
+ }
82
114
  function setAtPath(obj, path, value) {
83
115
  const parts = path.split(".");
84
116
  let current = obj;
@@ -131,4 +163,4 @@ function pickDefinedProfile(src) {
131
163
  * keeps the federated-login core (`@aooth/idp`, phase 2) storage-agnostic.
132
164
  */
133
165
  var FederatedIdentityStore = class {};
134
- export { maskEmail as a, setAtPath as c, UserAuthError as d, incrementAtPath as i, UserStore as l, pickDefinedProfile as n, maskMfaValue as o, deepMerge as r, maskPhone as s, FederatedIdentityStore as t, USER_AUTH_ERROR_MESSAGES as u };
166
+ export { incrementAtPath as a, maskPhone as c, USER_AUTH_ERROR_CODES as d, USER_AUTH_ERROR_MESSAGES as f, dropNullFields as i, setAtPath as l, pickDefinedProfile as n, maskEmail as o, UserAuthError as p, deepMerge as r, maskMfaValue as s, FederatedIdentityStore as t, UserStore as u };
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-DL0He6X_.cjs");
2
+ const require_federated_identity_store = require("./federated-identity-store-BjGt6Kny.cjs");
3
3
  let node_crypto = require("node:crypto");
4
4
  // src/base-x/base32.ts
5
5
  /**
@@ -509,6 +509,18 @@ var UserService = class {
509
509
  return this.incrementAndMaybeLock(user.id, user.account, "INVALID_CREDENTIALS", lockoutOverride);
510
510
  }
511
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
+ /**
512
524
  * Stamp a successful login on the user record: `account.lastLogin = now` and
513
525
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
514
526
  *
@@ -576,7 +588,7 @@ var UserService = class {
576
588
  accepted = false;
577
589
  const account = user.account;
578
590
  if (!account.pendingInvitation) return null;
579
- if (account.inviteNonce !== void 0 && account.inviteNonce !== nonce) return null;
591
+ if (account.inviteNonce != null && account.inviteNonce !== nonce) return null;
580
592
  accepted = true;
581
593
  return { set: { account: { pendingInvitation: false } } };
582
594
  });
@@ -756,9 +768,7 @@ var UserService = class {
756
768
  * total tries across BOTH factors, not `2 * threshold`.
757
769
  */
758
770
  async verifyMfa(id, code, config, lockoutOverride) {
759
- const user = await this.getUser(id);
760
- if (!user.account.active) throw new require_federated_identity_store.UserAuthError("INACTIVE");
761
- await this.ensureNotLockedOrThrow(id, user.account);
771
+ const user = await this.assertCanSignIn(id);
762
772
  const totp = user.mfa.methods.find((m) => m.name === "totp" && m.confirmed);
763
773
  if (!totp) throw new require_federated_identity_store.UserAuthError("MFA_NOT_CONFIGURED");
764
774
  const matchedCounter = verifyTotpCode(totp.value, code, config);
@@ -1429,6 +1439,7 @@ exports.PASSWORD_POLICY_MESSAGES = PASSWORD_POLICY_MESSAGES;
1429
1439
  exports.PasswordHasher = PasswordHasher;
1430
1440
  exports.PasswordPolicy = PasswordPolicy;
1431
1441
  exports.SEEN_DEVICES_DEFAULT_CAP = SEEN_DEVICES_DEFAULT_CAP;
1442
+ exports.USER_AUTH_ERROR_CODES = require_federated_identity_store.USER_AUTH_ERROR_CODES;
1432
1443
  exports.USER_AUTH_ERROR_MESSAGES = require_federated_identity_store.USER_AUTH_ERROR_MESSAGES;
1433
1444
  exports.UserAuthError = require_federated_identity_store.UserAuthError;
1434
1445
  exports.UserService = UserService;
package/dist/index.d.cts CHANGED
@@ -1,17 +1,42 @@
1
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
2
  /**
3
- * The default English message of each `UserAuthError` type — the error's
4
- * `type` is its message code.
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}).
5
28
  *
6
29
  * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
7
- * translator (`setTranslator`) translates a `UserAuthError` by its type and the
30
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
8
31
  * texts reach the `$i18n` the server sends with form schemas and `/meta`.
9
32
  */
10
- export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorType, string>>;
33
+ export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorCode, string>>;
11
34
  export declare class UserAuthError extends Error {
12
35
  readonly type: UserAuthErrorType;
13
36
  readonly details?: Record<string, unknown> | undefined;
14
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;
15
40
  constructor(type: UserAuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
16
41
  }
17
42
  export declare class PasswordHasher {
@@ -156,6 +181,13 @@ export declare class UserService<T extends object = object> {
156
181
  */
157
182
  findByIdentifier(value: string): Promise<(UserCredentials & T) | null>;
158
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>;
159
191
  /**
160
192
  * Stamp a successful login on the user record: `account.lastLogin = now` and
161
193
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
@@ -536,4 +568,4 @@ export declare function maskEmail(email: string): string;
536
568
  export declare function maskPhone(phone: string): string;
537
569
  export declare function maskMfaValue(method: MfaMethod): string;
538
570
  export declare function setAtPath(obj: object, path: string, value: unknown): void;
539
- 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 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,17 +1,42 @@
1
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
2
  /**
3
- * The default English message of each `UserAuthError` type — the error's
4
- * `type` is its message code.
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}).
5
28
  *
6
29
  * `@aooth/auth-moost` registers it with moost's `registerMessages`, so a moost
7
- * translator (`setTranslator`) translates a `UserAuthError` by its type and the
30
+ * translator (`setTranslator`) translates a `UserAuthError` by its code and the
8
31
  * texts reach the `$i18n` the server sends with form schemas and `/meta`.
9
32
  */
10
- export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorType, string>>;
33
+ export declare const USER_AUTH_ERROR_MESSAGES: Readonly<Record<UserAuthErrorCode, string>>;
11
34
  export declare class UserAuthError extends Error {
12
35
  readonly type: UserAuthErrorType;
13
36
  readonly details?: Record<string, unknown> | undefined;
14
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;
15
40
  constructor(type: UserAuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
16
41
  }
17
42
  export declare class PasswordHasher {
@@ -156,6 +181,13 @@ export declare class UserService<T extends object = object> {
156
181
  */
157
182
  findByIdentifier(value: string): Promise<(UserCredentials & T) | null>;
158
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>;
159
191
  /**
160
192
  * Stamp a successful login on the user record: `account.lastLogin = now` and
161
193
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
@@ -536,4 +568,4 @@ export declare function maskEmail(email: string): string;
536
568
  export declare function maskPhone(phone: string): string;
537
569
  export declare function maskMfaValue(method: MfaMethod): string;
538
570
  export declare function setAtPath(obj: object, path: string, value: unknown): void;
539
- 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 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, d 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_MESSAGES } from "./federated-identity-store-B1J4lMeN.mjs";
1
+ import { a as incrementAtPath, c as maskPhone, d as USER_AUTH_ERROR_CODES, f as USER_AUTH_ERROR_MESSAGES, l as setAtPath, n as pickDefinedProfile, o as maskEmail, p as UserAuthError, r as deepMerge, s as maskMfaValue, t as FederatedIdentityStore, u as UserStore } from "./federated-identity-store-fEO9MIyH.mjs";
2
2
  import { createHash, createHmac, randomBytes, randomInt, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
3
3
  // src/base-x/base32.ts
4
4
  /**
@@ -508,6 +508,18 @@ var UserService = class {
508
508
  return this.incrementAndMaybeLock(user.id, user.account, "INVALID_CREDENTIALS", lockoutOverride);
509
509
  }
510
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
+ /**
511
523
  * Stamp a successful login on the user record: `account.lastLogin = now` and
512
524
  * reset `account.failedLoginAttempts = 0`. The single writer of `lastLogin`.
513
525
  *
@@ -575,7 +587,7 @@ var UserService = class {
575
587
  accepted = false;
576
588
  const account = user.account;
577
589
  if (!account.pendingInvitation) return null;
578
- if (account.inviteNonce !== void 0 && account.inviteNonce !== nonce) return null;
590
+ if (account.inviteNonce != null && account.inviteNonce !== nonce) return null;
579
591
  accepted = true;
580
592
  return { set: { account: { pendingInvitation: false } } };
581
593
  });
@@ -755,9 +767,7 @@ var UserService = class {
755
767
  * total tries across BOTH factors, not `2 * threshold`.
756
768
  */
757
769
  async verifyMfa(id, code, config, lockoutOverride) {
758
- const user = await this.getUser(id);
759
- if (!user.account.active) throw new UserAuthError("INACTIVE");
760
- await this.ensureNotLockedOrThrow(id, user.account);
770
+ const user = await this.assertCanSignIn(id);
761
771
  const totp = user.mfa.methods.find((m) => m.name === "totp" && m.confirmed);
762
772
  if (!totp) throw new UserAuthError("MFA_NOT_CONFIGURED");
763
773
  const matchedCounter = verifyTotpCode(totp.value, code, config);
@@ -1422,4 +1432,4 @@ function verifyMfaCode(submitted, expectedHash) {
1422
1432
  if (a.length !== b.length) return false;
1423
1433
  return timingSafeEqual(a, b);
1424
1434
  }
1425
- export { FederatedIdentityStore, FederatedIdentityStoreMemory, PASSWORD_POLICY_MESSAGES, PasswordHasher, PasswordPolicy, SEEN_DEVICES_DEFAULT_CAP, 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 };
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.5",
3
+ "version": "0.2.7",
4
4
  "description": "User credential primitives for aoothjs",
5
5
  "keywords": [
6
6
  "aoothjs",
@@ -42,6 +42,10 @@
42
42
  "import": "./dist/atscript-db.mjs",
43
43
  "require": "./dist/atscript-db.cjs"
44
44
  },
45
+ "./atscript-db/model": {
46
+ "types": "./src/atscript-db/user-credentials.as.d.ts",
47
+ "default": "./src/atscript-db/user-credentials.as"
48
+ },
45
49
  "./atscript-db/model.as": {
46
50
  "types": "./src/atscript-db/user-credentials.as.d.ts",
47
51
  "default": "./src/atscript-db/user-credentials.as"
@@ -60,18 +64,18 @@
60
64
  "access": "public"
61
65
  },
62
66
  "devDependencies": {
63
- "@atscript/core": "^0.2.8",
64
- "@atscript/db": "^0.1.171",
65
- "@atscript/db-sql-tools": "^0.1.171",
66
- "@atscript/db-sqlite": "^0.1.171",
67
- "@atscript/typescript": "^0.2.8",
67
+ "@atscript/core": "^0.2.11",
68
+ "@atscript/db": "^0.1.175",
69
+ "@atscript/db-sql-tools": "^0.1.175",
70
+ "@atscript/db-sqlite": "^0.1.175",
71
+ "@atscript/typescript": "^0.2.11",
68
72
  "@types/better-sqlite3": "^7.6.13",
69
- "@uniqu/core": "^0.2.1",
73
+ "@uniqu/core": "^0.2.2",
70
74
  "better-sqlite3": "^12.6.2",
71
- "unplugin-atscript": "^0.2.8"
75
+ "unplugin-atscript": "^0.2.11"
72
76
  },
73
77
  "peerDependencies": {
74
- "@atscript/db": "^0.1.171"
78
+ "@atscript/db": "^0.1.175"
75
79
  },
76
80
  "peerDependenciesMeta": {
77
81
  "@atscript/db": {