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.
Files changed (76) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +14 -9
  7. package/src/access/scoped.ts +118 -44
  8. package/src/access/sealed-access.ts +50 -23
  9. package/src/access/sealed.ts +56 -31
  10. package/src/access/types.ts +27 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +28 -12
  13. package/src/cli/commands/admin.ts +93 -48
  14. package/src/cli/commands/daemon.ts +42 -17
  15. package/src/cli/commands/entries.ts +195 -60
  16. package/src/cli/commands/grant.ts +24 -22
  17. package/src/cli/commands/members.ts +307 -0
  18. package/src/cli/commands/run.ts +191 -44
  19. package/src/cli/context.ts +163 -15
  20. package/src/cli/index.ts +33 -5
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +79 -0
  23. package/src/core/admin.ts +144 -76
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +15 -16
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +8 -2
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +87 -0
  31. package/src/core/identity.ts +132 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/json-file.ts +20 -0
  34. package/src/core/keyring.ts +100 -56
  35. package/src/core/layout.ts +143 -26
  36. package/src/core/lock.ts +128 -16
  37. package/src/core/naming.ts +150 -50
  38. package/src/core/password.ts +111 -0
  39. package/src/core/payload.ts +42 -38
  40. package/src/core/revisions.ts +11 -6
  41. package/src/core/rotate.ts +59 -42
  42. package/src/core/state.ts +102 -54
  43. package/src/core/txn.ts +9 -7
  44. package/src/core/vault.ts +108 -46
  45. package/src/core/worktrees.ts +51 -0
  46. package/src/daemon/admin-routes.ts +33 -21
  47. package/src/daemon/agent-routes.ts +31 -11
  48. package/src/daemon/client.ts +24 -2
  49. package/src/daemon/daemon.ts +218 -33
  50. package/src/daemon/grants.ts +25 -7
  51. package/src/daemon/http.ts +11 -2
  52. package/src/daemon/live-access.ts +8 -4
  53. package/src/daemon/protocol.ts +17 -12
  54. package/src/daemon/requests.ts +75 -51
  55. package/src/daemon/spawn.ts +218 -9
  56. package/src/export/1password.ts +157 -0
  57. package/src/import/1password-live.ts +399 -0
  58. package/src/import/1password.ts +26 -5
  59. package/src/import/bitwarden.ts +3 -3
  60. package/src/import/csv.ts +1 -1
  61. package/src/import/dotenv.ts +4 -3
  62. package/src/import/index.ts +1 -0
  63. package/src/import/keepass.ts +2 -2
  64. package/src/import/lastpass.ts +2 -2
  65. package/src/import/shared.ts +67 -10
  66. package/src/import/typeclaw.ts +2 -2
  67. package/src/import/types.ts +1 -1
  68. package/src/index.ts +58 -0
  69. package/src/owner.ts +156 -0
  70. package/src/prompt/browser.ts +48 -15
  71. package/src/prompt/index.ts +121 -64
  72. package/src/prompt/page.ts +27 -11
  73. package/src/prompt/styles.ts +64 -34
  74. package/src/prompt/types.ts +7 -4
  75. package/src/redact/index.ts +48 -12
  76. package/src/redact/scrub-file.ts +15 -7
@@ -1,5 +1,5 @@
1
1
  import { timingSafeEqual } from 'node:crypto'
2
- import { existsSync, readFileSync } from 'node:fs'
2
+ import { existsSync } from 'node:fs'
3
3
 
4
4
  import { z } from 'zod'
5
5
 
@@ -8,12 +8,13 @@ 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(),
14
15
  hash: z.string(),
15
16
  label: z.string(),
16
- groups: z.array(z.string()),
17
+ tiers: z.array(z.string()),
17
18
  only: z.array(z.string()),
18
19
  exp: z.iso.datetime(),
19
20
  created: z.iso.datetime(),
@@ -24,7 +25,7 @@ const RecordSchema = z.object({
24
25
  })
25
26
  export type GrantRecord = z.infer<typeof RecordSchema>
