@crombolo/data 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/data",
3
- "version": "0.66.0",
3
+ "version": "0.68.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.68.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/audit.ts CHANGED
@@ -51,9 +51,17 @@ export interface AuditEntryInput {
51
51
  ipAddress?: string | null
52
52
  forwardedFor?: string | null
53
53
  detail?: string | null
54
+ /** Who acted for the user: the host's tool an exchanged token names (story 366). */
55
+ actor?: AuditActor | null
54
56
  occurredAt?: Date
55
57
  }
56
58
 
59
+ /** The tool acting for a person, by the id its token gave and the name the site knows it by. */
60
+ export interface AuditActor {
61
+ id: string
62
+ name: string | null
63
+ }
64
+
57
65
  export interface AuditEntry {
58
66
  id: number
59
67
  occurredAt: Date
@@ -68,6 +76,7 @@ export interface AuditEntry {
68
76
  ipAddress: string | null
69
77
  forwardedFor: string | null
70
78
  detail: string | null
79
+ actor: AuditActor | null
71
80
  }
72
81
 
73
82
  export interface AuditFilter {
@@ -117,6 +126,7 @@ export function auditRecord(entry: AuditEntry) {
117
126
  ipAddress: entry.ipAddress,
118
127
  forwardedFor: entry.forwardedFor,
119
128
  detail: entry.detail,
129
+ actor: entry.actor,
120
130
  }
121
131
  }
122
132
 
@@ -140,6 +150,7 @@ const LIMITS = {
140
150
  ipAddress: 64,
141
151
  forwardedFor: 255,
142
152
  detail: 4000,
153
+ actor: 255,
143
154
  } as const
144
155
 
145
156
  type Condition = (eb: ExpressionBuilder<CoreTables, 'audit_entry'>) => Expression<SqlBool>
@@ -152,6 +163,11 @@ function clip(value: string | null | undefined, limit: number): string | null {
152
163
  return value.length > limit ? value.slice(0, limit) : value
153
164
  }
154
165
 
166
+ const actorColumns = (actor: AuditActor | null) => ({
167
+ actor_id: clip(actor?.id, LIMITS.actor),
168
+ actor_name: clip(actor?.name, LIMITS.actor),
169
+ })
170
+
155
171
  function text(value: unknown): string | null {
156
172
  return value === null || value === undefined ? null : String(value)
157
173
  }
@@ -171,6 +187,7 @@ function toEntry(row: Record<string, unknown>): AuditEntry {
171
187
  ipAddress: text(row.ip_address),
172
188
  forwardedFor: text(row.forwarded_for),
173
189
  detail: text(row.detail),
190
+ actor: row.actor_id ? { id: String(row.actor_id), name: text(row.actor_name) } : null,
174
191
  }
175
192
  }
176
193
 
@@ -183,6 +200,8 @@ export interface AuditContext {
183
200
  viewing?: { userKey: string; groups: string }
184
201
  /** A person acting through one of their command-line tokens (story 351), by its name. */
185
202
  token?: { userKey: string; name: string }
203
+ /** A person acting through a token exchanged at the remote (story 364), by the provider's name. */
204
+ exchange?: { userKey: string; provider: string; actor?: AuditActor }
186
205
  }
187
206
 
188
207
  const contexts = new AsyncLocalStorage<AuditContext>()
@@ -217,12 +236,30 @@ export function detailInContext(
217
236
  const notes = [
218
237
  context.viewing?.userKey === who ? `while viewing as ${context.viewing.groups}` : undefined,
219
238
  context.token?.userKey === who ? `through the token ${context.token.name}` : undefined,
239
+ context.exchange?.userKey === who
240
+ ? `signed in through ${context.exchange.provider}${byActor(context.exchange.actor)}`
241
+ : undefined,
220
242
  ].filter((note): note is string => note !== undefined)
221
243
  if (notes.length === 0) return entry.detail
222
244
  const note = notes.join(', ')
223
245
  return entry.detail ? `${entry.detail}, ${note}` : `${note[0]?.toUpperCase()}${note.slice(1)}`
224
246
  }
225
247
 
248
+ /** ", by Acme console": who acted for the person, by name or else by id. */
249
+ export const byActor = (actor: AuditActor | null | undefined): string =>
250
+ actor ? `, by ${actor.name ?? actor.id}` : ''
251
+
252
+ /** The actor an entry is written with: its own, or the request's for the same person. */
253
+ function actorInContext(
254
+ entry: Pick<AuditEntryInput, 'userKey' | 'actor'>,
255
+ context = currentAuditContext(),
256
+ ): AuditActor | null {
257
+ if (entry.actor) return entry.actor
258
+ const actor = context?.exchange?.actor
259
+ if (!actor || !entry.userKey || !UUID.test(entry.userKey)) return null
260
+ return context?.exchange?.userKey === normaliseUuid(entry.userKey) ? actor : null
261
+ }
262
+
226
263
  export class AuditLog {
227
264
  #db: Db
228
265
 
@@ -254,6 +291,7 @@ export class AuditLog {
254
291
  ip_address: clip(entry.ipAddress, LIMITS.ipAddress),
255
292
  forwarded_for: clip(entry.forwardedFor, LIMITS.forwardedFor),
256
293
  detail: clip(detailInContext(entry), LIMITS.detail),
294
+ ...actorColumns(actorInContext(entry)),
257
295
  })
