@crombolo/auth 0.37.0 → 0.38.1

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 (3) hide show
  1. package/package.json +3 -3
  2. package/src/device.ts +64 -47
  3. package/src/store.ts +227 -166
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/auth",
3
- "version": "0.37.0",
3
+ "version": "0.38.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. OAuth2 authorization server, password hashing, cookies and member tickets for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,8 +28,8 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.37.0",
32
- "@crombolo/data": "0.37.0",
31
+ "@crombolo/core": "0.38.1",
32
+ "@crombolo/data": "0.38.1",
33
33
  "jose": "^6.2.12",
34
34
  "uqr": "^0.1.3"
35
35
  }
package/src/device.ts CHANGED
@@ -95,21 +95,20 @@ export class DeviceStore {
95
95
  for (let attempt = 0; ; attempt++) {
96
96
  const code = userCode()
97
97
  try {
98
- await this.#db.exec(
99
- `INSERT INTO device_authorization
100
- (device_code_hash, user_code, client_id, client_name, scope, status, interval_seconds, expires_at, create_date)
101
- VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`,
102
- [
103
- hashToken(deviceCode),
104
- code,
105
- init.clientId,
106
- init.clientName,
107
- init.scope,
108
- DEVICE_POLL_SECONDS,
109
- DbDate.toDb(expiresAt),
110
- DbDate.toDb(new Date()),
111
- ],
112
- )
98
+ await this.#db.q
99
+ .insertInto('device_authorization')
100
+ .values({
101
+ device_code_hash: hashToken(deviceCode),
102
+ user_code: code,
103
+ client_id: init.clientId,
104
+ client_name: init.clientName,
105
+ scope: init.scope,
106
+ status: 'pending',
107
+ interval_seconds: DEVICE_POLL_SECONDS,
108
+ expires_at: DbDate.toDb(expiresAt),
109
+ create_date: DbDate.toDb(new Date()),
110
+ })
111
+ .execute()
113
112
  return { deviceCode, userCode: code, expiresAt }
114
113
  } catch (error) {
115
114
  if (attempt >= 4) throw error
@@ -118,56 +117,70 @@ export class DeviceStore {
118
117
  }
119
118
 
120
119
  async byDeviceCode(deviceCode: string): Promise<DeviceAuthorizationRow | undefined> {
121
- const rows = await this.#db.query(
122
- 'SELECT * FROM device_authorization WHERE device_code_hash = ?',
123
- [hashToken(deviceCode)],
124
- )
125
- return rows[0] ? mapRow(rows[0]) : undefined
120
+ const row = await this.#db.q
121
+ .selectFrom('device_authorization')
122
+ .selectAll()
123
+ .where('device_code_hash', '=', hashToken(deviceCode))
124
+ .executeTakeFirst()
125
+ return row ? mapRow(row) : undefined
126
126
  }
127
127
 
128
128
  async byUserCode(code: string): Promise<DeviceAuthorizationRow | undefined> {
129
- const rows = await this.#db.query('SELECT * FROM device_authorization WHERE user_code = ?', [
130
- normaliseUserCode(code),
131
- ])
132
- return rows[0] ? mapRow(rows[0]) : undefined
129
+ const row = await this.#db.q
130
+ .selectFrom('device_authorization')
131
+ .selectAll()
132
+ .where('user_code', '=', normaliseUserCode(code))
133
+ .executeTakeFirst()
134
+ return row ? mapRow(row) : undefined
133
135
  }
134
136
 
135
137
  async polled(id: number, intervalSeconds: number): Promise<void> {
136
- await this.#db.exec(
137
- 'UPDATE device_authorization SET last_polled_at = ?, interval_seconds = ? WHERE id = ?',
138
- [DbDate.toDb(new Date()), intervalSeconds, id],
139
- )
138
+ await this.#db.q
139
+ .updateTable('device_authorization')
140
+ .set({ last_polled_at: DbDate.toDb(new Date()), interval_seconds: intervalSeconds })
141
+ .where('id', '=', id)
142
+ .execute()
140
143
  }
141
144
 
142
145
  /** Approves or denies a pending one; false when it was no longer pending. */
