@smplcty/auth 0.6.4 → 2.0.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 (90) hide show
  1. package/README.md +187 -201
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +16 -18
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/errors.d.ts +19 -4
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +23 -5
  9. package/dist/errors.js.map +1 -1
  10. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  11. package/dist/find-user-by-communication-method.js +4 -0
  12. package/dist/find-user-by-communication-method.js.map +1 -1
  13. package/dist/get-user-role-names.d.ts.map +1 -1
  14. package/dist/get-user-role-names.js +2 -0
  15. package/dist/get-user-role-names.js.map +1 -1
  16. package/dist/index.d.ts +9 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +12 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal/hash-token.d.ts +16 -0
  21. package/dist/internal/hash-token.d.ts.map +1 -0
  22. package/dist/internal/hash-token.js +21 -0
  23. package/dist/internal/hash-token.js.map +1 -0
  24. package/dist/methods/errors.d.ts +23 -0
  25. package/dist/methods/errors.d.ts.map +1 -0
  26. package/dist/methods/errors.js +28 -0
  27. package/dist/methods/errors.js.map +1 -0
  28. package/dist/methods/oidc/index.d.ts +92 -0
  29. package/dist/methods/oidc/index.d.ts.map +1 -0
  30. package/dist/methods/oidc/index.js +104 -0
  31. package/dist/methods/oidc/index.js.map +1 -0
  32. package/dist/methods/router.d.ts +19 -0
  33. package/dist/methods/router.d.ts.map +1 -0
  34. package/dist/methods/router.js +95 -0
  35. package/dist/methods/router.js.map +1 -0
  36. package/dist/methods/twilio/index.d.ts +44 -0
  37. package/dist/methods/twilio/index.d.ts.map +1 -0
  38. package/dist/methods/twilio/index.js +77 -0
  39. package/dist/methods/twilio/index.js.map +1 -0
  40. package/dist/methods/types.d.ts +106 -0
  41. package/dist/methods/types.d.ts.map +1 -0
  42. package/dist/methods/types.js +2 -0
  43. package/dist/methods/types.js.map +1 -0
  44. package/dist/revoke-session.d.ts +20 -15
  45. package/dist/revoke-session.d.ts.map +1 -1
  46. package/dist/revoke-session.js +66 -20
  47. package/dist/revoke-session.js.map +1 -1
  48. package/dist/scope/flat-tenant.d.ts +36 -0
  49. package/dist/scope/flat-tenant.d.ts.map +1 -0
  50. package/dist/scope/flat-tenant.js +60 -0
  51. package/dist/scope/flat-tenant.js.map +1 -0
  52. package/dist/set-helpers.d.ts +44 -53
  53. package/dist/set-helpers.d.ts.map +1 -1
  54. package/dist/set-helpers.js +67 -68
  55. package/dist/set-helpers.js.map +1 -1
  56. package/dist/touch-session.d.ts +13 -0
  57. package/dist/touch-session.d.ts.map +1 -0
  58. package/dist/touch-session.js +28 -0
  59. package/dist/touch-session.js.map +1 -0
  60. package/dist/types.d.ts +59 -18
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/validate-session.d.ts +15 -14
  63. package/dist/validate-session.d.ts.map +1 -1
  64. package/dist/validate-session.js +28 -27
  65. package/dist/validate-session.js.map +1 -1
  66. package/dist/with-service-context.d.ts +15 -12
  67. package/dist/with-service-context.d.ts.map +1 -1
  68. package/dist/with-service-context.js +34 -30
  69. package/dist/with-service-context.js.map +1 -1
  70. package/dist/with-session.d.ts +22 -16
  71. package/dist/with-session.d.ts.map +1 -1
  72. package/dist/with-session.js +67 -63
  73. package/dist/with-session.js.map +1 -1
  74. package/package.json +33 -2
  75. package/schema/functions/current_user_id.yaml +18 -0
  76. package/schema/functions/resolve_session.yaml +42 -23
  77. package/schema/post/0001-backfill-audit-by.sql +15 -0
  78. package/schema/tables/auth_domains.yaml +43 -0
  79. package/schema/tables/communication_channels.yaml +5 -1
  80. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  81. package/schema/tables/roles.yaml +43 -7
  82. package/schema/tables/sessions.yaml +10 -0
  83. package/schema/tables/tenants.yaml +24 -1
  84. package/schema/tables/user_communication_methods.yaml +5 -1
  85. package/schema/tables/user_roles.yaml +1 -0
  86. package/schema/tables/users.yaml +27 -0
  87. package/dist/with-transaction.d.ts +0 -31
  88. package/dist/with-transaction.d.ts.map +0 -1
  89. package/dist/with-transaction.js +0 -49
  90. package/dist/with-transaction.js.map +0 -1
