@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.
- package/README.md +198 -223
- package/dist/create-session.d.ts +10 -9
- package/dist/create-session.d.ts.map +1 -1
- package/dist/create-session.js +18 -23
- package/dist/create-session.js.map +1 -1
- package/dist/dev-otp.d.ts.map +1 -1
- package/dist/dev-otp.js +4 -10
- package/dist/dev-otp.js.map +1 -1
- package/dist/errors.d.ts +19 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +23 -5
- package/dist/errors.js.map +1 -1
- package/dist/find-user-by-communication-method.d.ts.map +1 -1
- package/dist/find-user-by-communication-method.js +8 -1
- package/dist/find-user-by-communication-method.js.map +1 -1
- package/dist/get-user-role-names.d.ts.map +1 -1
- package/dist/get-user-role-names.js +2 -0
- package/dist/get-user-role-names.js.map +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -7
- package/dist/index.js.map +1 -1
- package/dist/internal/hash-token.d.ts +16 -0
- package/dist/internal/hash-token.d.ts.map +1 -0
- package/dist/internal/hash-token.js +21 -0
- package/dist/internal/hash-token.js.map +1 -0
- package/dist/methods/errors.d.ts +37 -0
- package/dist/methods/errors.d.ts.map +1 -0
- package/dist/methods/errors.js +48 -0
- package/dist/methods/errors.js.map +1 -0
- package/dist/methods/oidc/index.d.ts +65 -0
- package/dist/methods/oidc/index.d.ts.map +1 -0
- package/dist/methods/oidc/index.js +76 -0
- package/dist/methods/oidc/index.js.map +1 -0
- package/dist/methods/router.d.ts +39 -0
- package/dist/methods/router.d.ts.map +1 -0
- package/dist/methods/router.js +153 -0
- package/dist/methods/router.js.map +1 -0
- package/dist/methods/twilio/index.d.ts +44 -0
- package/dist/methods/twilio/index.d.ts.map +1 -0
- package/dist/methods/twilio/index.js +77 -0
- package/dist/methods/twilio/index.js.map +1 -0
- package/dist/methods/types.d.ts +124 -0
- package/dist/methods/types.d.ts.map +1 -0
- package/dist/methods/types.js +2 -0
- package/dist/methods/types.js.map +1 -0
- package/dist/revoke-session.d.ts +20 -15
- package/dist/revoke-session.d.ts.map +1 -1
- package/dist/revoke-session.js +66 -20
- package/dist/revoke-session.js.map +1 -1
- package/dist/scope/flat-tenant.d.ts +36 -0
- package/dist/scope/flat-tenant.d.ts.map +1 -0
- package/dist/scope/flat-tenant.js +60 -0
- package/dist/scope/flat-tenant.js.map +1 -0
- package/dist/set-helpers.d.ts +44 -53
- package/dist/set-helpers.d.ts.map +1 -1
- package/dist/set-helpers.js +67 -74
- package/dist/set-helpers.js.map +1 -1
- package/dist/touch-session.d.ts +13 -0
- package/dist/touch-session.d.ts.map +1 -0
- package/dist/touch-session.js +28 -0
- package/dist/touch-session.js.map +1 -0
- package/dist/types.d.ts +59 -18
- package/dist/types.d.ts.map +1 -1
- package/dist/validate-session.d.ts +15 -14
- package/dist/validate-session.d.ts.map +1 -1
- package/dist/validate-session.js +28 -27
- package/dist/validate-session.js.map +1 -1
- package/dist/with-service-context.d.ts +15 -12
- package/dist/with-service-context.d.ts.map +1 -1
- package/dist/with-service-context.js +34 -39
- package/dist/with-service-context.js.map +1 -1
- package/dist/with-session.d.ts +22 -16
- package/dist/with-session.d.ts.map +1 -1
- package/dist/with-session.js +67 -66
- package/dist/with-session.js.map +1 -1
- package/package.json +53 -4
- package/schema/functions/current_user_id.yaml +18 -0
- package/schema/functions/resolve_session.yaml +42 -23
- package/schema/post/0001-backfill-audit-by.sql +15 -0
- package/schema/tables/auth_domains.yaml +43 -0
- package/schema/tables/communication_channels.yaml +5 -1
- package/schema/tables/dev_otp_enrollments.yaml +1 -0
- package/schema/tables/roles.yaml +43 -7
- package/schema/tables/sessions.yaml +10 -0
- package/schema/tables/tenants.yaml +24 -1
- package/schema/tables/user_communication_methods.yaml +5 -1
- package/schema/tables/user_roles.yaml +1 -0
- package/schema/tables/users.yaml +27 -0
- package/dist/with-transaction.d.ts +0 -31
- package/dist/with-transaction.d.ts.map +0 -1
- package/dist/with-transaction.js +0 -49
- 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
|
|
10
|
-
*
|
|
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
|
-
/**
|
|
14
|
-
readonly
|
|
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
|
-
*
|
|
24
|
-
*
|
|
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
|
-
/**
|
|
34
|
-
* the user
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
|
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
|
-
|
|
116
|
-
|
|
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
|
package/dist/types.d.ts.map
CHANGED
|
@@ -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
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
|
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import type { Queryable,
|
|
1
|
+
import type { Queryable, SessionInfo } from './types.js';
|
|
2
2
|
/**
|
|
3
|
-
* Look up a session by
|
|
3
|
+
* Look up a session by its raw token and verify it is still valid.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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 `
|
|
16
|
-
* @throws {SessionNotFoundError} If no
|
|
17
|
-
* @throws {SessionExpiredError} If the session
|
|
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,
|
|
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":"
|
|
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"}
|
package/dist/validate-session.js
CHANGED
|
@@ -1,48 +1,49 @@
|
|
|
1
1
|
import { InvalidInputError, SessionExpiredError, SessionNotFoundError } from './errors.js';
|
|
2
|
-
|
|
3
|
-
const CREATED_COL = `created${TS_SUFFIX}`;
|
|
2
|
+
import { hashToken } from './internal/hash-token.js';
|
|
4
3
|
const SELECT_SESSION = `
|
|
5
4
|
SELECT
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
s
|
|
9
|
-
s.
|
|
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
|
|
19
|
+
* Look up a session by its raw token and verify it is still valid.
|
|
17
20
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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 `
|
|
29
|
-
* @throws {SessionNotFoundError} If no
|
|
30
|
-
* @throws {SessionExpiredError} If the session
|
|
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,
|
|
33
|
-
if (typeof
|
|
34
|
-
throw new InvalidInputError('
|
|
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, [
|
|
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
|
-
//
|
|
42
|
-
//
|
|
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;
|
|
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
|
-
*
|
|
4
|
-
*
|
|
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
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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
|
-
*
|
|
15
|
-
*
|
|
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}
|
|
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;
|
|
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 {
|
|
2
|
-
import {
|
|
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
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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
|
-
*
|
|
22
|
-
*
|
|
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}
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
serviceName
|
|
39
|
-
|
|
40
|
-
await client
|
|
41
|
-
|
|
42
|
-
|
|
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,
|
|
1
|
+
{"version":3,"file":"with-service-context.js","sourceRoot":"","sources":["../src/with-service-context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE5D,MAAM,mBAAmB,GAAG;;;;;CAK3B,CAAC;AAMF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,KAAK,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"}
|
package/dist/with-session.d.ts
CHANGED
|
@@ -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.
|
|
5
|
-
*
|
|
6
|
-
* role, sets the
|
|
7
|
-
*
|
|
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
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
-
* {
|
|
23
|
+
* { token, roleName: 'user' },
|
|
19
24
|
* async (client, ctx) => {
|
|
20
|
-
* // ctx = { userId,
|
|
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
|
|
28
|
-
* @throws {SessionExpiredError} If the session has
|
|
29
|
-
* @throws {
|
|
30
|
-
* @throws {InvalidInputError} If `
|
|
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;
|
|
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"}
|