143
146
  async decide(id: number, userId: number, approve: boolean): Promise<boolean> {
144
- const rows = await this.#db.query<{ id: number }>(
145
- `UPDATE device_authorization SET status = ?, user_id = ?, decided_at = ?
146
- WHERE id = ? AND status = 'pending' RETURNING id`,
147
- [approve ? 'approved' : 'denied', userId, DbDate.toDb(new Date()), id],
148
- )
147
+ const rows = await this.#db.q
148
+ .updateTable('device_authorization')
149
+ .set({
150
+ status: approve ? 'approved' : 'denied',
151
+ user_id: userId,
152
+ decided_at: DbDate.toDb(new Date()),
153
+ })
154
+ .where('id', '=', id)
155
+ .where('status', '=', 'pending')
156
+ .returning('id')
157
+ .execute()
149
158
  return rows.length > 0
150
159
  }
151
160
 
152
161
  /** Marks an approved one as having had its tokens issued, once; false if it already had. */
153
162
  async issued(id: number, sessionId: string): Promise<boolean> {
154
- const rows = await this.#db.query<{ id: number }>(
155
- `UPDATE device_authorization SET status = 'issued', session_id = ?
156
- WHERE id = ? AND status = 'approved' RETURNING id`,
157
- [sessionId, id],
158
- )
163
+ const rows = await this.#db.q
164
+ .updateTable('device_authorization')
165
+ .set({ status: 'issued', session_id: sessionId })
166
+ .where('id', '=', id)
167
+ .where('status', '=', 'approved')
168
+ .returning('id')
169
+ .execute()
159
170
  return rows.length > 0
160
171
  }
161
172
 
162
173
  /** The devices signed in as this user, whose sessions are still open. */
163
174
  async signedIn(userId: number): Promise<SignedInDevice[]> {
164
- const rows = await this.#db.query<Record<string, unknown>>(
165
- `SELECT d.id, d.client_name, s.logged_in_utc, s.last_validated_utc
166
- FROM device_authorization d JOIN user_login_session s ON s.session_id = d.session_id
167
- WHERE d.user_id = ? AND d.status = 'issued' AND s.logged_out_utc IS NULL
168
- ORDER BY s.logged_in_utc DESC`,
169
- [userId],
170
- )
175
+ const rows = await this.#db.q
176
+ .selectFrom('device_authorization as d')
177
+ .innerJoin('user_login_session as s', 's.session_id', 'd.session_id')
178
+ .select(['d.id', 'd.client_name', 's.logged_in_utc', 's.last_validated_utc'])
179
+ .where('d.user_id', '=', userId)
180
+ .where('d.status', '=', 'issued')
181
+ .where('s.logged_out_utc', 'is', null)
182
+ .orderBy('s.logged_in_utc', 'desc')
183
+ .execute()
171
184
  return rows.map((row) => ({
172
185
  id: Number(row.id),
173
186
  clientName: row.client_name === null ? null : String(row.client_name),
@@ -177,7 +190,11 @@ export class DeviceStore {
177
190
  }
178
191
 
179
192
  async byId(id: number): Promise<DeviceAuthorizationRow | undefined> {
180
- const rows = await this.#db.query('SELECT * FROM device_authorization WHERE id = ?', [id])
181
- return rows[0] ? mapRow(rows[0]) : undefined
193
+ const row = await this.#db.q
194
+ .selectFrom('device_authorization')
195
+ .selectAll()
196
+ .where('id', '=', id)
197
+ .executeTakeFirst()
198
+ return row ? mapRow(row) : undefined
182
199
  }
183
200
  }
package/src/store.ts CHANGED
@@ -84,8 +84,21 @@ function mapUser(row: Record<string, unknown>): UserRow {
84
84
  }
85
85
  }
86
86
 
87
- const USER_COLUMNS =
88
- 'id, key, user_name, login, email, password_hash, password_config, language, avatar, is_locked_out, is_approved, failed_login_attempts, kind'
87
+ const USER_COLUMNS = [
88
+ 'id',
89
+ 'key',
90
+ 'user_name',
91
+ 'login',
92
+ 'email',
93
+ 'password_hash',
94
+ 'password_config',
95
+ 'language',
96
+ 'avatar',
97
+ 'is_locked_out',
98
+ 'is_approved',
99
+ 'failed_login_attempts',
100
+ 'kind',
101
+ ] as const
89
102
 
90
103
  export class AuthStore {
91
104
  #db: Db
@@ -99,62 +112,80 @@ export class AuthStore {
99
112
 
100
113
  async findUserByLogin(login: string): Promise<UserRow | undefined> {
101
114
  // login is a case-insensitive column in both dialects, so no lower() needed.
102
- const rows = await this.#db.query(`SELECT ${USER_COLUMNS} FROM user_account WHERE login = ?`, [
103
- login,
104
- ])
105
- return rows[0] ? mapUser(rows[0]) : undefined
115
+ const row = await this.#db.q
116
+ .selectFrom('user_account')
117
+ .select(USER_COLUMNS)
118
+ .where('login', '=', login)
119
+ .executeTakeFirst()
120
+ return row ? mapUser(row) : undefined
106
121
  }
107
122
 
108
123
  async findUserById(id: number): Promise<UserRow | undefined> {
109
- const rows = await this.#db.query(`SELECT ${USER_COLUMNS} FROM user_account WHERE id = ?`, [id])
110
- return rows[0] ? mapUser(rows[0]) : undefined
124
+ const row = await this.#db.q
125
+ .selectFrom('user_account')
126
+ .select(USER_COLUMNS)
127
+ .where('id', '=', id)
128
+ .executeTakeFirst()
129
+ return row ? mapUser(row) : undefined
111
130
  }
112
131
 
113
132
  /** An API user's client credential: whose it is, and the secret's hash. */
114
133
  async findClientCredential(
115
134
  clientId: string,
116
135
  ): Promise<{ userId: number; secretHash: string } | undefined> {
117
- const rows = await this.#db.query<{ user_id: number; secret_hash: string }>(
118
- 'SELECT user_id, secret_hash FROM user_client_credential WHERE client_id = ?',
119
- [clientId],
120
- )
121
- return rows[0]
122
- ? { userId: Number(rows[0].user_id), secretHash: String(rows[0].secret_hash) }
123
- : undefined
136
+ const row = await this.#db.q
137
+ .selectFrom('user_client_credential')
138
+ .select(['user_id', 'secret_hash'])
139
+ .where('client_id', '=', clientId)
140
+ .executeTakeFirst()
141
+ return row ? { userId: Number(row.user_id), secretHash: String(row.secret_hash) } : undefined
124
142
  }