@@ -1,48 +1,49 @@
1
1
  import { InvalidInputError, SessionExpiredError, SessionNotFoundError } from './errors.js';
2
- const TS_SUFFIX = process.env['USE_AT_FOR_TIMESTAMPS'] !== 'false' ? '_at' : '';
3
- const CREATED_COL = `created${TS_SUFFIX}`;
2
+ import { hashToken } from './internal/hash-token.js';
4
3
  const SELECT_SESSION = `
5
4
  SELECT
6
- s.session_id AS "sessionId",
7
- ucm.user_id AS "userId",
8
- s.${CREATED_COL} AS "createdAt",
9
- s.expires_at AS "expiresAt"
5
+ ucm.user_id AS "userId",
6
+ s.created_at AS "createdAt",
7
+ s.expires_at AS "expiresAt",
8
+ s.last_seen_at AS "lastSeenAt"
10
9
  FROM sessions s
11
10
  JOIN user_communication_methods ucm
12
11
  ON ucm.user_communication_method_id = s.user_communication_method_id
12
+ JOIN users u ON u.user_id = ucm.user_id
13
13
  WHERE s.session_id = $1
14
+ AND s.deleted_at IS NULL
15
+ AND ucm.deleted_at IS NULL
16
+ AND u.deleted_at IS NULL
14
17
  `;
15
18
  /**
16
- * Look up a session by ID and verify it is still valid.
19
+ * Look up a session by its raw token and verify it is still valid.
17
20
  *
18
- * Returns the {@link Session} on success. Throws if the session does
19
- * not exist, has expired, or the input is malformed. Does not set any
20
- * Postgres session variables — this is purely a check.
21
+ * Hashes the token, finds the matching `sessions` row, and returns its
22
+ * {@link SessionInfo} on success. Throws if the token matches no session,
23
+ * the session has expired (or was revoked — revocation sets `expires_at`
24
+ * to now), or the input is malformed. Sets no GUCs — this is purely a
25
+ * check.
21
26
  *
22
- * Use this function in API Gateway authorizers, refresh-token flows,
23
- * and any other place where you need to verify a token without entering
24
- * a request transaction. For an authenticated request that will run
25
- * queries, use {@link withSession} instead — it does this validation
26
- * AND sets up the database context in one call.
27
+ * Use this in API Gateway authorizers, refresh flows, and anywhere you
28
+ * need to verify a token without entering a request transaction. For an
29
+ * authenticated request that will run queries, use {@link withSession} —
30
+ * it validates AND sets up the database context in one call.
27
31
  *
28
- * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
29
- * @throws {SessionNotFoundError} If no row matches `sessionId`.
30
- * @throws {SessionExpiredError} If the session row exists but `expires_at` has passed.
32
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
33
+ * @throws {SessionNotFoundError} If no session matches the token.
34
+ * @throws {SessionExpiredError} If the session has expired or was revoked.
31
35
  */
