typevault 0.6.1 → 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 +5 -5
- 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/state.ts +21 -23
- 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
|
@@ -22,7 +22,7 @@ import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/
|
|
|
22
22
|
import type { EntryName } from '../core/naming'
|
|
23
23
|
import { loadState } from '../core/state'
|
|
24
24
|
import { touchIdAvailable } from '../core/touch-id'
|
|
25
|
-
import { Vault } from '../core/vault'
|
|
25
|
+
import { readSnapshot, Vault } from '../core/vault'
|
|
26
26
|
import { worktreeVaults } from '../core/worktrees'
|
|
27
27
|
import { callDaemon, isDaemonAlive } from '../daemon/client'
|
|
28
28
|
import { LiveAccess } from '../daemon/live-access'
|
|
@@ -190,7 +190,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
190
190
|
}
|
|
191
191
|
if (grant.startsWith('tvl1.')) {
|
|
192
192
|
const layout = layoutFrom(env)
|
|
193
|
-
checkOwnerPin(layout, env)
|
|
193
|
+
await checkOwnerPin(layout, env)
|
|
194
194
|
await ensureDaemon(layout, env)
|
|
195
195
|
return { kind: 'live', access: new LiveAccess(layout.agentSocket, grant) }
|
|
196
196
|
}
|
|
@@ -206,7 +206,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
206
206
|
*/
|
|
207
207
|
async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
208
208
|
const layout = layoutFrom(env)
|
|
209
|
-
checkOwnerPin(layout, env)
|
|
209
|
+
await checkOwnerPin(layout, env)
|
|
210
210
|
if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
|
|
211
211
|
const identity = readIdentity(env)
|
|
212
212
|
if (identity === undefined) {
|
|
@@ -225,8 +225,8 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
|
225
225
|
* A live connection reads through a daemon that may have trusted the owner without this process's pin, so a set
|
|
226
226
|
* `TYPEVAULT_OWNER` is checked against the vault here, before anything is read through it.
|
|
227
227
|
*/
|
|
228
|
-
function checkOwnerPin(layout: Layout, env: Env): void {
|
|
229
|
-
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))
|
|
230
230
|
}
|
|
231
231
|
|
|
232
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'),
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
|
|
6
|
+
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
7
|
+
import { canonicalJson, utf8 } from './encoding'
|
|
8
|
+
import { TypeVaultError } from './errors'
|
|
9
|
+
import { atomicWrite, ensureDir } from './fsx'
|
|
10
|
+
import { readJsonFile } from './json-file'
|
|
11
|
+
import type { Layout } from './layout'
|
|
12
|
+
import { holdLock } from './lock'
|
|
13
|
+
|
|
14
|
+
export const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
|
|
15
|
+
const Link = z.object({ from: z.string(), to: PublicKeySchema, sig: z.string() })
|
|
16
|
+
const AuditChain = z.object({ chain: z.string(), sig: z.string() })
|
|
17
|
+
const Owner = PublicKeySchema.extend({ handovers: z.array(Link).default([]), audit: AuditChain.optional() })
|
|
18
|
+
type Link = z.infer<typeof Link>
|
|
19
|
+
type AuditChain = z.infer<typeof AuditChain>
|
|
20
|
+
export type Owner = z.infer<typeof Owner>
|
|
21
|
+
const Trust = z.object({ ownerSignPublic: z.string() })
|
|
22
|
+
|
|
23
|
+
const linkBytes = (from: string, to: PublicKey) => utf8(canonicalJson({ purpose: 'typevault:handover', from, to }))
|
|
24
|
+
const auditBytes = (chain: string, signPublic: string) =>
|
|
25
|
+
utf8(canonicalJson({ purpose: 'typevault:audit-chain', chain, signPublic }))
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The vault's audit identity: its first owner key, which names the state-directory audit chain. Each owner signs it
|
|
29
|
+
* again, so a machine that trusts the current owner trusts it without trusting the history in between. Until the first
|
|
30
|
+
* rotation it is the current owner key itself.
|
|
31
|
+
*/
|
|
32
|
+
export const auditChainOf = (owner: Owner): string => owner.audit?.chain ?? owner.signPublic
|
|
33
|
+
|
|
34
|
+
/** The audit identity `chain`, endorsed by the owner `key` that holds `signPublic`. */
|
|
35
|
+
export const signAuditChain = (chain: string, key: SecretKey, signPublic: string): AuditChain => ({
|
|
36
|
+
chain,
|
|
37
|
+
sig: sign(key.signSecret, auditBytes(chain, signPublic)),
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
export function handover(from: Owner, signing: SecretKey, to: PublicKey): readonly Link[] {
|
|
41
|
+
return [
|
|
42
|
+
...from.handovers,
|
|
43
|
+
{ from: from.signPublic, to, sig: sign(signing.signSecret, linkBytes(from.signPublic, to)) },
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function ownerDoc(key: PublicKey, handovers: readonly Link[] = [], audit?: AuditChain): string {
|
|
48
|
+
return `${JSON.stringify({ v: 1, ...key, handovers, ...(audit === undefined ? {} : { audit }) }, null, 2)}\n`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readOwner(layout: Layout): Owner {
|
|
52
|
+
return readOwnerFile(layout.ownerFile)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function readOwnerFile(path: string): Owner {
|
|
56
|
+
if (!existsSync(path)) throw new TypeVaultError('not_found', `no vault at ${dirname(path)} (run typevault init)`)
|
|
57
|
+
const owner = readJsonFile(path, Owner)
|
|
58
|
+
const seen = new Set([owner.signPublic])
|
|
59
|
+
let expected = owner.signPublic
|
|
60
|
+
for (const { from, to, sig } of owner.handovers.toReversed()) {
|
|
61
|
+
if (to.signPublic !== expected || seen.has(from) || !verifySignature(from, linkBytes(from, to), sig)) {
|
|
62
|
+
throw new TypeVaultError('tampered', 'invalid vault owner handover')
|
|
63
|
+
}
|
|
64
|
+
seen.add(from)
|
|
65
|
+
expected = from
|
|
66
|
+
}
|
|
67
|
+
const last = owner.handovers.at(-1)
|
|
68
|
+
if (last !== undefined && last.to.recipient !== owner.recipient)
|
|
69
|
+
throw new TypeVaultError('tampered', 'invalid handover recipient')
|
|
70
|
+
if (owner.audit === undefined) {
|
|
71
|
+
if (owner.handovers.length > 0)
|
|
72
|
+
throw new TypeVaultError('tampered', 'a rotated owner.json must sign its audit chain')
|
|
73
|
+
} else if (!verifySignature(owner.signPublic, auditBytes(owner.audit.chain, owner.signPublic), owner.audit.sig)) {
|
|
74
|
+
throw new TypeVaultError('tampered', 'invalid vault audit chain signature')
|
|
75
|
+
}
|
|
76
|
+
return owner
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Both pins are forward-only. A static deployment pin may be an ancestor, but cannot override a newer local pin. */
|
|
80
|
+
export function trustOwner(layout: Layout, owner: Owner, pinned: string | undefined): void {
|
|
81
|
+
const endorses = (key: string) => key === owner.signPublic || owner.handovers.some(({ from }) => from === key)
|
|
82
|
+
if (pinned && !endorses(pinned)) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
|
|
83
|
+
const local = () => (existsSync(layout.trustFile) ? readJsonFile(layout.trustFile, Trust).ownerSignPublic : undefined)
|
|
84
|
+
if (local() === owner.signPublic) return
|
|
85
|
+
// Different processes may finish verifying different generations concurrently. Never overwrite a newer pin.
|
|
86
|
+
ensureDir(layout.root, 0o700)
|
|
87
|
+
const release = holdLock(`${layout.trustFile}.lock`)
|
|
88
|
+
if (!release) throw new TypeVaultError('locked', 'another process is updating owner trust; retry')
|
|
89
|
+
try {
|
|
90
|
+
const current = local()
|
|
91
|
+
if (current !== undefined && !endorses(current))
|
|
92
|
+
throw new TypeVaultError('tampered', 'vault owner changed without a trusted handover')
|
|
93
|
+
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
94
|
+
} finally {
|
|
95
|
+
release()
|
|
96
|
+
}
|
|
97
|
+
}
|
package/src/core/rotate.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
|
|
1
3
|
import { encodeSecretKey, generateSecretKey, publicKeyOf, seal, type SecretKey } from './crypto'
|
|
2
|
-
import { utf8 } from './encoding'
|
|
4
|
+
import { canonicalJson, utf8 } from './encoding'
|
|
3
5
|
import { sealEntry, type SignerRef, signerOf } from './entries'
|
|
4
6
|
import { TypeVaultError } from './errors'
|
|
5
|
-
import { wrapPath } from './keyring'
|
|
6
|
-
import {
|
|
7
|
+
import { ownerWrapPath, wrapPath } from './keyring'
|
|
8
|
+
import { auditChainOf, handover, ownerDoc, readOwner, signAuditChain } from './owner-trust'
|
|
9
|
+
import { type Tier, tiersDoc, includersOf, reach, type VaultState, membersDoc, signersDoc, ceilingsDoc } from './state'
|
|
7
10
|
import type { Txn } from './txn'
|
|
8
|
-
import type { Vault } from './vault'
|
|
11
|
+
import type { ScanProblem, StoredEntry, Vault } from './vault'
|
|
9
12
|
|
|
10
13
|
export type RotateContext = {
|
|
11
14
|
readonly vault: Vault
|
|
@@ -17,6 +20,51 @@ export type RotateContext = {
|
|
|
17
20
|
readonly exposed: boolean
|
|
18
21
|
}
|
|
19
22
|
|
|
23
|
+
export async function rotateOwner(context: RotateContext): Promise<readonly string[]> {
|
|
24
|
+
const { vault, state, txn } = context
|
|
25
|
+
// Git doesn't take the vault lock, so owner.json can change under a rotation. The handover extends the owner document
|
|
26
|
+
// this rotation validated, and is staged only while owner.json still is exactly that document.
|
|
27
|
+
const previous = { recipient: state.owner.recipient, signPublic: state.owner.signPublic, handovers: state.handovers }
|
|
28
|
+
const unchanged = () => {
|
|
29
|
+
const current = readOwner(vault.layout)
|
|
30
|
+
const { recipient, signPublic, handovers } = current
|
|
31
|
+
if (
|
|
32
|
+
canonicalJson({ recipient, signPublic, handovers }) !== canonicalJson(previous) ||
|
|
33
|
+
auditChainOf(current) !== state.origin
|
|
34
|
+
)
|
|
35
|
+
throw new TypeVaultError('conflict', 'owner.json changed while rotating the owner key; pull and retry')
|
|
36
|
+
}
|
|
37
|
+
unchanged()
|
|
38
|
+
const owner = await generateSecretKey({ kind: 'owner' })
|
|
39
|
+
const pub = await publicKeyOf(owner)
|
|
40
|
+
const encoded = utf8(encodeSecretKey(owner))
|
|
41
|
+
for (const [name, member] of Object.entries(state.members)) {
|
|
42
|
+
if (member.owner) txn.put(ownerWrapPath(name), await seal([member.recipient], encoded))
|
|
43
|
+
}
|
|
44
|
+
txn.put('members.json', membersDoc(state.members, owner, state.seqs.members + 1))
|
|
45
|
+
txn.put('signers.json', signersDoc(state.signers, owner, state.seqs.signers + 1))
|
|
46
|
+
txn.put('ceilings.json', ceilingsDoc(state.ceilings, owner, state.seqs.ceilings + 1))
|
|
47
|
+
const affected = await rotateTiers({ ...context, owner, state: { ...state, owner: pub } }, Object.keys(state.tiers))
|
|
48
|
+
unchanged()
|
|
49
|
+
// The new owner endorses the same audit chain, so the vault's committed audit anchors keep their name.
|
|
50
|
+
const audit = signAuditChain(state.origin, owner, pub.signPublic)
|
|
51
|
+
txn.put('owner.json', ownerDoc(pub, handover(previous, context.owner, pub), audit))
|
|
52
|
+
return affected
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const unaccountedEntryFiles = (
|
|
56
|
+
vault: Vault,
|
|
57
|
+
entries: readonly StoredEntry[],
|
|
58
|
+
problems: readonly ScanProblem[],
|
|
59
|
+
): readonly string[] => {
|
|
60
|
+
const accounted = new Set([
|
|
61
|
+
...entries.map(({ envelope }) => `${envelope.id}.json`),
|
|
62
|
+
...problems.map(({ file }) => file),
|
|
63
|
+
])
|
|
64
|
+
const files = existsSync(vault.layout.entries) ? readdirSync(vault.layout.entries) : []
|
|
65
|
+
return files.filter((file) => file.endsWith('.json') && !accounted.has(file))
|
|
66
|
+
}
|
|
67
|
+
|
|
20
68
|
const signedBy = (signer: SignerRef, tier: string): boolean =>
|
|
21
69
|
(signer.kind === 'tier' && signer.tier === tier) ||
|
|
22
70
|
(signer.kind === 'cert' && signer.cert.issuer.kind === 'tier' && signer.cert.issuer.tier === tier)
|
|
@@ -29,7 +77,8 @@ const signedBy = (signer: SignerRef, tier: string): boolean =>
|
|
|
29
77
|
*/
|
|
30
78
|
export async function rotateTiers(context: RotateContext, names: readonly string[]): Promise<readonly string[]> {
|
|
31
79
|
const { vault, owner, state, txn, exposed } = context
|
|
32
|
-
|
|
80
|
+
const ownerChanged = state.owner.signPublic !== vault.state.owner.signPublic
|
|
81
|
+
if (names.length === 0 && !ownerChanged) return []
|
|
33
82
|
const rotated = new Map<string, { readonly key: SecretKey; readonly tier: Tier }>()
|
|
34
83
|
for (const name of new Set(names)) {
|
|
35
84
|
const meta = state.tiers[name]
|
|
@@ -71,7 +120,19 @@ export async function rotateTiers(context: RotateContext, names: readonly string
|
|
|
71
120
|
const reached = new Set([...rotated.keys()].flatMap((name) => [...reach(state.tiers, name)]))
|
|
72
121
|
const affected: string[] = []
|
|
73
122
|
const now = new Date().toISOString()
|
|
74
|
-
const { entries } = await vault.scan()
|
|
123
|
+
const { entries, problems } = await vault.scan()
|
|
124
|
+
// A scan leaves out entries no held key opens. An owner rotation must re-seal every one of them, or the ones it misses
|
|
125
|
+
// stay sealed to the old keys alone, so each entry file has to be read or reported.
|
|
126
|
+
const unopened = ownerChanged ? unaccountedEntryFiles(vault, entries, problems) : []
|
|
127
|
+
if (ownerChanged && problems.length + unopened.length > 0) {
|
|
128
|
+
const files = [...problems, ...unopened.map((file) => ({ file, reason: 'its tier key cannot be opened' }))]
|
|
129
|
+
.map(({ file, reason }) => `${file} (${reason})`)
|
|
130
|
+
.join(', ')
|
|
131
|
+
throw new TypeVaultError(
|
|
132
|
+
'tampered',
|
|
133
|
+
`cannot rotate the owner while entries are unreadable: ${files}. Run typevault doctor; move a file you can't vouch for out of entries/ (or restore it from git), then retry`,
|
|
134
|
+
)
|
|
135
|
+
}
|
|
75
136
|
for (const { envelope, payload } of entries) {
|
|
76
137
|
const reachable = reached.has(envelope.tier)
|
|
77
138
|
if (!reachable && ![...rotated.keys()].some((name) => signedBy(envelope.signer, name))) continue
|
package/src/core/state.ts
CHANGED
|
@@ -5,9 +5,9 @@ import { z } from 'zod'
|
|
|
5
5
|
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
6
6
|
import { canonicalJson, type Json, utf8 } from './encoding'
|
|
7
7
|
import { TypeVaultError } from './errors'
|
|
8
|
-
import { atomicWrite, ensureDir } from './fsx'
|
|
9
8
|
import { readJsonFile } from './json-file'
|
|
10
9
|
import type { Layout } from './layout'
|
|
10
|
+
import { auditChainOf, type Owner, PublicKeySchema, readOwner as verifiedOwner, trustOwner } from './owner-trust'
|
|
11
11
|
import { RevisionMarks } from './revisions'
|
|
12
12
|
|
|
13
13
|
export type Tier = {
|
|
@@ -42,6 +42,10 @@ export type ManifestSeqs = {
|
|
|
42
42
|
|
|
43
43
|
export type VaultState = {
|
|
44
44
|
readonly owner: PublicKey
|
|
45
|
+
/** The vault's first owner key, its audit identity: signed by the current owner and pinned on this machine. */
|
|
46
|
+
readonly origin: string
|
|
47
|
+
/** The verified handover chain that led to `owner`. */
|
|
48
|
+
readonly handovers: Owner['handovers']
|
|
45
49
|
/** Each manifest's sequence number: every signed change bumps it, and a lower one is a rollback. */
|
|
46
50
|
readonly seqs: ManifestSeqs
|
|
47
51
|
readonly tiers: Tiers
|
|
@@ -61,7 +65,6 @@ export function parseMemberName(name: string): string {
|
|
|
61
65
|
return name
|
|
62
66
|
}
|
|
63
67
|
|
|
64
|
-
const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
|
|
65
68
|
const TierSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
|
|
66
69
|
const seq = z.number().int().positive()
|
|
67
70
|
const TiersBody = z.object({ v: z.literal(1), seq, tiers: z.record(z.string(), TierSchema) })
|
|
@@ -83,7 +86,6 @@ const SignersBody = z.object({
|
|
|
83
86
|
signers: z.record(z.string(), z.object({ signPublic: z.string(), tiers: z.array(z.string()) })),
|
|
84
87
|
})
|
|
85
88
|
const CeilingsBody = z.object({ v: z.literal(1), seq, ceilings: z.record(z.string(), z.string()) })
|
|
86
|
-
const TrustSchema = z.object({ ownerSignPublic: z.string() })
|
|
87
89
|
|
|
88
90
|
export const signedDoc = (body: Json, key: SecretKey): string =>
|
|
89
91
|
`${JSON.stringify({ body, sig: sign(key.signSecret, utf8(canonicalJson(body))) }, null, 2)}\n`
|
|
@@ -106,24 +108,6 @@ function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: P
|
|
|
106
108
|
return parsed.data
|
|
107
109
|
}
|
|
108
110
|
|
|
109
|
-
/** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
|
|
110
|
-
function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<string, string | undefined>>): void {
|
|
111
|
-
const pinned = env['TYPEVAULT_OWNER']
|
|
112
|
-
if (pinned !== undefined && pinned !== '') {
|
|
113
|
-
if (pinned !== owner.signPublic) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
|
|
114
|
-
return
|
|
115
|
-
}
|
|
116
|
-
if (!existsSync(layout.trustFile)) {
|
|
117
|
-
ensureDir(layout.root, 0o700)
|
|
118
|
-
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
119
|
-
return
|
|
120
|
-
}
|
|
121
|
-
const trust = readJsonFile(layout.trustFile, TrustSchema)
|
|
122
|
-
if (trust.ownerSignPublic !== owner.signPublic) {
|
|
123
|
-
throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
111
|
export function readOwner(layout: Layout): PublicKey {
|
|
128
112
|
if (!existsSync(layout.ownerFile))
|
|
129
113
|
throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
|
|
@@ -131,14 +115,25 @@ export function readOwner(layout: Layout): PublicKey {
|
|
|
131
115
|
}
|
|
132
116
|
|
|
133
117
|
export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
|
|
134
|
-
const owner =
|
|
135
|
-
checkTrust(layout, owner, env)
|
|
118
|
+
const owner = verifiedOwner(layout)
|
|
136
119
|
const tiers = readSigned(layout.tiersFile, TiersBody, owner)
|
|
137
120
|
const members = readSigned(layout.membersFile, MembersBody, owner)
|
|
138
121
|
const signers = readSigned(layout.signersFile, SignersBody, owner)
|
|
139
122
|
const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, owner)
|
|
140
123
|
// An older, still validly signed manifest from git history would resurrect removed signers or ceilings.
|
|
141
124
|
const marks = new RevisionMarks(layout.revisionsFile)
|
|
125
|
+
if (!marks.accept('owner:handovers', owner.handovers.length)) {
|
|
126
|
+
throw new TypeVaultError('tampered', 'owner.json has fewer handovers than this machine has seen')
|
|
127
|
+
}
|
|
128
|
+
// The current owner signs the audit chain, so trusting that owner authenticates it. A machine also pins the first
|
|
129
|
+
// chain it trusted, so no later owner.json can move its audit anchors elsewhere.
|
|
130
|
+
const auditChain = auditChainOf(owner)
|
|
131
|
+
const pinned = `owner:audit:${auditChain}`
|
|
132
|
+
if (!marks.allows('owner:audit', 0) && marks.allows(pinned, 0)) {
|
|
133
|
+
throw new TypeVaultError('tampered', 'owner.json names a different audit chain than this machine trusted')
|
|
134
|
+
}
|
|
135
|
+
marks.accept('owner:audit', 1)
|
|
136
|
+
marks.accept(pinned, 1)
|
|
142
137
|
for (const [name, doc] of [
|
|
143
138
|
['tiers', tiers],
|
|
144
139
|
['members', members],
|
|
@@ -152,9 +147,12 @@ export function loadState(layout: Layout, env: Readonly<Record<string, string |
|
|
|
152
147
|
)
|
|
153
148
|
}
|
|
154
149
|
}
|
|
150
|
+
trustOwner(layout, owner, env['TYPEVAULT_OWNER'])
|
|
155
151
|
marks.save()
|
|
156
152
|
return {
|
|
157
153
|
owner,
|
|
154
|
+
origin: auditChain,
|
|
155
|
+
handovers: owner.handovers,
|
|
158
156
|
seqs: { tiers: tiers.seq, members: members.seq, signers: signers.seq, ceilings: ceilings.seq },
|
|
159
157
|
tiers: tiers.tiers,
|
|
160
158
|
members: members.members,
|
package/src/core/vault.ts
CHANGED
|
@@ -86,9 +86,29 @@ export function resolveName(tiers: Tiers, copies: readonly StoredEntry[]): Store
|
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
/** An opened vault directory plus the keys this process holds. All reads and writes go through the vault lock. */
|
|
89
|
+
const pendingTxn = (layout: Layout): boolean => existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Runs `read` under the shared vault lock, never on a half-applied transaction: a rotation re-signs manifests and wraps
|
|
93
|
+
* before owner.json, so an unlocked or unrecovered read could mix generations. A transaction left by a writer that died
|
|
94
|
+
* is rolled forward first; one that appears while waiting for the lock sends the read around again.
|
|
95
|
+
*/
|
|
96
|
+
export async function readSnapshot<T>(layout: Layout, env: Env, read: () => Promise<T>): Promise<T> {
|
|
97
|
+
// Recovery rewrites the journal, and the vault lock doesn't reach another host sharing this state directory.
|
|
98
|
+
refuseForeignDaemon(layout, env)
|
|
99
|
+
for (;;) {
|
|
100
|
+
if (pendingTxn(layout)) await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
|
|
101
|
+
const snapshot = await withLock(layout.lockFile, 'shared', async () =>
|
|
102
|
+
pendingTxn(layout) ? undefined : { value: await read() },
|
|
103
|
+
)
|
|
104
|
+
if (snapshot !== undefined) return snapshot.value
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
89
108
|
export class Vault {
|
|
90
109
|
readonly layout: Layout
|
|
91
110
|
readonly #keys: readonly SecretKey[]
|
|
111
|
+
readonly #openedOwner: string
|
|
92
112
|
readonly #env: Env
|
|
93
113
|
readonly #member: string | undefined
|
|
94
114
|
#state: VaultState
|
|
@@ -98,6 +118,7 @@ export class Vault {
|
|
|
98
118
|
this.layout = layout
|
|
99
119
|
this.#keys = keys
|
|
100
120
|
this.#env = env
|
|
121
|
+
this.#openedOwner = state.owner.signPublic
|
|
101
122
|
this.#member = member
|
|
102
123
|
this.#state = state
|
|
103
124
|
this.#keyring = new Keyring(layout, state, keys)
|
|
@@ -105,21 +126,24 @@ export class Vault {
|
|
|
105
126
|
|
|
106
127
|
/** Opens the vault with `keys`. An owner member's key also brings the owner key it unwraps. */
|
|
107
128
|
static async open(layout: Layout, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
await
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
|
|
116
|
-
return new Vault(layout, all, env, state, member?.name)
|
|
129
|
+
return readSnapshot(layout, env, async () => {
|
|
130
|
+
const state = loadState(layout, env)
|
|
131
|
+
const owner = await unwrapOwner(layout, state, keys)
|
|
132
|
+
const [member] = await heldMembers(state, keys)
|
|
133
|
+
const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
|
|
134
|
+
return new Vault(layout, all, env, state, member?.name)
|
|
135
|
+
})
|
|
117
136
|
}
|
|
118
137
|
|
|
119
138
|
get state(): VaultState {
|
|
120
139
|
return this.#state
|
|
121
140
|
}
|
|
122
141
|
|
|
142
|
+
/** The audit anchors file this vault's validated state names: the only one its audit writes checkpoint to. */
|
|
143
|
+
get anchorsFile(): string {
|
|
144
|
+
return this.layout.anchorsFileFor(this.#state.origin)
|
|
145
|
+
}
|
|
146
|
+
|
|
123
147
|
get keyring(): Keyring {
|
|
124
148
|
return this.#keyring
|
|
125
149
|
}
|
|
@@ -135,8 +159,20 @@ export class Vault {
|
|
|
135
159
|
|
|
136
160
|
/** Re-reads owner-signed state; call after another process may have changed it. */
|
|
137
161
|
refresh(): void {
|
|
162
|
+
this.reload()
|
|
163
|
+
if (this.#state.owner.signPublic !== this.#openedOwner) {
|
|
164
|
+
throw new TypeVaultError(
|
|
165
|
+
'locked',
|
|
166
|
+
'the vault owner rotated; reopen the vault (for a session, run typevault lock then typevault unlock)',
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Apply committed state without transferring an already-open handle's authority across a handover. */
|
|
172
|
+
reload(): void {
|
|
138
173
|
this.#state = loadState(this.layout, this.#env)
|
|
139
|
-
|
|
174
|
+
const keys = this.#state.owner.signPublic === this.#openedOwner ? this.#keys : []
|
|
175
|
+
this.#keyring = new Keyring(this.layout, this.#state, keys)
|
|
140
176
|
}
|
|
141
177
|
|
|
142
178
|
/** Every entry this process can open. Untrustworthy files are reported, never returned. */
|
|
@@ -66,13 +66,17 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
66
66
|
label: body.label,
|
|
67
67
|
ceiling: ceiling.name,
|
|
68
68
|
})
|
|
69
|
-
await appendAudit(
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
69
|
+
await appendAudit(
|
|
70
|
+
context.vault.layout,
|
|
71
|
+
{
|
|
72
|
+
action: 'grant.issue',
|
|
73
|
+
mode: 'live',
|
|
74
|
+
grant: record.id,
|
|
75
|
+
label: record.label,
|
|
76
|
+
tiers: record.tiers,
|
|
77
|
+
},
|
|
78
|
+
context.vault.anchorsFile,
|
|
79
|
+
)
|
|
76
80
|
return json({ token, id: record.id, exp: record.exp })
|
|
77
81
|
},
|
|
78
82
|
'/v1/grants': async () => json(context.grants.list().filter(ownedBy(ceiling, await currentTier(context, ceiling)))),
|
|
@@ -84,14 +88,18 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
84
88
|
(record) => owned(record) && (record.id === id || (label !== undefined && record.label === label)),
|
|
85
89
|
)
|
|
86
90
|
for (const grant of revoked) context.sessions.delete(grant)
|
|
87
|
-
await appendAudit(
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
91
|
+
await appendAudit(
|
|
92
|
+
context.vault.layout,
|
|
93
|
+
{
|
|
94
|
+
action: 'grant.revoke',
|
|
95
|
+
mode: 'live',
|
|
96
|
+
entries: [],
|
|
97
|
+
tiers: [],
|
|
98
|
+
...(label === undefined ? {} : { label }),
|
|
99
|
+
...(id === undefined ? {} : { grant: id }),
|
|
100
|
+
},
|
|
101
|
+
context.vault.anchorsFile,
|
|
102
|
+
)
|
|
95
103
|
return json({ revoked })
|
|
96
104
|
},
|
|
97
105
|
'/v1/audit': async (request) => {
|
|
@@ -167,13 +167,17 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
167
167
|
ceiling: grant.record.ceiling,
|
|
168
168
|
})
|
|
169
169
|
const { record } = issued
|
|
170
|
-
await appendAudit(
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
170
|
+
await appendAudit(
|
|
171
|
+
context.vault.layout,
|
|
172
|
+
{
|
|
173
|
+
action: 'grant.derive',
|
|
174
|
+
mode: 'live',
|
|
175
|
+
grant: record.id,
|
|
176
|
+
label: record.label,
|
|
177
|
+
tiers: record.tiers,
|
|
178
|
+
},
|
|
179
|
+
context.vault.anchorsFile,
|
|
180
|
+
)
|
|
177
181
|
return json({ token: issued.token, id: record.id, exp: record.exp })
|
|
178
182
|
},
|
|
179
183
|
'/v1/request': async (request) => {
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/hold
|
|
|
10
10
|
import { type Layout, localLayout } from '../core/layout'
|
|
11
11
|
import { holdLock, isLockHeld } from '../core/lock'
|
|
12
12
|
import { loadState, readOwner } from '../core/state'
|
|
13
|
-
import { Vault } from '../core/vault'
|
|
13
|
+
import { readSnapshot, Vault } from '../core/vault'
|
|
14
14
|
import { worktreeVaults } from '../core/worktrees'
|
|
15
15
|
import { adminRoutes, type Ceiling } from './admin-routes'
|
|
16
16
|
import { agentRoutes, type DaemonContext } from './agent-routes'
|
|
@@ -56,7 +56,11 @@ async function openSession(context: DaemonContext, ttlMs: number): Promise<strin
|
|
|
56
56
|
const tiers = [...(await vault.keyring.reachableTiers())].sort()
|
|
57
57
|
const { token, record } = grants.issue({ tiers, only: [], ttlMs, label: 'session', ceiling: SESSION_CEILING })
|
|
58
58
|
atomicWrite(vault.layout.sessionFile, token, 0o600)
|
|
59
|
-
await appendAudit(
|
|
59
|
+
await appendAudit(
|
|
60
|
+
vault.layout,
|
|
61
|
+
{ action: 'grant.issue', mode: 'live', grant: record.id, label: 'session', tiers },
|
|
62
|
+
vault.anchorsFile,
|
|
63
|
+
)
|
|
60
64
|
return record.id
|
|
61
65
|
}
|
|
62
66
|
|
|
@@ -145,10 +149,19 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
145
149
|
// A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
|
|
146
150
|
const bound =
|
|
147
151
|
(fetch: (request: Request) => Promise<Response>) =>
|
|
148
|
-
async (request: Request): Promise<Response> =>
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
+
async (request: Request): Promise<Response> => {
|
|
153
|
+
if (new URL(request.url).pathname === '/v1/ping') return fetch(request)
|
|
154
|
+
if (!sourceAlive()) return errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
|
|
155
|
+
try {
|
|
156
|
+
// Includes cached redaction values and worktree attachment: neither necessarily scans the vault. The snapshot
|
|
157
|
+
// finishes an interrupted rotation and keeps a running one's half-written files out of view; it's released
|
|
158
|
+
// before dispatch so writes can take the lock.
|
|
159
|
+
await readSnapshot(layout, options.env, async () => vault.refresh())
|
|
160
|
+
} catch (error) {
|
|
161
|
+
return errorResponse(error)
|
|
162
|
+
}
|
|
163
|
+
return fetch(request)
|
|
164
|
+
}
|
|
152
165
|
const listen = (path: string, fetch: (request: Request) => Promise<Response>) => {
|
|
153
166
|
const server = Bun.serve({ unix: path, fetch, maxRequestBodySize: 1 << 20 })
|
|
154
167
|
// Windows sockets take the run directory's ACL; chmod there only toggles read-only.
|
package/src/daemon/requests.ts
CHANGED
|
@@ -96,13 +96,17 @@ export class PromptRequests {
|
|
|
96
96
|
}
|
|
97
97
|
if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
|
|
98
98
|
await session.access.set({ name: input.name, fields: payload.fields, tier })
|
|
99
|
-
await appendAudit(
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
99
|
+
await appendAudit(
|
|
100
|
+
this.#vault.layout,
|
|
101
|
+
{
|
|
102
|
+
action: 'request.stored',
|
|
103
|
+
mode: 'live',
|
|
104
|
+
grant: grant.id,
|
|
105
|
+
label: grant.label,
|
|
106
|
+
entries: [input.name],
|
|
107
|
+
},
|
|
108
|
+
this.#vault.anchorsFile,
|
|
109
|
+
)
|
|
106
110
|
await handle.accept()
|
|
107
111
|
return input.name
|
|
108
112
|
} catch (error) {
|
|
@@ -111,13 +115,17 @@ export class PromptRequests {
|
|
|
111
115
|
? error
|
|
112
116
|
: new TypeVaultError('unavailable', 'the submitted secret could not be stored')
|
|
113
117
|
try {
|
|
114
|
-
await appendAudit(
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
118
|
+
await appendAudit(
|
|
119
|
+
this.#vault.layout,
|
|
120
|
+
{
|
|
121
|
+
action: 'request.rejected',
|
|
122
|
+
mode: 'live',
|
|
123
|
+
grant: grant.id,
|
|
124
|
+
label: grant.label,
|
|
125
|
+
entries: [input.name],
|
|
126
|
+
},
|
|
127
|
+
this.#vault.anchorsFile,
|
|
128
|
+
)
|
|
121
129
|
} finally {
|
|
122
130
|
await handle.reject(rejected)
|
|
123
131
|
}
|
|
@@ -134,15 +142,19 @@ export class PromptRequests {
|
|
|
134
142
|
if (!(error instanceof TypeVaultError)) console.error('typevault daemon: storing a prompted secret failed', error)
|
|
135
143
|
})
|
|
136
144
|
this.#pending.set(handle.id, { owner: grant.id, stored })
|
|
137
|
-
await appendAudit(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
145
|
+
await appendAudit(
|
|
146
|
+
this.#vault.layout,
|
|
147
|
+
{
|
|
148
|
+
action: 'request.open',
|
|
149
|
+
mode: 'live',
|
|
150
|
+
grant: grant.id,
|
|
151
|
+
label: grant.label,
|
|
152
|
+
entries: [input.name],
|
|
153
|
+
tiers: [tier],
|
|
154
|
+
reason: input.reason,
|
|
155
|
+
},
|
|
156
|
+
this.#vault.anchorsFile,
|
|
157
|
+
)
|
|
146
158
|
return { id: handle.id, url: handle.url, code, expiresAt }
|
|
147
159
|
}
|
|
148
160
|
|