@crombolo/data 0.66.0 → 0.67.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/data",
3
- "version": "0.66.0",
3
+ "version": "0.67.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.66.0",
32
+ "@crombolo/core": "0.67.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/audit.ts CHANGED
@@ -183,6 +183,8 @@ export interface AuditContext {
183
183
  viewing?: { userKey: string; groups: string }
184
184
  /** A person acting through one of their command-line tokens (story 351), by its name. */
185
185
  token?: { userKey: string; name: string }
186
+ /** A person acting through a token exchanged at the remote (story 364), by the provider's name. */
187
+ exchange?: { userKey: string; provider: string }
186
188
  }
187
189
 
188
190
  const contexts = new AsyncLocalStorage<AuditContext>()
@@ -217,6 +219,9 @@ export function detailInContext(
217
219
  const notes = [
218
220
  context.viewing?.userKey === who ? `while viewing as ${context.viewing.groups}` : undefined,
219
221
  context.token?.userKey === who ? `through the token ${context.token.name}` : undefined,
222
+ context.exchange?.userKey === who
223
+ ? `signed in through ${context.exchange.provider}`
224
+ : undefined,
220
225
  ].filter((note): note is string => note !== undefined)
221
226
  if (notes.length === 0) return entry.detail
222
227
  const note = notes.join(', ')
package/src/index.ts CHANGED
@@ -47,6 +47,7 @@ export * from './repositories/notifications.ts'
47
47
  export * from './repositories/public-access.ts'
48
48
  export * from './repositories/redirects.ts'
49
49
  export * from './repositories/references.ts'
50
+ export * from './repositories/remote-exchange-ids.ts'
50
51
  export * from './repositories/remote-jobs.ts'
51
52
  export * from './repositories/remote-trust.ts'
52
53
  export * from './repositories/tags.ts'
@@ -114,6 +115,7 @@ export * from './schema/pruned-permissions.ts'
114
115
  export * from './schema/public-access.ts'
115
116
  export * from './schema/recycle-bin.ts'
116
117
  export * from './schema/remote.ts'
118
+ export * from './schema/remote-exchange.ts'
117
119
  export * from './schema/remote-trust.ts'
118
120
  export * from './schema/rich-text-ui.ts'
119
121
  export * from './schema/search-index.ts'
@@ -22,13 +22,27 @@ export interface ExternalLogin {
22
22
  loginProvider: string
23
23
  /** The provider's id for the account: its `sub`. */
24
24
  providerKey: string
25
+ /**
26
+ * What names the person across the provider's apps (`oid` for Entra), and
27
+ * the issuer it came from (story 364): set at each sign-in since 0.67.0.
28
+ */
29
+ identity: ProviderIdentity | undefined
25
30
  createDate: Date
26
31
  }
27
32
 
33
+ export interface ProviderIdentity {
34
+ value: string
35
+ issuer: string
36
+ }
37
+
28
38
  const toLogin = (row: Record<string, unknown>): ExternalLogin => ({
29
39
  ownerKey: normaliseUuid(String(row.user_or_member_key)),
30
40
  loginProvider: String(row.login_provider),
31
41
  providerKey: String(row.provider_key),
42
+ identity:
43
+ typeof row.identity_value === 'string' && typeof row.identity_issuer === 'string'
44
+ ? { value: row.identity_value, issuer: row.identity_issuer }
45
+ : undefined,
32
46
  createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
33
47
  })
34
48
 
@@ -50,6 +64,35 @@ export class ExternalLoginRepository {
50
64
  return row ? toLogin(row) : undefined
51
65
  }
52
66
 
67
+ /** Who the person a provider's identifying claim names is linked to, from that issuer only. */
68
+ async findByIdentity(
69
+ loginProvider: string,
70
+ identity: ProviderIdentity,
71
+ ): Promise<ExternalLogin | undefined> {
72
+ const row = await this.#db.q
73
+ .selectFrom('external_login')
74
+ .selectAll()
75
+ .where('login_provider', '=', loginProvider)
76
+ .where('identity_value', '=', identity.value)
77
+ .where('identity_issuer', '=', identity.issuer)
78
+ .executeTakeFirst()
79
+ return row ? toLogin(row) : undefined
80
+ }
81
+
82
+ /** Records what names the person at the provider on their link, as a sign-in reads it. */
83
+ async recordIdentity(
84
+ loginProvider: string,
85
+ providerKey: string,
86
+ identity: ProviderIdentity | undefined,
87
+ ): Promise<void> {
88
+ await this.#db.q
89
+ .updateTable('external_login')
90
+ .set({ identity_value: identity?.value ?? null, identity_issuer: identity?.issuer ?? null })
91
+ .where('login_provider', '=', loginProvider)
92
+ .where('provider_key', '=', providerKey)
93
+ .execute()
94
+ }
95
+
53
96
  /** Every provider account linked to a member or user. */
54
97
  async forOwner(ownerKey: string): Promise<ExternalLogin[]> {
55
98
  const rows = await this.#db.q
@@ -62,7 +105,12 @@ export class ExternalLoginRepository {
62
105
  }
63
106
 
64
107
  /** Links a provider account to a member or user, replacing an earlier link to that provider. */
65
- async link(ownerKey: string, loginProvider: string, providerKey: string): Promise<void> {
108
+ async link(
109
+ ownerKey: string,
110
+ loginProvider: string,
111
+ providerKey: string,
112
+ identity?: ProviderIdentity,
113
+ ): Promise<void> {
66
114
  await this.#db.transaction(async (tx) => {
67
115
  await removeLink(tx, ownerKey, loginProvider)
68
116
  await tx.q
@@ -71,6 +119,8 @@ export class ExternalLoginRepository {
71
119
  user_or_member_key: normaliseUuid(ownerKey),
72
120
  login_provider: loginProvider,
73
121
  provider_key: providerKey,
122
+ identity_value: identity?.value ?? null,
123
+ identity_issuer: identity?.issuer ?? null,
74
124
  create_date: DbDate.toDb(new Date()),
75
125
  })
76
126
  .execute()
@@ -25,6 +25,8 @@ import {
25
25
  } from './documents.ts'
26
26
  import { NodeRepository } from './nodes.ts'
27
27
 
28
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
29
+
28
30
  /** The sign-in facet beside a member's content. */
29
31
  export interface MemberIdentity {
30
32
  email: string
@@ -209,6 +211,23 @@ export class MemberRepository {
209
211
  return node ? this.#groupKeysOf(node.id) : []
210
212
  }
211
213
 
214
+ /** Those of `keys` that name no member group. */
215
+ async notGroups(keys: readonly string[]): Promise<string[]> {
216
+ const missing: string[] = []
217
+ for (const key of keys) if (!(await this.#group(key))) missing.push(key)
218
+ return missing
219
+ }
220
+
221
+ /**
222
+ * The member group a key names. Anything not shaped as a key names none, as
223
+ * Postgres's uuid column would refuse it.
224
+ */
225
+ async #group(key: string) {
226
+ if (!UUID.test(key)) return undefined
227
+ const node = await this.#nodes.byKey(key)
228
+ return node?.objectType === ObjectTypes.MemberGroup ? node : undefined
229
+ }
230
+
212
231
  /** Whether a username or an e-mail is taken by anyone other than `exceptKey`. */
213
232
  async taken(field: 'username' | 'email', value: string, exceptKey?: string): Promise<boolean> {
214
233
  const column = field === 'username' ? 'm.login_name' : 'm.email'
@@ -233,8 +252,8 @@ export class MemberRepository {
233
252
  async #writeGroups(nodeId: number, groupKeys: readonly string[]): Promise<void> {
234
253
  await this.#db.q.deleteFrom('member_group_member').where('member_id', '=', nodeId).execute()
235
254
  for (const key of groupKeys) {
236
- const group = await this.#nodes.byKey(key)
237
- if (!group || group.objectType !== ObjectTypes.MemberGroup) continue
255
+ const group = await this.#group(key)
256
+ if (!group) continue
238
257
  await this.#db.q
239
258
  .insertInto('member_group_member')
240
259
  .values({ member_id: nodeId, member_group_id: group.id })
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The one-time ids of tokens a provider issued for the remote's exchange
3
+ * (story 364), each kept until its token expires, so no token is exchanged
4
+ * twice.
5
+ */
6
+ import type { Db } from '../database.ts'
7
+ import { DbDate } from '../dialect.ts'
8
+
9
+ export class RemoteExchangeIds {
10
+ #db: Db
11
+
12
+ constructor(db: Db) {
13
+ this.#db = db
14
+ }
15
+
16
+ /** Spends an id; false when it was spent before. Sweeps the ids whose tokens have expired. */
17
+ async spend(
18
+ issuer: string,
19
+ tokenId: string,
20
+ expiresAt: Date,
21
+ now = new Date(),
22
+ ): Promise<boolean> {
23
+ await this.#db.q
24
+ .deleteFrom('remote_exchange_id')
25
+ .where('expires_at', '<', DbDate.toDb(now))
26
+ .execute()
27
+ const seen = await this.#db.q
28
+ .selectFrom('remote_exchange_id')
29
+ .select('id')
30
+ .where('issuer', '=', issuer)
31
+ .where('token_id', '=', tokenId)
32
+ .executeTakeFirst()
33
+ if (seen) return false
34
+ try {
35
+ await this.#db.q
36
+ .insertInto('remote_exchange_id')
37
+ .values({ issuer, token_id: tokenId, expires_at: DbDate.toDb(expiresAt) })
38
+ .execute()
39
+ return true
40
+ } catch {
41
+ // Two exchanges of one token at once: the unique index lets one in.
42
+ return false
43
+ }
44
+ }
45
+ }
@@ -69,6 +69,7 @@ import { publicAccessMigration } from './public-access.ts'
69
69
  import { recycleBinMigration } from './recycle-bin.ts'
70
70
  import { redirectsMigration } from './redirects.ts'
71
71
  import { remoteMigration } from './remote.ts'
72
+ import { remoteExchangeMigration } from './remote-exchange.ts'
72
73
  import { remoteTrustMigration } from './remote-trust.ts'
73
74
  import { richTextUiMigration } from './rich-text-ui.ts'
74
75
  import { searchIndexMigration } from './search-index.ts'
@@ -171,4 +172,5 @@ export const cromboloPlan = new MigrationPlan([
171
172
  userStartNodesDroppedMigration,
172
173
  sessionViewAsMigration,
173
174
  cliTokensMigration,
175
+ remoteExchangeMigration,
174
176
  ])
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Migration 079 — a person signed in through a provider reaches the remote
3
+ * (story 364). `external_login` gains the value of the claim that names the
4
+ * person across the provider's apps (`oid` for Entra) and the issuer it came
5
+ * from, which the exchange finds them by; `remote_exchange_id` keeps each
6
+ * exchanged token's one-time id until the token expires, so none is used twice.
7
+ */
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { sql } from '../query.ts'
11
+ import { STATE_CLI_TOKENS } from './cli-tokens.ts'
12
+
13
+ export const STATE_REMOTE_EXCHANGE = '{7d2a9c4e-0079-4b1f-a3e8-5c6d0f2b0079}'
14
+
15
+ export const remoteExchangeMigration: Migration = {
16
+ from: STATE_CLI_TOKENS,
17
+ to: STATE_REMOTE_EXCHANGE,
18
+ name: 'AddRemoteExchange',
19
+ kind: 'expand',
20
+ release: '0.67.0',
21
+ async up(db: Db) {
22
+ const t = db.dialect.types
23
+ await db.q.schema
24
+ .alterTable('external_login')
25
+ .addColumn('identity_value', sql.raw(t.varchar(255)))
26
+ .execute()
27
+ await db.q.schema
28
+ .alterTable('external_login')
29
+ .addColumn('identity_issuer', sql.raw(t.varchar(255)))
30
+ .execute()
31
+ await db.q.schema
32
+ .createIndex('ix_external_login_identity')
33
+ .on('external_login')
34
+ .columns(['login_provider', 'identity_value'])
35
+ .execute()
36
+ await db.q.schema
37
+ .createTable('remote_exchange_id')
38
+ .addColumn('id', sql.raw(t.identity))
39
+ .addColumn('issuer', sql.raw(t.varchar(255)), (c) => c.notNull())
40
+ .addColumn('token_id', sql.raw(t.varchar(255)), (c) => c.notNull())
41
+ .addColumn('expires_at', sql.raw(t.timestamp), (c) => c.notNull())
42
+ .execute()
43
+ await db.q.schema
44
+ .createIndex('ux_remote_exchange_id')
45
+ .unique()
46
+ .on('remote_exchange_id')
47
+ .columns(['issuer', 'token_id'])
48
+ .execute()
49
+ },
50
+ }
package/src/tables.gen.ts CHANGED
@@ -410,6 +410,8 @@ export interface CoreTables {
410
410
  external_login: {
411
411
  create_date: Timestamp
412
412
  id: Generated<number>
413
+ identity_issuer: string | null
414
+ identity_value: string | null
413
415
  login_provider: string
414
416
  provider_key: string
415
417
  user_data: string | null
@@ -675,6 +677,12 @@ export interface CoreTables {
675
677
  rule_key: string
676
678
  token_hash: string
677
679
  }
680
+ remote_exchange_id: {
681
+ expires_at: Timestamp
682
+ id: Generated<number>
683
+ issuer: string
684
+ token_id: string
685
+ }
678
686
  remote_job: {
679
687
  create_date: Timestamp
680
688
  decided_at: Timestamp | null