typevault 0.6.1 → 0.7.1
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 +16 -7
- 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 +25 -11
- package/src/cli/commands/grant.ts +7 -1
- package/src/cli/commands/members.ts +25 -9
- package/src/cli/context.ts +60 -17
- package/src/cli/index.ts +5 -3
- package/src/cli/owner-change.ts +100 -0
- package/src/core/admin.ts +173 -34
- 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/txn.ts +25 -3
- package/src/core/vault.ts +46 -10
- package/src/core/version.ts +7 -5
- package/src/daemon/admin-routes.ts +27 -17
- package/src/daemon/agent-routes.ts +96 -10
- package/src/daemon/client.ts +12 -3
- package/src/daemon/daemon.ts +58 -12
- package/src/daemon/grants.ts +9 -3
- package/src/daemon/owner-changes.ts +203 -0
- package/src/daemon/owner-window.ts +41 -0
- package/src/daemon/protocol.ts +44 -0
- package/src/daemon/requests.ts +35 -23
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
import { TypeVaultError } from '../core/errors'
|
|
4
|
+
import type { Layout } from '../core/layout'
|
|
5
|
+
import { isDaemonAlive } from '../daemon/client'
|
|
6
|
+
import type { LiveAccess } from '../daemon/live-access'
|
|
7
|
+
import { OWNER_CHANGE_KEEP_MS, readOutcome, settledResult } from '../daemon/owner-changes'
|
|
8
|
+
import { AdminResultSchema, AdmittedSchema, AdminWaitedSchema } from '../daemon/protocol'
|
|
9
|
+
|
|
10
|
+
const TRANSPORT_RETRIES = 5
|
|
11
|
+
|
|
12
|
+
type Outcome = z.infer<typeof AdminResultSchema>
|
|
13
|
+
|
|
14
|
+
// The client wraps what the transport threw (fetch, a timeout, a cut-off body); an error of our own wrapping another is not.
|
|
15
|
+
const lostInTransport = (error: unknown): error is TypeVaultError =>
|
|
16
|
+
error instanceof TypeVaultError && error.cause instanceof Error && !(error.cause instanceof TypeVaultError)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Admits an owner change under the caller's own id and polls until its outcome arrives. After an answer lost in
|
|
20
|
+
* transport, the id's receipt decides what happened before anything is sent again: a change the daemon already took
|
|
21
|
+
* (which may have rotated the owner or outlived the session since) is collected, and only a definite miss within the
|
|
22
|
+
* daemon's retry window is sent again. A change that failed is reported with its own error, never sent again. Once the
|
|
23
|
+
* daemon is gone, the outcome it kept in the run directory answers. Without either, the outcome is unknown, never
|
|
24
|
+
* reported as a failure.
|
|
25
|
+
*/
|
|
26
|
+
export async function ownerChange(
|
|
27
|
+
access: Pick<LiveAccess, 'call'>,
|
|
28
|
+
layout: Pick<Layout, 'run' | 'agentSocket'>,
|
|
29
|
+
body: { readonly change: string },
|
|
30
|
+
): Promise<Outcome> {
|
|
31
|
+
const { change } = body
|
|
32
|
+
const sentAt = Date.now()
|
|
33
|
+
let admission: 'unsent' | 'unsure' | 'admitted' = 'unsent'
|
|
34
|
+
let resent = false
|
|
35
|
+
let sentOnce = false
|
|
36
|
+
const unknown = (cause: unknown) =>
|
|
37
|
+
new TypeVaultError(
|
|
38
|
+
'unavailable',
|
|
39
|
+
"the session stopped answering, so this owner change's outcome is unknown: check the vault before running it again",
|
|
40
|
+
{ cause },
|
|
41
|
+
)
|
|
42
|
+
// A change's own errors come back as receipt states, so a refused poll is the daemon's: one that can't serve this
|
|
43
|
+
// receipt (another release's, say) says nothing of the change, and the receipt saved on disk may.
|
|
44
|
+
const poll = async () => {
|
|
45
|
+
try {
|
|
46
|
+
return await access.call('/v1/admin/wait', { change }, AdminWaitedSchema)
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (lostInTransport(error)) throw error
|
|
49
|
+
const kept = readOutcome(layout.run, change, AdminResultSchema)
|
|
50
|
+
if (kept !== undefined) return kept
|
|
51
|
+
throw unknown(error)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (let failures = 0; ;) {
|
|
55
|
+
try {
|
|
56
|
+
if (admission === 'unsure') {
|
|
57
|
+
const waited = await poll()
|
|
58
|
+
if (waited.state === 'unknown') {
|
|
59
|
+
if (resent || Date.now() - sentAt >= OWNER_CHANGE_KEEP_MS) throw unknown(undefined)
|
|
60
|
+
admission = 'unsent'
|
|
61
|
+
} else {
|
|
62
|
+
admission = 'admitted'
|
|
63
|
+
if (waited.state !== 'running') return settledResult(waited)
|
|
64
|
+
failures = 0
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (admission === 'unsent') {
|
|
69
|
+
const resending = sentOnce
|
|
70
|
+
sentOnce = true
|
|
71
|
+
admission = 'unsure'
|
|
72
|
+
try {
|
|
73
|
+
await access.call('/v1/admin', body, AdmittedSchema)
|
|
74
|
+
} catch (error) {
|
|
75
|
+
// A refused resend says nothing of the original request, which may have been admitted late and changed what the
|
|
76
|
+
// daemon accepts (an owner rotation): its receipt decides, and the resend is not tried again.
|
|
77
|
+
if (!resending || lostInTransport(error)) throw error
|
|
78
|
+
resent = true
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
admission = 'admitted'
|
|
82
|
+
}
|
|
83
|
+
const waited = await poll()
|
|
84
|
+
// An admitted change has a receipt for as long as its window lasts: without one, nothing can say what happened.
|
|
85
|
+
if (waited.state === 'unknown') throw unknown(undefined)
|
|
86
|
+
if (waited.state !== 'running') return settledResult(waited)
|
|
87
|
+
failures = 0
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (!lostInTransport(error)) throw error
|
|
90
|
+
const kept = readOutcome(layout.run, change, AdminResultSchema)
|
|
91
|
+
if (kept !== undefined) return settledResult(kept)
|
|
92
|
+
if (++failures >= TRANSPORT_RETRIES || !(await isDaemonAlive(layout.agentSocket))) {
|
|
93
|
+
// A draining daemon may have saved the outcome and closed while it was probed.
|
|
94
|
+
const late = readOutcome(layout.run, change, AdminResultSchema)
|
|
95
|
+
if (late !== undefined) return settledResult(late)
|
|
96
|
+
throw unknown(error)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
package/src/core/admin.ts
CHANGED
|
@@ -2,9 +2,10 @@ import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal,
|
|
|
2
2
|
import { fromBase64, utf8 } from './encoding'
|
|
3
3
|
import { signerOf } from './entries'
|
|
4
4
|
import { TypeVaultError } from './errors'
|
|
5
|
+
import { decodeMemberPublic } from './identity'
|
|
5
6
|
import { ownerWrapPath, wrapPath } from './keyring'
|
|
6
7
|
import { withLock } from './lock'
|
|
7
|
-
import { rotateTiers } from './rotate'
|
|
8
|
+
import { rotateOwner, rotateTiers } from './rotate'
|
|
8
9
|
import {
|
|
9
10
|
ceilingsDoc,
|
|
10
11
|
type MemberKind,
|
|
@@ -18,7 +19,7 @@ import {
|
|
|
18
19
|
signersDoc,
|
|
19
20
|
type VaultState,
|
|
20
21
|
} from './state'
|
|
21
|
-
import { commitTxn, Txn } from './txn'
|
|
22
|
+
import { commitTxn, MarkedCommitted, recoverTxns, Txn } from './txn'
|
|
22
23
|
import type { Vault } from './vault'
|
|
23
24
|
|
|
24
25
|
export type NewMember = PublicKey & {
|
|
@@ -31,6 +32,42 @@ export type NewMember = PublicKey & {
|
|
|
31
32
|
const reachOf = (state: VaultState, tiers: readonly string[]): readonly string[] =>
|
|
32
33
|
[...new Set(tiers.flatMap((tier) => [...reach(state.tiers, tier)]))].sort()
|
|
33
34
|
|
|
35
|
+
/**
|
|
36
|
+
* A change that committed, after which the vault couldn't be reloaded: its result stands, and the vault keeps the state
|
|
37
|
+
* it had until its next refresh tries again.
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* A change committed by its marker whose files couldn't be applied yet: the vault completes it when next opened. It
|
|
41
|
+
* keeps the code of what stopped it (a symlink planted in the vault stays `tampered`), but never stands for a failure.
|
|
42
|
+
*/
|
|
43
|
+
export class UncertainChange extends TypeVaultError {
|
|
44
|
+
constructor(cause: unknown) {
|
|
45
|
+
const reason = cause instanceof TypeVaultError ? ` (${cause.message})` : ''
|
|
46
|
+
super(
|
|
47
|
+
cause instanceof TypeVaultError ? cause.code : 'unavailable',
|
|
48
|
+
`the change was committed but its files could not be written yet${reason}; the vault finishes it when next opened, so check it before running this again`,
|
|
49
|
+
{ cause },
|
|
50
|
+
)
|
|
51
|
+
this.name = 'UncertainChange'
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type MemberRemoval = {
|
|
56
|
+
readonly affected: readonly string[]
|
|
57
|
+
readonly removed: readonly string[]
|
|
58
|
+
readonly ownerRotated: boolean
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class CommittedChange extends Error {
|
|
62
|
+
readonly result: unknown
|
|
63
|
+
|
|
64
|
+
constructor(result: unknown, cause: unknown) {
|
|
65
|
+
super('the change committed, but the vault could not be reloaded', { cause })
|
|
66
|
+
this.name = 'CommittedChange'
|
|
67
|
+
this.result = result
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
34
71
|
/** Owner-only changes to tiers, members, signers and ceilings. Each one lands as a single transaction. */
|
|
35
72
|
export class Admin {
|
|
36
73
|
readonly #vault: Vault
|
|
@@ -43,13 +80,28 @@ export class Admin {
|
|
|
43
80
|
this.#owner = owner
|
|
44
81
|
}
|
|
45
82
|
|
|
46
|
-
#mutate(build: (state: VaultState, txn: Txn) => Promise<
|
|
83
|
+
#mutate<T>(build: (state: VaultState, txn: Txn) => Promise<T>): Promise<T> {
|
|
47
84
|
return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
|
|
48
85
|
this.#vault.refresh()
|
|
49
86
|
const txn = new Txn()
|
|
50
|
-
await build(this.#vault.state, txn)
|
|
51
|
-
|
|
52
|
-
|
|
87
|
+
const result = await build(this.#vault.state, txn)
|
|
88
|
+
try {
|
|
89
|
+
commitTxn(this.#vault.layout, txn)
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (!(error instanceof MarkedCommitted)) throw error
|
|
92
|
+
// Committed by its marker: rolling it forward now confirms it; failing that, its outcome is uncertain, never a failure.
|
|
93
|
+
try {
|
|
94
|
+
recoverTxns(this.#vault.layout)
|
|
95
|
+
} catch (recovery) {
|
|
96
|
+
throw new UncertainChange(recovery)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
this.#vault.reload()
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw new CommittedChange(result, error)
|
|
103
|
+
}
|
|
104
|
+
return result
|
|
53
105
|
})
|
|
54
106
|
}
|
|
55
107
|
|
|
@@ -111,9 +163,8 @@ export class Admin {
|
|
|
111
163
|
* Drops an include and rotates the included tier in one transaction: a crash leaves both or neither, never a
|
|
112
164
|
* dropped include whose old wrap still opens the included tier.
|
|
113
165
|
*/
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
await this.#mutate(async (state, txn) => {
|
|
166
|
+
exclude(tier: string, included: string): Promise<readonly string[]> {
|
|
167
|
+
return this.#mutate(async (state, txn) => {
|
|
117
168
|
const holder = state.tiers[tier]
|
|
118
169
|
if (holder === undefined || !holder.includes.includes(included)) {
|
|
119
170
|
throw new TypeVaultError('not_found', `"${tier}" does not include "${included}"`)
|
|
@@ -121,23 +172,15 @@ export class Admin {
|
|
|
121
172
|
const updated = { ...holder, includes: holder.includes.filter((name) => name !== included) }
|
|
122
173
|
// Rotating removes the included tier's old generation, the dropped wrap with it, and rewrites tiers.json.
|
|
123
174
|
const context = { vault: this.#vault, owner: this.#owner, txn, exposed: true }
|
|
124
|
-
|
|
125
|
-
included,
|
|
126
|
-
])
|
|
175
|
+
return rotateTiers({ ...context, state: { ...state, tiers: { ...state.tiers, [tier]: updated } } }, [included])
|
|
127
176
|
})
|
|
128
|
-
return affected
|
|
129
177
|
}
|
|
130
178
|
|
|
131
179
|
/** Rotates every tier `name` reaches. Returns their entry names, now flagged for rotation at the source. */
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
{ vault: this.#vault, owner: this.#owner, state, txn, exposed: true },
|
|
137
|
-
reachOf(state, [name]),
|
|
138
|
-
)
|
|
139
|
-
})
|
|
140
|
-
return affected
|
|
180
|
+
rotate(name: string): Promise<readonly string[]> {
|
|
181
|
+
return this.#mutate(async (state, txn) =>
|
|
182
|
+
rotateTiers({ vault: this.#vault, owner: this.#owner, state, txn, exposed: true }, reachOf(state, [name])),
|
|
183
|
+
)
|
|
141
184
|
}
|
|
142
185
|
|
|
143
186
|
/**
|
|
@@ -152,6 +195,9 @@ export class Admin {
|
|
|
152
195
|
const unknown = member.tiers.find((tier) => state.tiers[tier] === undefined)
|
|
153
196
|
if (unknown !== undefined) throw new TypeVaultError('not_found', `no tier "${unknown}"`)
|
|
154
197
|
const { kind, recipient, signPublic, owner, tiers } = member
|
|
198
|
+
// One key under two names would survive removing either name.
|
|
199
|
+
const alias = Object.entries(state.members).find(([, other]) => other.recipient === recipient)
|
|
200
|
+
if (alias !== undefined) throw new TypeVaultError('conflict', `this key is already member "${alias[0]}"`)
|
|
155
201
|
const members = { ...state.members, [name]: { kind, recipient, signPublic, owner, tiers: [...tiers] } }
|
|
156
202
|
if (owner) txn.put(ownerWrapPath(name), await seal([recipient], utf8(encodeSecretKey(this.#owner))))
|
|
157
203
|
txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
|
|
@@ -163,22 +209,35 @@ export class Admin {
|
|
|
163
209
|
/**
|
|
164
210
|
* Drops a member and rotates every tier they reached, in one transaction: a crash leaves both or neither, never a
|
|
165
211
|
* 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.
|
|
212
|
+
* rotation: what they already decrypted can only be revoked at each secret's source. Any other name listing the same
|
|
213
|
+
* key goes too: it would otherwise keep that key's access. Also returns who was removed and whether the owner key
|
|
214
|
+
* rotated, as found under the transaction's own lock.
|
|
167
215
|
*/
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
await this.#mutate(async (state, txn) => {
|
|
216
|
+
removeMember(name: string): Promise<MemberRemoval> {
|
|
217
|
+
return this.#mutate(async (state, txn) => {
|
|
171
218
|
const member = state.members[name]
|
|
172
219
|
if (member === undefined) throw new TypeVaultError('not_found', `no member "${name}"`)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
179
|
-
|
|
220
|
+
const removed = Object.entries(state.members).filter(([, other]) => other.recipient === member.recipient)
|
|
221
|
+
const members = Object.fromEntries(
|
|
222
|
+
Object.entries(state.members).filter(([, other]) => other.recipient !== member.recipient),
|
|
223
|
+
)
|
|
224
|
+
const context = { vault: this.#vault, owner: this.#owner, state: { ...state, members }, txn, exposed: true }
|
|
225
|
+
const names = removed.map(([gone]) => gone)
|
|
226
|
+
for (const gone of names) txn.remove(`members/${gone}.key`)
|
|
227
|
+
if (removed.some(([, gone]) => gone.owner)) {
|
|
228
|
+
if (!Object.values(members).some((remaining) => remaining.owner)) {
|
|
229
|
+
throw new TypeVaultError('invalid', `"${name}" is the last owner; add another owner first`)
|
|
230
|
+
}
|
|
231
|
+
for (const [gone, { owner }] of removed) if (owner) txn.remove(ownerWrapPath(gone))
|
|
232
|
+
return { affected: await rotateOwner(context), removed: names, ownerRotated: true }
|
|
233
|
+
}
|
|
234
|
+
txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
|
|
235
|
+
const tiers = reachOf(
|
|
236
|
+
state,
|
|
237
|
+
removed.flatMap(([, gone]) => gone.tiers),
|
|
238
|
+
)
|
|
239
|
+
return { affected: await rotateTiers(context, tiers), removed: names, ownerRotated: false }
|
|
180
240
|
})
|
|
181
|
-
return affected
|
|
182
241
|
}
|
|
183
242
|
|
|
184
243
|
async setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
|
|
@@ -232,3 +291,83 @@ export class Admin {
|
|
|
232
291
|
return signerOf(this.#owner)
|
|
233
292
|
}
|
|
234
293
|
}
|
|
294
|
+
|
|
295
|
+
/** One owner change, as the CLI asks it: run here in direct mode, or by an unlocked session's daemon. */
|
|
296
|
+
export type AdminOp =
|
|
297
|
+
| {
|
|
298
|
+
readonly op: 'tier.add' | 'tier.rm' | 'key.rotate' | 'ceiling.rm' | 'signer.rm' | 'member.rm'
|
|
299
|
+
readonly name: string
|
|
300
|
+
}
|
|
301
|
+
| { readonly op: 'tier.include' | 'tier.exclude'; readonly tier: string; readonly included: string }
|
|
302
|
+
| { readonly op: 'ceiling.set'; readonly name: string; readonly tier: string }
|
|
303
|
+
| { readonly op: 'signer.add'; readonly id: string; readonly publicKey: string; readonly tiers: readonly string[] }
|
|
304
|
+
| {
|
|
305
|
+
readonly op: 'member.add'
|
|
306
|
+
readonly name: string
|
|
307
|
+
readonly publicKey: string
|
|
308
|
+
readonly owner: boolean
|
|
309
|
+
readonly tiers: readonly string[]
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export type AdminResult = {
|
|
313
|
+
/** Entries flagged for rotation at their source. */
|
|
314
|
+
readonly affected: readonly string[]
|
|
315
|
+
/** Members `member.rm` removed: every name sharing the removed key. */
|
|
316
|
+
readonly removed: readonly string[]
|
|
317
|
+
readonly ownerRotated: boolean
|
|
318
|
+
/** False when the change committed but the vault couldn't be reloaded after it. */
|
|
319
|
+
readonly reloaded: boolean
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export const runAdminOp = (vault: Vault, request: AdminOp): Promise<AdminResult> => dispatch(new Admin(vault), request)
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* A change's own result, also when it committed but the vault couldn't be reloaded after it. Every Admin method returns
|
|
326
|
+
* its transaction's result, so the result a CommittedChange carries is of that method's type.
|
|
327
|
+
*/
|
|
328
|
+
async function committed<T>(change: Promise<T>): Promise<{ readonly value: T; readonly reloaded: boolean }> {
|
|
329
|
+
try {
|
|
330
|
+
return { value: await change, reloaded: true }
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (error instanceof CommittedChange) return { value: error.result as T, reloaded: false }
|
|
333
|
+
throw error
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const NONE = { affected: [], removed: [], ownerRotated: false } as const
|
|
338
|
+
|
|
339
|
+
async function dispatch(admin: Admin, request: AdminOp): Promise<AdminResult> {
|
|
340
|
+
const plain = async (change: Promise<void>) => ({ ...NONE, reloaded: (await committed(change)).reloaded })
|
|
341
|
+
const rotation = async (change: Promise<readonly string[]>) => {
|
|
342
|
+
const { value, reloaded } = await committed(change)
|
|
343
|
+
return { ...NONE, affected: value, reloaded }
|
|
344
|
+
}
|
|
345
|
+
switch (request.op) {
|
|
346
|
+
case 'tier.add':
|
|
347
|
+
return plain(admin.addTier(request.name))
|
|
348
|
+
case 'tier.rm':
|
|
349
|
+
return plain(admin.removeTier(request.name))
|
|
350
|
+
case 'tier.include':
|
|
351
|
+
return plain(admin.include(request.tier, request.included))
|
|
352
|
+
case 'tier.exclude':
|
|
353
|
+
return rotation(admin.exclude(request.tier, request.included))
|
|
354
|
+
case 'key.rotate':
|
|
355
|
+
return rotation(admin.rotate(request.name))
|
|
356
|
+
case 'ceiling.set':
|
|
357
|
+
return plain(admin.setCeiling(request.name, request.tier))
|
|
358
|
+
case 'ceiling.rm':
|
|
359
|
+
return plain(admin.removeCeiling(request.name))
|
|
360
|
+
case 'signer.add':
|
|
361
|
+
return plain(admin.setSigner(request.id, request.publicKey, request.tiers))
|
|
362
|
+
case 'signer.rm':
|
|
363
|
+
return plain(admin.removeSigner(request.name))
|
|
364
|
+
case 'member.add': {
|
|
365
|
+
const pub = decodeMemberPublic(request.publicKey)
|
|
366
|
+
return plain(admin.addMember(request.name, { ...pub, owner: request.owner, tiers: request.tiers }))
|
|
367
|
+
}
|
|
368
|
+
case 'member.rm': {
|
|
369
|
+
const { value, reloaded } = await committed(admin.removeMember(request.name))
|
|
370
|
+
return { ...value, reloaded }
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
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
|
+
}
|