@crombolo/auth 0.64.0 → 0.66.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/package.json +3 -3
- package/src/cli-tokens.ts +299 -0
- package/src/index.ts +1 -0
- package/src/service.ts +86 -14
- package/src/store.ts +109 -44
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.66.0",
|
|
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.
|
|
32
|
-
"@crombolo/data": "0.
|
|
31
|
+
"@crombolo/core": "0.66.0",
|
|
32
|
+
"@crombolo/data": "0.66.0",
|
|
33
33
|
"jose": "^6.2.12",
|
|
34
34
|
"uqr": "^0.1.3"
|
|
35
35
|
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command-line tokens (story 351): a person's own long-lived credential for a
|
|
3
|
+
* script or a CI job, acting as them with their permissions as they are now.
|
|
4
|
+
* Only a token's hash is kept; the token itself is shown once, when it is made.
|
|
5
|
+
* docs/operations.md, "Command-line tokens".
|
|
6
|
+
*/
|
|
7
|
+
import { CliTokenPermissions, normaliseUuid } from '@crombolo/core'
|
|
8
|
+
import { type Db, DbDate } from '@crombolo/data'
|
|
9
|
+
import { generateToken, hashToken } from './pkce.ts'
|
|
10
|
+
import { AuthStore, type UserRow } from './store.ts'
|
|
11
|
+
|
|
12
|
+
/** What every token starts with, so secret scanners can recognise one. */
|
|
13
|
+
export const CLI_TOKEN_PREFIX = 'crombolo_pat_'
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_CLI_TOKEN_DAYS = 30
|
|
16
|
+
export const DEFAULT_CLI_TOKEN_MAX_DAYS = 90
|
|
17
|
+
const DAY_MS = 86_400_000
|
|
18
|
+
const HOUR_MS = 3_600_000
|
|
19
|
+
|
|
20
|
+
export const isCliToken = (token: string): boolean => token.startsWith(CLI_TOKEN_PREFIX)
|
|
21
|
+
|
|
22
|
+
export interface CliTokenSettings {
|
|
23
|
+
/** `cliTokens`: off, no token is issued and every one is refused. */
|
|
24
|
+
enabled: boolean
|
|
25
|
+
/** `cliTokenMaxDays`: the longest a token may last. */
|
|
26
|
+
maxDays: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CliToken {
|
|
30
|
+
key: string
|
|
31
|
+
userId: number
|
|
32
|
+
name: string
|
|
33
|
+
createdAt: Date
|
|
34
|
+
expiresAt: Date
|
|
35
|
+
lastUsedAt: Date | null
|
|
36
|
+
revokedAt: Date | null
|
|
37
|
+
revokedBy: string | null
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface CliTokenPerson {
|
|
41
|
+
id: number
|
|
42
|
+
key: string
|
|
43
|
+
name: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type CliTokenRefusal =
|
|
47
|
+
| 'unknown'
|
|
48
|
+
| 'expired'
|
|
49
|
+
| 'revoked'
|
|
50
|
+
| 'disabled'
|
|
51
|
+
| 'locked'
|
|
52
|
+
| 'removed'
|
|
53
|
+
| 'not-allowed'
|
|
54
|
+
| 'off'
|
|
55
|
+
|
|
56
|
+
/** Why a token was refused, in a sentence each. */
|
|
57
|
+
export const CLI_TOKEN_REFUSALS: Readonly<Record<CliTokenRefusal, string>> = {
|
|
58
|
+
unknown: 'This site does not know that token.',
|
|
59
|
+
expired: 'That token has expired.',
|
|
60
|
+
revoked: 'That token has been revoked.',
|
|
61
|
+
disabled: "That token's person has been disabled.",
|
|
62
|
+
locked: "That token's person is locked out.",
|
|
63
|
+
removed: "That token's person has been removed from the site.",
|
|
64
|
+
'not-allowed':
|
|
65
|
+
"That token's person is no longer in a group that gives command-line tokens, so it doesn't work for now.",
|
|
66
|
+
off: 'This site does not take command-line tokens.',
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type IssueRefusal = 'off' | 'not-allowed' | 'name' | 'name-taken' | 'days'
|
|
70
|
+
|
|
71
|
+
export type Issued =
|
|
72
|
+
| { ok: true; token: string; issued: CliToken }
|
|
73
|
+
| { ok: false; refused: IssueRefusal; message: string }
|
|
74
|
+
|
|
75
|
+
export type ResolvedCliToken =
|
|
76
|
+
| { ok: true; user: UserRow; token: CliToken; firstUse: boolean }
|
|
77
|
+
| { ok: false; reason: CliTokenRefusal; token?: CliToken }
|
|
78
|
+
|
|
79
|
+
const toToken = (row: {
|
|
80
|
+
key: string
|
|
81
|
+
user_id: number
|
|
82
|
+
name: string
|
|
83
|
+
created_at: unknown
|
|
84
|
+
expires_at: unknown
|
|
85
|
+
last_used_at: unknown
|
|
86
|
+
revoked_at: unknown
|
|
87
|
+
revoked_by: string | null
|
|
88
|
+
}): CliToken => ({
|
|
89
|
+
key: normaliseUuid(String(row.key)),
|
|
90
|
+
userId: Number(row.user_id),
|
|
91
|
+
name: String(row.name),
|
|
92
|
+
createdAt: DbDate.fromDb(row.created_at) ?? new Date(0),
|
|
93
|
+
expiresAt: DbDate.fromDb(row.expires_at) ?? new Date(0),
|
|
94
|
+
lastUsedAt: DbDate.fromDb(row.last_used_at) ?? null,
|
|
95
|
+
revokedAt: DbDate.fromDb(row.revoked_at) ?? null,
|
|
96
|
+
revokedBy: row.revoked_by ?? null,
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
const COLUMNS = [
|
|
100
|
+
'key',
|
|
101
|
+
'user_id',
|
|
102
|
+
'name',
|
|
103
|
+
'created_at',
|
|
104
|
+
'expires_at',
|
|
105
|
+
'last_used_at',
|
|
106
|
+
'revoked_at',
|
|
107
|
+
'revoked_by',
|
|
108
|
+
] as const
|
|
109
|
+
|
|
110
|
+
export class CliTokens {
|
|
111
|
+
#db: Db
|
|
112
|
+
#store: AuthStore
|
|
113
|
+
#settings: CliTokenSettings
|
|
114
|
+
|
|
115
|
+
constructor(db: Db, settings: CliTokenSettings) {
|
|
116
|
+
this.#db = db
|
|
117
|
+
this.#store = new AuthStore(db)
|
|
118
|
+
this.#settings = settings
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
get settings(): CliTokenSettings {
|
|
122
|
+
return this.#settings
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A person by key, e-mail or login, for listing or revoking someone's tokens. */
|
|
126
|
+
async person(who: string): Promise<CliTokenPerson | undefined> {
|
|
127
|
+
const wanted = who.trim().toLowerCase()
|
|
128
|
+
const uuid = /^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/.test(wanted)
|
|
129
|
+
const row = await this.#db.q
|
|
130
|
+
.selectFrom('user_account')
|
|
131
|
+
.select(['id', 'key', 'user_name'])
|
|
132
|
+
.where((eb) =>
|
|
133
|
+
uuid
|
|
134
|
+
? eb('key', '=', normaliseUuid(wanted))
|
|
135
|
+
: eb.or([
|
|
136
|
+
eb(eb.fn('lower', ['email']), '=', wanted),
|
|
137
|
+
eb(eb.fn('lower', ['login']), '=', wanted),
|
|
138
|
+
]),
|
|
139
|
+
)
|
|
140
|
+
.executeTakeFirst()
|
|
141
|
+
return (
|
|
142
|
+
row && {
|
|
143
|
+
id: Number(row.id),
|
|
144
|
+
key: normaliseUuid(String(row.key)),
|
|
145
|
+
name: String(row.user_name),
|
|
146
|
+
}
|
|
147
|
+
)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A token's person, or a stand-in once they have been removed. */
|
|
151
|
+
async ownerOf(token: CliToken): Promise<CliTokenPerson> {
|
|
152
|
+
const row = await this.#db.q
|
|
153
|
+
.selectFrom('user_account')
|
|
154
|
+
.select(['id', 'key', 'user_name'])
|
|
155
|
+
.where('id', '=', token.userId)
|
|
156
|
+
.executeTakeFirst()
|
|
157
|
+
return row
|
|
158
|
+
? { id: Number(row.id), key: normaliseUuid(String(row.key)), name: String(row.user_name) }
|
|
159
|
+
: { id: token.userId, key: '', name: 'a removed user' }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Whether the person's groups give them command-line tokens now. */
|
|
163
|
+
async mayCreate(userId: number): Promise<boolean> {
|
|
164
|
+
const authorization = await this.#store.loadAuthorization(userId)
|
|
165
|
+
return authorization.permissions.includes(CliTokenPermissions.Create)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A new token for the person, returned once: `days` defaults to 30 and is capped by the site. */
|
|
169
|
+
async issue(userId: number, name: string, days?: number, now = new Date()): Promise<Issued> {
|
|
170
|
+
const refuse = (refused: IssueRefusal, message: string): Issued => ({
|
|
171
|
+
ok: false,
|
|
172
|
+
refused,
|
|
173
|
+
message,
|
|
174
|
+
})
|
|
175
|
+
const { enabled, maxDays } = this.#settings
|
|
176
|
+
if (!enabled) return refuse('off', CLI_TOKEN_REFUSALS.off)
|
|
177
|
+
if (!(await this.mayCreate(userId)))
|
|
178
|
+
return refuse(
|
|
179
|
+
'not-allowed',
|
|
180
|
+
"None of your groups gives you command-line tokens, so you can't create one.",
|
|
181
|
+
)
|
|
182
|
+
const trimmed = name.trim()
|
|
183
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing them is the point
|
|
184
|
+
if (trimmed.length === 0 || trimmed.length > 100 || /[\u0000-\u001f]/.test(trimmed))
|
|
185
|
+
return refuse('name', 'Give the token a name of up to 100 characters.')
|
|
186
|
+
const lasting = days ?? Math.min(DEFAULT_CLI_TOKEN_DAYS, maxDays)
|
|
187
|
+
if (!Number.isInteger(lasting) || lasting < 1 || lasting > maxDays)
|
|
188
|
+
return refuse(
|
|
189
|
+
'days',
|
|
190
|
+
`A token lasts from 1 to ${maxDays} day${maxDays === 1 ? '' : 's'} on this site.`,
|
|
191
|
+
)
|
|
192
|
+
if ((await this.byName(userId, trimmed)) !== undefined)
|
|
193
|
+
return refuse('name-taken', `You already have a token called "${trimmed}".`)
|
|
194
|
+
const token = `${CLI_TOKEN_PREFIX}${generateToken(32)}`
|
|
195
|
+
const issued: CliToken = {
|
|
196
|
+
key: crypto.randomUUID(),
|
|
197
|
+
userId,
|
|
198
|
+
name: trimmed,
|
|
199
|
+
createdAt: now,
|
|
200
|
+
expiresAt: new Date(now.getTime() + lasting * DAY_MS),
|
|
201
|
+
lastUsedAt: null,
|
|
202
|
+
revokedAt: null,
|
|
203
|
+
revokedBy: null,
|
|
204
|
+
}
|
|
205
|
+
await this.#db.q
|
|
206
|
+
.insertInto('cli_token')
|
|
207
|
+
.values({
|
|
208
|
+
key: issued.key,
|
|
209
|
+
user_id: userId,
|
|
210
|
+
name: issued.name,
|
|
211
|
+
token_hash: hashToken(token),
|
|
212
|
+
created_at: DbDate.toDb(issued.createdAt),
|
|
213
|
+
expires_at: DbDate.toDb(issued.expiresAt),
|
|
214
|
+
})
|
|
215
|
+
.execute()
|
|
216
|
+
return { ok: true, token, issued }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A person's tokens not yet revoked, or everyone's, newest first. */
|
|
220
|
+
async list(userId?: number): Promise<CliToken[]> {
|
|
221
|
+
let query = this.#db.q
|
|
222
|
+
.selectFrom('cli_token')
|
|
223
|
+
.select(COLUMNS)
|
|
224
|
+
.where('revoked_at', 'is', null)
|
|
225
|
+
.orderBy('created_at', 'desc')
|
|
226
|
+
.orderBy('id', 'desc')
|
|
227
|
+
if (userId !== undefined) query = query.where('user_id', '=', userId)
|
|
228
|
+
return (await query.execute()).map(toToken)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** A person's token by its name, among those not revoked. */
|
|
232
|
+
async byName(userId: number, name: string): Promise<CliToken | undefined> {
|
|
233
|
+
const row = await this.#db.q
|
|
234
|
+
.selectFrom('cli_token')
|
|
235
|
+
.select(COLUMNS)
|
|
236
|
+
.where('user_id', '=', userId)
|
|
237
|
+
.where('name', '=', name.trim())
|
|
238
|
+
.where('revoked_at', 'is', null)
|
|
239
|
+
.executeTakeFirst()
|
|
240
|
+
return row && toToken(row)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async byKey(key: string): Promise<CliToken | undefined> {
|
|
244
|
+
const row = await this.#db.q
|
|
245
|
+
.selectFrom('cli_token')
|
|
246
|
+
.select(COLUMNS)
|
|
247
|
+
.where('key', '=', normaliseUuid(key))
|
|
248
|
+
.executeTakeFirst()
|
|
249
|
+
return row && toToken(row)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Revokes a token, by whom; the token as it was, or undefined when there is none to revoke. */
|
|
253
|
+
async revoke(key: string, byUserKey: string, now = new Date()): Promise<CliToken | undefined> {
|
|
254
|
+
const token = await this.byKey(key)
|
|
255
|
+
if (!token || token.revokedAt) return undefined
|
|
256
|
+
await this.#db.q
|
|
257
|
+
.updateTable('cli_token')
|
|
258
|
+
.set({ revoked_at: DbDate.toDb(now), revoked_by: normaliseUuid(byUserKey) })
|
|
259
|
+
.where('key', '=', token.key)
|
|
260
|
+
.execute()
|
|
261
|
+
return token
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The person a token acts as, or why it may not. Its use is noted at most once
|
|
266
|
+
* an hour; `firstUse` says this is the first, for the audit log.
|
|
267
|
+
*/
|
|
268
|
+
async resolve(token: string, now = new Date()): Promise<ResolvedCliToken> {
|
|
269
|
+
if (!isCliToken(token)) return { ok: false, reason: 'unknown' }
|
|
270
|
+
if (!this.#settings.enabled) return { ok: false, reason: 'off' }
|
|
271
|
+
const row = await this.#db.q
|
|
272
|
+
.selectFrom('cli_token')
|
|
273
|
+
.select(COLUMNS)
|
|
274
|
+
.where('token_hash', '=', hashToken(token))
|
|
275
|
+
.executeTakeFirst()
|
|
276
|
+
if (!row) return { ok: false, reason: 'unknown' }
|
|
277
|
+
const found = toToken(row)
|
|
278
|
+
const refused = (reason: CliTokenRefusal): ResolvedCliToken => ({
|
|
279
|
+
ok: false,
|
|
280
|
+
reason,
|
|
281
|
+
token: found,
|
|
282
|
+
})
|
|
283
|
+
if (found.revokedAt) return refused('revoked')
|
|
284
|
+
if (found.expiresAt.getTime() <= now.getTime()) return refused('expired')
|
|
285
|
+
const user = await this.#store.findUserById(found.userId)
|
|
286
|
+
if (!user) return refused('removed')
|
|
287
|
+
if (!user.isApproved) return refused('disabled')
|
|
288
|
+
if (user.isLockedOut) return refused('locked')
|
|
289
|
+
if (!(await this.mayCreate(user.id))) return refused('not-allowed')
|
|
290
|
+
const firstUse = found.lastUsedAt === null
|
|
291
|
+
if (firstUse || now.getTime() - (found.lastUsedAt?.getTime() ?? 0) >= HOUR_MS)
|
|
292
|
+
await this.#db.q
|
|
293
|
+
.updateTable('cli_token')
|
|
294
|
+
.set({ last_used_at: DbDate.toDb(now) })
|
|
295
|
+
.where('key', '=', found.key)
|
|
296
|
+
.execute()
|
|
297
|
+
return { ok: true, user, token: found, firstUse }
|
|
298
|
+
}
|
|
299
|
+
}
|
package/src/index.ts
CHANGED
package/src/service.ts
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
} from './device.ts'
|
|
12
12
|
import { hashPassword, isNativeHash, passwordConfigJson, verifyPassword } from './password.ts'
|
|
13
13
|
import { type CodeChallengeMethod, generateToken, verifyChallenge } from './pkce.ts'
|
|
14
|
-
import type { AuthStore, UserRow } from './store.ts'
|
|
14
|
+
import type { Authorization, AuthStore, UserRow } from './store.ts'
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* The `client_id` the vendored backoffice sends, which `routes.ts` checks an
|
|
@@ -87,6 +87,15 @@ export type TokenResult =
|
|
|
87
87
|
| { ok: true; grant: TokenGrant }
|
|
88
88
|
| { ok: false; error: TokenError; description: string }
|
|
89
89
|
|
|
90
|
+
/** How long an administrator's session views as groups before it ends by itself (story 314). */
|
|
91
|
+
export const VIEW_AS_MS = 3_600_000
|
|
92
|
+
|
|
93
|
+
/** The groups a session is viewing as, and when that ends. */
|
|
94
|
+
export interface ViewingAs {
|
|
95
|
+
groups: Array<{ key: string; name: string }>
|
|
96
|
+
until: Date
|
|
97
|
+
}
|
|
98
|
+
|
|
90
99
|
export interface ResolvedIdentity {
|
|
91
100
|
user: UserRow
|
|
92
101
|
sessionId: string
|
|
@@ -95,8 +104,28 @@ export interface ResolvedIdentity {
|
|
|
95
104
|
isAdmin: boolean
|
|
96
105
|
hasAccessToAllLanguages: boolean
|
|
97
106
|
permissions: string[]
|
|
107
|
+
/**
|
|
108
|
+
* Set while this session views as groups: everything above is theirs. Only
|
|
109
|
+
* ever set for a user who is an administrator in their own right.
|
|
110
|
+
*/
|
|
111
|
+
viewingAs?: ViewingAs
|
|
98
112
|
}
|
|
99
113
|
|
|
114
|
+
const identityFrom = (
|
|
115
|
+
user: UserRow,
|
|
116
|
+
authorization: Authorization,
|
|
117
|
+
): Omit<ResolvedIdentity, 'sessionId'> => ({
|
|
118
|
+
user,
|
|
119
|
+
allowedSections: toSectionAliases(authorization.appAliases),
|
|
120
|
+
groupKeys: authorization.groupKeys,
|
|
121
|
+
isAdmin: authorization.isAdmin,
|
|
122
|
+
hasAccessToAllLanguages: authorization.hasAccessToAllLanguages,
|
|
123
|
+
permissions: authorization.permissions,
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
const groupsOf = (authorization: Authorization) =>
|
|
127
|
+
authorization.groupKeys.map((key, i) => ({ key, name: authorization.groupNames[i] ?? key }))
|
|
128
|
+
|
|
100
129
|
/**
|
|
101
130
|
* Normalises login timing so a valid username with a wrong password takes the
|
|
102
131
|
* same time as an unknown username. Without this, response time reveals which
|
|
@@ -349,14 +378,31 @@ export class AuthService {
|
|
|
349
378
|
}
|
|
350
379
|
}
|
|
351
380
|
|
|
352
|
-
/**
|
|
353
|
-
|
|
381
|
+
/**
|
|
382
|
+
* Resolves a reference access token to an identity, or undefined. A session
|
|
383
|
+
* viewing as groups (story 314) resolves to theirs until the view ends.
|
|
384
|
+
*/
|
|
385
|
+
async resolveAccessToken(
|
|
386
|
+
accessToken: string,
|
|
387
|
+
now = new Date(),
|
|
388
|
+
): Promise<ResolvedIdentity | undefined> {
|
|
354
389
|
const token = await this.#store.findToken(accessToken, 'access')
|
|
355
|
-
if (!token || token.revokedAt || token.expiresAt.getTime() <
|
|
390
|
+
if (!token || token.revokedAt || token.expiresAt.getTime() < now.getTime()) return undefined
|
|
356
391
|
const session = await this.#store.findSession(token.sessionId)
|
|
357
392
|
if (!session) return undefined
|
|
358
|
-
const
|
|
359
|
-
|
|
393
|
+
const user = await this.#activeUser(token.userId)
|
|
394
|
+
if (!user) return undefined
|
|
395
|
+
const own = await this.#store.loadAuthorization(user.id)
|
|
396
|
+
const view = session.view
|
|
397
|
+
if (view && view.until.getTime() > now.getTime() && own.isAdmin) {
|
|
398
|
+
const theirs = await this.#store.loadGroupAuthorization(view.groupKeys)
|
|
399
|
+
return {
|
|
400
|
+
...identityFrom(user, theirs),
|
|
401
|
+
sessionId: token.sessionId,
|
|
402
|
+
viewingAs: { groups: groupsOf(theirs), until: view.until },
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return { ...identityFrom(user, own), sessionId: token.sessionId }
|
|
360
406
|
}
|
|
361
407
|
|
|
362
408
|
/**
|
|
@@ -365,16 +411,42 @@ export class AuthService {
|
|
|
365
411
|
* are locked out or not approved.
|
|
366
412
|
*/
|
|
367
413
|
async identityOf(userId: number): Promise<Omit<ResolvedIdentity, 'sessionId'> | undefined> {
|
|
414
|
+
const user = await this.#activeUser(userId)
|
|
415
|
+
return user && identityFrom(user, await this.#store.loadAuthorization(user.id))
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async #activeUser(userId: number): Promise<UserRow | undefined> {
|
|
368
419
|
const user = await this.#store.findUserById(userId)
|
|
369
|
-
|
|
370
|
-
|
|
420
|
+
return user && !user.isLockedOut && user.isApproved ? user : undefined
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Turns a session to the given groups' rights for an hour (story 314), for an
|
|
425
|
+
* administrator in their own right only, whatever the session views as now.
|
|
426
|
+
*/
|
|
427
|
+
async startViewing(
|
|
428
|
+
sessionId: string,
|
|
429
|
+
groupKeys: readonly string[],
|
|
430
|
+
now = new Date(),
|
|
431
|
+
): Promise<ViewingAs | 'refused' | 'no-groups'> {
|
|
432
|
+
const session = await this.#store.findSession(sessionId)
|
|
433
|
+
const user = session && (await this.#activeUser(session.userId))
|
|
434
|
+
if (!user || !(await this.#store.loadAuthorization(user.id)).isAdmin) return 'refused'
|
|
435
|
+
const groups = await this.#store.loadGroupAuthorization(groupKeys)
|
|
436
|
+
if (groups.groupKeys.length === 0) return 'no-groups'
|
|
437
|
+
const until = new Date(now.getTime() + VIEW_AS_MS)
|
|
438
|
+
await this.#store.setSessionView(sessionId, { groupKeys: groups.groupKeys, until })
|
|
439
|
+
return { groups: groupsOf(groups), until }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Turns a session back to its user's own rights; answers what it was viewing as, if anything. */
|
|
443
|
+
async stopViewing(sessionId: string, now = new Date()): Promise<ViewingAs | undefined> {
|
|
444
|
+
const view = (await this.#store.findSession(sessionId))?.view
|
|
445
|
+
await this.#store.setSessionView(sessionId, undefined)
|
|
446
|
+
if (!view || view.until.getTime() <= now.getTime()) return undefined
|
|
371
447
|
return {
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
groupKeys: authorization.groupKeys,
|
|
375
|
-
isAdmin: authorization.isAdmin,
|
|
376
|
-
hasAccessToAllLanguages: authorization.hasAccessToAllLanguages,
|
|
377
|
-
permissions: authorization.permissions,
|
|
448
|
+
groups: groupsOf(await this.#store.loadGroupAuthorization(view.groupKeys)),
|
|
449
|
+
until: view.until,
|
|
378
450
|
}
|
|
379
451
|
}
|
|
380
452
|
|
package/src/store.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* Everything bearer-shaped is stored hashed, so a database read cannot yield a
|
|
5
5
|
* usable credential.
|
|
6
6
|
*/
|
|
7
|
+
import { normaliseUuid } from '@crombolo/core'
|
|
7
8
|
import { type Db, DbDate, fromDbBool, Locks } from '@crombolo/data'
|
|
8
9
|
import { DeviceStore } from './device.ts'
|
|
9
10
|
import { hashToken } from './pkce.ts'
|
|
@@ -26,6 +27,48 @@ export interface UserRow {
|
|
|
26
27
|
kind: 'Default' | 'Api'
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
/** A session viewing as user groups (story 314): their keys, and when it ends. */
|
|
31
|
+
export interface SessionView {
|
|
32
|
+
groupKeys: string[]
|
|
33
|
+
until: Date
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SessionRow {
|
|
37
|
+
userId: number
|
|
38
|
+
view?: SessionView
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What a set of groups allows, unioned across them. */
|
|
42
|
+
export interface Authorization {
|
|
43
|
+
appAliases: string[]
|
|
44
|
+
groupKeys: string[]
|
|
45
|
+
groupNames: string[]
|
|
46
|
+
isAdmin: boolean
|
|
47
|
+
hasAccessToAllLanguages: boolean
|
|
48
|
+
permissions: string[]
|
|
49
|
+
granular: Array<{ nodeKey: string; permission: string; context: string }>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const NO_AUTHORIZATION: Authorization = {
|
|
53
|
+
appAliases: [],
|
|
54
|
+
groupKeys: [],
|
|
55
|
+
groupNames: [],
|
|
56
|
+
isAdmin: false,
|
|
57
|
+
hasAccessToAllLanguages: false,
|
|
58
|
+
permissions: [],
|
|
59
|
+
granular: [],
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const parseKeys = (json: string | null): string[] => {
|
|
63
|
+
if (!json) return []
|
|
64
|
+
try {
|
|
65
|
+
const parsed: unknown = JSON.parse(json)
|
|
66
|
+
return Array.isArray(parsed) ? parsed.filter((k): k is string => typeof k === 'string') : []
|
|
67
|
+
} catch {
|
|
68
|
+
return []
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
29
72
|
export interface AuthorizationCodeInit {
|
|
30
73
|
code: string
|
|
31
74
|
userId: number
|
|
@@ -250,14 +293,34 @@ export class AuthStore {
|
|
|
250
293
|
.execute()
|
|
251
294
|
}
|
|
252
295
|
|
|
253
|
-
async findSession(sessionId: string): Promise<
|
|
296
|
+
async findSession(sessionId: string): Promise<SessionRow | undefined> {
|
|
254
297
|
const row = await this.#db.q
|
|
255
298
|
.selectFrom('user_login_session')
|
|
256
|
-
.select('user_id')
|
|
299
|
+
.select(['user_id', 'view_as_groups', 'view_as_until'])
|
|
257
300
|
.where('session_id', '=', sessionId)
|
|
258
301
|
.where('logged_out_utc', 'is', null)
|
|
259
302
|
.executeTakeFirst()
|
|
260
|
-
|
|
303
|
+
if (!row) return undefined
|
|
304
|
+
const until = DbDate.fromDb(row.view_as_until)
|
|
305
|
+
return {
|
|
306
|
+
userId: Number(row.user_id),
|
|
307
|
+
...(row.view_as_groups && until
|
|
308
|
+
? { view: { groupKeys: parseKeys(row.view_as_groups), until } }
|
|
309
|
+
: {}),
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Sets, or with undefined clears, what an open session is viewing as. */
|
|
314
|
+
async setSessionView(sessionId: string, view: SessionView | undefined): Promise<void> {
|
|
315
|
+
await this.#db.q
|
|
316
|
+
.updateTable('user_login_session')
|
|
317
|
+
.set({
|
|
318
|
+
view_as_groups: view ? JSON.stringify(view.groupKeys) : null,
|
|
319
|
+
view_as_until: view ? DbDate.toDb(view.until) : null,
|
|
320
|
+
})
|
|
321
|
+
.where('session_id', '=', sessionId)
|
|
322
|
+
.where('logged_out_utc', 'is', null)
|
|
323
|
+
.execute()
|
|
261
324
|
}
|
|
262
325
|
|
|
263
326
|
async endSession(sessionId: string): Promise<void> {
|
|
@@ -404,65 +467,67 @@ export class AuthStore {
|
|
|
404
467
|
await this.#db.q.deleteFrom('auth_token').where('expires_at', '<', cutoff).execute()
|
|
405
468
|
}
|
|
406
469
|
|
|
407
|
-
/**
|
|
408
|
-
async loadAuthorization(userId: number): Promise<{
|
|
409
|
-
appAliases: string[]
|
|
410
|
-
groupKeys: string[]
|
|
411
|
-
isAdmin: boolean
|
|
412
|
-
hasAccessToAllLanguages: boolean
|
|
413
|
-
permissions: string[]
|
|
414
|
-
granular: Array<{ nodeKey: string; permission: string; context: string }>
|
|
415
|
-
}> {
|
|
470
|
+
/** What the user's own groups allow. */
|
|
471
|
+
async loadAuthorization(userId: number): Promise<Authorization> {
|
|
416
472
|
const groups = await this.#db.q
|
|
417
473
|
.selectFrom('user_group as g')
|
|
418
474
|
.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'])
|
|
475
|
+
.select(['g.id', 'g.key', 'g.alias', 'g.name', 'g.has_access_to_all_languages'])
|
|
420
476
|
.where('m.user_id', '=', userId)
|
|
421
477
|
.execute()
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
const hasAccessToAllLanguages = groups.some((g) => fromDbBool(g.has_access_to_all_languages))
|
|
478
|
+
return this.#authorizationOf(groups)
|
|
479
|
+
}
|
|
425
480
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
481
|
+
/** What the groups with these keys allow, as if someone were a member of exactly them. */
|
|
482
|
+
async loadGroupAuthorization(groupKeys: readonly string[]): Promise<Authorization> {
|
|
483
|
+
const keys = groupKeys.filter((k) => /^[0-9a-f-]{32,36}$/i.test(k)).map(normaliseUuid)
|
|
484
|
+
if (keys.length === 0) return NO_AUTHORIZATION
|
|
485
|
+
const groups = await this.#db.q
|
|
486
|
+
.selectFrom('user_group as g')
|
|
487
|
+
.select(['g.id', 'g.key', 'g.alias', 'g.name', 'g.has_access_to_all_languages'])
|
|
488
|
+
.where('g.key', 'in', keys)
|
|
489
|
+
.orderBy('g.name')
|
|
490
|
+
.execute()
|
|
491
|
+
return this.#authorizationOf(groups)
|
|
492
|
+
}
|
|
436
493
|
|
|
494
|
+
async #authorizationOf(
|
|
495
|
+
groups: Array<{
|
|
496
|
+
id: number
|
|
497
|
+
key: string
|
|
498
|
+
alias: string
|
|
499
|
+
name: string | null
|
|
500
|
+
has_access_to_all_languages: unknown
|
|
501
|
+
}>,
|
|
502
|
+
): Promise<Authorization> {
|
|
503
|
+
if (groups.length === 0) return NO_AUTHORIZATION
|
|
504
|
+
const ids = groups.map((g) => Number(g.id))
|
|
505
|
+
const keys = groups.map((g) => String(g.key))
|
|
437
506
|
const sections = await this.#db.q
|
|
438
|
-
.selectFrom('user_group_section
|
|
439
|
-
.
|
|
440
|
-
.select('s.app_alias')
|
|
507
|
+
.selectFrom('user_group_section')
|
|
508
|
+
.select('app_alias')
|
|
441
509
|
.distinct()
|
|
442
|
-
.where('
|
|
510
|
+
.where('user_group_id', 'in', ids)
|
|
443
511
|
.execute()
|
|
444
512
|
const permissions = await this.#db.q
|
|
445
|
-
.selectFrom('user_group_permission
|
|
446
|
-
.
|
|
447
|
-
.innerJoin('user_group_member as m', 'm.user_group_id', 'g.id')
|
|
448
|
-
.select('p.permission')
|
|
513
|
+
.selectFrom('user_group_permission')
|
|
514
|
+
.select('permission')
|
|
449
515
|
.distinct()
|
|
450
|
-
.where('
|
|
516
|
+
.where('user_group_key', 'in', keys)
|
|
451
517
|
.execute()
|
|
452
518
|
const granular = await this.#db.q
|
|
453
|
-
.selectFrom('user_group_granular_permission
|
|
454
|
-
.
|
|
455
|
-
.
|
|
456
|
-
.
|
|
457
|
-
.where('m.user_id', '=', userId)
|
|
458
|
-
.where('gp.unique_id', 'is not', null)
|
|
519
|
+
.selectFrom('user_group_granular_permission')
|
|
520
|
+
.select(['unique_id', 'permission', 'context'])
|
|
521
|
+
.where('user_group_key', 'in', keys)
|
|
522
|
+
.where('unique_id', 'is not', null)
|
|
459
523
|
.execute()
|
|
460
524
|
|
|
461
525
|
return {
|
|
462
526
|
appAliases: sections.map((s) => String(s.app_alias)),
|
|
463
|
-
groupKeys,
|
|
464
|
-
|
|
465
|
-
|
|
527
|
+
groupKeys: keys,
|
|
528
|
+
groupNames: groups.map((g) => String(g.name ?? g.alias)),
|
|
529
|
+
isAdmin: groups.some((g) => String(g.alias) === 'admin'),
|
|
530
|
+
hasAccessToAllLanguages: groups.some((g) => fromDbBool(g.has_access_to_all_languages)),
|
|
466
531
|
permissions: permissions.map((p) => String(p.permission)),
|
|
467
532
|
granular: granular.map((g) => ({
|
|
468
533
|
nodeKey: String(g.unique_id),
|