typevault 0.7.0 → 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 +6 -1
- package/src/cli/commands/admin.ts +23 -10
- package/src/cli/commands/members.ts +11 -11
- package/src/cli/context.ts +55 -12
- package/src/cli/owner-change.ts +100 -0
- package/src/core/admin.ts +151 -29
- package/src/core/txn.ts +25 -3
- package/src/core/version.ts +7 -5
- package/src/daemon/admin-routes.ts +4 -2
- package/src/daemon/agent-routes.ts +85 -3
- package/src/daemon/client.ts +12 -3
- package/src/daemon/daemon.ts +40 -7
- 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/package.json
CHANGED
package/src/access/scoped.ts
CHANGED
|
@@ -39,7 +39,7 @@ const valueOf = (entry: StoredEntry): EntryValue =>
|
|
|
39
39
|
*/
|
|
40
40
|
export class ScopedVault implements Access {
|
|
41
41
|
readonly #vault: Vault
|
|
42
|
-
|
|
42
|
+
#chain: ScopeChain
|
|
43
43
|
readonly #identity: ScopedIdentity
|
|
44
44
|
readonly #handedOut = new Set<string>()
|
|
45
45
|
|
|
@@ -63,6 +63,11 @@ export class ScopedVault implements Access {
|
|
|
63
63
|
)
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
/** A new scope for the same grant; the values handed out so far stay remembered for redaction. */
|
|
67
|
+
rescope(chain: ScopeChain): void {
|
|
68
|
+
this.#chain = chain
|
|
69
|
+
}
|
|
70
|
+
|
|
66
71
|
#allows(entry: StoredEntry): boolean {
|
|
67
72
|
return allowsEntry(this.#chain, this.#vault.state, entry.envelope.tier, entry.payload.name)
|
|
68
73
|
}
|
|
@@ -14,7 +14,7 @@ import { parseEntryName } from '../../core/naming'
|
|
|
14
14
|
import { Vault } from '../../core/vault'
|
|
15
15
|
import { GrantStore } from '../../daemon/grants'
|
|
16
16
|
import { stopDaemon } from '../../daemon/spawn'
|
|
17
|
-
import { layoutFrom,
|
|
17
|
+
import { layoutFrom, openDirect, openPublic, runAdmin, wantsGlobal } from '../context'
|
|
18
18
|
import { csv, note, print, table } from '../output'
|
|
19
19
|
import { ensureIdentity, identityArgs } from './members'
|
|
20
20
|
|
|
@@ -74,23 +74,29 @@ export const tier = defineCommand({
|
|
|
74
74
|
add: defineCommand({
|
|
75
75
|
meta: { name: 'add' },
|
|
76
76
|
args: named,
|
|
77
|
-
run: async ({ args }) => (await
|
|
77
|
+
run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.add', name: args.name })),
|
|
78
78
|
}),
|
|
79
79
|
rm: defineCommand({
|
|
80
80
|
meta: { name: 'rm' },
|
|
81
81
|
args: named,
|
|
82
|
-
run: async ({ args }) => (await
|
|
82
|
+
run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.rm', name: args.name })),
|
|
83
83
|
}),
|
|
84
84
|
include: defineCommand({
|
|
85
85
|
meta: { name: 'include', description: '<tier> reaches everything <included> reaches' },
|
|
86
86
|
args: pair,
|
|
87
|
-
run: async ({ args }) =>
|
|
87
|
+
run: async ({ args }) =>
|
|
88
|
+
void (await runAdmin(process.env, { op: 'tier.include', tier: args.tier, included: args.included })),
|
|
88
89
|
}),
|
|
89
90
|
exclude: defineCommand({
|
|
90
91
|
meta: { name: 'exclude', description: 'Drop an include and rotate the included tier' },
|
|
91
92
|
args: pair,
|
|
92
93
|
async run({ args }) {
|
|
93
|
-
|
|
94
|
+
const { affected } = await runAdmin(process.env, {
|
|
95
|
+
op: 'tier.exclude',
|
|
96
|
+
tier: args.tier,
|
|
97
|
+
included: args.included,
|
|
98
|
+
})
|
|
99
|
+
printRotation(args.included, affected)
|
|
94
100
|
},
|
|
95
101
|
}),
|
|
96
102
|
},
|
|
@@ -121,7 +127,7 @@ export const key = defineCommand({
|
|
|
121
127
|
},
|
|
122
128
|
args: named,
|
|
123
129
|
async run({ args }) {
|
|
124
|
-
printRotation(args.name,
|
|
130
|
+
printRotation(args.name, (await runAdmin(process.env, { op: 'key.rotate', name: args.name })).affected)
|
|
125
131
|
},
|
|
126
132
|
}),
|
|
127
133
|
},
|
|
@@ -140,12 +146,13 @@ export const ceiling = defineCommand({
|
|
|
140
146
|
set: defineCommand({
|
|
141
147
|
meta: { name: 'set' },
|
|
142
148
|
args: { name: { type: 'positional', required: true }, tier: { type: 'positional', required: true } },
|
|
143
|
-
run: async ({ args }) =>
|
|
149
|
+
run: async ({ args }) =>
|
|
150
|
+
void (await runAdmin(process.env, { op: 'ceiling.set', name: args.name, tier: args.tier })),
|
|
144
151
|
}),
|
|
145
152
|
rm: defineCommand({
|
|
146
153
|
meta: { name: 'rm' },
|
|
147
154
|
args: named,
|
|
148
|
-
run: async ({ args }) => (await
|
|
155
|
+
run: async ({ args }) => void (await runAdmin(process.env, { op: 'ceiling.rm', name: args.name })),
|
|
149
156
|
}),
|
|
150
157
|
},
|
|
151
158
|
})
|
|
@@ -169,12 +176,18 @@ export const signer = defineCommand({
|
|
|
169
176
|
publicKey: { type: 'positional', required: true, description: 'Base64 Ed25519 public key' },
|
|
170
177
|
tiers: { type: 'string', required: true, description: 'Comma-separated tiers, or *' },
|
|
171
178
|
},
|
|
172
|
-
run: async ({ args }) =>
|
|
179
|
+
run: async ({ args }) =>
|
|
180
|
+
void (await runAdmin(process.env, {
|
|
181
|
+
op: 'signer.add',
|
|
182
|
+
id: args.id,
|
|
183
|
+
publicKey: args.publicKey,
|
|
184
|
+
tiers: csv(args.tiers),
|
|
185
|
+
})),
|
|
173
186
|
}),
|
|
174
187
|
rm: defineCommand({
|
|
175
188
|
meta: { name: 'rm' },
|
|
176
189
|
args: named,
|
|
177
|
-
run: async ({ args }) => (await
|
|
190
|
+
run: async ({ args }) => void (await runAdmin(process.env, { op: 'signer.rm', name: args.name })),
|
|
178
191
|
}),
|
|
179
192
|
},
|
|
180
193
|
})
|
|
@@ -4,7 +4,6 @@ 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'
|
|
8
7
|
import { publicKeyOf } from '../../core/crypto'
|
|
9
8
|
import { TypeVaultError } from '../../core/errors'
|
|
10
9
|
import { atomicWrite } from '../../core/fsx'
|
|
@@ -32,9 +31,8 @@ import {
|
|
|
32
31
|
DEFAULT_SESSION_MS,
|
|
33
32
|
findLayout,
|
|
34
33
|
layoutFrom,
|
|
35
|
-
openAdmin,
|
|
36
|
-
openDirect,
|
|
37
34
|
openPublic,
|
|
35
|
+
runAdmin,
|
|
38
36
|
unlockSession,
|
|
39
37
|
worktreeSessions,
|
|
40
38
|
type Env,
|
|
@@ -130,7 +128,13 @@ export const member = defineCommand({
|
|
|
130
128
|
if (tiers.length === 0 && args.owner !== true)
|
|
131
129
|
throw new TypeVaultError('invalid', 'member add needs --tier or --owner')
|
|
132
130
|
const pub = decodeMemberPublic(args.publicKey)
|
|
133
|
-
await (
|
|
131
|
+
await runAdmin(process.env, {
|
|
132
|
+
op: 'member.add',
|
|
133
|
+
name: args.name,
|
|
134
|
+
publicKey: args.publicKey,
|
|
135
|
+
owner: args.owner === true,
|
|
136
|
+
tiers,
|
|
137
|
+
})
|
|
134
138
|
print(`added ${pub.kind} member ${args.name}${tiers.length === 0 ? '' : ` (rotated ${tiers.join(', ')})`}`)
|
|
135
139
|
note('commit the vault so they can pull it')
|
|
136
140
|
},
|
|
@@ -139,14 +143,10 @@ export const member = defineCommand({
|
|
|
139
143
|
meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
|
|
140
144
|
args: { name: { type: 'positional', required: true } },
|
|
141
145
|
async run({ args }) {
|
|
142
|
-
const
|
|
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)
|
|
146
|
+
const { affected, removed, ownerRotated } = await runAdmin(process.env, { op: 'member.rm', name: args.name })
|
|
147
147
|
print(`removed ${removed.join(', ')}`)
|
|
148
148
|
if (removed.length > 1) note(`${removed.join(', ')} shared one key, so all of them were removed.`)
|
|
149
|
-
if (
|
|
149
|
+
if (ownerRotated) {
|
|
150
150
|
note(
|
|
151
151
|
'Owner key rotated. Commit the vault; members must pull it. For an open session, run typevault lock then typevault unlock.',
|
|
152
152
|
)
|
|
@@ -247,7 +247,7 @@ export const unlock = defineCommand({
|
|
|
247
247
|
const env = process.env
|
|
248
248
|
const ttlMs = args.for === undefined ? DEFAULT_SESSION_MS : parseTtl(args.for)
|
|
249
249
|
if (ttlMs > MAX_TIMER_MS) throw new TypeVaultError('invalid', '--for is too long (at most 24 days)')
|
|
250
|
-
const started = await unlockSession(env, passwords(), ttlMs)
|
|
250
|
+
const started = (await unlockSession(env, passwords(), ttlMs)) !== undefined
|
|
251
251
|
const id = vaultIdOf((await openPublic(env)).state.owner.signPublic)
|
|
252
252
|
print(started ? `unlocked vault ${id} for ${args.for}` : `vault ${id} is already unlocked`)
|
|
253
253
|
},
|
package/src/cli/context.ts
CHANGED
|
@@ -7,8 +7,8 @@ import { ScopedVault } from '../access/scoped'
|
|
|
7
7
|
import { readSealedGrant } from '../access/sealed'
|
|
8
8
|
import { SealedAccess } from '../access/sealed-access'
|
|
9
9
|
import type { Access, EntryValue } from '../access/types'
|
|
10
|
-
import {
|
|
11
|
-
import type
|
|
10
|
+
import { type AdminOp, type AdminResult, runAdminOp } from '../core/admin'
|
|
11
|
+
import { randomToken, type SecretKey, sign } from '../core/crypto'
|
|
12
12
|
import { TypeVaultError } from '../core/errors'
|
|
13
13
|
import { atomicWrite } from '../core/fsx'
|
|
14
14
|
import {
|
|
@@ -26,8 +26,11 @@ 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'
|
|
29
|
+
import { ownerWindowMessage } from '../daemon/owner-window'
|
|
30
|
+
import { ChallengeSchema } from '../daemon/protocol'
|
|
29
31
|
import { ensureDaemon, LOCKED_MESSAGE, startSession, stopDaemon } from '../daemon/spawn'
|
|
30
32
|
import { note } from './output'
|
|
33
|
+
import { ownerChange } from './owner-change'
|
|
31
34
|
import { type Passwords, passwords, passwordsFromStdin } from './password'
|
|
32
35
|
|
|
33
36
|
export type Env = Readonly<Record<string, string | undefined>>
|
|
@@ -102,11 +105,11 @@ export async function unlockHuman(env: Env, identity: Identity | undefined, pass
|
|
|
102
105
|
|
|
103
106
|
/**
|
|
104
107
|
* Unlocks a human member's session: their key goes to a daemon that holds it for `ttlMs`, and this user's CLI
|
|
105
|
-
* reads through the session grant it writes. Returns
|
|
108
|
+
* reads through the session grant it writes. Returns the key it unlocked with, or undefined when a session already runs.
|
|
106
109
|
*/
|
|
107
|
-
export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<
|
|
110
|
+
export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<SecretKey | undefined> {
|
|
108
111
|
const layout = layoutFrom(env)
|
|
109
|
-
if (await hasSession(layout)) return
|
|
112
|
+
if (await hasSession(layout)) return undefined
|
|
110
113
|
const identity = readIdentity(env)
|
|
111
114
|
const key = await unlockHuman(env, identity, passwords)
|
|
112
115
|
const vault = await Vault.open(layout, [key], env)
|
|
@@ -124,7 +127,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
|
|
|
124
127
|
note('replaced a running daemon that held no unlocked session')
|
|
125
128
|
}
|
|
126
129
|
await startSession(layout, env, key, ttlMs)
|
|
127
|
-
return
|
|
130
|
+
return key
|
|
128
131
|
}
|
|
129
132
|
|
|
130
133
|
const hasSession = async (layout: Layout): Promise<boolean> =>
|
|
@@ -169,7 +172,44 @@ function refreshSealedCopy(vault: Vault, identity: Identity & { readonly kind: '
|
|
|
169
172
|
/** The vault's public, owner-signed state, readable without any key. */
|
|
170
173
|
export const openPublic = (env: Env): Promise<Vault> => Vault.open(layoutFrom(env), [], env)
|
|
171
174
|
|
|
172
|
-
|
|
175
|
+
/**
|
|
176
|
+
* An owner change. A machine member makes it with its own key, and a process under a grant never borrows the person's
|
|
177
|
+
* session for one. A person's goes through their unlocked session (unlocking it first, as a read does), proving they
|
|
178
|
+
* are there with the key that unlock used, or else asking for it once the session's owner window has closed.
|
|
179
|
+
*/
|
|
180
|
+
export async function runAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
|
|
181
|
+
const direct = machineKeys(env).length > 0 || isSet(env['TYPEVAULT_GRANT'])
|
|
182
|
+
const result = direct ? await runAdminOp(await openDirect(env), request) : await sessionAdmin(env, request)
|
|
183
|
+
if (!result.reloaded) {
|
|
184
|
+
note(
|
|
185
|
+
'the change committed, but the vault could not be reloaded after it: run typevault lock, then typevault unlock',
|
|
186
|
+
)
|
|
187
|
+
}
|
|
188
|
+
return result
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function sessionAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
|
|
192
|
+
const { access, unlockedWith } = await sessionAccess(env)
|
|
193
|
+
const { open, nonce } = await access.call('/v1/admin/challenge', {}, ChallengeSchema)
|
|
194
|
+
const key = open ? undefined : (unlockedWith ?? (await ownerKey(env)))
|
|
195
|
+
const proof = key === undefined ? undefined : { nonce, signature: sign(key.signSecret, ownerWindowMessage(nonce)) }
|
|
196
|
+
const body = { request, change: randomToken(16), ...(proof === undefined ? {} : { proof }) }
|
|
197
|
+
const { unserved, scopeRefreshed, ...result } = await ownerChange(access, layoutFrom(env), body)
|
|
198
|
+
if (!scopeRefreshed && result.reloaded) {
|
|
199
|
+
note('this session does not reach the tiers the change added yet: run typevault lock, then typevault unlock')
|
|
200
|
+
}
|
|
201
|
+
for (const name of unserved) {
|
|
202
|
+
note(`ceiling "${name}" is set, but its admin socket didn't open: run typevault lock, then typevault unlock`)
|
|
203
|
+
}
|
|
204
|
+
return result
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function ownerKey(env: Env): Promise<SecretKey> {
|
|
208
|
+
if (!process.stdin.isTTY && !passwordsFromStdin()) {
|
|
209
|
+
throw new TypeVaultError('locked', 'owner changes need your password or Touch ID: run this at a terminal')
|
|
210
|
+
}
|
|
211
|
+
return unlockHuman(env, readIdentity(env), passwords())
|
|
212
|
+
}
|
|
173
213
|
|
|
174
214
|
export type ResolvedAccess =
|
|
175
215
|
| { readonly kind: 'live'; readonly access: LiveAccess }
|
|
@@ -181,7 +221,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
181
221
|
const grant = env['TYPEVAULT_GRANT']?.trim()
|
|
182
222
|
if (grant === undefined || grant === '') {
|
|
183
223
|
const machine = machineKeys(env)
|
|
184
|
-
if (machine.length === 0) return { kind: 'live', access: await sessionAccess(env) }
|
|
224
|
+
if (machine.length === 0) return { kind: 'live', access: (await sessionAccess(env)).access }
|
|
185
225
|
const tier = env['TYPEVAULT_TIER']
|
|
186
226
|
const vault = await Vault.open(layoutFrom(env), machine, env)
|
|
187
227
|
const ownTiers = vault.member === undefined ? [] : (vault.state.members[vault.member]?.tiers ?? [])
|
|
@@ -202,11 +242,13 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
202
242
|
|
|
203
243
|
/**
|
|
204
244
|
* A human member's CLI reads through the unlocked session's grant. On a terminal a locked vault asks for the
|
|
205
|
-
* password right away; anywhere else (an agent) it stays locked until a human unlocks it.
|
|
245
|
+
* password right away; anywhere else (an agent) it stays locked until a human unlocks it. `unlockedWith` is the key a
|
|
246
|
+
* person just unlocked with here.
|
|
206
247
|
*/
|
|
207
|
-
async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
248
|
+
async function sessionAccess(env: Env): Promise<{ readonly access: LiveAccess; readonly unlockedWith?: SecretKey }> {
|
|
208
249
|
const layout = layoutFrom(env)
|
|
209
250
|
await checkOwnerPin(layout, env)
|
|
251
|
+
let unlockedWith: SecretKey | undefined
|
|
210
252
|
if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
|
|
211
253
|
const identity = readIdentity(env)
|
|
212
254
|
if (identity === undefined) {
|
|
@@ -214,11 +256,12 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
|
214
256
|
}
|
|
215
257
|
const canAsk = process.stdin.isTTY || passwordsFromStdin()
|
|
216
258
|
if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
217
|
-
await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
|
|
259
|
+
unlockedWith = await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
|
|
218
260
|
}
|
|
219
261
|
// A session daemon from another release fails here instead of misreading this CLI's requests.
|
|
220
262
|
await ensureDaemon(layout, env)
|
|
221
|
-
|
|
263
|
+
const access = new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
|
|
264
|
+
return unlockedWith === undefined ? { access } : { access, unlockedWith }
|
|
222
265
|
}
|
|
223
266
|
|
|
224
267
|
/**
|
|
@@ -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,6 +2,7 @@ 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
8
|
import { rotateOwner, rotateTiers } from './rotate'
|
|
@@ -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
|
|
@@ -48,8 +85,22 @@ export class Admin {
|
|
|
48
85
|
this.#vault.refresh()
|
|
49
86
|
const txn = new Txn()
|
|
50
87
|
const result = await build(this.#vault.state, txn)
|
|
51
|
-
|
|
52
|
-
|
|
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
|
+
}
|
|
53
104
|
return result
|
|
54
105
|
})
|
|
55
106
|
}
|
|
@@ -112,9 +163,8 @@ export class Admin {
|
|
|
112
163
|
* Drops an include and rotates the included tier in one transaction: a crash leaves both or neither, never a
|
|
113
164
|
* dropped include whose old wrap still opens the included tier.
|
|
114
165
|
*/
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
await this.#mutate(async (state, txn) => {
|
|
166
|
+
exclude(tier: string, included: string): Promise<readonly string[]> {
|
|
167
|
+
return this.#mutate(async (state, txn) => {
|
|
118
168
|
const holder = state.tiers[tier]
|
|
119
169
|
if (holder === undefined || !holder.includes.includes(included)) {
|
|
120
170
|
throw new TypeVaultError('not_found', `"${tier}" does not include "${included}"`)
|
|
@@ -122,23 +172,15 @@ export class Admin {
|
|
|
122
172
|
const updated = { ...holder, includes: holder.includes.filter((name) => name !== included) }
|
|
123
173
|
// Rotating removes the included tier's old generation, the dropped wrap with it, and rewrites tiers.json.
|
|
124
174
|
const context = { vault: this.#vault, owner: this.#owner, txn, exposed: true }
|
|
125
|
-
|
|
126
|
-
included,
|
|
127
|
-
])
|
|
175
|
+
return rotateTiers({ ...context, state: { ...state, tiers: { ...state.tiers, [tier]: updated } } }, [included])
|
|
128
176
|
})
|
|
129
|
-
return affected
|
|
130
177
|
}
|
|
131
178
|
|
|
132
179
|
/** Rotates every tier `name` reaches. Returns their entry names, now flagged for rotation at the source. */
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
{ vault: this.#vault, owner: this.#owner, state, txn, exposed: true },
|
|
138
|
-
reachOf(state, [name]),
|
|
139
|
-
)
|
|
140
|
-
})
|
|
141
|
-
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
|
+
)
|
|
142
184
|
}
|
|
143
185
|
|
|
144
186
|
/**
|
|
@@ -168,9 +210,10 @@ export class Admin {
|
|
|
168
210
|
* Drops a member and rotates every tier they reached, in one transaction: a crash leaves both or neither, never a
|
|
169
211
|
* removed member whose keys still open new ciphertext. Returns the entries they could read, now flagged for
|
|
170
212
|
* 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.
|
|
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.
|
|
172
215
|
*/
|
|
173
|
-
removeMember(name: string): Promise<
|
|
216
|
+
removeMember(name: string): Promise<MemberRemoval> {
|
|
174
217
|
return this.#mutate(async (state, txn) => {
|
|
175
218
|
const member = state.members[name]
|
|
176
219
|
if (member === undefined) throw new TypeVaultError('not_found', `no member "${name}"`)
|
|
@@ -179,22 +222,21 @@ export class Admin {
|
|
|
179
222
|
Object.entries(state.members).filter(([, other]) => other.recipient !== member.recipient),
|
|
180
223
|
)
|
|
181
224
|
const context = { vault: this.#vault, owner: this.#owner, state: { ...state, members }, txn, exposed: true }
|
|
182
|
-
|
|
225
|
+
const names = removed.map(([gone]) => gone)
|
|
226
|
+
for (const gone of names) txn.remove(`members/${gone}.key`)
|
|
183
227
|
if (removed.some(([, gone]) => gone.owner)) {
|
|
184
228
|
if (!Object.values(members).some((remaining) => remaining.owner)) {
|
|
185
229
|
throw new TypeVaultError('invalid', `"${name}" is the last owner; add another owner first`)
|
|
186
230
|
}
|
|
187
231
|
for (const [gone, { owner }] of removed) if (owner) txn.remove(ownerWrapPath(gone))
|
|
188
|
-
return rotateOwner(context)
|
|
232
|
+
return { affected: await rotateOwner(context), removed: names, ownerRotated: true }
|
|
189
233
|
}
|
|
190
234
|
txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
state,
|
|
195
|
-
removed.flatMap(([, gone]) => gone.tiers),
|
|
196
|
-
),
|
|
235
|
+
const tiers = reachOf(
|
|
236
|
+
state,
|
|
237
|
+
removed.flatMap(([, gone]) => gone.tiers),
|
|
197
238
|
)
|
|
239
|
+
return { affected: await rotateTiers(context, tiers), removed: names, ownerRotated: false }
|
|
198
240
|
})
|
|
199
241
|
}
|
|
200
242
|
|
|
@@ -249,3 +291,83 @@ export class Admin {
|
|
|
249
291
|
return signerOf(this.#owner)
|
|
250
292
|
}
|
|
251
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
|
+
}
|