125
143
 
126
144
  async recordLoginSuccess(userId: number, sessionId: string, ipAddress?: string): Promise<void> {
127
145
  const now = DbDate.toDb(new Date())
128
- await this.#db.exec(
129
- 'UPDATE user_account SET failed_login_attempts = 0, last_login_date = ?, update_date = ? WHERE id = ?',
130
- [now, now, userId],
131
- )
132
- await this.#db.exec(
133
- `INSERT INTO user_login_session (session_id, user_id, logged_in_utc, last_validated_utc, ip_address)
134
- VALUES (?, ?, ?, ?, ?)`,
135
- [sessionId, userId, now, now, ipAddress ?? null],
136
- )
146
+ await this.#db.q
147
+ .updateTable('user_account')
148
+ .set({ failed_login_attempts: 0, last_login_date: now, update_date: now })
149
+ .where('id', '=', userId)
150
+ .execute()
151
+ await this.#db.q
152
+ .insertInto('user_login_session')
153
+ .values({
154
+ session_id: sessionId,
155
+ user_id: userId,
156
+ logged_in_utc: now,
157
+ last_validated_utc: now,
158
+ ip_address: ipAddress ?? null,
159
+ })
160
+ .execute()
137
161
  }
138
162
 
139
163
  async recordLoginFailure(userId: number): Promise<number> {
140
- const rows = await this.#db.query<{ failed_login_attempts: number }>(
141
- 'SELECT failed_login_attempts FROM user_account WHERE id = ?',
142
- [userId],
143
- )
144
- const attempts = Number(rows[0]?.failed_login_attempts ?? 0) + 1
145
- await this.#db.exec(
146
- 'UPDATE user_account SET failed_login_attempts = ?, update_date = ? WHERE id = ?',
147
- [attempts, DbDate.toDb(new Date()), userId],
148
- )
164
+ const row = await this.#db.q
165
+ .selectFrom('user_account')
166
+ .select('failed_login_attempts')
167
+ .where('id', '=', userId)
168
+ .executeTakeFirst()
169
+ const attempts = Number(row?.failed_login_attempts ?? 0) + 1
170
+ await this.#db.q
171
+ .updateTable('user_account')
172
+ .set({ failed_login_attempts: attempts, update_date: DbDate.toDb(new Date()) })
173
+ .where('id', '=', userId)
174
+ .execute()
149
175
  return attempts
