@smplcty/auth 0.6.3 → 1.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 (93) hide show
  1. package/README.md +198 -223
  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 +18 -23
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/dev-otp.d.ts.map +1 -1
  7. package/dist/dev-otp.js +4 -10
  8. package/dist/dev-otp.js.map +1 -1
  9. package/dist/errors.d.ts +19 -4
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +23 -5
  12. package/dist/errors.js.map +1 -1
  13. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  14. package/dist/find-user-by-communication-method.js +8 -1
  15. package/dist/find-user-by-communication-method.js.map +1 -1
  16. package/dist/get-user-role-names.d.ts.map +1 -1
  17. package/dist/get-user-role-names.js +2 -0
  18. package/dist/get-user-role-names.js.map +1 -1
  19. package/dist/index.d.ts +10 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +13 -7
  22. package/dist/index.js.map +1 -1
  23. package/dist/internal/hash-token.d.ts +16 -0
  24. package/dist/internal/hash-token.d.ts.map +1 -0
  25. package/dist/internal/hash-token.js +21 -0
  26. package/dist/internal/hash-token.js.map +1 -0
  27. package/dist/methods/errors.d.ts +37 -0
  28. package/dist/methods/errors.d.ts.map +1 -0
  29. package/dist/methods/errors.js +48 -0
  30. package/dist/methods/errors.js.map +1 -0
  31. package/dist/methods/oidc/index.d.ts +65 -0
  32. package/dist/methods/oidc/index.d.ts.map +1 -0
  33. package/dist/methods/oidc/index.js +76 -0
  34. package/dist/methods/oidc/index.js.map +1 -0
  35. package/dist/methods/router.d.ts +39 -0
  36. package/dist/methods/router.d.ts.map +1 -0
  37. package/dist/methods/router.js +153 -0
  38. package/dist/methods/router.js.map +1 -0
  39. package/dist/methods/twilio/index.d.ts +44 -0
  40. package/dist/methods/twilio/index.d.ts.map +1 -0
  41. package/dist/methods/twilio/index.js +77 -0
  42. package/dist/methods/twilio/index.js.map +1 -0
  43. package/dist/methods/types.d.ts +124 -0
  44. package/dist/methods/types.d.ts.map +1 -0
  45. package/dist/methods/types.js +2 -0
  46. package/dist/methods/types.js.map +1 -0
  47. package/dist/revoke-session.d.ts +20 -15
  48. package/dist/revoke-session.d.ts.map +1 -1
  49. package/dist/revoke-session.js +66 -20
  50. package/dist/revoke-session.js.map +1 -1
  51. package/dist/scope/flat-tenant.d.ts +36 -0
  52. package/dist/scope/flat-tenant.d.ts.map +1 -0
  53. package/dist/scope/flat-tenant.js +60 -0
  54. package/dist/scope/flat-tenant.js.map +1 -0
  55. package/dist/set-helpers.d.ts +44 -53
  56. package/dist/set-helpers.d.ts.map +1 -1
  57. package/dist/set-helpers.js +67 -74
  58. package/dist/set-helpers.js.map +1 -1
  59. package/dist/touch-session.d.ts +13 -0
  60. package/dist/touch-session.d.ts.map +1 -0
  61. package/dist/touch-session.js +28 -0
  62. package/dist/touch-session.js.map +1 -0
  63. package/dist/types.d.ts +59 -18
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/validate-session.d.ts +15 -14
  66. package/dist/validate-session.d.ts.map +1 -1
  67. package/dist/validate-session.js +28 -27
  68. package/dist/validate-session.js.map +1 -1
  69. package/dist/with-service-context.d.ts +15 -12
  70. package/dist/with-service-context.d.ts.map +1 -1
  71. package/dist/with-service-context.js +34 -39
  72. package/dist/with-service-context.js.map +1 -1
  73. package/dist/with-session.d.ts +22 -16
  74. package/dist/with-session.d.ts.map +1 -1
  75. package/dist/with-session.js +67 -66
  76. package/dist/with-session.js.map +1 -1
  77. package/package.json +53 -4
  78. package/schema/functions/current_user_id.yaml +18 -0
  79. package/schema/functions/resolve_session.yaml +42 -23
  80. package/schema/post/0001-backfill-audit-by.sql +15 -0
  81. package/schema/tables/auth_domains.yaml +43 -0
  82. package/schema/tables/communication_channels.yaml +5 -1
  83. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  84. package/schema/tables/roles.yaml +43 -7
  85. package/schema/tables/sessions.yaml +10 -0
  86. package/schema/tables/tenants.yaml +24 -1
  87. package/schema/tables/user_communication_methods.yaml +5 -1
  88. package/schema/tables/user_roles.yaml +1 -0
  89. package/schema/tables/users.yaml +27 -0
  90. package/dist/with-transaction.d.ts +0 -31
  91. package/dist/with-transaction.d.ts.map +0 -1
  92. package/dist/with-transaction.js +0 -49
  93. package/dist/with-transaction.js.map +0 -1
@@ -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,MA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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,CACnC,EAAE,EAAE,SAAS,EACb,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,OAAO,CAAC,CAqBlB"}
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"}
@@ -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;AAG3F,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAChF,MAAM,WAAW,GAAG,UAAU,SAAS,EAAE,CAAC;AAE1C,MAAM,cAAc,GAAG;;;;QAIf,WAAW;;;;;;CAMlB,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,EAAa,EACb,SAAiB;IAEjB,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,iBAAiB,CAAC,sCAAsC,CAAC,CAAC;IACtE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAU,cAAc,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;IACtE,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,oBAAoB,EAAE,CAAC;IACnC,CAAC;IAED,mEAAmE;IACnE,oEAAoE;IACpE,gEAAgE;IAChE,mEAAmE;IACnE,iEAAiE;IACjE,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
+ {"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;AAC3F,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD,MAAM,cAAc,GAAG;;;;;;;;;;;;;;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,CAuBZ"}
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,54 +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, [
37
- SESSION_VAR_NAMES.sessionId,
38
- serviceName,
39
- ]);
40
- await client.query(SET_CONFIG_SESSION, [
41
- SESSION_VAR_NAMES.roleName,
42
- 'settings',
43
- ]);
44
- await client.query(SET_CONFIG_SESSION, [
45
- SESSION_VAR_NAMES.allTenants,
46
- 'true',
47
- ]);
48
- return await fn(client);
49
- }
50
- finally {
51
- client.release();
52
- }
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
+ });
53
48
  }
54
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,iB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AAK,UAAU,kBAAkB,CACtC,IAAU,EACV,WAAmB,EACnB,EAAsC;IAEtC,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChE,MAAM,IAAI,iBAAiB,CAAC,wCAAwC,CAAC,CAAC;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;AAS3C,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,kBAAkB,EACnB,MAAM,YAAY,CAAC;AA6CpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CA2DZ"}
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"}