@basaltkit/auth 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -137,9 +137,52 @@ const users: UserSource = {
137
137
  },
138
138
  // Optional, but required for email verification and password reset:
139
139
  async update(id, patch: UserPatch) { /* UPDATE ... */ return null },
140
+ // Optional: bulk contact lookup (see below).
141
+ async findByIds(ids) { /* SELECT id, email, email_verified WHERE id IN (...) */ return [] },
140
142
  }
141
143
  ```
142
144
 
145
+ | Method | Required? | Returns | Purpose |
146
+ |---|---|---|---|
147
+ | `findByEmail(email)` | Yes | `AuthUser \| null` | Sign-in and registration lookups. Emails are case-insensitive identities. |
148
+ | `findById(id)` | Yes | `AuthUser \| null` | Resolving the user behind a token, session or API key. |
149
+ | `create({ email, passwordHash })` | Yes | `AuthUser` | Registration; the hash arrives already computed. |
150
+ | `update(id, patch)` | No | `AuthUser \| null` | Email verification and password reset need it (`AUTH_UPDATE_UNSUPPORTED` without it). |
151
+ | `findByIds(ids)` | No | `PublicUser[]` | **Bulk contact lookup** — see below. |
152
+
153
+ #### `findByIds` — one lookup instead of N
154
+
155
+ `findById` resolves one account at a time, which pushes anything that needs the
156
+ *contact details of a group* ("email every admin of this tenant") into either N
157
+ round trips or — worse — reading the auth tables directly from application code,
158
+ coupling the product to the auth schema.
159
+
160
+ `findByIds` is the bulk counterpart, and its contract is deliberately narrower
161
+ than `findById`'s:
162
+
163
+ - it resolves **`PublicUser`**, never `AuthUser` — a directory lookup has no
164
+ business carrying a password hash, and the shipped drivers do not even
165
+ `SELECT` the credential columns;
166
+ - one entry per **found** id, **in the order of `ids`**; ids with no account are
167
+ omitted, so the result may be shorter than the input;
168
+ - duplicate ids collapse to one entry, and an empty list resolves to `[]`
169
+ without touching the database.
170
+
171
+ It is optional: stores written before it keep compiling, and callers fall back
172
+ to one `findById` per id. `@basaltkit/teams` does exactly that — pass the same
173
+ `UserSource` to `teamsPlugin({ users })` and `teams.roleRecipients(tenantId,
174
+ 'admin')` returns the admins' contacts, taking the batched path automatically
175
+ when your driver has one.
176
+
177
+ ```ts
178
+ const contacts = await users.findByIds?.(['u1', 'u2', 'ghost'])
179
+ // → [{ id: 'u1', email: 'ada@acme.test', emailVerified: true }, { id: 'u2', ... }]
180
+ ```
181
+
182
+ The shipped drivers (`@basaltkit/auth-prisma`, `@basaltkit/auth-sqlite`) and
183
+ `MemoryUserSource` all implement it; the SQL ones chunk the id list so a large
184
+ tenant can't exceed the driver's bind-parameter limit.
185
+
143
186
  ### Register, login, and logout (by code)
144
187
 
145
188
  All operations are also available programmatically through the `Auth` class:
@@ -442,7 +485,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
442
485
 
443
486
  | Name | Type | Required? | Default | Description |
444
487
  |---|---|---|---|---|
445
- | `users` | `UserSource` | Yes | — | Where users come from (your DB). |
488
+ | `users` | `UserSource` | Yes | — | Where users come from (your DB). Implement the optional `findByIds` for batched contact lookups. |
446
489
  | `secret` | `string` | Yes | — | Secret that signs the JWTs (HS256). |
447
490
  | `hasher` | `PasswordHasher` | No | `ScryptPasswordHasher` | Password hashing algorithm. |
448
491
  | `sessions` | `SessionStore` | No | `MemorySessionStore` | Session storage. |
@@ -509,6 +552,7 @@ Options (`ApiKeysPluginOptions`):
509
552
  | `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
510
553
  | `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
511
554
  | `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
