typevault 0.1.0 → 0.3.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.
Files changed (76) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +14 -9
  7. package/src/access/scoped.ts +118 -44
  8. package/src/access/sealed-access.ts +50 -23
  9. package/src/access/sealed.ts +56 -31
  10. package/src/access/types.ts +27 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +28 -12
  13. package/src/cli/commands/admin.ts +93 -48
  14. package/src/cli/commands/daemon.ts +42 -17
  15. package/src/cli/commands/entries.ts +195 -60
  16. package/src/cli/commands/grant.ts +24 -22
  17. package/src/cli/commands/members.ts +307 -0
  18. package/src/cli/commands/run.ts +191 -44
  19. package/src/cli/context.ts +163 -15
  20. package/src/cli/index.ts +33 -5
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +79 -0
  23. package/src/core/admin.ts +144 -76
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +15 -16
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +8 -2
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +87 -0
  31. package/src/core/identity.ts +132 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/json-file.ts +20 -0
  34. package/src/core/keyring.ts +100 -56
  35. package/src/core/layout.ts +143 -26
  36. package/src/core/lock.ts +128 -16
  37. package/src/core/naming.ts +150 -50
  38. package/src/core/password.ts +111 -0
  39. package/src/core/payload.ts +42 -38
  40. package/src/core/revisions.ts +11 -6
  41. package/src/core/rotate.ts +59 -42
  42. package/src/core/state.ts +102 -54
  43. package/src/core/txn.ts +9 -7
  44. package/src/core/vault.ts +108 -46
  45. package/src/core/worktrees.ts +51 -0
  46. package/src/daemon/admin-routes.ts +33 -21
  47. package/src/daemon/agent-routes.ts +31 -11
  48. package/src/daemon/client.ts +24 -2
  49. package/src/daemon/daemon.ts +218 -33
  50. package/src/daemon/grants.ts +25 -7
  51. package/src/daemon/http.ts +11 -2
  52. package/src/daemon/live-access.ts +8 -4
  53. package/src/daemon/protocol.ts +17 -12
  54. package/src/daemon/requests.ts +75 -51
  55. package/src/daemon/spawn.ts +218 -9
  56. package/src/export/1password.ts +157 -0
  57. package/src/import/1password-live.ts +399 -0
  58. package/src/import/1password.ts +26 -5
  59. package/src/import/bitwarden.ts +3 -3
  60. package/src/import/csv.ts +1 -1
  61. package/src/import/dotenv.ts +4 -3
  62. package/src/import/index.ts +1 -0
  63. package/src/import/keepass.ts +2 -2
  64. package/src/import/lastpass.ts +2 -2
  65. package/src/import/shared.ts +67 -10
  66. package/src/import/typeclaw.ts +2 -2
  67. package/src/import/types.ts +1 -1
  68. package/src/index.ts +58 -0
  69. package/src/owner.ts +156 -0
  70. package/src/prompt/browser.ts +48 -15
  71. package/src/prompt/index.ts +121 -64
  72. package/src/prompt/page.ts +27 -11
  73. package/src/prompt/styles.ts +64 -34
  74. package/src/prompt/types.ts +7 -4
  75. package/src/redact/index.ts +48 -12
  76. package/src/redact/scrub-file.ts +15 -7
@@ -1,10 +1,12 @@
1
1
  import { appendAudit, type AuditEvent, type AuditMode } from '../audit/log'
2
2
  import { signerOf } from '../core/entries'
3
3
  import { TypeVaultError } from '../core/errors'
4
- import { type EntryName, matchesOnly } from '../core/naming'
4
+ import { withLock } from '../core/lock'
5
+ import { type EntryName, type Field, matchesOnly } from '../core/naming'
5
6
  import { resolveName, type StoredEntry, type Vault } from '../core/vault'
6
7
  import { needsRefresh, refreshOAuth } from '../oauth/refresh'
