typevault 0.2.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 +10 -10
- package/package.json +1 -1
- package/src/access/env.ts +3 -3
- package/src/access/scope.ts +7 -2
- package/src/access/scoped.ts +22 -4
- package/src/access/sealed-access.ts +5 -0
- package/src/access/sealed.ts +25 -12
- package/src/access/types.ts +2 -0
- package/src/audit/log.ts +15 -4
- package/src/cli/commands/admin.ts +7 -2
- package/src/cli/commands/daemon.ts +10 -3
- package/src/cli/commands/entries.ts +31 -7
- package/src/cli/commands/grant.ts +12 -2
- package/src/cli/commands/members.ts +40 -14
- package/src/cli/commands/run.ts +133 -23
- package/src/cli/context.ts +12 -4
- package/src/cli/index.ts +6 -1
- package/src/cli/web-prompt.ts +28 -14
- package/src/core/admin.ts +23 -6
- package/src/core/doctor.ts +6 -7
- package/src/core/errors.ts +2 -2
- package/src/core/holder.ts +9 -6
- package/src/core/identity.ts +5 -3
- package/src/core/json-file.ts +20 -0
- package/src/core/layout.ts +5 -7
- package/src/core/naming.ts +13 -10
- package/src/core/payload.ts +2 -2
- package/src/core/revisions.ts +3 -2
- package/src/core/state.ts +16 -8
- package/src/core/txn.ts +4 -3
- package/src/core/worktrees.ts +18 -6
- package/src/daemon/agent-routes.ts +2 -0
- package/src/daemon/client.ts +9 -2
- package/src/daemon/daemon.ts +9 -2
- package/src/daemon/grants.ts +4 -3
- package/src/daemon/http.ts +8 -2
- package/src/daemon/live-access.ts +4 -0
- package/src/daemon/requests.ts +65 -36
- package/src/daemon/spawn.ts +42 -12
- package/src/import/dotenv.ts +2 -1
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +8 -0
- package/src/prompt/types.ts +4 -1
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
package/src/core/state.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
|
|
3
3
|
import { z } from 'zod'
|
|
4
4
|
|
|
5
5
|
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
6
|
-
import { canonicalJson,
|
|
6
|
+
import { canonicalJson, type Json, utf8 } from './encoding'
|
|
7
7
|
import { TypeVaultError } from './errors'
|
|
8
|
-
import { atomicWrite } from './fsx'
|
|
8
|
+
import { atomicWrite, ensureDir } from './fsx'
|
|
9
|
+
import { readJsonFile } from './json-file'
|
|
9
10
|
import type { Layout } from './layout'
|
|
10
11
|
import { RevisionMarks } from './revisions'
|
|
11
12
|
|
|
@@ -96,11 +97,13 @@ export const ceilingsDoc = (ceilings: VaultState['ceilings'], key: SecretKey, se
|
|
|
96
97
|
signedDoc({ v: 1, seq, ceilings }, key)
|
|
97
98
|
|
|
98
99
|
function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: PublicKey): T {
|
|
99
|
-
const doc = z.object({ body: z.json(), sig: z.string() })
|
|
100
|
+
const doc = readJsonFile(path, z.object({ body: z.json(), sig: z.string() }))
|
|
100
101
|
if (!verifySignature(owner.signPublic, utf8(canonicalJson(doc.body)), doc.sig)) {
|
|
101
102
|
throw new TypeVaultError('tampered', `${path} is not signed by the vault owner`)
|
|
102
103
|
}
|
|
103
|
-
|
|
104
|
+
const parsed = schema.safeParse(doc.body)
|
|
105
|
+
if (!parsed.success) throw new TypeVaultError('tampered', `${path} has a malformed manifest body`)
|
|
106
|
+
return parsed.data
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
/** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
|
|
@@ -111,19 +114,24 @@ function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<strin
|
|
|
111
114
|
return
|
|
112
115
|
}
|
|
113
116
|
if (!existsSync(layout.trustFile)) {
|
|
117
|
+
ensureDir(layout.root, 0o700)
|
|
114
118
|
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
115
119
|
return
|
|
116
120
|
}
|
|
117
|
-
const trust =
|
|
121
|
+
const trust = readJsonFile(layout.trustFile, TrustSchema)
|
|
118
122
|
if (trust.ownerSignPublic !== owner.signPublic) {
|
|
119
123
|
throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
|
|
120
124
|
}
|
|
121
125
|
}
|
|
122
126
|
|
|
123
|
-
export function
|
|
127
|
+
export function readOwner(layout: Layout): PublicKey {
|
|
124
128
|
if (!existsSync(layout.ownerFile))
|
|
125
129
|
throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
|
|
126
|
-
|
|
130
|
+
return readJsonFile(layout.ownerFile, PublicKeySchema)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
|
|
134
|
+
const owner = readOwner(layout)
|
|
127
135
|
checkTrust(layout, owner, env)
|
|
128
136
|
const tiers = readSigned(layout.tiersFile, TiersBody, owner)
|
|
129
137
|
const members = readSigned(layout.membersFile, MembersBody, owner)
|
package/src/core/txn.ts
CHANGED
|
@@ -4,9 +4,10 @@ import { dirname, isAbsolute, join, normalize, sep } from 'node:path'
|
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
|
|
6
6
|
import { randomHex } from './crypto'
|
|
7
|
-
import {
|
|
7
|
+
import { utf8 } from './encoding'
|
|
8
8
|
import { TypeVaultError } from './errors'
|
|
9
9
|
import { assertNoSymlinks, atomicWrite, fsyncDir } from './fsx'
|
|
10
|
+
import { readJsonFile } from './json-file'
|
|
10
11
|
import type { Layout } from './layout'
|
|
11
12
|
|
|
12
13
|
const COMMITTED = 'COMMITTED'
|
|
@@ -53,7 +54,7 @@ function checkRel(rel: string): string {
|
|
|
53
54
|
export function commitTxn(layout: Layout, txn: Txn): void {
|
|
54
55
|
if (txn.isEmpty) return
|
|
55
56
|
const dir = join(layout.txnDir, randomHex(8))
|
|
56
|
-
mkdirSync(join(dir, 'files'), { recursive: true })
|
|
57
|
+
mkdirSync(join(dir, 'files'), { recursive: true, mode: 0o700 })
|
|
57
58
|
const puts = [...txn.puts.keys()]
|
|
58
59
|
puts.forEach((rel, index) => atomicWrite(join(dir, 'files', String(index)), txn.puts.get(rel) ?? new Uint8Array()))
|
|
59
60
|
atomicWrite(join(dir, 'manifest.json'), JSON.stringify({ puts, removes: [...txn.removes] }))
|
|
@@ -63,7 +64,7 @@ export function commitTxn(layout: Layout, txn: Txn): void {
|
|
|
63
64
|
|
|
64
65
|
/** Idempotent: a crash halfway through is finished by running it again. */
|
|
65
66
|
function applyTxn(layout: Layout, dir: string): void {
|
|
66
|
-
const manifest =
|
|
67
|
+
const manifest = readJsonFile(join(dir, 'manifest.json'), ManifestSchema)
|
|
67
68
|
const touched = new Set<string>()
|
|
68
69
|
manifest.puts.forEach((rel, index) => {
|
|
69
70
|
const staged = join(dir, 'files', String(index))
|
package/src/core/worktrees.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
-
import { dirname, join, relative } from 'node:path'
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
3
3
|
|
|
4
4
|
/** git's own variables (set inside hooks, say) would point it at another repository than the vault's. */
|
|
5
5
|
const gitEnv = (): Record<string, string | undefined> =>
|
|
@@ -29,11 +29,23 @@ export async function worktreeVaults(vault: string): Promise<readonly string[]>
|
|
|
29
29
|
if (top === undefined || top === '') return []
|
|
30
30
|
const path = relative(realpathSync(top), own)
|
|
31
31
|
const listed = (await git(dirname(own), ['worktree', 'list', '--porcelain'])) ?? ''
|
|
32
|
-
|
|
32
|
+
const checkouts = listed
|
|
33
33
|
.split('\n')
|
|
34
34
|
.filter((line) => line.startsWith('worktree '))
|
|
35
|
-
.map((line) =>
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
|
39
51
|
}
|
|
@@ -37,6 +37,7 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
37
37
|
mode: 'live',
|
|
38
38
|
grant: record.id,
|
|
39
39
|
label: record.label,
|
|
40
|
+
owner: isSession && record.parent === undefined && context.vault.keyring.owner !== undefined,
|
|
40
41
|
ownTiers: isSession ? (context.sessionTiers ?? []) : record.tiers,
|
|
41
42
|
...(isSession || record.tiers[0] === undefined ? {} : { defaultTier: record.tiers[0] }),
|
|
42
43
|
})
|
|
@@ -56,6 +57,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
56
57
|
return json({ ...record, ownTiers: await access.ownTiers() })
|
|
57
58
|
},
|
|
58
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() }),
|
|
59
61
|
'/v1/get': async (request) => {
|
|
60
62
|
const { name, reason } = await parseBody(request, NameBody)
|
|
61
63
|
return json(await session(context, request).access.get(name, reason))
|
package/src/daemon/client.ts
CHANGED
|
@@ -41,7 +41,10 @@ export async function callDaemon<T>(
|
|
|
41
41
|
signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
|
|
42
42
|
})
|
|
43
43
|
} catch (error) {
|
|
44
|
-
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
|
+
}
|
|
45
48
|
throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`)
|
|
46
49
|
}
|
|
47
50
|
throw error
|
|
@@ -53,7 +56,11 @@ export async function callDaemon<T>(
|
|
|
53
56
|
? new TypeVaultError(toCode(parsed.data.error.code), parsed.data.error.message)
|
|
54
57
|
: new TypeVaultError('unavailable', `daemon answered ${response.status}`)
|
|
55
58
|
}
|
|
56
|
-
|
|
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
|
|
57
64
|
}
|
|
58
65
|
|
|
59
66
|
/** The PID of the daemon answering on `socket`, or undefined when none answers (or it is too old to say). */
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { atomicWrite, ensureDir } from '../core/fsx'
|
|
|
9
9
|
import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
|
|
10
10
|
import { type Layout, localLayout } from '../core/layout'
|
|
11
11
|
import { holdLock, isLockHeld } from '../core/lock'
|
|
12
|
-
import { loadState } from '../core/state'
|
|
12
|
+
import { loadState, readOwner } from '../core/state'
|
|
13
13
|
import { Vault } from '../core/vault'
|
|
14
14
|
import { worktreeVaults } from '../core/worktrees'
|
|
15
15
|
import { adminRoutes, type Ceiling } from './admin-routes'
|
|
@@ -129,9 +129,13 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
|
|
|
129
129
|
attaching.delete(started)
|
|
130
130
|
}
|
|
131
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 })
|
|
132
136
|
const context: DaemonContext = {
|
|
133
137
|
vault,
|
|
134
|
-
grants
|
|
138
|
+
grants,
|
|
135
139
|
sessions: new Map(),
|
|
136
140
|
requests: new PromptRequests(vault, options.prompt ?? {}),
|
|
137
141
|
...(options.session === undefined
|
|
@@ -238,6 +242,9 @@ async function worktreeLayout(vault: Vault, env: DaemonOptions['env'], target: s
|
|
|
238
242
|
throw new TypeVaultError('denied', `${target} is not this vault in a worktree of its repository`)
|
|
239
243
|
}
|
|
240
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
|
+
}
|
|
241
248
|
loadState(layout, { ...env, TYPEVAULT_OWNER: vault.state.owner.signPublic })
|
|
242
249
|
return layout
|
|
243
250
|
}
|
package/src/daemon/grants.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { timingSafeEqual } from 'node:crypto'
|
|
2
|
-
import { existsSync
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
3
|
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
|
|
@@ -8,6 +8,7 @@ import { randomHex, randomToken, sha256Hex } from '../core/crypto'
|
|
|
8
8
|
import { utf8 } from '../core/encoding'
|
|
9
9
|
import { TypeVaultError } from '../core/errors'
|
|
10
10
|
import { atomicWrite } from '../core/fsx'
|
|
11
|
+
import { readJsonFile } from '../core/json-file'
|
|
11
12
|
|
|
12
13
|
const RecordSchema = z.object({
|
|
13
14
|
id: z.string(),
|
|
@@ -45,7 +46,7 @@ export const SESSION_CEILING = ':session'
|
|
|
45
46
|
export const MAX_CHAIN = 8
|
|
46
47
|
|
|
47
48
|
/**
|
|
48
|
-
* Live grants, persisted (hashed) so a daemon restart doesn't cut
|
|
49
|
+
* Live grants, persisted (hashed) so a daemon restart doesn't cut issued grants off. `typevault lock` ends them.
|
|
49
50
|
* A token is `tvl1.<id>.<secret>`; only sha256(secret) is stored.
|
|
50
51
|
*/
|
|
51
52
|
export class GrantStore {
|
|
@@ -54,7 +55,7 @@ export class GrantStore {
|
|
|
54
55
|
|
|
55
56
|
constructor(path: string) {
|
|
56
57
|
this.#path = path
|
|
57
|
-
this.#records = existsSync(path) ? z.array(RecordSchema)
|
|
58
|
+
this.#records = existsSync(path) ? readJsonFile(path, z.array(RecordSchema)) : []
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
#save(): void {
|
package/src/daemon/http.ts
CHANGED
|
@@ -30,7 +30,14 @@ export function errorResponse(error: unknown): Response {
|
|
|
30
30
|
|
|
31
31
|
export async function parseBody<T>(request: Request, schema: z.ZodType<T>): Promise<T> {
|
|
32
32
|
const text = await request.text()
|
|
33
|
-
|
|
33
|
+
let body: unknown
|
|
34
|
+
try {
|
|
35
|
+
body = text === '' ? {} : JSON.parse(text)
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (error instanceof SyntaxError) throw new TypeVaultError('invalid', 'request body is not JSON')
|
|
38
|
+
throw error
|
|
39
|
+
}
|
|
40
|
+
const parsed = schema.safeParse(body)
|
|
34
41
|
if (!parsed.success)
|
|
35
42
|
throw new TypeVaultError('invalid', `bad request: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
|
|
36
43
|
return parsed.data
|
|
@@ -47,7 +54,6 @@ export function router(routes: Readonly<Record<string, Handler>>): (request: Req
|
|
|
47
54
|
try {
|
|
48
55
|
return await handler(request)
|
|
49
56
|
} catch (error) {
|
|
50
|
-
if (error instanceof SyntaxError) return errorResponse(new TypeVaultError('invalid', 'request body is not JSON'))
|
|
51
57
|
return errorResponse(error)
|
|
52
58
|
}
|
|
53
59
|
}
|
|
@@ -28,6 +28,10 @@ export class LiveAccess implements Access {
|
|
|
28
28
|
return (await this.call('/v1/list', {}, z.array(EntrySummarySchema))).map(toSummaryValue)
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
async unreadableEntries(): Promise<number> {
|
|
32
|
+
return (await this.call('/v1/unreadable', {}, z.object({ count: z.number().int() }))).count
|
|
33
|
+
}
|
|
34
|
+
|
|
31
35
|
async get(name: EntryName, reason?: string): Promise<EntryValue> {
|
|
32
36
|
return toEntryValue(await this.call('/v1/get', { name, reason }, EntryValueSchema))
|
|
33
37
|
}
|
package/src/daemon/requests.ts
CHANGED
|
@@ -47,12 +47,17 @@ export class PromptRequests {
|
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
#prompt(): Promise<PromptServer> {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
this.#server ??= startPromptServer(this.#options).catch((error: unknown) => {
|
|
51
|
+
this.#server = undefined
|
|
52
|
+
throw error
|
|
53
|
+
})
|
|
54
|
+
return this.#server
|
|
53
55
|
}
|
|
54
56
|
|
|
55
|
-
async open(
|
|
57
|
+
async open(
|
|
58
|
+
session: RequestSession,
|
|
59
|
+
input: RequestInput,
|
|
60
|
+
): Promise<{ id: string; url: string; code: string; expiresAt: number }> {
|
|
56
61
|
const { chain, grant } = session
|
|
57
62
|
const state = this.#vault.state
|
|
58
63
|
const tier = input.tier ?? grant.tiers[0]
|
|
@@ -65,35 +70,59 @@ export class PromptRequests {
|
|
|
65
70
|
throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
|
|
66
71
|
}
|
|
67
72
|
const code = matchCode()
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
73
|
+
const expiresAt = Date.now() + TTL_MS
|
|
74
|
+
const handle = (await this.#prompt()).open(
|
|
75
|
+
{
|
|
76
|
+
name: input.name,
|
|
77
|
+
...(input.preset === undefined ? {} : { preset: input.preset }),
|
|
78
|
+
tier,
|
|
79
|
+
reason: input.reason,
|
|
80
|
+
requester: grant.label,
|
|
81
|
+
code,
|
|
82
|
+
recipients: [meta.recipient, state.owner.recipient],
|
|
83
|
+
expiresAt: new Date(expiresAt),
|
|
84
|
+
},
|
|
85
|
+
{ validate: true },
|
|
86
|
+
)
|
|
78
87
|
// Whoever holds the URL can submit, the requesting agent included, so the daemon checks what it got instead
|
|
79
88
|
// of signing it blind: it must be exactly the requested entry, and the grant must still be live.
|
|
80
89
|
const stored = handle.done.then(async (ciphertext) => {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
90
|
+
try {
|
|
91
|
+
const key = (await this.#vault.keyring.unlock(tier)) ?? this.#vault.keyring.owner
|
|
92
|
+
if (key === undefined) throw new TypeVaultError('denied', `no key here can read tier "${tier}"`)
|
|
93
|
+
const payload = decodePayload(await unseal([key.identity], ciphertext))
|
|
94
|
+
if (payload.name !== input.name || payload.env !== undefined || payload.needsRotation !== undefined) {
|
|
95
|
+
throw new TypeVaultError('tampered', 'the submitted secret does not match the request')
|
|
96
|
+
}
|
|
97
|
+
if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
|
|
98
|
+
await session.access.set({ name: input.name, fields: payload.fields, tier })
|
|
99
|
+
await appendAudit(this.#vault.layout, {
|
|
100
|
+
action: 'request.stored',
|
|
101
|
+
mode: 'live',
|
|
102
|
+
grant: grant.id,
|
|
103
|
+
label: grant.label,
|
|
104
|
+
entries: [input.name],
|
|
105
|
+
})
|
|
106
|
+
await handle.accept()
|
|
107
|
+
return input.name
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const rejected =
|
|
110
|
+
error instanceof TypeVaultError
|
|
111
|
+
? error
|
|
112
|
+
: new TypeVaultError('unavailable', 'the submitted secret could not be stored')
|
|
113
|
+
try {
|
|
114
|
+
await appendAudit(this.#vault.layout, {
|
|
115
|
+
action: 'request.rejected',
|
|
116
|
+
mode: 'live',
|
|
117
|
+
grant: grant.id,
|
|
118
|
+
label: grant.label,
|
|
119
|
+
entries: [input.name],
|
|
120
|
+
})
|
|
121
|
+
} finally {
|
|
122
|
+
await handle.reject(rejected)
|
|
123
|
+
}
|
|
124
|
+
throw error
|
|
86
125
|
}
|
|
87
|
-
if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
|
|
88
|
-
await session.access.set({ name: input.name, fields: payload.fields, tier })
|
|
89
|
-
await appendAudit(this.#vault.layout, {
|
|
90
|
-
action: 'request.stored',
|
|
91
|
-
mode: 'live',
|
|
92
|
-
grant: grant.id,
|
|
93
|
-
label: grant.label,
|
|
94
|
-
entries: [input.name],
|
|
95
|
-
})
|
|
96
|
-
return input.name
|
|
97
126
|
})
|
|
98
127
|
// Forget the request a while after it settles, whether or not anyone waits for it.
|
|
99
128
|
const forget = (): void => {
|
|
@@ -114,21 +143,21 @@ export class PromptRequests {
|
|
|
114
143
|
tiers: [tier],
|
|
115
144
|
reason: input.reason,
|
|
116
145
|
})
|
|
117
|
-
return { id: handle.id, url: handle.url, code }
|
|
146
|
+
return { id: handle.id, url: handle.url, code, expiresAt }
|
|
118
147
|
}
|
|
119
148
|
|
|
120
149
|
async wait(grantId: string, id: string): Promise<EntryName> {
|
|
121
150
|
const pending = this.#pending.get(id)
|
|
122
151
|
if (pending === undefined || pending.owner !== grantId) throw new TypeVaultError('not_found', 'no such request')
|
|
123
|
-
|
|
124
|
-
return await pending.stored
|
|
125
|
-
} finally {
|
|
126
|
-
this.#pending.delete(id)
|
|
127
|
-
}
|
|
152
|
+
return pending.stored
|
|
128
153
|
}
|
|
129
154
|
|
|
130
155
|
async stop(): Promise<void> {
|
|
131
|
-
|
|
156
|
+
// A failed startup has no listener to stop, including one still settling when shutdown begins.
|
|
157
|
+
await this.#server?.then(
|
|
158
|
+
(server) => server.stop(),
|
|
159
|
+
() => undefined,
|
|
160
|
+
)
|
|
132
161
|
}
|
|
133
162
|
}
|
|
134
163
|
|
package/src/daemon/spawn.ts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
-
import { closeSync, existsSync, openSync, readFileSync, rmSync } from 'node:fs'
|
|
2
|
+
import { closeSync, existsSync, openSync, readFileSync, rmSync, statSync } from 'node:fs'
|
|
3
3
|
import { dirname, join, resolve } from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
|
|
6
6
|
import { z } from 'zod'
|
|
7
7
|
|
|
8
8
|
import { machineKeys } from '../access/keys'
|
|
9
|
+
import { appendAudit } from '../audit/log'
|
|
9
10
|
import { encodeSecretKey, type SecretKey } from '../core/crypto'
|
|
10
11
|
import { TypeVaultError } from '../core/errors'
|
|
11
12
|
import { ensureDir } from '../core/fsx'
|
|
12
|
-
import { refuseForeignDaemon } from '../core/holder'
|
|
13
|
+
import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
|
|
13
14
|
import { configDir, type Layout } from '../core/layout'
|
|
14
|
-
import { isLockHeld } from '../core/lock'
|
|
15
|
+
import { holdLock, isLockHeld } from '../core/lock'
|
|
15
16
|
import { callDaemon, isDaemonAlive, servingPid } from './client'
|
|
16
17
|
|
|
17
18
|
type Env = Readonly<Record<string, string | undefined>>
|
|
@@ -98,6 +99,30 @@ export async function stopDaemon(layout: Layout): Promise<void> {
|
|
|
98
99
|
}
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
/**
|
|
103
|
+
* What `typevault lock` does once the daemon is gone: no live grant comes back with the next unlock. Under the daemon
|
|
104
|
+
* lock and a claim on the state directory, so no daemon, on this machine or one sharing the directory, can start in
|
|
105
|
+
* between and write back the grants it just loaded. The file is deleted rather than parsed, which is also how a damaged
|
|
106
|
+
* one is cleared.
|
|
107
|
+
*/
|
|
108
|
+
export async function endLiveGrants(layout: Layout, env: Env): Promise<void> {
|
|
109
|
+
if (!existsSync(layout.grantsFile) && !existsSync(layout.sessionFile)) return
|
|
110
|
+
const release = holdLock(layout.daemonLock)
|
|
111
|
+
if (release === undefined) {
|
|
112
|
+
throw new TypeVaultError('conflict', 'a typevault daemon started here while locking; run `typevault lock` again')
|
|
113
|
+
}
|
|
114
|
+
let claim: DaemonClaim | undefined
|
|
115
|
+
try {
|
|
116
|
+
claim = claimDaemon(layout, env)
|
|
117
|
+
rmSync(layout.grantsFile, { force: true })
|
|
118
|
+
rmSync(layout.sessionFile, { force: true })
|
|
119
|
+
await appendAudit(layout, { action: 'grant.revoke', mode: 'live', reason: 'typevault lock' })
|
|
120
|
+
} finally {
|
|
121
|
+
claim?.release()
|
|
122
|
+
release()
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
101
126
|
function pidIn(pidFile: string): number | undefined {
|
|
102
127
|
if (!existsSync(pidFile)) return undefined
|
|
103
128
|
const pid = Number.parseInt(readFileSync(pidFile, 'utf8'), 10)
|
|
@@ -157,7 +182,8 @@ export async function startBackground(
|
|
|
157
182
|
ensureDir(layout.run, 0o700)
|
|
158
183
|
// A background daemon has no terminal: its output goes to a log, so a failed start can say why.
|
|
159
184
|
const logPath = join(layout.run, 'daemon.log')
|
|
160
|
-
const
|
|
185
|
+
const logOffset = existsSync(logPath) ? statSync(logPath).size : 0
|
|
186
|
+
const log = openSync(logPath, 'a', 0o600)
|
|
161
187
|
// The child starts in its private run directory, never the project's: Bun reads bunfig.toml (a preload) and .env from
|
|
162
188
|
// its directory, and anyone who can edit a checkout (an agent) could have it read the key off stdin. So it is handed
|
|
163
189
|
// the vault by path. Its private state is where this process resolved it: `env` may lack the HOME this process fell
|
|
@@ -190,16 +216,20 @@ export async function startBackground(
|
|
|
190
216
|
}
|
|
191
217
|
// Two starts racing: the one that loses exits with a conflict while the other's daemon is already serving.
|
|
192
218
|
if (await isDaemonAlive(layout.agentSocket)) return
|
|
193
|
-
throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath)}`)
|
|
219
|
+
throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath, logOffset)}`)
|
|
194
220
|
}
|
|
195
221
|
|
|
196
|
-
/**
|
|
197
|
-
function whyNotStarted(logPath: string): string {
|
|
198
|
-
const
|
|
199
|
-
? readFileSync(logPath
|
|
222
|
+
/** Prefer the current start's cause over a runtime's source excerpt, with where to read the rest. */
|
|
223
|
+
function whyNotStarted(logPath: string, offset: number): string {
|
|
224
|
+
const lines = existsSync(logPath)
|
|
225
|
+
? readFileSync(logPath)
|
|
226
|
+
.subarray(offset)
|
|
227
|
+
.toString('utf8')
|
|
200
228
|
.split('\n')
|
|
201
229
|
.map((line) => line.trim())
|
|
202
|
-
.
|
|
203
|
-
:
|
|
204
|
-
|
|
230
|
+
.filter((line) => line !== '')
|
|
231
|
+
: []
|
|
232
|
+
const first = lines.find((line) => line.startsWith('typevault:') || /^\w*error:/i.test(line)) ?? lines[0]
|
|
233
|
+
const message = first?.replace(/^typevault:\s*/, '')
|
|
234
|
+
return message === undefined ? `no output (see ${logPath})` : `${message} (full log: ${logPath})`
|
|
205
235
|
}
|
package/src/import/dotenv.ts
CHANGED
|
@@ -8,8 +8,9 @@ import type { ImportResult } from './types'
|
|
|
8
8
|
const VariableSchema = z.object({ name: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), value: z.string() }).readonly()
|
|
9
9
|
|
|
10
10
|
export function parseDotenv(text: string): ImportResult {
|
|
11
|
+
const variables = new Map(parseDotenvVariables(text).map((variable) => [variable.name, variable]))
|
|
11
12
|
return collectEntries(
|
|
12
|
-
|
|
13
|
+
[...variables.values()].map(({ name, value }) => ({
|
|
13
14
|
title: name,
|
|
14
15
|
preset: 'api_key',
|
|
15
16
|
fields: { $default: value },
|