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
package/src/daemon/daemon.ts
CHANGED
|
@@ -10,13 +10,16 @@ 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
|
-
import { agentRoutes, type DaemonContext } from './agent-routes'
|
|
16
|
+
import { agentRoutes, type DaemonContext, type OwnerChangeResult } from './agent-routes'
|
|
17
17
|
import { isDaemonAlive } from './client'
|
|
18
18
|
import { GrantStore, SESSION_CEILING } from './grants'
|
|
19
19
|
import { errorResponse, json, router } from './http'
|
|
20
|
+
import { OwnerChanges } from './owner-changes'
|
|
21
|
+
import { OwnerWindow } from './owner-window'
|
|
22
|
+
import { AdminResultSchema } from './protocol'
|
|
20
23
|
import { type PromptOptions, PromptRequests } from './requests'
|
|
21
24
|
import { LOCKED_MESSAGE, startSession, stopDaemon } from './spawn'
|
|
22
25
|
|
|
@@ -56,7 +59,11 @@ async function openSession(context: DaemonContext, ttlMs: number): Promise<strin
|
|
|
56
59
|
const tiers = [...(await vault.keyring.reachableTiers())].sort()
|
|
57
60
|
const { token, record } = grants.issue({ tiers, only: [], ttlMs, label: 'session', ceiling: SESSION_CEILING })
|
|
58
61
|
atomicWrite(vault.layout.sessionFile, token, 0o600)
|
|
59
|
-
await appendAudit(
|
|
62
|
+
await appendAudit(
|
|
63
|
+
vault.layout,
|
|
64
|
+
{ action: 'grant.issue', mode: 'live', grant: record.id, label: 'session', tiers },
|
|
65
|
+
vault.anchorsFile,
|
|
66
|
+
)
|
|
60
67
|
return record.id
|
|
61
68
|
}
|
|
62
69
|
|
|
@@ -96,7 +103,7 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
96
103
|
if (vault.keyring.owner === undefined && vault.member === undefined) {
|
|
97
104
|
throw new TypeVaultError('denied', 'this key is not a member of the vault')
|
|
98
105
|
}
|
|
99
|
-
const ceilings = ceilingsOf(vault)
|
|
106
|
+
const ceilings = [...ceilingsOf(vault)]
|
|
100
107
|
if (ceilings.length === 0 && options.session === undefined)
|
|
101
108
|
throw new TypeVaultError('invalid', 'no ceilings configured (typevault ceiling set <name> <tier>)')
|
|
102
109
|
|
|
@@ -140,26 +147,44 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
140
147
|
requests: new PromptRequests(vault, options.prompt ?? {}),
|
|
141
148
|
...(options.session === undefined
|
|
142
149
|
? {}
|
|
143
|
-
: {
|
|
150
|
+
: {
|
|
151
|
+
sessionTiers: member?.tiers ?? [],
|
|
152
|
+
ownerWindow: new OwnerWindow(),
|
|
153
|
+
ownerChanges: new OwnerChanges<OwnerChangeResult>(layout.run, AdminResultSchema),
|
|
154
|
+
serveNewCeilings: () => serveNewCeilings(),
|
|
155
|
+
...(attach === undefined ? {} : { attach }),
|
|
156
|
+
}),
|
|
144
157
|
}
|
|
145
158
|
// A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
|
|
146
159
|
const bound =
|
|
147
160
|
(fetch: (request: Request) => Promise<Response>) =>
|
|
148
|
-
async (request: Request): Promise<Response> =>
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
161
|
+
async (request: Request): Promise<Response> => {
|
|
162
|
+
const path = new URL(request.url).pathname
|
|
163
|
+
// Collecting an owner change's outcome reads only this daemon's memory: it must not queue behind the vault lock that
|
|
164
|
+
// change holds, and it keeps answering while a shared session whose source ended drains that change.
|
|
165
|
+
if (path === '/v1/ping' || path === '/v1/admin/wait') return fetch(request)
|
|
166
|
+
if (!sourceAlive()) return errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
|
|
167
|
+
try {
|
|
168
|
+
// Includes cached redaction values and worktree attachment: neither necessarily scans the vault. The snapshot
|
|
169
|
+
// finishes an interrupted rotation and keeps a running one's half-written files out of view; it's released
|
|
170
|
+
// before dispatch so writes can take the lock.
|
|
171
|
+
await readSnapshot(layout, options.env, async () => vault.refresh())
|
|
172
|
+
} catch (error) {
|
|
173
|
+
return errorResponse(error)
|
|
174
|
+
}
|
|
175
|
+
return fetch(request)
|
|
176
|
+
}
|
|
152
177
|
const listen = (path: string, fetch: (request: Request) => Promise<Response>) => {
|
|
153
178
|
const server = Bun.serve({ unix: path, fetch, maxRequestBodySize: 1 << 20 })
|
|
154
179
|
// Windows sockets take the run directory's ACL; chmod there only toggles read-only.
|
|
155
180
|
if (process.platform !== 'win32') chmodSync(path, 0o600)
|
|
156
181
|
return server
|
|
157
182
|
}
|
|
183
|
+
const serveCeiling = (ceiling: Ceiling) =>
|
|
184
|
+
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling))))
|
|
158
185
|
const servers = [
|
|
159
186
|
listen(layout.agentSocket, bound(router(agentRoutes(context)))),
|
|
160
|
-
...ceilings.map(
|
|
161
|
-
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling)))),
|
|
162
|
-
),
|
|
187
|
+
...ceilings.map(serveCeiling),
|
|
163
188
|
listen(
|
|
164
189
|
layout.controlSocket,
|
|
165
190
|
router({
|
|
@@ -171,6 +196,23 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
171
196
|
}),
|
|
172
197
|
),
|
|
173
198
|
]
|
|
199
|
+
// A ceiling set through this session gets its socket right away; stopping removes it with the others. One whose socket
|
|
200
|
+
// can't open stays untracked, so the next owner change tries again, and is returned: the change itself committed.
|
|
201
|
+
const serveNewCeilings = (): readonly string[] => {
|
|
202
|
+
const unserved: string[] = []
|
|
203
|
+
for (const ceiling of ceilingsOf(vault)) {
|
|
204
|
+
if (ceilings.some((served) => served.name === ceiling.name)) continue
|
|
205
|
+
try {
|
|
206
|
+
servers.push(serveCeiling(ceiling))
|
|
207
|
+
} catch (error) {
|
|
208
|
+
console.error(`typevault daemon: opening the admin socket of ceiling "${ceiling.name}" failed`, error)
|
|
209
|
+
unserved.push(ceiling.name)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
ceilings.push(ceiling)
|
|
213
|
+
}
|
|
214
|
+
return unserved
|
|
215
|
+
}
|
|
174
216
|
atomicWrite(join(layout.run, 'daemon.pid'), String(process.pid), 0o600)
|
|
175
217
|
const session = options.session === undefined ? undefined : await openSession(context, options.session.ttlMs)
|
|
176
218
|
const adopt = (): void => {
|
|
@@ -192,8 +234,12 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
192
234
|
clearInterval(watch)
|
|
193
235
|
stopping = true
|
|
194
236
|
try {
|
|
237
|
+
// Closed before the first wait, so nothing is admitted while attachments settle. A change still running would
|
|
238
|
+
// otherwise persist grants or open sockets after cleanup.
|
|
239
|
+
const ownerChanges = context.ownerChanges?.stop()
|
|
195
240
|
// An attachment still starting would otherwise leave its worktree unlocked after this stop.
|
|
196
241
|
await Promise.allSettled(attaching)
|
|
242
|
+
await ownerChanges
|
|
197
243
|
// The claim was cleared and someone else's daemon now owns the grants, session and run files. Saving this
|
|
198
244
|
// daemon's stale grant store or removing those files would undo its successor's, so only local resources go.
|
|
199
245
|
if (!claim.owns()) {
|
package/src/daemon/grants.ts
CHANGED
|
@@ -58,10 +58,12 @@ export class GrantStore {
|
|
|
58
58
|
this.#records = existsSync(path) ? readJsonFile(path, z.array(RecordSchema)) : []
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
/** Writes `records` first, so a failed write leaves the grants in memory as they are on disk. */
|
|
62
|
+
#save(records: readonly GrantRecord[] = this.#records): void {
|
|
62
63
|
const now = Date.now()
|
|
63
|
-
|
|
64
|
-
atomicWrite(this.#path, JSON.stringify(
|
|
64
|
+
const live = records.filter((record) => Date.parse(record.exp) > now)
|
|
65
|
+
atomicWrite(this.#path, JSON.stringify(live), 0o600)
|
|
66
|
+
this.#records = live
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
issue(request: GrantRequest): { readonly token: string; readonly record: GrantRecord } {
|
|
@@ -117,6 +119,10 @@ export class GrantStore {
|
|
|
117
119
|
return { record, chain: chain.map(({ tiers, only }) => ({ tiers, only })) }
|
|
118
120
|
}
|
|
119
121
|
|
|
122
|
+
retier(id: string, tiers: readonly string[]): void {
|
|
123
|
+
this.#save(this.#records.map((record) => (record.id === id ? { ...record, tiers: [...tiers] } : record)))
|
|
124
|
+
}
|
|
125
|
+
|
|
120
126
|
/** Whether grant `id` and all its ancestors are still unrevoked and unexpired. */
|
|
121
127
|
isLive(id: string): boolean {
|
|
122
128
|
for (let link = this.#records.find((r) => r.id === id); link !== undefined;) {
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
|
|
6
|
+
import { UncertainChange } from '../core/admin'
|
|
7
|
+
import { TypeVaultError } from '../core/errors'
|
|
8
|
+
import { atomicWrite, ensureDir } from '../core/fsx'
|
|
9
|
+
import { toCode } from './client'
|
|
10
|
+
|
|
11
|
+
/** Under Bun's 10-second idle timeout, which also cuts a request whose handler hasn't answered yet. */
|
|
12
|
+
export const OWNER_CHANGE_POLL_MS = 5_000
|
|
13
|
+
/** How long an outcome stays readable, and so how long admitting the same id again is recognized as a retry. */
|
|
14
|
+
export const OWNER_CHANGE_KEEP_MS = 10 * 60_000
|
|
15
|
+
export const OwnerChangeId = z.string().regex(/^[A-Za-z0-9_-]{22}$/, 'not an owner change id')
|
|
16
|
+
|
|
17
|
+
const ChangeErrorSchema = z.object({ code: z.string(), message: z.string() })
|
|
18
|
+
const Outcome = z.union([
|
|
19
|
+
z.object({ result: z.unknown() }),
|
|
20
|
+
z.object({ error: ChangeErrorSchema }),
|
|
21
|
+
z.object({ uncertain: ChangeErrorSchema }),
|
|
22
|
+
])
|
|
23
|
+
type Outcome = z.infer<typeof Outcome>
|
|
24
|
+
export type ChangeError = { readonly code: string; readonly message: string }
|
|
25
|
+
/**
|
|
26
|
+
* A settled change: what it returned, the error it failed with, or, committed by its marker but not yet written, an
|
|
27
|
+
* uncertain outcome the vault finishes later. None is the same as having no receipt.
|
|
28
|
+
*/
|
|
29
|
+
export type Settled<T> =
|
|
30
|
+
| { readonly state: 'done'; readonly result: T }
|
|
31
|
+
| { readonly state: 'failed'; readonly error: ChangeError }
|
|
32
|
+
| { readonly state: 'uncertain'; readonly error: ChangeError }
|
|
33
|
+
export type Waited<T> = Settled<T> | { readonly state: 'running' } | { readonly state: 'unknown' }
|
|
34
|
+
|
|
35
|
+
const outcomesDir = (run: string): string => join(run, 'owner-changes')
|
|
36
|
+
const outcomePath = (run: string, id: string): string => join(outcomesDir(run), `${OwnerChangeId.parse(id)}.json`)
|
|
37
|
+
|
|
38
|
+
const missing = (error: unknown): boolean => error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
|
39
|
+
|
|
40
|
+
/** Whether the receipt at `path` is past its window; one removed meanwhile counts as past it. */
|
|
41
|
+
function expired(path: string): boolean {
|
|
42
|
+
try {
|
|
43
|
+
return statSync(path).mtimeMs + OWNER_CHANGE_KEEP_MS <= Date.now()
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (missing(error)) return true
|
|
46
|
+
throw error
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Cleanup only: a receipt removed meanwhile is already gone, and one that can't be removed is refused on reads anyway.
|
|
51
|
+
function remove(path: string): void {
|
|
52
|
+
try {
|
|
53
|
+
rmSync(path)
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!missing(error)) console.error('typevault daemon: removing an expired owner-change outcome failed', error)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function readOutcome<T>(run: string, id: string, schema: z.ZodType<T>): Settled<T> | undefined {
|
|
60
|
+
const path = outcomePath(run, id)
|
|
61
|
+
if (!existsSync(path)) return undefined
|
|
62
|
+
if (expired(path)) {
|
|
63
|
+
remove(path)
|
|
64
|
+
return undefined
|
|
65
|
+
}
|
|
66
|
+
const outcome = Outcome.parse(JSON.parse(readFileSync(path, 'utf8')))
|
|
67
|
+
if ('error' in outcome) return { state: 'failed', error: outcome.error }
|
|
68
|
+
if ('uncertain' in outcome) return { state: 'uncertain', error: outcome.uncertain }
|
|
69
|
+
return { state: 'done', result: schema.parse(outcome.result) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The settled change's own result, or its own error thrown. */
|
|
73
|
+
export function settledResult<T>(settled: Settled<T>): T {
|
|
74
|
+
if (settled.state === 'done') return settled.result
|
|
75
|
+
throw new TypeVaultError(toCode(settled.error.code), settled.error.message)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Owner changes through a session, one at a time, so each publishes its effects in commit order. A rotation can outlast
|
|
80
|
+
* any one request, and the session itself, so a change is admitted at once under the caller's own random id, the
|
|
81
|
+
* receipt it polls with, and its outcome is kept for a while: in memory, and in the run directory for a caller whose
|
|
82
|
+
* daemon stopped meanwhile. Within that window, admitting an id again changes nothing, so a caller that lost the answer
|
|
83
|
+
* can ask again; past it, the id is unknown.
|
|
84
|
+
* Stopping admits nothing new, cancels what hasn't started and waits for the one running.
|
|
85
|
+
*/
|
|
86
|
+
export class OwnerChanges<T> {
|
|
87
|
+
readonly #run: string
|
|
88
|
+
readonly #schema: z.ZodType<T>
|
|
89
|
+
#tail: Promise<unknown> = Promise.resolve()
|
|
90
|
+
#stopping = false
|
|
91
|
+
readonly #changes = new Map<string, { readonly settled: Promise<Settled<T>>; settledAt?: number }>()
|
|
92
|
+
|
|
93
|
+
constructor(run: string, schema: z.ZodType<T>) {
|
|
94
|
+
this.#run = run
|
|
95
|
+
this.#schema = schema
|
|
96
|
+
this.#prune()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
has(id: string): boolean {
|
|
100
|
+
const change = this.#change(id)
|
|
101
|
+
if (change !== undefined) return true
|
|
102
|
+
const path = outcomePath(this.#run, id)
|
|
103
|
+
return existsSync(path) && !expired(path)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
admit(id: string, run: () => Promise<T>): void {
|
|
107
|
+
if (this.has(id)) return
|
|
108
|
+
if (this.#stopping) throw new TypeVaultError('locked', 'this session is locking: nothing changed')
|
|
109
|
+
this.#prune()
|
|
110
|
+
const done = this.#tail.then(() => {
|
|
111
|
+
if (this.#stopping)
|
|
112
|
+
throw new TypeVaultError('locked', 'the session locked before this change started: nothing changed')
|
|
113
|
+
return run()
|
|
114
|
+
})
|
|
115
|
+
const settled = done.then(
|
|
116
|
+
(result): Settled<T> => ({ state: 'done', result }),
|
|
117
|
+
(error: unknown): Settled<T> =>
|
|
118
|
+
error instanceof UncertainChange
|
|
119
|
+
? { state: 'uncertain', error: { code: error.code, message: error.message } }
|
|
120
|
+
: { state: 'failed', error: outcomeError(error) },
|
|
121
|
+
)
|
|
122
|
+
this.#changes.set(id, { settled })
|
|
123
|
+
this.#tail = settled.then((outcome) => this.#keep(id, onDisk(outcome)))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async wait(id: string, waitMs: number): Promise<Waited<T>> {
|
|
127
|
+
const settled = this.#change(id)?.settled
|
|
128
|
+
if (settled === undefined) return readOutcome(this.#run, id, this.#schema) ?? { state: 'unknown' }
|
|
129
|
+
const { promise: timedOut, resolve } = Promise.withResolvers<Waited<T>>()
|
|
130
|
+
const timer = setTimeout(() => resolve({ state: 'running' }), waitMs)
|
|
131
|
+
try {
|
|
132
|
+
return await Promise.race([settled, timedOut])
|
|
133
|
+
} finally {
|
|
134
|
+
clearTimeout(timer)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Closes admission at once; settles once the running change has finished and its outcome is kept. */
|
|
139
|
+
stop(): Promise<void> {
|
|
140
|
+
this.#stopping = true
|
|
141
|
+
return this.#tail.then(() => undefined)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The change has settled whatever happens here: a receipt that can't be written leaves it in memory only, and never
|
|
145
|
+
// stops the next change or a drain.
|
|
146
|
+
#change(id: string): { readonly settled: Promise<Settled<T>>; settledAt?: number } | undefined {
|
|
147
|
+
const change = this.#changes.get(id)
|
|
148
|
+
if (change?.settledAt !== undefined && change.settledAt + OWNER_CHANGE_KEEP_MS <= Date.now()) {
|
|
149
|
+
this.#changes.delete(id)
|
|
150
|
+
return undefined
|
|
151
|
+
}
|
|
152
|
+
return change
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#keep(id: string, outcome: Outcome): void {
|
|
156
|
+
const change = this.#changes.get(id)
|
|
157
|
+
if (change !== undefined) change.settledAt = Date.now()
|
|
158
|
+
setTimeout(() => this.#changes.delete(id), OWNER_CHANGE_KEEP_MS).unref()
|
|
159
|
+
try {
|
|
160
|
+
ensureDir(outcomesDir(this.#run), 0o700)
|
|
161
|
+
atomicWrite(outcomePath(this.#run, id), JSON.stringify(outcome), 0o600)
|
|
162
|
+
} catch (error) {
|
|
163
|
+
console.error('typevault daemon: keeping the outcome of an owner change on disk failed', error)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#prune(): void {
|
|
168
|
+
const dir = outcomesDir(this.#run)
|
|
169
|
+
let files: string[]
|
|
170
|
+
try {
|
|
171
|
+
files = existsSync(dir) && statSync(dir).isDirectory() ? readdirSync(dir) : []
|
|
172
|
+
} catch (error) {
|
|
173
|
+
console.error('typevault daemon: listing owner-change outcomes failed', error)
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
for (const file of files) {
|
|
177
|
+
const path = join(dir, file)
|
|
178
|
+
try {
|
|
179
|
+
if (expired(path)) remove(path)
|
|
180
|
+
} catch (error) {
|
|
181
|
+
console.error('typevault daemon: checking an owner-change outcome failed', error)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function onDisk<T>(settled: Settled<T>): Outcome {
|
|
188
|
+
switch (settled.state) {
|
|
189
|
+
case 'done':
|
|
190
|
+
return { result: settled.result }
|
|
191
|
+
case 'failed':
|
|
192
|
+
return { error: settled.error }
|
|
193
|
+
case 'uncertain':
|
|
194
|
+
return { uncertain: settled.error }
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function outcomeError(error: unknown): ChangeError {
|
|
199
|
+
if (error instanceof TypeVaultError) return { code: error.code, message: error.message }
|
|
200
|
+
// Unexpected failures stay out of outcomes, as out of responses: they may carry details an agent shouldn't see.
|
|
201
|
+
console.error('typevault daemon: owner change failed', error)
|
|
202
|
+
return { code: 'unavailable', message: 'internal daemon error' }
|
|
203
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { randomToken, verifySignature } from '../core/crypto'
|
|
2
|
+
import { utf8 } from '../core/encoding'
|
|
3
|
+
import { TypeVaultError } from '../core/errors'
|
|
4
|
+
|
|
5
|
+
export const OWNER_WINDOW_MS = 5 * 60_000
|
|
6
|
+
const CHALLENGE_TTL_MS = 5 * 60_000
|
|
7
|
+
|
|
8
|
+
export const ownerWindowMessage = (nonce: string): Uint8Array => utf8(`typevault owner window ${nonce}`)
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Agents run as the same user and can read the session token, so a session alone never makes owner changes: they go
|
|
12
|
+
* through only within a few minutes of a proof, a challenge signed with the member's own key, which only an owner
|
|
13
|
+
* command makes. It starts closed, so an unlock for reading opens nothing. A chain of owner commands asks once; an
|
|
14
|
+
* agent can't open the window itself.
|
|
15
|
+
*/
|
|
16
|
+
export class OwnerWindow {
|
|
17
|
+
#until = 0
|
|
18
|
+
readonly #challenges = new Map<string, number>()
|
|
19
|
+
|
|
20
|
+
get isOpen(): boolean {
|
|
21
|
+
return Date.now() < this.#until
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
challenge(): string {
|
|
25
|
+
const now = Date.now()
|
|
26
|
+
for (const [nonce, exp] of this.#challenges) if (exp <= now) this.#challenges.delete(nonce)
|
|
27
|
+
const nonce = randomToken(16)
|
|
28
|
+
this.#challenges.set(nonce, now + CHALLENGE_TTL_MS)
|
|
29
|
+
return nonce
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Each challenge works once, so a captured proof can't reopen the window. */
|
|
33
|
+
open(nonce: string, signature: string, signPublic: string): void {
|
|
34
|
+
const exp = this.#challenges.get(nonce)
|
|
35
|
+
this.#challenges.delete(nonce)
|
|
36
|
+
if (exp === undefined || exp <= Date.now() || !verifySignature(signPublic, ownerWindowMessage(nonce), signature)) {
|
|
37
|
+
throw new TypeVaultError('denied', 'that proof does not allow owner changes')
|
|
38
|
+
}
|
|
39
|
+
this.#until = Date.now() + OWNER_WINDOW_MS
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/daemon/protocol.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { z } from 'zod'
|
|
|
2
2
|
|
|
3
3
|
import { isPreset, parseEntryName } from '../core/naming'
|
|
4
4
|
import { FieldsSchema } from '../core/payload'
|
|
5
|
+
import { OwnerChangeId } from './owner-changes'
|
|
5
6
|
|
|
6
7
|
const name = z.string().transform((value) => parseEntryName(value))
|
|
7
8
|
const preset = z.string().refine(isPreset, 'unknown preset').optional()
|
|
@@ -51,3 +52,46 @@ export const GrantBody = z.object({
|
|
|
51
52
|
})
|
|
52
53
|
export const RevokeBody = z.object({ id: z.string().optional(), label: z.string().optional() })
|
|
53
54
|
export const AuditBody = z.object({ label: z.string().optional() })
|
|
55
|
+
const named = z.object({
|
|
56
|
+
op: z.enum(['tier.add', 'tier.rm', 'key.rotate', 'ceiling.rm', 'signer.rm', 'member.rm']),
|
|
57
|
+
name: z.string(),
|
|
58
|
+
})
|
|
59
|
+
export const AdminBody = z.object({
|
|
60
|
+
request: z.union([
|
|
61
|
+
named,
|
|
62
|
+
z.object({ op: z.enum(['tier.include', 'tier.exclude']), tier: z.string(), included: z.string() }),
|
|
63
|
+
z.object({ op: z.literal('ceiling.set'), name: z.string(), tier: z.string() }),
|
|
64
|
+
z.object({ op: z.literal('signer.add'), id: z.string(), publicKey: z.string(), tiers }),
|
|
65
|
+
z.object({ op: z.literal('member.add'), name: z.string(), publicKey: z.string(), owner: z.boolean(), tiers }),
|
|
66
|
+
]),
|
|
67
|
+
proof: z.object({ nonce: z.string().max(64), signature: z.string().max(200) }).optional(),
|
|
68
|
+
/** The caller's own id for this change: admitting it again changes nothing. */
|
|
69
|
+
change: OwnerChangeId,
|
|
70
|
+
})
|
|
71
|
+
export const AdminResultSchema = z.object({
|
|
72
|
+
affected: z.array(z.string()),
|
|
73
|
+
removed: z.array(z.string()),
|
|
74
|
+
ownerRotated: z.boolean(),
|
|
75
|
+
/** False when the change committed but the session's vault couldn't be reloaded after it. */
|
|
76
|
+
reloaded: z.boolean(),
|
|
77
|
+
/** Ceilings the change set whose admin sockets the session couldn't open. */
|
|
78
|
+
unserved: z.array(z.string()),
|
|
79
|
+
/** False when the change committed but the session's grant couldn't be widened to the tiers it now reaches. */
|
|
80
|
+
scopeRefreshed: z.boolean(),
|
|
81
|
+
})
|
|
82
|
+
export const ChallengeSchema = z.object({ open: z.boolean(), nonce: z.string() })
|
|
83
|
+
export const AdmittedSchema = z.object({ change: OwnerChangeId })
|
|
84
|
+
export const AdminWaitBody = z.object({
|
|
85
|
+
change: OwnerChangeId,
|
|
86
|
+
waitMs: z.number().int().min(0).max(5_000).optional(),
|
|
87
|
+
})
|
|
88
|
+
export const AdminWaitedSchema = z.discriminatedUnion('state', [
|
|
89
|
+
z.object({ state: z.literal('running') }),
|
|
90
|
+
/** No receipt for that id: never admitted, or past its window. */
|
|
91
|
+
z.object({ state: z.literal('unknown') }),
|
|
92
|
+
z.object({ state: z.literal('done'), result: AdminResultSchema }),
|
|
93
|
+
/** The change itself failed with this error. */
|
|
94
|
+
z.object({ state: z.literal('failed'), error: z.object({ code: z.string(), message: z.string() }) }),
|
|
95
|
+
/** Committed by its marker but not yet written: the vault finishes it when next opened. */
|
|
96
|
+
z.object({ state: z.literal('uncertain'), error: z.object({ code: z.string(), message: z.string() }) }),
|
|
97
|
+
])
|
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
|
|