150
176
  }
151
177
 
152
178
  async lockOut(userId: number): Promise<void> {
153
179
  const now = DbDate.toDb(new Date())
154
- await this.#db.exec(
155
- 'UPDATE user_account SET is_locked_out = ?, last_lockout_date = ?, update_date = ? WHERE id = ?',
156
- [this.#db.dialect.boolValue(true), now, now, userId],
157
- )
180
+ await this.#db.q
181
+ .updateTable('user_account')
182
+ .set({
183
+ is_locked_out: this.#db.dialect.boolValue(true) as boolean | number,
184
+ last_lockout_date: now,
185
+ update_date: now,
186
+ })
187
+ .where('id', '=', userId)
188
+ .execute()
158
189
  }
159
190
 
160
191
  /**
@@ -170,85 +201,97 @@ export class AuthStore {
170
201
  passwordHash: string,
171
202
  passwordConfig: string,
172
203
  ): Promise<void> {
173
- await this.#db.exec(
174
- 'UPDATE user_account SET password_hash = ?, password_config = ? WHERE id = ?',
175
- [passwordHash, passwordConfig, userId],
176
- )
204
+ await this.#db.q
205
+ .updateTable('user_account')
206
+ .set({ password_hash: passwordHash, password_config: passwordConfig })
207
+ .where('id', '=', userId)
208
+ .execute()
177
209
  }
178
210
 
179
211
  async setPassword(userId: number, passwordHash: string, passwordConfig: string): Promise<void> {
180
212
  const now = DbDate.toDb(new Date())
181
- await this.#db.exec(
182
- `UPDATE user_account
183
- SET password_hash = ?, password_config = ?, security_stamp = ?,
184
- last_password_change_date = ?, failed_login_attempts = 0, update_date = ?
185
- WHERE id = ?`,
186
- [passwordHash, passwordConfig, crypto.randomUUID(), now, now, userId],
187
- )
213
+ await this.#db.q
214
+ .updateTable('user_account')
215
+ .set({
216
+ password_hash: passwordHash,
217
+ password_config: passwordConfig,
218
+ security_stamp: crypto.randomUUID(),
219
+ last_password_change_date: now,
220
+ failed_login_attempts: 0,
221
+ update_date: now,
222
+ })
223
+ .where('id', '=', userId)
224
+ .execute()
188
225
  }
189
226
 
190
227
  /** Ends every session a user holds, so a password change logs them out. */
191
228
  async endAllSessionsForUser(userId: number): Promise<number> {
192
- const sessions = await this.#db.query<{ session_id: string }>(
193
- 'SELECT session_id FROM user_login_session WHERE user_id = ? AND logged_out_utc IS NULL',
194
- [userId],
195
- )
229
+ const sessions = await this.#db.q
230
+ .selectFrom('user_login_session')
231
+ .select('session_id')
232
+ .where('user_id', '=', userId)
233
+ .where('logged_out_utc', 'is', null)
234
+ .execute()
196
235
  for (const session of sessions) await this.endSession(String(session.session_id))
197
236
  return sessions.length
198
237
  }
199
238
 
200
239
  /** Clears a lockout without touching the password. */
201
240
  async enable(userId: number): Promise<void> {
202
- await this.#db.exec(
203
- 'UPDATE user_account SET is_locked_out = ?, is_approved = ?, failed_login_attempts = 0, update_date = ? WHERE id = ?',
204
- [
205
- this.#db.dialect.boolValue(false),
206
- this.#db.dialect.boolValue(true),
207
- DbDate.toDb(new Date()),
208
- userId,
209
- ],
210
- )
241
+ await this.#db.q
242
+ .updateTable('user_account')
243
+ .set({
244
+ is_locked_out: this.#db.dialect.boolValue(false) as boolean | number,
245
+ is_approved: this.#db.dialect.boolValue(true) as boolean | number,
246
+ failed_login_attempts: 0,
247
+ update_date: DbDate.toDb(new Date()),
248
+ })
249
+ .where('id', '=', userId)
250
+ .execute()
211
251
  }
