@yaks/d1 0.0.0-stage → 0.2.36

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/vault.ts ADDED
@@ -0,0 +1,487 @@
1
+ // A vault of secrets in D1: what yaks.app keeps where a box keeps private
2
+ // files. It meets @yaks/secrets' `Vault` by shape and never imports it, so this
3
+ // package knows nothing of secrets beyond the few fields it stores; the check
4
+ // that the shapes agree is ./vault_test.ts, which hands this vault to the
5
+ // secrets plugin.
6
+ //
7
+ // The table sits in whatever database the caller binds, often the graph's own,
8
+ // so every value is encrypted under a key the caller holds (AES-GCM, the row's
9
+ // own key as associated data, so a row copied under another name does not
10
+ // open). The database, its Time Travel and its exports hold only ciphertext;
11
+ // the key lives wherever the Worker keeps its own secrets.
12
+ //
13
+ // D1 has no interactive transaction, so the lock a read-change-write needs is a
14
+ // lease row: taken by an upsert that only wins over an expired lease, and
15
+ // deleted by its holder. Callers in this isolate wait in a queue first, so the
16
+ // lease row only ever arbitrates between isolates.
17
+ //
18
+
19
+ import {
20
+ among,
21
+ and,
22
+ col,
23
+ type CreateIndex,
24
+ type CreateTable,
25
+ type Delete,
26
+ desc,
27
+ eq,
28
+ exists,
29
+ type Expr,
30
+ type Insert,
31
+ lt,
32
+ ne,
33
+ not,
34
+ or,
35
+ select,
36
+ type Stmt,
37
+ table,
38
+ val,
39
+ } from '@yaks/sql'
40
+ import { type Clock, locks, sleep, system } from '@yaks/fp'
41
+ import { access, type D1Like, type Prepared } from './d1.js'
42
+ import { Expired, retryFor, transient } from './retry.js'
43
+
44
+ /** What a vault keeps for one secret — @yaks/secrets' `Sealed`, by shape. */
45
+ export type Sealed = {
46
+ name?: string
47
+ handle: string
48
+ value?: string
49
+ op?: string
50
+ }
51
+
52
+ /** Metadata of a retained version, without its credential value. */
53
+ export type Trashed = {
54
+ id: string
55
+ eid: string
56
+ handle: string
57
+ name?: string
58
+ at: number
59
+ }
60
+
61
+ /** A vault in D1, answering with promises. */
62
+ export type D1Vault = {
63
+ salt: () => Promise<Uint8Array>
64
+ read: (eid: string) => Promise<Sealed | undefined>
65
+ readMany: (
66
+ eids: readonly string[],
67
+ ) => Promise<Map<string, PromiseSettledResult<Sealed>>>
68
+ seal: (eid: string, sealed: Sealed) => Promise<void>
69
+ drop: (eid: string) => Promise<void>
70
+ trash: () => Promise<Trashed[]>
71
+ past: (id: string) => Promise<Sealed | undefined>
72
+ restore: (id: string) => Promise<boolean>
73
+ purge: (id: string) => Promise<void>
74
+ /** Permanently erase the active secrets and all saved versions of these eids. */
75
+ erase: (eids: string[]) => Promise<void>
76
+ all: () => Promise<[string, Sealed][]>
77
+ lock: <T>(eid: string, fn: () => Promise<T>) => Promise<T>
78
+ }
79
+
80
+ // The salt is a row like any secret, under a name no secret's uuid can be.
81
+ let SALT = 'salt'
82
+ // How long a lease stands if its holder dies holding it, and how long a
83
+ // caller waits for one before giving up.
84
+ let LEASE = 30_000
85
+
86
+ let VAULT = 'yak_vault'
87
+ let LOCK = 'yak_vault_lock'
88
+ let TRASH = 'yak_vault_trash'
89
+ // Erasure keeps only the identity so a seal already on its way cannot
90
+ // recreate the deleted value.
91
+ let ERASED = 'yak_vault_erased'
92
+ let WRITES = 'yak_vault_write'
93
+ // Longer than a resend can be outstanding, including the binding's own wait.
94
+ let KEEP_WRITES = 86_400_000
95
+
96
+ let key = { name: 'k', type: 'text', pk: true }
97
+ let SCHEMA: (CreateTable | CreateIndex)[] = [
98
+ {
99
+ t: 'create table',
100
+ name: VAULT,
101
+ ifNot: true,
102
+ cols: [key, { name: 'v', type: 'text', notNull: true }],
103
+ },
104
+ {
105
+ t: 'create table',
106
+ name: TRASH,
107
+ ifNot: true,
108
+ cols: [key, { name: 'eid', type: 'text', notNull: true }, {
109
+ name: 'at',
110
+ type: 'integer',
111
+ notNull: true,
112
+ }, { name: 'v', type: 'text', notNull: true }],
113
+ },
114
+ {
115
+ t: 'create table',
116
+ name: LOCK,
117
+ ifNot: true,
118
+ cols: [
119
+ key,
120
+ { name: 'holder', type: 'text', notNull: true },
121
+ { name: 'expires', type: 'integer', notNull: true },
122
+ ],
123
+ },
124
+ { t: 'create table', name: ERASED, ifNot: true, cols: [key] },
125
+ {
126
+ t: 'create table',
127
+ name: WRITES,
128
+ ifNot: true,
129
+ cols: [key, { name: 'at', type: 'integer', notNull: true }],
130
+ },
131
+ {
132
+ t: 'create index',
133
+ name: 'yak_vault_write_at',
134
+ on: WRITES,
135
+ ifNot: true,
136
+ cols: [col('at')],
137
+ },
138
+ ]
139
+
140
+ // The lease on `k` for `holder` until `expires`, taken only over one that ran
141
+ // out before `now`; it returns a row when it was taken.
142
+ let take = (k: string, holder: string, expires: number, now: number): Stmt => ({
143
+ t: 'insert',
144
+ into: LOCK,
145
+ cols: ['k', 'holder', 'expires'],
146
+ rows: [[val(k), val(holder), val(expires)]],
147
+ upsert: [{
148
+ on: [col('k')],
149
+ set: {
150
+ holder: col('holder', 'excluded'),
151
+ expires: col('expires', 'excluded'),
152
+ },
153
+ // The same holder and expiry on a resend acknowledge a committed take.
154
+ when: or(
155
+ lt(col('expires', LOCK), val(now)),
156
+ eq(col('holder', LOCK), val(holder)),
157
+ ),
158
+ }],
159
+ returning: [col('holder')],
160
+ })
161
+
162
+ let present = (from: string, k: Expr) =>
163
+ exists(
164
+ select({ cols: [col('k')], from: table(from), where: eq(col('k'), k) }),
165
+ )
166
+
167
+ // A secret's row written, and whether one already there is replaced.
168
+ let put = (k: string, v: string, replace: boolean, fresh?: Expr): Insert => ({
169
+ t: 'insert',
170
+ into: VAULT,
171
+ cols: ['k', 'v'],
172
+ q: select({
173
+ cols: [val(k), val(v)],
174
+ where: fresh
175
+ ? and(fresh, not(present(ERASED, val(k))))
176
+ : not(present(ERASED, val(k))),
177
+ }),
178
+ upsert: [replace ? { on: [col('k')], set: { v: col('v', 'excluded') } } : {}],
179
+ })
180
+
181
+ let get = (k: string): Stmt =>
182
+ select({ cols: [col('v')], from: table(VAULT), where: eq(col('k'), val(k)) })
183
+
184
+ let getMany = (eids: readonly string[]): Stmt =>
185
+ select({
186
+ cols: [col('k'), col('v')],
187
+ from: table(VAULT),
188
+ where: among(col('k'), eids.map(val)),
189
+ })
190
+
191
+ let missingTable = /\bno such table: (?:main\.)?yak_vault(?:_trash)?\b/i
192
+ // D1 accepts at most 100 bound parameters per statement.
193
+ let READ_LIMIT = 100
194
+
195
+ // Keep the existing ciphertext under its original associated entity id. The
196
+ // archive and the change following it commit in the same D1 batch.
197
+ let archived = (eid: string, fresh: Expr): Insert => ({
198
+ t: 'insert',
199
+ into: TRASH,
200
+ cols: ['k', 'eid', 'at', 'v'],
201
+ q: select({
202
+ cols: [val(crypto.randomUUID()), col('k'), val(Date.now()), col('v')],
203
+ from: table(VAULT),
204
+ where: and(fresh, eq(col('k'), val(eid))),
205
+ }),
206
+ })
207
+ let removed = (from: string, id: string, fresh?: Expr): Delete => ({
208
+ t: 'delete',
209
+ from,
210
+ where: fresh ? and(fresh, eq(col('k'), val(id))) : eq(col('k'), val(id)),
211
+ })
212
+
213
+ // Commit a receipt with the change, even when there was nothing to archive.
214
+ // A resend must skip the entire change, including after a different writer
215
+ // has changed or removed the active value in the meantime.
216
+ let writing = (change: (fresh: Expr) => Stmt[]): Stmt[] => {
217
+ let k = val(crypto.randomUUID())
218
+ let now = Date.now()
219
+ return [
220
+ { t: 'delete', from: WRITES, where: lt(col('at'), val(now - KEEP_WRITES)) },
221
+ ...change(not(present(WRITES, k))),
222
+ { t: 'insert', into: WRITES, rows: [[k, val(now)]], upsert: [{}] },
223
+ ]
224
+ }
225
+
226
+ let base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))
227
+ let unbase64 = (text: string) =>
228
+ Uint8Array.from(atob(text), (c) => c.charCodeAt(0))
229
+ let utf8 = new TextEncoder()
230
+
231
+ /**
232
+ * The vault in a D1 database, every value encrypted under `key` (AES-GCM),
233
+ * which may still be on its way — a key imported from a Worker secret is. Its
234
+ * tables are created on first use.
235
+ *
236
+ * ```ts
237
+ * import { d1Vault } from '@yaks/d1'
238
+ *
239
+ * // let vault = d1Vault(env.DB, key)
240
+ * // graph({ storage, vocab, plugins: [secrets(vault, write, vocab)] }) // @yaks/secrets
241
+ * ```
242
+ */
243
+ export let d1Vault = <S extends Prepared<S>>(
244
+ db: D1Like<S>,
245
+ key: CryptoKey | Promise<CryptoKey>,
246
+ clock: Clock = system,
247
+ ): D1Vault => {
248
+ let ready = false
249
+ let io = access(db, undefined, clock)
250
+ // Keep only completed setup. An invocation cancelled during D1's batch
251
+ // can leave its promise pending forever. Concurrent setup uses ifNot.
252
+ // Making the tables is once per isolate, so no caller's deadline bounds it.
253
+ let setup = async () => {
254
+ if (ready) return
255
+ await io.batch(SCHEMA)
256
+ ready = true
257
+ }
258
+ let read = async (s: Stmt, until?: number) => {
259
+ let initialized = ready
260
+ let send = async () =>
261
+ (await io.all<Record<string, string>>(s, until)).results
262
+ try {
263
+ return await send()
264
+ } catch (e) {
265
+ // A cold reader normally finds the tables already on disk. Only an
266
+ // uninitialized database needs schema work before answering a read.
267
+ if (initialized || !missingTable.test(String(e))) throw e
268
+ await setup()
269
+ return await send()
270
+ }
271
+ }
272
+ let run = async (
273
+ s: Stmt | Stmt[],
274
+ until?: number,
275
+ ): Promise<Record<string, string>[]> => {
276
+ try {
277
+ if (!Array.isArray(s) && s.t == 'select') return await read(s, until)
278
+ await setup()
279
+ if (Array.isArray(s)) {
280
+ await io.batch(s, until)
281
+ return []
282
+ }
283
+ return (await io.all<Record<string, string>>(s, until)).results
284
+ } catch (e) {
285
+ // The D1 operation has already spent its retries. Generating a new write
286
+ // in @yaks/secrets would also generate a different receipt.
287
+ if (e instanceof Error && 'retryable' in e && e.retryable === true) {
288
+ Object.assign(e, { retryable: false })
289
+ }
290
+ throw e
291
+ }
292
+ }
293
+
294
+ let seal = async (k: string, text: string) => {
295
+ let iv = crypto.getRandomValues(new Uint8Array(12))
296
+ let data = new Uint8Array(
297
+ await crypto.subtle.encrypt(
298
+ { name: 'AES-GCM', iv, additionalData: utf8.encode(k) },
299
+ await key,
300
+ utf8.encode(text),
301
+ ),
302
+ )
303
+ let both = new Uint8Array(12 + data.length)
304
+ both.set(iv)
305
+ both.set(data, 12)
306
+ return base64(both)
307
+ }
308
+ let open = async (k: string, v: string) => {
309
+ let both = unbase64(v)
310
+ return new TextDecoder().decode(
311
+ await crypto.subtle.decrypt(
312
+ {
313
+ name: 'AES-GCM',
314
+ iv: both.slice(0, 12),
315
+ additionalData: utf8.encode(k),
316
+ },
317
+ await key,
318
+ both.slice(12),
319
+ ),
320
+ )
321
+ }
322
+ let unseal = async (eid: string, v: string): Promise<Sealed> =>
323
+ JSON.parse(await open(eid, v))
324
+
325
+ let salt: Uint8Array | undefined
326
+ // One lock per key within this isolate (@yaks/fp `locks`).
327
+ let held = locks()
328
+ return {
329
+ // Two isolates asking at once each offer one; the first written wins and
330
+ // both read it back.
331
+ salt: async () => {
332
+ if (salt) return salt
333
+ let offer = crypto.getRandomValues(new Uint8Array(32))
334
+ await run(put(SALT, await seal(SALT, base64(offer)), false))
335
+ let [row] = await run(get(SALT))
336
+ return salt = unbase64(await open(SALT, row.v))
337
+ },
338
+ read: async (eid) => {
339
+ let [row] = await run(get(eid))
340
+ return row ? await unseal(eid, row.v) : undefined
341
+ },
342
+ readMany: async (eids) => {
343
+ let ids = [...new Set(eids)]
344
+ let found = new Map<string, PromiseSettledResult<Sealed>>()
345
+ for (let at = 0; at < ids.length; at += READ_LIMIT) {
346
+ let rows = await run(getMany(ids.slice(at, at + READ_LIMIT)))
347
+ let values = await Promise.allSettled(rows.map((r) => unseal(r.k, r.v)))
348
+ rows.forEach((r, i) => found.set(r.k, values[i]))
349
+ }
350
+ return found
351
+ },
352
+ seal: async (eid, sealed) => {
353
+ let value = await seal(eid, JSON.stringify(sealed))
354
+ await run(
355
+ writing((
356
+ fresh,
357
+ ) => [archived(eid, fresh), put(eid, value, true, fresh)]),
358
+ )
359
+ },
360
+ drop: async (eid) => {
361
+ await run(
362
+ writing((fresh) => [archived(eid, fresh), removed(VAULT, eid, fresh)]),
363
+ )
364
+ },
365
+ trash: async () => {
366
+ let rows = await run(select({
367
+ cols: [col('k'), col('eid'), col('at'), col('v')],
368
+ from: table(TRASH),
369
+ order: [desc(col('rowid'))],
370
+ }))
371
+ return Promise.all(rows.map(async (r) => {
372
+ let sealed = JSON.parse(await open(r.eid, r.v)) as Sealed
373
+ return {
374
+ id: r.k,
375
+ eid: r.eid,
376
+ at: Number(r.at),
377
+ handle: sealed.handle,
378
+ ...sealed.name ? { name: sealed.name } : {},
379
+ }
380
+ }))
381
+ },
382
+ past: async (id) => {
383
+ let [row] = await run(select({
384
+ cols: [col('eid'), col('v')],
385
+ from: table(TRASH),
386
+ where: eq(col('k'), val(id)),
387
+ }))
388
+ return row ? JSON.parse(await open(row.eid, row.v)) as Sealed : undefined
389
+ },
390
+ restore: async (id) => {
391
+ let [row] = await run(select({
392
+ cols: [col('eid')],
393
+ from: table(TRASH),
394
+ where: eq(col('k'), val(id)),
395
+ }))
396
+ if (!row) return false
397
+ await run(writing((fresh) => {
398
+ let eligible = and(
399
+ fresh,
400
+ present(TRASH, val(id)),
401
+ not(present(ERASED, val(row.eid))),
402
+ )
403
+ return [
404
+ archived(row.eid, eligible),
405
+ {
406
+ t: 'insert',
407
+ into: VAULT,
408
+ cols: ['k', 'v'],
409
+ q: select({
410
+ cols: [col('eid'), col('v')],
411
+ from: table(TRASH),
412
+ where: and(eligible, eq(col('k'), val(id))),
413
+ }),
414
+ upsert: [{ on: [col('k')], set: { v: col('v', 'excluded') } }],
415
+ },
416
+ removed(TRASH, id, eligible),
417
+ ]
418
+ }))
419
+ return true
420
+ },
421
+ purge: async (id) => {
422
+ await run(removed(TRASH, id))
423
+ },
424
+ erase: async (eids) => {
425
+ for (let at = 0; at < eids.length; at += 50) {
426
+ let ids = eids.slice(at, at + 50).map(val)
427
+ await run([
428
+ {
429
+ t: 'insert',
430
+ into: ERASED,
431
+ cols: ['k'],
432
+ rows: ids.map((id) => [id]),
433
+ upsert: [{}],
434
+ },
435
+ { t: 'delete', from: VAULT, where: among(col('k'), ids) },
436
+ { t: 'delete', from: TRASH, where: among(col('eid'), ids) },
437
+ ])
438
+ }
439
+ },
440
+ all: async () => {
441
+ let rows = await run(select({
442
+ cols: [col('k'), col('v')],
443
+ from: table(VAULT),
444
+ where: ne(col('k'), val(SALT)),
445
+ }))
446
+ return Promise.all(
447
+ rows.map(async (r) =>
448
+ [r.k, JSON.parse(await open(r.k, r.v))] as [string, Sealed]
449
+ ),
450
+ )
451
+ },
452
+ lock: (eid, fn) =>
453
+ held(eid, async () => {
454
+ // The tables first, so the lease and each ask start once they stand.
455
+ await setup()
456
+ let me = crypto.randomUUID()
457
+ let until = clock.now() + LEASE
458
+ let failed: unknown
459
+ for (let wait = 5;; wait = Math.min(wait * 2, 500)) {
460
+ let now = clock.now()
461
+ if (now >= until) {
462
+ throw failed ?? new Error(`${eid} is locked elsewhere`)
463
+ }
464
+ // A resent ask is won again by its own holder, so one D1 did not
465
+ // answer in time is asked again within the lease.
466
+ try {
467
+ let ask = take(eid, me, now + LEASE, now)
468
+ if ((await run(ask, Math.min(until, now + retryFor))).length) break
469
+ failed = undefined
470
+ } catch (e) {
471
+ if (!(e instanceof Expired) && !transient(e)) throw e
472
+ failed = e
473
+ }
474
+ await sleep(wait, undefined, clock)
475
+ }
476
+ try {
477
+ return await fn()
478
+ } finally {
479
+ await run({
480
+ t: 'delete',
481
+ from: LOCK,
482
+ where: and(eq(col('k'), val(eid)), eq(col('holder'), val(me))),
483
+ })
484
+ }
485
+ }),
486
+ }
487
+ }