typevault 0.1.0 → 0.3.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/README.md +156 -115
- package/package.json +14 -2
- package/src/access/env.ts +77 -17
- package/src/access/keys.ts +14 -14
- package/src/access/schemas.ts +6 -12
- package/src/access/scope.ts +14 -9
- package/src/access/scoped.ts +118 -44
- package/src/access/sealed-access.ts +50 -23
- package/src/access/sealed.ts +56 -31
- package/src/access/types.ts +27 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +28 -12
- package/src/cli/commands/admin.ts +93 -48
- package/src/cli/commands/daemon.ts +42 -17
- package/src/cli/commands/entries.ts +195 -60
- package/src/cli/commands/grant.ts +24 -22
- package/src/cli/commands/members.ts +307 -0
- package/src/cli/commands/run.ts +191 -44
- package/src/cli/context.ts +163 -15
- package/src/cli/index.ts +33 -5
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +79 -0
- package/src/core/admin.ts +144 -76
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +15 -16
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +8 -2
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +87 -0
- package/src/core/identity.ts +132 -0
- package/src/core/init.ts +73 -23
- package/src/core/json-file.ts +20 -0
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +143 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +150 -50
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +11 -6
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +102 -54
- package/src/core/txn.ts +9 -7
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +51 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +31 -11
- package/src/daemon/client.ts +24 -2
- package/src/daemon/daemon.ts +218 -33
- package/src/daemon/grants.ts +25 -7
- package/src/daemon/http.ts +11 -2
- package/src/daemon/live-access.ts +8 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +75 -51
- package/src/daemon/spawn.ts +218 -9
- package/src/export/1password.ts +157 -0
- package/src/import/1password-live.ts +399 -0
- package/src/import/1password.ts +26 -5
- package/src/import/bitwarden.ts +3 -3
- package/src/import/csv.ts +1 -1
- package/src/import/dotenv.ts +4 -3
- package/src/import/index.ts +1 -0
- package/src/import/keepass.ts +2 -2
- package/src/import/lastpass.ts +2 -2
- package/src/import/shared.ts +67 -10
- package/src/import/typeclaw.ts +2 -2
- package/src/import/types.ts +1 -1
- package/src/index.ts +58 -0
- package/src/owner.ts +156 -0
- package/src/prompt/browser.ts +48 -15
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +27 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +7 -4
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/** git's own variables (set inside hooks, say) would point it at another repository than the vault's. */
|
|
5
|
+
const gitEnv = (): Record<string, string | undefined> =>
|
|
6
|
+
Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')))
|
|
7
|
+
|
|
8
|
+
async function git(cwd: string, args: readonly string[]): Promise<string | undefined> {
|
|
9
|
+
let proc: Bun.Subprocess<'ignore', 'pipe', 'ignore'>
|
|
10
|
+
try {
|
|
11
|
+
proc = Bun.spawn(['git', ...args], { cwd, env: gitEnv(), stdin: 'ignore', stdout: 'pipe', stderr: 'ignore' })
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
|
|
14
|
+
throw error
|
|
15
|
+
}
|
|
16
|
+
const [code, output] = await Promise.all([proc.exited, new Response(proc.stdout).text()])
|
|
17
|
+
return code === 0 ? output : undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The same vault in every other worktree of the git repository `vault` is checked out in: the checkouts an unlocked
|
|
22
|
+
* session is shared between. Only worktrees the repository itself lists count, so a directory that merely copies the
|
|
23
|
+
* vault or clones the repository is never one.
|
|
24
|
+
*/
|
|
25
|
+
export async function worktreeVaults(vault: string): Promise<readonly string[]> {
|
|
26
|
+
if (!existsSync(vault)) return []
|
|
27
|
+
const own = realpathSync(vault)
|
|
28
|
+
const top = (await git(dirname(own), ['rev-parse', '--show-toplevel']))?.trim()
|
|
29
|
+
if (top === undefined || top === '') return []
|
|
30
|
+
const path = relative(realpathSync(top), own)
|
|
31
|
+
const listed = (await git(dirname(own), ['worktree', 'list', '--porcelain'])) ?? ''
|
|
32
|
+
const checkouts = listed
|
|
33
|
+
.split('\n')
|
|
34
|
+
.filter((line) => line.startsWith('worktree '))
|
|
35
|
+
.map((line) => line.slice('worktree '.length))
|
|
36
|
+
if (!checkouts.some((checkout) => existsSync(checkout) && realpathSync(checkout) === realpathSync(top))) return []
|
|
37
|
+
const common = (await git(dirname(own), ['rev-parse', '--git-common-dir']))?.trim()
|
|
38
|
+
if (common === undefined) return []
|
|
39
|
+
const repository = realpathSync(resolve(dirname(own), common))
|
|
40
|
+
const vaults: string[] = []
|
|
41
|
+
for (const checkout of checkouts) {
|
|
42
|
+
const candidate = join(checkout, path)
|
|
43
|
+
if (!existsSync(join(candidate, 'owner.json')) || realpathSync(candidate) === own) continue
|
|
44
|
+
// A copied .git can still list the original repository's worktrees. They must point back to this repository.
|
|
45
|
+
const other = (await git(checkout, ['rev-parse', '--git-common-dir']))?.trim()
|
|
46
|
+
if (other !== undefined && realpathSync(resolve(checkout, other)) === repository) {
|
|
47
|
+
vaults.push(realpathSync(candidate))
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return vaults
|
|
51
|
+
}
|
|
@@ -2,45 +2,57 @@ import { parseTtl } from '../access/scope'
|
|
|
2
2
|
import { issueSealedGrant } from '../access/sealed'
|
|
3
3
|
import { appendAudit, readAudit } from '../audit/log'
|
|
4
4
|
import { TypeVaultError } from '../core/errors'
|
|
5
|
+
import { withLock } from '../core/lock'
|
|
5
6
|
import { reach } from '../core/state'
|
|
6
7
|
import type { DaemonContext } from './agent-routes'
|
|
7
8
|
import { type Handler, json, parseBody } from './http'
|
|
8
9
|
import { AuditBody, GrantBody, RevokeBody } from './protocol'
|
|
9
10
|
|
|
10
|
-
/** `*` means the
|
|
11
|
-
export type Ceiling = { readonly name: string; readonly
|
|
11
|
+
/** `*` means the owner's own socket: no ceiling. */
|
|
12
|
+
export type Ceiling = { readonly name: string; readonly tier: string | '*' }
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
/**
|
|
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.
|
|
17
|
+
*/
|
|
18
|
+
async function currentTier(context: DaemonContext, ceiling: Ceiling): Promise<string | undefined> {
|
|
19
|
+
const { vault } = context
|
|
20
|
+
await withLock(vault.layout.lockFile, 'shared', async () => vault.refresh())
|
|
21
|
+
return vault.state.ceilings[ceiling.name] ?? (ceiling.tier === '*' ? '*' : undefined)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function checkCeiling(context: DaemonContext, ceiling: string | undefined, tiers: readonly string[]): void {
|
|
25
|
+
if (ceiling === undefined) throw new TypeVaultError('denied', "this socket's ceiling was removed")
|
|
14
26
|
const state = context.vault.state
|
|
15
|
-
for (const
|
|
16
|
-
if (state.
|
|
17
|
-
if (ceiling
|
|
18
|
-
throw new TypeVaultError('denied', `
|
|
27
|
+
for (const tier of tiers) {
|
|
28
|
+
if (state.tiers[tier] === undefined) throw new TypeVaultError('not_found', `no tier "${tier}"`)
|
|
29
|
+
if (ceiling !== '*' && !reach(state.tiers, ceiling).has(tier)) {
|
|
30
|
+
throw new TypeVaultError('denied', `tier "${tier}" is above this socket's ceiling ("${ceiling}")`)
|
|
19
31
|
}
|
|
20
32
|
}
|
|
21
33
|
}
|
|
22
34
|
|
|
23
35
|
/** Routes on an admin socket: issuing and revoking grants, bounded by that socket's ceiling. */
|
|
24
36
|
/** An uncapped socket sees every grant; a capped one only the grants it issued. */
|
|
25
|
-
const ownedBy = (ceiling: Ceiling) => (record: { readonly ceiling: string }) =>
|
|
26
|
-
|
|
37
|
+
const ownedBy = (ceiling: Ceiling, tier: string | undefined) => (record: { readonly ceiling: string }) =>
|
|
38
|
+
tier === '*' || record.ceiling === ceiling.name
|
|
27
39
|
|
|
28
40
|
export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<Record<string, Handler>> {
|
|
29
41
|
return {
|
|
30
42
|
'/v1/ping': async () => json({ ok: true }),
|
|
31
43
|
'/v1/status': async () =>
|
|
32
44
|
json({
|
|
33
|
-
ceiling: ceiling
|
|
34
|
-
|
|
45
|
+
ceiling: (await currentTier(context, ceiling)) ?? null,
|
|
46
|
+
tiers: Object.keys(context.vault.state.tiers),
|
|
35
47
|
grants: context.grants.list().length,
|
|
36
48
|
}),
|
|
37
49
|
'/v1/grant': async (request) => {
|
|
38
50
|
const body = await parseBody(request, GrantBody)
|
|
39
|
-
checkCeiling(context, ceiling, body.
|
|
51
|
+
checkCeiling(context, await currentTier(context, ceiling), body.tiers)
|
|
40
52
|
const ttlMs = parseTtl(body.ttl)
|
|
41
53
|
if (body.sealed) {
|
|
42
54
|
const token = await issueSealedGrant(context.vault, {
|
|
43
|
-
|
|
55
|
+
tiers: body.tiers,
|
|
44
56
|
only: body.only,
|
|
45
57
|
ttlMs,
|
|
46
58
|
label: body.label,
|
|
@@ -48,7 +60,7 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
48
60
|
return json({ token })
|
|
49
61
|
}
|
|
50
62
|
const { token, record } = context.grants.issue({
|
|
51
|
-
|
|
63
|
+
tiers: body.tiers,
|
|
52
64
|
only: body.only,
|
|
53
65
|
ttlMs,
|
|
54
66
|
label: body.label,
|
|
@@ -59,15 +71,15 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
59
71
|
mode: 'live',
|
|
60
72
|
grant: record.id,
|
|
61
73
|
label: record.label,
|
|
62
|
-
|
|
74
|
+
tiers: record.tiers,
|
|
63
75
|
})
|
|
64
76
|
return json({ token, id: record.id, exp: record.exp })
|
|
65
77
|
},
|
|
66
|
-
'/v1/grants': async () => json(context.grants.list().filter(ownedBy(ceiling))),
|
|
78
|
+
'/v1/grants': async () => json(context.grants.list().filter(ownedBy(ceiling, await currentTier(context, ceiling)))),
|
|
67
79
|
'/v1/revoke': async (request) => {
|
|
68
80
|
const { id, label } = await parseBody(request, RevokeBody)
|
|
69
81
|
if (id === undefined && label === undefined) throw new TypeVaultError('invalid', 'revoke needs an id or a label')
|
|
70
|
-
const owned = ownedBy(ceiling)
|
|
82
|
+
const owned = ownedBy(ceiling, await currentTier(context, ceiling))
|
|
71
83
|
const revoked = context.grants.revoke(
|
|
72
84
|
(record) => owned(record) && (record.id === id || (label !== undefined && record.label === label)),
|
|
73
85
|
)
|
|
@@ -76,16 +88,16 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
76
88
|
action: 'grant.revoke',
|
|
77
89
|
mode: 'live',
|
|
78
90
|
entries: [],
|
|
79
|
-
|
|
91
|
+
tiers: [],
|
|
80
92
|
...(label === undefined ? {} : { label }),
|
|
81
93
|
...(id === undefined ? {} : { grant: id }),
|
|
82
94
|
})
|
|
83
95
|
return json({ revoked })
|
|
84
96
|
},
|
|
85
97
|
'/v1/audit': async (request) => {
|
|
86
|
-
// The trail names entries of every
|
|
87
|
-
if (ceiling
|
|
88
|
-
throw new TypeVaultError('denied', 'the audit trail is only readable on the
|
|
98
|
+
// The trail names entries of every tier, so only the uncapped socket may read it.
|
|
99
|
+
if ((await currentTier(context, ceiling)) !== '*')
|
|
100
|
+
throw new TypeVaultError('denied', 'the audit trail is only readable on the owner socket')
|
|
89
101
|
const { label } = await parseBody(request, AuditBody)
|
|
90
102
|
return json(readAudit(context.vault.layout).filter((record) => label === undefined || record['label'] === label))
|
|
91
103
|
},
|
|
@@ -3,9 +3,9 @@ import { ScopedVault } from '../access/scoped'
|
|
|
3
3
|
import { appendAudit } from '../audit/log'
|
|
4
4
|
import { TypeVaultError } from '../core/errors'
|
|
5
5
|
import type { Vault } from '../core/vault'
|
|
6
|
-
import type
|
|
6
|
+
import { type GrantStore, type ResolvedGrant, SESSION_CEILING } from './grants'
|
|
7
7
|
import { type Handler, json, parseBody } from './http'
|
|
8
|
-
import { DeriveBody, MoveBody, NameBody, RequestBody, SetBody, ValuesBody, WaitBody } from './protocol'
|
|
8
|
+
import { AttachBody, DeriveBody, MoveBody, NameBody, RequestBody, SetBody, ValuesBody, WaitBody } from './protocol'
|
|
9
9
|
import type { PromptRequests } from './requests'
|
|
10
10
|
|
|
11
11
|
export type DaemonContext = {
|
|
@@ -14,6 +14,10 @@ export type DaemonContext = {
|
|
|
14
14
|
/** One ScopedVault per live grant, so redaction knows every value that grant has read. */
|
|
15
15
|
readonly sessions: Map<string, ScopedVault>
|
|
16
16
|
readonly requests: PromptRequests
|
|
17
|
+
/** The tiers an unlocked session's member holds directly: what `run` loads in bulk, as in direct mode. */
|
|
18
|
+
readonly sessionTiers?: readonly string[]
|
|
19
|
+
/** An unlocked session's: starts the same session in another worktree of this vault's repository, until `exp`. */
|
|
20
|
+
readonly attach?: (vault: string, exp: number) => Promise<void>
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
function bearer(request: Request): string {
|
|
@@ -27,12 +31,15 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
27
31
|
const { record } = grant
|
|
28
32
|
const existing = context.sessions.get(record.id)
|
|
29
33
|
if (existing !== undefined) return { grant, access: existing }
|
|
34
|
+
// A session reaches every tier its member does, but like direct mode it never picks a tier for `set` on its own.
|
|
35
|
+
const isSession = record.ceiling === SESSION_CEILING
|
|
30
36
|
const access = new ScopedVault(context.vault, grant.chain, {
|
|
31
37
|
mode: 'live',
|
|
32
38
|
grant: record.id,
|
|
33
39
|
label: record.label,
|
|
34
|
-
|
|
35
|
-
|
|
40
|
+
owner: isSession && record.parent === undefined && context.vault.keyring.owner !== undefined,
|
|
41
|
+
ownTiers: isSession ? (context.sessionTiers ?? []) : record.tiers,
|
|
42
|
+
...(isSession || record.tiers[0] === undefined ? {} : { defaultTier: record.tiers[0] }),
|
|
36
43
|
})
|
|
37
44
|
context.sessions.set(record.id, access)
|
|
38
45
|
return { grant, access }
|
|
@@ -41,13 +48,16 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
41
48
|
/** Routes on the agent socket. Every call needs a live grant; none can create a grant from nothing. */
|
|
42
49
|
export function agentRoutes(context: DaemonContext): Readonly<Record<string, Handler>> {
|
|
43
50
|
return {
|
|
44
|
-
|
|
51
|
+
// The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names.
|
|
52
|
+
'/v1/ping': async () => json({ ok: true, pid: process.pid }),
|
|
45
53
|
'/v1/whoami': async (request) => {
|
|
46
|
-
const { grant } = session(context, request)
|
|
54
|
+
const { grant, access } = session(context, request)
|
|
47
55
|
const { hash: _hash, ...record } = grant.record
|
|
48
|
-
|
|
56
|
+
// `tiers` is what the grant may reach; `ownTiers` is what `run` loads in bulk, narrower for a session.
|
|
57
|
+
return json({ ...record, ownTiers: await access.ownTiers() })
|
|
49
58
|
},
|
|
50
59
|
'/v1/list': async (request) => json(await session(context, request).access.list()),
|
|
60
|
+
'/v1/unreadable': async (request) => json({ count: await session(context, request).access.unreadableEntries() }),
|
|
51
61
|
'/v1/get': async (request) => {
|
|
52
62
|
const { name, reason } = await parseBody(request, NameBody)
|
|
53
63
|
return json(await session(context, request).access.get(name, reason))
|
|
@@ -58,8 +68,8 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
58
68
|
},
|
|
59
69
|
'/v1/set': async (request) => json(await session(context, request).access.set(await parseBody(request, SetBody))),
|
|
60
70
|
'/v1/remove': async (request) => {
|
|
61
|
-
const { name,
|
|
62
|
-
await session(context, request).access.remove(name,
|
|
71
|
+
const { name, tier } = await parseBody(request, NameBody)
|
|
72
|
+
await session(context, request).access.remove(name, tier)
|
|
63
73
|
return json({ ok: true })
|
|
64
74
|
},
|
|
65
75
|
'/v1/move': async (request) => {
|
|
@@ -73,7 +83,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
73
83
|
const body = await parseBody(request, DeriveBody)
|
|
74
84
|
const remaining = Date.parse(grant.record.exp) - Date.now()
|
|
75
85
|
const issued = context.grants.issue({
|
|
76
|
-
|
|
86
|
+
tiers: body.tiers ?? grant.record.tiers,
|
|
77
87
|
only: body.only,
|
|
78
88
|
ttlMs: body.ttl === undefined ? remaining : parseTtl(body.ttl),
|
|
79
89
|
// Prefixed with the parent's label so a derived grant can't pose as another session.
|
|
@@ -87,7 +97,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
87
97
|
mode: 'live',
|
|
88
98
|
grant: record.id,
|
|
89
99
|
label: record.label,
|
|
90
|
-
|
|
100
|
+
tiers: record.tiers,
|
|
91
101
|
})
|
|
92
102
|
return json({ token: issued.token, id: record.id, exp: record.exp })
|
|
93
103
|
},
|
|
@@ -101,6 +111,16 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
101
111
|
),
|
|
102
112
|
)
|
|
103
113
|
},
|
|
114
|
+
// Only the session's own grant shares it: a grant derived from it (an agent's) can't widen itself to a worktree.
|
|
115
|
+
'/v1/attach': async (request) => {
|
|
116
|
+
const { record } = session(context, request).grant
|
|
117
|
+
if (context.attach === undefined || record.ceiling !== SESSION_CEILING || record.parent !== undefined) {
|
|
118
|
+
throw new TypeVaultError('denied', 'only an unlocked session can be shared with a worktree')
|
|
119
|
+
}
|
|
120
|
+
const { vault } = await parseBody(request, AttachBody)
|
|
121
|
+
await context.attach(vault, Date.parse(record.exp))
|
|
122
|
+
return json({ ok: true })
|
|
123
|
+
},
|
|
104
124
|
'/v1/request/wait': async (request) => {
|
|
105
125
|
const { grant } = session(context, request)
|
|
106
126
|
const { id } = await parseBody(request, WaitBody)
|
package/src/daemon/client.ts
CHANGED
|
@@ -12,6 +12,9 @@ const CODES: readonly ErrorCode[] = [
|
|
|
12
12
|
'expired',
|
|
13
13
|
'locked',
|
|
14
14
|
'unavailable',
|
|
15
|
+
'in_use',
|
|
16
|
+
'no_vault',
|
|
17
|
+
'not_member',
|
|
15
18
|
]
|
|
16
19
|
const toCode = (code: string): ErrorCode => CODES.find((known) => known === code) ?? 'unavailable'
|
|
17
20
|
|
|
@@ -38,7 +41,10 @@ export async function callDaemon<T>(
|
|
|
38
41
|
signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
|
|
39
42
|
})
|
|
40
43
|
} catch (error) {
|
|
41
|
-
if (error instanceof Error
|
|
44
|
+
if (error instanceof Error) {
|
|
45
|
+
if (error.name === 'TimeoutError') {
|
|
46
|
+
throw new TypeVaultError('unavailable', 'the typevault daemon request timed out', { cause: error })
|
|
47
|
+
}
|
|
42
48
|
throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`)
|
|
43
49
|
}
|
|
44
50
|
throw error
|
|
@@ -50,7 +56,23 @@ export async function callDaemon<T>(
|
|
|
50
56
|
? new TypeVaultError(toCode(parsed.data.error.code), parsed.data.error.message)
|
|
51
57
|
: new TypeVaultError('unavailable', `daemon answered ${response.status}`)
|
|
52
58
|
}
|
|
53
|
-
|
|
59
|
+
const parsed = schema.safeParse(payload)
|
|
60
|
+
if (!parsed.success) {
|
|
61
|
+
throw new TypeVaultError('unavailable', 'the running typevault daemon does not match this CLI: restart it')
|
|
62
|
+
}
|
|
63
|
+
return parsed.data
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The PID of the daemon answering on `socket`, or undefined when none answers (or it is too old to say). */
|
|
67
|
+
export async function servingPid(socket: string): Promise<number | undefined> {
|
|
68
|
+
const Ping = z.object({ ok: z.literal(true), pid: z.number().int().positive() })
|
|
69
|
+
try {
|
|
70
|
+
return (await callDaemon(socket, '/v1/ping', {}, Ping, { timeoutMs: 1_000 })).pid
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof TypeVaultError || error instanceof z.ZodError) return undefined
|
|
73
|
+
if (error instanceof Error && error.name === 'TimeoutError') return undefined
|
|
74
|
+
throw error
|
|
75
|
+
}
|
|
54
76
|
}
|
|
55
77
|
|
|
56
78
|
export async function isDaemonAlive(socket: string): Promise<boolean> {
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -1,66 +1,178 @@
|
|
|
1
|
-
import { chmodSync, existsSync, readdirSync, rmSync } from 'node:fs'
|
|
1
|
+
import { chmodSync, existsSync, readdirSync, realpathSync, rmSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
|
|
4
|
-
import {
|
|
5
|
-
import { anchorAudit } from '../audit/log'
|
|
4
|
+
import { anchorAudit, appendAudit } from '../audit/log'
|
|
6
5
|
import { adoptCertWrites } from '../core/adopt'
|
|
6
|
+
import { randomHex, type SecretKey } from '../core/crypto'
|
|
7
7
|
import { TypeVaultError } from '../core/errors'
|
|
8
8
|
import { atomicWrite, ensureDir } from '../core/fsx'
|
|
9
|
-
import {
|
|
9
|
+
import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
|
|
10
|
+
import { type Layout, localLayout } from '../core/layout'
|
|
11
|
+
import { holdLock, isLockHeld } from '../core/lock'
|
|
12
|
+
import { loadState, readOwner } from '../core/state'
|
|
10
13
|
import { Vault } from '../core/vault'
|
|
14
|
+
import { worktreeVaults } from '../core/worktrees'
|
|
11
15
|
import { adminRoutes, type Ceiling } from './admin-routes'
|
|
12
16
|
import { agentRoutes, type DaemonContext } from './agent-routes'
|
|
13
17
|
import { isDaemonAlive } from './client'
|
|
14
|
-
import { GrantStore } from './grants'
|
|
15
|
-
import { router } from './http'
|
|
18
|
+
import { GrantStore, SESSION_CEILING } from './grants'
|
|
19
|
+
import { errorResponse, json, router } from './http'
|
|
16
20
|
import { type PromptOptions, PromptRequests } from './requests'
|
|
21
|
+
import { LOCKED_MESSAGE, startSession, stopDaemon } from './spawn'
|
|
17
22
|
|
|
18
23
|
const ADOPT_EVERY_MS = 60_000
|
|
24
|
+
const SOURCE_CHECK_MS = 1_000
|
|
25
|
+
const SESSION_LOCK = /^session-[0-9a-f]+\.lock$/
|
|
19
26
|
|
|
20
27
|
export type DaemonOptions = {
|
|
21
|
-
readonly
|
|
28
|
+
readonly layout: Layout
|
|
22
29
|
readonly env: Readonly<Record<string, string | undefined>>
|
|
30
|
+
/** Member keys (or, in tests, the owner key). The daemon is the only process that holds them unlocked. */
|
|
31
|
+
readonly keys: readonly SecretKey[]
|
|
23
32
|
readonly prompt?: PromptOptions
|
|
33
|
+
/**
|
|
34
|
+
* An unlocked human session: a grant over everything the keys reach is written to `run/session.token` for
|
|
35
|
+
* this user's CLI, and both end with the daemon. `sourceLock` makes it a session shared from another worktree's:
|
|
36
|
+
* it serves only while that session's daemon holds this lock, which the OS drops however that daemon ends.
|
|
37
|
+
*/
|
|
38
|
+
readonly session?: { readonly ttlMs: number; readonly sourceLock?: string }
|
|
39
|
+
}
|
|
40
|
+
export type RunningDaemon = {
|
|
41
|
+
readonly stop: () => Promise<void>
|
|
42
|
+
readonly ceilings: readonly Ceiling[]
|
|
43
|
+
/** Settles when the host asks this daemon to stop over its control socket (how `stopDaemon` does it on Windows). */
|
|
44
|
+
readonly stopRequested: Promise<void>
|
|
24
45
|
}
|
|
25
|
-
export type RunningDaemon = { readonly stop: () => Promise<void>; readonly ceilings: readonly Ceiling[] }
|
|
26
46
|
|
|
27
|
-
/** One admin socket per
|
|
47
|
+
/** One admin socket per owner-signed ceiling, plus an uncapped `default` socket when this daemon holds the owner key. */
|
|
28
48
|
function ceilingsOf(vault: Vault): readonly Ceiling[] {
|
|
29
|
-
const signed = Object.entries(vault.state.ceilings).map(([name,
|
|
30
|
-
const
|
|
31
|
-
return
|
|
49
|
+
const signed = Object.entries(vault.state.ceilings).map(([name, tier]) => ({ name, tier }))
|
|
50
|
+
const owner = vault.keyring.owner !== undefined && vault.state.ceilings['default'] === undefined
|
|
51
|
+
return owner ? [...signed, { name: 'default', tier: '*' }] : signed
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function openSession(context: DaemonContext, ttlMs: number): Promise<string> {
|
|
55
|
+
const { vault, grants } = context
|
|
56
|
+
const tiers = [...(await vault.keyring.reachableTiers())].sort()
|
|
57
|
+
const { token, record } = grants.issue({ tiers, only: [], ttlMs, label: 'session', ceiling: SESSION_CEILING })
|
|
58
|
+
atomicWrite(vault.layout.sessionFile, token, 0o600)
|
|
59
|
+
await appendAudit(vault.layout, { action: 'grant.issue', mode: 'live', grant: record.id, label: 'session', tiers })
|
|
60
|
+
return record.id
|
|
32
61
|
}
|
|
33
62
|
|
|
34
63
|
export async function startDaemon(options: DaemonOptions): Promise<RunningDaemon> {
|
|
35
|
-
const layout =
|
|
64
|
+
const { layout } = options
|
|
36
65
|
ensureDir(layout.run, 0o700)
|
|
66
|
+
ensureDir(layout.sockets, 0o700)
|
|
67
|
+
refuseForeignDaemon(layout, options.env)
|
|
37
68
|
if (await isDaemonAlive(layout.agentSocket))
|
|
38
69
|
throw new TypeVaultError('conflict', 'a typevault daemon is already running')
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
70
|
+
// Held until this daemon's cleanup is done: one still shutting down here keeps a replacement from starting, and
|
|
71
|
+
// `stopDaemon` knows the old one is gone when the lock frees up, with no PID to trust.
|
|
72
|
+
const release = holdLock(layout.daemonLock)
|
|
73
|
+
if (release === undefined) throw new TypeVaultError('conflict', 'a typevault daemon is still shutting down here')
|
|
74
|
+
let claim: DaemonClaim | undefined
|
|
75
|
+
try {
|
|
76
|
+
claim = claimDaemon(layout, options.env)
|
|
77
|
+
return await serve(options, claim, release)
|
|
78
|
+
} catch (error) {
|
|
79
|
+
claim?.release()
|
|
80
|
+
release()
|
|
81
|
+
throw error
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: () => void): Promise<RunningDaemon> {
|
|
86
|
+
const { layout } = options
|
|
87
|
+
for (const file of readdirSync(layout.sockets).filter((name) => name.endsWith('.sock'))) {
|
|
88
|
+
rmSync(join(layout.sockets, file))
|
|
89
|
+
}
|
|
90
|
+
// Left by a session that ended without cleanup: removing them stops any worktree session still bound to one.
|
|
91
|
+
for (const file of readdirSync(layout.run).filter((name) => SESSION_LOCK.test(name))) {
|
|
92
|
+
rmSync(join(layout.run, file), { force: true })
|
|
93
|
+
}
|
|
94
|
+
if (options.keys.length === 0) throw new TypeVaultError('locked', 'the vault is locked (run `typevault unlock`)')
|
|
95
|
+
const vault = await Vault.open(layout, options.keys, options.env)
|
|
96
|
+
if (vault.keyring.owner === undefined && vault.member === undefined) {
|
|
97
|
+
throw new TypeVaultError('denied', 'this key is not a member of the vault')
|
|
98
|
+
}
|
|
44
99
|
const ceilings = ceilingsOf(vault)
|
|
45
|
-
if (ceilings.length === 0)
|
|
46
|
-
throw new TypeVaultError('invalid', 'no ceilings configured (typevault ceiling set <name> <
|
|
100
|
+
if (ceilings.length === 0 && options.session === undefined)
|
|
101
|
+
throw new TypeVaultError('invalid', 'no ceilings configured (typevault ceiling set <name> <tier>)')
|
|
47
102
|
|
|
103
|
+
const { promise: stopRequested, resolve: requestStop } = Promise.withResolvers<void>()
|
|
104
|
+
const member = vault.member === undefined ? undefined : vault.state.members[vault.member]
|
|
105
|
+
const sourceLock = options.session?.sourceLock
|
|
106
|
+
const sourceAlive = (): boolean => sourceLock === undefined || isLockHeld(sourceLock)
|
|
107
|
+
// Held while this session runs, under a name no later session reuses: what worktree sessions shared from it check.
|
|
108
|
+
const sessionLock = options.session === undefined ? undefined : join(layout.run, `session-${randomHex(8)}.lock`)
|
|
109
|
+
const releaseSessionLock = sessionLock === undefined ? undefined : holdLock(sessionLock)
|
|
110
|
+
const worktrees = new Map<string, Layout>()
|
|
111
|
+
const attaching = new Set<Promise<void>>()
|
|
112
|
+
let stopping = false
|
|
113
|
+
const [key] = options.keys
|
|
114
|
+
const attach =
|
|
115
|
+
key === undefined || sessionLock === undefined
|
|
116
|
+
? undefined
|
|
117
|
+
: async (target: string, exp: number): Promise<void> => {
|
|
118
|
+
if (stopping) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
119
|
+
const started = (async () => {
|
|
120
|
+
const worktree = await worktreeLayout(vault, options.env, target)
|
|
121
|
+
// Recorded before it starts, so a stop that comes in meanwhile still stops it.
|
|
122
|
+
worktrees.set(target, worktree)
|
|
123
|
+
await startWorktreeSession(worktree, options.env, key, exp, sessionLock)
|
|
124
|
+
})()
|
|
125
|
+
attaching.add(started)
|
|
126
|
+
try {
|
|
127
|
+
await started
|
|
128
|
+
} finally {
|
|
129
|
+
attaching.delete(started)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const grants = new GrantStore(layout.grantsFile)
|
|
133
|
+
// A session ends with its daemon, however that daemon ended: one killed before its cleanup left both of these.
|
|
134
|
+
grants.revoke((record) => record.ceiling === SESSION_CEILING)
|
|
135
|
+
rmSync(layout.sessionFile, { force: true })
|
|
48
136
|
const context: DaemonContext = {
|
|
49
137
|
vault,
|
|
50
|
-
grants
|
|
138
|
+
grants,
|
|
51
139
|
sessions: new Map(),
|
|
52
140
|
requests: new PromptRequests(vault, options.prompt ?? {}),
|
|
141
|
+
...(options.session === undefined
|
|
142
|
+
? {}
|
|
143
|
+
: { sessionTiers: member?.tiers ?? [], ...(attach === undefined ? {} : { attach }) }),
|
|
53
144
|
}
|
|
145
|
+
// A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
|
|
146
|
+
const bound =
|
|
147
|
+
(fetch: (request: Request) => Promise<Response>) =>
|
|
148
|
+
async (request: Request): Promise<Response> =>
|
|
149
|
+
sourceAlive() || new URL(request.url).pathname === '/v1/ping'
|
|
150
|
+
? fetch(request)
|
|
151
|
+
: errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
|
|
54
152
|
const listen = (path: string, fetch: (request: Request) => Promise<Response>) => {
|
|
55
153
|
const server = Bun.serve({ unix: path, fetch, maxRequestBodySize: 1 << 20 })
|
|
56
|
-
|
|
154
|
+
// Windows sockets take the run directory's ACL; chmod there only toggles read-only.
|
|
155
|
+
if (process.platform !== 'win32') chmodSync(path, 0o600)
|
|
57
156
|
return server
|
|
58
157
|
}
|
|
59
158
|
const servers = [
|
|
60
|
-
listen(layout.agentSocket, router(agentRoutes(context))),
|
|
61
|
-
...ceilings.map((ceiling) =>
|
|
159
|
+
listen(layout.agentSocket, bound(router(agentRoutes(context)))),
|
|
160
|
+
...ceilings.map((ceiling) =>
|
|
161
|
+
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling)))),
|
|
162
|
+
),
|
|
163
|
+
listen(
|
|
164
|
+
layout.controlSocket,
|
|
165
|
+
router({
|
|
166
|
+
'/v1/shutdown': async () => {
|
|
167
|
+
// Stopped once this response is out: stopping the server while its own request is in flight never settles.
|
|
168
|
+
setTimeout(requestStop, 0)
|
|
169
|
+
return json({ ok: true })
|
|
170
|
+
},
|
|
171
|
+
}),
|
|
172
|
+
),
|
|
62
173
|
]
|
|
63
174
|
atomicWrite(join(layout.run, 'daemon.pid'), String(process.pid), 0o600)
|
|
175
|
+
const session = options.session === undefined ? undefined : await openSession(context, options.session.ttlMs)
|
|
64
176
|
const adopt = (): void => {
|
|
65
177
|
adoptCertWrites(vault).then(undefined, (error: unknown) =>
|
|
66
178
|
console.error('typevault daemon: adopting sealed writes failed', error),
|
|
@@ -68,21 +180,94 @@ export async function startDaemon(options: DaemonOptions): Promise<RunningDaemon
|
|
|
68
180
|
}
|
|
69
181
|
adopt()
|
|
70
182
|
const adoption = setInterval(adopt, ADOPT_EVERY_MS)
|
|
183
|
+
const watch = setInterval(() => {
|
|
184
|
+
if (!sourceAlive()) requestStop()
|
|
185
|
+
}, SOURCE_CHECK_MS)
|
|
71
186
|
|
|
72
187
|
return {
|
|
73
188
|
ceilings,
|
|
189
|
+
stopRequested,
|
|
74
190
|
stop: async () => {
|
|
75
191
|
clearInterval(adoption)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
192
|
+
clearInterval(watch)
|
|
193
|
+
stopping = true
|
|
194
|
+
try {
|
|
195
|
+
// An attachment still starting would otherwise leave its worktree unlocked after this stop.
|
|
196
|
+
await Promise.allSettled(attaching)
|
|
197
|
+
// The claim was cleared and someone else's daemon now owns the grants, session and run files. Saving this
|
|
198
|
+
// daemon's stale grant store or removing those files would undo its successor's, so only local resources go.
|
|
199
|
+
if (!claim.owns()) {
|
|
200
|
+
await Promise.all(servers.map((server) => server.stop(true)))
|
|
201
|
+
await context.requests.stop()
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
// Worktrees share this session, so they lock with it.
|
|
205
|
+
for (const worktree of worktrees.values()) await stopWorktree(worktree)
|
|
206
|
+
if (session !== undefined) {
|
|
207
|
+
context.grants.revoke((record) => record.id === session)
|
|
208
|
+
if (existsSync(layout.sessionFile)) rmSync(layout.sessionFile)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
await Promise.all(servers.map((server) => server.stop(true)))
|
|
212
|
+
await context.requests.stop()
|
|
213
|
+
// A vault deleted under its daemon has nowhere left to anchor (and writing there would half re-create it).
|
|
214
|
+
if (existsSync(layout.ownerFile)) await anchorAudit(layout)
|
|
215
|
+
for (const file of [
|
|
216
|
+
layout.agentSocket,
|
|
217
|
+
...ceilings.map((c) => layout.adminSocket(c.name)),
|
|
218
|
+
layout.controlSocket,
|
|
219
|
+
join(layout.run, 'daemon.pid'),
|
|
220
|
+
]) {
|
|
221
|
+
if (existsSync(file)) rmSync(file)
|
|
222
|
+
}
|
|
223
|
+
} finally {
|
|
224
|
+
releaseSessionLock?.()
|
|
225
|
+
if (sessionLock !== undefined) rmSync(sessionLock, { force: true })
|
|
226
|
+
claim.release()
|
|
227
|
+
releaseLock()
|
|
85
228
|
}
|
|
86
229
|
},
|
|
87
230
|
}
|
|
88
231
|
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* `target`, if it is the same vault in another worktree of this one's repository: where this session may start, so
|
|
235
|
+
* agents working there aren't locked out. Anything else (a copy of the vault, a clone of the repository) gets no key:
|
|
236
|
+
* only worktrees the repository lists count. The worktree keeps its own state and files, and trusts the owner this
|
|
237
|
+
* session does, never one its own owner.json names on first use.
|
|
238
|
+
*/
|
|
239
|
+
async function worktreeLayout(vault: Vault, env: DaemonOptions['env'], target: string): Promise<Layout> {
|
|
240
|
+
const listed = await worktreeVaults(vault.layout.vault)
|
|
241
|
+
if (!existsSync(target) || !listed.includes(realpathSync(target))) {
|
|
242
|
+
throw new TypeVaultError('denied', `${target} is not this vault in a worktree of its repository`)
|
|
243
|
+
}
|
|
244
|
+
const layout = localLayout(target, env)
|
|
245
|
+
if (readOwner(layout).signPublic !== vault.state.owner.signPublic) {
|
|
246
|
+
throw new TypeVaultError('tampered', "this worktree's vault has a different owner")
|
|
247
|
+
}
|
|
248
|
+
loadState(layout, { ...env, TYPEVAULT_OWNER: vault.state.owner.signPublic })
|
|
249
|
+
return layout
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function startWorktreeSession(
|
|
253
|
+
layout: Layout,
|
|
254
|
+
env: DaemonOptions['env'],
|
|
255
|
+
key: SecretKey,
|
|
256
|
+
exp: number,
|
|
257
|
+
sessionLock: string,
|
|
258
|
+
): Promise<void> {
|
|
259
|
+
if (await isDaemonAlive(layout.agentSocket)) {
|
|
260
|
+
if (existsSync(layout.sessionFile)) return
|
|
261
|
+
await stopDaemon(layout)
|
|
262
|
+
}
|
|
263
|
+
await startSession(layout, env, key, exp - Date.now(), sessionLock)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function stopWorktree(layout: Layout): Promise<void> {
|
|
267
|
+
try {
|
|
268
|
+
await stopDaemon(layout)
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error instanceof TypeVaultError && error.code === 'not_found') return
|
|
271
|
+
console.error(`typevault daemon: locking the worktree at ${layout.vault} failed`, error)
|
|
272
|
+
}
|
|
273
|
+
}
|