typevault 0.1.0 → 0.2.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 (72) 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 +7 -7
  7. package/src/access/scoped.ts +100 -44
  8. package/src/access/sealed-access.ts +45 -23
  9. package/src/access/sealed.ts +33 -21
  10. package/src/access/types.ts +25 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +14 -9
  13. package/src/cli/commands/admin.ts +87 -47
  14. package/src/cli/commands/daemon.ts +33 -15
  15. package/src/cli/commands/entries.ts +166 -55
  16. package/src/cli/commands/grant.ts +12 -20
  17. package/src/cli/commands/members.ts +281 -0
  18. package/src/cli/commands/run.ts +61 -24
  19. package/src/cli/context.ts +155 -15
  20. package/src/cli/index.ts +27 -4
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +65 -0
  23. package/src/core/admin.ts +125 -74
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +9 -9
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +6 -0
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +84 -0
  31. package/src/core/identity.ts +130 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/keyring.ts +100 -56
  34. package/src/core/layout.ts +145 -26
  35. package/src/core/lock.ts +128 -16
  36. package/src/core/naming.ts +146 -49
  37. package/src/core/password.ts +111 -0
  38. package/src/core/payload.ts +42 -38
  39. package/src/core/revisions.ts +8 -4
  40. package/src/core/rotate.ts +59 -42
  41. package/src/core/state.ts +88 -48
  42. package/src/core/txn.ts +5 -4
  43. package/src/core/vault.ts +108 -46
  44. package/src/core/worktrees.ts +39 -0
  45. package/src/daemon/admin-routes.ts +33 -21
  46. package/src/daemon/agent-routes.ts +29 -11
  47. package/src/daemon/client.ts +15 -0
  48. package/src/daemon/daemon.ts +210 -32
  49. package/src/daemon/grants.ts +21 -4
  50. package/src/daemon/http.ts +3 -0
  51. package/src/daemon/live-access.ts +4 -4
  52. package/src/daemon/protocol.ts +17 -12
  53. package/src/daemon/requests.ts +17 -22
  54. package/src/daemon/spawn.ts +188 -9
  55. package/src/export/1password.ts +157 -0
  56. package/src/import/1password-live.ts +399 -0
  57. package/src/import/1password.ts +26 -5
  58. package/src/import/bitwarden.ts +3 -3
  59. package/src/import/csv.ts +1 -1
  60. package/src/import/dotenv.ts +2 -2
  61. package/src/import/index.ts +1 -0
  62. package/src/import/keepass.ts +2 -2
  63. package/src/import/lastpass.ts +2 -2
  64. package/src/import/shared.ts +67 -10
  65. package/src/import/typeclaw.ts +2 -2
  66. package/src/import/types.ts +1 -1
  67. package/src/index.ts +58 -0
  68. package/src/owner.ts +156 -0
  69. package/src/prompt/browser.ts +48 -15
  70. package/src/prompt/page.ts +19 -11
  71. package/src/prompt/styles.ts +64 -34
  72. package/src/prompt/types.ts +3 -3
package/src/core/state.ts CHANGED
@@ -9,92 +9,131 @@ import { atomicWrite } from './fsx'
9
9
  import type { Layout } from './layout'
10
10
  import { RevisionMarks } from './revisions'
11
11
 
