typevault 0.1.0 → 0.2.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 +7 -7
- package/src/access/scoped.ts +100 -44
- package/src/access/sealed-access.ts +45 -23
- package/src/access/sealed.ts +33 -21
- package/src/access/types.ts +25 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +14 -9
- package/src/cli/commands/admin.ts +87 -47
- package/src/cli/commands/daemon.ts +33 -15
- package/src/cli/commands/entries.ts +166 -55
- package/src/cli/commands/grant.ts +12 -20
- package/src/cli/commands/members.ts +281 -0
- package/src/cli/commands/run.ts +61 -24
- package/src/cli/context.ts +155 -15
- package/src/cli/index.ts +27 -4
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +65 -0
- package/src/core/admin.ts +125 -74
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +9 -9
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +6 -0
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +84 -0
- package/src/core/identity.ts +130 -0
- package/src/core/init.ts +73 -23
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +145 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +146 -49
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +8 -4
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +88 -48
- package/src/core/txn.ts +5 -4
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +39 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +29 -11
- package/src/daemon/client.ts +15 -0
- package/src/daemon/daemon.ts +210 -32
- package/src/daemon/grants.ts +21 -4
- package/src/daemon/http.ts +3 -0
- package/src/daemon/live-access.ts +4 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +17 -22
- package/src/daemon/spawn.ts +188 -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 +2 -2
- 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/page.ts +19 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +3 -3
|
@@ -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,14 @@ 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
|
-
...(record.
|
|
40
|
+
ownTiers: isSession ? (context.sessionTiers ?? []) : record.tiers,
|
|
41
|
+
...(isSession || record.tiers[0] === undefined ? {} : { defaultTier: record.tiers[0] }),
|
|
36
42
|
})
|
|
37
43
|
context.sessions.set(record.id, access)
|
|
38
44
|
return { grant, access }
|
|
@@ -41,11 +47,13 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
41
47
|
/** Routes on the agent socket. Every call needs a live grant; none can create a grant from nothing. */
|
|
42
48
|
export function agentRoutes(context: DaemonContext): Readonly<Record<string, Handler>> {
|
|
43
49
|
return {
|
|
44
|
-
|
|
50
|
+
// The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names.
|
|
51
|
+
'/v1/ping': async () => json({ ok: true, pid: process.pid }),
|
|
45
52
|
'/v1/whoami': async (request) => {
|
|
46
|
-
const { grant } = session(context, request)
|
|
53
|
+
const { grant, access } = session(context, request)
|
|
47
54
|
const { hash: _hash, ...record } = grant.record
|
|
48
|
-
|
|
55
|
+
// `tiers` is what the grant may reach; `ownTiers` is what `run` loads in bulk, narrower for a session.
|
|
56
|
+
return json({ ...record, ownTiers: await access.ownTiers() })
|
|
49
57
|
},
|
|
50
58
|
'/v1/list': async (request) => json(await session(context, request).access.list()),
|
|
51
59
|
'/v1/get': async (request) => {
|
|
@@ -58,8 +66,8 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
58
66
|
},
|
|
59
67
|
'/v1/set': async (request) => json(await session(context, request).access.set(await parseBody(request, SetBody))),
|
|
60
68
|
'/v1/remove': async (request) => {
|
|
61
|
-
const { name,
|
|
62
|
-
await session(context, request).access.remove(name,
|
|
69
|
+
const { name, tier } = await parseBody(request, NameBody)
|
|
70
|
+
await session(context, request).access.remove(name, tier)
|
|
63
71
|
return json({ ok: true })
|
|
64
72
|
},
|
|
65
73
|
'/v1/move': async (request) => {
|
|
@@ -73,7 +81,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
73
81
|
const body = await parseBody(request, DeriveBody)
|
|
74
82
|
const remaining = Date.parse(grant.record.exp) - Date.now()
|
|
75
83
|
const issued = context.grants.issue({
|
|
76
|
-
|
|
84
|
+
tiers: body.tiers ?? grant.record.tiers,
|
|
77
85
|
only: body.only,
|
|
78
86
|
ttlMs: body.ttl === undefined ? remaining : parseTtl(body.ttl),
|
|
79
87
|
// Prefixed with the parent's label so a derived grant can't pose as another session.
|
|
@@ -87,7 +95,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
87
95
|
mode: 'live',
|
|
88
96
|
grant: record.id,
|
|
89
97
|
label: record.label,
|
|
90
|
-
|
|
98
|
+
tiers: record.tiers,
|
|
91
99
|
})
|
|
92
100
|
return json({ token: issued.token, id: record.id, exp: record.exp })
|
|
93
101
|
},
|
|
@@ -101,6 +109,16 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
101
109
|
),
|
|
102
110
|
)
|
|
103
111
|
},
|
|
112
|
+
// Only the session's own grant shares it: a grant derived from it (an agent's) can't widen itself to a worktree.
|
|
113
|
+
'/v1/attach': async (request) => {
|
|
114
|
+
const { record } = session(context, request).grant
|
|
115
|
+
if (context.attach === undefined || record.ceiling !== SESSION_CEILING || record.parent !== undefined) {
|
|
116
|
+
throw new TypeVaultError('denied', 'only an unlocked session can be shared with a worktree')
|
|
117
|
+
}
|
|
118
|
+
const { vault } = await parseBody(request, AttachBody)
|
|
119
|
+
await context.attach(vault, Date.parse(record.exp))
|
|
120
|
+
return json({ ok: true })
|
|
121
|
+
},
|
|
104
122
|
'/v1/request/wait': async (request) => {
|
|
105
123
|
const { grant } = session(context, request)
|
|
106
124
|
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
|
|
|
@@ -53,6 +56,18 @@ export async function callDaemon<T>(
|
|
|
53
56
|
return schema.parse(payload)
|
|
54
57
|
}
|
|
55
58
|
|
|
59
|
+
/** The PID of the daemon answering on `socket`, or undefined when none answers (or it is too old to say). */
|
|
60
|
+
export async function servingPid(socket: string): Promise<number | undefined> {
|
|
61
|
+
const Ping = z.object({ ok: z.literal(true), pid: z.number().int().positive() })
|
|
62
|
+
try {
|
|
63
|
+
return (await callDaemon(socket, '/v1/ping', {}, Ping, { timeoutMs: 1_000 })).pid
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error instanceof TypeVaultError || error instanceof z.ZodError) return undefined
|
|
66
|
+
if (error instanceof Error && error.name === 'TimeoutError') return undefined
|
|
67
|
+
throw error
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
56
71
|
export async function isDaemonAlive(socket: string): Promise<boolean> {
|
|
57
72
|
try {
|
|
58
73
|
await callDaemon(socket, '/v1/ping', {}, z.object({ ok: z.literal(true) }), { timeoutMs: 1_000 })
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -1,66 +1,174 @@
|
|
|
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 } 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
|
+
}
|
|
48
132
|
const context: DaemonContext = {
|
|
49
133
|
vault,
|
|
50
134
|
grants: new GrantStore(layout.grantsFile),
|
|
51
135
|
sessions: new Map(),
|
|
52
136
|
requests: new PromptRequests(vault, options.prompt ?? {}),
|
|
137
|
+
...(options.session === undefined
|
|
138
|
+
? {}
|
|
139
|
+
: { sessionTiers: member?.tiers ?? [], ...(attach === undefined ? {} : { attach }) }),
|
|
53
140
|
}
|
|
141
|
+
// A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
|
|
142
|
+
const bound =
|
|
143
|
+
(fetch: (request: Request) => Promise<Response>) =>
|
|
144
|
+
async (request: Request): Promise<Response> =>
|
|
145
|
+
sourceAlive() || new URL(request.url).pathname === '/v1/ping'
|
|
146
|
+
? fetch(request)
|
|
147
|
+
: errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
|
|
54
148
|
const listen = (path: string, fetch: (request: Request) => Promise<Response>) => {
|
|
55
149
|
const server = Bun.serve({ unix: path, fetch, maxRequestBodySize: 1 << 20 })
|
|
56
|
-
|
|
150
|
+
// Windows sockets take the run directory's ACL; chmod there only toggles read-only.
|
|
151
|
+
if (process.platform !== 'win32') chmodSync(path, 0o600)
|
|
57
152
|
return server
|
|
58
153
|
}
|
|
59
154
|
const servers = [
|
|
60
|
-
listen(layout.agentSocket, router(agentRoutes(context))),
|
|
61
|
-
...ceilings.map((ceiling) =>
|
|
155
|
+
listen(layout.agentSocket, bound(router(agentRoutes(context)))),
|
|
156
|
+
...ceilings.map((ceiling) =>
|
|
157
|
+
listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling)))),
|
|
158
|
+
),
|
|
159
|
+
listen(
|
|
160
|
+
layout.controlSocket,
|
|
161
|
+
router({
|
|
162
|
+
'/v1/shutdown': async () => {
|
|
163
|
+
// Stopped once this response is out: stopping the server while its own request is in flight never settles.
|
|
164
|
+
setTimeout(requestStop, 0)
|
|
165
|
+
return json({ ok: true })
|
|
166
|
+
},
|
|
167
|
+
}),
|
|
168
|
+
),
|
|
62
169
|
]
|
|
63
170
|
atomicWrite(join(layout.run, 'daemon.pid'), String(process.pid), 0o600)
|
|
171
|
+
const session = options.session === undefined ? undefined : await openSession(context, options.session.ttlMs)
|
|
64
172
|
const adopt = (): void => {
|
|
65
173
|
adoptCertWrites(vault).then(undefined, (error: unknown) =>
|
|
66
174
|
console.error('typevault daemon: adopting sealed writes failed', error),
|
|
@@ -68,21 +176,91 @@ export async function startDaemon(options: DaemonOptions): Promise<RunningDaemon
|
|
|
68
176
|
}
|
|
69
177
|
adopt()
|
|
70
178
|
const adoption = setInterval(adopt, ADOPT_EVERY_MS)
|
|
179
|
+
const watch = setInterval(() => {
|
|
180
|
+
if (!sourceAlive()) requestStop()
|
|
181
|
+
}, SOURCE_CHECK_MS)
|
|
71
182
|
|
|
72
183
|
return {
|
|
73
184
|
ceilings,
|
|
185
|
+
stopRequested,
|
|
74
186
|
stop: async () => {
|
|
75
187
|
clearInterval(adoption)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
188
|
+
clearInterval(watch)
|
|
189
|
+
stopping = true
|
|
190
|
+
try {
|
|
191
|
+
// An attachment still starting would otherwise leave its worktree unlocked after this stop.
|
|
192
|
+
await Promise.allSettled(attaching)
|
|
193
|
+
// The claim was cleared and someone else's daemon now owns the grants, session and run files. Saving this
|
|
194
|
+
// daemon's stale grant store or removing those files would undo its successor's, so only local resources go.
|
|
195
|
+
if (!claim.owns()) {
|
|
196
|
+
await Promise.all(servers.map((server) => server.stop(true)))
|
|
197
|
+
await context.requests.stop()
|
|
198
|
+
return
|
|
199
|
+
}
|
|
200
|
+
// Worktrees share this session, so they lock with it.
|
|
201
|
+
for (const worktree of worktrees.values()) await stopWorktree(worktree)
|
|
202
|
+
if (session !== undefined) {
|
|
203
|
+
context.grants.revoke((record) => record.id === session)
|
|
204
|
+
if (existsSync(layout.sessionFile)) rmSync(layout.sessionFile)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
await Promise.all(servers.map((server) => server.stop(true)))
|
|
208
|
+
await context.requests.stop()
|
|
209
|
+
// A vault deleted under its daemon has nowhere left to anchor (and writing there would half re-create it).
|
|
210
|
+
if (existsSync(layout.ownerFile)) await anchorAudit(layout)
|
|
211
|
+
for (const file of [
|
|
212
|
+
layout.agentSocket,
|
|
213
|
+
...ceilings.map((c) => layout.adminSocket(c.name)),
|
|
214
|
+
layout.controlSocket,
|
|
215
|
+
join(layout.run, 'daemon.pid'),
|
|
216
|
+
]) {
|
|
217
|
+
if (existsSync(file)) rmSync(file)
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
releaseSessionLock?.()
|
|
221
|
+
if (sessionLock !== undefined) rmSync(sessionLock, { force: true })
|
|
222
|
+
claim.release()
|
|
223
|
+
releaseLock()
|
|
85
224
|
}
|
|
86
225
|
},
|
|
87
226
|
}
|
|
88
227
|
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* `target`, if it is the same vault in another worktree of this one's repository: where this session may start, so
|
|
231
|
+
* agents working there aren't locked out. Anything else (a copy of the vault, a clone of the repository) gets no key:
|
|
232
|
+
* only worktrees the repository lists count. The worktree keeps its own state and files, and trusts the owner this
|
|
233
|
+
* session does, never one its own owner.json names on first use.
|
|
234
|
+
*/
|
|
235
|
+
async function worktreeLayout(vault: Vault, env: DaemonOptions['env'], target: string): Promise<Layout> {
|
|
236
|
+
const listed = await worktreeVaults(vault.layout.vault)
|
|
237
|
+
if (!existsSync(target) || !listed.includes(realpathSync(target))) {
|
|
238
|
+
throw new TypeVaultError('denied', `${target} is not this vault in a worktree of its repository`)
|
|
239
|
+
}
|
|
240
|
+
const layout = localLayout(target, env)
|
|
241
|
+
loadState(layout, { ...env, TYPEVAULT_OWNER: vault.state.owner.signPublic })
|
|
242
|
+
return layout
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function startWorktreeSession(
|
|
246
|
+
layout: Layout,
|
|
247
|
+
env: DaemonOptions['env'],
|
|
248
|
+
key: SecretKey,
|
|
249
|
+
exp: number,
|
|
250
|
+
sessionLock: string,
|
|
251
|
+
): Promise<void> {
|
|
252
|
+
if (await isDaemonAlive(layout.agentSocket)) {
|
|
253
|
+
if (existsSync(layout.sessionFile)) return
|
|
254
|
+
await stopDaemon(layout)
|
|
255
|
+
}
|
|
256
|
+
await startSession(layout, env, key, exp - Date.now(), sessionLock)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function stopWorktree(layout: Layout): Promise<void> {
|
|
260
|
+
try {
|
|
261
|
+
await stopDaemon(layout)
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (error instanceof TypeVaultError && error.code === 'not_found') return
|
|
264
|
+
console.error(`typevault daemon: locking the worktree at ${layout.vault} failed`, error)
|
|
265
|
+
}
|
|
266
|
+
}
|
package/src/daemon/grants.ts
CHANGED
|
@@ -13,7 +13,7 @@ const RecordSchema = z.object({
|
|
|
13
13
|
id: z.string(),
|
|
14
14
|
hash: z.string(),
|
|
15
15
|
label: z.string(),
|
|
16
|
-
|
|
16
|
+
tiers: z.array(z.string()),
|
|
17
17
|
only: z.array(z.string()),
|
|
18
18
|
exp: z.iso.datetime(),
|
|
19
19
|
created: z.iso.datetime(),
|
|
@@ -24,7 +24,7 @@ const RecordSchema = z.object({
|
|
|
24
24
|
})
|
|
25
25
|
export type GrantRecord = z.infer<typeof RecordSchema>
|
|
26
26
|
export type GrantRequest = {
|
|
27
|
-
readonly
|
|
27
|
+
readonly tiers: readonly string[]
|
|
28
28
|
readonly only: readonly string[]
|
|
29
29
|
readonly ttlMs: number
|
|
30
30
|
readonly label: string
|
|
@@ -35,6 +35,15 @@ export type ResolvedGrant = { readonly record: GrantRecord; readonly chain: Scop
|
|
|
35
35
|
|
|
36
36
|
const PREFIX = 'tvl1'
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* The ceiling name marking an unlocked session's grant (and grants derived from it). It is no valid ceiling name,
|
|
40
|
+
* so no admin socket owns the session: a ceiling named `session` can neither list nor revoke it.
|
|
41
|
+
*/
|
|
42
|
+
export const SESSION_CEILING = ':session'
|
|
43
|
+
|
|
44
|
+
/** Every request under a grant checks each link of its chain, so derivation may not nest without bound. */
|
|
45
|
+
export const MAX_CHAIN = 8
|
|
46
|
+
|
|
38
47
|
/**
|
|
39
48
|
* Live grants, persisted (hashed) so a daemon restart doesn't cut sessions off.
|
|
40
49
|
* A token is `tvl1.<id>.<secret>`; only sha256(secret) is stored.
|
|
@@ -56,6 +65,14 @@ export class GrantStore {
|
|
|
56
65
|
|
|
57
66
|
issue(request: GrantRequest): { readonly token: string; readonly record: GrantRecord } {
|
|
58
67
|
const parent = request.parent === undefined ? undefined : this.#records.find((r) => r.id === request.parent)
|
|
68
|
+
let links = 1
|
|
69
|
+
for (let link = parent; link !== undefined; links++) {
|
|
70
|
+
const parentId = link.parent
|
|
71
|
+
link = parentId === undefined ? undefined : this.#records.find((r) => r.id === parentId)
|
|
72
|
+
}
|
|
73
|
+
if (links > MAX_CHAIN) {
|
|
74
|
+
throw new TypeVaultError('invalid', `a grant can be derived at most ${MAX_CHAIN - 1} levels deep`)
|
|
75
|
+
}
|
|
59
76
|
const requestedExp = Date.now() + request.ttlMs
|
|
60
77
|
const exp = parent === undefined ? requestedExp : Math.min(requestedExp, Date.parse(parent.exp))
|
|
61
78
|
const secret = randomToken(32)
|
|
@@ -63,7 +80,7 @@ export class GrantStore {
|
|
|
63
80
|
id: randomHex(8),
|
|
64
81
|
hash: sha256Hex(utf8(secret)),
|
|
65
82
|
label: request.label,
|
|
66
|
-
|
|
83
|
+
tiers: [...request.tiers],
|
|
67
84
|
only: [...request.only],
|
|
68
85
|
exp: new Date(exp).toISOString(),
|
|
69
86
|
created: new Date().toISOString(),
|
|
@@ -96,7 +113,7 @@ export class GrantStore {
|
|
|
96
113
|
link = parentId === undefined ? undefined : this.#records.find((r) => r.id === parentId)
|
|
97
114
|
if (parentId !== undefined && link === undefined) throw new TypeVaultError('denied', 'parent grant is gone')
|
|
98
115
|
}
|
|
99
|
-
return { record, chain: chain.map(({
|
|
116
|
+
return { record, chain: chain.map(({ tiers, only }) => ({ tiers, only })) }
|
|
100
117
|
}
|
|
101
118
|
|
|
102
119
|
/** Whether grant `id` and all its ancestors are still unrevoked and unexpired. */
|
package/src/daemon/http.ts
CHANGED
|
@@ -40,16 +40,16 @@ export class LiveAccess implements Access {
|
|
|
40
40
|
return toSummaryValue(await this.call('/v1/set', input, EntrySummarySchema))
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
async remove(name: EntryName,
|
|
44
|
-
await this.call('/v1/remove', { name, ...(
|
|
43
|
+
async remove(name: EntryName, tier?: string): Promise<void> {
|
|
44
|
+
await this.call('/v1/remove', { name, ...(tier === undefined ? {} : { tier }) }, Ok)
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
async move(from: EntryName, to: EntryName): Promise<void> {
|
|
48
48
|
await this.call('/v1/move', { from, to }, Ok)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
async
|
|
52
|
-
return (await this.call('/v1/whoami', {}, z.object({
|
|
51
|
+
async ownTiers(): Promise<readonly string[]> {
|
|
52
|
+
return (await this.call('/v1/whoami', {}, z.object({ ownTiers: z.array(z.string()) }))).ownTiers
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
async readValues(): Promise<readonly string[]> {
|