@crombolo/auth 0.66.0 → 0.68.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/auth",
3
- "version": "0.66.0",
3
+ "version": "0.68.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.66.0",
32
- "@crombolo/data": "0.66.0",
31
+ "@crombolo/core": "0.68.0",
32
+ "@crombolo/data": "0.68.0",
33
33
  "jose": "^6.2.12",
34
34
  "uqr": "^0.1.3"
35
35
  }
package/src/device.ts CHANGED
@@ -15,6 +15,18 @@ import { generateToken, hashToken } from './pkce.ts'
15
15
 
16
16
  /** The client id the CLI signs in as. */
17
17
  export const REMOTE_CLIENT_ID = 'crombolo-cli'
18
+
19
+ /**
20
+ * The client a token exchanged through a provider is issued to (story 364),
21
+ * with the provider's id after the colon: what marks its sessions as a machine's.
22
+ */
23
+ export const EXCHANGE_CLIENT_PREFIX = 'crombolo-exchange:'
24
+
25
+ /** The provider an exchanged token came through, when the client is one. */
26
+ export const exchangeProviderOf = (clientId: string): string | undefined =>
27
+ clientId.startsWith(EXCHANGE_CLIENT_PREFIX)
28
+ ? clientId.slice(EXCHANGE_CLIENT_PREFIX.length)
29
+ : undefined
18
30
  export const DEVICE_CODE_SECONDS = 10 * 60
19
31
  export const DEVICE_POLL_SECONDS = 5
20
32
 
@@ -116,6 +128,59 @@ export class DeviceStore {
116
128
  }
117
129
  }
118
130
 
131
+ /**
132
+ * A device signed in already, with no code to approve: a token exchanged
133
+ * through a provider (story 364), listed and signed out like any other.
134
+ */
135
+ async signedInByExchange(init: {
136
+ clientId: string
137
+ clientName: string
138
+ userId: number
139
+ sessionId: string
140
+ expiresAt: Date
141
+ /** The tool the token named as acting for the person (story 366). */
142
+ actor?: { id: string; name: string | null }
143
+ }): Promise<void> {
144
+ const now = new Date()
145
+ for (let attempt = 0; ; attempt++) {
146
+ try {
147
+ await this.#db.q
148
+ .insertInto('device_authorization')
149
+ .values({
150
+ device_code_hash: hashToken(generateToken()),
151
+ user_code: userCode(),
152
+ client_id: init.clientId,
153
+ client_name: init.clientName,
154
+ scope: '',
155
+ status: 'issued',
156
+ user_id: init.userId,
157
+ session_id: init.sessionId,
158
+ actor_id: init.actor?.id ?? null,
159
+ actor_name: init.actor?.name ?? null,
160
+ interval_seconds: DEVICE_POLL_SECONDS,
161
+ expires_at: DbDate.toDb(init.expiresAt),
162
+ decided_at: DbDate.toDb(now),
163
+ create_date: DbDate.toDb(now),
164
+ })
165
+ .execute()
166
+ return
167
+ } catch (error) {
168
+ if (attempt >= 4) throw error
169
+ }
170
+ }
171
+ }
172
+
173
+ /** The actor a device signed in by exchange was made for, by its session. */
174
+ async exchangeActor(sessionId: string): Promise<{ id: string; name: string | null } | undefined> {
175
+ const row = await this.#db.q
176
+ .selectFrom('device_authorization')
177
+ .select(['actor_id', 'actor_name'])
178
+ .where('session_id', '=', sessionId)
179
+ .where('actor_id', 'is not', null)
180
+ .executeTakeFirst()
181
+ return row?.actor_id ? { id: row.actor_id, name: row.actor_name } : undefined
182
+ }
183
+
119
184
  async byDeviceCode(deviceCode: string): Promise<DeviceAuthorizationRow | undefined> {
120
185
  const row = await this.#db.q
121
186
  .selectFrom('device_authorization')
package/src/oidc.ts CHANGED
@@ -17,6 +17,8 @@ export interface OidcClaims {
17
17
  name: string
18
18
  /** Where group or role values come from, for mapping onto groups. */
19
19
  groups?: string
20
+ /** What names the person across tokens for other apps of the provider; `sub` when unset. */
21
+ identity?: string
20
22
  }
21
23
 
22
24
  /** One provider, as a preset describes it. */
@@ -41,6 +43,8 @@ export interface OidcIdentity {
41
43
  name: string | undefined
42
44
  /** The values of the provider's groups claim, when it names one. */
43
45
  groups: string[]
46
+ /** The value of the claim that names the person (story 364): `sub` unless the provider says. */
47
+ identity: string | undefined
44
48
  claims: JWTPayload
45
49
  }
46
50
 
@@ -189,6 +193,7 @@ export class OidcClient {
189
193
  emailVerified: verified === true || verified === 'true',
190
194
  name: stringClaim(claims, this.options.claims.name),
191
195
  groups: listClaim(claims, this.options.claims.groups),
196
+ identity: stringClaim(claims, this.options.claims.identity ?? 'sub'),
192
197
  claims,
193
198
  }
194
199
  }