12
- export type Group = {
12
+ export type Tier = {
13
13
  readonly includes: readonly string[]
14
14
  readonly gen: number
15
15
  readonly recipient: string
16
16
  readonly signPublic: string
17
17
  }
18
- export type Signer = { readonly signPublic: string; readonly groups: readonly string[] }
19
- export type Groups = Readonly<Record<string, Group>>
18
+ export type Signer = { readonly signPublic: string; readonly tiers: readonly string[] }
19
+ export type Tiers = Readonly<Record<string, Tier>>
20
20
 
21
- /** Everything public about a vault. Groups, signers and ceilings are signed by the operator key. */
22
- export type ManifestSeqs = { readonly groups: number; readonly signers: number; readonly ceilings: number }
21
+ /** A person (unlocks with a password) or a machine (holds its key directly). */
22
+ export type MemberKind = 'human' | 'machine'
23
+ export type Member = {
24
+ readonly kind: MemberKind
25
+ readonly recipient: string
26
+ readonly signPublic: string
27
+ /** Owners get the owner key wrapped to them. */
28
+ readonly owner: boolean
29
+ /** Tiers whose key is wrapped to this member. */
30
+ readonly tiers: readonly string[]
31
+ }
32
+ export type Members = Readonly<Record<string, Member>>
33
+
34
+ /** Everything public about a vault. Tiers, members, signers and ceilings are signed by the owner key. */
35
+ export type ManifestSeqs = {
36
+ readonly tiers: number
37
+ readonly members: number
38
+ readonly signers: number
39
+ readonly ceilings: number
40
+ }
23
41
 
24
42
  export type VaultState = {
25
- readonly operator: PublicKey
43
+ readonly owner: PublicKey
26
44
  /** Each manifest's sequence number: every signed change bumps it, and a lower one is a rollback. */
27
45
  readonly seqs: ManifestSeqs
28
- readonly groups: Groups
46
+ readonly tiers: Tiers
47
+ readonly members: Members
29
48
  readonly signers: Readonly<Record<string, Signer>>
30
49
  readonly ceilings: Readonly<Record<string, string>>
31
50
  }
32
51
 
33
- const GROUP_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
34
- export function parseGroupName(name: string): string {
35
- if (!GROUP_NAME.test(name)) throw new TypeVaultError('invalid', `invalid group name "${name}" (use [a-z0-9-])`)
52
+ const TIER_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
53
+ export function parseTierName(name: string): string {
54
+ if (!TIER_NAME.test(name)) throw new TypeVaultError('invalid', `invalid tier name "${name}" (use [a-z0-9-])`)
55
+ return name
56
+ }
57
+
58
+ export function parseMemberName(name: string): string {
59
+ if (!TIER_NAME.test(name)) throw new TypeVaultError('invalid', `invalid member name "${name}" (use [a-z0-9-])`)
36
60
  return name
37
61
  }
38
62
 
39
63
  const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
40
- const GroupSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
64
+ const TierSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
41
65
  const seq = z.number().int().positive()
42
- const GroupsBody = z.object({ v: z.literal(1), seq, groups: z.record(z.string(), GroupSchema) })
66
+ const TiersBody = z.object({ v: z.literal(1), seq, tiers: z.record(z.string(), TierSchema) })
67
+ const MembersBody = z.object({
68
+ v: z.literal(1),
69
+ seq,
70
+ members: z.record(
71
+ z.string(),
72
+ PublicKeySchema.extend({
73
+ kind: z.enum(['human', 'machine']),
74
+ owner: z.boolean(),
75
+ tiers: z.array(z.string()),
76
+ }),
77
+ ),
78
+ })
43
79
  const SignersBody = z.object({
44
80
  v: z.literal(1),
45
81
  seq,
46
- signers: z.record(z.string(), z.object({ signPublic: z.string(), groups: z.array(z.string()) })),
82
+ signers: z.record(z.string(), z.object({ signPublic: z.string(), tiers: z.array(z.string()) })),
47
83
  })
48
84
  const CeilingsBody = z.object({ v: z.literal(1), seq, ceilings: z.record(z.string(), z.string()) })
49
- const TrustSchema = z.object({ operatorSignPublic: z.string() })
85
+ const TrustSchema = z.object({ ownerSignPublic: z.string() })
50
86
 
51
87
  export const signedDoc = (body: Json, key: SecretKey): string =>
52
88
  `${JSON.stringify({ body, sig: sign(key.signSecret, utf8(canonicalJson(body))) }, null, 2)}\n`
53
89
 
54
- export const groupsDoc = (groups: Groups, key: SecretKey, seq: number): string => signedDoc({ v: 1, seq, groups }, key)
90
+ export const tiersDoc = (tiers: Tiers, key: SecretKey, seq: number): string => signedDoc({ v: 1, seq, tiers }, key)
91
+ export const membersDoc = (members: Members, key: SecretKey, seq: number): string =>
92
+ signedDoc({ v: 1, seq, members }, key)
55
93
  export const signersDoc = (signers: VaultState['signers'], key: SecretKey, seq: number): string =>
56
94
  signedDoc({ v: 1, seq, signers }, key)
57
95
  export const ceilingsDoc = (ceilings: VaultState['ceilings'], key: SecretKey, seq: number): string =>
58
96
  signedDoc({ v: 1, seq, ceilings }, key)
59
97
 
60
- function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, operator: PublicKey): T {
98
+ function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: PublicKey): T {
61
99
  const doc = z.object({ body: z.json(), sig: z.string() }).parse(JSON.parse(fromUtf8(readFileSync(path))))
62
- if (!verifySignature(operator.signPublic, utf8(canonicalJson(doc.body)), doc.sig)) {
63
- throw new TypeVaultError('tampered', `${path} is not signed by the vault operator`)
100
+ if (!verifySignature(owner.signPublic, utf8(canonicalJson(doc.body)), doc.sig)) {
101
+ throw new TypeVaultError('tampered', `${path} is not signed by the vault owner`)
64
102
  }
65
103
  return schema.parse(doc.body)
66
104
  }
67
105
 
68
- /** The operator key is trusted on first use (or pinned via TYPEVAULT_OPERATOR); a changed key is tampering. */
69
- function checkTrust(layout: Layout, operator: PublicKey, env: Readonly<Record<string, string | undefined>>): void {
70
- const pinned = env['TYPEVAULT_OPERATOR']
106
+ /** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
107
+ function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<string, string | undefined>>): void {
108
+ const pinned = env['TYPEVAULT_OWNER']
71
109
  if (pinned !== undefined && pinned !== '') {
72
- if (pinned !== operator.signPublic)
73
- throw new TypeVaultError('tampered', 'vault operator does not match TYPEVAULT_OPERATOR')
110
+ if (pinned !== owner.signPublic) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
74
111
  return
75
112
  }
76
113
  if (!existsSync(layout.trustFile)) {
77
- atomicWrite(layout.trustFile, JSON.stringify({ operatorSignPublic: operator.signPublic }), 0o600)
114
+ atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
78
115
  return
79
116
  }
80
117
  const trust = TrustSchema.parse(JSON.parse(fromUtf8(readFileSync(layout.trustFile))))
81
- if (trust.operatorSignPublic !== operator.signPublic) {
82
- throw new TypeVaultError('tampered', 'vault operator key changed since this machine first trusted it')
118
+ if (trust.ownerSignPublic !== owner.signPublic) {
119
+ throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
83
120
  }
84
121
  }
85
122
 
86
123
  export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
87
- if (!existsSync(layout.operatorFile))
88
- throw new TypeVaultError('not_found', `no vault at ${layout.root} (run typevault init)`)
89
- const operator = PublicKeySchema.parse(JSON.parse(fromUtf8(readFileSync(layout.operatorFile))))
90
- checkTrust(layout, operator, env)
91
- const groups = readSigned(layout.groupsFile, GroupsBody, operator)
92
- const signers = readSigned(layout.signersFile, SignersBody, operator)
93
- const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, operator)
124
+ if (!existsSync(layout.ownerFile))
125
+ throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
126
+ const owner = PublicKeySchema.parse(JSON.parse(fromUtf8(readFileSync(layout.ownerFile))))
127
+ checkTrust(layout, owner, env)
128
+ const tiers = readSigned(layout.tiersFile, TiersBody, owner)
129
+ const members = readSigned(layout.membersFile, MembersBody, owner)
130
+ const signers = readSigned(layout.signersFile, SignersBody, owner)
131
+ const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, owner)
94
132
  // An older, still validly signed manifest from git history would resurrect removed signers or ceilings.
95
133
  const marks = new RevisionMarks(layout.revisionsFile)
96
134
  for (const [name, doc] of [
97
- ['groups', groups],
135
+ ['tiers', tiers],
136
+ ['members', members],
98
137
  ['signers', signers],
99
138
  ['ceilings', ceilings],
100
139
  ] as const) {
@@ -107,30 +146,31 @@ export function loadState(layout: Layout, env: Readonly<Record<string, string |
107
146
  }
108
147
  marks.save()
109
148
  return {
110
- operator,
111
- seqs: { groups: groups.seq, signers: signers.seq, ceilings: ceilings.seq },
112
- groups: groups.groups,
149
+ owner,
150
+ seqs: { tiers: tiers.seq, members: members.seq, signers: signers.seq, ceilings: ceilings.seq },
151
+ tiers: tiers.tiers,
152
+ members: members.members,
113
153
  signers: signers.signers,
114
154
  ceilings: ceilings.ceilings,
115
155
  }
116
156
  }
117
157
 
118
- /** Every group `name` reaches through includes, itself included. */
119
- export function reach(groups: Groups, name: string): ReadonlySet<string> {
158
+ /** Every tier `name` reaches through includes, itself included. */
159
+ export function reach(tiers: Tiers, name: string): ReadonlySet<string> {
120
160
  const seen = new Set<string>()
121
- const visit = (group: string): void => {
122
- if (seen.has(group)) return
123
- seen.add(group)
124
- for (const included of groups[group]?.includes ?? []) visit(included)
161
+ const visit = (tier: string): void => {
162
+ if (seen.has(tier)) return
163
+ seen.add(tier)
164
+ for (const included of tiers[tier]?.includes ?? []) visit(included)
125
165
  }
126
166
  visit(name)
127
167
  return seen
128
168
  }
129
169
 
130
- export const reachesGroup = (groups: Groups, from: readonly string[], target: string): boolean =>
131
- from.some((group) => group === '*' || reach(groups, group).has(target))
170
+ export const reachesTier = (tiers: Tiers, from: readonly string[], target: string): boolean =>
171
+ from.some((tier) => tier === '*' || reach(tiers, tier).has(target))
132
172
 
133
- export const includersOf = (groups: Groups, name: string): readonly string[] =>
134
- Object.entries(groups)
135
- .filter(([, group]) => group.includes.includes(name))
173
+ export const includersOf = (tiers: Tiers, name: string): readonly string[] =>
174
+ Object.entries(tiers)
175
+ .filter(([, tier]) => tier.includes.includes(name))
136
176
  .map(([includer]) => includer)
package/src/core/txn.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from 'node:fs'
1
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
2
2
  import { dirname, isAbsolute, join, normalize, sep } from 'node:path'
3
3
 
4
4
  import { z } from 'zod'
@@ -14,7 +14,7 @@ const ManifestSchema = z.object({ puts: z.array(z.string()), removes: z.array(z.
14
14
 
15
15
  /**
16
16
  * A batch of vault file changes that lands all-or-nothing. Puts apply in insertion order and
17
- * removes after them, so a caller flips a pointer file (groups.json) by putting it last.
17
+ * removes after them, so a caller flips a pointer file (tiers.json) by putting it last.
18
18
  * Mutable on purpose: it accumulates changes until `commitTxn`.
19
19
  */
20
20
  export class Txn {
@@ -70,8 +70,9 @@ function applyTxn(layout: Layout, dir: string): void {
70
70
  if (!existsSync(staged)) return
71
71
  assertNoSymlinks(layout.vault, checkRel(rel))
72
72
  const target = join(layout.vault, checkRel(rel))
73
- mkdirSync(dirname(target), { recursive: true })
74
- renameSync(staged, target)
73
+ // Staging (run/) and the vault may sit on different filesystems, where rename fails: write the bytes in place.
74
+ atomicWrite(target, readFileSync(staged))
75
+ rmSync(staged)
75
76
  touched.add(dirname(target))
76
77
  })
77
78
  for (const rel of manifest.removes) {
package/src/core/vault.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { existsSync, lstatSync, readdirSync, readFileSync, rmSync } from 'node:fs'
2
- import { join } from 'node:path'
2
+ import { basename, dirname, join } from 'node:path'
3
3
 
4
4
  import { randomHex, type SecretKey } from './crypto'
5
5
  import { fromUtf8 } from './encoding'
@@ -10,18 +10,21 @@ import {
10
10
  openEntry,
11
11
  sealEntry,
12
12
  signCiphertext,
13
+ certEntryId,
13
14
  type SignerContext,
15
+ type SignerRef,
14
16
  verifyEnvelope,
15
17
  } from './entries'
16
18
  import { TypeVaultError } from './errors'
17
19
  import { assertNoSymlinks, atomicWrite, fsyncDir } from './fsx'
18
- import { Keyring } from './keyring'
19
- import { type Layout, layoutOf } from './layout'
20
+ import { refuseForeignDaemon } from './holder'
21
+ import { heldMembers, Keyring, unwrapOwner } from './keyring'
22
+ import type { Layout } from './layout'
20
23
  import { withLock } from './lock'
21
- import type { EntryName, EntryType } from './naming'
24
+ import type { EntryName, Field } from './naming'
22
25
  import type { EntryPayload } from './payload'
23
26
  import { RevisionMarks } from './revisions'
24
- import { type Groups, loadState, reach, type VaultState } from './state'
27
+ import { type Tiers, loadState, reach, type VaultState } from './state'
25
28
  import { commitTxn, recoverTxns, Txn } from './txn'
26
29
 
27
30
  export type StoredEntry = { readonly envelope: Envelope; readonly payload: EntryPayload }
@@ -40,9 +43,8 @@ export type PutOptions = { readonly ifRev?: number; readonly base?: EntryBase }
40
43
 
41
44
  export type EntryInput = {
42
45
  readonly name: EntryName
43
- readonly type: EntryType
44
- readonly fields: Readonly<Record<string, string>>
45
- readonly group: string
46
+ readonly fields: Readonly<Record<string, Field>>
47
+ readonly tier: string
46
48
  readonly env?: string
47
49
  readonly origin?: string
48
50
  readonly tags?: readonly string[]
@@ -59,24 +61,24 @@ function parseJson(bytes: Uint8Array): unknown {
59
61
  }
60
62
  }
61
63
 
62
- const sameFields = (a: Readonly<Record<string, string>>, b: Readonly<Record<string, string>>): boolean =>
64
+ const sameFields = (a: Readonly<Record<string, Field>>, b: Readonly<Record<string, Field>>): boolean =>
63
65
  JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort())
64
66
 
65
67
  /**
66
- * The entry a name means when several files carry it. A copy in a group that reaches the other's group wins, so a
67
- * lower group can never shadow a higher one (timestamps are writer-chosen and never decide). Within one group the
68
- * higher revision wins. Copies in groups neither reaches are a conflict for `doctor`.
68
+ * The entry a name means when several files carry it. A copy in a tier that reaches the other's tier wins, so a
69
+ * lower tier can never shadow a higher one (timestamps are writer-chosen and never decide). Within one tier the
70
+ * higher revision wins. Copies in tiers neither reaches are a conflict for `doctor`.
69
71
  */
70
- export function resolveName(groups: Groups, copies: readonly StoredEntry[]): StoredEntry | undefined {
72
+ export function resolveName(tiers: Tiers, copies: readonly StoredEntry[]): StoredEntry | undefined {
71
73
  return copies.reduce<StoredEntry | undefined>((best, entry) => {
72
74
  if (best === undefined) return entry
73
75
  const [a, b] = [best.envelope, entry.envelope]
74
- if (a.group === b.group) return b.rev > a.rev || (b.rev === a.rev && b.id > a.id) ? entry : best
75
- if (reach(groups, a.group).has(b.group)) return best
76
- if (reach(groups, b.group).has(a.group)) return entry
76
+ if (a.tier === b.tier) return b.rev > a.rev || (b.rev === a.rev && b.id > a.id) ? entry : best
77
+ if (reach(tiers, a.tier).has(b.tier)) return best
78
+ if (reach(tiers, b.tier).has(a.tier)) return entry
77
79
  throw new TypeVaultError(
78
80
  'conflict',
79
- `${entry.payload.name} exists in unrelated groups "${a.group}" and "${b.group}" (run typevault doctor)`,
81
+ `${entry.payload.name} exists in unrelated tiers "${a.tier}" and "${b.tier}" (run typevault doctor)`,
80
82
  )
81
83
  }, undefined)
82
84
  }
@@ -86,23 +88,30 @@ export class Vault {
86
88
  readonly layout: Layout
87
89
  readonly #keys: readonly SecretKey[]
88
90
  readonly #env: Env
91
+ readonly #member: string | undefined
89
92
  #state: VaultState
90
93
  #keyring: Keyring
91
94
 
92
- private constructor(layout: Layout, keys: readonly SecretKey[], env: Env) {
95
+ private constructor(layout: Layout, keys: readonly SecretKey[], env: Env, state: VaultState, member?: string) {
93
96
  this.layout = layout
94
97
  this.#keys = keys
95
98
  this.#env = env
96
- this.#state = loadState(layout, env)
97
- this.#keyring = new Keyring(layout, this.#state, keys)
99
+ this.#member = member
100
+ this.#state = state
101
+ this.#keyring = new Keyring(layout, state, keys)
98
102
  }
99
103
 
100
- static async open(root: string, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
101
- const layout = layoutOf(root)
104
+ /** Opens the vault with `keys`. An owner member's key also brings the owner key it unwraps. */
105
+ static async open(layout: Layout, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
106
+ refuseForeignDaemon(layout, env)
102
107
  if (existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0) {
103
108
  await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
104
109
  }
105
- return new Vault(layout, keys, env)
110
+ const state = loadState(layout, env)
111
+ const owner = await unwrapOwner(layout, state, keys)
112
+ const [member] = await heldMembers(state, keys)
113
+ const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
114
+ return new Vault(layout, all, env, state, member?.name)
106
115
  }
107
116
 
108
117
  get state(): VaultState {
@@ -117,7 +126,12 @@ export class Vault {
117
126
  return this.#keys
118
127
  }
119
128
 
120
- /** Re-reads operator-signed state; call after another process may have changed it. */
129
+ /** The member this process acts as, when it holds a member key the vault lists. */
130
+ get member(): string | undefined {
131
+ return this.#member
132
+ }
133
+
134
+ /** Re-reads owner-signed state; call after another process may have changed it. */
121
135
  refresh(): void {
122
136
  this.#state = loadState(this.layout, this.#env)
123
137
  this.#keyring = new Keyring(this.layout, this.#state, this.#keys)
@@ -129,7 +143,7 @@ export class Vault {
129
143
  this.refresh()
130
144
  const entries: StoredEntry[] = []
131
145
  const problems: ScanProblem[] = []
132
- assertNoSymlinks(this.layout.root, 'vault/entries')
146
+ assertNoSymlinks(dirname(this.layout.vault), join(basename(this.layout.vault), 'entries'))
133
147
  const files = existsSync(this.layout.entries) ? readdirSync(this.layout.entries) : []
134
148
  const marks = new RevisionMarks(this.layout.revisionsFile)
135
149
  for (const file of files.filter(
@@ -148,7 +162,13 @@ export class Vault {
148
162
  problems.push({ file, reason })
149
163
  continue
150
164
  }
151
- if (!marks.accept(parsed.data.id, parsed.data.rev)) {
165
+ // Accepting expired certificates must not move the marks: a backdated high revision nobody adopts would
166
+ // otherwise lock out the trusted one.
167
+ const current =
168
+ options.acceptExpiredCerts === true
169
+ ? marks.allows(parsed.data.id, parsed.data.rev)
170
+ : marks.accept(parsed.data.id, parsed.data.rev)
171
+ if (!current) {
152
172
  problems.push({ file, reason: `revision ${parsed.data.rev} was replaced or deleted on this machine` })
153
173
  continue
154
174
  }
@@ -178,7 +198,7 @@ export class Vault {
178
198
  async find(name: EntryName): Promise<StoredEntry | undefined> {
179
199
  const { entries } = await this.scan()
180
200
  return resolveName(
181
- this.#state.groups,
201
+ this.#state.tiers,
182
202
  entries.filter((entry) => entry.payload.name === name),
183
203
  )
184
204
  }
@@ -200,7 +220,6 @@ export class Vault {
200
220
  const payload: EntryPayload = {
201
221
  v: 1,
202
222
  name: input.name,
203
- type: input.type,
204
223
  fields: input.fields,
205
224
  tags: input.tags ?? found?.payload.tags ?? [],
206
225
  created: prior?.created ?? now,
@@ -209,7 +228,8 @@ export class Vault {
209
228
  ...(input.origin === undefined ? {} : { origin: input.origin }),
210
229
  ...(changed || found?.payload.needsRotation !== true ? {} : { needsRotation: true }),
211
230
  }
212
- const draft = { id: prior?.id ?? randomHex(16), group: input.group, rev: currentRev + 1, at: now, payload }
231
+ const id = entryIdIn(signer.ref, input.tier, input.name, prior?.id)
232
+ const draft = { id, tier: input.tier, rev: currentRev + 1, at: now, payload }
213
233
  return { envelope: await sealEntry(draft, this.#state, signer), payload }
214
234
  }
215
235
 
@@ -219,11 +239,16 @@ export class Vault {
219
239
  */
220
240
  put(input: EntryInput, signer: SignerContext, options: PutOptions = {}): Promise<StoredEntry> {
221
241
  return withLock(this.layout.lockFile, 'exclusive', async () => {
222
- const stored = await this.#draft(input, await this.find(input.name), options, signer)
242
+ const found = await this.find(input.name)
243
+ const stored = await this.#draft(input, found, options, signer)
223
244
  atomicWrite(
224
245
  join(this.layout.entries, `${stored.envelope.id}.json`),
225
246
  `${JSON.stringify(stored.envelope, null, 2)}\n`,
226
247
  )
248
+ // A certificate may only replace the files it was issued with, never delete another one.
249
+ if (found !== undefined && found.envelope.id !== stored.envelope.id && signer.ref.kind !== 'cert') {
250
+ this.#unlink(found.envelope.id)
251
+ }
227
252
  return stored
228
253
  })
229
254
  }
@@ -231,33 +256,40 @@ export class Vault {
231
256
  /** Writes many entries as one transaction (an import): all of them land, or none do. */
232
257
  putMany(
233
258
  inputs: readonly EntryInput[],
234
- signerFor: (group: string) => Promise<SignerContext>,
259
+ signerFor: (tier: string) => Promise<SignerContext>,
235
260
  ): Promise<readonly StoredEntry[]> {
236
261
  return withLock(this.layout.lockFile, 'exclusive', async () => {
237
262
  const { entries } = await this.scan()
238
263
  const txn = new Txn()
239
264
  const stored: StoredEntry[] = []
265
+ const retiered: string[] = []
240
266
  for (const input of inputs) {
241
267
  const found = resolveName(
242
- this.#state.groups,
268
+ this.#state.tiers,
243
269
  entries.filter((entry) => entry.payload.name === input.name),
244
270
  )
245
- const entry = await this.#draft(input, found, {}, await signerFor(input.group))
271
+ const signer = await signerFor(input.tier)
272
+ const entry = await this.#draft(input, found, {}, signer)
246
273
  txn.put(`entries/${entry.envelope.id}.json`, `${JSON.stringify(entry.envelope, null, 2)}\n`)
274
+ if (found !== undefined && found.envelope.id !== entry.envelope.id && signer.ref.kind !== 'cert') {
275
+ txn.remove(`entries/${found.envelope.id}.json`)
276
+ retiered.push(found.envelope.id)
277
+ }
247
278
  stored.push(entry)
248
279
  }
249
280
  commitTxn(this.layout, txn)
281
+ for (const id of retiered) this.#tombstone(id)
250
282
  return stored
251
283
  })
252
284
  }
253
285
 
254
- /** Removes the entry `name` resolves to, or the copy in `group` (how a cross-group conflict is settled). */
255
- remove(name: EntryName, group?: string): Promise<StoredEntry> {
286
+ /** Removes the entry `name` resolves to, or the copy in `tier` (how a cross-tier conflict is settled). */
287
+ remove(name: EntryName, tier?: string): Promise<StoredEntry> {
256
288
  return withLock(this.layout.lockFile, 'exclusive', async () => {
257
289
  const existing =
258
- group === undefined
290
+ tier === undefined
259
291
  ? await this.find(name)
260
- : (await this.scan()).entries.find((entry) => entry.payload.name === name && entry.envelope.group === group)
292
+ : (await this.scan()).entries.find((entry) => entry.payload.name === name && entry.envelope.tier === tier)
261
293
  if (existing === undefined) throw new TypeVaultError('not_found', `no entry named ${name}`)
262
294
  rmSync(join(this.layout.entries, `${existing.envelope.id}.json`))
263
295
  fsyncDir(this.layout.entries)
@@ -267,38 +299,68 @@ export class Vault {
267
299
  }
268
300
 
269
301
  /** Stores a payload encrypted elsewhere under `name`, replacing any entry of that name. */
270
- putCiphertext(name: EntryName, group: string, ciphertext: Uint8Array, signer: SignerContext): Promise<Envelope> {
302
+ putCiphertext(name: EntryName, tier: string, ciphertext: Uint8Array, signer: SignerContext): Promise<Envelope> {
271
303
  return withLock(this.layout.lockFile, 'exclusive', async () => {
272
304
  const existing = await this.find(name)
273
- const draft = { id: existing?.envelope.id ?? randomHex(16), group, rev: (existing?.envelope.rev ?? 0) + 1 }
305
+ const id = entryIdIn(signer.ref, tier, name, existing?.envelope.id)
306
+ const draft = { id, tier, rev: (existing?.envelope.rev ?? 0) + 1 }
274
307
  const envelope = signCiphertext({ ...draft, at: new Date().toISOString() }, ciphertext, this.#state, signer)
275
308
  atomicWrite(join(this.layout.entries, `${envelope.id}.json`), `${JSON.stringify(envelope, null, 2)}\n`)
309
+ if (existing !== undefined && existing.envelope.id !== envelope.id && signer.ref.kind !== 'cert') {
310
+ this.#unlink(existing.envelope.id)
311
+ }
276
312
  return envelope
277
313
  })
278
314
  }
279
315
 
280
- /** Deletes an entry file by id, for writers that can't read the entry (sealed grants). */
281
- removeById(id: string): Promise<void> {
316
+ /**
317
+ * Deletes an entry file by id, for writers that can't read the entry (sealed grants).
318
+ * `allows` judges the verified envelope under the lock; the file stays unless it returns true.
319
+ */
320
+ removeById(id: string, allows: (envelope: Envelope) => boolean): Promise<void> {
282
321
  return withLock(this.layout.lockFile, 'exclusive', async () => {
283
- if (!/^[0-9a-f]{32}$/.test(id)) throw new TypeVaultError('invalid', 'invalid entry id')
322
+ if (!EnvelopeSchema.shape.id.safeParse(id).success) throw new TypeVaultError('invalid', 'invalid entry id')
323
+ this.refresh()
284
324
  const path = join(this.layout.entries, `${id}.json`)
285
325
  if (!existsSync(path)) throw new TypeVaultError('not_found', 'entry is already gone')
286
- rmSync(path)
287
- fsyncDir(this.layout.entries)
288
- this.#tombstone(id)
326
+ const parsed = EnvelopeSchema.safeParse(parseJson(readFileSync(path)))
327
+ if (!parsed.success || parsed.data.id !== id || verifyEnvelope(parsed.data, this.#state) !== undefined) {
328
+ throw new TypeVaultError('denied', 'refusing to remove an entry file that does not verify')
329
+ }
330
+ if (!allows(parsed.data)) throw new TypeVaultError('denied', 'this grant cannot remove that entry')
331
+ this.#unlink(id)
289
332
  })
290
333
  }
291
334
 
335
+ #unlink(id: string): void {
336
+ rmSync(join(this.layout.entries, `${id}.json`))
337
+ fsyncDir(this.layout.entries)
338
+ this.#tombstone(id)
339
+ }
340
+
292
341
  move(from: EntryName, to: EntryName, signer: SignerContext): Promise<StoredEntry> {
293
342
  return withLock(this.layout.lockFile, 'exclusive', async () => {
294
343
  const existing = await this.find(from)
295
344
  if (existing === undefined) throw new TypeVaultError('not_found', `no entry named ${from}`)
296
345
  if ((await this.find(to)) !== undefined) throw new TypeVaultError('conflict', `${to} already exists`)
297
346
  const payload = { ...existing.payload, name: to }
298
- const draft = { id: existing.envelope.id, group: existing.envelope.group, rev: existing.envelope.rev + 1 }
347
+ const { tier } = existing.envelope
348
+ // A fresh id: a grant issued for the old name lists the old one, and must not follow the entry to its new name.
349
+ const draft = { id: entryIdIn(signer.ref, tier, to, undefined), tier, rev: existing.envelope.rev + 1 }
299
350
  const envelope = await sealEntry({ ...draft, at: new Date().toISOString(), payload }, this.#state, signer)
300
351
  atomicWrite(join(this.layout.entries, `${envelope.id}.json`), `${JSON.stringify(envelope, null, 2)}\n`)
352
+ this.#unlink(existing.envelope.id)
301
353
  return { envelope, payload }
302
354
  })
303
355
  }
304
356
  }
357
+
358
+ /**
359
+ * An entry keeps its id only within its tier: the id names the tier (see `verifyEnvelope`), so a retier mints a new one.
360
+ * A certificate keeps only an id it was issued with; a blind writer's `current` comes from a holder-editable bundle.
361
+ */
362
+ const entryIdIn = (signer: SignerRef, tier: string, name: string, current: string | undefined): string => {
363
+ const kept = current?.startsWith(`${tier}.`) === true ? current : undefined
364
+ if (signer.kind !== 'cert') return kept ?? `${tier}.${randomHex(16)}`
365
+ return kept !== undefined && signer.cert.ids.includes(kept) ? kept : certEntryId(signer.cert, tier, name)
366
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync, realpathSync } from 'node:fs'
2
+ import { dirname, join, relative } from 'node:path'
3
+
4
+ /** git's own variables (set inside hooks, say) would point it at another repository than the vault's. */
5
+ const gitEnv = (): Record<string, string | undefined> =>
6
+ Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')))
7
+
8
+ async function git(cwd: string, args: readonly string[]): Promise<string | undefined> {
9
+ let proc: Bun.Subprocess<'ignore', 'pipe', 'ignore'>
10
+ try {
11
+ proc = Bun.spawn(['git', ...args], { cwd, env: gitEnv(), stdin: 'ignore', stdout: 'pipe', stderr: 'ignore' })
12
+ } catch (error) {
13
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
14
+ throw error
15
+ }
16
+ const [code, output] = await Promise.all([proc.exited, new Response(proc.stdout).text()])
17
+ return code === 0 ? output : undefined
18
+ }
19
+
20
+ /**
21
+ * The same vault in every other worktree of the git repository `vault` is checked out in: the checkouts an unlocked
22
+ * session is shared between. Only worktrees the repository itself lists count, so a directory that merely copies the
23
+ * vault or clones the repository is never one.
24
+ */
25
+ export async function worktreeVaults(vault: string): Promise<readonly string[]> {
26
+ if (!existsSync(vault)) return []
27
+ const own = realpathSync(vault)
28
+ const top = (await git(dirname(own), ['rev-parse', '--show-toplevel']))?.trim()
29
+ if (top === undefined || top === '') return []
30
+ const path = relative(realpathSync(top), own)
31
+ const listed = (await git(dirname(own), ['worktree', 'list', '--porcelain'])) ?? ''
32
+ return listed
33
+ .split('\n')
34
+ .filter((line) => line.startsWith('worktree '))
35
+ .map((line) => join(line.slice('worktree '.length), path))
36
+ .filter((candidate) => existsSync(join(candidate, 'owner.json')))
37
+ .map((candidate) => realpathSync(candidate))
38
+ .filter((candidate) => candidate !== own)
39
+ }