26
27
  export type GrantRequest = {
27
- readonly groups: readonly string[]
28
+ readonly tiers: readonly string[]
28
29
  readonly only: readonly string[]
29
30
  readonly ttlMs: number
30
31
  readonly label: string
@@ -36,7 +37,16 @@ export type ResolvedGrant = { readonly record: GrantRecord; readonly chain: Scop
36
37
  const PREFIX = 'tvl1'
37
38
 
38
39
  /**
39
- * Live grants, persisted (hashed) so a daemon restart doesn't cut sessions off.
40
+ * The ceiling name marking an unlocked session's grant (and grants derived from it). It is no valid ceiling name,
41
+ * so no admin socket owns the session: a ceiling named `session` can neither list nor revoke it.
42
+ */
43
+ export const SESSION_CEILING = ':session'
44
+
45
+ /** Every request under a grant checks each link of its chain, so derivation may not nest without bound. */
46
+ export const MAX_CHAIN = 8
47
+
48
+ /**
49
+ * Live grants, persisted (hashed) so a daemon restart doesn't cut issued grants off. `typevault lock` ends them.
40
50
  * A token is `tvl1.<id>.<secret>`; only sha256(secret) is stored.
41
51
  */
42
52
  export class GrantStore {
@@ -45,7 +55,7 @@ export class GrantStore {
45
55
 
46
56
  constructor(path: string) {
47
57
  this.#path = path
48
- this.#records = existsSync(path) ? z.array(RecordSchema).parse(JSON.parse(readFileSync(path, 'utf8'))) : []
58
+ this.#records = existsSync(path) ? readJsonFile(path, z.array(RecordSchema)) : []
49
59
  }
50
60
 
51
61
  #save(): void {
@@ -56,6 +66,14 @@ export class GrantStore {
56
66
 
57
67
  issue(request: GrantRequest): { readonly token: string; readonly record: GrantRecord } {
58
68
  const parent = request.parent === undefined ? undefined : this.#records.find((r) => r.id === request.parent)
69
+ let links = 1
70
+ for (let link = parent; link !== undefined; links++) {
71
+ const parentId = link.parent
72
+ link = parentId === undefined ? undefined : this.#records.find((r) => r.id === parentId)
73
+ }
74
+ if (links > MAX_CHAIN) {
75
+ throw new TypeVaultError('invalid', `a grant can be derived at most ${MAX_CHAIN - 1} levels deep`)
76
+ }
59
77
  const requestedExp = Date.now() + request.ttlMs
60
78
  const exp = parent === undefined ? requestedExp : Math.min(requestedExp, Date.parse(parent.exp))
61
79
  const secret = randomToken(32)
@@ -63,7 +81,7 @@ export class GrantStore {
63
81
  id: randomHex(8),
64
82
  hash: sha256Hex(utf8(secret)),
65
83
  label: request.label,
66
- groups: [...request.groups],
84
+ tiers: [...request.tiers],
67
85
  only: [...request.only],
68
86
  exp: new Date(exp).toISOString(),
69
87
  created: new Date().toISOString(),
@@ -96,7 +114,7 @@ export class GrantStore {
96
114
  link = parentId === undefined ? undefined : this.#records.find((r) => r.id === parentId)
97
115
  if (parentId !== undefined && link === undefined) throw new TypeVaultError('denied', 'parent grant is gone')
98
116
  }
99
- return { record, chain: chain.map(({ groups, only }) => ({ groups, only })) }
117
+ return { record, chain: chain.map(({ tiers, only }) => ({ tiers, only })) }
100
118
  }
101
119
 
102
120
  /** Whether grant `id` and all its ancestors are still unrevoked and unexpired. */
@@ -12,6 +12,9 @@ const STATUS: Readonly<Record<ErrorCode, number>> = {
12
12
  tampered: 422,
13
13
  locked: 423,
14
14
  unavailable: 503,
15
+ in_use: 423,
16
+ no_vault: 404,
17
+ not_member: 403,
15
18
  }
16
19
 
17
20
  export const json = (body: unknown, status = 200): Response =>
@@ -27,7 +30,14 @@ export function errorResponse(error: unknown): Response {
27
30
 
28
31
  export async function parseBody<T>(request: Request, schema: z.ZodType<T>): Promise<T> {
29
32
  const text = await request.text()
30
- const parsed = schema.safeParse(text === '' ? {} : JSON.parse(text))
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)
31
41
  if (!parsed.success)
32
42
  throw new TypeVaultError('invalid', `bad request: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
33
43
  return parsed.data
@@ -44,7 +54,6 @@ export function router(routes: Readonly<Record<string, Handler>>): (request: Req
44
54
  try {
45
55
  return await handler(request)
46
56
  } catch (error) {
47
- if (error instanceof SyntaxError) return errorResponse(new TypeVaultError('invalid', 'request body is not JSON'))
48
57
  return errorResponse(error)
49
58
  }
50
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
  }
@@ -40,16 +44,16 @@ export class LiveAccess implements Access {
40
44
  return toSummaryValue(await this.call('/v1/set', input, EntrySummarySchema))
41
45
  }
42
46
 
43
- async remove(name: EntryName, group?: string): Promise<void> {
44
- await this.call('/v1/remove', { name, ...(group === undefined ? {} : { group }) }, Ok)
47
+ async remove(name: EntryName, tier?: string): Promise<void> {
48
+ await this.call('/v1/remove', { name, ...(tier === undefined ? {} : { tier }) }, Ok)
45
49
  }
46
50
 
47
51
  async move(from: EntryName, to: EntryName): Promise<void> {
48
52
  await this.call('/v1/move', { from, to }, Ok)
49
53
  }
50
54
 
51
- async ownGroups(): Promise<readonly string[]> {
52
- return (await this.call('/v1/whoami', {}, z.object({ groups: z.array(z.string()) }))).groups
55
+ async ownTiers(): Promise<readonly string[]> {
56
+ return (await this.call('/v1/whoami', {}, z.object({ ownTiers: z.array(z.string()) }))).ownTiers
53
57
  }
54
58
 
55
59
  async readValues(): Promise<readonly string[]> {
@@ -1,18 +1,22 @@
1
1
  import { z } from 'zod'
2
2
 
3
- import { isEntryType, parseEntryName } from '../core/naming'
3
+ import { isPreset, parseEntryName } from '../core/naming'
4
+ import { FieldsSchema } from '../core/payload'
4
5
 
5
6
  const name = z.string().transform((value) => parseEntryName(value))
6
- const type = z.string().refine(isEntryType, 'unknown entry type')
7
+ const preset = z.string().refine(isPreset, 'unknown preset').optional()
7
8
  const reason = z.string().max(500).optional()
9
+ /** Every request under a grant matches against its `only` patterns, so a grant may not carry an unbounded list. */
10
+ const only = z.array(z.string().max(256)).max(100).default([])
11
+ /** Every request under a grant checks its tiers too, so they are capped like `only`. */
12
+ const tiers = z.array(z.string().max(256)).max(100)
8
13
 
9
- export const NameBody = z.object({ name, reason, group: z.string().optional() })
10
- export const ValuesBody = z.object({ only: z.array(z.string()).default([]), reason })
14
+ export const NameBody = z.object({ name, reason, tier: z.string().optional() })
15
+ export const ValuesBody = z.object({ only, reason })
11
16
  export const SetBody = z.object({
12
17
  name,
13
- type,
14
- fields: z.record(z.string(), z.string()),
15
- group: z.string().optional(),
18
+ fields: FieldsSchema,
19
+ tier: z.string().optional(),
16
20
  env: z
17
21
  .string()
18
22
  .regex(/^[A-Z_][A-Z0-9_]*$/)
@@ -23,16 +27,17 @@ export const SetBody = z.object({
23
27
  })
24
28
  export const MoveBody = z.object({ from: name, to: name })
25
29
  export const DeriveBody = z.object({
26
- groups: z.array(z.string()).optional(),
27
- only: z.array(z.string()).default([]),
30
+ tiers: tiers.optional(),
31
+ only,
28
32
  ttl: z.string().optional(),
29
33
  label: z.string().max(200).optional(),
30
34
  })
31
- export const RequestBody = z.object({ name, type, group: z.string().optional(), reason: z.string().min(1).max(500) })
35
+ export const RequestBody = z.object({ name, preset, tier: z.string().optional(), reason: z.string().min(1).max(500) })
32
36
  export const WaitBody = z.object({ id: z.string() })
37
+ export const AttachBody = z.object({ vault: z.string() })
33
38
  export const GrantBody = z.object({
34
- groups: z.array(z.string()).min(1),
35
- only: z.array(z.string()).default([]),
39
+ tiers: tiers.min(1),
40
+ only,
36
41
  ttl: z.string().default('1h'),
37
42
  label: z.string().max(200).default('unlabeled'),
38
43
  sealed: z.boolean().default(false),
@@ -4,7 +4,7 @@ import { appendAudit } from '../audit/log'
4
4
  import { randomToken } from '../core/crypto'
5
5
  import { unseal } from '../core/crypto'
6
6
  import { TypeVaultError } from '../core/errors'
7
- import type { EntryName, EntryType } from '../core/naming'
7
+ import type { EntryName, Preset } from '../core/naming'
8
8
  import { decodePayload } from '../core/payload'
9
9
  import type { Vault } from '../core/vault'
10
10
  import { type PromptServer, startPromptServer } from '../prompt'
@@ -24,12 +24,12 @@ export type RequestSession = {
24
24
 
25
25
  export type RequestInput = {
26
26
  readonly name: EntryName
27
- readonly type: EntryType
28
- readonly group?: string | undefined
27
+ readonly preset?: Preset | undefined
28
+ readonly tier?: string | undefined
29
29
  readonly reason: string
30
30
  }
31
31
 
32
- const matchCode = (): string =>
32
+ export const matchCode = (): string =>
33
33
  [...crypto.getRandomValues(new Uint8Array(6))].map((byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length]).join('')
34
34
 
35
35
  type Pending = { readonly owner: string; readonly stored: Promise<EntryName> }
@@ -47,58 +47,82 @@ export class PromptRequests {
47
47
  }
48
48
 
49
49
  #prompt(): Promise<PromptServer> {
50
- const server = this.#server ?? startPromptServer(this.#options)
51
- this.#server = server
52
- return server
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(session: RequestSession, input: RequestInput): Promise<{ id: string; url: string; code: string }> {
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
- const group = input.group ?? grant.groups[0]
59
- const meta = group === undefined ? undefined : state.groups[group]
60
- if (group === undefined || meta === undefined || !allowsEntry(chain, state, group, input.name)) {
61
- throw new TypeVaultError('denied', `this grant cannot store ${input.name} in group "${group ?? '?'}"`)
63
+ const tier = input.tier ?? grant.tiers[0]
64
+ const meta = tier === undefined ? undefined : state.tiers[tier]
65
+ if (tier === undefined || meta === undefined || !allowsEntry(chain, state, tier, input.name)) {
66
+ throw new TypeVaultError('denied', `this grant cannot store ${input.name} in tier "${tier ?? '?'}"`)
62
67
  }
63
68
  const existing = await this.#vault.find(input.name)
64
- if (existing !== undefined && !allowsEntry(chain, state, existing.envelope.group, input.name)) {
69
+ if (existing !== undefined && !allowsEntry(chain, state, existing.envelope.tier, input.name)) {
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 handle = (await this.#prompt()).open({
69
- name: input.name,
70
- type: input.type,
71
- group,
72
- reason: input.reason,
73
- requester: grant.label,
74
- code,
75
- recipients: [meta.recipient, state.operator.recipient],
76
- expiresAt: new Date(Date.now() + TTL_MS),
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
- const key = (await this.#vault.keyring.unlock(group)) ?? this.#vault.keyring.operator
82
- if (key === undefined) throw new TypeVaultError('denied', `no key here can read group "${group}"`)
83
- const payload = decodePayload(await unseal([key.identity], ciphertext))
84
- if (
85
- payload.name !== input.name ||
86
- payload.type !== input.type ||
87
- payload.env !== undefined ||
88
- payload.needsRotation !== undefined
89
- ) {
90
- throw new TypeVaultError('tampered', 'the submitted secret does not match the request')
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
91
125
  }
92
- if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
93
- await session.access.set({ name: input.name, type: input.type, fields: payload.fields, group })
94
- await appendAudit(this.#vault.layout, {
95
- action: 'request.stored',
96
- mode: 'live',
97
- grant: grant.id,
98
- label: grant.label,
99
- entries: [input.name],
100
- })
101
- return input.name
102
126
  })
103
127
  // Forget the request a while after it settles, whether or not anyone waits for it.
104
128
  const forget = (): void => {
@@ -116,24 +140,24 @@ export class PromptRequests {
116
140
  grant: grant.id,
117
141
  label: grant.label,
118
142
  entries: [input.name],
119
- groups: [group],
143
+ tiers: [tier],
120
144
  reason: input.reason,
121
145
  })
122
- return { id: handle.id, url: handle.url, code }
146
+ return { id: handle.id, url: handle.url, code, expiresAt }
123
147
  }
124
148
 
125
149
  async wait(grantId: string, id: string): Promise<EntryName> {
126
150
  const pending = this.#pending.get(id)
127
151
  if (pending === undefined || pending.owner !== grantId) throw new TypeVaultError('not_found', 'no such request')
128
- try {
129
- return await pending.stored
130
- } finally {
131
- this.#pending.delete(id)
132
- }
152
+ return pending.stored
133
153
  }
134
154
 
135
155
  async stop(): Promise<void> {
136
- if (this.#server !== undefined) await (await this.#server).stop()
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
+ )
137
161
  }
138
162
  }
139
163
 
@@ -1,26 +1,235 @@
1
1
  import { spawn } from 'node:child_process'
2
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, statSync } from 'node:fs'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
2
5
 
6
+ import { z } from 'zod'
7
+
8
+ import { machineKeys } from '../access/keys'
9
+ import { appendAudit } from '../audit/log'
10
+ import { encodeSecretKey, type SecretKey } from '../core/crypto'
3
11
  import { TypeVaultError } from '../core/errors'
4
- import type { Layout } from '../core/layout'
5
- import { isDaemonAlive } from './client'
12
+ import { ensureDir } from '../core/fsx'
13
+ import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
14
+ import { configDir, type Layout } from '../core/layout'
15
+ import { holdLock, isLockHeld } from '../core/lock'
16
+ import { callDaemon, isDaemonAlive, servingPid } from './client'
17
+
18
+ type Env = Readonly<Record<string, string | undefined>>
6
19
 
7
20
  const START_TIMEOUT_MS = 10_000
8
21
  const POLL_MS = 50
9
- const CLI = new URL('../cli/index.ts', import.meta.url).pathname
22
+ const CLI = fileURLToPath(new URL('../cli/index.ts', import.meta.url))
23
+
24
+ export const LOCKED_MESSAGE = 'the vault is locked: ask a human to run `typevault unlock`'
10
25
 
11
- /** Starts the daemon in the background if it isn't running, like gpg-agent. */
12
- export async function ensureDaemon(layout: Layout, env: Readonly<Record<string, string | undefined>>): Promise<void> {
26
+ /**
27
+ * Starts the daemon in the background if it isn't running, like gpg-agent. Only a machine member can start one
28
+ * unattended; a human's daemon is started by `typevault unlock`, so a locked vault stays locked.
29
+ */
30
+ export async function ensureDaemon(layout: Layout, env: Env): Promise<void> {
13
31
  if (await isDaemonAlive(layout.agentSocket)) return
14
- const child = spawn(process.execPath, [CLI, 'daemon', 'run'], {
32
+ if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
33
+ refuseForeignDaemon(layout, env)
34
+ await startBackground(layout, env, [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout)])
35
+ }
36
+
37
+ /**
38
+ * Starts an unlocked session daemon holding `key`, handed over stdin so it never shows up in argv or env. With
39
+ * `sourceLock`, the session is another one's, shared with a worktree: it serves only while that one's daemon holds
40
+ * this lock, so it ends with it however that daemon ends.
41
+ */
42
+ export async function startSession(
43
+ layout: Layout,
44
+ env: Env,
45
+ key: SecretKey,
46
+ ttlMs: number,
47
+ sourceLock?: string,
48
+ ): Promise<void> {
49
+ const ttl = `${Math.ceil(ttlMs / 1000)}s`
50
+ const command = [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout), '--key-stdin', '--ttl', ttl]
51
+ if (sourceLock !== undefined) command.push('--source-lock', sourceLock)
52
+ // A token left by a daemon that died would pass for this session's before it writes its own.
53
+ rmSync(layout.sessionFile, { force: true })
54
+ await startBackground(layout, env, command, encodeSecretKey(key))
55
+ // The agent socket answers before the session's grant is written, and a caller reads that grant next.
56
+ const deadline = Date.now() + START_TIMEOUT_MS
57
+ while (!existsSync(layout.sessionFile)) {
58
+ if (Date.now() > deadline) throw new TypeVaultError('unavailable', 'the unlocked session did not start')
59
+ await Bun.sleep(POLL_MS)
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Stops this checkout's daemon and waits until it is gone, cleanup included: until it releases `run/daemon.lock`.
65
+ * Only the process that answers on the checkout's socket is signaled, by the PID it reports itself, so a stale PID
66
+ * file can never aim the signal at an unrelated process.
67
+ */
68
+ export async function stopDaemon(layout: Layout): Promise<void> {
69
+ const serving = await servingPid(layout.agentSocket)
70
+ if (!isLockHeld(layout.daemonLock)) {
71
+ const pidFile = join(layout.run, 'daemon.pid')
72
+ if (serving !== undefined || (await isDaemonAlive(layout.agentSocket))) {
73
+ // Something answers but holds no daemon lock: a daemon from an older release. It can't be identified safely.
74
+ throw new TypeVaultError(
75
+ 'conflict',
76
+ `a typevault daemon from an older release is running here; stop it (its PID is in ${pidFile}) and retry`,
77
+ )
78
+ }
79
+ // No lock and no socket, yet the PID file names a live process: an older daemon still cleaning up, or an
80
+ // unrelated process that reused a stale PID. Neither can be told apart safely, so nothing is signaled or replaced.
81
+ const pid = pidIn(pidFile)
82
+ if (pid !== undefined && isRunning(pid)) {
83
+ throw new TypeVaultError(
84
+ 'conflict',
85
+ `${pidFile} names a running process (pid ${pid}) that holds no daemon lock: if it is an older typevault daemon, wait for it to exit or stop it; if not, delete ${pidFile}`,
86
+ )
87
+ }
88
+ throw new TypeVaultError('not_found', 'no daemon is running')
89
+ }
90
+ // With the lock held but no socket answering, the daemon is already shutting down: another signal would only cut
91
+ // its cleanup short, so this just waits.
92
+ if (serving !== undefined) await tellToStop(layout, serving)
93
+ const deadline = Date.now() + STOP_TIMEOUT_MS
94
+ while (isLockHeld(layout.daemonLock)) {
95
+ if (Date.now() > deadline) {
96
+ throw new TypeVaultError('unavailable', `the typevault daemon did not stop (${layout.daemonLock} is still held)`)
97
+ }
98
+ await Bun.sleep(POLL_MS)
99
+ }
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
+
126
+ function pidIn(pidFile: string): number | undefined {
127
+ if (!existsSync(pidFile)) return undefined
128
+ const pid = Number.parseInt(readFileSync(pidFile, 'utf8'), 10)
129
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined
130
+ }
131
+
132
+ function isRunning(pid: number): boolean {
133
+ try {
134
+ process.kill(pid, 0)
135
+ return true
136
+ } catch (error) {
137
+ if (error instanceof Error && 'code' in error && error.code === 'ESRCH') return false
138
+ throw error
139
+ }
140
+ }
141
+
142
+ /**
143
+ * SIGTERM on Unix. Windows has no catchable signal (process.kill terminates outright, skipping cleanup), so there the
144
+ * daemon is asked over its control socket, which only this host's user reaches (sandboxes get the agent socket).
145
+ */
146
+ async function tellToStop(layout: Layout, pid: number): Promise<void> {
147
+ if (process.platform === 'win32') {
148
+ try {
149
+ await callDaemon(layout.controlSocket, '/v1/shutdown', {}, z.object({ ok: z.literal(true) }), {
150
+ timeoutMs: 1_000,
151
+ })
152
+ } catch (error) {
153
+ // It closed its socket since answering: it is already stopping.
154
+ if (!(error instanceof TypeVaultError)) throw error
155
+ }
156
+ return
157
+ }
158
+ try {
159
+ process.kill(pid, 'SIGTERM')
160
+ } catch (error) {
161
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error
162
+ }
163
+ }
164
+
165
+ const STOP_TIMEOUT_MS = 5_000
166
+
167
+ const isSet = (value: string | undefined): boolean => value !== undefined && value !== ''
168
+
169
+ const vaultArgs = (layout: Layout): readonly string[] =>
170
+ layout.scope === 'local' ? ['--vault', resolve(layout.vault)] : []
171
+
172
+ /**
173
+ * Runs `command` detached as this checkout's daemon and waits until the agent socket answers. Exported for tests,
174
+ * which stand in their own daemon.
175
+ */
176
+ export async function startBackground(
177
+ layout: Layout,
178
+ env: Env,
179
+ command: readonly string[],
180
+ stdin?: string,
181
+ ): Promise<void> {
182
+ ensureDir(layout.run, 0o700)
183
+ // A background daemon has no terminal: its output goes to a log, so a failed start can say why.
184
+ const logPath = join(layout.run, 'daemon.log')
185
+ const logOffset = existsSync(logPath) ? statSync(logPath).size : 0
186
+ const log = openSync(logPath, 'a', 0o600)
187
+ // The child starts in its private run directory, never the project's: Bun reads bunfig.toml (a preload) and .env from
188
+ // its directory, and anyone who can edit a checkout (an agent) could have it read the key off stdin. So it is handed
189
+ // the vault by path. Its private state is where this process resolved it: `env` may lack the HOME this process fell
190
+ // back to.
191
+ // An explicit state or run directory may be relative to this process's directory, which the child doesn't share.
192
+ const childEnv = {
193
+ ...env,
194
+ XDG_CONFIG_HOME: dirname(configDir(env)),
195
+ ...(isSet(env['TYPEVAULT_STATE_DIR']) ? { TYPEVAULT_STATE_DIR: layout.root } : {}),
196
+ ...(isSet(env['TYPEVAULT_RUN_DIR']) ? { TYPEVAULT_RUN_DIR: layout.sockets } : {}),
197
+ }
198
+ const [executable = process.execPath, ...args] = command
199
+ const child = spawn(executable, args, {
15
200
  detached: true,
16
- stdio: 'ignore',
17
- env: { ...env, TYPEVAULT_DIR: layout.root },
201
+ stdio: [stdin === undefined ? 'ignore' : 'pipe', log, log],
202
+ cwd: layout.run,
203
+ env: layout.scope === 'local' ? childEnv : { ...childEnv, TYPEVAULT_DIR: resolve(layout.vault) },
18
204
  })
205
+ closeSync(log)
206
+ if (stdin !== undefined) child.stdin?.end(stdin)
19
207
  child.unref()
20
208
  const deadline = Date.now() + START_TIMEOUT_MS
21
209
  while (Date.now() < deadline) {
22
210
  if (await isDaemonAlive(layout.agentSocket)) return
211
+ // A daemon that dies on startup won't come up later, so its exit ends the wait, unless another start holds the
212
+ // daemon lock: this child lost a race to it, and the winner may still be opening its vault before it serves.
213
+ const exited = child.exitCode !== null || child.signalCode !== null
214
+ if (exited && !isLockHeld(layout.daemonLock)) break
23
215
  await Bun.sleep(POLL_MS)
24
216
  }
25
- throw new TypeVaultError('unavailable', 'the typevault daemon did not start (run `typevault daemon run` to see why)')
217
+ // Two starts racing: the one that loses exits with a conflict while the other's daemon is already serving.
218
+ if (await isDaemonAlive(layout.agentSocket)) return
219
+ throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath, logOffset)}`)
220
+ }
221
+
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')
228
+ .split('\n')
229
+ .map((line) => line.trim())
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})`
26
235
  }