@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
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The flat-tenant scope GUCs. Set by the {@link flatTenantScope} preset;
3
+ * **not** part of the core identity contract. Reference them in RLS
4
+ * policies if you adopt the preset.
5
+ *
6
+ * - `app.tenant_ids` — comma-separated tenant ids the user belongs to.
7
+ * - `app.all_tenants` — `'true'` when the user has a wildcard
8
+ * (`tenant_id IS NULL`) membership; such users see every tenant.
9
+ */
10
+ export const FLAT_TENANT_GUC = {
11
+ tenantIds: 'app.tenant_ids',
12
+ allTenants: 'app.all_tenants',
13
+ };
14
+ const SET_CONFIG = 'SELECT set_config($1, $2, true)';
15
+ // Resolve the user's tenant membership from user_roles. tenant_id IS NULL
16
+ // is a wildcard (all tenants); concrete ids are the explicit memberships.
17
+ // Runs as the request user — an RLS policy keyed on current_user_id()
18
+ // (already set by withSession) lets the user read their own rows.
19
+ const SELECT_TENANTS = `
20
+ SELECT
21
+ COALESCE(
22
+ array_agg(DISTINCT tenant_id) FILTER (WHERE tenant_id IS NOT NULL),
23
+ '{}'::integer[]
24
+ ) AS tenant_ids,
25
+ COALESCE(bool_or(tenant_id IS NULL), false) AS all_tenants
26
+ FROM user_roles
27
+ WHERE user_id = $1
28
+ AND deleted_at IS NULL
29
+ `;
30
+ /**
31
+ * A ready-made scope hook implementing the flat `tenant_ids` /
32
+ * `all_tenants` model (the 0.6.x behavior), now opt-in rather than baked
33
+ * into the core.
34
+ *
35
+ * Adopt it for simple multi-tenant apps that don't need a custom scope:
36
+ *
37
+ * ```ts
38
+ * import { withSession } from '@smplcty/auth';
39
+ * import { flatTenantScope } from '@smplcty/auth/flat-tenant';
40
+ *
41
+ * const scope = flatTenantScope();
42
+ * await withSession(pool, { token }, fn, { scope });
43
+ * ```
44
+ *
45
+ * It sets `app.tenant_ids` and `app.all_tenants` from the user's
46
+ * `user_roles` rows. Your RLS policies read those GUCs to filter by
47
+ * tenant. Apps with a richer intra-tenant model (producer/region/plant,
48
+ * rep hierarchy, …) ship their own scope hook instead.
49
+ */
50
+ export function flatTenantScope() {
51
+ return async (client, identity) => {
52
+ const { rows } = await client.query(SELECT_TENANTS, [identity.userId]);
53
+ const row = rows[0];
54
+ const tenantIds = row?.tenant_ids ?? [];
55
+ const allTenants = row?.all_tenants ?? false;
56
+ await client.query(SET_CONFIG, [FLAT_TENANT_GUC.tenantIds, tenantIds.join(',')]);
57
+ await client.query(SET_CONFIG, [FLAT_TENANT_GUC.allTenants, allTenants ? 'true' : 'false']);
58
+ };
59
+ }
60
+ //# sourceMappingURL=flat-tenant.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flat-tenant.js","sourceRoot":"","sources":["../../src/scope/flat-tenant.ts"],"names":[],"mappings":"AAGA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,gBAAgB;IAC3B,UAAU,EAAE,iBAAiB;CACrB,CAAC;AAEX,MAAM,UAAU,GAAG,iCAAiC,CAAC;AAErD,0EAA0E;AAC1E,0EAA0E;AAC1E,sEAAsE;AACtE,kEAAkE;AAClE,MAAM,cAAc,GAAG;;;;;;;;;;CAUtB,CAAC;AAOF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,KAAK,EAAE,MAAkB,EAAE,QAAyB,EAAiB,EAAE;QAC5E,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CAAY,cAAc,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QAClF,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,MAAM,SAAS,GAAG,GAAG,EAAE,UAAU,IAAI,EAAE,CAAC;QACxC,MAAM,UAAU,GAAG,GAAG,EAAE,WAAW,IAAI,KAAK,CAAC;QAC7C,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,eAAe,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACjF,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,eAAe,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9F,CAAC,CAAC;AACJ,CAAC"}
@@ -1,78 +1,69 @@
1
1
  import type { PoolClient } from 'pg';
