@ultimat3/auth 31.59.0 → 31.61.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 CHANGED
@@ -937,6 +937,49 @@ rather than an actor calls the same read: `verifySessionWithUser(auth.sessions,
937
937
  answers `{ session, user }` (`user: null` when the session outlived its user — delete the session and
938
938
  refuse), one join on an adapter with `getSessionWithUser`, else `verifySession` then `findUserById`.
939
939
 
940
+ An app that needs rows of its own beside the session (the memberships its actor is built from)
941
+ reads them in the same statement and passes that read as a fourth argument. It selects
942
+ `SESSION_WITH_USER_COLUMNS` (every column aliased `s_*` or `u_*`, so alias your own apart) over
943
+ `x_sessions s left join x_users u on u.id = s.user_id`, and reads the row with `sessionWithUserOf`:
944
+
945
+ ```ts
946
+ import {
947
+ type Auth,
948
+ SESSION_WITH_USER_COLUMNS,
949
+ sessionWithUserOf,
950
+ verifySessionWithUser,
951
+ } from '@ultimat3/auth';
952
+ import { type DbClient, sql } from '@ultimat3/db';
953
+
954
+ type Row = Readonly<Record<string, unknown>>;
955
+
956
+ // `client` is the one the adapter was built over (`postgresAuthAdapter(client)`), so the read
957
+ // finds the sessions the adapter wrote.
958
+ export async function sessionWithOrgs(auth: Auth, client: DbClient, token: string) {
959
+ let rows: readonly Row[] = [];
960
+ const { session, user } = await verifySessionWithUser(
961
+ auth.sessions,
962
+ auth.adapter,
963
+ token,
964
+ async (id) => {
965
+ rows = await client.query<Row>(sql`
966
+ select ${SESSION_WITH_USER_COLUMNS}, m.org_id as m_org_id
967
+ from x_sessions s left join x_users u on u.id = s.user_id
968
+ left join memberships m on m.user_id = s.user_id
969
+ where s.id = ${id}`);
970
+ return rows[0] === undefined ? null : sessionWithUserOf(rows[0]);
971
+ },
972
+ );
973
+ // `rows` may be trusted only now: the session was admitted above.
974
+ // A person with no membership still has one row, its `m_org_id` null.
975
+ const orgIds = rows.map((row) => row['m_org_id']).filter((id) => id !== null);
976
+ return { session, user, orgIds };
977
+ }
978
+ ```
979
+
980
+ The builtin adapter's own `getSessionWithUser` selects the same list, so the two never drift.
981
+ Nothing the read returns is handed back before the session is admitted.
982
+
940
983
  **Revocation is unaffected, and deliberately so.** `authenticate` re-reads the *user* row on every
941
984
  request — in that same join — so a revoked role takes effect on the very next one with no token-expiry lag — a better
942
985
  property than any claims-in-a-JWT design. Throttling the session write is safe; caching the user
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.59.0",
3
+ "version": "31.61.0",
4
4
  "description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -50,8 +50,8 @@
50
50
  "test": "bun test"
51
51
  },
52
52
  "dependencies": {
53
- "@ultimat3/core": "31.59.0",
54
- "@ultimat3/db": "31.59.0",
55
- "@ultimat3/schema": "31.59.0"
53
+ "@ultimat3/core": "31.61.0",
54
+ "@ultimat3/db": "31.61.0",
55
+ "@ultimat3/schema": "31.61.0"
56
56
  }
57
57
  }
@@ -3,12 +3,14 @@
3
3
  // readers, no `any`: a renamed column reads as its empty value here and fails a round-trip test,
4
4
  // never as a silent `undefined`.
5
5
 
6
+ import { type SqlFragment, sql } from '@ultimat3/db';
6
7
  import type {
7
8
  AuthAccount,
8
9
  AuthApiKeyRecord,
9
10
  AuthSession,
10
11
  AuthUser,
11
12
  AuthVerification,
13
+ SessionWithUser,
12
14
  } from './adapter';
13
15
 
14
16
  export type Row = Readonly<Record<string, unknown>>;
@@ -112,3 +114,37 @@ export const unprefixed = (row: Row, prefix: string): Row =>
112
114
  .filter(([key]) => key.startsWith(prefix))
113
115
  .map(([key, value]) => [key.slice(prefix.length), value]),
114
116
  );
117
+
118
+ /**
119
+ * The select list of a session joined to its user, every column aliased: the session's as `s_*`,
120
+ * the user's as `u_*`, over `x_sessions s left join x_users u on u.id = s.user_id`. What the
121
+ * builtin adapter's `getSessionWithUser` selects, exported so an app can join rows of its own to
122
+ * the same statement (aliased apart from these) and hand the row to `sessionWithUserOf`. A column
123
+ * renamed here fails the adapter's round-trip tests, so the two never drift.
124
+ */
125
+ export const SESSION_WITH_USER_COLUMNS: SqlFragment = sql`
126
+ s.id as s_id, s.user_id as s_user_id, s.token_hash as s_token_hash,
127
+ s.created_at as s_created_at, s.absolute_expires_at as s_absolute_expires_at,
128
+ s.last_seen_at as s_last_seen_at, s.ip as s_ip, s.user_agent as s_user_agent,
129
+ s.mfa_satisfied as s_mfa_satisfied,
130
+ u.id as u_id, u.email as u_email, u.email_verified_at as u_email_verified_at,
131
+ u.password_hash as u_password_hash, u.org_id as u_org_id, u.roles as u_roles,
132
+ u.permissions as u_permissions, u.scopes as u_scopes, u.mfa_secret as u_mfa_secret,
133
+ u.recovery_code_hashes as u_recovery_code_hashes, u.external_id as u_external_id,
134
+ u.disabled_at as u_disabled_at, u.created_at as u_created_at`;
135
+
136
+ /**
137
+ * A row carrying `SESSION_WITH_USER_COLUMNS` read into the session and its user: `null` when the row
138
+ * holds no session, `user: null` when the session outlived its user. Columns of any other prefix
139
+ * are ignored. The session is NOT admitted here: hand it to `verifySessionWithUser`, which checks
140
+ * the secret and both clocks before it answers the user.
141
+ */
142
+ export function sessionWithUserOf(row: Row): SessionWithUser | null {
143
+ const session = unprefixed(row, 's_');
144
+ if (textOrNull(session, 'id') === null) return null;
145
+ const user = unprefixed(row, 'u_');
146
+ return {
147
+ session: toSession(session),
148
+ user: textOrNull(user, 'id') === null ? null : toUser(user),
149
+ };
150
+ }
@@ -22,13 +22,14 @@ import type {
22
22
  } from './adapter';
23
23
  import {
24
24
  type Row,
25
+ SESSION_WITH_USER_COLUMNS,
26
+ sessionWithUserOf,
25
27
  text,
26
28
  toAccount,
27
29
  toApiKey,
28
30
  toSession,
29
31
  toUser,
30
32
  toVerification,
31
- unprefixed,
32
33
  } from './builtin-adapter-rows';
33
34
  import { usersUniqueViolation } from './builtin-adapter-violation';
34
35
  import { authWriteFailed } from './errors';
@@ -302,23 +303,16 @@ export class PostgresAuthAdapter implements AuthAdapter {
302
303
  }
303
304
 
304
305
  /**
305
- * The session's columns aliased `s_*`, because both tables have an `id` and a `created_at`; the
306
- * user's arrive under their own names. A left join, so a session that outlived its user still
307
- * comes back — `authenticate` deletes it, exactly as it does after the two-read path.
306
+ * One statement: the session and its user, every column aliased (`SESSION_WITH_USER_COLUMNS`). A
307
+ * left join, so a session that outlived its user still comes back — `authenticate` deletes it,
308
+ * exactly as it does after the two-read path.
308
309
  */
309
310
  async getSessionWithUser(id: string): Promise<SessionWithUser | null> {
310
311
  const row = await this.#db.one<Row>(sql`
