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,23 +1,25 @@
1
1
  import { z } from 'zod'
2
2
 
3
- import { seal, type SecretKey, sign, unseal, verifySignature } from './crypto'
3
+ import { seal, type SecretKey, sha256Hex, sign, unseal, verifySignature } from './crypto'
4
4
  import { canonicalJson, fromBase64, type Json, toBase64, utf8 } from './encoding'
5
5
  import { TypeVaultError } from './errors'
6
6
  import type { Keyring } from './keyring'
7
7
  import { matchesOnly } from './naming'
8
8
  import { decodePayload, encodePayload, type EntryPayload } from './payload'
9
- import { reach, reachesGroup, type VaultState } from './state'
9
+ import { reach, reachesTier, type VaultState } from './state'
10
10
 
11
11
  const IssuerSchema = z.discriminatedUnion('kind', [
12
- z.object({ kind: z.literal('operator') }),
13
- z.object({ kind: z.literal('group'), group: z.string(), gen: z.number().int().positive() }),
12
+ z.object({ kind: z.literal('owner') }),
13
+ z.object({ kind: z.literal('tier'), tier: z.string(), gen: z.number().int().positive() }),
14
14
  z.object({ kind: z.literal('signer'), id: z.string() }),
15
15
  ])
16
16
  export const CertSchema = z.object({
17
17
  signPublic: z.string(),
18
- groups: z.array(z.string()),
19
- /** Name patterns the holder may write; empty means any name in its groups. */
18
+ tiers: z.array(z.string()),
19
+ /** Name patterns the holder may write; empty means any name in its tiers. */
20
20
  only: z.array(z.string()),
21
+ /** Ids of the entries the grant was issued with: the only existing files it may replace or remove. */
22
+ ids: z.array(z.string()),
21
23
  exp: z.iso.datetime(),
22
24
  issuer: IssuerSchema,
23
25
  sig: z.string(),
@@ -25,8 +27,8 @@ export const CertSchema = z.object({
25
27
  const SignerSchema = z.union([IssuerSchema, z.object({ kind: z.literal('cert'), cert: CertSchema })])
26
28
  export const EnvelopeSchema = z.object({
27
29
  v: z.literal(1),
28
- id: z.string().regex(/^[0-9a-f]{32}$/),
29
- group: z.string(),
30
+ id: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\.[0-9a-f]{32}$/),
31
+ tier: z.string(),
30
32
  gen: z.number().int().positive(),
31
33
  rev: z.number().int().positive(),
32
34
  at: z.iso.datetime(),
@@ -43,23 +45,25 @@ export type Envelope = z.infer<typeof EnvelopeSchema>
43
45
  /** Who signs a write: a reference other readers can check plus the matching signing secret. */
44
46
  export type SignerContext = { readonly ref: SignerRef; readonly signSecret: Uint8Array }
45
47
 
46
- export const signerOf = (key: SecretKey): SignerContext => ({
47
- ref:
48
- key.role.kind === 'operator' ? { kind: 'operator' } : { kind: 'group', group: key.role.group, gen: key.role.gen },
49
- signSecret: key.signSecret,
50
- })
48
+ export function signerOf(key: SecretKey): SignerContext {
49
+ const { role } = key
50
+ // A member key only opens wraps; writes are signed by the tier or owner key it unwraps.
51
+ if (role.kind === 'member') throw new TypeVaultError('denied', 'a member key cannot sign entries')
52
+ return {
53
+ ref: role.kind === 'owner' ? { kind: 'owner' } : { kind: 'tier', tier: role.tier, gen: role.gen },
54
+ signSecret: key.signSecret,
55
+ }
56
+ }
51
57
 
52
- type Authority = { readonly signPublic: string; readonly groups: readonly string[] }
58
+ type Authority = { readonly signPublic: string; readonly tiers: readonly string[] }
53
59
 
54
60
  function authorityOf(ref: IssuerRef, state: VaultState): Authority | undefined {
55
61
  switch (ref.kind) {
56
- case 'operator':
57
- return { signPublic: state.operator.signPublic, groups: ['*'] }
58
- case 'group': {
59
- const group = state.groups[ref.group]
60
- return group === undefined || group.gen !== ref.gen
61
- ? undefined
62
- : { signPublic: group.signPublic, groups: [ref.group] }
62
+ case 'owner':
63
+ return { signPublic: state.owner.signPublic, tiers: ['*'] }
64
+ case 'tier': {
65
+ const tier = state.tiers[ref.tier]
66
+ return tier === undefined || tier.gen !== ref.gen ? undefined : { signPublic: tier.signPublic, tiers: [ref.tier] }
63
67
  }
64
68
  case 'signer':
65
69
  return state.signers[ref.id]
@@ -72,12 +76,23 @@ function assertNever(value: never): never {
72
76
  throw new TypeVaultError('invalid', `unexpected value ${JSON.stringify(value)}`)
73
77
  }
74
78
 
79
+ /**
80
+ * The id a certificate writes a new entry under. Bound to the certificate and the name, so a holder can never aim a
81
+ * write at another entry's file: names are encrypted, so ids alone can't show which file holds what.
82
+ */
83
+ export const certEntryId = (cert: Cert, tier: string, name: string): string =>
84
+ `${tier}.${sha256Hex(utf8(`${cert.sig}\n${name}`)).slice(0, 32)}`
85
+
86
+ export const certMayHold = (cert: Cert, id: string, tier: string, name: string): boolean =>
87
+ cert.ids.includes(id) || id === certEntryId(cert, tier, name)
88
+
75
89
  const certBytes = (cert: Omit<Cert, 'sig'>): Uint8Array =>
76
90
  utf8(
77
91
  canonicalJson({
78
92
  signPublic: cert.signPublic,
79
- groups: cert.groups,
93
+ tiers: cert.tiers,
80
94
  only: cert.only,
95
+ ids: cert.ids,
81
96
  exp: cert.exp,
82
97
  issuer: cert.issuer,
83
98
  }),
@@ -90,37 +105,31 @@ export function issueCert(cert: Omit<Cert, 'sig' | 'issuer'>, issuer: SignerCont
90
105
  }
91
106
 
92
107
  const envelopeBytes = (envelope: Omit<Envelope, 'sig'>): Uint8Array => {
93
- const { v, id, group, gen, rev, at, payload, signer } = envelope
94
- const body: Json = { v, id, group, gen, rev, at, payload, signer }
108
+ const { v, id, tier, gen, rev, at, payload, signer } = envelope
109
+ const body: Json = { v, id, tier, gen, rev, at, payload, signer }
95
110
  return utf8(canonicalJson(body))
96
111
  }
97
112
 
98
- /** Whether `signer` may sign entries of `group`, judged only from operator-signed state. */
99
- /** `now` is the reader's clock for certificate expiry; `null` skips that one check (explicit operator adoption). */
113
+ /** Whether `signer` may sign entries of `tier`, judged only from owner-signed state. */
114
+ /** `now` is the reader's clock for certificate expiry; `null` skips that one check (explicit owner adoption). */
100
115
  export function signerAuthority(
101
116
  signer: SignerRef,
102
- group: string,
117
+ tier: string,
103
118
  state: VaultState,
104
119
  at: string,
105
120
  now: number | null = Date.now(),
106
121
  ): string | undefined {
107
122
  if (signer.kind !== 'cert') {
108
123
  const authority = authorityOf(signer, state)
109
- return authority !== undefined && reachesGroup(state.groups, authority.groups, group)
110
- ? authority.signPublic
111
- : undefined
124
+ return authority !== undefined && reachesTier(state.tiers, authority.tiers, tier) ? authority.signPublic : undefined
112
125
  }
113
126
  const { cert } = signer
114
127
  const issuer = authorityOf(cert.issuer, state)
115
128
  if (issuer === undefined || !verifySignature(issuer.signPublic, certBytes(cert), cert.sig)) return undefined
116
- if (!cert.groups.every((g) => reachesGroup(state.groups, issuer.groups, g))) return undefined
129
+ if (!cert.tiers.every((g) => reachesTier(state.tiers, issuer.tiers, g))) return undefined
117
130
  // Expiry is judged by the reader's clock: `at` is chosen by the holder, so it can't be trusted to bound it.
118
131
  const exp = Date.parse(cert.exp)
119
- if (
120
- !cert.groups.some((g) => reach(state.groups, g).has(group)) ||
121
- Date.parse(at) > exp ||
122
- (now !== null && now > exp)
123
- ) {
132
+ if (!cert.tiers.some((g) => reach(state.tiers, g).has(tier)) || Date.parse(at) > exp || (now !== null && now > exp)) {
124
133
  return undefined
125
134
  }
126
135
  return cert.signPublic
@@ -128,17 +137,17 @@ export function signerAuthority(
128
137
 
129
138
  export type EntryDraft = {
130
139
  readonly id: string
131
- readonly group: string
140
+ readonly tier: string
132
141
  readonly rev: number
133
142
  readonly at: string
134
143
  readonly payload: EntryPayload
135
144
  }
136
145
 
137
146
  export async function sealEntry(draft: EntryDraft, state: VaultState, signer: SignerContext): Promise<Envelope> {
138
- const group = state.groups[draft.group]
139
- if (group === undefined) throw new TypeVaultError('not_found', `no group "${draft.group}"`)
140
- const ciphertext = await seal([group.recipient, state.operator.recipient], encodePayload(draft.payload))
141
- return signCiphertext({ id: draft.id, group: draft.group, rev: draft.rev, at: draft.at }, ciphertext, state, signer)
147
+ const tier = state.tiers[draft.tier]
148
+ if (tier === undefined) throw new TypeVaultError('not_found', `no tier "${draft.tier}"`)
149
+ const ciphertext = await seal([tier.recipient, state.owner.recipient], encodePayload(draft.payload))
150
+ return signCiphertext({ id: draft.id, tier: draft.tier, rev: draft.rev, at: draft.at }, ciphertext, state, signer)
142
151
  }
143
152
 
144
153
  /** Signs an envelope around a payload that was encrypted elsewhere (the secret-prompt page encrypts in the browser). */
@@ -148,12 +157,12 @@ export function signCiphertext(
148
157
  state: VaultState,
149
158
  signer: SignerContext,
150
159
  ): Envelope {
151
- const group = state.groups[draft.group]
152
- if (group === undefined) throw new TypeVaultError('not_found', `no group "${draft.group}"`)
153
- if (signerAuthority(signer.ref, draft.group, state, draft.at) === undefined) {
154
- throw new TypeVaultError('denied', `this key cannot sign entries in group "${draft.group}"`)
160
+ const tier = state.tiers[draft.tier]
161
+ if (tier === undefined) throw new TypeVaultError('not_found', `no tier "${draft.tier}"`)
162
+ if (signerAuthority(signer.ref, draft.tier, state, draft.at) === undefined) {
163
+ throw new TypeVaultError('denied', `this key cannot sign entries in tier "${draft.tier}"`)
155
164
  }
156
- const unsigned = { v: 1 as const, id: draft.id, group: draft.group, gen: group.gen, rev: draft.rev, at: draft.at }
165
+ const unsigned = { v: 1 as const, id: draft.id, tier: draft.tier, gen: tier.gen, rev: draft.rev, at: draft.at }
157
166
  const envelope = { ...unsigned, payload: toBase64(ciphertext), signer: signer.ref }
158
167
  return { ...envelope, sig: sign(signer.signSecret, envelopeBytes(envelope)) }
159
168
  }
@@ -164,28 +173,33 @@ const CLOCK_SKEW_MS = 5 * 60_000
164
173
  export type VerifyOptions = { readonly acceptExpiredCerts?: boolean }
165
174
 
166
175
  export function verifyEnvelope(envelope: Envelope, state: VaultState, options: VerifyOptions = {}): string | undefined {
167
- const group = state.groups[envelope.group]
168
- if (group === undefined) return `unknown group "${envelope.group}"`
169
- if (group.gen !== envelope.gen) return `stale generation ${envelope.gen} (current ${group.gen})`
176
+ const tier = state.tiers[envelope.tier]
177
+ if (tier === undefined) return `unknown tier "${envelope.tier}"`
178
+ // The id names its tier, so a file can only ever be replaced by a write its tier's signers could make.
179
+ if (!envelope.id.startsWith(`${envelope.tier}.`)) return `entry id does not belong to tier "${envelope.tier}"`
180
+ if (tier.gen !== envelope.gen) return `stale generation ${envelope.gen} (current ${tier.gen})`
170
181
  if (Date.parse(envelope.at) > Date.now() + CLOCK_SKEW_MS) return 'timestamp is in the future'
171
182
  const signPublic = signerAuthority(
172
183
  envelope.signer,
173
- envelope.group,
184
+ envelope.tier,
174
185
  state,
175
186
  envelope.at,
176
187
  options.acceptExpiredCerts === true ? null : Date.now(),
177
188
  )
178
- if (signPublic === undefined) return 'signer is not allowed to write this group'
189
+ if (signPublic === undefined) return 'signer is not allowed to write this tier'
179
190
  return verifySignature(signPublic, envelopeBytes(envelope), envelope.sig) ? undefined : 'bad signature'
180
191
  }
181
192
 
182
193
  export async function openEntry(envelope: Envelope, keyring: Keyring): Promise<EntryPayload | undefined> {
183
- const key = await keyring.unlock(envelope.group)
194
+ const key = await keyring.unlock(envelope.tier)
184
195
  if (key === undefined) return undefined
185
196
  const payload = decodePayload(await unseal([key.identity], fromBase64(envelope.payload)))
186
197
  const { signer } = envelope
187
198
  if (signer.kind === 'cert' && signer.cert.only.length > 0 && !matchesOnly(payload.name, signer.cert.only)) {
188
199
  throw new TypeVaultError('tampered', `${payload.name} is outside the writing grant's --only`)
189
200
  }
201
+ if (signer.kind === 'cert' && !certMayHold(signer.cert, envelope.id, envelope.tier, payload.name)) {
202
+ throw new TypeVaultError('tampered', `${payload.name} took over an entry its writing grant was not issued`)
203
+ }
190
204
  return payload
191
205
  }
@@ -7,12 +7,18 @@ export type ErrorCode =
7
7
  | 'expired'
8
8
  | 'locked'
9
9
  | 'unavailable'
10
+ /** Another machine's daemon is using this vault's state directory. */
11
+ | 'in_use'
12
+ /** No vault at the given directory. */
13
+ | 'no_vault'
14
+ /** A vault is there, but the key given is not one of its members. */
15
+ | 'not_member'
10
16
 
11
17
  export class TypeVaultError extends Error {
12
18
  readonly code: ErrorCode
13
19
 
14
- constructor(code: ErrorCode, message: string) {
15
- super(message)
20
+ constructor(code: ErrorCode, message: string, options?: ErrorOptions) {
21
+ super(message, options)
16
22
  this.name = 'TypeVaultError'
17
23
  this.code = code
18
24
  }
package/src/core/fsx.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs'
1
+ import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs'
2
2
  import { basename, dirname, join, sep } from 'node:path'
3
3
 
4
4
  import { randomHex } from './crypto'
@@ -10,6 +10,8 @@ export const ensureDir = (path: string, mode = 0o755): void => {
10
10
  }
11
11
 
12
12
  export function fsyncDir(path: string): void {
13
+ // Windows can't open a directory as a file; NTFS journals the rename itself.
14
+ if (process.platform === 'win32') return
13
15
  const fd = openSync(path, 'r')
14
16
  try {
15
17
  fsyncSync(fd)
@@ -42,7 +44,9 @@ export function assertNoSymlinks(base: string, rel: string): void {
42
44
  let path = base
43
45
  for (const part of rel.split(sep).filter((segment) => segment !== '')) {
44
46
  path = join(path, part)
45
- if (!existsSync(path)) return
46
- if (lstatSync(path).isSymbolicLink()) throw new TypeVaultError('tampered', `${path} is a symlink`)
47
+ // lstat, not exists: a dangling symlink reads as missing yet a write through it creates its target.
48
+ const stat = lstatSync(path, { throwIfNoEntry: false })
49
+ if (stat === undefined) return
50
+ if (stat.isSymbolicLink()) throw new TypeVaultError('tampered', `${path} is a symlink`)
47
51
  }
48
52
  }
@@ -0,0 +1,87 @@
1
+ import { existsSync, rmSync, writeFileSync } from 'node:fs'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { randomHex } from './crypto'
6
+ import { TypeVaultError } from './errors'
7
+ import { readJsonFile } from './json-file'
8
+ import { hostId, type Layout } from './layout'
9
+
10
+ type Env = Readonly<Record<string, string | undefined>>
11
+
12
+ const CLAIM_ATTEMPTS = 3
13
+
14
+ const HolderSchema = z.object({ host: z.string(), pid: z.number().int(), token: z.string(), at: z.string() })
15
+ type Holder = z.infer<typeof HolderSchema>
16
+
17
+ export type DaemonClaim = {
18
+ readonly release: () => void
19
+ readonly owns: () => boolean
20
+ }
21
+
22
+ /**
23
+ * flock does not cross machines (a bind mount between macOS and a Linux VM, say), so whoever runs a daemon (or
24
+ * re-initializes the vault) also claims the state directory in `daemon.holder`, created exclusively. An opener on the
25
+ * same machine trusts the flock; one on another machine refuses while any claim from another host is there. Another
26
+ * machine's claim is never taken over: nothing here can tell a crashed daemon from a paused one, so a claim left by a
27
+ * crash stays until someone who knows that daemon is gone deletes it.
28
+ */
29
+ export function refuseForeignDaemon(layout: Layout, env: Env): void {
30
+ const holder = readHolder(layout)
31
+ if (holder !== undefined && holder.host !== hostId(env)) throw inUse(layout, holder)
32
+ }
33
+
34
+ /**
35
+ * Claims the state directory for this process until `release`. The caller must hold `daemonLock`, so a claim this
36
+ * machine left behind belongs to a daemon that is gone, and is replaced. Another machine's claim fails with `in_use`.
37
+ */
38
+ export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
39
+ const token = randomHex(8)
40
+ const record = JSON.stringify({ host: hostId(env), pid: process.pid, token, at: new Date().toISOString() })
41
+ for (let attempt = 0; ; attempt++) {
42
+ try {
43
+ writeFileSync(layout.daemonHolder, record, { flag: 'wx', mode: 0o600 })
44
+ break
45
+ } catch (error) {
46
+ if (!isCode(error, 'EEXIST')) throw error
47
+ }
48
+ const holder = readHolder(layout)
49
+ if (holder !== undefined && holder.host !== hostId(env)) throw inUse(layout, holder)
50
+ if (attempt + 1 >= CLAIM_ATTEMPTS) {
51
+ throw new TypeVaultError('in_use', `could not claim ${layout.root}: another process keeps claiming it`)
52
+ }
53
+ if (holder !== undefined) rmSync(layout.daemonHolder, { force: true })
54
+ }
55
+ const owns = (): boolean => readHolder(layout)?.token === token
56
+ return {
57
+ owns,
58
+ release: () => {
59
+ if (owns()) rmSync(layout.daemonHolder, { force: true })
60
+ },
61
+ }
62
+ }
63
+
64
+ function readHolder(layout: Layout): Holder | undefined {
65
+ if (!existsSync(layout.daemonHolder)) return undefined
66
+ try {
67
+ return readJsonFile(layout.daemonHolder, HolderSchema)
68
+ } catch (error) {
69
+ if (isCode(error, 'ENOENT')) return undefined
70
+ if (error instanceof TypeVaultError && error.code === 'tampered') {
71
+ throw new TypeVaultError(
72
+ 'tampered',
73
+ `${layout.daemonHolder} is malformed; if its daemon is gone for good, delete this file and retry`,
74
+ )
75
+ }
76
+ throw error
77
+ }
78
+ }
79
+
80
+ const inUse = (layout: Layout, holder: Holder): TypeVaultError =>
81
+ new TypeVaultError(
82
+ 'in_use',
83
+ `a typevault daemon on another machine (${holder.host}, pid ${holder.pid}, since ${holder.at}) is using ${layout.root}; one machine at a time may use a state directory (if that daemon is gone for good, delete ${layout.daemonHolder})`,
84
+ )
85
+
86
+ const isCode = (error: unknown, code: string): boolean =>
87
+ error instanceof Error && 'code' in error && error.code === code
@@ -0,0 +1,132 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { z } from 'zod'
5
+
6
+ import {
7
+ decodeSecretKey,
8
+ encodeSecretKey,
9
+ generateSecretKey,
10
+ type PublicKey,
11
+ publicKeyOf,
12
+ type SecretKey,
13
+ } from './crypto'
14
+ import { fromBase64Url, fromUtf8, toBase64Url, utf8 } from './encoding'
15
+ import { TypeVaultError } from './errors'
16
+ import { assertNoSymlinks, atomicWrite, ensureDir } from './fsx'
17
+ import { readJsonFile } from './json-file'
18
+ import { configDir, type Layout } from './layout'
19
+ import { generateSecretKeyCode, openWithPassword, sealWithPassword } from './password'
20
+ import { type MemberKind, parseMemberName } from './state'
21
+
22
+ type Env = Readonly<Record<string, string | undefined>>
23
+
24
+ /**
25
+ * Who this device acts as, in every vault. A human's member key is sealed by their password and Secret Key; a
26
+ * machine (CI, an agent host) has no one to type a password, so it holds its member key directly.
27
+ */
28
+ export type Identity = PublicKey &
29
+ (
30
+ | {
31
+ readonly v: 1
32
+ readonly kind: 'human'
33
+ readonly name: string
34
+ readonly secretKey: string
35
+ readonly sealedKey: string
36
+ }
37
+ | { readonly v: 1; readonly kind: 'machine'; readonly name: string; readonly key: string }
38
+ )
39
+
40
+ export type MemberPublic = PublicKey & { readonly kind: MemberKind }
41
+
42
+ const PublicFields = { recipient: z.string(), signPublic: z.string() }
43
+ const IdentitySchema = z.discriminatedUnion('kind', [
44
+ z.object({
45
+ v: z.literal(1),
46
+ kind: z.literal('human'),
47
+ name: z.string(),
48
+ secretKey: z.string(),
49
+ sealedKey: z.string(),
50
+ ...PublicFields,
51
+ }),
52
+ z.object({ v: z.literal(1), kind: z.literal('machine'), name: z.string(), key: z.string(), ...PublicFields }),
53
+ ])
54
+ const MemberPublicSchema = z.object({
55
+ kind: z.enum(['human', 'machine']),
56
+ recipient: z.string().startsWith('age1'),
57
+ signPublic: z.string(),
58
+ })
59
+ const PUBLIC_PREFIX = 'tvp1:'
60
+
61
+ export const identityPath = (env: Env): string => join(configDir(env), 'identity.json')
62
+
63
+ export function readIdentity(env: Env): Identity | undefined {
64
+ const path = identityPath(env)
65
+ return existsSync(path) ? readJsonFile(path, IdentitySchema) : undefined
66
+ }
67
+
68
+ export function writeIdentity(env: Env, identity: Identity): void {
69
+ ensureDir(configDir(env), 0o700)
70
+ atomicWrite(identityPath(env), `${JSON.stringify(identity, null, 2)}\n`, 0o600)
71
+ }
72
+
73
+ export async function createIdentity(
74
+ rawName: string,
75
+ kind: MemberKind,
76
+ password?: string,
77
+ ): Promise<{ readonly identity: Identity; readonly key: SecretKey }> {
78
+ const name = parseMemberName(rawName)
79
+ const key = await generateSecretKey({ kind: 'member', name })
80
+ const pub = await publicKeyOf(key)
81
+ if (kind === 'machine') return { identity: { v: 1, kind, name, key: encodeSecretKey(key), ...pub }, key }
82
+ if (password === undefined || password === '') throw new TypeVaultError('invalid', 'a human member needs a password')
83
+ const secretKey = generateSecretKeyCode()
84
+ const sealedKey = await sealMemberKey(key, password, secretKey)
85
+ return { identity: { v: 1, kind, name, secretKey, sealedKey, ...pub }, key }
86
+ }
87
+
88
+ export const memberPublicOfIdentity = (identity: Identity): MemberPublic => ({
89
+ kind: identity.kind,
90
+ recipient: identity.recipient,
91
+ signPublic: identity.signPublic,
92
+ })
93
+
94
+ /**
95
+ * Where a person's sealed member key is committed in a vault. The vault comes from git, so a planted symlink here
96
+ * must never steer a read or a write outside it (onto identity.json, say).
97
+ */
98
+ export function sealedCopyPath(layout: Layout, name: string): string {
99
+ const rel = join('members', `${parseMemberName(name)}.key`)
100
+ assertNoSymlinks(layout.vault, rel)
101
+ return join(layout.vault, rel)
102
+ }
103
+
104
+ export const sealMemberKey = (key: SecretKey, password: string, secretKey: string): Promise<string> =>
105
+ sealWithPassword(utf8(encodeSecretKey(key)), password, secretKey)
106
+
107
+ /** The member key inside a sealed copy (an identity's, or the one committed in a vault's members/). */
108
+ export async function openMemberKey(sealedKey: string, password: string, secretKey: string): Promise<SecretKey> {
109
+ const key = decodeSecretKey(fromUtf8(await openWithPassword(sealedKey, password, secretKey)))
110
+ if (key.role.kind !== 'member') throw new TypeVaultError('invalid', 'the sealed key is not a member key')
111
+ return key
112
+ }
113
+
114
+ export function unlockIdentity(identity: Identity, password?: string): Promise<SecretKey> {
115
+ if (identity.kind === 'machine') return Promise.resolve(decodeSecretKey(identity.key))
116
+ if (password === undefined) throw new TypeVaultError('locked', 'a password is needed to unlock this identity')
117
+ return openMemberKey(identity.sealedKey, password, identity.secretKey)
118
+ }
119
+
120
+ export const encodeMemberPublic = (member: MemberPublic): string =>
121
+ PUBLIC_PREFIX + toBase64Url(utf8(JSON.stringify(member)))
122
+
123
+ export function decodeMemberPublic(text: string): MemberPublic {
124
+ const trimmed = text.trim()
125
+ if (!trimmed.startsWith(PUBLIC_PREFIX)) throw new TypeVaultError('invalid', 'not a member public key (tvp1:...)')
126
+ try {
127
+ return MemberPublicSchema.parse(JSON.parse(fromUtf8(fromBase64Url(trimmed.slice(PUBLIC_PREFIX.length)))))
128
+ } catch (error) {
129
+ if (error instanceof Error) throw new TypeVaultError('invalid', 'malformed member public key')
130
+ throw error
131
+ }
132
+ }
package/src/core/init.ts CHANGED
@@ -1,30 +1,80 @@
1
- import { existsSync } from 'node:fs'
2
- import { join } from 'node:path'
1
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
2
+ import { basename, dirname, join } from 'node:path'
3
3
 
4
- import { encodeSecretKey, generateSecretKey, publicKeyOf, type SecretKey } from './crypto'
4
+ import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal, type SecretKey } from './crypto'
5
+ import { utf8 } from './encoding'
5
6
  import { TypeVaultError } from './errors'
6
7
  import { atomicWrite, ensureDir } from './fsx'
7
- import { layoutOf } from './layout'
8
- import { ceilingsDoc, groupsDoc, signersDoc } from './state'
8
+ import { type Identity, type MemberPublic, memberPublicOfIdentity, sealedCopyPath } from './identity'
9
+ import { ownerWrapPath } from './keyring'
10
+ import { globalLayout, type Layout, localLayout } from './layout'
11
+ import { ceilingsDoc, membersDoc, parseMemberName, signersDoc, tiersDoc } from './state'
9
12
 
10
- /** Ignores everything in the vault directory except `vault/`, the only part that is safe to commit. */
11
- const ROOT_GITIGNORE = '/*\n!/vault/\n!/.gitignore\n'
13
+ type Env = Readonly<Record<string, string | undefined>>
12
14
 
13
- /** Creates an empty vault and its operator key. The operator key is the recovery path; keep a copy offline. */
14
- export async function initVault(root: string): Promise<SecretKey> {
15
- const layout = layoutOf(root)
16
- if (existsSync(layout.operatorFile)) throw new TypeVaultError('conflict', `a vault already exists at ${root}`)
17
- for (const dir of [layout.keys, layout.groupKeys, layout.audit, layout.run]) ensureDir(dir, 0o700)
15
+ /** The first member, who becomes the owner. A human's password-sealed key is committed beside the vault. */
16
+ export type Founder = { readonly name: string; readonly member: MemberPublic; readonly sealedKey?: string }
17
+
18
+ export const founderOf = (identity: Identity): Founder => ({
19
+ name: identity.name,
20
+ member: memberPublicOfIdentity(identity),
21
+ ...(identity.kind === 'human' ? { sealedKey: identity.sealedKey } : {}),
22
+ })
23
+
24
+ export type Created = { readonly layout: Layout; readonly owner: SecretKey }
25
+
26
+ /**
27
+ * Creates an empty global vault owned by `founder`, all of it safe to commit. The owner key is never written down in
28
+ * the clear: it exists only wrapped to owner members, so the founder's password and Secret Key are the recovery path.
29
+ */
30
+ export const initGlobalVault = (founder: Founder, env: Env = process.env): Promise<Created> =>
31
+ create(globalLayout(env), founder)
32
+
33
+ /** Creates an empty project vault at `dir`, all of it safe to commit. */
34
+ export const initLocalVault = (dir: string, founder: Founder, env: Env = process.env): Promise<Created> =>
35
+ create(localLayout(dir, env), founder)
36
+
37
+ async function create(layout: Layout, founder: Founder): Promise<Created> {
38
+ refuseExisting(layout.ownerFile, layout.vault)
39
+ return { layout, owner: await writeVault(layout, founder) }
40
+ }
41
+
42
+ function refuseExisting(ownerFile: string, where: string): void {
43
+ if (existsSync(ownerFile)) throw new TypeVaultError('conflict', `a vault already exists at ${where}`)
44
+ // Pre-rename vaults are not migrated; init over one would keep its stale runtime state (revision marks).
45
+ if (existsSync(join(dirname(ownerFile), 'operator.json'))) {
46
+ throw new TypeVaultError(
47
+ 'conflict',
48
+ `an old-format vault (operator.json) exists at ${where}; move it and its typevault root aside, then run init again`,
49
+ )
50
+ }
51
+ }
52
+
53
+ async function writeVault(layout: Layout, founder: Founder): Promise<SecretKey> {
54
+ const name = parseMemberName(founder.name)
55
+ // A vault re-created at the same place reuses this checkout's state directory. Its runtime state (grants, a
56
+ // session token, revision marks) belongs to the old vault, so it goes; the trust pin is rewritten below. The daemon
57
+ // lock and claim stay: whoever initializes may hold them to keep a daemon from starting meanwhile.
58
+ const kept = new Set([basename(layout.daemonLock), basename(layout.daemonHolder)])
59
+ for (const name of existsSync(layout.run) ? readdirSync(layout.run) : []) {
60
+ if (!kept.has(name)) rmSync(join(layout.run, name), { recursive: true, force: true })
61
+ }
62
+ const ownerKey = await generateSecretKey({ kind: 'owner' })
63
+ const owner: PublicKey = await publicKeyOf(ownerKey)
64
+ const { kind, recipient, signPublic } = founder.member
65
+ for (const dir of [layout.audit, layout.run]) ensureDir(dir, 0o700)
18
66
  ensureDir(layout.entries)
19
- const operatorKey = await generateSecretKey({ kind: 'operator' })
20
- const operator = await publicKeyOf(operatorKey)
21
- atomicWrite(layout.operatorKey, `${encodeSecretKey(operatorKey)}\n`, 0o600)
22
- atomicWrite(layout.groupsFile, groupsDoc({}, operatorKey, 1))
23
- atomicWrite(layout.signersFile, signersDoc({}, operatorKey, 1))
24
- atomicWrite(layout.ceilingsFile, ceilingsDoc({}, operatorKey, 1))
25
- atomicWrite(join(layout.root, '.gitignore'), ROOT_GITIGNORE)
26
- atomicWrite(layout.trustFile, JSON.stringify({ operatorSignPublic: operator.signPublic }), 0o600)
27
- // operator.json last: its presence is what marks the directory as an initialized vault.
28
- atomicWrite(layout.operatorFile, `${JSON.stringify({ v: 1, ...operator }, null, 2)}\n`)
29
- return operatorKey
67
+ atomicWrite(layout.tiersFile, tiersDoc({}, ownerKey, 1))
68
+ atomicWrite(
69
+ layout.membersFile,
70
+ membersDoc({ [name]: { kind, recipient, signPublic, owner: true, tiers: [] } }, ownerKey, 1),
71
+ )
72
+ atomicWrite(layout.signersFile, signersDoc({}, ownerKey, 1))
73
+ atomicWrite(layout.ceilingsFile, ceilingsDoc({}, ownerKey, 1))
74
+ atomicWrite(join(layout.vault, ownerWrapPath(name)), await seal([recipient], utf8(encodeSecretKey(ownerKey))))
75
+ if (founder.sealedKey !== undefined) atomicWrite(sealedCopyPath(layout, name), founder.sealedKey)
76
+ atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
77
+ // owner.json last: its presence is what marks the directory as an initialized vault.
78
+ atomicWrite(layout.ownerFile, `${JSON.stringify({ v: 1, ...owner }, null, 2)}\n`)
79
+ return ownerKey
30
80
  }
@@ -0,0 +1,20 @@
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { TypeVaultError } from './errors'
6
+
7
+ /** Syntax and schema failures in persisted state are corruption, never request-body errors. */
8
+ export function parseJsonText<T>(path: string, text: string, schema: z.ZodType<T>): T {
9
+ try {
10
+ return schema.parse(JSON.parse(text))
11
+ } catch (error) {
12
+ if (error instanceof SyntaxError || error instanceof z.ZodError) {
13
+ throw new TypeVaultError('tampered', `${path} is malformed; repair or restore this file before retrying`)
14
+ }
15
+ throw error
16
+ }
17
+ }
18
+
19
+ export const readJsonFile = <T>(path: string, schema: z.ZodType<T>): T =>
20
+ parseJsonText(path, readFileSync(path, 'utf8'), schema)