2
2
  /**
3
- * The four GUC variable names this library uses. Re-exported here in
4
- * case consumers need them in custom RLS policies.
3
+ * The identity GUC contract — the only GUCs `@smplcty/auth` sets. All are
4
+ * transaction-local (`set_config(name, value, true)`), so they're
5
+ * discarded automatically on COMMIT/ROLLBACK; cross-request leakage is
6
+ * impossible. Re-exported so consumers can reference them in RLS policies.
7
+ *
8
+ * Scope GUCs (tenant ids, plant/region scope, visible rep ids, …) are
9
+ * **not** here — intra-tenant scope is app-owned (set via the scope hook).
10
+ *
11
+ * - `app.actor_id` — the acting user (human or service). Powers
12
+ * `current_user_id()` and audit attribution.
13
+ * - `app.session_id` — the session hash, for correlation/audit.
14
+ * - `app.active_role` — the chosen mode/persona role for the request.
15
+ * - `app.privileges` — comma-separated privilege names the user holds.
5
16
  */
6
- export declare const SESSION_VAR_NAMES: {
17
+ export declare const IDENTITY_GUC: {
18
+ readonly actorId: "app.actor_id";
7
19
  readonly sessionId: "app.session_id";
8
- readonly roleName: "app.role_name";
9
- readonly tenantIds: "app.tenant_ids";
10
- readonly allTenants: "app.all_tenants";
20
+ readonly activeRole: "app.active_role";
21
+ readonly privileges: "app.privileges";
11
22
  };
12
23
  /**
13
- * Set `app.session_id` for the current transaction.
14
- *
15
- * **Contract:** `client` must be inside an open transaction. Either wrap
16
- * with `withTransaction(pool, fn)` or call `await client.query('BEGIN')`
17
- * yourself first.
18
- *
19
- * The variable is set with transaction scope (`set_config(name, value, true)`)
20
- * and is automatically discarded on COMMIT or ROLLBACK. There is no risk
21
- * of cross-request leakage.
22
- *
23
- * **Warning:** This helper does not validate that the session exists or
24
- * is unexpired. Use `validateSession` or `withSession` if you want
25
- * automatic verification.
24
+ * Set a single transaction-local GUC. Low-level escape hatch; prefer the
25
+ * named setters or `setIdentityContext`.
26
26
  *
27
- * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
27
+ * **Contract:** `client` must be inside an open transaction.
28
28
  */
29
- export declare function setSessionId(client: PoolClient, sessionId: string): Promise<void>;
29
+ export declare function setLocal(client: PoolClient, name: string, value: string): Promise<void>;
30
30
  /**
31
- * Set `app.role_name` for the current transaction.
32
- *
33
- * **Contract:** `client` must be inside an open transaction.
34
- *
35
- * **Warning:** This helper does not verify that the requested role is
36
- * one the current session is allowed to use. The caller is responsible
37
- * for not passing user-supplied input directly. Use `withSession` to get
38
- * automatic role validation against the database.
31
+ * Set `app.actor_id` — the user (or service principal) performing the
32
+ * request. `current_user_id()` and the audit trigger read it.
39
33
  *
40
- * @typeParam TRole - String literal union of roles in your application.
41
- * Defaults to `string`. Narrow this in a thin wrapper.
42
- * @throws {InvalidInputError} If `roleName` is not a non-empty string.
34
+ * @throws {InvalidInputError} If `actorId` is not a positive integer.
43
35
  */
44
- export declare function setRoleName<TRole extends string = string>(client: PoolClient, roleName: TRole): Promise<void>;
36
+ export declare function setActorId(client: PoolClient, actorId: number): Promise<void>;
45
37
  /**
46
- * Set `app.tenant_ids` for the current transaction. The value is encoded
47
- * as a comma-separated string of integers (so RLS policies can parse it
48
- * with `string_to_array`). Empty arrays produce an empty string.
38
+ * Set `app.session_id` (the session hash) for correlation/audit.
49
39
  *
50
- * **Contract:** `client` must be inside an open transaction.
51
- *
52
- * @throws {InvalidInputError} If any element of `tenantIds` is not a finite integer.
40
+ * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
53
41
  */
54
- export declare function setTenantIds(client: PoolClient, tenantIds: readonly number[]): Promise<void>;
42
+ export declare function setSessionId(client: PoolClient, sessionId: string): Promise<void>;
55
43
  /**
56
- * Set `app.all_tenants` for the current transaction. When `true`, RLS
57
- * policies typically bypass tenant filtering and allow access to every
58
- * tenant's rows.
44
+ * Set `app.active_role` — the mode/persona role for this request. Pass
45
+ * null to clear it (privilege-only request).
59
46
  *
60
- * **Contract:** `client` must be inside an open transaction.
47
+ * @throws {InvalidInputError} If `roleName` is neither a non-empty string nor null.
48
+ */
49
+ export declare function setActiveRole(client: PoolClient, roleName: string | null): Promise<void>;
50
+ /**
51
+ * Set `app.privileges` — a comma-separated list of the privilege names the
52
+ * user holds. RLS policies parse it with `string_to_array(_, ',')`.
61
53
  *
62
- * @throws {InvalidInputError} If `allTenants` is not a boolean.
54
+ * @throws {InvalidInputError} If `privileges` is not an array of strings,
55
+ * or any entry contains a comma.
63
56
  */
64
- export declare function setAllTenants(client: PoolClient, allTenants: boolean): Promise<void>;
57
+ export declare function setPrivileges(client: PoolClient, privileges: readonly string[]): Promise<void>;
65
58
  /**
66
- * Set all four session variables in one call. Equivalent to calling
67
- * `setSessionId`, `setRoleName`, `setTenantIds`, and `setAllTenants`
68
- * sequentially, but more concise.
59
+ * Set all four identity GUCs in one call.
69
60
  *
70
61
  * **Contract:** `client` must be inside an open transaction.
71
62
  */
72
- export declare function setSessionContext<TRole extends string = string>(client: PoolClient, context: {
63
+ export declare function setIdentityContext(client: PoolClient, context: {
64
+ actorId: number;
73
65
  sessionId: string;
74
- roleName: TRole;
75
- tenantIds: readonly number[];
76
- allTenants: boolean;
66
+ activeRole: string | null;
67
+ privileges: readonly string[];
77
68
  }): Promise<void>;
78
69
  //# sourceMappingURL=set-helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"set-helpers.d.ts","sourceRoot":"","sources":["../src/set-helpers.ts"],"names":[],"mappings":"A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,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAK7F;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKnF;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKvF;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAK9F;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAapG;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE;IACP,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/B,GACA,OAAO,CAAC,IAAI,CAAC,CAKf"}
@@ -1,29 +1,52 @@
1
1
  import { InvalidInputError } from './errors.js';
2
2
  const SET_CONFIG = 'SELECT set_config($1, $2, true)';
3
3
  /**
4
- * The four GUC variable names this library uses. Re-exported here in
5
- * case consumers need them in custom RLS policies.
4
+ * The identity GUC contract — the only GUCs `@smplcty/auth` sets. All are
5
+ * transaction-local (`set_config(name, value, true)`), so they're
6
+ * discarded automatically on COMMIT/ROLLBACK; cross-request leakage is
7
+ * impossible. Re-exported so consumers can reference them in RLS policies.
8
+ *
9
+ * Scope GUCs (tenant ids, plant/region scope, visible rep ids, …) are
10
+ * **not** here — intra-tenant scope is app-owned (set via the scope hook).
11
+ *
12
+ * - `app.actor_id` — the acting user (human or service). Powers
13
+ * `current_user_id()` and audit attribution.
14
+ * - `app.session_id` — the session hash, for correlation/audit.
15
+ * - `app.active_role` — the chosen mode/persona role for the request.
16
+ * - `app.privileges` — comma-separated privilege names the user holds.
6
17
  */
7
- export const SESSION_VAR_NAMES = {
18
+ export const IDENTITY_GUC = {
19
+ actorId: 'app.actor_id',
8
20
  sessionId: 'app.session_id',
9
- roleName: 'app.role_name',
10
- tenantIds: 'app.tenant_ids',
11
- allTenants: 'app.all_tenants',
21
+ activeRole: 'app.active_role',
22
+ privileges: 'app.privileges',
12
23
  };
13
24
  /**
14
- * Set `app.session_id` for the current transaction.
25
+ * Set a single transaction-local GUC. Low-level escape hatch; prefer the
26
+ * named setters or `setIdentityContext`.
15
27
  *
16
- * **Contract:** `client` must be inside an open transaction. Either wrap
17
- * with `withTransaction(pool, fn)` or call `await client.query('BEGIN')`
18
- * yourself first.
19
- *
20
- * The variable is set with transaction scope (`set_config(name, value, true)`)
21
- * and is automatically discarded on COMMIT or ROLLBACK. There is no risk
22
- * of cross-request leakage.
28
+ * **Contract:** `client` must be inside an open transaction.
29
+ */
30
+ export async function setLocal(client, name, value) {
31
+ if (typeof name !== 'string' || name.length === 0) {
32
+ throw new InvalidInputError('GUC name must be a non-empty string');
33
+ }
34
+ await client.query(SET_CONFIG, [name, value]);
35
+ }
36
+ /**
37
+ * Set `app.actor_id` — the user (or service principal) performing the
38
+ * request. `current_user_id()` and the audit trigger read it.
23
39
  *
24
- * **Warning:** This helper does not validate that the session exists or
25
- * is unexpired. Use `validateSession` or `withSession` if you want
26
- * automatic verification.
40
+ * @throws {InvalidInputError} If `actorId` is not a positive integer.
41
+ */
42
+ export async function setActorId(client, actorId) {
43
+ if (!Number.isInteger(actorId) || actorId <= 0) {
44
+ throw new InvalidInputError('actorId must be a positive integer');
45
+ }
46
+ await client.query(SET_CONFIG, [IDENTITY_GUC.actorId, String(actorId)]);
47
+ }
48
+ /**
49
+ * Set `app.session_id` (the session hash) for correlation/audit.
27
50
  *
28
51
  * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
29
52
  */
@@ -31,74 +54,50 @@ export async function setSessionId(client, sessionId) {
31
54
  if (typeof sessionId !== 'string' || sessionId.length === 0) {
32
55
  throw new InvalidInputError('sessionId must be a non-empty string');
33
56
  }
34
- await client.query(SET_CONFIG, [SESSION_VAR_NAMES.sessionId, sessionId]);
57
+ await client.query(SET_CONFIG, [IDENTITY_GUC.sessionId, sessionId]);
35
58
  }
36
59
  /**
37
- * Set `app.role_name` for the current transaction.
60
+ * Set `app.active_role` — the mode/persona role for this request. Pass
61
+ * null to clear it (privilege-only request).
38
62
  *
39
- * **Contract:** `client` must be inside an open transaction.
40
- *
41
- * **Warning:** This helper does not verify that the requested role is
42
- * one the current session is allowed to use. The caller is responsible
43
- * for not passing user-supplied input directly. Use `withSession` to get
44
- * automatic role validation against the database.
45
- *
46
- * @typeParam TRole - String literal union of roles in your application.
47
- * Defaults to `string`. Narrow this in a thin wrapper.
48
- * @throws {InvalidInputError} If `roleName` is not a non-empty string.
63
+ * @throws {InvalidInputError} If `roleName` is neither a non-empty string nor null.
49
64
  */
50
- export async function setRoleName(client, roleName) {
51
- if (typeof roleName !== 'string' || roleName.length === 0) {
52
- throw new InvalidInputError('roleName must be a non-empty string');
65
+ export async function setActiveRole(client, roleName) {
66
+ if (roleName !== null && (typeof roleName !== 'string' || roleName.length === 0)) {
67
+ throw new InvalidInputError('roleName must be a non-empty string or null');
53
68
  }
54
- await client.query(SET_CONFIG, [SESSION_VAR_NAMES.roleName, roleName]);
69
+ await client.query(SET_CONFIG, [IDENTITY_GUC.activeRole, roleName ?? '']);
55
70
  }
56
71
  /**
57
- * Set `app.tenant_ids` for the current transaction. The value is encoded
58
- * as a comma-separated string of integers (so RLS policies can parse it
59
- * with `string_to_array`). Empty arrays produce an empty string.
60
- *
61
- * **Contract:** `client` must be inside an open transaction.
72
+ * Set `app.privileges` — a comma-separated list of the privilege names the
73
+ * user holds. RLS policies parse it with `string_to_array(_, ',')`.
62
74
  *
63
- * @throws {InvalidInputError} If any element of `tenantIds` is not a finite integer.
75
+ * @throws {InvalidInputError} If `privileges` is not an array of strings,
76
+ * or any entry contains a comma.
64
77
  */
65
- export async function setTenantIds(client, tenantIds) {
66
- if (!Array.isArray(tenantIds)) {
67
- throw new InvalidInputError('tenantIds must be an array of integers');
78
+ export async function setPrivileges(client, privileges) {
79
+ if (!Array.isArray(privileges)) {
80
+ throw new InvalidInputError('privileges must be an array of strings');
68
81
  }
69
- for (const id of tenantIds) {
70
- if (!Number.isInteger(id)) {
71
- throw new InvalidInputError(`tenantIds must contain only integers; got ${String(id)}`);
82
+ for (const p of privileges) {
83
+ if (typeof p !== 'string' || p.length === 0) {
84
+ throw new InvalidInputError('privileges must contain only non-empty strings');
85
+ }
86
+ if (p.includes(',')) {
87
+ throw new InvalidInputError(`privilege names must not contain commas; got "${p}"`);
72
88
  }
73
89
  }
74
- await client.query(SET_CONFIG, [SESSION_VAR_NAMES.tenantIds, tenantIds.join(',')]);
75
- }
76
- /**
77
- * Set `app.all_tenants` for the current transaction. When `true`, RLS
78
- * policies typically bypass tenant filtering and allow access to every
79
- * tenant's rows.
80
- *
81
- * **Contract:** `client` must be inside an open transaction.
82
- *
83
- * @throws {InvalidInputError} If `allTenants` is not a boolean.
84
- */
85
- export async function setAllTenants(client, allTenants) {
86
- if (typeof allTenants !== 'boolean') {
87
- throw new InvalidInputError('allTenants must be a boolean');
88
- }
89
- await client.query(SET_CONFIG, [SESSION_VAR_NAMES.allTenants, allTenants ? 'true' : 'false']);
90
+ await client.query(SET_CONFIG, [IDENTITY_GUC.privileges, privileges.join(',')]);
90
91
  }
91
92
  /**
92
- * Set all four session variables in one call. Equivalent to calling
93
- * `setSessionId`, `setRoleName`, `setTenantIds`, and `setAllTenants`
94
- * sequentially, but more concise.
93
+ * Set all four identity GUCs in one call.
95
94
  *
96
95
  * **Contract:** `client` must be inside an open transaction.
97
96
  */
98
- export async function setSessionContext(client, context) {
97
+ export async function setIdentityContext(client, context) {
98
+ await setActorId(client, context.actorId);
99
99
  await setSessionId(client, context.sessionId);
100
- await setRoleName(client, context.roleName);
101
- await setTenantIds(client, context.tenantIds);
102
- await setAllTenants(client, context.allTenants);
100
+ await setActiveRole(client, context.activeRole);
101
+ await setPrivileges(client, context.privileges);
103
102
  }
104
103
  //# sourceMappingURL=set-helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"set-helpers.js","sourceRoot":"","sources":["../src/set-helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,UAAU,GAAG,iCAAiC,CAAC;AAErD;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,SAAS,EAAE,gBAAgB;IAC3B,QAAQ,EAAE,eAAe;IACzB,SAAS,EAAE,gBAAgB;IAC3B,UAAU,EAAE,iBAAiB;CACrB,CAAC;AAEX;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,MAAkB,EAAE,SAAiB;IACtE,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,iBAAiB,CAAC,sCAAsC,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,iBAAiB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAgC,MAAkB,EAAE,QAAe;IAClG,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,iBAAiB,CAAC,qCAAqC,CAAC,CAAC;IACrE,CAAC;I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AiB,CAAC,iDAAiD,CAAC,GAAG,CAAC,CAAC;QACrF,CAAC;IACH,CAAC;IACD,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAClF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAAkB,EAClB,OAKC;IAED,MAAM,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1C,MAAM,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC9C,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;IAChD,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { Queryable } from './types.js';
2
+ /**
3
+ * Record activity on a session: stamp `last_seen_at = now()`. Powers the
4
+ * "track activity" requirement (distinct from `created_at`, the sign-in
5
+ * time). No-ops on an unknown, expired, or revoked session.
6
+ *
7
+ * Returns `true` if a live session was touched, `false` otherwise — handy
8
+ * for piggy-backing a liveness check on the activity update.
9
+ *
10
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
11
+ */
12
+ export declare function touchSession(db: Queryable, token: string): Promise<boolean>;
13
+ //# sourceMappingURL=touch-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"touch-session.d.ts","sourceRoot":"","sources":["../src/touch-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAW5C;;;;;;;;;GASG;AACH,wBAAsB,YAAY,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMjF"}
@@ -0,0 +1,28 @@
1
+ import { InvalidInputError } from './errors.js';
2
+ import { hashToken } from './internal/hash-token.js';
3
+ // Record activity. Only touches still-valid sessions so a touch can't
4
+ // resurrect an expired/revoked one. Returns whether a live session matched.
5
+ const TOUCH = `
6
+ UPDATE sessions
7
+ SET last_seen_at = now()
8
+ WHERE session_id = $1
9
+ AND expires_at > now()
10
+ `;
11
+ /**
12
+ * Record activity on a session: stamp `last_seen_at = now()`. Powers the
13
+ * "track activity" requirement (distinct from `created_at`, the sign-in
14
+ * time). No-ops on an unknown, expired, or revoked session.
15
+ *
16
+ * Returns `true` if a live session was touched, `false` otherwise — handy
17
+ * for piggy-backing a liveness check on the activity update.
18
+ *
19
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
20
+ */
21
+ export async function touchSession(db, token) {
22
+ if (typeof token !== 'string' || token.length === 0) {
23
+ throw new InvalidInputError('token must be a non-empty string');
24
+ }
25
+ const { rowCount } = await db.query(TOUCH, [hashToken(token)]);
26
+ return (rowCount ?? 0) > 0;
27
+ }
28
+ //# sourceMappingURL=touch-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"touch-session.js","sourceRoot":"","sources":["../src/touch-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD,sEAAsE;AACtE,4EAA4E;AAC5E,MAAM,KAAK,GAAG;;;;;CAKb,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,EAAa,EAAE,KAAa;IAC7D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,iBAAiB,CAAC,kCAAkC,CAAC,CAAC;IAClE,CAAC;IACD,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC/D,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC"}
package/dist/types.d.ts CHANGED
@@ -6,12 +6,16 @@ import type { Pool, PoolClient } from 'pg';
6
6
  */
7
7
  export type Queryable = Pool | PoolClient;
8
8
  /**
9
- * A persisted session row, returned from `createSession` and
10
- * `validateSession`.
9
+ * A freshly created session, returned from `createSession`.
10
+ *
11
+ * `token` is the **raw opaque bearer credential** — it is returned to the
12
+ * client exactly once and is never stored server-side. Only its hash is
13
+ * persisted (as the `sessions` primary key). Treat `token` like a password:
14
+ * hand it to the client and forget it.
11
15
  */
12
16
  export interface Session {
13
- /** Server-generated session token. Treat as a bearer credential. */
14
- readonly sessionId: string;
17
+ /** Raw opaque bearer token. Returned once; only its hash is stored. */
18
+ readonly token: string;
15
19
  /** The user this session was created for. */
16
20
  readonly userId: number;
17
21
  /** When the session row was created. */
@@ -20,8 +24,26 @@ export interface Session {
20
24
  readonly expiresAt: Date;
21
25
  }
22
26
  /**
23
- * The fully resolved authentication context for a request. Passed to the
24
- * callback inside `withSession`.
27
+ * A validated session, returned from `validateSession`. Carries no raw
28
+ * token — the token is never recoverable from a stored session.
29
+ */
30
+ export interface SessionInfo {
31
+ /** The user this session belongs to. */
32
+ readonly userId: number;
33
+ /** When the session row was created (sign-in time). */
34
+ readonly createdAt: Date;
35
+ /** When the session expires. */
36
+ readonly expiresAt: Date;
37
+ /** Last recorded activity (`touchSession`), or null if never touched. */
38
+ readonly lastSeenAt: Date | null;
39
+ }
40
+ /**
41
+ * The resolved identity for a request. Passed to the callback inside
42
+ * `withSession` and to the app-supplied scope hook.
43
+ *
44
+ * Note this carries **no tenant/scope data** — intra-tenant scope is
45
+ * app-owned (see the scope hook). The library resolves identity only:
46
+ * the user, the active role, the roles the user holds, and the privileges.
25
47
  *
26
48
  * @typeParam TRole - String literal union of role names valid in your
27
49
  * application. Defaults to `string`. Narrow this in a thin wrapper —
@@ -30,16 +52,29 @@ export interface Session {
30
52
  export interface SessionContext<TRole extends string = string> {
31
53
  /** The user this session belongs to. */
32
54
  readonly userId: number;
33
- /** Tenant IDs the user has access to. Empty if `allTenants` is true and
34
- * the user has no tenant-scoped roles. */
35
- readonly tenantIds: readonly number[];
36
- /** True if the user has at least one role that is not tenant-scoped
37
- * (i.e. a `user_roles` row with `tenant_id IS NULL`). When true, RLS
38
- * policies typically bypass tenant filtering. */
39
- readonly allTenants: boolean;
40
- /** All roles assigned to the user (across all tenants). */
55
+ /** The active mode/persona role for this request (becomes
56
+ * `app.active_role`), or null when the user holds only privileges and
57
+ * requested no role. */
58
+ readonly activeRole: TRole | null;
59
+ /** All selectable (non-privilege) roles the user holds. */
41
60
  readonly roles: readonly TRole[];
61
+ /** All privileges (always-on capability flags) the user holds.
62
+ * Exported as `app.privileges`. */
63
+ readonly privileges: readonly string[];
42
64
  }
65
+ /**
66
+ * The identity handed to an app's scope hook. Same shape as
67
+ * {@link SessionContext}.
68
+ */
69
+ export type SessionIdentity<TRole extends string = string> = SessionContext<TRole>;
70
+ /**
71
+ * An app-supplied hook that sets whatever scope GUCs the app's RLS needs
72
+ * (or is a no-op when scope is enforced function-carried). Called by
73
+ * `withSession` after the identity GUCs are set, inside the request
74
+ * transaction. The library ships no scope model of its own — see the
75
+ * `@smplcty/auth/flat-tenant` preset for the common tenant case.
76
+ */
77
+ export type ScopeHook<TRole extends string = string> = (client: PoolClient, identity: SessionIdentity<TRole>) => Promise<void>;
43
78
  /**
44
79
  * Geolocation metadata captured at session creation time. All fields
45
80
  * optional — only what your app supplies will be stored.
@@ -89,7 +124,7 @@ export interface FindUserQuery {
89
124
  * idiomatic shape so a pino logger can be passed directly without
90
125
  * adaptation.
91
126
  *
92
- * The library never logs PII or session IDs. It only emits structural
127
+ * The library never logs PII or raw tokens. It only emits structural
93
128
  * events with safe identifiers (userId, role, hash prefixes).
94
129
  */
95
130
  export interface Logger {
@@ -101,7 +136,10 @@ export interface Logger {
101
136
  /**
102
137
  * Options accepted by `withSession`.
103
138
  */
104
- export interface WithSessionOptions {
139
+ export interface WithSessionOptions<TRole extends string = string> {
140
+ /** App-supplied scope hook — sets intra-tenant scope GUCs (or no-op).
141
+ * The library sets no scope GUC itself. */
142
+ scope?: ScopeHook<TRole>;
105
143
  /** Optional logger. Defaults to a no-op. */
106
144
  logger?: Logger;
107
145
  }
@@ -112,7 +150,10 @@ export interface WithSessionOptions {
112
150
  * application. Defaults to `string`.
113
151
  */
114
152
  export interface SessionAuth<TRole extends string = string> {
115
- sessionId: string;
116
- roleName: TRole;
153
+ /** The raw opaque bearer token from the client (e.g. a cookie/header). */
154
+ token: string;
155
+ /** The mode/persona role to activate for this request. Omit to use the
156
+ * user's default role (or none, if the user holds only privileges). */
157
+ roleName?: TRole;
117
158
  }
118
159
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAE3C;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,IAAI,GAAG,UAAU,CAAC;AAE1C;;;GAGG;AACH,MAAM,WAAW,OAAO;IACtB,oEAAoE;IACpE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wCAAwC;IACxC,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,4EAA4E;IAC5E,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;CAC1B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IAC3D,wCAAwC;IACxC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;+CAC2C;IAC3C,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;I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iF;IACjF,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,MAAM;IACrB,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACxD,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACvD,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACvD,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACzD;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IAC/D;gDAC4C;IAC5C,KAAK,CAAC,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC;IACzB,4CAA4C;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,MAAM,WAAW,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACxD,0EAA0E;IAC1E,KAAK,EAAE,MAAM,CAAC;IACd;4EACwE;IACxE,QAAQ,CAAC,EAAE,KAAK,CAAC;CAClB"}
@@ -1,20 +1,21 @@
1
- import type { Queryable, Session } from './types.js';
1
+ import type { Queryable, SessionInfo } from './types.js';
2
2
  /**
3
- * Look up a session by ID and verify it is still valid.
3
+ * Look up a session by its raw token and verify it is still valid.
4
4
  *
5
- * Returns the {@link Session} on success. Throws if the session does
6
- * not exist, has expired, or the input is malformed. Does not set any
7
- * Postgres session variables — this is purely a check.
5
+ * Hashes the token, finds the matching `sessions` row, and returns its
6
+ * {@link SessionInfo} on success. Throws if the token matches no session,
7
+ * the session has expired (or was revoked — revocation sets `expires_at`
8
+ * to now), or the input is malformed. Sets no GUCs — this is purely a
9
+ * check.
8
10
  *
9
- * Use this function in API Gateway authorizers, refresh-token flows,
10
- * and any other place where you need to verify a token without entering
11
- * a request transaction. For an authenticated request that will run
12
- * queries, use {@link withSession} instead — it does this validation
13
- * AND sets up the database context in one call.
11
+ * Use this in API Gateway authorizers, refresh flows, and anywhere you
12
+ * need to verify a token without entering a request transaction. For an
13
+ * authenticated request that will run queries, use {@link withSession} —
14
+ * it validates AND sets up the database context in one call.
14
15
  *
15
- * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
16
- * @throws {SessionNotFoundError} If no row matches `sessionId`.
17
- * @throws {SessionExpiredError} If the session row exists but `expires_at` has passed.
16
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
17
+ * @throws {SessionNotFoundError} If no session matches the token.
18
+ * @throws {SessionExpiredError} If the session has expired or was revoked.
18
19
  */
19
- export declare function validateSession(db: Queryable, sessionId: string): Promise<Session>;
20
+ export declare function validateSession(db: Queryable, token: string): Promise<SessionInfo>;
20
21
  //# sourceMappingURL=validate-session.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-session.d.ts","sourceRoot":"","sources":["../src/validate-session.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAiBrD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBxF"}
1
+ {"version":3,"file":"validate-session.d.ts","sourceRoot":"","sources":["../src/validate-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAkBzD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAkBxF"}