package/src/service.ts CHANGED
@@ -7,6 +7,8 @@ import {
7
7
  DEVICE_CODE_SECONDS,
8
8
  DEVICE_POLL_SECONDS,
9
9
  type DeviceAuthorizationRow,
10
+ EXCHANGE_CLIENT_PREFIX,
11
+ exchangeProviderOf,
10
12
  type SignedInDevice,
11
13
  } from './device.ts'
12
14
  import { hashPassword, isNativeHash, passwordConfigJson, verifyPassword } from './password.ts'
@@ -99,6 +101,10 @@ export interface ViewingAs {
99
101
  export interface ResolvedIdentity {
100
102
  user: UserRow
101
103
  sessionId: string
104
+ /** The provider a token exchanged through it came by (story 364); never set for a browser's session. */
105
+ exchangedThrough?: string
106
+ /** The tool acting for the person, as the exchanged token named it (story 366). */
107
+ exchangedActor?: { id: string; name: string | null }
102
108
  allowedSections: Array<SectionAlias | ExtensionSectionAlias>
103
109
  groupKeys: string[]
104
110
  isAdmin: boolean
@@ -394,15 +400,21 @@ export class AuthService {
394
400
  if (!user) return undefined
395
401
  const own = await this.#store.loadAuthorization(user.id)
396
402
  const view = session.view
403
+ const provider = exchangeProviderOf(token.clientId)
404
+ const actor = provider ? await this.#store.devices.exchangeActor(token.sessionId) : undefined
405
+ const through = provider
406
+ ? { exchangedThrough: provider, ...(actor ? { exchangedActor: actor } : {}) }
407
+ : {}
397
408
  if (view && view.until.getTime() > now.getTime() && own.isAdmin) {
398
409
  const theirs = await this.#store.loadGroupAuthorization(view.groupKeys)
399
410
  return {
400
411
  ...identityFrom(user, theirs),
401
412
  sessionId: token.sessionId,
402
413
  viewingAs: { groups: groupsOf(theirs), until: view.until },
414
+ ...through,
403
415
  }
404
416
  }
405
- return { ...identityFrom(user, own), sessionId: token.sessionId }
417
+ return { ...identityFrom(user, own), sessionId: token.sessionId, ...through }
406
418
  }
407
419
 
408
420
  /**
@@ -532,6 +544,50 @@ export class AuthService {
532
544
  return { ok: true, grant: await this.#issue(user.id, sessionId, clientId, row.scope), user }
533
545
  }
534
546
 
547
+ /**
548
+ * Signs a user in for a token exchanged through a provider (story 364): the
549
+ * same refusals as any sign-in, then a signed-in device of its own with an
550
+ * access token and no refresh token, so it ends when the token does.
551
+ */
552
+ async signInByExchange(
553
+ login: string,
554
+ provider: { id: string; name: string },
555
+ seconds: number,
556
+ ipAddress?: string,
557
+ actor?: { id: string; name: string | null },
558
+ ): Promise<
559
+ | { status: 'success'; user: UserRow; accessToken: string; expiresIn: number }
560
+ | { status: 'notAllowed'; reason: 'lockedOut' | 'notApproved' | 'unknown' }
561
+ > {
562
+ const user = await this.#store.findUserByLogin(login)
563
+ if (!user) return { status: 'notAllowed', reason: 'unknown' }
564
+ if (user.isLockedOut) return { status: 'notAllowed', reason: 'lockedOut' }
565
+ if (!user.isApproved) return { status: 'notAllowed', reason: 'notApproved' }
566
+ const sessionId = crypto.randomUUID()
567
+ const clientId = `${EXCHANGE_CLIENT_PREFIX}${provider.id}`
568
+ const expiresAt = new Date(Date.now() + seconds * 1000)
569
+ await this.#store.recordLoginSuccess(user.id, sessionId, ipAddress)
570
+ await this.#store.devices.signedInByExchange({
571
+ clientId,
572
+ clientName: `Signed in through ${provider.name}${actor ? `, by ${actor.name ?? actor.id}` : ''}`,
573
+ userId: user.id,
574
+ sessionId,
575
+ expiresAt,
576
+ actor,
577
+ })
578
+ const accessToken = generateToken()
579
+ await this.#store.createToken({
580
+ token: accessToken,
581
+ type: 'access',
582
+ userId: user.id,
583
+ sessionId,
584
+ clientId,
585
+ scope: '',
586
+ expiresAt,
587
+ })
588
+ return { status: 'success', user, accessToken, expiresIn: seconds }
589
+ }
590
+
535
591
  /** The devices signed in as this user. */
536
592
  signedInDevices(userId: number): Promise<SignedInDevice[]> {
537
593
  return this.#store.devices.signedIn(userId)