@smplcty/auth 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +352 -0
  3. package/dist/create-session.d.ts +29 -0
  4. package/dist/create-session.d.ts.map +1 -0
  5. package/dist/create-session.js +108 -0
  6. package/dist/create-session.js.map +1 -0
  7. package/dist/errors.d.ts +44 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/errors.js +54 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/find-user-by-communication-method.d.ts +27 -0
  12. package/dist/find-user-by-communication-method.d.ts.map +1 -0
  13. package/dist/find-user-by-communication-method.js +47 -0
  14. package/dist/find-user-by-communication-method.js.map +1 -0
  15. package/dist/index.d.ts +10 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +13 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/internal/hash-id.d.ts +8 -0
  20. package/dist/internal/hash-id.d.ts.map +1 -0
  21. package/dist/internal/hash-id.js +11 -0
  22. package/dist/internal/hash-id.js.map +1 -0
  23. package/dist/internal/noop-logger.d.ts +7 -0
  24. package/dist/internal/noop-logger.d.ts.map +1 -0
  25. package/dist/internal/noop-logger.js +11 -0
  26. package/dist/internal/noop-logger.js.map +1 -0
  27. package/dist/revoke-session.d.ts +16 -0
  28. package/dist/revoke-session.d.ts.map +1 -0
  29. package/dist/revoke-session.js +22 -0
  30. package/dist/revoke-session.js.map +1 -0
  31. package/dist/set-helpers.d.ts +78 -0
  32. package/dist/set-helpers.d.ts.map +1 -0
  33. package/dist/set-helpers.js +110 -0
  34. package/dist/set-helpers.js.map +1 -0
  35. package/dist/types.d.ts +118 -0
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/types.js +2 -0
  38. package/dist/types.js.map +1 -0
  39. package/dist/validate-session.d.ts +20 -0
  40. package/dist/validate-session.d.ts.map +1 -0
  41. package/dist/validate-session.js +49 -0
  42. package/dist/validate-session.js.map +1 -0
  43. package/dist/with-session.d.ts +33 -0
  44. package/dist/with-session.d.ts.map +1 -0
  45. package/dist/with-session.js +134 -0
  46. package/dist/with-session.js.map +1 -0
  47. package/dist/with-transaction.d.ts +31 -0
  48. package/dist/with-transaction.d.ts.map +1 -0
  49. package/dist/with-transaction.js +49 -0
  50. package/dist/with-transaction.js.map +1 -0
  51. package/package.json +68 -0
  52. package/schema/tables/communication_channels.yaml +11 -0
  53. package/schema/tables/roles.yaml +29 -0
  54. package/schema/tables/sessions.yaml +30 -0
  55. package/schema/tables/tenants.yaml +11 -0
  56. package/schema/tables/user_communication_methods.yaml +23 -0
  57. package/schema/tables/user_roles.yaml +25 -0
  58. package/schema/tables/users.yaml +7 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mabulu Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,352 @@