555
+ | `UserSource.findByIds(ids)` | Optional bulk contact lookup: `PublicUser[]`, in the order of `ids`, missing ids omitted. Powers `@basaltkit/teams`' `roleRecipients`. |
512
556
  | `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
513
557
  | `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
514
558
  | `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
package/dist/stores.d.ts CHANGED
@@ -23,11 +23,32 @@ export interface UserSource {
23
23
  }): Promise<AuthUser>;
24
24
  /** Required for email verification and password reset. Returns the updated user. */
25
25
  update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
26
+ /**
27
+ * Bulk counterpart of {@link UserSource.findById}, for resolving the contact
28
+ * details of accounts the caller already knows — e.g. "email every admin of
29
+ * this tenant" (`@basaltkit/teams`' `roleRecipients`). Without it a caller
30
+ * either makes one round trip per id or reads the auth tables directly; the
31
+ * point of this method is that it has to do neither.
32
+ *
33
+ * Contract:
34
+ * - resolves {@link PublicUser}, **never** `AuthUser` — a directory lookup
35
+ * has no business carrying a password hash, and a driver should not even
36
+ * SELECT the credential columns;
37
+ * - one entry per **found** id, in the order of `ids`; ids with no account
38
+ * are omitted, so the result may be shorter than the input;
39
+ * - duplicate ids yield a single entry, and an empty list resolves to `[]`
40
+ * without touching the database.
41
+ *
42
+ * Optional: stores written before it keep compiling, and callers fall back to
43
+ * one `findById` per id.
44
+ */
45
+ findByIds?(ids: readonly string[]): Promise<PublicUser[]>;
26
46
  }
27
47
  export declare class MemoryUserSource implements UserSource {
28
48
  private readonly users;
29
49
  findByEmail(email: string): Promise<AuthUser | null>;
30
50
  findById(id: string): Promise<AuthUser | null>;
51
+ findByIds(ids: readonly string[]): Promise<PublicUser[]>;
31
52
  create(data: {
32
53
  email: string;
33
54
  passwordHash: string;
package/dist/stores.js CHANGED
@@ -1,6 +1,16 @@
1
1
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
2
  /** SHA-256 of a session id — only this is persisted, never the raw cookie value. */
3
3
  const hashSessionId = (id) => createHash('sha256').update(id).digest('hex');
4
+ /**
5
+ * Projects a stored user onto the safe, non-credential shape. Local to this
6
+ * module: the exported `publicUser` lives in `auth.ts`, which imports from
7
+ * here, so stores can't reach for it without a cycle.
8
+ */
9
+ const contactOf = (user) => ({
10
+ id: user.id,
11
+ email: user.email,
12
+ emailVerified: user.emailVerified ?? false,
13
+ });
4
14
  export class MemoryUserSource {
5
15
  users = new Map();
6
16
  async findByEmail(email) {
@@ -16,6 +26,20 @@ export class MemoryUserSource {
16
26
  async findById(id) {
17
27
  return this.users.get(id) ?? null;
18
28
  }
29
+ async findByIds(ids) {
30
+ const out = [];
31
+ const seen = new Set();
32
+ for (const id of ids) {
33
+ if (seen.has(id))
34
+ continue;
35
+ seen.add(id);
36
+ const user = this.users.get(id);
37
+ // Project, never hand out the live record: this is a contact list.
38
+ if (user)
39
+ out.push(contactOf(user));
40
+ }
41
+ return out;
42
+ }
19
43
  async create(data) {
20
44
  const user = { id: randomUUID(), emailVerified: false, ...data };
21
45
  this.users.set(user.id, user);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -18,8 +18,8 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@basaltkit/core": "^1.3.2",
22
- "@basaltkit/http": "^2.2.0"
21
+ "@basaltkit/core": "^1.4.0",
22
+ "@basaltkit/http": "^2.4.0"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"
@@ -29,7 +29,7 @@
29
29
  "typescript": "^7.0.2",
30
30
  "vitest": "^5.0.1",
31
31
  "zod": "^4.6.5",
32
- "@basaltkit/fastify": "^2.2.0",
32
+ "@basaltkit/fastify": "^2.3.0",
33
33
  "@basaltkit/tsconfig": "^0.24.0"
34
34
  },
35
35
  "publishConfig": {