258
296
  .execute()
259
297
  }
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'
@@ -89,6 +90,7 @@ export * from './schema/delivery-member-tokens.ts'
89
90
  export * from './schema/diagnostics.ts'
90
91
  export * from './schema/drop-assistant.ts'
91
92
  export * from './schema/elements.ts'
93
+ export * from './schema/exchange-actor.ts'
92
94
  export * from './schema/extension-activity.ts'
93
95
  export * from './schema/extension-settings.ts'
94
96
  export * from './schema/form-library.ts'
@@ -114,6 +116,7 @@ export * from './schema/pruned-permissions.ts'
114
116
  export * from './schema/public-access.ts'
115
117
  export * from './schema/recycle-bin.ts'
116
118
  export * from './schema/remote.ts'
119
+ export * from './schema/remote-exchange.ts'
117
120
  export * from './schema/remote-trust.ts'
118
121
  export * from './schema/rich-text-ui.ts'
119
122
  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
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Migration 080 — the actor an exchanged token names is in the history (story
3
+ * 366). A device signed in by exchange keeps the actor its token named, the
4
+ * host's tool acting for the person, and every audit entry can carry the actor
5
+ * it was written for.
6
+ */
7
+ import type { Db } from '../database.ts'
8
+ import type { Migration } from '../migrations.ts'
9
+ import { sql } from '../query.ts'
10
+ import { STATE_REMOTE_EXCHANGE } from './remote-exchange.ts'
11
+
12
+ export const STATE_EXCHANGE_ACTOR = '{3b8e1f60-0080-4c2d-9a7e-1d4f6b2c0080}'
13
+
14
+ export const exchangeActorMigration: Migration = {
15
+ from: STATE_REMOTE_EXCHANGE,
16
+ to: STATE_EXCHANGE_ACTOR,
17
+ name: 'AddExchangeActor',
18
+ kind: 'expand',
19
+ release: '0.68.0',
20
+ async up(db: Db) {
21
+ const t = db.dialect.types
22
+ for (const table of ['device_authorization', 'audit_entry'] as const) {
23
+ await db.q.schema
24
+ .alterTable(table)
25
+ .addColumn('actor_id', sql.raw(t.varchar(255)))
26
+ .execute()
27
+ await db.q.schema
28
+ .alterTable(table)
29
+ .addColumn('actor_name', sql.raw(t.varchar(255)))
30
+ .execute()
31
+ }
32
+ },
33
+ }
@@ -42,6 +42,7 @@ import { deliveryMemberTokensMigration } from './delivery-member-tokens.ts'
42
42
  import { diagnosticsMigration } from './diagnostics.ts'
43
43
  import { dropAssistantMigration } from './drop-assistant.ts'
44
44
  import { elementsMigration } from './elements.ts'
45
+ import { exchangeActorMigration } from './exchange-actor.ts'
45
46
  import { extensionActivityMigration } from './extension-activity.ts'
46
47
  import { extensionSettingsMigration } from './extension-settings.ts'
47
48
  import { formLibraryMigration } from './form-library.ts'
@@ -69,6 +70,7 @@ import { publicAccessMigration } from './public-access.ts'
69
70
  import { recycleBinMigration } from './recycle-bin.ts'
70
71
  import { redirectsMigration } from './redirects.ts'
71
72
  import { remoteMigration } from './remote.ts'
73
+ import { remoteExchangeMigration } from './remote-exchange.ts'
72
74
  import { remoteTrustMigration } from './remote-trust.ts'
73
75
  import { richTextUiMigration } from './rich-text-ui.ts'
74
76
  import { searchIndexMigration } from './search-index.ts'
@@ -171,4 +173,6 @@ export const cromboloPlan = new MigrationPlan([
171
173
  userStartNodesDroppedMigration,
172
174
  sessionViewAsMigration,
173
175
  cliTokensMigration,
176
+ remoteExchangeMigration,
177
+ exchangeActorMigration,
174
178
  ])
@@ -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
@@ -51,6 +51,8 @@ export interface CoreTables {
51
51
  }
52
52
  audit_entry: {
53
53
  action: string
54
+ actor_id: string | null
55
+ actor_name: string | null
54
56
  category: string
55
57
  detail: string | null
56
58
  entity_key: string | null
@@ -330,6 +332,8 @@ export interface CoreTables {
330
332
  scopes: string
331
333
  }
332
334
  device_authorization: {
335
+ actor_id: string | null
336
+ actor_name: string | null
333
337
  client_id: string
334
338
  client_name: string | null
335
339
  create_date: Timestamp
@@ -410,6 +414,8 @@ export interface CoreTables {
410
414
  external_login: {
411
415
  create_date: Timestamp
412
416
  id: Generated<number>
417
+ identity_issuer: string | null
418
+ identity_value: string | null
413
419
  login_provider: string
414
420
  provider_key: string
415
421
  user_data: string | null
@@ -675,6 +681,12 @@ export interface CoreTables {
675
681
  rule_key: string
676
682
  token_hash: string
677
683
  }
684
+ remote_exchange_id: {
685
+ expires_at: Timestamp
686
+ id: Generated<number>
687
+ issuer: string
688
+ token_id: string
689
+ }
678
690
  remote_job: {
679
691
  create_date: Timestamp
680
692
  decided_at: Timestamp | null