1
+ # @smplcty/auth
2
+
3
+ Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@smplcty/auth.svg)](https://www.npmjs.com/package/@smplcty/auth)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
+
8
+ ## Why
9
+
10
+ Multi-tenant Postgres apps that use Row-Level Security need three things in every request:
11
+
12
+ 1. A validated session attached to a real user.
13
+ 2. A role for that session that gates which RLS policies apply.
14
+ 3. A list of tenant IDs the session is allowed to see.
15
+
16
+ These need to be set as session variables (`app.session_id`, `app.role_name`, `app.tenant_ids`, `app.all_tenants`) on a dedicated database connection, inside a transaction so they don't leak across requests.
17
+
18
+ `@smplcty/auth` makes that boring and safe. The high-level `withSession` does the whole dance in one call. The low-level `set*` helpers and `withTransaction` are there for migration and unusual cases.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ pnpm add @smplcty/auth pg
24
+ ```
25
+
26
+ `pg` is a peer dependency.
27
+
28
+ ## High-level usage — `withSession`
29
+
30
+ The default API. Hand it a pool, an authenticated session, and a callback. It checks out a connection, opens a transaction, validates the session, sets all four session variables via parameterized `set_config`, runs your code, and commits (or rolls back on throw).
31
+
32
+ ```ts
33
+ import { withSession } from '@smplcty/auth';
34
+
35
+ const widgets = await withSession(
36
+ pool,
37
+ { sessionId, roleName: 'user' },
38
+ async (client, ctx) => {
39
+ // ctx = { userId, tenantIds, allTenants, roles }
40
+ const { rows } = await client.query('SELECT * FROM widgets');
41
+ return rows;
42
+ }
43
+ );
44
+ ```
45
+
46
+ If the session doesn't exist, is expired, or the user doesn't have the requested role, `withSession` throws **before** your callback runs. Your code never sees an invalid context.
47
+
48
+ ### Errors thrown by `withSession`
49
+
50
+ | Error | When |
51
+ |---|---|
52
+ | `SessionNotFoundError` | sessionId doesn't match any row |
53
+ | `SessionExpiredError` | session row exists but `expires_at` has passed |
54
+ | `RoleNotAssignedError` | user does not have the requested role |
55
+ | `InvalidInputError` | sessionId or roleName is empty / wrong type |
56
+
57
+ All errors extend `AuthError` and have a `code` property:
58
+
59
+ ```ts
60
+ try {
61
+ await withSession(pool, { sessionId, roleName: 'user' }, fn);
62
+ } catch (err) {
63
+ if (err instanceof AuthError && err.code === 'SESSION_EXPIRED') {
64
+ // redirect to login
65
+ }
66
+ throw err;
67
+ }
68
+ ```
69
+
70
+ ## Low-level usage — `withTransaction` + `set*` helpers
71
+
72
+ For migrating existing code that has its own session-extraction logic, or for tests, or for any case where you need more control than `withSession` gives you.
73
+
74
+ ```ts
75
+ import {
76
+ withTransaction,
77
+ setSessionId,
78
+ setRoleName,
79
+ setTenantIds,
80
+ setAllTenants,
81
+ } from '@smplcty/auth';
82
+
83
+ await withTransaction(pool, async (client) => {
84
+ await setSessionId(client, sessionId);
85
+ await setRoleName(client, 'user');
86
+ await setTenantIds(client, [1, 2, 3]);
87
+ await setAllTenants(client, false);
88
+
89
+ return client.query('SELECT * FROM widgets');
90
+ });
91
+ ```
92
+
93
+ Or all four at once:
94
+
95
+ ```ts
96
+ import { withTransaction, setSessionContext } from '@smplcty/auth';
97
+
98
+ await withTransaction(pool, async (client) => {
99
+ await setSessionContext(client, {
100
+ sessionId,
101
+ roleName: 'user',
102
+ tenantIds: [1, 2, 3],
103
+ allTenants: false,
104
+ });
105
+ return client.query('SELECT * FROM widgets');
106
+ });
107
+ ```
108
+
109
+ **Important contract:** every `set*` helper requires a `PoolClient` that is already inside an open transaction. The `withTransaction` wrapper guarantees that. If you try to pass a `Pool`, the type checker rejects it. The variables are set with **transaction scope** (`set_config(name, value, true)`) — they are automatically discarded when the transaction commits or rolls back, so cross-request leakage is impossible.
110
+
111
+ The low-level helpers do **not** validate that the session exists or that the user has the role. If you need validation, use `withSession`. If you bypass `withSession`, validate session and role yourself before setting them.
112
+
113
+ ## Sign-in flow primitives
114
+
115
+ `createSession`, `validateSession`, `revokeSession`, and `findUserByCommunicationMethod` are the helpers you need to build a sign-in / sign-out / authorizer flow. None of them are coupled to a specific OTP provider, identity model, or transport.
116
+
117
+ ### `findUserByCommunicationMethod`
118
+
119
+ ```ts
120
+ import { findUserByCommunicationMethod } from '@smplcty/auth';
121
+
122
+ const lookup = await findUserByCommunicationMethod(db, {
123
+ channel: 'email',
124
+ code: 'alice@example.com',
125
+ });
126
+ if (!lookup) {
127
+ // user not registered
128
+ return;
129
+ }
130
+ // lookup = { userId, userCommunicationMethodId }
131
+ ```
132
+
133
+ ### `createSession`
134
+
135
+ ```ts
136
+ import { createSession } from '@smplcty/auth';
137
+
138
+ const session = await createSession(db, {
139
+ userCommunicationMethodId: lookup.userCommunicationMethodId,
140
+ ttl: '30 days',
141
+ ip: req.ip,
142
+ geo: { country: 'US', region: 'CA' },
143
+ });
144
+ // session = { sessionId, userId, createdAt, expiresAt }
145
+ ```
146
+
147
+ `ttl` is a Postgres interval string, evaluated server-side via `now() + interval $ttl`. This means the expiration time has zero clock-skew between your app and the database.
148
+
149
+ ### `validateSession`
150
+
151
+ For authorizers and other "is this token alive?" checks. Returns the Session if valid, throws if not. Does not set any database context.
152
+
153
+ ```ts
154
+ import { validateSession, SessionExpiredError } from '@smplcty/auth';
155
+
156
+ try {
157
+ const session = await validateSession(db, sessionId);
158
+ return { allow: true, principalId: String(session.userId) };
159
+ } catch (err) {
160
+ return { allow: false };
161
+ }
162
+ ```
163
+
164
+ ### `revokeSession`
165
+
166
+ ```ts
167
+ import { revokeSession } from '@smplcty/auth';
168
+
169
+ await revokeSession(db, sessionId); // idempotent — no error if already revoked
170
+ ```
171
+
172
+ Hard-deletes the session row.
173
+
174
+ ## Typed roles
175
+
176
+ By default `roleName` is typed as `string`, which works for any consumer. To get autocomplete and typo detection for your specific role names, write a thin wrapper in your application code:
177
+
178
+ ```ts
179
+ // src/lib/auth.ts
180
+ import {
181
+ withSession as baseWithSession,
182
+ type SessionContext as BaseContext,
183
+ type Pool,
184
+ type PoolClient,
185
+ } from '@smplcty/auth';
186
+
187
+ export type RoleName = 'user' | 'settings' | 'security';
188
+ export type SessionContext = BaseContext<RoleName>;
189
+
190
+ export async function withSession<T>(
191
+ pool: Pool,
192
+ auth: { sessionId: string; roleName: RoleName },
193
+ fn: (client: PoolClient, ctx: SessionContext) => Promise<T>,
194
+ ): Promise<T> {
195
+ return baseWithSession<RoleName, T>(pool, auth, fn);
196
+ }
197
+
198
+ export * from '@smplcty/auth';
199
+ ```
200
+
201
+ Now everywhere in your app:
202
+
203
+ ```ts
204
+ import { withSession, type RoleName } from './lib/auth';
205
+
206
+ await withSession(pool, { sessionId, roleName: 'user' }, async (client, ctx) => {
207
+ ctx.roles; // readonly RoleName[]
208
+ });
209
+ ```
210
+
211
+ A typo in `roleName` becomes a compile error.
212
+
213
+ ## Logging
214
+
215
+ `@smplcty/auth` does not log anything by default. To get diagnostic logs, pass an optional logger to `withSession`:
216
+
217
+ ```ts
218
+ import { withSession } from '@smplcty/auth';
219
+ import pino from 'pino';
220
+
221
+ const logger = pino({ redact: ['*.sessionId', 'headers.authorization'] });
222
+
223
+ await withSession(
224
+ pool,
225
+ { sessionId, roleName: 'user' },
226
+ fn,
227
+ { logger }
228
+ );
229
+ ```
230
+
231
+ The `Logger` interface matches pino's structured-logging shape (`(data, msg)`), so you can pass a pino logger directly with no adapter. The library never logs the session ID or any PII; it logs structural events like `'session validated'` with non-sensitive identifiers like `userId` and a hash prefix of the session ID.
232
+
233
+ If you don't pass a logger, the library is silent.
234
+
235
+ ## Required database schema
236
+
237
+ This library reads and writes specific tables and session variables. It does **not** run migrations — you own your schema. The exact schema the library expects is shipped inside the package at `node_modules/@smplcty/auth/schema/`:
238
+
239
+ ```
240
+ @smplcty/auth/schema/
241
+ └── tables/
242
+ ├── tenants.yaml
243
+ ├── roles.yaml # includes inline seeds for the
244
+ │ # canonical 'user', 'settings',
245
+ │ # 'security' roles (IDs 1-3)
246
+ ├── users.yaml
247
+ ├── communication_channels.yaml
248
+ ├── user_communication_methods.yaml
249
+ ├── user_roles.yaml
250
+ └── sessions.yaml
251
+ ```
252
+
253
+ These files **are** the schema. They are validated end-to-end by the library's own test suite on every release — if the library passes its tests, your database will accept them.
254
+
255
+ The canonical role seeds are colocated with the table definition in `roles.yaml`. Role IDs 1-3 are reserved for the standard `'user'`, `'settings'`, `'security'` rows; consumers adding their own roles should use IDs >= 100. The library never references these IDs directly — it always looks up by name — so the IDs are just a stable convention for migration-time conflict detection.
256
+
257
+ ### If you use [`@smplcty/schema-flow`](https://www.npmjs.com/package/@smplcty/schema-flow)
258
+
259
+ Copy the shipped files into your own schema directory:
260
+
261
+ ```sh
262
+ cp node_modules/@smplcty/auth/schema/tables/*.yaml schema/tables/
263
+ npx @smplcty/schema-flow run
264
+ ```
265
+
266
+ You can edit the copies if you need additional columns (e.g. add a `last_seen_at` to `sessions`) — just keep the columns the library reads/writes intact.
267
+
268
+ ### If you use any other migration tool (Drizzle, Prisma, hand-rolled SQL, …)
269
+
270
+ Translate the YAML manually. The equivalent DDL is:
271
+
272
+ ```sql
273
+ CREATE TABLE tenants (
274
+ tenant_id SERIAL PRIMARY KEY,
275
+ name TEXT NOT NULL UNIQUE
276
+ );
277
+
278
+ CREATE TABLE roles (
279
+ role_id SERIAL PRIMARY KEY,
280
+ name TEXT NOT NULL UNIQUE
281
+ );
282
+ INSERT INTO roles (role_id, name) VALUES
283
+ (1, 'user'),
284
+ (2, 'settings'),
285
+ (3, 'security')
286
+ ON CONFLICT (role_id) DO NOTHING;
287
+
288
+ CREATE TABLE users (
289
+ user_id SERIAL PRIMARY KEY,
290
+ name TEXT
291
+ );
292
+
293
+ CREATE TABLE communication_channels (
294
+ communication_channel_id SERIAL PRIMARY KEY,
295
+ name TEXT NOT NULL UNIQUE
296
+ );
297
+
298
+ CREATE TABLE user_communication_methods (
299
+ user_communication_method_id SERIAL PRIMARY KEY,
300
+ user_id INT NOT NULL REFERENCES users(user_id),
301
+ communication_channel_id INT NOT NULL REFERENCES communication_channels(communication_channel_id),
302
+ code TEXT NOT NULL,
303
+ UNIQUE (communication_channel_id, code)
304
+ );
305
+
306
+ CREATE TABLE user_roles (
307
+ user_role_id SERIAL PRIMARY KEY,
308
+ user_id INT NOT NULL REFERENCES users(user_id),
309
+ role_id INT NOT NULL REFERENCES roles(role_id),
310
+ tenant_id INT REFERENCES tenants(tenant_id) -- NULL = global / all tenants
311
+ );
312
+
313
+ CREATE TABLE sessions (
314
+ session_id TEXT PRIMARY KEY,
315
+ user_communication_method_id INT NOT NULL REFERENCES user_communication_methods(user_communication_method_id),
316
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
317
+ expires_at TIMESTAMPTZ NOT NULL,
318
+ ip TEXT,
319
+ city TEXT,
320
+ region TEXT,
321
+ country TEXT,
322
+ latitude TEXT,
323
+ longitude TEXT
324
+ );
325
+ ```
326
+
327
+ The DDL above is kept in sync with the shipped YAML files by hand. If you're paranoid about drift between this snippet and what the library actually requires, copy the YAML files instead — they are the source of truth.
328
+
329
+ The library also expects four custom Postgres session variables to be readable from your RLS policies:
330
+
331
+ | GUC | Set by | Type |
332
+ |---|---|---|
333
+ | `app.session_id` | `setSessionId` / `setSessionContext` / `withSession` | text |
334
+ | `app.role_name` | `setRoleName` / `setSessionContext` / `withSession` | text |
335
+ | `app.tenant_ids` | `setTenantIds` / `setSessionContext` / `withSession` | comma-separated text (parsed into int[] in policies) |
336
+ | `app.all_tenants` | `setAllTenants` / `setSessionContext` / `withSession` | text `'true'` or `'false'` |
337
+
338
+ These are set with **transaction scope** (`set_config(name, value, true)`) and discarded automatically on COMMIT or ROLLBACK.
339
+
340
+ ## Security model
341
+
342
+ - Every parameterized query — no string interpolation anywhere in the library.
343
+ - Session variables set via `set_config($1, $2, true)`, not `SET ... TO ...` with concatenation. SQL injection in session/role names is impossible.
344
+ - Transaction scope on every session variable. Cross-request leaks are impossible.
345
+ - `withSession` validates session existence, expiration, and role assignment before running the callback. Fails closed on any check.
346
+ - `crypto.randomUUID()` for session IDs (122 bits of entropy).
347
+ - No `console.*` calls in library code. PII in logs is the consumer's choice, not the library's default.
348
+ - No transitive runtime dependencies — only `pg` as a peer dependency.
349
+
350
+ ## License
351
+
352
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,29 @@
1
+ import type { CreateSessionInput, Queryable, Session } from './types.js';
2
+ /**
3
+ * Create a new session for an already-authenticated user.
4
+ *
5
+ * The caller is responsible for verifying the user's identity (via
6
+ * Twilio Verify, OIDC callback, password check, or whatever) BEFORE
7
+ * calling this function. `createSession` does not perform any
8
+ * authentication of its own — it simply persists a session row and
9
+ * returns the new session token.
10
+ *
11
+ * The session ID is generated server-side using `crypto.randomUUID()`
12
+ * (122 bits of entropy). The expiration is computed server-side as
13
+ * `now() + interval $ttl` so there is no clock skew between the app and
14
+ * the database.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const session = await createSession(db, {
19
+ * userCommunicationMethodId: 42,
20
+ * ttl: '30 days',
21
+ * ip: req.ip,
22
+ * geo: { country: 'US', region: 'CA' },
23
+ * });
24
+ * ```
25
+ *
26
+ * @throws {InvalidInputError} If `ttl` is empty or `userCommunicationMethodId` is not a positive integer.
27
+ */
28
+ export declare function createSession(db: Queryable, input: CreateSessionInput): Promise<Session>;
29
+ //# sourceMappingURL=create-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-session.d.ts","sourceRoot":"","sources":["../src/create-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAiDzE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,kBAAkB,GACxB,OAAO,CAAC,OAAO,CAAC,CAyDlB"}
@@ -0,0 +1,108 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { InvalidInputError } from './errors.js';
3
+ const INSERT_SESSION = `
4
+ INSERT INTO sessions (
5
+ session_id,
6
+ user_communication_method_id,
7
+ expires_at,
8
+ ip,
9
+ city,
10
+ region,
11
+ country,
12
+ latitude,
13
+ longitude
14
+ )
15
+ VALUES (
16
+ $1,
17
+ $2,
18
+ now() + ($3)::interval,
19
+ $4,
20
+ $5,
21
+ $6,
22
+ $7,
23
+ $8,
24
+ $9
25
+ )
26
+ RETURNING
27
+ session_id AS "sessionId",
28
+ user_communication_method_id AS "_userCommunicationMethodId",
29
+ created_at AS "createdAt",
30
+ expires_at AS "expiresAt"
31
+ `;
32
+ const SELECT_USER_ID = `
33
+ SELECT user_id AS "userId"
34
+ FROM user_communication_methods
35
+ WHERE user_communication_method_id = $1
36
+ `;
37
+ /**
38
+ * Create a new session for an already-authenticated user.
39
+ *
40
+ * The caller is responsible for verifying the user's identity (via
41
+ * Twilio Verify, OIDC callback, password check, or whatever) BEFORE
42
+ * calling this function. `createSession` does not perform any
43
+ * authentication of its own — it simply persists a session row and
44
+ * returns the new session token.
45
+ *
46
+ * The session ID is generated server-side using `crypto.randomUUID()`
47
+ * (122 bits of entropy). The expiration is computed server-side as
48
+ * `now() + interval $ttl` so there is no clock skew between the app and
49
+ * the database.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const session = await createSession(db, {
54
+ * userCommunicationMethodId: 42,
55
+ * ttl: '30 days',
56
+ * ip: req.ip,
57
+ * geo: { country: 'US', region: 'CA' },
58
+ * });
59
+ * ```
60
+ *
61
+ * @throws {InvalidInputError} If `ttl` is empty or `userCommunicationMethodId` is not a positive integer.
62
+ */
63
+ export async function createSession(db, input) {
64
+ if (!Number.isInteger(input.userCommunicationMethodId) ||
65
+ input.userCommunicationMethodId <= 0) {
66
+ throw new InvalidInputError('userCommunicationMethodId must be a positive integer');
67
+ }
68
+ if (typeof input.ttl !== 'string' || input.ttl.length === 0) {
69
+ throw new InvalidInputError('ttl must be a non-empty Postgres interval string (e.g. "30 days")');
70
+ }
71
+ const sessionId = randomUUID();
72
+ const geo = input.geo ?? {};
73
+ const { rows } = await db.query(INSERT_SESSION, [
74
+ sessionId,
75
+ input.userCommunicationMethodId,
76
+ input.ttl,
77
+ input.ip ?? null,
78
+ geo.city ?? null,
79
+ geo.region ?? null,
80
+ geo.country ?? null,
81
+ geo.latitude ?? null,
82
+ geo.longitude ?? null,
83
+ ]);
84
+ const row = rows[0];
85
+ if (!row) {
86
+ // Should be impossible — INSERT ... RETURNING always produces a row
87
+ // when the INSERT succeeds. If we get here, the FK constraint must
88
+ // have failed silently, which would mean a pg client misconfiguration.
89
+ throw new Error('createSession: INSERT did not return a row');
90
+ }
91
+ const userResult = await db.query(SELECT_USER_ID, [
92
+ input.userCommunicationMethodId,
93
+ ]);
94
+ const userRow = userResult.rows[0];
95
+ if (!userRow) {
96
+ // The FK on sessions.user_communication_method_id should have
97
+ // prevented the INSERT above from succeeding if this row didn't
98
+ // exist. Defensive throw.
99
+ throw new Error('createSession: user_communication_method_id has no matching user');
100
+ }
101
+ return {
102
+ sessionId: row.sessionId,
103
+ userId: userRow.userId,
104
+ createdAt: row.createdAt,
105
+ expiresAt: row.expiresAt,
106
+ };
107
+ }
108
+ //# sourceMappingURL=create-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-session.js","sourceRoot":"","sources":["../src/create-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtB,CAAC;AAEF,MAAM,cAAc,GAAG;;;;CAItB,CAAC;AAaF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,EAAa,EACb,KAAyB;IAEzB,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,yBAAyB,CAAC;QAClD,KAAK,CAAC,yBAAyB,IAAI,CAAC,EACpC,CAAC;QACD,MAAM,IAAI,iBAAiB,CACzB,sDAAsD,CACvD,CAAC;IACJ,CAAC;IACD,IAAI,OAAO,KAAK,CAAC,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,iBAAiB,CACzB,mEAAmE,CACpE,CAAC;IACJ,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,EAAE,CAAC;IAC/B,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,IAAI,EAAE,CAAC;IAE5B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAqB,cAAc,EAAE;QAClE,SAAS;QACT,KAAK,CAAC,yBAAyB;QAC/B,KAAK,CAAC,GAAG;QACT,KAAK,CAAC,EAAE,IAAI,IAAI;QAChB,GAAG,CAAC,IAAI,IAAI,IAAI;QAChB,GAAG,CAAC,MAAM,IAAI,IAAI;QAClB,GAAG,CAAC,OAAO,IAAI,IAAI;QACnB,GAAG,CAAC,QAAQ,IAAI,IAAI;QACpB,GAAG,CAAC,SAAS,IAAI,IAAI;KACtB,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,oEAAoE;QACpE,mEAAmE;QACnE,uEAAuE;QACvE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IAED,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,KAAK,CAAY,cAAc,EAAE;QAC3D,KAAK,CAAC,yBAAyB;KAChC,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACnC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,8DAA8D;QAC9D,gEAAgE;QAChE,0BAA0B;QAC1B,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,SAAS,EAAE,GAAG,CAAC,SAAS;KACzB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Base class for all errors thrown by `@smplcty/auth`. Every error has a
3
+ * `code` discriminator so consumers can `switch` on it without `instanceof`.
4
+ */
5
+ export declare class AuthError extends Error {
6
+ readonly name: string;
7
+ readonly code: string;
8
+ }
9
+ /**
10
+ * Thrown when a session ID does not match any row in the `sessions` table.
11
+ */
12
+ export declare class SessionNotFoundError extends AuthError {
13
+ readonly name = "SessionNotFoundError";
14
+ readonly code: "SESSION_NOT_FOUND";
15
+ constructor(message?: string);
16
+ }
17
+ /**
18
+ * Thrown when a session row exists but its `expires_at` has passed.
19
+ */
20
+ export declare class SessionExpiredError extends AuthError {
21
+ readonly name = "SessionExpiredError";
22
+ readonly code: "SESSION_EXPIRED";
23
+ readonly expiresAt: Date;
24
+ constructor(expiresAt: Date, message?: string);
25
+ }
26
+ /**
27
+ * Thrown when a user does not have the role requested for a session.
28
+ */
29
+ export declare class RoleNotAssignedError extends AuthError {
30
+ readonly name = "RoleNotAssignedError";
31
+ readonly code: "ROLE_NOT_ASSIGNED";
32
+ readonly roleName: string;
33
+ constructor(roleName: string, message?: string);
34
+ }
35
+ /**
36
+ * Thrown when a function input fails validation (empty string, wrong type,
37
+ * etc.) before the library will hit the database.
38
+ */
39
+ export declare class InvalidInputError extends AuthError {
40
+ readonly name = "InvalidInputError";
41
+ readonly code: "INVALID_INPUT";
42
+ constructor(message: string);
43
+ }
44
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC,SAAkB,IAAI,EAAE,MAAM,CAAe;IAC7C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAgB;CACtC;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IACjD,SAAkB,IAAI,0BAA0B;IAChD,SAAkB,IAAI,EAAG,mBAAmB,CAAU;gBAE1C,OAAO,GAAE,MAA4B;CAGlD;AAED;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,SAAS;IAChD,SAAkB,IAAI,yBAAyB;IAC/C,SAAkB,IAAI,EAAG,iBAAiB,CAAU;IACpD,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;gBAEb,SAAS,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,MAAM;CAI9C;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IACjD,SAAkB,IAAI,0BAA0B;IAChD,SAAkB,IAAI,EAAG,mBAAmB,CAAU;IACtD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAI/C;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,SAAS;IAC9C,SAAkB,IAAI,uBAAuB;IAC7C,SAAkB,IAAI,EAAG,eAAe,CAAU;gBAEtC,OAAO,EAAE,MAAM;CAG5B"}
package/dist/errors.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Base class for all errors thrown by `@smplcty/auth`. Every error has a
3
+ * `code` discriminator so consumers can `switch` on it without `instanceof`.
4
+ */
5
+ export class AuthError extends Error {
6
+ name = 'AuthError';
7
+ code = 'AUTH_ERROR';
8
+ }
9
+ /**
10
+ * Thrown when a session ID does not match any row in the `sessions` table.
11
+ */
12
+ export class SessionNotFoundError extends AuthError {
13
+ name = 'SessionNotFoundError';
14
+ code = 'SESSION_NOT_FOUND';
15
+ constructor(message = 'Session not found') {
16
+ super(message);
17
+ }
18
+ }
19
+ /**
20
+ * Thrown when a session row exists but its `expires_at` has passed.
21
+ */
22
+ export class SessionExpiredError extends AuthError {
23
+ name = 'SessionExpiredError';
24
+ code = 'SESSION_EXPIRED';
25
+ expiresAt;
26
+ constructor(expiresAt, message) {
27
+ super(message ?? `Session expired at ${expiresAt.toISOString()}`);
28
+ this.expiresAt = expiresAt;
29
+ }
30
+ }
31
+ /**
32
+ * Thrown when a user does not have the role requested for a session.
33
+ */
34
+ export class RoleNotAssignedError extends AuthError {
35
+ name = 'RoleNotAssignedError';
36
+ code = 'ROLE_NOT_ASSIGNED';
37
+ roleName;
38
+ constructor(roleName, message) {
39
+ super(message ?? `User does not have role: ${roleName}`);
40
+ this.roleName = roleName;
41
+ }
42
+ }
43
+ /**
44
+ * Thrown when a function input fails validation (empty string, wrong type,
45
+ * etc.) before the library will hit the database.
46
+ */
47
+ export class InvalidInputError extends AuthError {
48
+ name = 'InvalidInputError';
49
+ code = 'INVALID_INPUT';
50
+ constructor(message) {
51
+ super(message);
52
+ }
53
+ }
54
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAChB,IAAI,GAAW,WAAW,CAAC;IACpC,IAAI,GAAW,YAAY,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,OAAO,oBAAqB,SAAQ,SAAS;IAC/B,IAAI,GAAG,sBAAsB,CAAC;IAC9B,IAAI,GAAG,mBAA4B,CAAC;IAEtD,YAAY,UAAkB,mBAAmB;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAC9B,IAAI,GAAG,qBAAqB,CAAC;IAC7B,IAAI,GAAG,iBAA0B,CAAC;IAC3C,SAAS,CAAO;IAEzB,YAAY,SAAe,EAAE,OAAgB;QAC3C,KAAK,CAAC,OAAO,IAAI,sBAAsB,SAAS,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,oBAAqB,SAAQ,SAAS;IAC/B,IAAI,GAAG,sBAAsB,CAAC;IAC9B,IAAI,GAAG,mBAA4B,CAAC;IAC7C,QAAQ,CAAS;IAE1B,YAAY,QAAgB,EAAE,OAAgB;QAC5C,KAAK,CAAC,OAAO,IAAI,4BAA4B,QAAQ,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IAC5B,IAAI,GAAG,mBAAmB,CAAC;IAC3B,IAAI,GAAG,eAAwB,CAAC;IAElD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF"}
@@ -0,0 +1,27 @@
1
+ import type { FindUserQuery, Queryable, UserByCommunicationMethod } from './types.js';
2
+ /**
3
+ * Look up the user attached to a communication method (an email address,
4
+ * phone number, etc). Returns `null` if no matching record exists.
5
+ *
6
+ * Returning `null` instead of throwing is deliberate: the caller (a
7
+ * sign-in endpoint, typically) decides whether to expose user-existence
8
+ * information to the client. To avoid the user-enumeration oracle, most
9
+ * sign-in endpoints should return the same response regardless of
10
+ * whether this returns a value or `null`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const lookup = await findUserByCommunicationMethod(db, {
15
+ * channel: 'email',
16
+ * code: 'alice@example.com',
17
+ * });
18
+ * if (!lookup) {
19
+ * // user not registered — but return success anyway to avoid enumeration
20
+ * return { ok: true };
21
+ * }
22
+ * ```
23
+ *
24
+ * @throws {InvalidInputError} If `channel` or `code` is empty.
25
+ */
26
+ export declare function findUserByCommunicationMethod(db: Queryable, query: FindUserQuery): Promise<UserByCommunicationMethod | null>;
27
+ //# sourceMappingURL=find-user-by-communication-method.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find-user-by-communication-method.d.ts","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,aAAa,EACb,SAAS,EACT,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,6BAA6B,CACjD,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,aAAa,GACnB,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAa3C"}