32
- export async function validateSession(db, sessionId) {
33
- if (typeof sessionId !== 'string' || sessionId.length === 0) {
34
- throw new InvalidInputError('sessionId must be a non-empty string');
36
+ export async function validateSession(db, token) {
37
+ if (typeof token !== 'string' || token.length === 0) {
38
+ throw new InvalidInputError('token must be a non-empty string');
35
39
  }
36
- const { rows } = await db.query(SELECT_SESSION, [sessionId]);
40
+ const { rows } = await db.query(SELECT_SESSION, [hashToken(token)]);
37
41
  const row = rows[0];
38
42
  if (!row) {
39
43
  throw new SessionNotFoundError();
40
44
  }
41
- // Compare against the database's now() rather than the local clock
42
- // would be ideal, but we already trust the row that the DB returned
43
- // and `expiresAt` is a timestamptz that pg parses to a JS Date.
44
- // Local-clock comparison is fine here because expiry is server-set
45
- // by createSession; we're only checking "have we passed it yet."
45
+ // Expiry is server-set by createSession (and by revoke, which sets it to
46
+ // now()). Local-clock comparison only checks "have we passed it yet."
46
47
  if (row.expiresAt.getTime() <= Date.now()) {
47
48
  throw new SessionExpiredError(row.expiresAt);
48
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"validate-session.js","sourceRoot":"","sources":["../src/validate-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AA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;;;;;;;CActB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,EAAa,EAAE,KAAa;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,iBAAiB,CAAC,kCAAkC,CAAC,CAAC;IAClE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAc,cAAc,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACjF,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,oBAAoB,EAAE,CAAC;IACnC,CAAC;IAED,yEAAyE;IACzE,sEAAsE;IACtE,IAAI,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;QAC1C,MAAM,IAAI,mBAAmB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,24 +1,27 @@
1
1
  import type { Pool, PoolClient } from 'pg';
2
2
  /**
3
- * Check out a client from the pool, set service-level GUCs
4
- * (role=settings, all_tenants=true, session_id=serviceName), run the
5
- * callback, and release the client.
3
+ * Run background work as a named service principal, inside a `@smplcty/db`
4
+ * transaction with `app.actor_id` set to that principal's `user_id`.
6
5
  *
7
- * Use this for background Lambdas that need to bypass RLS without a
8
- * real user session. The GUCs are set session-scoped (not
9
- * transaction-local) so they persist across all queries on the held
10
- * client without requiring a wrapping transaction.
6
+ * Background writers (ingestion, transform workers, app-init) have no human
7
+ * session, but audit attribution (`created_by`/`updated_by`, stamped from
8
+ * `app.actor_id`) is NOT NULL — so service writes need an actor too.
9
+ * Provision a `users` row with `kind = 'service'` for each service and pass
10
+ * its name here.
11
+ *
12
+ * Sets `app.actor_id` (the service's user_id) and `app.session_id` (the
13
+ * service name, for correlation). No active role / privileges — service
14
+ * principals act through `current_user_id()` and RLS, not roles.
11
15
  *
12
16
  * @example
13
17
  * ```ts
14
- * const pool = await getPool();
15
- * return withServiceContext(pool, 'handle-hierarchy-refresh', async (client) => {
16
- * const { rows } = await client.query('SELECT * FROM hierarchy_change_log');
17
- * // ... business logic
18
+ * await withServiceContext(pool, 'transform-worker', async (client) => {
19
+ * await client.query('INSERT INTO metrics (...) VALUES (...)'); // audited to the service
18
20
  * });
19
21
  * ```
20
22
  *
21
- * @throws {InvalidInputError} If `serviceName` is empty.
23
+ * @throws {InvalidInputError} If `serviceName` is empty.
24
+ * @throws {ServicePrincipalNotFoundError} If no `kind='service'` user has that name.
22
25
  */
23
26
  export declare function withServiceContext<T>(pool: Pool, serviceName: string, fn: (client: PoolClient) => Promise<T>): Promise<T>;
24
27
  //# sourceMappingURL=with-service-context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"with-service-context.d.ts","sourceRoot":"","sources":["../src/with-service-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAW3C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,IAAI,EAAE,IAAI,EACV,WAAW,EAAE,MAAM,EACnB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,GACrC,OAAO,CAAC,CAAC,CAAC,CAcZ"}
1
+ {"version":3,"file":"with-service-context.d.ts","sourceRoot":"","sources":["../src/with-service-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAgB3C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,IAAI,EAAE,IAAI,EACV,WAAW,EAAE,MAAM,EACnB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,GACrC,OAAO,CAAC,CAAC,CAAC,CAiBZ"}
@@ -1,45 +1,49 @@
1
- import { InvalidInputError } from './errors.js';
2
- import { SESSION_VAR_NAMES } from './set-helpers.js';
1
+ import { withTransaction } from '@smplcty/db';
2
+ import { InvalidInputError, ServicePrincipalNotFoundError } from './errors.js';
3
+ import { setActorId, setSessionId } from './set-helpers.js';
4
+ const SELECT_SERVICE_USER = `
5
+ SELECT user_id AS "userId"
6
+ FROM users
7
+ WHERE name = $1 AND kind = 'service'
8
+ LIMIT 1
9
+ `;
3
10
  /**
4
- * Session-scoped `set_config` — persists for the lifetime of the
5
- * connection, not just the current transaction. Used by background
6
- * jobs that run multiple statements outside a transaction.
7
- */
8
- const SET_CONFIG_SESSION = 'SELECT set_config($1, $2, false)';
9
- /**
10
- * Check out a client from the pool, set service-level GUCs
11
- * (role=settings, all_tenants=true, session_id=serviceName), run the
12
- * callback, and release the client.
11
+ * Run background work as a named service principal, inside a `@smplcty/db`
12
+ * transaction with `app.actor_id` set to that principal's `user_id`.
13
+ *
14
+ * Background writers (ingestion, transform workers, app-init) have no human
15
+ * session, but audit attribution (`created_by`/`updated_by`, stamped from
16
+ * `app.actor_id`) is NOT NULL — so service writes need an actor too.
17
+ * Provision a `users` row with `kind = 'service'` for each service and pass
18
+ * its name here.
13
19
  *
14
- * Use this for background Lambdas that need to bypass RLS without a
15
- * real user session. The GUCs are set session-scoped (not
16
- * transaction-local) so they persist across all queries on the held
17
- * client without requiring a wrapping transaction.
20
+ * Sets `app.actor_id` (the service's user_id) and `app.session_id` (the
21
+ * service name, for correlation). No active role / privileges — service
22
+ * principals act through `current_user_id()` and RLS, not roles.
18
23
  *
19
24
  * @example
20
25
  * ```ts
21
- * const pool = await getPool();
22
- * return withServiceContext(pool, 'handle-hierarchy-refresh', async (client) => {
23
- * const { rows } = await client.query('SELECT * FROM hierarchy_change_log');
24
- * // ... business logic
26
+ * await withServiceContext(pool, 'transform-worker', async (client) => {
27
+ * await client.query('INSERT INTO metrics (...) VALUES (...)'); // audited to the service
25
28
  * });
26
29
  * ```
27
30
  *
28
- * @throws {InvalidInputError} If `serviceName` is empty.
31
+ * @throws {InvalidInputError} If `serviceName` is empty.
32
+ * @throws {ServicePrincipalNotFoundError} If no `kind='service'` user has that name.
29
33
  */
30
34
  export async function withServiceContext(pool, serviceName, fn) {
31
35
  if (typeof serviceName !== 'string' || serviceName.length === 0) {
32
36
  throw new InvalidInputError('serviceName must be a non-empty string');
33
37
  }
34
- const client = await pool.connect();
35
- try {
36
- await client.query(SET_CONFIG_SESSION, [SESSION_VAR_NAMES.sessionId, serviceName]);
37
- await client.query(SET_CONFIG_SESSION, [SESSION_VAR_NAMES.roleName, 'settings']);
38
- await client.query(SET_CONFIG_SESSION, [SESSION_VAR_NAMES.allTenants, 'true']);
39
- return await fn(client);
40
- }
41
- finally {
42
- client.release();
43
- }
38
+ return withTransaction(pool, async (client) => {
39
+ const { rows } = await client.query(SELECT_SERVICE_USER, [serviceName]);
40
+ const row = rows[0];
41
+ if (!row) {
42
+ throw new ServicePrincipalNotFoundError(serviceName);
43
+ }
44
+ await setActorId(client, row.userId);
45
+ await setSessionId(client, serviceName);
46
+ return fn(client);
47
+ });
44
48
  }
45
49
  //# sourceMappingURL=with-service-context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"with-service-context.js","sourceRoot":"","sources":["../src/with-service-context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,IAAU,EACV,WAAmB,EACnB,EAAs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C;IACxE,CAAC;IAED,OAAO,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;QAC5C,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CAAiB,mBAAmB,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;QACxF,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,MAAM,IAAI,6BAA6B,CAAC,WAAW,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,YAAY,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAExC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,33 +1,39 @@
1
1
  import type { Pool, PoolClient } from 'pg';
2
2
  import type { SessionAuth, SessionContext, WithSessionOptions } from './types.js';
3
3
  /**
4
- * The high-level "just make it work" entry point. Checks out a
5
- * connection, opens a transaction, validates the session, validates the
6
- * role, sets the four `app.*` GUC variables via parameterized
7
- * `set_config(_, _, true)`, runs the callback, and commits (or rolls
8
- * back on throw).
4
+ * The high-level "just make it work" request entry point. Opens a
5
+ * `@smplcty/db` transaction, resolves the session from its token, validates
6
+ * it, picks and validates the active role, sets the identity GUCs, runs the
7
+ * app scope hook, then runs the callback — committing on success or rolling
8
+ * back on throw.
9
9
  *
10
- * The session variables use **transaction scope**, so they're discarded
11
- * automatically when this function returns. Cross-request leakage is
12
- * impossible.
10
+ * Active-role selection (in TS, not the resolver):
11
+ * 1. `roleName` if given — must be one the user holds, else {@link RoleNotHeldError}.
12
+ * 2. otherwise the user's default role, if any.
13
+ * 3. otherwise none — a privilege-only request, which is **not** an error.
14
+ *
15
+ * Identity GUCs are transaction-local, so they vanish on COMMIT/ROLLBACK —
16
+ * no cross-request leakage. Scope GUCs are not set here: pass a `scope`
17
+ * hook (e.g. `flatTenantScope()`) for that, or rely on function-carried RLS.
13
18
  *
14
19
  * @example
15
20
  * ```ts
16
21
  * const widgets = await withSession(
17
22
  * pool,
18
- * { sessionId, roleName: 'user' },
23
+ * { token, roleName: 'user' },
19
24
  * async (client, ctx) => {
20
- * // ctx = { userId, tenantIds, allTenants, roles }
25
+ * // ctx = { userId, activeRole, roles, privileges }
21
26
  * const { rows } = await client.query('SELECT * FROM widgets');
22
27
  * return rows;
23
- * }
28
+ * },
29
+ * { scope: flatTenantScope() },
24
30
  * );
25
31
  * ```
26
32
  *
27
- * @throws {SessionNotFoundError} If no session row matches `auth.sessionId`.
28
- * @throws {SessionExpiredError} If the session has passed its `expires_at`.
29
- * @throws {RoleNotAssignedError} If the user does not have `auth.roleName`.
30
- * @throws {InvalidInputError} If `auth.sessionId` or `auth.roleName` is empty.
33
+ * @throws {SessionNotFoundError} If no session matches the token.
34
+ * @throws {SessionExpiredError} If the session has expired (or was revoked).
35
+ * @throws {RoleNotHeldError} If `roleName` is given but not held.
36
+ * @throws {InvalidInputError} If `token` is empty.
31
37
  */
32
- export declare function withSession<TRole extends string = string, T = unknown>(pool: Pool, auth: SessionAuth<TRole>, fn: (client: PoolClient, ctx: SessionContext<TRole>) => Promise<T>, options?: WithSessionOptions): Promise<T>;
38
+ export declare function withSession<TRole extends string = string, T = unknown>(pool: Pool, auth: SessionAuth<TRole>, fn: (client: PoolClient, ctx: SessionContext<TRole>) => Promise<T>, options?: WithSessionOptions<TRole>): Promise<T>;
33
39
  //# sourceMappingURL=with-session.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"with-session.d.ts","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAK3C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA6ClF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,OAAO,EAC1E,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,EACxB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,cAAc,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAClE,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,CAAC,CAAC,CAkDZ"}
1
+ {"version":3,"file":"with-session.d.ts","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAO3C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA2BlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,OAAO,EAC1E,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,EACxB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,cAAc,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAClE,OAAO,GAAE,kBAAkB,CAAC,KAAK,CAAM,GACtC,OAAO,CAAC,CAAC,CAAC,CA+DZ"}
@@ -1,105 +1,109 @@
1
- import { RoleNotAssignedError, SessionExpiredError, SessionNotFoundError } from './errors.js';
1
+ import { withTransaction } from '@smplcty/db';
2
+ import { RoleNotHeldError, SessionExpiredError, SessionNotFoundError } from './errors.js';
2
3
  import { hashId } from './internal/hash-id.js';
4
+ import { hashToken } from './internal/hash-token.js';
3
5
  import { noopLogger } from './internal/noop-logger.js';
4
- import { setSessionContext } from './set-helpers.js';
5
- import { withTransaction } from './with-transaction.js';
6
+ import { setIdentityContext } from './set-helpers.js';
6
7
  /**
7
- * Resolves the session and the user's roles in one query. Returns null
8
- * if the session row doesn't exist or doesn't belong to a user with the
9
- * requested role.
10
- *
11
- * The query joins through `sessions → user_communication_methods → users
12
- * → user_roles → roles`, filtering by the requested role name. It also
13
- * computes:
14
- *
15
- * - `tenantIds`: distinct non-null tenant_ids on user_roles rows
16
- * - `allTenants`: true if any user_roles row has tenant_id IS NULL
17
- * - `roles`: array of all distinct role names assigned to the user
18
- *
19
- * The roles array is sourced from a separate inner join so we get every
20
- * role the user has, not just the one being requested. The `_hasRole`
21
- * column tells us whether the requested role specifically was found.
22
- */
23
- /**
24
- * Uses the resolve_session() SECURITY DEFINER function so the query
25
- * bypasses RLS on auth tables (user_communication_methods, user_roles).
26
- * This lets app_user resolve sessions without needing GUCs set first.
8
+ * Calls the pure `resolve_session` SECURITY DEFINER resolver so the read
9
+ * bypasses RLS on the auth tables (sessions, user_communication_methods,
10
+ * user_roles). The resolver validates nothing — it returns the user, the
11
+ * expiry, the roles the user holds, the default role, and the privileges.
12
+ * Validation and role selection happen here in TS.
27
13
  */
28
14
  const RESOLVE_SESSION = `
29
15
  SELECT
30
- user_id AS "userId",
31
- expires_at AS "expiresAt",
32
- tenant_ids AS "tenantIds",
33
- all_tenants AS "allTenants",
34
- roles AS "roles",
35
- has_requested_role AS "hasRequestedRole"
36
- FROM resolve_session($1, $2)
16
+ user_id AS "userId",
17
+ expires_at AS "expiresAt",
18
+ roles AS "roles",
19
+ default_role AS "defaultRole",
20
+ privileges AS "privileges"
21
+ FROM resolve_session($1)
37
22
  `;
38
23
  /**
39
- * The high-level "just make it work" entry point. Checks out a
40
- * connection, opens a transaction, validates the session, validates the
41
- * role, sets the four `app.*` GUC variables via parameterized
42
- * `set_config(_, _, true)`, runs the callback, and commits (or rolls
43
- * back on throw).
24
+ * The high-level "just make it work" request entry point. Opens a
25
+ * `@smplcty/db` transaction, resolves the session from its token, validates
26
+ * it, picks and validates the active role, sets the identity GUCs, runs the
27
+ * app scope hook, then runs the callback — committing on success or rolling
28
+ * back on throw.
29
+ *
30
+ * Active-role selection (in TS, not the resolver):
31
+ * 1. `roleName` if given — must be one the user holds, else {@link RoleNotHeldError}.
32
+ * 2. otherwise the user's default role, if any.
33
+ * 3. otherwise none — a privilege-only request, which is **not** an error.
44
34
  *
45
- * The session variables use **transaction scope**, so they're discarded
46
- * automatically when this function returns. Cross-request leakage is
47
- * impossible.
35
+ * Identity GUCs are transaction-local, so they vanish on COMMIT/ROLLBACK —
36
+ * no cross-request leakage. Scope GUCs are not set here: pass a `scope`
37
+ * hook (e.g. `flatTenantScope()`) for that, or rely on function-carried RLS.
48
38
  *
49
39
  * @example
50
40
  * ```ts
51
41
  * const widgets = await withSession(
52
42
  * pool,
53
- * { sessionId, roleName: 'user' },
43
+ * { token, roleName: 'user' },
54
44
  * async (client, ctx) => {
55
- * // ctx = { userId, tenantIds, allTenants, roles }
45
+ * // ctx = { userId, activeRole, roles, privileges }
56
46
  * const { rows } = await client.query('SELECT * FROM widgets');
57
47
  * return rows;
58
- * }
48
+ * },
49
+ * { scope: flatTenantScope() },
59
50
  * );
60
51
  * ```
61
52
  *
62
- * @throws {SessionNotFoundError} If no session row matches `auth.sessionId`.
63
- * @throws {SessionExpiredError} If the session has passed its `expires_at`.
64
- * @throws {RoleNotAssignedError} If the user does not have `auth.roleName`.
65
- * @throws {InvalidInputError} If `auth.sessionId` or `auth.roleName` is empty.
53
+ * @throws {SessionNotFoundError} If no session matches the token.
54
+ * @throws {SessionExpiredError} If the session has expired (or was revoked).
55
+ * @throws {RoleNotHeldError} If `roleName` is given but not held.
56
+ * @throws {InvalidInputError} If `token` is empty.
66
57
  */
67
58
  export async function withSession(pool, auth, fn, options = {}) {
68
59
  const log = options.logger ?? noopLogger;
69
- const sessionHash = hashId(auth.sessionId);
60
+ const tokenHash = hashToken(auth.token);
61
+ const fingerprint = hashId(auth.token);
70
62
  return withTransaction(pool, async (client) => {
71
- const { rows } = await client.query(RESOLVE_SESSION, [auth.sessionId, auth.roleName]);
63
+ const { rows } = await client.query(RESOLVE_SESSION, [tokenHash]);
72
64
  const row = rows[0];
73
65
  if (!row) {
74
- log.warn({ sessionHash }, 'session not found');
66
+ log.warn({ session: fingerprint }, 'session not found');
75
67
  throw new SessionNotFoundError();
76
68
  }
69
+ // Revocation is just expiry: revoke sets expires_at = now(). So an
70
+ // expired-or-revoked session fails the same check.
77
71
  if (row.expiresAt.getTime() <= Date.now()) {
78
- log.warn({ sessionHash, expiresAt: row.expiresAt.toISOString() }, 'session expired');
72
+ log.warn({ session: fingerprint, expiresAt: row.expiresAt.toISOString() }, 'session expired');
79
73
  throw new SessionExpiredError(row.expiresAt);
80
74
  }
81
- if (row.hasRequestedRole !== true) {
82
- log.warn({ sessionHash, userId: row.userId, requestedRole: auth.roleName }, 'role not assigned');
83
- throw new RoleNotAssignedError(auth.roleName);
75
+ // Active-role selection happens here, not in the resolver.
76
+ let activeRole;
77
+ if (auth.roleName !== undefined) {
78
+ if (!row.roles.includes(auth.roleName)) {
79
+ log.warn({ session: fingerprint, userId: row.userId, requestedRole: auth.roleName }, 'role not held');
80
+ throw new RoleNotHeldError(auth.roleName);
81
+ }
82
+ activeRole = auth.roleName;
83
+ }
84
+ else {
85
+ activeRole = row.defaultRole ?? null;
84
86
  }
85
87
  const ctx = {
86
88
  userId: row.userId,
87
- tenantIds: row.tenantIds,
88
- allTenants: row.allTenants,
89
+ activeRole,
89
90
  roles: row.roles,
91
+ privileges: row.privileges,
90
92
  };
91
- await setSessionContext(client, {
92
- sessionId: auth.sessionId,
93
- roleName: auth.roleName,
94
- tenantIds: ctx.tenantIds,
95
- allTenants: ctx.allTenants,
93
+ await setIdentityContext(client, {
94
+ actorId: ctx.userId,
95
+ sessionId: tokenHash,
96
+ activeRole: ctx.activeRole,
97
+ privileges: ctx.privileges,
96
98
  });
99
+ // App-owned intra-tenant scope. No-op when omitted.
100
+ await options.scope?.(client, ctx);
97
101
  log.debug({
98
- sessionHash,
102
+ session: fingerprint,
99
103
  userId: ctx.userId,
100
- roleName: auth.roleName,
101
- tenantCount: ctx.tenantIds.length,
102
- allTenants: ctx.allTenants,
104
+ activeRole: ctx.activeRole,
105
+ roleCount: ctx.roles.length,
106
+ privilegeCount: ctx.privileges.length,
103
107
  }, 'session context set');
104
108
  return fn(client, ctx);
105
109
  });
@@ -1 +1 @@
1
- {"version":3,"file":"with-session.js","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC9F,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD;;;;;;;;;;;;;;;;GAgBG;AACH;;;;GAIG;AACH,MAAM,eAAe,GAAG;;;;;;;;;CASvB,CAAC;AAWF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,IAAU,EACV,IAAwB,EACxB,EAAkE,EAClE,UAA8B,EAAE;IAEhC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,UAAU,CAAC;IACzC,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAE3C,OAAO,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;QAC5C,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CAAc,eAAe,EAAE,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACnG,MAAM,GAAG,GAAG,IAAI,C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,EAAE,GAAG,CAAC,UAAU;SAC3B,CAAC;QAEF,MAAM,kBAAkB,CAAC,MAAM,EAAE;YAC/B,OAAO,EAAE,GAAG,CAAC,MAAM;YACnB,SAAS,EAAE,SAAS;YACpB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,CAAC,CAAC;QAEH,oDAAoD;QACpD,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAEnC,GAAG,CAAC,KAAK,CACP;YACE,OAAO,EAAE,WAAW;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,SAAS,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC3B,cAAc,EAAE,GAAG,CAAC,UAAU,CAAC,MAAM;SACtC,EACD,qBAAqB,CACtB,CAAC;QAEF,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smplcty/auth",
3
- "version": "0.6.4",
3
+ "version": "2.0.0",
4
4
  "description": "Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,6 +11,21 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js",
13
13
  "default": "./dist/index.js"
14
+ },
15
+ "./oidc": {
16
+ "types": "./dist/methods/oidc/index.d.ts",
17
+ "import": "./dist/methods/oidc/index.js",
18
+ "default": "./dist/methods/oidc/index.js"
19
+ },
20
+ "./twilio": {
21
+ "types": "./dist/methods/twilio/index.d.ts",
22
+ "import": "./dist/methods/twilio/index.js",
23
+ "default": "./dist/methods/twilio/index.js"
24
+ },
25
+ "./flat-tenant": {
26
+ "types": "./dist/scope/flat-tenant.d.ts",
27
+ "import": "./dist/scope/flat-tenant.js",
28
+ "default": "./dist/scope/flat-tenant.js"
14
29
  }
15
30
  },
16
31
  "files": [
@@ -70,17 +85,31 @@
70
85
  ]
71
86
  },
72
87
  "peerDependencies": {
88
+ "@smplcty/twilio": ">=0.1.0",
89
+ "oauth4webapi": ">=3.0.0",
73
90
  "pg": ">=8.0.0"
74
91
  },
92
+ "peerDependenciesMeta": {
93
+ "@smplcty/twilio": {
94
+ "optional": true
95
+ },
96
+ "oauth4webapi": {
97
+ "optional": true
98
+ }
99
+ },
75
100
  "devDependencies": {
76
101
  "@eslint/js": "^10.0.1",
77
102
  "@release-it/keep-a-changelog": "^7.1.0",
78
- "@smplcty/schema-flow": "^0.3.7",
103
+ "@smplcty/schema-flow": "^0.11.2",
104
+ "@smplcty/twilio": "^0.1.1",
105
+ "@testcontainers/postgresql": "^12.0.1",
79
106
  "@types/node": "^25.5.2",
80
107
  "@types/pg": "^8.20.0",
81
108
  "eslint": "^10.2.0",
82
109
  "husky": "^9.1.7",
110
+ "jose": "^6.2.3",
83
111
  "lint-staged": "^17.0.7",
112
+ "oauth4webapi": "^3.8.6",
84
113
  "pg": "^8.20.0",
85
114
  "prettier": "^3.8.4",
86
115
  "release-it": "^20.2.0",
@@ -89,6 +118,8 @@
89
118
  "vitest": "^4.1.4"
90
119
  },
91
120
  "dependencies": {
121
+ "@smplcty/db": "^4.2.0",
122
+ "@smplcty/schema-std": "^0.0.1",
92
123
  "otplib": "^13.4.0"
93
124
  }
94
125
  }
@@ -0,0 +1,18 @@
1
+ name: current_user_id
2
+ language: sql
3
+ volatility: stable
4
+ # Reads the per-request actor from the app.actor_id GUC (set by
5
+ # withSession / withServiceContext). This is the join key for app RLS and
6
+ # scope functions: policies that need "the current user" call this rather
7
+ # than re-reading the GUC themselves.
8
+ #
9
+ # Returns NULL when no actor is set (unauthenticated / outside a request
10
+ # context) — RLS policies treat a NULL current user as "see nothing".
11
+ returns: integer
12
+ args: []
13
+ body: |
14
+ SELECT NULLIF(current_setting('app.actor_id', true), '')::integer;
15
+ comment: >
16
+ Returns the current request's actor (users.user_id) from the
17
+ app.actor_id GUC, or NULL if unset. The stable, RLS-friendly accessor
18
+ app scope functions key on.