311
- select s.id as s_id, s.user_id as s_user_id, s.token_hash as s_token_hash,
312
- s.created_at as s_created_at, s.absolute_expires_at as s_absolute_expires_at,
313
- s.last_seen_at as s_last_seen_at, s.ip as s_ip, s.user_agent as s_user_agent,
314
- s.mfa_satisfied as s_mfa_satisfied, u.*
312
+ select ${SESSION_WITH_USER_COLUMNS}
315
313
  from x_sessions s left join x_users u on u.id = s.user_id
316
314
  where s.id = ${id}`);
317
- if (row === null) return null;
318
- return {
319
- session: toSession(unprefixed(row, 's_')),
320
- user: row['id'] === null || row['id'] === undefined ? null : toUser(row),
321
- };
315
+ return row === null ? null : sessionWithUserOf(row);
322
316
  }
323
317
 
324
318
  async deleteSessionsCreatedBefore(before: Date): Promise<number> {
package/src/index.ts CHANGED
@@ -97,6 +97,10 @@ export type {
97
97
  AuthServerRoute,
98
98
  } from './authorization-server-wire';
99
99
  export { type PostgresAuthAdapter, postgresAuthAdapter } from './builtin-adapter';
100
+ export {
101
+ SESSION_WITH_USER_COLUMNS,
102
+ sessionWithUserOf,
103
+ } from './builtin-adapter-rows';
100
104
  /** The opaque per-principal id a per-request document hands the page's client store. */
101
105
  export type { ClientScopeOptions } from './client-scope';
102
106
  export { clientScopeOf } from './client-scope';
@@ -429,7 +433,7 @@ export {
429
433
  sessionExpiry,
430
434
  verifySession,
431
435
  } from './session';
432
- export type { VerifiedSession } from './session-user';
436
+ export type { SessionWithUserRead, VerifiedSession } from './session-user';
433
437
  export { verifySessionWithUser } from './session-user';
434
438
  /** A sign-out response's headers: the session cookie expired, and `Clear-Site-Data`. */
435
439
  export type { SignOutHeadersOptions } from './sign-out';
@@ -1,8 +1,9 @@
1
1
  // Single responsibility: a session token to its live session AND its user, in the fewest reads the
2
2
  // adapter allows — one join when it has `getSessionWithUser`, else `verifySession` then
3
- // `findUserById`. Admission is `admitSession` either way; whether the user may act is the caller's.
3
+ // `findUserById` — or in the caller's own read, when it joins rows of its own to the session.
4
+ // Admission is `admitSession` either way; whether the user may act is the caller's.
4
5
 
5
- import type { AuthAdapter, AuthSession, AuthUser } from './adapter';
6
+ import type { AuthAdapter, AuthSession, AuthUser, SessionWithUser } from './adapter';
6
7
  import { sessionUnknown } from './errors';
7
8
  import { admitSession, parseSessionToken, type SessionRuntime, verifySession } from './session';
8
9
 
@@ -12,23 +13,35 @@ export interface VerifiedSession {
12
13
  readonly user: AuthUser | null;
13
14
  }
14
15
 
16
+ /**
17
+ * The caller's own read of the session and its user, by session id: one statement that selects
18
+ * `SESSION_WITH_USER_COLUMNS` beside rows of the caller's own, read with `sessionWithUserOf`.
19
+ * `null` for a session that does not exist.
20
+ */
21
+ export type SessionWithUserRead = (sessionId: string) => Promise<SessionWithUser | null>;
22
+
15
23
  /**
16
24
  * The user is read only once the session is admitted on the two-read path, and on the join it is
17
25
  * read in the same statement but handed back only after admission: a forged or expired token
18
- * never yields a user either way.
26
+ * never yields a user either way. `read`, when given, is that join, in place of the adapter's
27
+ * `getSessionWithUser`: an app that needs its own rows beside the session reads them in the same
28
+ * statement, and still nothing it read is trusted until the session is admitted here. A token that
29
+ * does not parse reads nothing.
19
30
  */
20
31
  export async function verifySessionWithUser(
21
32
  runtime: SessionRuntime,
22
33
  adapter: AuthAdapter,
23
34
  token: string,
35
+ read?: SessionWithUserRead,
24
36
  ): Promise<VerifiedSession> {
25
- if (adapter.getSessionWithUser === undefined) {
37
+ const join = read ?? adapter.getSessionWithUser?.bind(adapter);
38
+ if (join === undefined) {
26
39
  const session = await verifySession(runtime, token);
27
40
  return { session, user: await adapter.findUserById(session.userId) };
28
41
  }
29
42
  const parsed = parseSessionToken(token);
30
43
  if (parsed === null) throw sessionUnknown();
31
- const joined = await adapter.getSessionWithUser(parsed.id);
44
+ const joined = await join(parsed.id);
32
45
  const session = await admitSession(runtime, parsed.secret, joined?.session ?? null);
33
46
  return { session, user: joined?.user ?? null };
34
47
  }