212
252
 
213
253
  async findSession(sessionId: string): Promise<{ userId: number } | undefined> {
214
- const rows = await this.#db.query<{ user_id: number }>(
215
- 'SELECT user_id FROM user_login_session WHERE session_id = ? AND logged_out_utc IS NULL',
216
- [sessionId],
217
- )
218
- return rows[0] ? { userId: Number(rows[0].user_id) } : undefined
254
+ const row = await this.#db.q
255
+ .selectFrom('user_login_session')
256
+ .select('user_id')
257
+ .where('session_id', '=', sessionId)
258
+ .where('logged_out_utc', 'is', null)
259
+ .executeTakeFirst()
260
+ return row ? { userId: Number(row.user_id) } : undefined
219
261
  }
220
262
 
221
263
  async endSession(sessionId: string): Promise<void> {
222
264
  const now = DbDate.toDb(new Date())
223
- await this.#db.exec(
224
- 'UPDATE user_login_session SET logged_out_utc = ? WHERE session_id = ? AND logged_out_utc IS NULL',
225
- [now, sessionId],
226
- )
227
- await this.#db.exec(
228
- 'UPDATE auth_token SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL',
229
- [now, sessionId],
230
- )
265
+ await this.#db.q
266
+ .updateTable('user_login_session')
267
+ .set({ logged_out_utc: now })
268
+ .where('session_id', '=', sessionId)
269
+ .where('logged_out_utc', 'is', null)
270
+ .execute()
271
+ await this.#db.q
272
+ .updateTable('auth_token')
273
+ .set({ revoked_at: now })
274
+ .where('session_id', '=', sessionId)
275
+ .where('revoked_at', 'is', null)
276
+ .execute()
231
277
  }
232
278
 
