@smplcty/auth 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +352 -0
- package/dist/create-session.d.ts +29 -0
- package/dist/create-session.d.ts.map +1 -0
- package/dist/create-session.js +108 -0
- package/dist/create-session.js.map +1 -0
- package/dist/errors.d.ts +44 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +54 -0
- package/dist/errors.js.map +1 -0
- package/dist/find-user-by-communication-method.d.ts +27 -0
- package/dist/find-user-by-communication-method.d.ts.map +1 -0
- package/dist/find-user-by-communication-method.js +47 -0
- package/dist/find-user-by-communication-method.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/hash-id.d.ts +8 -0
- package/dist/internal/hash-id.d.ts.map +1 -0
- package/dist/internal/hash-id.js +11 -0
- package/dist/internal/hash-id.js.map +1 -0
- package/dist/internal/noop-logger.d.ts +7 -0
- package/dist/internal/noop-logger.d.ts.map +1 -0
- package/dist/internal/noop-logger.js +11 -0
- package/dist/internal/noop-logger.js.map +1 -0
- package/dist/revoke-session.d.ts +16 -0
- package/dist/revoke-session.d.ts.map +1 -0
- package/dist/revoke-session.js +22 -0
- package/dist/revoke-session.js.map +1 -0
- package/dist/set-helpers.d.ts +78 -0
- package/dist/set-helpers.d.ts.map +1 -0
- package/dist/set-helpers.js +110 -0
- package/dist/set-helpers.js.map +1 -0
- package/dist/types.d.ts +118 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validate-session.d.ts +20 -0
- package/dist/validate-session.d.ts.map +1 -0
- package/dist/validate-session.js +49 -0
- package/dist/validate-session.js.map +1 -0
- package/dist/with-session.d.ts +33 -0
- package/dist/with-session.d.ts.map +1 -0
- package/dist/with-session.js +134 -0
- package/dist/with-session.js.map +1 -0
- package/dist/with-transaction.d.ts +31 -0
- package/dist/with-transaction.d.ts.map +1 -0
- package/dist/with-transaction.js +49 -0
- package/dist/with-transaction.js.map +1 -0
- package/package.json +68 -0
- package/schema/tables/communication_channels.yaml +11 -0
- package/schema/tables/roles.yaml +29 -0
- package/schema/tables/sessions.yaml +30 -0
- package/schema/tables/tenants.yaml +11 -0
- package/schema/tables/user_communication_methods.yaml +23 -0
- package/schema/tables/user_roles.yaml +25 -0
- package/schema/tables/users.yaml +7 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { InvalidInputError } from './errors.js';
|
|
2
|
+
const SELECT_BY_COMMUNICATION_METHOD = `
|
|
3
|
+
SELECT
|
|
4
|
+
ucm.user_id AS "userId",
|
|
5
|
+
ucm.user_communication_method_id AS "userCommunicationMethodId"
|
|
6
|
+
FROM user_communication_methods ucm
|
|
7
|
+
JOIN communication_channels cc
|
|
8
|
+
ON cc.communication_channel_id = ucm.communication_channel_id
|
|
9
|
+
WHERE cc.name = $1
|
|
10
|
+
AND ucm.code = $2
|
|
11
|
+
LIMIT 1
|
|
12
|
+
`;
|
|
13
|
+
/**
|
|
14
|
+
* Look up the user attached to a communication method (an email address,
|
|
15
|
+
* phone number, etc). Returns `null` if no matching record exists.
|
|
16
|
+
*
|
|
17
|
+
* Returning `null` instead of throwing is deliberate: the caller (a
|
|
18
|
+
* sign-in endpoint, typically) decides whether to expose user-existence
|
|
19
|
+
* information to the client. To avoid the user-enumeration oracle, most
|
|
20
|
+
* sign-in endpoints should return the same response regardless of
|
|
21
|
+
* whether this returns a value or `null`.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* const lookup = await findUserByCommunicationMethod(db, {
|
|
26
|
+
* channel: 'email',
|
|
27
|
+
* code: 'alice@example.com',
|
|
28
|
+
* });
|
|
29
|
+
* if (!lookup) {
|
|
30
|
+
* // user not registered — but return success anyway to avoid enumeration
|
|
31
|
+
* return { ok: true };
|
|
32
|
+
* }
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @throws {InvalidInputError} If `channel` or `code` is empty.
|
|
36
|
+
*/
|
|
37
|
+
export async function findUserByCommunicationMethod(db, query) {
|
|
38
|
+
if (typeof query?.channel !== 'string' || query.channel.length === 0) {
|
|
39
|
+
throw new InvalidInputError('query.channel must be a non-empty string');
|
|
40
|
+
}
|
|
41
|
+
if (typeof query?.code !== 'string' || query.code.length === 0) {
|
|
42
|
+
throw new InvalidInputError('query.code must be a non-empty string');
|
|
43
|
+
}
|
|
44
|
+
const { rows } = await db.query(SELECT_BY_COMMUNICATION_METHOD, [query.channel, query.code]);
|
|
45
|
+
return rows[0] ?? null;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=find-user-by-communication-method.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"find-user-by-communication-method.js","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAOhD,MAAM,8BAA8B,GAAG;;;;;;;;;;CAUtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,EAAa,EACb,KAAoB;IAEpB,IAAI,OAAO,KAAK,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrE,MAAM,IAAI,iBAAiB,CAAC,0CAA0C,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,OAAO,KAAK,EAAE,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAC7B,8BAA8B,EAC9B,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAC5B,CAAC;IACF,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AACzB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotAssignedError, InvalidInputError, } from './errors.js';
|
|
2
|
+
export type { Queryable, Session, SessionContext, SessionAuth, CreateSessionInput, GeoLocation, UserByCommunicationMethod, FindUserQuery, Logger, WithSessionOptions, } from './types.js';
|
|
3
|
+
export { createSession } from './create-session.js';
|
|
4
|
+
export { validateSession } from './validate-session.js';
|
|
5
|
+
export { revokeSession } from './revoke-session.js';
|
|
6
|
+
export { findUserByCommunicationMethod } from './find-user-by-communication-method.js';
|
|
7
|
+
export { withSession } from './with-session.js';
|
|
8
|
+
export { withTransaction } from './with-transaction.js';
|
|
9
|
+
export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACV,SAAS,EACT,OAAO,EACP,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,yBAAyB,EACzB,aAAa,EACb,MAAM,EACN,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAGvF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Errors
|
|
2
|
+
export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotAssignedError, InvalidInputError, } from './errors.js';
|
|
3
|
+
// Session lifecycle
|
|
4
|
+
export { createSession } from './create-session.js';
|
|
5
|
+
export { validateSession } from './validate-session.js';
|
|
6
|
+
export { revokeSession } from './revoke-session.js';
|
|
7
|
+
export { findUserByCommunicationMethod } from './find-user-by-communication-method.js';
|
|
8
|
+
// Request bootstrapping
|
|
9
|
+
export { withSession } from './with-session.js';
|
|
10
|
+
export { withTransaction } from './with-transaction.js';
|
|
11
|
+
// Low-level helpers — must be called inside an open transaction.
|
|
12
|
+
export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,SAAS;AACT,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAgBrB,oBAAoB;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAEvF,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,iEAAiE;AACjE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Truncated, non-reversible identifier suitable for log correlation.
|
|
3
|
+
* Never log a raw session ID — log `hashId(sessionId)` instead. Twelve hex
|
|
4
|
+
* chars is enough to disambiguate within a single log stream while
|
|
5
|
+
* remaining a one-way hash.
|
|
6
|
+
*/
|
|
7
|
+
export declare function hashId(value: string): string;
|
|
8
|
+
//# sourceMappingURL=hash-id.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash-id.d.ts","sourceRoot":"","sources":["../../src/internal/hash-id.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE5C"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Truncated, non-reversible identifier suitable for log correlation.
|
|
4
|
+
* Never log a raw session ID — log `hashId(sessionId)` instead. Twelve hex
|
|
5
|
+
* chars is enough to disambiguate within a single log stream while
|
|
6
|
+
* remaining a one-way hash.
|
|
7
|
+
*/
|
|
8
|
+
export function hashId(value) {
|
|
9
|
+
return createHash('sha256').update(value).digest('hex').slice(0, 12);
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=hash-id.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash-id.js","sourceRoot":"","sources":["../../src/internal/hash-id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,KAAa;IAClC,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACvE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"noop-logger.d.ts","sourceRoot":"","sources":["../../src/internal/noop-logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,MAKxB,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A logger that discards every message. Used as the default when the
|
|
3
|
+
* caller does not provide a logger.
|
|
4
|
+
*/
|
|
5
|
+
export const noopLogger = {
|
|
6
|
+
debug: () => { },
|
|
7
|
+
info: () => { },
|
|
8
|
+
warn: () => { },
|
|
9
|
+
error: () => { },
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=noop-logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"noop-logger.js","sourceRoot":"","sources":["../../src/internal/noop-logger.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAW;IAChC,KAAK,EAAE,GAAG,EAAE,GAAE,CAAC;IACf,IAAI,EAAE,GAAG,EAAE,GAAE,CAAC;IACd,IAAI,EAAE,GAAG,EAAE,GAAE,CAAC;IACd,KAAK,EAAE,GAAG,EAAE,GAAE,CAAC;CAChB,CAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Queryable } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Revoke a session by hard-deleting its row from the `sessions` table.
|
|
4
|
+
*
|
|
5
|
+
* Idempotent: revoking a non-existent session is not an error. Returns
|
|
6
|
+
* normally regardless of whether a row was deleted.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* await revokeSession(db, sessionId);
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @throws {InvalidInputError} If `sessionId` is not a non-empty string.
|
|
14
|
+
*/
|
|
15
|
+
export declare function revokeSession(db: Queryable, sessionId: string): Promise<void>;
|
|
16
|
+
//# sourceMappingURL=revoke-session.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revoke-session.d.ts","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C;;;;;;;;;;;;GAYG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,SAAS,EACb,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAKf"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { InvalidInputError } from './errors.js';
|
|
2
|
+
const DELETE_SESSION = 'DELETE FROM sessions WHERE session_id = $1';
|
|
3
|
+
/**
|
|
4
|
+
* Revoke a session by hard-deleting its row from the `sessions` table.
|
|
5
|
+
*
|
|
6
|
+
* Idempotent: revoking a non-existent session is not an error. Returns
|
|
7
|
+
* normally regardless of whether a row was deleted.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* await revokeSession(db, sessionId);
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @throws {InvalidInputError} If `sessionId` is not a non-empty string.
|
|
15
|
+
*/
|
|
16
|
+
export async function revokeSession(db, sessionId) {
|
|
17
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
18
|
+
throw new InvalidInputError('sessionId must be a non-empty string');
|
|
19
|
+
}
|
|
20
|
+
await db.query(DELETE_SESSION, [sessionId]);
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=revoke-session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revoke-session.js","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,cAAc,GAAG,4CAA4C,CAAC;AAEpE;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,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;IACD,MAAM,EAAE,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9C,CAAC"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { PoolClient } from 'pg';
|
|
2
|
+
/**
|
|
3
|
+
* The four GUC variable names this library uses. Re-exported here in
|
|
4
|
+
* case consumers need them in custom RLS policies.
|
|
5
|
+
*/
|
|
6
|
+
export declare const SESSION_VAR_NAMES: {
|
|
7
|
+
readonly sessionId: "app.session_id";
|
|
8
|
+
readonly roleName: "app.role_name";
|
|
9
|
+
readonly tenantIds: "app.tenant_ids";
|
|
10
|
+
readonly allTenants: "app.all_tenants";
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
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.
|
|
26
|
+
*
|
|
27
|
+
* @throws {InvalidInputError} If `sessionId` is not a non-empty string.
|
|
28
|
+
*/
|
|
29
|
+
export declare function setSessionId(client: PoolClient, sessionId: string): Promise<void>;
|
|
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.
|
|
39
|
+
*
|
|
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.
|
|
43
|
+
*/
|
|
44
|
+
export declare function setRoleName<TRole extends string = string>(client: PoolClient, roleName: TRole): Promise<void>;
|
|
45
|
+
/**
|
|
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.
|
|
49
|
+
*
|
|
50
|
+
* **Contract:** `client` must be inside an open transaction.
|
|
51
|
+
*
|
|
52
|
+
* @throws {InvalidInputError} If any element of `tenantIds` is not a finite integer.
|
|
53
|
+
*/
|
|
54
|
+
export declare function setTenantIds(client: PoolClient, tenantIds: readonly number[]): Promise<void>;
|
|
55
|
+
/**
|
|
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.
|
|
59
|
+
*
|
|
60
|
+
* **Contract:** `client` must be inside an open transaction.
|
|
61
|
+
*
|
|
62
|
+
* @throws {InvalidInputError} If `allTenants` is not a boolean.
|
|
63
|
+
*/
|
|
64
|
+
export declare function setAllTenants(client: PoolClient, allTenants: boolean): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Set all four session variables in one call. Equivalent to calling
|
|
67
|
+
* `setSessionId`, `setRoleName`, `setTenantIds`, and `setAllTenants`
|
|
68
|
+
* sequentially, but more concise.
|
|
69
|
+
*
|
|
70
|
+
* **Contract:** `client` must be inside an open transaction.
|
|
71
|
+
*/
|
|
72
|
+
export declare function setSessionContext<TRole extends string = string>(client: PoolClient, context: {
|
|
73
|
+
sessionId: string;
|
|
74
|
+
roleName: TRole;
|
|
75
|
+
tenantIds: readonly number[];
|
|
76
|
+
allTenants: boolean;
|
|
77
|
+
}): Promise<void>;
|
|
78
|
+
//# sourceMappingURL=set-helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"set-helpers.d.ts","sourceRoot":"","sources":["../src/set-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAKrC;;;GAGG;AACH,eAAO,MAAM,iBAAiB;;;;;CAKpB,CAAC;AAEX;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAKf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAC7D,MAAM,EAAE,UAAU,EAClB,QAAQ,EAAE,KAAK,GACd,OAAO,CAAC,IAAI,CAAC,CAKf;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,SAAS,MAAM,EAAE,GAC3B,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,UAAU,EAClB,UAAU,EAAE,OAAO,GAClB,OAAO,CAAC,IAAI,CAAC,CAQf;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EACnE,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE;IACP,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC;IAChB,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,UAAU,EAAE,OAAO,CAAC;CACrB,GACA,OAAO,CAAC,IAAI,CAAC,CAKf"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { InvalidInputError } from './errors.js';
|
|
2
|
+
const SET_CONFIG = 'SELECT set_config($1, $2, true)';
|
|
3
|
+
/**
|
|
4
|
+
* The four GUC variable names this library uses. Re-exported here in
|
|
5
|
+
* case consumers need them in custom RLS policies.
|
|
6
|
+
*/
|
|
7
|
+
export const SESSION_VAR_NAMES = {
|
|
8
|
+
sessionId: 'app.session_id',
|
|
9
|
+
roleName: 'app.role_name',
|
|
10
|
+
tenantIds: 'app.tenant_ids',
|
|
11
|
+
allTenants: 'app.all_tenants',
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Set `app.session_id` for the current transaction.
|
|
15
|
+
*
|
|
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.
|
|
23
|
+
*
|
|
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.
|
|
27
|
+
*
|
|
28
|
+
* @throws {InvalidInputError} If `sessionId` is not a non-empty string.
|
|
29
|
+
*/
|
|
30
|
+
export async function setSessionId(client, sessionId) {
|
|
31
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
32
|
+
throw new InvalidInputError('sessionId must be a non-empty string');
|
|
33
|
+
}
|
|
34
|
+
await client.query(SET_CONFIG, [SESSION_VAR_NAMES.sessionId, sessionId]);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Set `app.role_name` for the current transaction.
|
|
38
|
+
*
|
|
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.
|
|
49
|
+
*/
|
|
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');
|
|
53
|
+
}
|
|
54
|
+
await client.query(SET_CONFIG, [SESSION_VAR_NAMES.roleName, roleName]);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
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.
|
|
62
|
+
*
|
|
63
|
+
* @throws {InvalidInputError} If any element of `tenantIds` is not a finite integer.
|
|
64
|
+
*/
|
|
65
|
+
export async function setTenantIds(client, tenantIds) {
|
|
66
|
+
if (!Array.isArray(tenantIds)) {
|
|
67
|
+
throw new InvalidInputError('tenantIds must be an array of integers');
|
|
68
|
+
}
|
|
69
|
+
for (const id of tenantIds) {
|
|
70
|
+
if (!Number.isInteger(id)) {
|
|
71
|
+
throw new InvalidInputError(`tenantIds must contain only integers; got ${String(id)}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
await client.query(SET_CONFIG, [
|
|
75
|
+
SESSION_VAR_NAMES.tenantIds,
|
|
76
|
+
tenantIds.join(','),
|
|
77
|
+
]);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Set `app.all_tenants` for the current transaction. When `true`, RLS
|
|
81
|
+
* policies typically bypass tenant filtering and allow access to every
|
|
82
|
+
* tenant's rows.
|
|
83
|
+
*
|
|
84
|
+
* **Contract:** `client` must be inside an open transaction.
|
|
85
|
+
*
|
|
86
|
+
* @throws {InvalidInputError} If `allTenants` is not a boolean.
|
|
87
|
+
*/
|
|
88
|
+
export async function setAllTenants(client, allTenants) {
|
|
89
|
+
if (typeof allTenants !== 'boolean') {
|
|
90
|
+
throw new InvalidInputError('allTenants must be a boolean');
|
|
91
|
+
}
|
|
92
|
+
await client.query(SET_CONFIG, [
|
|
93
|
+
SESSION_VAR_NAMES.allTenants,
|
|
94
|
+
allTenants ? 'true' : 'false',
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Set all four session variables in one call. Equivalent to calling
|
|
99
|
+
* `setSessionId`, `setRoleName`, `setTenantIds`, and `setAllTenants`
|
|
100
|
+
* sequentially, but more concise.
|
|
101
|
+
*
|
|
102
|
+
* **Contract:** `client` must be inside an open transaction.
|
|
103
|
+
*/
|
|
104
|
+
export async function setSessionContext(client, context) {
|
|
105
|
+
await setSessionId(client, context.sessionId);
|
|
106
|
+
await setRoleName(client, context.roleName);
|
|
107
|
+
await setTenantIds(client, context.tenantIds);
|
|
108
|
+
await setAllTenants(client, context.allTenants);
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=set-helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|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
|
+
* A `pg.Pool` or any single checked-out `pg.PoolClient`. Functions that
|
|
4
|
+
* accept this type can be called with either — they perform a single query
|
|
5
|
+
* and don't need to span multiple statements on the same connection.
|
|
6
|
+
*/
|
|
7
|
+
export type Queryable = Pool | PoolClient;
|
|
8
|
+
/**
|
|
9
|
+
* A persisted session row, returned from `createSession` and
|
|
10
|
+
* `validateSession`.
|
|
11
|
+
*/
|
|
12
|
+
export interface Session {
|
|
13
|
+
/** Server-generated session token. Treat as a bearer credential. */
|
|
14
|
+
readonly sessionId: string;
|
|
15
|
+
/** The user this session was created for. */
|
|
16
|
+
readonly userId: number;
|
|
17
|
+
/** When the session row was created. */
|
|
18
|
+
readonly createdAt: Date;
|
|
19
|
+
/** When the session expires. After this instant, the session is invalid. */
|
|
20
|
+
readonly expiresAt: Date;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The fully resolved authentication context for a request. Passed to the
|
|
24
|
+
* callback inside `withSession`.
|
|
25
|
+
*
|
|
26
|
+
* @typeParam TRole - String literal union of role names valid in your
|
|
27
|
+
* application. Defaults to `string`. Narrow this in a thin wrapper —
|
|
28
|
+
* see the README for the recommended pattern.
|
|
29
|
+
*/
|
|
30
|
+
export interface SessionContext<TRole extends string = string> {
|
|
31
|
+
/** The user this session belongs to. */
|
|
32
|
+
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). */
|
|
41
|
+
readonly roles: readonly TRole[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Geolocation metadata captured at session creation time. All fields
|
|
45
|
+
* optional — only what your app supplies will be stored.
|
|
46
|
+
*/
|
|
47
|
+
export interface GeoLocation {
|
|
48
|
+
city?: string;
|
|
49
|
+
region?: string;
|
|
50
|
+
country?: string;
|
|
51
|
+
latitude?: string;
|
|
52
|
+
longitude?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Input to `createSession`.
|
|
56
|
+
*/
|
|
57
|
+
export interface CreateSessionInput {
|
|
58
|
+
/** The communication method (email row, phone row, etc.) the user
|
|
59
|
+
* authenticated with. Get this from `findUserByCommunicationMethod`. */
|
|
60
|
+
userCommunicationMethodId: number;
|
|
61
|
+
/** Postgres interval string — e.g. `'30 days'`, `'12 hours'`, `'1 week'`.
|
|
62
|
+
* Evaluated server-side via `now() + interval $ttl`. There is no
|
|
63
|
+
* default; sessions never live forever. */
|
|
64
|
+
ttl: string;
|
|
65
|
+
/** IP address of the requester. Optional. */
|
|
66
|
+
ip?: string;
|
|
67
|
+
/** Geolocation derived from the requester's IP. Optional. */
|
|
68
|
+
geo?: GeoLocation;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Result of `findUserByCommunicationMethod`.
|
|
72
|
+
*/
|
|
73
|
+
export interface UserByCommunicationMethod {
|
|
74
|
+
readonly userId: number;
|
|
75
|
+
readonly userCommunicationMethodId: number;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Query for `findUserByCommunicationMethod`.
|
|
79
|
+
*/
|
|
80
|
+
export interface FindUserQuery {
|
|
81
|
+
/** The name of the communication channel — typically `'email'` or
|
|
82
|
+
* `'phone'`. Matched against `communication_channels.name`. */
|
|
83
|
+
channel: string;
|
|
84
|
+
/** The address or number — matched against `user_communication_methods.code`. */
|
|
85
|
+
code: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* A pluggable structured logger. The argument order matches `pino`'s
|
|
89
|
+
* idiomatic shape so a pino logger can be passed directly without
|
|
90
|
+
* adaptation.
|
|
91
|
+
*
|
|
92
|
+
* The library never logs PII or session IDs. It only emits structural
|
|
93
|
+
* events with safe identifiers (userId, role, hash prefixes).
|
|
94
|
+
*/
|
|
95
|
+
export interface Logger {
|
|
96
|
+
debug(data: Record<string, unknown>, msg: string): void;
|
|
97
|
+
info(data: Record<string, unknown>, msg: string): void;
|
|
98
|
+
warn(data: Record<string, unknown>, msg: string): void;
|
|
99
|
+
error(data: Record<string, unknown>, msg: string): void;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Options accepted by `withSession`.
|
|
103
|
+
*/
|
|
104
|
+
export interface WithSessionOptions {
|
|
105
|
+
/** Optional logger. Defaults to a no-op. */
|
|
106
|
+
logger?: Logger;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Authentication parameters passed to `withSession`.
|
|
110
|
+
*
|
|
111
|
+
* @typeParam TRole - String literal union of role names valid in your
|
|
112
|
+
* application. Defaults to `string`.
|
|
113
|
+
*/
|
|
114
|
+
export interface SessionAuth<TRole extends string = string> {
|
|
115
|
+
sessionId: string;
|
|
116
|
+
roleName: TRole;
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +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;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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;IACjC,4CAA4C;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,MAAM,WAAW,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC;CACjB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Queryable, Session } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Look up a session by ID and verify it is still valid.
|
|
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.
|
|
8
|
+
*
|
|
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.
|
|
14
|
+
*
|
|
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.
|
|
18
|
+
*/
|
|
19
|
+
export declare function validateSession(db: Queryable, sessionId: string): Promise<Session>;
|
|
20
|
+
//# sourceMappingURL=validate-session.d.ts.map
|
|
@@ -0,0 +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;AAcrD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,eAAe,CACnC,EAAE,EAAE,SAAS,EACb,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,OAAO,CAAC,CAqBlB"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { InvalidInputError, SessionExpiredError, SessionNotFoundError } from './errors.js';
|
|
2
|
+
const SELECT_SESSION = `
|
|
3
|
+
SELECT
|
|
4
|
+
s.session_id AS "sessionId",
|
|
5
|
+
ucm.user_id AS "userId",
|
|
6
|
+
s.created_at AS "createdAt",
|
|
7
|
+
s.expires_at AS "expiresAt"
|
|
8
|
+
FROM sessions s
|
|
9
|
+
JOIN user_communication_methods ucm
|
|
10
|
+
ON ucm.user_communication_method_id = s.user_communication_method_id
|
|
11
|
+
WHERE s.session_id = $1
|
|
12
|
+
`;
|
|
13
|
+
/**
|
|
14
|
+
* Look up a session by ID and verify it is still valid.
|
|
15
|
+
*
|
|
16
|
+
* Returns the {@link Session} on success. Throws if the session does
|
|
17
|
+
* not exist, has expired, or the input is malformed. Does not set any
|
|
18
|
+
* Postgres session variables — this is purely a check.
|
|
19
|
+
*
|
|
20
|
+
* Use this function in API Gateway authorizers, refresh-token flows,
|
|
21
|
+
* and any other place where you need to verify a token without entering
|
|
22
|
+
* a request transaction. For an authenticated request that will run
|
|
23
|
+
* queries, use {@link withSession} instead — it does this validation
|
|
24
|
+
* AND sets up the database context in one call.
|
|
25
|
+
*
|
|
26
|
+
* @throws {InvalidInputError} If `sessionId` is not a non-empty string.
|
|
27
|
+
* @throws {SessionNotFoundError} If no row matches `sessionId`.
|
|
28
|
+
* @throws {SessionExpiredError} If the session row exists but `expires_at` has passed.
|
|
29
|
+
*/
|
|
30
|
+
export async function validateSession(db, sessionId) {
|
|
31
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
32
|
+
throw new InvalidInputError('sessionId must be a non-empty string');
|
|
33
|
+
}
|
|
34
|
+
const { rows } = await db.query(SELECT_SESSION, [sessionId]);
|
|
35
|
+
const row = rows[0];
|
|
36
|
+
if (!row) {
|
|
37
|
+
throw new SessionNotFoundError();
|
|
38
|
+
}
|
|
39
|
+
// Compare against the database's now() rather than the local clock
|
|
40
|
+
// would be ideal, but we already trust the row that the DB returned
|
|
41
|
+
// and `expiresAt` is a timestamptz that pg parses to a JS Date.
|
|
42
|
+
// Local-clock comparison is fine here because expiry is server-set
|
|
43
|
+
// by createSession; we're only checking "have we passed it yet."
|
|
44
|
+
if (row.expiresAt.getTime() <= Date.now()) {
|
|
45
|
+
throw new SessionExpiredError(row.expiresAt);
|
|
46
|
+
}
|
|
47
|
+
return row;
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=validate-session.js.map
|
|
@@ -0,0 +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,cAAc,GAAG;;;;;;;;;;CAUtB,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"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Pool, PoolClient } from 'pg';
|
|
2
|
+
import type { SessionAuth, SessionContext, WithSessionOptions } from './types.js';
|
|
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).
|
|
9
|
+
*
|
|
10
|
+
* The session variables use **transaction scope**, so they're discarded
|
|
11
|
+
* automatically when this function returns. Cross-request leakage is
|
|
12
|
+
* impossible.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* const widgets = await withSession(
|
|
17
|
+
* pool,
|
|
18
|
+
* { sessionId, roleName: 'user' },
|
|
19
|
+
* async (client, ctx) => {
|
|
20
|
+
* // ctx = { userId, tenantIds, allTenants, roles }
|
|
21
|
+
* const { rows } = await client.query('SELECT * FROM widgets');
|
|
22
|
+
* return rows;
|
|
23
|
+
* }
|
|
24
|
+
* );
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
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.
|
|
31
|
+
*/
|
|
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>;
|
|
33
|
+
//# sourceMappingURL=with-session.d.ts.map
|
|
@@ -0,0 +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;AAqEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;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"}
|