typevault 0.8.0 → 0.9.1

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": "typevault",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
@@ -1,4 +1,5 @@
1
1
  import { appendAudit, type AuditEvent, type AuditMode } from '../audit/log'
2
+ import { canonicalJson, type Json } from '../core/encoding'
2
3
  import { signerOf } from '../core/entries'
3
4
  import { TypeVaultError } from '../core/errors'
4
5
  import { withLock } from '../core/lock'
@@ -13,6 +14,7 @@ import {
13
14
  type EntryValue,
14
15
  entryInputOf,
15
16
  type SetInput,
17
+ putOptionsOf,
16
18
  toSummary,
17
19
  toValue,
18
20
  writtenFromAbove,
@@ -30,6 +32,16 @@ export type ScopedIdentity = {
30
32
  readonly defaultTier?: string
31
33
  }
32
34
 
35
+ // Writes that keep landing during each refresh retry are a writer storm, not a race to wait out.
36
+ const REFRESH_ATTEMPTS = 3
37
+
38
+ // Key order means nothing in a field, so a writer that re-serializes an OAuth map must not look like a replacement.
39
+ const sameEnvelope = (a: StoredEntry, b: StoredEntry): boolean =>
40
+ canonicalJson(a.envelope as unknown as Json) === canonicalJson(b.envelope as unknown as Json)
41
+
42
+ const sameField = (a: Field | undefined, b: Field | undefined): boolean =>
43
+ a !== undefined && b !== undefined && canonicalJson(a as Json) === canonicalJson(b as Json)
44
+
33
45
  const valueOf = (entry: StoredEntry): EntryValue =>
34
46
  toValue(entry.envelope.tier, entry.envelope.id, entry.envelope.rev, entry.payload)
35
47
 
@@ -82,6 +94,13 @@ export class ScopedVault implements Access {
82
94
  return [...byName.values()].flatMap((copies) => resolveName(this.#vault.state.tiers, copies) ?? [])
83
95
  }
84
96
 
97
+ /** The copy of `name` this scope sees, chosen as `#visible` chooses it, without resolving any other name. */
98
+ async #visibleCopy(name: EntryName): Promise<StoredEntry | undefined> {
99
+ const { entries } = await this.#vault.scan()
100
+ const copies = entries.filter((entry) => entry.payload.name === name && this.#allows(entry))
101
+ return resolveName(this.#vault.state.tiers, copies)
102
+ }
103
+
85
104
  async unreadableEntries(): Promise<number> {
86
105
  return (await this.#vault.scan()).problems.length
87
106
  }
@@ -133,9 +152,80 @@ export class ScopedVault implements Access {
133
152
  return changed ? this.#storeRefreshed(entry, fields) : entry
134
153
  }
135
154
 
155
+ /**
156
+ * Stores the refreshed OAuth fields of `entry`. The provider call ran outside the vault lock, so another write may
157
+ * have landed since `entry` was read: the write is a compare-and-swap, and after a conflict only the OAuth fields
158
+ * still holding the value refreshed from are replaced, leaving every other change as it was. The re-read goes
159
+ * through this grant's scope against the vault's current tiers, so an entry the grant lost meanwhile is neither
160
+ * written nor returned. A removed or replaced entry gets nothing, and neither does one whose refreshed fields were
161
+ * all rewritten by someone else: there is nothing left to store, so it is returned as it stands.
162
+ */
136
163
  async #storeRefreshed(entry: StoredEntry, fields: Readonly<Record<string, Field>>): Promise<StoredEntry> {
164
+ const refreshed = Object.entries(fields).filter(([field, value]) => value !== entry.payload.fields[field])
165
+ let current = entry
166
+ for (let attempt = 0; attempt < REFRESH_ATTEMPTS; attempt++) {
167
+ const read = current
168
+ const merged = { ...read.payload.fields }
169
+ let applied = false
170
+ for (const [field, value] of refreshed) {
171
+ if (!sameField(current.payload.fields[field], entry.payload.fields[field])) continue
172
+ merged[field] = value
173
+ applied = true
174
+ }
175
+ if (!applied) return current
176
+ try {
177
+ const stored = await this.#vault.put(
178
+ this.#refreshInput(current, merged),
179
+ signerOf(await this.#refreshKey(current)),
180
+ // A refresh replaces short-lived tokens, not the credentials a rotation warning is about.
181
+ {
182
+ copy: read.envelope.id,
183
+ ifRev: read.envelope.rev,
184
+ rotates: false,
185
+ // Access can be withdrawn, or another copy can come to win the name in this scope, without this copy's
186
+ // revision changing, so both are judged under the lock, not just here. Two writes from one sealed bundle
187
+ // even share an id and revision, so the copy must also be byte for byte the one this attempt read.
188
+ allows: (found, copies) => {
189
+ if (!this.#allows(found)) return false
190
+ const winner = resolveName(
191
+ this.#vault.state.tiers,
192
+ copies.filter((copy) => this.#allows(copy)),
193
+ )
194
+ if (winner?.envelope.id !== found.envelope.id || !sameEnvelope(found, read)) {
195
+ throw new TypeVaultError(
196
+ 'conflict',
197
+ `${found.payload.name} changed while its token was refreshed; read it again`,
198
+ )
199
+ }
200
+ return true
201
+ },
202
+ },
203
+ )
204
+ await this.#audit({ action: 'refresh', entries: [entry.payload.name] })
205
+ return stored
206
+ } catch (error) {
207
+ if (!(error instanceof TypeVaultError) || error.code !== 'conflict') throw error
208
+ }
209
+ // The copy this grant sees, chosen as `values()` chose it, so a same-name copy in another tier never stands in.
210
+ const found = await this.#visibleCopy(entry.payload.name)
211
+ if (found === undefined) throw new TypeVaultError('not_found', `no entry named ${entry.payload.name}`)
212
+ if (found.envelope.id !== entry.envelope.id) {
213
+ throw new TypeVaultError(
214
+ 'conflict',
215
+ `${entry.payload.name} changed while its token was refreshed; read it again`,
216
+ )
217
+ }
218
+ current = found
219
+ }
220
+ throw new TypeVaultError(
221
+ 'conflict',
222
+ `${entry.payload.name} kept changing while its token was refreshed; read it again`,
223
+ )
224
+ }
225
+
226
+ #refreshInput(entry: StoredEntry, fields: Readonly<Record<string, Field>>) {
137
227
  const { name, env, origin, tags } = entry.payload
138
- const input = {
228
+ return {
139
229
  name,
140
230
  fields,
141
231
  tier: entry.envelope.tier,
@@ -143,8 +233,11 @@ export class ScopedVault implements Access {
143
233
  ...(env === undefined ? {} : { env }),
144
234
  ...(origin === undefined ? {} : { origin }),
145
235
  }
146
- // A read must not promote the original writer's metadata to the reader's authority. Reuse its owner/tier
147
- // key when held; certificates and unavailable signing keys narrow to the entry's own tier.
236
+ }
237
+
238
+ // A read must not promote the original writer's metadata to the reader's authority. Reuse its owner/tier key when
239
+ // held; certificates and unavailable signing keys narrow to the entry's own tier.
240
+ async #refreshKey(entry: StoredEntry) {
148
241
  const { signer, tier } = entry.envelope
149
242
  const original =
150
243
  signer.kind === 'owner'
@@ -154,9 +247,7 @@ export class ScopedVault implements Access {
154
247
  : undefined
155
248
  const key = original ?? (await this.#vault.keyring.unlock(tier))
156
249
  if (key === undefined) throw new TypeVaultError('denied', `no key here can refresh tier "${tier}"`)
157
- const refreshed = await this.#vault.put(input, signerOf(key))
158
- await this.#audit({ action: 'refresh', entries: [name] })
159
- return refreshed
250
+ return key
160
251
  }
161
252
 
162
253
  #remember(value: EntryValue): EntryValue {
@@ -240,12 +331,7 @@ export class ScopedVault implements Access {
240
331
  if (existing !== undefined && !this.#allows(existing)) {
241
332
  throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
242
333
  }
243
- const { ifRev } = input
244
- const stored = await this.#vault.put(
245
- entryInputOf(input, tier),
246
- await this.#signerFor(tier),
247
- ifRev === undefined ? {} : { ifRev },
248
- )
334
+ const stored = await this.#vault.put(entryInputOf(input, tier), await this.#signerFor(tier), putOptionsOf(input))
249
335
  await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] })
250
336
  return toSummary(valueOf(stored))
251
337
  }
@@ -9,7 +9,15 @@ import { Vault } from '../core/vault'
9
9
  import { secretValues } from './env'
10
10
  import { allowsEntry } from './scope'
11
11
  import { type SealedBundle, sealedSigningSecret } from './sealed'
12
- import { type Access, type EntrySummary, type EntryValue, entryInputOf, type SetInput, toSummary } from './types'
12
+ import {
13
+ type Access,
14
+ type EntrySummary,
15
+ type EntryValue,
16
+ entryInputOf,
17
+ putOptionsOf,
18
+ type SetInput,
19
+ toSummary,
20
+ } from './types'
13
21
 
14
22
  type Env = Readonly<Record<string, string | undefined>>
15
23
 
@@ -84,6 +92,14 @@ export class SealedAccess implements Access {
84
92
  }
85
93
 
86
94
  async set(input: SetInput): Promise<EntrySummary> {
95
+ // A blind writer sees only the bundled snapshot, not what the name holds now, so it can neither check the entry's
96
+ // id nor carry its current rotation warning forward. Refuse rather than report a guarantee it didn't give.
97
+ if (input.ifId !== undefined || input.rotates === false) {
98
+ throw new TypeVaultError(
99
+ 'unavailable',
100
+ `a sealed grant can't verify the entry it replaces, so it can't take ${input.ifId === undefined ? 'rotates: false' : 'ifId'}; use a live grant`,
101
+ )
102
+ }
87
103
  const bundle = this.#live()
88
104
  const vault = await this.#vault()
89
105
  const prior = bundle.entries.find((value) => value.name === input.name)
@@ -95,11 +111,10 @@ export class SealedAccess implements Access {
95
111
  if (prior !== undefined && prior.tier !== tier) {
96
112
  throw new TypeVaultError('denied', `${input.name} is in tier "${prior.tier}"; a sealed grant cannot move it`)
97
113
  }
98
- const { ifRev } = input
99
114
  const stored = await vault.put(
100
115
  entryInputOf(input, tier),
101
116
  { ref: { kind: 'cert', cert: bundle.write.cert }, signSecret: sealedSigningSecret(bundle) },
102
- { ...(ifRev === undefined ? {} : { ifRev }), ...(prior === undefined ? {} : { base: prior }) },
117
+ { ...putOptionsOf(input), ...(prior === undefined ? {} : { base: prior }) },
103
118
  )
104
119
  await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] }, vault.anchorsFile)
105
120
  const { envelope, payload } = stored
@@ -3,6 +3,7 @@ import { TypeVaultError } from '../core/errors'
3
3
  import { type EntryName, type Field, isReservedEnvName } from '../core/naming'
4
4
  import type { EntryPayload } from '../core/payload'
5
5
  import { reachesTier, type VaultState } from '../core/state'
6
+ import type { PutOptions } from '../core/vault'
6
7
 
7
8
  export type EntrySummary = {
8
9
  readonly name: EntryName
@@ -36,6 +37,25 @@ export type SetInput = {
36
37
  readonly source?: string | undefined
37
38
  readonly tags?: readonly string[] | undefined
38
39
  readonly ifRev?: number | undefined
40
+ /**
41
+ * Write only if the name still holds this entry (`EntryValue.id`): a same-name replacement can share its revision.
42
+ * A sealed grant refuses it, since it can't read what the name holds now.
43
+ */
44
+ readonly ifId?: string | undefined
45
+ /**
46
+ * False when the new fields don't rotate the entry's credentials, such as a passkey's sign count: its rotation time
47
+ * and any `needsRotation` warning stay as they were. A sealed grant refuses `false`, since it can't read the warning.
48
+ */
49
+ readonly rotates?: boolean | undefined
50
+ }
51
+
52
+ /** The compare-and-swap and rotation options of a write, without the ones a parsed request leaves undefined. */
53
+ export function putOptionsOf(input: SetInput): PutOptions {
54
+ return {
55
+ ...(input.ifRev === undefined ? {} : { ifRev: input.ifRev }),
56
+ ...(input.ifId === undefined ? {} : { ifId: input.ifId }),
57
+ ...(input.rotates === undefined ? {} : { rotates: input.rotates }),
58
+ }
39
59
  }
40
60
 
41
61
  /** The vault-level input for a write, without the optional keys a parsed request leaves undefined. */
package/src/core/vault.ts CHANGED
@@ -40,7 +40,25 @@ export type EntryBase = {
40
40
  readonly source?: string
41
41
  }
42
42
 
43
- export type PutOptions = { readonly ifRev?: number; readonly base?: EntryBase }
43
+ export type PutOptions = {
44
+ readonly ifRev?: number
45
+ readonly ifId?: string
46
+ /** False for a write that changes fields without rotating the entry's credentials (an OAuth refresh, a counter). */
47
+ readonly rotates?: boolean
48
+ /**
49
+ * Replace exactly the copy with this id instead of the copy the name resolves to: a scoped writer's own copy of a
50
+ * name that several tiers hold. A copy no longer stored is a conflict.
51
+ */
52
+ readonly copy?: string
53
+ /**
54
+ * Judges the copy being replaced under the write lock, against the state that lock just loaded, given every verified
55
+ * copy of the name: a scoped writer's own check that it may still write that copy, and that the copy is still the
56
+ * one its scope resolves the name to. An owner-backed vault would otherwise pass any copy it can open. Refused is
57
+ * not found.
58
+ */
59
+ readonly allows?: (found: StoredEntry, copies: readonly StoredEntry[]) => boolean
60
+ readonly base?: EntryBase
61
+ }
44
62
 
45
63
  export type EntryInput = {
46
64
  readonly name: EntryName
@@ -63,6 +81,12 @@ function parseJson(bytes: Uint8Array): unknown {
63
81
  }
64
82
  }
65
83
 
84
+ function copyIn(copies: readonly StoredEntry[], name: EntryName, id: string): StoredEntry {
85
+ const copy = copies.find((entry) => entry.envelope.id === id)
86
+ if (copy === undefined) throw new TypeVaultError('conflict', `${name} no longer has the copy ${id}`)
87
+ return copy
88
+ }
89
+
66
90
  const sameFields = (a: Readonly<Record<string, Field>>, b: Readonly<Record<string, Field>>): boolean =>
67
91
  JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort())
68
92
 
@@ -241,6 +265,11 @@ export class Vault {
241
265
  )
242
266
  }
243
267
 
268
+ async #copies(name: EntryName): Promise<readonly StoredEntry[]> {
269
+ const { entries } = await this.scan()
270
+ return entries.filter((entry) => entry.payload.name === name)
271
+ }
272
+
244
273
  /** The envelope that writing `input` over `found` (or a blind writer's `base`) produces. */
245
274
  async #draft(
246
275
  input: EntryInput,
@@ -253,8 +282,13 @@ export class Vault {
253
282
  if (options.ifRev !== undefined && currentRev !== options.ifRev) {
254
283
  throw new TypeVaultError('conflict', `${input.name} is at revision ${currentRev}, not ${options.ifRev}`)
255
284
  }
285
+ // A name deleted and recreated can be back at the same revision; the id tells the two entries apart.
286
+ if (options.ifId !== undefined && prior?.id !== options.ifId) {
287
+ throw new TypeVaultError('conflict', `${input.name} is not the entry ${options.ifId}`)
288
+ }
256
289
  const now = new Date().toISOString()
257
- const changed = found === undefined || !sameFields(found.payload.fields, input.fields)
290
+ const changed =
291
+ (found === undefined || !sameFields(found.payload.fields, input.fields)) && options.rotates !== false
258
292
  const source = input.source ?? prior?.source
259
293
  const payload: EntryPayload = {
260
294
  v: 1,
@@ -281,7 +315,22 @@ export class Vault {
281
315
  */
282
316
  put(input: EntryInput, signer: SignerContext, options: PutOptions = {}): Promise<StoredEntry> {
283
317
  return withLock(this.layout.lockFile, 'exclusive', async () => {
284
- const found = await this.find(input.name)
318
+ const copies =
319
+ options.copy === undefined && options.allows === undefined ? undefined : await this.#copies(input.name)
320
+ const found =
321
+ copies === undefined
322
+ ? await this.find(input.name)
323
+ : options.copy === undefined
324
+ ? resolveName(this.#state.tiers, copies)
325
+ : copyIn(copies, input.name, options.copy)
326
+ if (
327
+ found !== undefined &&
328
+ copies !== undefined &&
329
+ options.allows !== undefined &&
330
+ !options.allows(found, copies)
331
+ ) {
332
+ throw new TypeVaultError('not_found', `no entry named ${input.name}`)
333
+ }
285
334
  const stored = await this.#draft(input, found, options, signer)
286
335
  atomicWrite(
287
336
  join(this.layout.entries, `${stored.envelope.id}.json`),
@@ -25,10 +25,12 @@ export const SetBody = z.object({
25
25
  origin: z.string().optional(),
26
26
  tags: z.array(z.string()).optional(),
27
27
  ifRev: z.number().int().nonnegative().optional(),
28
+ ifId: z.string().optional(),
29
+ rotates: z.boolean().optional(),
28
30
  })
29
31
  /** The entries an import writes, sent as staged chunks of their serialized JSON. */
30
32
  export const ImportEntries = z.array(
31
- SetBody.omit({ tier: true, ifRev: true }).extend({ source: z.string().optional() }),
33
+ SetBody.omit({ tier: true, ifRev: true, ifId: true, rotates: true }).extend({ source: z.string().optional() }),
32
34
  )
33
35
  /** One base64 chunk of an import, staged until `ImportBody` commits it; the first chunk starts a new upload. */
34
36
  export const ImportStageBody = z.object({ upload: z.string().max(64).optional(), chunk: z.base64() })