typevault 0.6.0 → 0.7.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.
- package/package.json +1 -1
- package/src/access/scoped.ts +10 -6
- package/src/access/sealed-access.ts +9 -5
- package/src/access/sealed.ts +12 -8
- package/src/audit/log.ts +71 -18
- package/src/cli/commands/admin.ts +2 -1
- package/src/cli/commands/grant.ts +7 -1
- package/src/cli/commands/members.ts +22 -6
- package/src/cli/context.ts +13 -6
- package/src/cli/index.ts +5 -3
- package/src/core/admin.ts +33 -16
- package/src/core/entries.ts +7 -2
- package/src/core/init.ts +2 -1
- package/src/core/keyring.ts +5 -1
- package/src/core/layout.ts +13 -11
- package/src/core/owner-trust.ts +97 -0
- package/src/core/rotate.ts +67 -6
- package/src/core/secure-enclave.ts +61 -17
- package/src/core/state.ts +21 -23
- package/src/core/touch-id.ts +6 -0
- package/src/core/vault.ts +46 -10
- package/src/daemon/admin-routes.ts +23 -15
- package/src/daemon/agent-routes.ts +11 -7
- package/src/daemon/daemon.ts +19 -6
- package/src/daemon/requests.ts +35 -23
package/package.json
CHANGED
package/src/access/scoped.ts
CHANGED
|
@@ -51,12 +51,16 @@ export class ScopedVault implements Access {
|
|
|
51
51
|
|
|
52
52
|
#audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>): Promise<void> {
|
|
53
53
|
const { mode, grant, label } = this.#identity
|
|
54
|
-
return appendAudit(
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
return appendAudit(
|
|
55
|
+
this.#vault.layout,
|
|
56
|
+
{
|
|
57
|
+
...event,
|
|
58
|
+
mode,
|
|
59
|
+
...(grant === undefined ? {} : { grant }),
|
|
60
|
+
...(label === undefined ? {} : { label }),
|
|
61
|
+
},
|
|
62
|
+
this.#vault.anchorsFile,
|
|
63
|
+
)
|
|
60
64
|
}
|
|
61
65
|
|
|
62
66
|
#allows(entry: StoredEntry): boolean {
|
|
@@ -47,11 +47,15 @@ export class SealedAccess implements Access {
|
|
|
47
47
|
return Vault.open(this.#layout, [], this.#env)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
/**
|
|
51
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Best effort: a sealed grant may run where no vault directory exists. Writes pass the anchors file of the vault they
|
|
52
|
+
* opened; reads don't open it, so they have none.
|
|
53
|
+
*/
|
|
54
|
+
async #audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>, anchorsFile?: string): Promise<void> {
|
|
52
55
|
const layout = this.#layout
|
|
53
56
|
if (layout === undefined || !existsSync(layout.ownerFile)) return
|
|
54
|
-
|
|
57
|
+
const record = { ...event, mode: 'sealed' as const, grant: this.#bundle.id, label: this.#bundle.label }
|
|
58
|
+
await appendAudit(layout, record, anchorsFile ?? layout.fixedAnchorsFile)
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
async list(): Promise<readonly EntrySummary[]> {
|
|
@@ -97,7 +101,7 @@ export class SealedAccess implements Access {
|
|
|
97
101
|
{ ref: { kind: 'cert', cert: bundle.write.cert }, signSecret: sealedSigningSecret(bundle) },
|
|
98
102
|
{ ...(ifRev === undefined ? {} : { ifRev }), ...(prior === undefined ? {} : { base: prior }) },
|
|
99
103
|
)
|
|
100
|
-
await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] })
|
|
104
|
+
await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] }, vault.anchorsFile)
|
|
101
105
|
const { envelope, payload } = stored
|
|
102
106
|
return {
|
|
103
107
|
name: payload.name,
|
|
@@ -129,7 +133,7 @@ export class SealedAccess implements Access {
|
|
|
129
133
|
allowsEntry([{ tiers: cert.tiers, only: cert.only }], vault.state, envelope.tier, name) &&
|
|
130
134
|
signerAuthority({ kind: 'cert', cert }, envelope.tier, vault.state, new Date().toISOString()) !== undefined,
|
|
131
135
|
)
|
|
132
|
-
await this.#audit({ action: 'remove', entries: [name] })
|
|
136
|
+
await this.#audit({ action: 'remove', entries: [name] }, vault.anchorsFile)
|
|
133
137
|
}
|
|
134
138
|
|
|
135
139
|
async move(from: EntryName, to: EntryName): Promise<void> {
|
package/src/access/sealed.ts
CHANGED
|
@@ -71,14 +71,18 @@ export async function issueSealedGrant(vault: Vault, request: SealedRequest): Pr
|
|
|
71
71
|
const write = { signSecret: toBase64(signing.signSecret), cert }
|
|
72
72
|
const identity = await generateX25519Identity()
|
|
73
73
|
const sealed = await seal([await identityToRecipient(identity)], utf8(JSON.stringify({ ...bundle, write })))
|
|
74
|
-
await appendAudit(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
74
|
+
await appendAudit(
|
|
75
|
+
vault.layout,
|
|
76
|
+
{
|
|
77
|
+
action: 'grant.issue',
|
|
78
|
+
mode: 'sealed',
|
|
79
|
+
grant: id,
|
|
80
|
+
label: request.label,
|
|
81
|
+
tiers: request.tiers,
|
|
82
|
+
entries: granted.map((value) => value.name),
|
|
83
|
+
},
|
|
84
|
+
vault.anchorsFile,
|
|
85
|
+
)
|
|
82
86
|
return `${PREFIX}${toBase64Url(utf8(identity))}.${toBase64Url(sealed)}`
|
|
83
87
|
}
|
|
84
88
|
|
package/src/audit/log.ts
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
appendFileSync,
|
|
3
|
+
closeSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
fsyncSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readdirSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
readSync,
|
|
10
|
+
statSync,
|
|
11
|
+
} from 'node:fs'
|
|
12
|
+
import { basename, dirname, relative } from 'node:path'
|
|
3
13
|
|
|
4
14
|
import { z } from 'zod'
|
|
5
15
|
|
|
@@ -75,15 +85,46 @@ export function readAudit(layout: Layout): readonly AuditRecord[] {
|
|
|
75
85
|
.map((line) => parseJsonText(layout.auditLog, line, RecordSchema))
|
|
76
86
|
}
|
|
77
87
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
88
|
+
/** Another state-directory chain's anchors file beside `anchorsFile`, when `anchorsFile` is one. A vault has only one. */
|
|
89
|
+
function otherStateAnchors(anchorsFile: string): string | undefined {
|
|
90
|
+
const name = basename(anchorsFile)
|
|
91
|
+
const dir = dirname(anchorsFile)
|
|
92
|
+
if (!name.startsWith('state-') || !existsSync(dir)) return undefined
|
|
93
|
+
return readdirSync(dir).find((file) => file.startsWith('state-') && file.endsWith('.jsonl') && file !== name)
|
|
83
94
|
}
|
|
84
95
|
|
|
85
|
-
|
|
86
|
-
|
|
96
|
+
function writeAnchor(layout: Layout, anchorsFile: string, last: AuditRecord): void {
|
|
97
|
+
assertInVault(layout, anchorsFile)
|
|
98
|
+
ensureDir(dirname(anchorsFile))
|
|
99
|
+
appendLine(anchorsFile, JSON.stringify({ seq: last.seq, hash: last.hash, at: last.at }))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// The anchors live in the committed vault: a pulled symlink there must not redirect a read or an append.
|
|
103
|
+
const assertInVault = (layout: Layout, anchorsFile: string): void =>
|
|
104
|
+
assertNoSymlinks(dirname(layout.vault), relative(dirname(layout.vault), anchorsFile))
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The last checkpoint's seq, for catching up deferred ones. An anchors file it can't read or parse gives undefined
|
|
108
|
+
* rather than throwing: this runs after the operation being audited took effect, checkpoint writes keep their own
|
|
109
|
+
* checks, and verification reports the damage.
|
|
110
|
+
*/
|
|
111
|
+
function lastAnchoredSeq(layout: Layout, anchorsFile: string): number | undefined {
|
|
112
|
+
try {
|
|
113
|
+
assertInVault(layout, anchorsFile)
|
|
114
|
+
if (!existsSync(anchorsFile)) return 0
|
|
115
|
+
const last = readFileSync(anchorsFile, 'utf8').trimEnd().split('\n').at(-1)
|
|
116
|
+
return last === undefined || last === '' ? 0 : AnchorSchema.parse(JSON.parse(last)).seq
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Appends one hash-chained record; every 100th record's head is anchored in the (committable) vault. `anchorsFile` is
|
|
124
|
+
* the one a validated vault state names. Without it, a state-directory chain has no trusted destination: the record
|
|
125
|
+
* stays in the local log and its checkpoint waits for the next write that has one.
|
|
126
|
+
*/
|
|
127
|
+
export function appendAudit(layout: Layout, event: AuditEvent, anchorsFile = layout.fixedAnchorsFile): Promise<void> {
|
|
87
128
|
return withLock(layout.auditLock, 'exclusive', async () => {
|
|
88
129
|
ensureDir(layout.audit, 0o700)
|
|
89
130
|
const last = readLast(layout)
|
|
@@ -91,15 +132,19 @@ export function appendAudit(layout: Layout, event: AuditEvent): Promise<void> {
|
|
|
91
132
|
const unhashed = { ...fields, seq: (last?.seq ?? 0) + 1, at: new Date().toISOString(), prev: last?.hash ?? GENESIS }
|
|
92
133
|
const record = { ...unhashed, hash: hashOf(unhashed) }
|
|
93
134
|
appendLine(layout.auditLog, JSON.stringify(record))
|
|
94
|
-
if (
|
|
135
|
+
if (anchorsFile === undefined) return
|
|
136
|
+
const anchored = record.seq % ANCHOR_EVERY === 0 ? undefined : lastAnchoredSeq(layout, anchorsFile)
|
|
137
|
+
const due = record.seq % ANCHOR_EVERY === 0 || (anchored !== undefined && record.seq - anchored >= ANCHOR_EVERY)
|
|
138
|
+
if (due) writeAnchor(layout, anchorsFile, record)
|
|
95
139
|
})
|
|
96
140
|
}
|
|
97
141
|
|
|
98
|
-
/** Anchors the current head now,
|
|
99
|
-
export function anchorAudit(layout: Layout): Promise<void> {
|
|
142
|
+
/** Anchors the current head now, in the anchors file a validated vault state names. */
|
|
143
|
+
export function anchorAudit(layout: Layout, anchorsFile = layout.fixedAnchorsFile): Promise<void> {
|
|
100
144
|
return withLock(layout.auditLock, 'exclusive', async () => {
|
|
101
145
|
const last = readAudit(layout).at(-1)
|
|
102
|
-
if (
|
|
146
|
+
if (anchorsFile === undefined || last === undefined) return
|
|
147
|
+
writeAnchor(layout, anchorsFile, last)
|
|
103
148
|
})
|
|
104
149
|
}
|
|
105
150
|
|
|
@@ -107,17 +152,25 @@ export type AuditVerdict =
|
|
|
107
152
|
| { readonly ok: true; readonly records: number }
|
|
108
153
|
| { readonly ok: false; readonly reason: string }
|
|
109
154
|
|
|
110
|
-
/**
|
|
111
|
-
|
|
155
|
+
/**
|
|
156
|
+
* Recomputes the chain and checks every anchor against it. A log too damaged to read fails the check. `anchorsFile`
|
|
157
|
+
* defaults to the one owner.json names; pass the one a validated vault state names instead.
|
|
158
|
+
*/
|
|
159
|
+
export function verifyAudit(layout: Layout, anchorsFile = layout.anchorsFile): AuditVerdict {
|
|
112
160
|
try {
|
|
113
|
-
return verifyChain(layout)
|
|
161
|
+
return verifyChain(layout, anchorsFile)
|
|
114
162
|
} catch (error) {
|
|
115
163
|
if (error instanceof TypeVaultError && error.code === 'tampered') return { ok: false, reason: error.message }
|
|
116
164
|
throw error
|
|
117
165
|
}
|
|
118
166
|
}
|
|
119
167
|
|
|
120
|
-
function verifyChain(layout: Layout): AuditVerdict {
|
|
168
|
+
function verifyChain(layout: Layout, anchorsFile: string): AuditVerdict {
|
|
169
|
+
// A vault's state-directory chain never changes name, so anchors under another name mean the owner history this
|
|
170
|
+
// machine accepted (on first use) isn't the one they were made for: report it rather than skip anchors it can't check.
|
|
171
|
+
// Only verification checks this, so a stray anchors file can't keep the vault from opening.
|
|
172
|
+
const other = otherStateAnchors(anchorsFile)
|
|
173
|
+
if (other !== undefined) return { ok: false, reason: `anchors exist for another audit chain (${other})` }
|
|
121
174
|
const records = readAudit(layout)
|
|
122
175
|
let prev = GENESIS
|
|
123
176
|
const heads = new Map<number, string>()
|
|
@@ -130,7 +183,7 @@ function verifyChain(layout: Layout): AuditVerdict {
|
|
|
130
183
|
heads.set(record.seq, hash)
|
|
131
184
|
prev = hash
|
|
132
185
|
}
|
|
133
|
-
const anchors = [layout.legacyAnchorsFile,
|
|
186
|
+
const anchors = [layout.legacyAnchorsFile, anchorsFile].flatMap((file) =>
|
|
134
187
|
existsSync(file)
|
|
135
188
|
? readFileSync(file, 'utf8')
|
|
136
189
|
.split('\n')
|
|
@@ -209,7 +209,8 @@ export const doctor = defineCommand({
|
|
|
209
209
|
`same name in several tiers: ${dup} (if the tiers are unrelated, reads of it fail: keep one with \`typevault rm <name> --tier <g>\`)`,
|
|
210
210
|
)
|
|
211
211
|
for (const name of report.needsRotation) print(`needs rotation: ${name}`)
|
|
212
|
-
|
|
212
|
+
// Anchors from the owner chain this vault was opened against, not from rereading owner.json.
|
|
213
|
+
const audit = verifyAudit(vault.layout, vault.layout.anchorsFileFor(vault.state.origin))
|
|
213
214
|
print(audit.ok ? `audit: ok (${audit.records} records)` : `audit: BROKEN: ${audit.reason}`)
|
|
214
215
|
if (report.problems.length > 0 || !audit.ok) process.exitCode = 1
|
|
215
216
|
},
|
|
@@ -9,6 +9,8 @@ import { issueSealedGrant } from '../../access/sealed'
|
|
|
9
9
|
import { GrantInfoSchema, IssuedSchema } from '../../admin'
|
|
10
10
|
import { readAudit, verifyAudit } from '../../audit/log'
|
|
11
11
|
import { TypeVaultError } from '../../core/errors'
|
|
12
|
+
import { loadState } from '../../core/state'
|
|
13
|
+
import { readSnapshot } from '../../core/vault'
|
|
12
14
|
import { adminCall, layoutFrom, openDirect } from '../context'
|
|
13
15
|
import { csv, print, table } from '../output'
|
|
14
16
|
|
|
@@ -72,7 +74,11 @@ export const audit = defineCommand({
|
|
|
72
74
|
async run({ args }) {
|
|
73
75
|
const layout = layoutFrom(process.env)
|
|
74
76
|
if (args.verify) {
|
|
75
|
-
|
|
77
|
+
// The anchors file comes from the owner chain that just passed the trust check, not from rereading owner.json.
|
|
78
|
+
const verdict = await readSnapshot(layout, process.env, async () => {
|
|
79
|
+
const { origin } = loadState(layout, process.env)
|
|
80
|
+
return verifyAudit(layout, layout.anchorsFileFor(origin))
|
|
81
|
+
})
|
|
76
82
|
print(verdict.ok ? `ok (${verdict.records} records)` : `BROKEN: ${verdict.reason}`)
|
|
77
83
|
if (!verdict.ok) process.exitCode = 1
|
|
78
84
|
return
|
|
@@ -4,6 +4,7 @@ import { userInfo } from 'node:os'
|
|
|
4
4
|
import { defineCommand } from 'citty'
|
|
5
5
|
|
|
6
6
|
import { parseTtl } from '../../access/scope'
|
|
7
|
+
import { Admin } from '../../core/admin'
|
|
7
8
|
import { publicKeyOf } from '../../core/crypto'
|
|
8
9
|
import { TypeVaultError } from '../../core/errors'
|
|
9
10
|
import { atomicWrite } from '../../core/fsx'
|
|
@@ -21,7 +22,7 @@ import {
|
|
|
21
22
|
writeIdentity,
|
|
22
23
|
} from '../../core/identity'
|
|
23
24
|
import { type Layout, localLayout, vaultIdOf } from '../../core/layout'
|
|
24
|
-
import { readOwner } from '../../core/
|
|
25
|
+
import { readOwner } from '../../core/owner-trust'
|
|
25
26
|
import { Vault } from '../../core/vault'
|
|
26
27
|
import { worktreeVaults } from '../../core/worktrees'
|
|
27
28
|
import { endLiveGrants, stopDaemon } from '../../daemon/spawn'
|
|
@@ -32,6 +33,7 @@ import {
|
|
|
32
33
|
findLayout,
|
|
33
34
|
layoutFrom,
|
|
34
35
|
openAdmin,
|
|
36
|
+
openDirect,
|
|
35
37
|
openPublic,
|
|
36
38
|
unlockSession,
|
|
37
39
|
worktreeSessions,
|
|
@@ -137,8 +139,18 @@ export const member = defineCommand({
|
|
|
137
139
|
meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
|
|
138
140
|
args: { name: { type: 'positional', required: true } },
|
|
139
141
|
async run({ args }) {
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
+
const vault = await openDirect(process.env)
|
|
143
|
+
const previous = vault.state.owner.signPublic
|
|
144
|
+
const before = Object.keys(vault.state.members)
|
|
145
|
+
const affected = await new Admin(vault).removeMember(args.name)
|
|
146
|
+
const removed = before.filter((name) => vault.state.members[name] === undefined)
|
|
147
|
+
print(`removed ${removed.join(', ')}`)
|
|
148
|
+
if (removed.length > 1) note(`${removed.join(', ')} shared one key, so all of them were removed.`)
|
|
149
|
+
if (vault.state.owner.signPublic !== previous) {
|
|
150
|
+
note(
|
|
151
|
+
'Owner key rotated. Commit the vault; members must pull it. For an open session, run typevault lock then typevault unlock.',
|
|
152
|
+
)
|
|
153
|
+
}
|
|
142
154
|
if (affected.length === 0) return
|
|
143
155
|
note('They may have kept what they read. Rotate these secrets at their source, then re-set them:')
|
|
144
156
|
for (const name of affected) note(` ${name}`)
|
|
@@ -248,9 +260,11 @@ export const lock = defineCommand({
|
|
|
248
260
|
if (layout === undefined) throw new TypeVaultError('not_found', 'no vault here')
|
|
249
261
|
const env = process.env
|
|
250
262
|
// An owner that can't be read doesn't prove another vault, so lock still reaches it.
|
|
251
|
-
|
|
263
|
+
// Every key the signature-verified handover chain passed through, ending at the current one.
|
|
264
|
+
const ownerOf = (target: Layout): { readonly keys: ReadonlySet<string> } | undefined => {
|
|
252
265
|
try {
|
|
253
|
-
|
|
266
|
+
const owner = readOwner(target)
|
|
267
|
+
return { keys: new Set([...owner.handovers.map(({ from }) => from), owner.signPublic]) }
|
|
254
268
|
} catch (error) {
|
|
255
269
|
if (error instanceof TypeVaultError) return undefined
|
|
256
270
|
throw error
|
|
@@ -263,7 +277,9 @@ export const lock = defineCommand({
|
|
|
263
277
|
.map((vault) => localLayout(vault, env))
|
|
264
278
|
.filter((worktree) => {
|
|
265
279
|
const other = ownerOf(worktree)
|
|
266
|
-
|
|
280
|
+
// Any owner key both verified chains passed through: the same vault on another generation (one that hasn't pulled
|
|
281
|
+
// a rotation yet) or rotated independently from a common owner. Claimed origins alone could disagree.
|
|
282
|
+
return own === undefined || other === undefined || [...other.keys].some((key) => own.keys.has(key))
|
|
267
283
|
})
|
|
268
284
|
// A session unlocked in any other worktree would only be shared here again on the next read, so it stops too, but
|
|
269
285
|
// the grants of a different vault are its own.
|
package/src/cli/context.ts
CHANGED
|
@@ -21,7 +21,8 @@ import {
|
|
|
21
21
|
import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/layout'
|
|
22
22
|
import type { EntryName } from '../core/naming'
|
|
23
23
|
import { loadState } from '../core/state'
|
|
24
|
-
import {
|
|
24
|
+
import { touchIdAvailable } from '../core/touch-id'
|
|
25
|
+
import { readSnapshot, Vault } from '../core/vault'
|
|
25
26
|
import { worktreeVaults } from '../core/worktrees'
|
|
26
27
|
import { callDaemon, isDaemonAlive } from '../daemon/client'
|
|
27
28
|
import { LiveAccess } from '../daemon/live-access'
|
|
@@ -75,11 +76,17 @@ export async function openDirect(env: Env): Promise<Vault> {
|
|
|
75
76
|
/**
|
|
76
77
|
* A person's member key: through Touch ID when they turned it on and are at this Mac's terminal, else (or when Touch
|
|
77
78
|
* ID fails) their password. Without a terminal it stays the password's error, so an agent can't raise the dialog.
|
|
79
|
+
* At a Mac with Touch ID that they haven't turned on, the password prompt suggests it.
|
|
78
80
|
*/
|
|
79
81
|
export async function unlockHuman(env: Env, identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
|
|
80
82
|
if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
|
|
81
83
|
if (identity.kind === 'machine') return unlockIdentity(identity)
|
|
82
|
-
|
|
84
|
+
const atThisMac = process.platform === 'darwin' && process.stdin.isTTY === true && !passwordsFromStdin()
|
|
85
|
+
if (identity.touchId === undefined) {
|
|
86
|
+
// The tip is optional: a probe that fails must not stand between the person and their password prompt.
|
|
87
|
+
const tip = atThisMac && (await touchIdAvailable().catch(() => false))
|
|
88
|
+
if (tip) note('tip: skip the password next time with `typevault touch-id enable`')
|
|
89
|
+
} else if (atThisMac) {
|
|
83
90
|
try {
|
|
84
91
|
return await unlockIdentityWithTouchId(env, identity, identity.touchId)
|
|
85
92
|
} catch (error) {
|
|
@@ -183,7 +190,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
183
190
|
}
|
|
184
191
|
if (grant.startsWith('tvl1.')) {
|
|
185
192
|
const layout = layoutFrom(env)
|
|
186
|
-
checkOwnerPin(layout, env)
|
|
193
|
+
await checkOwnerPin(layout, env)
|
|
187
194
|
await ensureDaemon(layout, env)
|
|
188
195
|
return { kind: 'live', access: new LiveAccess(layout.agentSocket, grant) }
|
|
189
196
|
}
|
|
@@ -199,7 +206,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
199
206
|
*/
|
|
200
207
|
async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
201
208
|
const layout = layoutFrom(env)
|
|
202
|
-
checkOwnerPin(layout, env)
|
|
209
|
+
await checkOwnerPin(layout, env)
|
|
203
210
|
if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
|
|
204
211
|
const identity = readIdentity(env)
|
|
205
212
|
if (identity === undefined) {
|
|
@@ -218,8 +225,8 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
|
218
225
|
* A live connection reads through a daemon that may have trusted the owner without this process's pin, so a set
|
|
219
226
|
* `TYPEVAULT_OWNER` is checked against the vault here, before anything is read through it.
|
|
220
227
|
*/
|
|
221
|
-
function checkOwnerPin(layout: Layout, env: Env): void {
|
|
222
|
-
if (isSet(env['TYPEVAULT_OWNER'])) loadState(layout, env)
|
|
228
|
+
async function checkOwnerPin(layout: Layout, env: Env): Promise<void> {
|
|
229
|
+
if (isSet(env['TYPEVAULT_OWNER'])) await readSnapshot(layout, env, async () => loadState(layout, env))
|
|
223
230
|
}
|
|
224
231
|
|
|
225
232
|
/**
|
package/src/cli/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { defineCommand, runCommand, runMain } from 'citty'
|
|
3
3
|
|
|
4
4
|
import { TypeVaultError } from '../core/errors'
|
|
5
|
+
import { PACKAGE_VERSION } from '../core/version'
|
|
5
6
|
import { ceiling, doctor, tier, init, key, signer } from './commands/admin'
|
|
6
7
|
import { daemon } from './commands/daemon'
|
|
7
8
|
import { get, ls, mv, otp, rm, set, whoami } from './commands/entries'
|
|
@@ -11,7 +12,7 @@ import { importCommand, redact, request, run, scrub } from './commands/run'
|
|
|
11
12
|
import { readPasswordsFromStdin } from './password'
|
|
12
13
|
|
|
13
14
|
const main = defineCommand({
|
|
14
|
-
meta: { name: 'typevault', description: 'A CLI-first secrets vault for agents' },
|
|
15
|
+
meta: { name: 'typevault', version: PACKAGE_VERSION, description: 'A CLI-first secrets vault for agents' },
|
|
15
16
|
args: {
|
|
16
17
|
global: { type: 'boolean', alias: 'g', description: 'Use the global vault instead of the project vault' },
|
|
17
18
|
'vault-password-stdin': {
|
|
@@ -62,9 +63,10 @@ if (argv.slice(0, split).includes(PASSWORD_STDIN)) readPasswordsFromStdin()
|
|
|
62
63
|
const ownArgs = argv.slice(0, split).filter((arg) => !isGlobalFlag(arg) && arg !== PASSWORD_STDIN)
|
|
63
64
|
const rawArgs = [...ownArgs, ...argv.slice(split)]
|
|
64
65
|
const wantsUsage = ownArgs.length === 0 || ownArgs.some((arg) => arg === '--help' || arg === '-h')
|
|
66
|
+
const wantsVersion = ownArgs.length === 1 && (ownArgs[0] === '--version' || ownArgs[0] === '-v')
|
|
65
67
|
|
|
66
|
-
if (wantsUsage) {
|
|
67
|
-
await runMain(main)
|
|
68
|
+
if (wantsUsage || wantsVersion) {
|
|
69
|
+
await runMain(main, { rawArgs: ownArgs })
|
|
68
70
|
} else {
|
|
69
71
|
try {
|
|
70
72
|
// no-excuse-ok: catch (top-level CLI boundary turns typed errors into a one-line message)
|
package/src/core/admin.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { signerOf } from './entries'
|
|
|
4
4
|
import { TypeVaultError } from './errors'
|
|
5
5
|
import { ownerWrapPath, wrapPath } from './keyring'
|
|
6
6
|
import { withLock } from './lock'
|
|
7
|
-
import { rotateTiers } from './rotate'
|
|
7
|
+
import { rotateOwner, rotateTiers } from './rotate'
|
|
8
8
|
import {
|
|
9
9
|
ceilingsDoc,
|
|
10
10
|
type MemberKind,
|
|
@@ -43,13 +43,14 @@ export class Admin {
|
|
|
43
43
|
this.#owner = owner
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
#mutate(build: (state: VaultState, txn: Txn) => Promise<
|
|
46
|
+
#mutate<T>(build: (state: VaultState, txn: Txn) => Promise<T>): Promise<T> {
|
|
47
47
|
return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
|
|
48
48
|
this.#vault.refresh()
|
|
49
49
|
const txn = new Txn()
|
|
50
|
-
await build(this.#vault.state, txn)
|
|
50
|
+
const result = await build(this.#vault.state, txn)
|
|
51
51
|
commitTxn(this.#vault.layout, txn)
|
|
52
|
-
this.#vault.
|
|
52
|
+
this.#vault.reload()
|
|
53
|
+
return result
|
|
53
54
|
})
|
|
54
55
|
}
|
|
55
56
|
|
|
@@ -152,6 +153,9 @@ export class Admin {
|
|
|
152
153
|
const unknown = member.tiers.find((tier) => state.tiers[tier] === undefined)
|
|
153
154
|
if (unknown !== undefined) throw new TypeVaultError('not_found', `no tier "${unknown}"`)
|
|
154
155
|
const { kind, recipient, signPublic, owner, tiers } = member
|
|
156
|
+
// One key under two names would survive removing either name.
|
|
157
|
+
const alias = Object.entries(state.members).find(([, other]) => other.recipient === recipient)
|
|
158
|
+
if (alias !== undefined) throw new TypeVaultError('conflict', `this key is already member "${alias[0]}"`)
|
|
155
159
|
const members = { ...state.members, [name]: { kind, recipient, signPublic, owner, tiers: [...tiers] } }
|
|
156
160
|
if (owner) txn.put(ownerWrapPath(name), await seal([recipient], utf8(encodeSecretKey(this.#owner))))
|
|
157
161
|
txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
|
|
@@ -163,22 +167,35 @@ export class Admin {
|
|
|
163
167
|
/**
|
|
164
168
|
* Drops a member and rotates every tier they reached, in one transaction: a crash leaves both or neither, never a
|
|
165
169
|
* removed member whose keys still open new ciphertext. Returns the entries they could read, now flagged for
|
|
166
|
-
* rotation: what they already decrypted can only be revoked at each secret's source.
|
|
170
|
+
* rotation: what they already decrypted can only be revoked at each secret's source. Any other name listing the same
|
|
171
|
+
* key goes too: it would otherwise keep that key's access.
|
|
167
172
|
*/
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
await this.#mutate(async (state, txn) => {
|
|
173
|
+
removeMember(name: string): Promise<readonly string[]> {
|
|
174
|
+
return this.#mutate(async (state, txn) => {
|
|
171
175
|
const member = state.members[name]
|
|
172
176
|
if (member === undefined) throw new TypeVaultError('not_found', `no member "${name}"`)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
179
|
-
|
|
177
|
+
const removed = Object.entries(state.members).filter(([, other]) => other.recipient === member.recipient)
|
|
178
|
+
const members = Object.fromEntries(
|
|
179
|
+
Object.entries(state.members).filter(([, other]) => other.recipient !== member.recipient),
|
|
180
|
+
)
|
|
181
|
+
const context = { vault: this.#vault, owner: this.#owner, state: { ...state, members }, txn, exposed: true }
|
|
182
|
+
for (const [gone] of removed) txn.remove(`members/${gone}.key`)
|
|
183
|
+
if (removed.some(([, gone]) => gone.owner)) {
|
|
184
|
+
if (!Object.values(members).some((remaining) => remaining.owner)) {
|
|
185
|
+
throw new TypeVaultError('invalid', `"${name}" is the last owner; add another owner first`)
|
|
186
|
+
}
|
|
187
|
+
for (const [gone, { owner }] of removed) if (owner) txn.remove(ownerWrapPath(gone))
|
|
188
|
+
return rotateOwner(context)
|
|
189
|
+
}
|
|
190
|
+
txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
|
|
191
|
+
return rotateTiers(
|
|
192
|
+
context,
|
|
193
|
+
reachOf(
|
|
194
|
+
state,
|
|
195
|
+
removed.flatMap(([, gone]) => gone.tiers),
|
|
196
|
+
),
|
|
197
|
+
)
|
|
180
198
|
})
|
|
181
|
-
return affected
|
|
182
199
|
}
|
|
183
200
|
|
|
184
201
|
async setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
|
package/src/core/entries.ts
CHANGED
|
@@ -159,12 +159,17 @@ export function signCiphertext(
|
|
|
159
159
|
): Envelope {
|
|
160
160
|
const tier = state.tiers[draft.tier]
|
|
161
161
|
if (tier === undefined) throw new TypeVaultError('not_found', `no tier "${draft.tier}"`)
|
|
162
|
-
|
|
162
|
+
const authority = signerAuthority(signer.ref, draft.tier, state, draft.at)
|
|
163
|
+
if (authority === undefined) {
|
|
163
164
|
throw new TypeVaultError('denied', `this key cannot sign entries in tier "${draft.tier}"`)
|
|
164
165
|
}
|
|
165
166
|
const unsigned = { v: 1 as const, id: draft.id, tier: draft.tier, gen: tier.gen, rev: draft.rev, at: draft.at }
|
|
166
167
|
const envelope = { ...unsigned, payload: toBase64(ciphertext), signer: signer.ref }
|
|
167
|
-
|
|
168
|
+
const message = envelopeBytes(envelope)
|
|
169
|
+
const sig = sign(signer.signSecret, message)
|
|
170
|
+
if (!verifySignature(authority, message, sig))
|
|
171
|
+
throw new TypeVaultError('denied', 'this signing key no longer has authority in the vault')
|
|
172
|
+
return { ...envelope, sig }
|
|
168
173
|
}
|
|
169
174
|
|
|
170
175
|
const CLOCK_SKEW_MS = 5 * 60_000
|
package/src/core/init.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { atomicWrite, ensureDir } from './fsx'
|
|
|
8
8
|
import { type Identity, type MemberPublic, memberPublicOfIdentity, sealedCopyPath } from './identity'
|
|
9
9
|
import { ownerWrapPath } from './keyring'
|
|
10
10
|
import { globalLayout, type Layout, localLayout } from './layout'
|
|
11
|
+
import { ownerDoc } from './owner-trust'
|
|
11
12
|
import { ceilingsDoc, membersDoc, parseMemberName, signersDoc, tiersDoc } from './state'
|
|
12
13
|
|
|
13
14
|
type Env = Readonly<Record<string, string | undefined>>
|
|
@@ -75,6 +76,6 @@ async function writeVault(layout: Layout, founder: Founder): Promise<SecretKey>
|
|
|
75
76
|
if (founder.sealedKey !== undefined) atomicWrite(sealedCopyPath(layout, name), founder.sealedKey)
|
|
76
77
|
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
77
78
|
// owner.json last: its presence is what marks the directory as an initialized vault.
|
|
78
|
-
atomicWrite(layout.ownerFile,
|
|
79
|
+
atomicWrite(layout.ownerFile, ownerDoc(owner))
|
|
79
80
|
return ownerKey
|
|
80
81
|
}
|
package/src/core/keyring.ts
CHANGED
|
@@ -49,7 +49,11 @@ export async function unwrapOwner(
|
|
|
49
49
|
keys: readonly SecretKey[],
|
|
50
50
|
): Promise<SecretKey | undefined> {
|
|
51
51
|
const held = keys.find((key) => key.role.kind === 'owner')
|
|
52
|
-
if (held !== undefined)
|
|
52
|
+
if (held !== undefined) {
|
|
53
|
+
if (!samePublic(await publicKeyOf(held), state.owner))
|
|
54
|
+
throw new TypeVaultError('denied', 'this owner key no longer owns the vault')
|
|
55
|
+
return held
|
|
56
|
+
}
|
|
53
57
|
for (const { name, key } of await heldMembers(state, keys)) {
|
|
54
58
|
if (state.members[name]?.owner !== true) continue
|
|
55
59
|
const owner = await openSealedKey(layout, ownerWrapPath(name), key, state.owner)
|
package/src/core/layout.ts
CHANGED
|
@@ -3,11 +3,9 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
|
3
3
|
import { homedir, hostname } from 'node:os'
|
|
4
4
|
import { dirname, join, resolve } from 'node:path'
|
|
5
5
|
|
|
6
|
-
import { z } from 'zod'
|
|
7
|
-
|
|
8
6
|
import { sha256Hex } from './crypto'
|
|
9
7
|
import { utf8 } from './encoding'
|
|
10
|
-
import {
|
|
8
|
+
import { auditChainOf, readOwnerFile } from './owner-trust'
|
|
11
9
|
|
|
12
10
|
export type Layout = {
|
|
13
11
|
/** `global`: one vault per user, `~/.typevault/`. `local`: a `.typevault/` committed in a project. */
|
|
@@ -29,6 +27,10 @@ export type Layout = {
|
|
|
29
27
|
readonly ceilingsFile: string
|
|
30
28
|
/** This checkout's audit anchors: one committed file per audit chain, so clones never check each other's. */
|
|
31
29
|
readonly anchorsFile: string
|
|
30
|
+
/** The anchors file for an audit chain already validated, so it isn't read again from owner.json. */
|
|
31
|
+
readonly anchorsFileFor: (auditChain: string) => string
|
|
32
|
+
/** The anchors file when its name doesn't come from owner.json; with a state directory only a validated state names it. */
|
|
33
|
+
readonly fixedAnchorsFile: string | undefined
|
|
32
34
|
/** Anchors from before chains had their own file; still checked against this checkout's log. */
|
|
33
35
|
readonly legacyAnchorsFile: string
|
|
34
36
|
readonly txnDir: string
|
|
@@ -149,16 +151,13 @@ function vaultLayout(scope: Layout['scope'], dir: string, env: Env): Layout {
|
|
|
149
151
|
const stateDir = setting(env, 'TYPEVAULT_STATE_DIR')
|
|
150
152
|
const root = stateDir ?? join(configDir(env), 'checkouts', shortHash(resolve(dir)))
|
|
151
153
|
// Without a state directory, a chain is named by where its log lives. With one, it is the vault's single chain,
|
|
152
|
-
// named by
|
|
154
|
+
// named by the vault's signed audit chain: nothing kept in the state directory can be lost or swapped to escape its
|
|
155
|
+
// anchors, and the name survives owner rotations.
|
|
153
156
|
const chain =
|
|
154
157
|
stateDir === undefined
|
|
155
158
|
? () => shortHash(`${hostId(env)}\0${root}`)
|
|
156
|
-
: () => `state-${vaultIdOf(
|
|
157
|
-
return build(scope, root, dir, setting(env, 'TYPEVAULT_RUN_DIR'), chain)
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function ownerSignPublic(vault: string): string {
|
|
161
|
-
return readJsonFile(join(vault, 'owner.json'), z.object({ signPublic: z.string() })).signPublic
|
|
159
|
+
: (auditChain = auditChainOf(readOwnerFile(join(dir, 'owner.json')))) => `state-${vaultIdOf(auditChain)}`
|
|
160
|
+
return build(scope, root, dir, setting(env, 'TYPEVAULT_RUN_DIR'), chain, stateDir !== undefined)
|
|
162
161
|
}
|
|
163
162
|
|
|
164
163
|
// A home directory reached through a symlink (macOS's /tmp, say) is still the same directory.
|
|
@@ -187,7 +186,8 @@ function build(
|
|
|
187
186
|
root: string,
|
|
188
187
|
vault: string,
|
|
189
188
|
runDir: string | undefined,
|
|
190
|
-
chain: () => string,
|
|
189
|
+
chain: (auditChain?: string) => string,
|
|
190
|
+
ownerNamed: boolean,
|
|
191
191
|
): Layout {
|
|
192
192
|
const audit = join(root, 'audit')
|
|
193
193
|
const run = join(root, 'run')
|
|
@@ -209,6 +209,8 @@ function build(
|
|
|
209
209
|
get anchorsFile() {
|
|
210
210
|
return join(vault, 'audit-anchors', `${chain()}.jsonl`)
|
|
211
211
|
},
|
|
212
|
+
anchorsFileFor: (auditChain) => join(vault, 'audit-anchors', `${chain(auditChain)}.jsonl`),
|
|
213
|
+
fixedAnchorsFile: ownerNamed ? undefined : join(vault, 'audit-anchors', `${chain()}.jsonl`),
|
|
212
214
|
legacyAnchorsFile: join(vault, 'audit-anchors.jsonl'),
|
|
213
215
|
// Staging lives in run/, which is never committed: a txn dir from git must not be able to steer deletes.
|
|
214
216
|
txnDir: join(run, 'txn'),
|