233
279
  async createAuthorizationCode(init: AuthorizationCodeInit): Promise<void> {
234
- await this.#db.exec(
235
- `INSERT INTO auth_code
236
- (code_hash, user_id, session_id, client_id, redirect_uri, code_challenge,
237
- code_challenge_method, scope, expires_at, create_date)
238
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
239
- [
240
- hashToken(init.code),
241
- init.userId,
242
- init.sessionId,
243
- init.clientId,
244
- init.redirectUri,
245
- init.codeChallenge,
246
- init.codeChallengeMethod,
247
- init.scope,
248
- DbDate.toDb(init.expiresAt),
249
- DbDate.toDb(new Date()),
250
- ],
251
- )
280
+ await this.#db.q
281
+ .insertInto('auth_code')
282
+ .values({
283
+ code_hash: hashToken(init.code),
284
+ user_id: init.userId,
285
+ session_id: init.sessionId,
286
+ client_id: init.clientId,
287
+ redirect_uri: init.redirectUri,
288
+ code_challenge: init.codeChallenge,
289
+ code_challenge_method: init.codeChallengeMethod,
290
+ scope: init.scope,
291
+ expires_at: DbDate.toDb(init.expiresAt),
292
+ create_date: DbDate.toDb(new Date()),
293
+ })
294
+ .execute()
252
295
  }
253
296
 
254
297
  /**
@@ -258,18 +301,27 @@ export class AuthStore {
258
301
  async consumeAuthorizationCode(code: string): Promise<AuthorizationCodeRow | undefined> {
259
302
  return this.#db.locks.withLock(Locks.KeyValues, async () => {
260
303
  const hash = hashToken(code)
261
- const rows = await this.#db.query(
262
- `SELECT user_id, session_id, client_id, redirect_uri, code_challenge,
263
- code_challenge_method, scope, expires_at, consumed_at
264
- FROM auth_code WHERE code_hash = ?`,
265
- [hash],
266
- )
267
- const row = rows[0]
304
+ const row = await this.#db.q
305
+ .selectFrom('auth_code')
306
+ .select([
307
+ 'user_id',
308
+ 'session_id',
309
+ 'client_id',
310
+ 'redirect_uri',
311
+ 'code_challenge',
312
+ 'code_challenge_method',
313
+ 'scope',
314
+ 'expires_at',
315
+ 'consumed_at',
316
+ ])
317
+ .where('code_hash', '=', hash)
318
+ .executeTakeFirst()
268
319
  if (!row) return undefined
269
- await this.#db.exec('UPDATE auth_code SET consumed_at = ? WHERE code_hash = ?', [
270
- DbDate.toDb(new Date()),
271
- hash,
272
- ])
320
+ await this.#db.q
321
+ .updateTable('auth_code')
322
+ .set({ consumed_at: DbDate.toDb(new Date()) })
323
+ .where('code_hash', '=', hash)
324
+ .execute()
273
325
  return {
274
326
  userId: Number(row.user_id),
275
327
  sessionId: String(row.session_id),
@@ -285,36 +337,44 @@ export class AuthStore {
285
337
  }
286
338
 
287
339
  async createToken(init: TokenInit): Promise<number> {
288
- await this.#db.exec(
289
- `INSERT INTO auth_token
290
- (token_hash, token_type, user_id, session_id, client_id, scope, expires_at, create_date, parent_id)
291
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
292
- [
293
- hashToken(init.token),
294
- init.type,
295
- init.userId,
296
- init.sessionId,
297
- init.clientId,
298
- init.scope,
299
- DbDate.toDb(init.expiresAt),
300
- DbDate.toDb(new Date()),
301
- init.parentId ?? null,
302
- ],
303
- )
304
- const rows = await this.#db.query<{ id: number }>(
305
- 'SELECT id FROM auth_token WHERE token_hash = ?',
306
- [hashToken(init.token)],
307
- )
308
- return Number(rows[0]?.id ?? 0)
340
+ await this.#db.q
341
+ .insertInto('auth_token')
342
+ .values({
343
+ token_hash: hashToken(init.token),
344
+ token_type: init.type,
345
+ user_id: init.userId,
346
+ session_id: init.sessionId,
347
+ client_id: init.clientId,
348
+ scope: init.scope,
349
+ expires_at: DbDate.toDb(init.expiresAt),
350
+ create_date: DbDate.toDb(new Date()),
351
+ parent_id: init.parentId ?? null,
352
+ })
353
+ .execute()
354
+ const row = await this.#db.q
355
+ .selectFrom('auth_token')
356
+ .select('id')
357
+ .where('token_hash', '=', hashToken(init.token))
358
+ .executeTakeFirst()
359
+ return Number(row?.id ?? 0)
309
360
  }
310
361
 
311
362
  async findToken(token: string, type: TokenType): Promise<TokenRow | undefined> {
312
- const rows = await this.#db.query(
313
- `SELECT id, token_type, user_id, session_id, client_id, scope, expires_at, revoked_at
314
- FROM auth_token WHERE token_hash = ? AND token_type = ?`,
315
- [hashToken(token), type],
316
- )
317
- const row = rows[0]
363
+ const row = await this.#db.q
364
+ .selectFrom('auth_token')
365
+ .select([
366
+ 'id',
367
+ 'token_type',
368
+ 'user_id',
369
+ 'session_id',
370
+ 'client_id',
371
+ 'scope',
372
+ 'expires_at',
373
+ 'revoked_at',
374
+ ])
375
+ .where('token_hash', '=', hashToken(token))
376
+ .where('token_type', '=', type)
377
+ .executeTakeFirst()
318
378
  if (!row) return undefined
319
379
  return {
320
380
  id: Number(row.id),
@@ -329,17 +389,19 @@ export class AuthStore {
329
389
  }
330
390
 
331
391
  async revokeToken(id: number): Promise<void> {
332
- await this.#db.exec(
333
- 'UPDATE auth_token SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',
334
- [DbDate.toDb(new Date()), id],
335
- )
392
+ await this.#db.q
393
+ .updateTable('auth_token')
394
+ .set({ revoked_at: DbDate.toDb(new Date()) })
395
+ .where('id', '=', id)
396
+ .where('revoked_at', 'is', null)
397
+ .execute()
336
398
  }
337
399
 
338
400
  /** Removes expired codes and tokens; called by the background job. */
