typevault 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/access/env.ts +1 -0
- package/src/access/scoped.ts +7 -1
- package/src/cli/commands/admin.ts +23 -10
- package/src/cli/commands/entries.ts +12 -5
- package/src/cli/commands/members.ts +11 -11
- package/src/cli/context.ts +85 -19
- package/src/cli/index.ts +4 -1
- package/src/cli/owner-change.ts +100 -0
- package/src/cli/requester.ts +240 -0
- package/src/core/admin.ts +151 -29
- package/src/core/identity.ts +7 -2
- package/src/core/naming.ts +30 -1
- package/src/core/passkey.ts +94 -0
- package/src/core/payload.ts +31 -0
- package/src/core/touch-id.ts +2 -1
- 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/src/import/bitwarden.ts +68 -0
- package/src/import/shared.ts +5 -1
- package/src/index.ts +1 -0
- package/src/prompt/browser.ts +1 -0
package/src/core/payload.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { z } from 'zod'
|
|
|
3
3
|
import { fromUtf8, utf8 } from './encoding'
|
|
4
4
|
import { TypeVaultError } from './errors'
|
|
5
5
|
import { type EntryName, type Field, isFieldName, isUsableEnvName, parseEntryName } from './naming'
|
|
6
|
+
import { decodeBase64Url, isP256PrivateKey, isUserHandle, MAX_SIGN_COUNT } from './passkey'
|
|
6
7
|
|
|
7
8
|
/** The plaintext sealed inside an entry file: everything except the tier is secret. */
|
|
8
9
|
export type EntryPayload = {
|
|
@@ -19,6 +20,10 @@ export type EntryPayload = {
|
|
|
19
20
|
readonly needsRotation?: boolean
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
const Base64UrlSchema = z
|
|
24
|
+
.string()
|
|
25
|
+
.refine((text) => decodeBase64Url(text) !== undefined, 'expected canonical base64url without padding')
|
|
26
|
+
|
|
22
27
|
export const FieldSchema = z.discriminatedUnion('type', [
|
|
23
28
|
z.object({ type: z.literal('secret'), value: z.string() }).strict(),
|
|
24
29
|
z.object({ type: z.literal('text'), value: z.string() }).strict(),
|
|
@@ -31,6 +36,32 @@ export const FieldSchema = z.discriminatedUnion('type', [
|
|
|
31
36
|
.refine((value) => typeof value['access_token'] === 'string', 'OAuth requires access_token'),
|
|
32
37
|
})
|
|
33
38
|
.strict(),
|
|
39
|
+
z
|
|
40
|
+
.object({
|
|
41
|
+
type: z.literal('passkey'),
|
|
42
|
+
value: z
|
|
43
|
+
.object({
|
|
44
|
+
rp_id: z.string().min(1),
|
|
45
|
+
credential_id: Base64UrlSchema,
|
|
46
|
+
private_key: z.string().refine((key) => {
|
|
47
|
+
const bytes = decodeBase64Url(key)
|
|
48
|
+
return bytes !== undefined && isP256PrivateKey(bytes)
|
|
49
|
+
}, 'expected a PKCS#8 P-256 private key in base64url'),
|
|
50
|
+
discoverable: z.boolean(),
|
|
51
|
+
user_handle: z
|
|
52
|
+
.string()
|
|
53
|
+
.refine(isUserHandle, 'expected a user handle of at most 64 bytes in canonical base64url')
|
|
54
|
+
.exactOptional(),
|
|
55
|
+
user_name: z.string().exactOptional(),
|
|
56
|
+
sign_count: z.number().int().nonnegative().max(MAX_SIGN_COUNT).exactOptional(),
|
|
57
|
+
})
|
|
58
|
+
.strict()
|
|
59
|
+
.refine(
|
|
60
|
+
(value) => !value.discoverable || value.user_handle !== undefined,
|
|
61
|
+
'a discoverable passkey needs its user_handle',
|
|
62
|
+
),
|
|
63
|
+
})
|
|
64
|
+
.strict(),
|
|
34
65
|
])
|
|
35
66
|
export const FieldsSchema = z.record(z.string().refine(isFieldName), FieldSchema)
|
|
36
67
|
|
package/src/core/touch-id.ts
CHANGED
|
@@ -81,7 +81,8 @@ export async function touchIdAvailable(): Promise<boolean> {
|
|
|
81
81
|
return hasTouchId()
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
/** `reason` completes the dialog's "typevault is trying to <reason>." */
|
|
85
|
+
export async function openWithTouchId(env: Env, seal: TouchIdSeal, reason: string): Promise<Uint8Array> {
|
|
85
86
|
const { exchangeWithEnclave } = await import('./secure-enclave')
|
|
86
87
|
return openFromEnclave(seal, (handle, ephemeral) => exchangeWithEnclave(env, handle, ephemeral, reason))
|
|
87
88
|
}
|
package/src/core/txn.ts
CHANGED
|
@@ -50,7 +50,18 @@ function checkRel(rel: string): string {
|
|
|
50
50
|
return path
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
/**
|
|
53
|
+
/** Applying a transaction failed after its commit marker: it is committed, and recovery rolls it forward. */
|
|
54
|
+
export class MarkedCommitted extends Error {
|
|
55
|
+
constructor(cause: unknown) {
|
|
56
|
+
super('the transaction is committed, but applying it failed', { cause })
|
|
57
|
+
this.name = 'MarkedCommitted'
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Stages every file, writes the commit marker, then applies. Caller must hold the exclusive vault lock. A failure
|
|
63
|
+
* before the marker leaves nothing behind; one after it is a MarkedCommitted.
|
|
64
|
+
*/
|
|
54
65
|
export function commitTxn(layout: Layout, txn: Txn): void {
|
|
55
66
|
if (txn.isEmpty) return
|
|
56
67
|
const dir = join(layout.txnDir, randomHex(8))
|
|
@@ -58,8 +69,19 @@ export function commitTxn(layout: Layout, txn: Txn): void {
|
|
|
58
69
|
const puts = [...txn.puts.keys()]
|
|
59
70
|
puts.forEach((rel, index) => atomicWrite(join(dir, 'files', String(index)), txn.puts.get(rel) ?? new Uint8Array()))
|
|
60
71
|
atomicWrite(join(dir, 'manifest.json'), JSON.stringify({ puts, removes: [...txn.removes] }))
|
|
61
|
-
|
|
62
|
-
|
|
72
|
+
const marker = join(dir, COMMITTED)
|
|
73
|
+
try {
|
|
74
|
+
atomicWrite(marker, '')
|
|
75
|
+
} catch (error) {
|
|
76
|
+
// The marker renames into place before its directory syncs: once it is there, recovery rolls the change forward.
|
|
77
|
+
if (existsSync(marker)) throw new MarkedCommitted(error)
|
|
78
|
+
throw error
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
applyTxn(layout, dir)
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new MarkedCommitted(error)
|
|
84
|
+
}
|
|
63
85
|
}
|
|
64
86
|
|
|
65
87
|
/** Idempotent: a crash halfway through is finished by running it again. */
|
package/src/core/version.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
|
|
3
|
+
import packageJson from '../../package.json' with { type: 'json' }
|
|
4
|
+
|
|
3
5
|
/**
|
|
4
|
-
* This release's version,
|
|
5
|
-
*
|
|
6
|
+
* This release's version, fixed when the module loads: a daemon reports it, so a CLI from another release knows not
|
|
7
|
+
* to talk to it. Read any later, an idle daemon would report the version of a package upgraded under it. A static
|
|
8
|
+
* import (not a file read beside the source) is inlined by the bundler, so a program built with
|
|
9
|
+
* `bun build --compile` reports it too.
|
|
6
10
|
*/
|
|
7
|
-
export const PACKAGE_VERSION = z
|
|
8
|
-
.object({ version: z.string() })
|
|
9
|
-
.parse(await Bun.file(new URL('../../package.json', import.meta.url)).json()).version
|
|
11
|
+
export const PACKAGE_VERSION = z.object({ version: z.string() }).parse(packageJson).version
|
|
@@ -13,12 +13,14 @@ export type Ceiling = { readonly name: string; readonly tier: string | '*' }
|
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* The ceiling this socket holds right now, `undefined` once removed. Read per request: the owner may lower or remove
|
|
16
|
-
* it while the daemon runs, and the socket must not keep granting what it was started with.
|
|
16
|
+
* it while the daemon runs, and the socket must not keep granting what it was started with. Without a signed ceiling,
|
|
17
|
+
* `default` is the owner's uncapped socket whenever this daemon holds the owner key, even if one was signed at startup.
|
|
17
18
|
*/
|
|
18
19
|
async function currentTier(context: DaemonContext, ceiling: Ceiling): Promise<string | undefined> {
|
|
19
20
|
const { vault } = context
|
|
20
21
|
await withLock(vault.layout.lockFile, 'shared', async () => vault.refresh())
|
|
21
|
-
|
|
22
|
+
const uncapped = ceiling.name === 'default' && vault.keyring.owner !== undefined
|
|
23
|
+
return vault.state.ceilings[ceiling.name] ?? (uncapped ? '*' : undefined)
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
function checkCeiling(context: DaemonContext, ceiling: string | undefined, tiers: readonly string[]): void {
|
|
@@ -3,12 +3,18 @@ import { randomBytes } from 'node:crypto'
|
|
|
3
3
|
import { parseTtl } from '../access/scope'
|
|
4
4
|
import { ScopedVault } from '../access/scoped'
|
|
5
5
|
import { appendAudit } from '../audit/log'
|
|
6
|
+
import { type AdminResult, runAdminOp } from '../core/admin'
|
|
6
7
|
import { TypeVaultError } from '../core/errors'
|
|
7
8
|
import type { Vault } from '../core/vault'
|
|
8
9
|
import { PACKAGE_VERSION } from '../core/version'
|
|
9
10
|
import { type GrantStore, type ResolvedGrant, SESSION_CEILING } from './grants'
|
|
10
11
|
import { type Handler, json, parseBody } from './http'
|
|
12
|
+
import { OWNER_CHANGE_POLL_MS, type OwnerChanges, readOutcome } from './owner-changes'
|
|
13
|
+
import type { OwnerWindow } from './owner-window'
|
|
11
14
|
import {
|
|
15
|
+
AdminBody,
|
|
16
|
+
AdminResultSchema,
|
|
17
|
+
AdminWaitBody,
|
|
12
18
|
AttachBody,
|
|
13
19
|
DeriveBody,
|
|
14
20
|
ImportBody,
|
|
@@ -33,8 +39,16 @@ export type DaemonContext = {
|
|
|
33
39
|
readonly sessionTiers?: readonly string[]
|
|
34
40
|
/** An unlocked session's: starts the same session in another worktree of this vault's repository, until `exp`. */
|
|
35
41
|
readonly attach?: (vault: string, exp: number) => Promise<void>
|
|
42
|
+
/** An unlocked session's: when its owner changes go through. */
|
|
43
|
+
readonly ownerWindow?: OwnerWindow
|
|
44
|
+
/** An unlocked session's: opens the admin socket of a ceiling an owner change just set; returns those that failed. */
|
|
45
|
+
readonly serveNewCeilings?: () => readonly string[]
|
|
46
|
+
/** An unlocked session's: the owner changes it admitted, run one at a time. */
|
|
47
|
+
readonly ownerChanges?: OwnerChanges<OwnerChangeResult>
|
|
36
48
|
}
|
|
37
49
|
|
|
50
|
+
export type OwnerChangeResult = AdminResult & { readonly unserved: readonly string[]; readonly scopeRefreshed: boolean }
|
|
51
|
+
|
|
38
52
|
function bearer(request: Request): string {
|
|
39
53
|
const header = request.headers.get('authorization') ?? ''
|
|
40
54
|
if (!header.startsWith('Bearer ')) throw new TypeVaultError('denied', 'missing grant (set TYPEVAULT_GRANT)')
|
|
@@ -60,6 +74,35 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
60
74
|
return { grant, access }
|
|
61
75
|
}
|
|
62
76
|
|
|
77
|
+
/** The unlocked session's own grant: a grant derived from it (an agent's) can't share it or change the vault's owner state. */
|
|
78
|
+
function ownSession(context: DaemonContext, request: Request, refusal: string): ResolvedGrant {
|
|
79
|
+
const { grant } = session(context, request)
|
|
80
|
+
if (grant.record.ceiling !== SESSION_CEILING || grant.record.parent !== undefined) {
|
|
81
|
+
throw new TypeVaultError('denied', refusal)
|
|
82
|
+
}
|
|
83
|
+
return grant
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const OWNER_ONLY = 'owner changes go through an unlocked session only'
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A session reaches every tier its key does, as when it opened: a tier an owner change added or included among them. Its
|
|
90
|
+
* cached scope is updated in place, keeping the values it handed out for redaction, and only once the grant is saved,
|
|
91
|
+
* so the two never disagree. False when finding those tiers or saving the grant failed.
|
|
92
|
+
*/
|
|
93
|
+
async function refreshScope(context: DaemonContext, grant: ResolvedGrant): Promise<boolean> {
|
|
94
|
+
let tiers: string[]
|
|
95
|
+
try {
|
|
96
|
+
tiers = [...(await context.vault.keyring.reachableTiers())].sort()
|
|
97
|
+
context.grants.retier(grant.record.id, tiers)
|
|
98
|
+
} catch (error) {
|
|
99
|
+
console.error('typevault daemon: widening the session grant after an owner change failed', error)
|
|
100
|
+
return false
|
|
101
|
+
}
|
|
102
|
+
context.sessions.get(grant.record.id)?.rescope([{ tiers, only: grant.record.only }])
|
|
103
|
+
return true
|
|
104
|
+
}
|
|
105
|
+
|
|
63
106
|
type StagedImport = {
|
|
64
107
|
readonly grant: string
|
|
65
108
|
readonly parts: Uint8Array[]
|
|
@@ -190,10 +233,49 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
190
233
|
),
|
|
191
234
|
)
|
|
192
235
|
},
|
|
193
|
-
|
|
236
|
+
'/v1/admin/challenge': async (request) => {
|
|
237
|
+
ownSession(context, request, OWNER_ONLY)
|
|
238
|
+
const window = context.ownerWindow
|
|
239
|
+
if (window === undefined) throw new TypeVaultError('denied', OWNER_ONLY)
|
|
240
|
+
return json({ open: window.isOpen, nonce: window.challenge() })
|
|
241
|
+
},
|
|
242
|
+
'/v1/admin': async (request) => {
|
|
243
|
+
const grant = ownSession(context, request, OWNER_ONLY)
|
|
244
|
+
const { ownerWindow: window, ownerChanges } = context
|
|
245
|
+
if (window === undefined || ownerChanges === undefined) throw new TypeVaultError('denied', OWNER_ONLY)
|
|
246
|
+
const { request: op, proof, change } = await parseBody(request, AdminBody)
|
|
247
|
+
// A caller that lost the answer asks again under the same id: that change already has, or will have, its outcome.
|
|
248
|
+
if (ownerChanges.has(change)) return json({ change })
|
|
249
|
+
if (proof !== undefined) {
|
|
250
|
+
const { vault } = context
|
|
251
|
+
const member = vault.member === undefined ? undefined : vault.state.members[vault.member]
|
|
252
|
+
if (member === undefined) throw new TypeVaultError('denied', 'this session holds no member key to prove')
|
|
253
|
+
window.open(proof.nonce, proof.signature, member.signPublic)
|
|
254
|
+
}
|
|
255
|
+
if (!window.isOpen) throw new TypeVaultError('locked', 'owner changes need your password or Touch ID again')
|
|
256
|
+
ownerChanges.admit(change, async () => {
|
|
257
|
+
const result = await runAdminOp(context.vault, op)
|
|
258
|
+
// Committed: what follows can't undo it, so a failure there is reported beside the result, never instead of it.
|
|
259
|
+
// A vault left on its old state can't say what the session now reaches; its next refresh reloads it or fails closed.
|
|
260
|
+
const scopeRefreshed = result.reloaded && (await refreshScope(context, grant))
|
|
261
|
+
return { ...result, scopeRefreshed, unserved: context.serveNewCeilings?.() ?? [] }
|
|
262
|
+
})
|
|
263
|
+
return json({ change })
|
|
264
|
+
},
|
|
265
|
+
// The change's own random id authorizes collecting its outcome, which names no secret value: the session that
|
|
266
|
+
// admitted it may have expired meanwhile, and the caller must still learn what to rotate at the source.
|
|
267
|
+
'/v1/admin/wait': async (request) => {
|
|
268
|
+
const { change, waitMs } = await parseBody(request, AdminWaitBody)
|
|
269
|
+
// A daemon with no owner queue (say a machine member's, started after a session drained a change and stopped)
|
|
270
|
+
// answers from the receipts that session left in the run directory.
|
|
271
|
+
if (context.ownerChanges === undefined) {
|
|
272
|
+
return json(readOutcome(context.vault.layout.run, change, AdminResultSchema) ?? { state: 'unknown' })
|
|
273
|
+
}
|
|
274
|
+
return json(await context.ownerChanges.wait(change, waitMs ?? OWNER_CHANGE_POLL_MS))
|
|
275
|
+
},
|
|
194
276
|
'/v1/attach': async (request) => {
|
|
195
|
-
const { record } =
|
|
196
|
-
if (context.attach === undefined
|
|
277
|
+
const { record } = ownSession(context, request, 'only an unlocked session can be shared with a worktree')
|
|
278
|
+
if (context.attach === undefined) {
|
|
197
279
|
throw new TypeVaultError('denied', 'only an unlocked session can be shared with a worktree')
|
|
198
280
|
}
|
|
199
281
|
const { vault } = await parseBody(request, AttachBody)
|
package/src/daemon/client.ts
CHANGED
|
@@ -16,7 +16,7 @@ const CODES: readonly ErrorCode[] = [
|
|
|
16
16
|
'no_vault',
|
|
17
17
|
'not_member',
|
|
18
18
|
]
|
|
19
|
-
const toCode = (code: string): ErrorCode => CODES.find((known) => known === code) ?? 'unavailable'
|
|
19
|
+
export const toCode = (code: string): ErrorCode => CODES.find((known) => known === code) ?? 'unavailable'
|
|
20
20
|
|
|
21
21
|
export type CallOptions = { readonly token?: string; readonly timeoutMs?: number }
|
|
22
22
|
|
|
@@ -45,11 +45,20 @@ export async function callDaemon<T>(
|
|
|
45
45
|
if (error.name === 'TimeoutError') {
|
|
46
46
|
throw new TypeVaultError('unavailable', 'the typevault daemon request timed out', { cause: error })
|
|
47
47
|
}
|
|
48
|
-
throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}
|
|
48
|
+
throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`, { cause: error })
|
|
49
|
+
}
|
|
50
|
+
throw error
|
|
51
|
+
}
|
|
52
|
+
let payload: unknown
|
|
53
|
+
try {
|
|
54
|
+
payload = await response.json()
|
|
55
|
+
} catch (error) {
|
|
56
|
+
// A reply cut off after its headers was lost in transport like a dropped connection: it is no answer from the daemon.
|
|
57
|
+
if (error instanceof Error) {
|
|
58
|
+
throw new TypeVaultError('unavailable', 'the typevault daemon reply was cut off', { cause: error })
|
|
49
59
|
}
|
|
50
60
|
throw error
|
|
51
61
|
}
|
|
52
|
-
const payload: unknown = await response.json()
|
|
53
62
|
if (!response.ok) {
|
|
54
63
|
const parsed = ErrorSchema.safeParse(payload)
|
|
55
64
|
throw parsed.success
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -13,10 +13,13 @@ import { loadState, readOwner } from '../core/state'
|
|
|
13
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
|
|
|
@@ -100,7 +103,7 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
100
103
|
if (vault.keyring.owner === undefined && vault.member === undefined) {
|
|
101
104
|
throw new TypeVaultError('denied', 'this key is not a member of the vault')
|
|
102
105
|
}
|
|
103
|
-
const ceilings = ceilingsOf(vault)
|
|
106
|
+
const ceilings = [...ceilingsOf(vault)]
|
|
104
107
|
if (ceilings.length === 0 && options.session === undefined)
|
|
105
108
|
throw new TypeVaultError('invalid', 'no ceilings configured (typevault ceiling set <name> <tier>)')
|
|
106
109
|
|
|
@@ -144,13 +147,22 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
144
147
|
requests: new PromptRequests(vault, options.prompt ?? {}),
|
|
145
148
|
...(options.session === undefined
|
|
146
149
|
? {}
|
|
147
|
-
: {
|
|
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
|
+
}),
|
|
148
157
|
}
|
|
149
158
|
// A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
|
|
150
159
|
const bound =
|
|
151
160
|
(fetch: (request: Request) => Promise<Response>) =>
|
|
152
161
|
async (request: Request): Promise<Response> => {
|
|
153
|
-
|
|
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)
|
|
154
166
|
if (!sourceAlive()) return errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
|
|
155
167
|
try {
|
|
156
168
|
// Includes cached redaction values and worktree attachment: neither necessarily scans the vault. The snapshot
|
|
@@ -168,11 +180,11 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
168
180
|
if (process.platform !== 'win32') chmodSync(path, 0o600)
|
|
169
181
|
return server
|
|
170
182
|
}
|
|
183
|
+
const serveCeiling = (ceiling: Ceiling) =>
|
|
184
|
+
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling))))
|
|
171
185
|
const servers = [
|
|
172
186
|
listen(layout.agentSocket, bound(router(agentRoutes(context)))),
|
|
173
|
-
...ceilings.map(
|
|
174
|
-
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling)))),
|
|
175
|
-
),
|
|
187
|
+
...ceilings.map(serveCeiling),
|
|
176
188
|
listen(
|
|
177
189
|
layout.controlSocket,
|
|
178
190
|
router({
|
|
@@ -184,6 +196,23 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
184
196
|
}),
|
|
185
197
|
),
|
|
186
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
|
+
}
|
|
187
216
|
atomicWrite(join(layout.run, 'daemon.pid'), String(process.pid), 0o600)
|
|
188
217
|
const session = options.session === undefined ? undefined : await openSession(context, options.session.ttlMs)
|
|
189
218
|
const adopt = (): void => {
|
|
@@ -205,8 +234,12 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
205
234
|
clearInterval(watch)
|
|
206
235
|
stopping = true
|
|
207
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()
|
|
208
240
|
// An attachment still starting would otherwise leave its worktree unlocked after this stop.
|
|
209
241
|
await Promise.allSettled(attaching)
|
|
242
|
+
await ownerChanges
|
|
210
243
|
// The claim was cleared and someone else's daemon now owns the grants, session and run files. Saving this
|
|
211
244
|
// daemon's stale grant store or removing those files would undo its successor's, so only local resources go.
|
|
212
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
|
+
}
|