7
- import { allowsEntry, allowsGroup, type ScopeChain } from './scope'
8
+ import { secretValues } from './env'
9
+ import { allowsEntry, allowsTier, type ScopeChain } from './scope'
8
10
  import {
9
11
  type Access,
10
12
  type EntrySummary,
@@ -20,14 +22,16 @@ export type ScopedIdentity = {
20
22
  readonly mode: AuditMode
21
23
  readonly grant?: string
22
24
  readonly label?: string
23
- /** Groups held directly; see `Access.ownGroups`. */
24
- readonly ownGroups?: readonly string[]
25
- /** Group used by `set` when the caller names none. */
26
- readonly defaultGroup?: string
25
+ /** The owner's own session, never a grant delegated from it. */
26
+ readonly owner?: boolean
27
+ /** Tiers held directly; see `Access.ownTiers`. */
28
+ readonly ownTiers?: readonly string[]
29
+ /** Tier used by `set` when the caller names none. */
30
+ readonly defaultTier?: string
27
31
  }
28
32
 
29
33
  const valueOf = (entry: StoredEntry): EntryValue =>
30
- toValue(entry.envelope.group, entry.envelope.id, entry.envelope.rev, entry.payload)
34
+ toValue(entry.envelope.tier, entry.envelope.id, entry.envelope.rev, entry.payload)
31
35
 
32
36
  /**
33
37
  * Vault access bounded by a scope chain, with every read and write audited. The daemon wraps each live
@@ -56,7 +60,7 @@ export class ScopedVault implements Access {
56
60
  }
57
61
 
58
62
  #allows(entry: StoredEntry): boolean {
59
- return allowsEntry(this.#chain, this.#vault.state, entry.envelope.group, entry.payload.name)
63
+ return allowsEntry(this.#chain, this.#vault.state, entry.envelope.tier, entry.payload.name)
60
64
  }
61
65
 
62
66
  /** One entry per name: the copy each name resolves to within this scope (see `resolveName`). */
@@ -66,7 +70,11 @@ export class ScopedVault implements Access {
66
70
  entries.filter((entry) => this.#allows(entry)),
67
71
  (entry) => entry.payload.name,
68
72
  )
69
- return [...byName.values()].flatMap((copies) => resolveName(this.#vault.state.groups, copies) ?? [])
73
+ return [...byName.values()].flatMap((copies) => resolveName(this.#vault.state.tiers, copies) ?? [])
74
+ }
75
+
76
+ async unreadableEntries(): Promise<number> {
77
+ return (await this.#vault.scan()).problems.length
70
78
  }
71
79
 
72
80
  async #find(name: EntryName): Promise<StoredEntry> {
@@ -75,37 +83,74 @@ export class ScopedVault implements Access {
75
83
  return entry
76
84
  }
77
85
 
78
- async #signerFor(group: string): Promise<ReturnType<typeof signerOf>> {
79
- // Direct mode is the key holder acting itself, so the operator signs as the operator. The daemon writes on behalf
80
- // of grants and signs with the group's own key, so a grant's writes never look operator-authored.
81
- const operator = this.#identity.mode === 'direct' ? this.#vault.keyring.operator : undefined
82
- const key = operator ?? (await this.#vault.keyring.unlock(group)) ?? this.#vault.keyring.operator
83
- if (key === undefined) throw new TypeVaultError('denied', `no key here can write group "${group}"`)
86
+ async #signerFor(tier: string): Promise<ReturnType<typeof signerOf>> {
87
+ // The owner signs its own writes in direct mode or its own session. Delegated grants use tier keys,
88
+ // so a grant's writes never look owner-authored.
89
+ const owner =
90
+ this.#identity.mode === 'direct' || this.#identity.owner === true ? this.#vault.keyring.owner : undefined
91
+ const key = owner ?? (await this.#vault.keyring.unlock(tier)) ?? this.#vault.keyring.owner
92
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${tier}"`)
84
93
  return signerOf(key)
85
94
  }
86
95
 
87
- /** OAuth entries past their expiry are refreshed and written back before anyone reads them. */
96
+ /** OAuth fields past their expiry are refreshed and written back before anyone reads them. */
88
97
  async #fresh(entry: StoredEntry): Promise<StoredEntry> {
89
98
  const now = new Date()
90
- if (entry.payload.type !== 'oauth' || !needsRefresh(entry.payload.fields, now)) return entry
91
- const fields = await refreshOAuth(entry.payload.fields, now)
92
- const { name, type, env, origin, tags } = entry.payload
99
+ const fields: Record<string, Field> = { ...entry.payload.fields }
100
+ let changed = false
101
+ try {
102
+ for (const [name, field] of Object.entries(fields)) {
103
+ switch (field.type) {
104
+ case 'oauth':
105
+ if (needsRefresh(field.value, now)) {
106
+ fields[name] = { type: 'oauth', value: await refreshOAuth(field.value, now) }
107
+ changed = true
108
+ }
109
+ break
110
+ case 'secret':
111
+ case 'text':
112
+ case 'totp':
113
+ break
114
+ default:
115
+ throw new TypeVaultError('invalid', `unexpected field ${JSON.stringify(field satisfies never)}`)
116
+ }
117
+ }
118
+ } catch (error) {
119
+ // A provider may have rotated an earlier field's refresh token already: store it before failing.
120
+ if (changed) await this.#storeRefreshed(entry, fields)
121
+ throw error
122
+ }
123
+ return changed ? this.#storeRefreshed(entry, fields) : entry
124
+ }
125
+
126
+ async #storeRefreshed(entry: StoredEntry, fields: Readonly<Record<string, Field>>): Promise<StoredEntry> {
127
+ const { name, env, origin, tags } = entry.payload
93
128
  const input = {
94
129
  name,
95
- type,
96
130
  fields,
97
- group: entry.envelope.group,
131
+ tier: entry.envelope.tier,
98
132
  tags,
99
133
  ...(env === undefined ? {} : { env }),
100
134
  ...(origin === undefined ? {} : { origin }),
101
135
  }
102
- const refreshed = await this.#vault.put(input, await this.#signerFor(entry.envelope.group))
136
+ // A read must not promote the original writer's metadata to the reader's authority. Reuse its owner/tier
137
+ // key when held; certificates and unavailable signing keys narrow to the entry's own tier.
138
+ const { signer, tier } = entry.envelope
139
+ const original =
140
+ signer.kind === 'owner'
141
+ ? this.#vault.keyring.owner
142
+ : signer.kind === 'tier'
143
+ ? await this.#vault.keyring.unlock(signer.tier)
144
+ : undefined
145
+ const key = original ?? (await this.#vault.keyring.unlock(tier))
146
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can refresh tier "${tier}"`)
147
+ const refreshed = await this.#vault.put(input, signerOf(key))
103
148
  await this.#audit({ action: 'refresh', entries: [name] })
104
149
  return refreshed
105
150
  }
106
151
 
107
152
  #remember(value: EntryValue): EntryValue {
108
- for (const field of Object.values(value.fields)) if (field !== '') this.#handedOut.add(field)
153
+ for (const secret of secretValues([value])) this.#handedOut.add(secret)
109
154
  return value
110
155
  }
111
156
 
@@ -124,7 +169,7 @@ export class ScopedVault implements Access {
124
169
  const fresh = await Promise.all(picked.map((entry) => this.#fresh(entry)))
125
170
  const names = fresh.map((entry) => entry.payload.name)
126
171
  await this.#audit({ action: 'read', entries: names, ...(reason === undefined ? {} : { reason }) })
127
- const own = this.#identity.ownGroups ?? []
172
+ const own = this.#identity.ownTiers ?? []
128
173
  return fresh.map((entry) =>
129
174
  this.#remember({
130
175
  ...valueOf(entry),
@@ -133,14 +178,34 @@ export class ScopedVault implements Access {
133
178
  )
134
179
  }
135
180
 
136
- async set(input: SetInput): Promise<EntrySummary> {
137
- const group = input.group ?? this.#identity.defaultGroup
138
- if (group === undefined) throw new TypeVaultError('invalid', 'choose a group with --group')
181
+ // The tier is chosen under the same exclusive lock as the write, from freshly read state, so a tier another
182
+ // process adds in between makes the choice ambiguous instead of silently picking the old only tier.
183
+ set(input: SetInput): Promise<EntrySummary> {
184
+ return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
185
+ this.#vault.refresh()
186
+ return this.#write(input, input.tier ?? this.#identity.defaultTier ?? (await this.#onlyWritableTier()))
187
+ })
188
+ }
189
+
190
+ /** Only infer when there is exactly one answer: the tier decides who can read the secret. */
191
+ async #onlyWritableTier(): Promise<string> {
192
+ const { state, keyring } = this.#vault
193
+ const writable = [...(await keyring.reachableTiers())].filter((name) => allowsTier(this.#chain, state, name))
194
+ const [only, ...others] = writable
195
+ if (only === undefined) {
196
+ throw new TypeVaultError('invalid', 'no tier to write to yet: create one with `typevault tier add <name>`')
197
+ }
198
+ if (others.length === 0) return only
199
+ const viaEnv = this.#identity.mode === 'direct' ? ' or set TYPEVAULT_TIER' : ''
200
+ throw new TypeVaultError('invalid', `choose a tier with --tier (one of: ${writable.join(', ')})${viaEnv}`)
201
+ }
202
+
203
+ async #write(input: SetInput, tier: string): Promise<EntrySummary> {
139
204
  if (
140
- !allowsGroup(this.#chain, this.#vault.state, group) ||
141
- !allowsEntry(this.#chain, this.#vault.state, group, input.name)
205
+ !allowsTier(this.#chain, this.#vault.state, tier) ||
206
+ !allowsEntry(this.#chain, this.#vault.state, tier, input.name)
142
207
  ) {
143
- throw new TypeVaultError('denied', `this grant cannot write ${input.name} in group "${group}"`)
208
+ throw new TypeVaultError('denied', `this grant cannot write ${input.name} in tier "${tier}"`)
144
209
  }
145
210
  const existing = await this.#vault.find(input.name)
146
211
  if (existing !== undefined && !this.#allows(existing)) {
@@ -148,34 +213,43 @@ export class ScopedVault implements Access {
148
213
  }
149
214
  const { ifRev } = input
150
215
  const stored = await this.#vault.put(
151
- entryInputOf(input, group),
152
- await this.#signerFor(group),
216
+ entryInputOf(input, tier),
217
+ await this.#signerFor(tier),
153
218
  ifRev === undefined ? {} : { ifRev },
154
219
  )
155
- await this.#audit({ action: 'write', entries: [input.name], groups: [group] })
220
+ await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] })
156
221
  return toSummary(valueOf(stored))
157
222
  }
158
223
 
159
- async remove(name: EntryName, group?: string): Promise<void> {
160
- if (group === undefined) await this.#find(name)
161
- else if (!allowsEntry(this.#chain, this.#vault.state, group, name)) {
162
- throw new TypeVaultError('not_found', `no entry named ${name}`)
163
- }
164
- await this.#vault.remove(name, group)
165
- await this.#audit({ action: 'remove', entries: [name], ...(group === undefined ? {} : { groups: [group] }) })
224
+ // The name is resolved once and the delete targets that copy's id: resolving it again could land on a copy that
225
+ // arrived in between (another process, or a git pull, which takes no lock), say in a tier above this scope.
226
+ remove(name: EntryName, tier?: string): Promise<void> {
227
+ return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
228
+ let entry: StoredEntry | undefined
229
+ if (tier === undefined) entry = await this.#find(name)
230
+ else {
231
+ const { entries } = await this.#vault.scan()
232
+ entry = entries.find((copy) => copy.payload.name === name && copy.envelope.tier === tier)
233
+ if (entry === undefined || !this.#allows(entry)) throw new TypeVaultError('not_found', `no entry named ${name}`)
234
+ }
235
+ await this.#vault.removeById(entry.envelope.id, (envelope) =>
236
+ allowsEntry(this.#chain, this.#vault.state, envelope.tier, name),
237
+ )
238
+ await this.#audit({ action: 'remove', entries: [name], ...(tier === undefined ? {} : { tiers: [tier] }) })
239
+ })
166
240
  }
167
241
 
168
242
  async move(from: EntryName, to: EntryName): Promise<void> {
169
243
  const entry = await this.#find(from)
170
- if (!allowsEntry(this.#chain, this.#vault.state, entry.envelope.group, to)) {
244
+ if (!allowsEntry(this.#chain, this.#vault.state, entry.envelope.tier, to)) {
171
245
  throw new TypeVaultError('denied', `this grant cannot use the name ${to}`)
172
246
  }
173
- await this.#vault.move(from, to, await this.#signerFor(entry.envelope.group))
247
+ await this.#vault.move(from, to, await this.#signerFor(entry.envelope.tier))
174
248
  await this.#audit({ action: 'move', entries: [from, to] })
175
249
  }
176
250
 
177
- async ownGroups(): Promise<readonly string[]> {
178
- return this.#identity.ownGroups ?? []
251
+ async ownTiers(): Promise<readonly string[]> {
252
+ return this.#identity.ownTiers ?? []
179
253
  }
180
254
 
181
255
  async readValues(): Promise<readonly string[]> {
@@ -1,10 +1,12 @@
1
1
  import { existsSync } from 'node:fs'
2
2
 
3
3
  import { appendAudit, type AuditEvent } from '../audit/log'
4
+ import { signerAuthority } from '../core/entries'
4
5
  import { TypeVaultError } from '../core/errors'
5
- import { layoutOf } from '../core/layout'
6
+ import type { Layout } from '../core/layout'
6
7
  import { type EntryName, matchesOnly } from '../core/naming'
7
8
  import { Vault } from '../core/vault'
9
+ import { secretValues } from './env'
8
10
  import { allowsEntry } from './scope'
9
11
  import { type SealedBundle, sealedSigningSecret } from './sealed'
10
12
  import { type Access, type EntrySummary, type EntryValue, entryInputOf, type SetInput, toSummary } from './types'
@@ -17,12 +19,13 @@ type Env = Readonly<Record<string, string | undefined>>
17
19
  */
18
20
  export class SealedAccess implements Access {
19
21
  readonly #bundle: SealedBundle
20
- readonly #root: string
22
+ readonly #layout: Layout | undefined
21
23
  readonly #env: Env
22
24
 
23
- constructor(bundle: SealedBundle, root: string, env: Env) {
25
+ /** `layout` is undefined where no vault is selected: reads still work, writes refuse. */
26
+ constructor(bundle: SealedBundle, layout: Layout | undefined, env: Env) {
24
27
  this.#bundle = bundle
25
- this.#root = root
28
+ this.#layout = layout
26
29
  this.#env = env
27
30
  }
28
31
 
@@ -38,16 +41,16 @@ export class SealedAccess implements Access {
38
41
  }
39
42
 
40
43
  async #vault(): Promise<Vault> {
41
- if (!existsSync(layoutOf(this.#root).operatorFile)) {
42
- throw new TypeVaultError('unavailable', 'writing with a sealed grant needs the vault directory (TYPEVAULT_DIR)')
44
+ if (this.#layout === undefined || !existsSync(this.#layout.ownerFile)) {
45
+ throw new TypeVaultError('unavailable', 'writing with a sealed grant needs the vault directory')
43
46
  }
44
- return Vault.open(this.#root, [], this.#env)
47
+ return Vault.open(this.#layout, [], this.#env)
45
48
  }
46
49
 
47
50
  /** Best effort: a sealed grant may run where no vault directory exists. */
48
51
  async #audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>): Promise<void> {
49
- const layout = layoutOf(this.#root)
50
- if (!existsSync(layout.operatorFile)) return
52
+ const layout = this.#layout
53
+ if (layout === undefined || !existsSync(layout.ownerFile)) return
51
54
  await appendAudit(layout, { ...event, mode: 'sealed', grant: this.#bundle.id, label: this.#bundle.label })
52
55
  }
53
56
 
@@ -55,6 +58,11 @@ export class SealedAccess implements Access {
55
58
  return this.#live().entries.map(toSummary)
56
59
  }
57
60
 
61
+ /** Its entries travel inside the sealed bundle, so there are no files here to fail. */
62
+ async unreadableEntries(): Promise<number> {
63
+ return 0
64
+ }
65
+
58
66
  async get(name: EntryName, reason?: string): Promise<EntryValue> {
59
67
  const entry = this.#entry(name)
60
68
  await this.#audit({ action: 'read', entries: [name], ...(reason === undefined ? {} : { reason }) })
@@ -74,23 +82,26 @@ export class SealedAccess implements Access {
74
82
  async set(input: SetInput): Promise<EntrySummary> {
75
83
  const bundle = this.#live()
76
84
  const vault = await this.#vault()
77
- const group = input.group ?? bundle.scope.groups[0]
78
- if (group === undefined || !allowsEntry([bundle.scope], vault.state, group, input.name)) {
79
- throw new TypeVaultError('denied', `this grant cannot write ${input.name} in group "${group ?? '?'}"`)
80
- }
81
85
  const prior = bundle.entries.find((value) => value.name === input.name)
86
+ const tier = input.tier ?? prior?.tier ?? bundle.scope.tiers[0]
87
+ if (tier === undefined || !allowsEntry([bundle.scope], vault.state, tier, input.name)) {
88
+ throw new TypeVaultError('denied', `this grant cannot write ${input.name} in tier "${tier ?? '?'}"`)
89
+ }
90
+ // Blind writes can't remove the old copy (that takes reading it), so moving tiers would leave two.
91
+ if (prior !== undefined && prior.tier !== tier) {
92
+ throw new TypeVaultError('denied', `${input.name} is in tier "${prior.tier}"; a sealed grant cannot move it`)
93
+ }
82
94
  const { ifRev } = input
83
95
  const stored = await vault.put(
84
- entryInputOf(input, group),
96
+ entryInputOf(input, tier),
85
97
  { ref: { kind: 'cert', cert: bundle.write.cert }, signSecret: sealedSigningSecret(bundle) },
86
98
  { ...(ifRev === undefined ? {} : { ifRev }), ...(prior === undefined ? {} : { base: prior }) },
87
99
  )
88
- await this.#audit({ action: 'write', entries: [input.name], groups: [group] })
100
+ await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] })
89
101
  const { envelope, payload } = stored
90
102
  return {
91
103
  name: payload.name,
92
- type: payload.type,
93
- group,
104
+ tier,
94
105
  rev: envelope.rev,
95
106
  tags: payload.tags,
96
107
  rotated: payload.rotated,
@@ -98,23 +109,39 @@ export class SealedAccess implements Access {
98
109
  }
99
110
  }
100
111
 
101
- async remove(name: EntryName, _group?: string): Promise<void> {
112
+ /**
113
+ * The bundle is holder-editable (whoever holds the grant can re-seal it), so only the issuer-signed
114
+ * certificate bounds what may be deleted: its tiers, `--only` and expiry, checked against the file on disk.
115
+ * The entry must still be the revision this grant carried (of an id its certificate lists), or one this grant's
116
+ * certificate wrote since.
117
+ */
118
+ async remove(name: EntryName, _tier?: string): Promise<void> {
102
119
  const entry = this.#entry(name)
103
- await (await this.#vault()).removeById(entry.id)
120
+ const { cert } = this.#bundle.write
121
+ const vault = await this.#vault()
122
+ await vault.removeById(
123
+ entry.id,
124
+ (envelope) =>
125
+ envelope.tier === entry.tier &&
126
+ ((cert.ids.includes(envelope.id) && envelope.rev === entry.rev) ||
127
+ (envelope.signer.kind === 'cert' && envelope.signer.cert.signPublic === cert.signPublic)) &&
128
+ allowsEntry([{ tiers: cert.tiers, only: cert.only }], vault.state, envelope.tier, name) &&
129
+ signerAuthority({ kind: 'cert', cert }, envelope.tier, vault.state, new Date().toISOString()) !== undefined,
130
+ )
104
131
  await this.#audit({ action: 'remove', entries: [name] })
105
132
  }
106
133
 
107
134
  async move(from: EntryName, to: EntryName): Promise<void> {
108
135
  const entry = this.#entry(from)
109
- await this.set({ name: to, type: entry.type, fields: entry.fields, group: entry.group, tags: entry.tags })
136
+ await this.set({ name: to, fields: entry.fields, tier: entry.tier, tags: entry.tags })
110
137
  await this.remove(from)
111
138
  }
112
139
 
113
- async ownGroups(): Promise<readonly string[]> {
114
- return this.#bundle.scope.groups
140
+ async ownTiers(): Promise<readonly string[]> {
141
+ return this.#bundle.scope.tiers
115
142
  }
116
143
 
117
144
  async readValues(): Promise<readonly string[]> {
118
- return this.#bundle.entries.flatMap((value) => Object.values(value.fields).filter((field) => field !== ''))
145
+ return secretValues(this.#bundle.entries)
119
146
  }
120
147
  }
@@ -4,7 +4,7 @@ import { generateX25519Identity, identityToRecipient } from 'age-encryption'
4
4
  import { z } from 'zod'
5
5
 
6
6
  import { appendAudit } from '../audit/log'
7
- import { generateSigningKey, randomHex, seal, unseal } from '../core/crypto'
7
+ import { generateSigningKey, randomHex, seal, type SecretKey, unseal } from '../core/crypto'
8
8
  import { fromBase64, fromBase64Url, fromUtf8, toBase64, toBase64Url, utf8 } from '../core/encoding'
9
9
  import { CertSchema, issueCert, signerOf } from '../core/entries'
10
10
  import { TypeVaultError } from '../core/errors'
@@ -20,7 +20,7 @@ const BundleSchema = z.object({
20
20
  v: z.literal(1),
21
21
  id: z.string(),
22
22
  label: z.string(),
23
- groups: z.array(z.string()),
23
+ tiers: z.array(z.string()),
24
24
  only: z.array(z.string()),
25
25
  exp: z.iso.datetime(),
26
26
  entries: z.array(EntryValueSchema),
@@ -40,33 +40,34 @@ export type SealedRequest = GrantScope & { readonly ttlMs: number; readonly labe
40
40
 
41
41
  /** Re-seals every entry the scope allows into a self-contained grant. The issuer's own key never leaves. */
42
42
  export async function issueSealedGrant(vault: Vault, request: SealedRequest): Promise<string> {
43
- const issuer =
44
- vault.keyring.operator ??
45
- vault.keys.find((key) => {
46
- const role = key.role
47
- return role.kind === 'group' && request.groups.every((group) => reach(vault.state.groups, role.group).has(group))
48
- })
49
- if (issuer === undefined) throw new TypeVaultError('denied', 'no key here reaches every requested group')
50
- for (const group of request.groups) {
51
- if (vault.state.groups[group] === undefined) throw new TypeVaultError('not_found', `no group "${group}"`)
43
+ const issuer = vault.keyring.owner ?? (await memberTierKey(vault, request.tiers))
44
+ if (issuer === undefined) throw new TypeVaultError('denied', 'no key here reaches every requested tier')
45
+ for (const tier of request.tiers) {
46
+ if (vault.state.tiers[tier] === undefined) throw new TypeVaultError('not_found', `no tier "${tier}"`)
52
47
  }
53
- const chain = [{ groups: request.groups, only: request.only }]
48
+ const chain = [{ tiers: request.tiers, only: request.only }]
54
49
  const { entries } = await vault.scan()
55
- const allowed = entries.filter((entry) => allowsEntry(chain, vault.state, entry.envelope.group, entry.payload.name))
50
+ const allowed = entries.filter((entry) => allowsEntry(chain, vault.state, entry.envelope.tier, entry.payload.name))
56
51
  const granted = [...Map.groupBy(allowed, (entry) => entry.payload.name).values()]
57
- .flatMap((copies) => resolveName(vault.state.groups, copies) ?? [])
52
+ .flatMap((copies) => resolveName(vault.state.tiers, copies) ?? [])
58
53
  .map((entry) => ({
59
- ...toValue(entry.envelope.group, entry.envelope.id, entry.envelope.rev, entry.payload),
60
- trustedWriter: writtenFromAbove(entry.envelope.signer, vault.state, request.groups),
54
+ ...toValue(entry.envelope.tier, entry.envelope.id, entry.envelope.rev, entry.payload),
55
+ trustedWriter: writtenFromAbove(entry.envelope.signer, vault.state, request.tiers),
61
56
  }))
62
57
  const id = randomHex(8)
63
58
  const exp = new Date(Date.now() + request.ttlMs).toISOString()
64
59
  const signing = generateSigningKey()
65
60
  const cert = issueCert(
66
- { signPublic: signing.signPublic, groups: [...request.groups], only: [...request.only], exp },
61
+ {
62
+ signPublic: signing.signPublic,
63
+ tiers: [...request.tiers],
64
+ only: [...request.only],
65
+ ids: granted.map((value) => value.id),
66
+ exp,
67
+ },
67
68
  signerOf(issuer),
68
69
  )
69
- const bundle = { v: 1, id, label: request.label, groups: request.groups, only: request.only, exp, entries: granted }
70
+ const bundle = { v: 1, id, label: request.label, tiers: request.tiers, only: request.only, exp, entries: granted }
70
71
  const write = { signSecret: toBase64(signing.signSecret), cert }
71
72
  const identity = await generateX25519Identity()
72
73
  const sealed = await seal([await identityToRecipient(identity)], utf8(JSON.stringify({ ...bundle, write })))
@@ -75,27 +76,51 @@ export async function issueSealedGrant(vault: Vault, request: SealedRequest): Pr
75
76
  mode: 'sealed',
76
77
  grant: id,
77
78
  label: request.label,
78
- groups: request.groups,
79
+ tiers: request.tiers,
79
80
  entries: granted.map((value) => value.name),
80
81
  })
81
82
  return `${PREFIX}${toBase64Url(utf8(identity))}.${toBase64Url(sealed)}`
82
83
  }
83
84
 
85
+ /** The key of a tier this member holds that reaches every one of `tiers`, to sign the grant's certificate. */
86
+ async function memberTierKey(vault: Vault, tiers: readonly string[]): Promise<SecretKey | undefined> {
87
+ const held = vault.member === undefined ? [] : (vault.state.members[vault.member]?.tiers ?? [])
88
+ for (const tier of held) {
89
+ if (!tiers.every((wanted) => reach(vault.state.tiers, tier).has(wanted))) continue
90
+ const key = await vault.keyring.unlock(tier)
91
+ if (key !== undefined) return key
92
+ }
93
+ return undefined
94
+ }
95
+
84
96
  /** Opens `tvg1:...` or `@/path/to/file` holding one. */
85
97
  export async function readSealedGrant(raw: string): Promise<SealedBundle> {
86
- const text = (raw.startsWith('@') ? readFileSync(raw.slice(1), 'utf8') : raw).trim()
87
- const [identity, ciphertext] = text.slice(PREFIX.length).split('.')
88
- if (!text.startsWith(PREFIX) || identity === undefined || ciphertext === undefined) {
89
- throw new TypeVaultError('invalid', 'not a sealed typevault grant')
98
+ let text = raw
99
+ if (raw.startsWith('@')) {
100
+ try {
101
+ text = readFileSync(raw.slice(1), 'utf8')
102
+ } catch (error) {
103
+ if (!(error instanceof Error)) throw error
104
+ throw new TypeVaultError('invalid', `cannot read the sealed grant file "${raw.slice(1)}"`)
105
+ }
90
106
  }
91
- const plaintext = await unseal([fromUtf8(fromBase64Url(identity))], fromBase64Url(ciphertext))
92
- const parsed = BundleSchema.safeParse(JSON.parse(fromUtf8(plaintext)))
93
- if (!parsed.success) throw new TypeVaultError('invalid', 'malformed sealed grant')
94
- const { groups, only, entries, ...rest } = parsed.data
95
- return {
96
- ...rest,
97
- scope: { groups, only },
98
- entries: entries.map(toEntryValue),
107
+ try {
108
+ const token = text.trim()
109
+ const [identity, ciphertext, extra] = token.slice(PREFIX.length).split('.')
110
+ if (!token.startsWith(PREFIX) || !identity || !ciphertext || extra !== undefined) {
111
+ throw new TypeVaultError('invalid', 'not a sealed typevault grant')
112
+ }
113
+ const plaintext = await unseal([fromUtf8(fromBase64Url(identity))], fromBase64Url(ciphertext))
114
+ const parsed = BundleSchema.parse(JSON.parse(fromUtf8(plaintext)))
115
+ const { tiers, only, entries, ...rest } = parsed
116
+ return {
117
+ ...rest,
118
+ scope: { tiers, only },
119
+ entries: entries.map(toEntryValue),
120
+ }
121
+ } catch (error) {
122
+ if (!(error instanceof Error)) throw error
123
+ throw new TypeVaultError('invalid', 'TYPEVAULT_GRANT is not a sealed typevault grant')
99
124
  }
100
125
  }
101
126