339
401
  async pruneExpired(now = new Date()): Promise<void> {
340
402
  const cutoff = DbDate.toDb(now)
341
- await this.#db.exec('DELETE FROM auth_code WHERE expires_at < ?', [cutoff])
342
- await this.#db.exec('DELETE FROM auth_token WHERE expires_at < ?', [cutoff])
403
+ await this.#db.q.deleteFrom('auth_code').where('expires_at', '<', cutoff).execute()
404
+ await this.#db.q.deleteFrom('auth_token').where('expires_at', '<', cutoff).execute()
343
405
  }
344
406
 
345
407
  /** Section aliases and admin membership, unioned across the user's groups. */
@@ -351,13 +413,12 @@ export class AuthStore {
351
413
  permissions: string[]
352
414
  granular: Array<{ nodeKey: string; permission: string; context: string }>
353
415
  }> {
354
- const groups = await this.#db.query(
355
- `SELECT g.id, g.key, g.alias, g.has_access_to_all_languages
356
- FROM user_group g
357
- JOIN user_group_member m ON m.user_group_id = g.id
358
- WHERE m.user_id = ?`,
359
- [userId],
360
- )
416
+ const groups = await this.#db.q
417
+ .selectFrom('user_group as g')
418
+ .innerJoin('user_group_member as m', 'm.user_group_id', 'g.id')
419
+ .select(['g.id', 'g.key', 'g.alias', 'g.has_access_to_all_languages'])
420
+ .where('m.user_id', '=', userId)
421
+ .execute()
361
422
  const groupKeys = groups.map((g) => String(g.key))
362
423
  const isAdmin = groups.some((g) => String(g.alias) === 'admin')
363
424
  const hasAccessToAllLanguages = groups.some((g) => fromDbBool(g.has_access_to_all_languages))
@@ -373,29 +434,29 @@ export class AuthStore {
373
434
  }
374
435
  }
375
436
 
376
- const sections = await this.#db.query<{ app_alias: string }>(
377
- `SELECT DISTINCT s.app_alias
378
- FROM user_group_section s
379
- JOIN user_group_member m ON m.user_group_id = s.user_group_id
380
- WHERE m.user_id = ?`,
381
- [userId],
382
- )
383
- const permissions = await this.#db.query<{ permission: string }>(
384
- `SELECT DISTINCT p.permission
385
- FROM user_group_permission p
386
- JOIN user_group g ON g.key = p.user_group_key
387
- JOIN user_group_member m ON m.user_group_id = g.id
388
- WHERE m.user_id = ?`,
389
- [userId],
390
- )
391
- const granular = await this.#db.query(
392
- `SELECT gp.unique_id, gp.permission, gp.context
393
- FROM user_group_granular_permission gp
394
- JOIN user_group g ON g.key = gp.user_group_key
395
- JOIN user_group_member m ON m.user_group_id = g.id
396
- WHERE m.user_id = ? AND gp.unique_id IS NOT NULL`,
397
- [userId],
398
- )
437
+ const sections = await this.#db.q
438
+ .selectFrom('user_group_section as s')
439
+ .innerJoin('user_group_member as m', 'm.user_group_id', 's.user_group_id')
440
+ .select('s.app_alias')
441
+ .distinct()
442
+ .where('m.user_id', '=', userId)
443
+ .execute()
444
+ const permissions = await this.#db.q
445
+ .selectFrom('user_group_permission as p')
446
+ .innerJoin('user_group as g', 'g.key', 'p.user_group_key')
447
+ .innerJoin('user_group_member as m', 'm.user_group_id', 'g.id')
448
+ .select('p.permission')
449
+ .distinct()
450
+ .where('m.user_id', '=', userId)
451
+ .execute()
452
+ const granular = await this.#db.q
453
+ .selectFrom('user_group_granular_permission as gp')
454
+ .innerJoin('user_group as g', 'g.key', 'gp.user_group_key')
455
+ .innerJoin('user_group_member as m', 'm.user_group_id', 'g.id')
456
+ .select(['gp.unique_id', 'gp.permission', 'gp.context'])
457
+ .where('m.user_id', '=', userId)
458
+ .where('gp.unique_id', 'is not', null)
459
+ .execute()
399
460
 
400
461
  return {
401
462
  appAliases: sections.map((s) => String(s.app_alias)),