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.
Files changed (72) 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 +7 -7
  7. package/src/access/scoped.ts +100 -44
  8. package/src/access/sealed-access.ts +45 -23
  9. package/src/access/sealed.ts +33 -21
  10. package/src/access/types.ts +25 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +14 -9
  13. package/src/cli/commands/admin.ts +87 -47
  14. package/src/cli/commands/daemon.ts +33 -15
  15. package/src/cli/commands/entries.ts +166 -55
  16. package/src/cli/commands/grant.ts +12 -20
  17. package/src/cli/commands/members.ts +281 -0
  18. package/src/cli/commands/run.ts +61 -24
  19. package/src/cli/context.ts +155 -15
  20. package/src/cli/index.ts +27 -4
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +65 -0
  23. package/src/core/admin.ts +125 -74
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +9 -9
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +6 -0
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +84 -0
  31. package/src/core/identity.ts +130 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/keyring.ts +100 -56
  34. package/src/core/layout.ts +145 -26
  35. package/src/core/lock.ts +128 -16
  36. package/src/core/naming.ts +146 -49
  37. package/src/core/password.ts +111 -0
  38. package/src/core/payload.ts +42 -38
  39. package/src/core/revisions.ts +8 -4
  40. package/src/core/rotate.ts +59 -42
  41. package/src/core/state.ts +88 -48
  42. package/src/core/txn.ts +5 -4
  43. package/src/core/vault.ts +108 -46
  44. package/src/core/worktrees.ts +39 -0
  45. package/src/daemon/admin-routes.ts +33 -21
  46. package/src/daemon/agent-routes.ts +29 -11
  47. package/src/daemon/client.ts +15 -0
  48. package/src/daemon/daemon.ts +210 -32
  49. package/src/daemon/grants.ts +21 -4
  50. package/src/daemon/http.ts +3 -0
  51. package/src/daemon/live-access.ts +4 -4
  52. package/src/daemon/protocol.ts +17 -12
  53. package/src/daemon/requests.ts +17 -22
  54. package/src/daemon/spawn.ts +188 -9
  55. package/src/export/1password.ts +157 -0
  56. package/src/import/1password-live.ts +399 -0
  57. package/src/import/1password.ts +26 -5
  58. package/src/import/bitwarden.ts +3 -3
  59. package/src/import/csv.ts +1 -1
  60. package/src/import/dotenv.ts +2 -2
  61. package/src/import/index.ts +1 -0
  62. package/src/import/keepass.ts +2 -2
  63. package/src/import/lastpass.ts +2 -2
  64. package/src/import/shared.ts +67 -10
  65. package/src/import/typeclaw.ts +2 -2
  66. package/src/import/types.ts +1 -1
  67. package/src/index.ts +58 -0
  68. package/src/owner.ts +156 -0
  69. package/src/prompt/browser.ts +48 -15
  70. package/src/prompt/page.ts +19 -11
  71. package/src/prompt/styles.ts +64 -34
  72. package/src/prompt/types.ts +3 -3
package/src/admin.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { z } from 'zod'
2
+
3
+ import { adminCall, type Env } from './cli/context'
4
+
5
+ export const IssuedSchema = z.object({ token: z.string() })
6
+ export const GrantInfoSchema = z.object({
7
+ id: z.string(),
8
+ label: z.string(),
9
+ tiers: z.array(z.string()),
10
+ only: z.array(z.string()),
11
+ exp: z.string(),
12
+ })
13
+ const RevokedSchema = z.object({ revoked: z.array(z.string()) })
14
+
15
+ export type GrantInfo = z.infer<typeof GrantInfoSchema>
16
+
17
+ export type GrantRequest = {
18
+ readonly tiers: readonly string[]
19
+ /** Names or globs the grant is narrowed to. Empty means everything in `tiers`. */
20
+ readonly only?: readonly string[]
21
+ /** e.g. `30m`, `1h`. Defaults to `1h`. */
22
+ readonly ttl?: string
23
+ /** Who this is for, e.g. `session:abc`. Shows up in the audit trail. */
24
+ readonly label?: string
25
+ /** An offline bundle: no daemon needed to read, no revocation. */
26
+ readonly sealed?: boolean
27
+ }
28
+
29
+ export type AdminOptions = {
30
+ /** The global vault's directory. Defaults to `TYPEVAULT_DIR`; without one the vault is chosen like the CLI's. */
31
+ readonly dir?: string
32
+ /** Use the global vault instead of the project's, like the CLI's `-g`. Defaults to `TYPEVAULT_GLOBAL`. */
33
+ readonly global?: boolean
34
+ /** Which admin socket to use (`admin-<ceiling>.sock`). Defaults to `TYPEVAULT_CEILING`, else `default`. */
35
+ readonly ceiling?: string
36
+ /** The vault's private state (trust pin, audit, run). Defaults to `TYPEVAULT_STATE_DIR`, else this user's config. */
37
+ readonly stateDir?: string
38
+ /** Where the daemon's sockets live, for a `stateDir` too deep for one. Defaults to `TYPEVAULT_RUN_DIR`. */
39
+ readonly runDir?: string
40
+ /** Where the defaults above are read from. Defaults to `process.env`. */
41
+ readonly env?: Env
42
+ }
43
+
44
+ export type AdminClient = {
45
+ /** Issues a grant within this socket's ceiling and returns its token. */
46
+ grant(request: GrantRequest): Promise<string>
47
+ /** The grants this socket may see: all of them on an uncapped socket, its own otherwise. */
48
+ list(): Promise<readonly GrantInfo[]>
49
+ /** Revokes by id or label, along with grants derived from them. Returns the revoked ids. */
50
+ revoke(target: { readonly id: string } | { readonly label: string }): Promise<readonly string[]>
51
+ }
52
+
53
+ /** Grant management over an admin socket, the same calls `typevault grant` makes. Starts the daemon if needed. */
54
+ export function createAdmin(options: AdminOptions = {}): AdminClient {
55
+ const env: Env = {
56
+ ...(options.env ?? process.env),
57
+ ...(options.dir === undefined ? {} : { TYPEVAULT_DIR: options.dir }),
58
+ ...(options.global === undefined ? {} : { TYPEVAULT_GLOBAL: options.global ? '1' : '' }),
59
+ ...(options.ceiling === undefined ? {} : { TYPEVAULT_CEILING: options.ceiling }),
60
+ ...(options.stateDir === undefined ? {} : { TYPEVAULT_STATE_DIR: options.stateDir }),
61
+ ...(options.runDir === undefined ? {} : { TYPEVAULT_RUN_DIR: options.runDir }),
62
+ }
63
+ return {
64
+ grant: async (request) => (await adminCall(env, '/v1/grant', request, IssuedSchema)).token,
65
+ list: () => adminCall(env, '/v1/grants', {}, z.array(GrantInfoSchema)),
66
+ revoke: async (target) => (await adminCall(env, '/v1/revoke', target, RevokedSchema)).revoked,
67
+ }
68
+ }
package/src/audit/log.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { appendFileSync, closeSync, existsSync, fsyncSync, openSync, readFileSync, readSync, statSync } from 'node:fs'
2
+ import { dirname, relative } from 'node:path'
2
3
 
3
4
  import { z } from 'zod'
4
5
 
5
6
  import { sha256Hex } from '../core/crypto'
6
7
  import { canonicalJson, type Json, utf8 } from '../core/encoding'
7
- import { ensureDir } from '../core/fsx'
8
+ import { assertNoSymlinks, ensureDir } from '../core/fsx'
8
9
  import type { Layout } from '../core/layout'
9
10
  import { withLock } from '../core/lock'
10
11
 
@@ -16,7 +17,7 @@ export type AuditEvent = {
16
17
  readonly mode: AuditMode
17
18
  readonly grant?: string
18
19
  readonly label?: string
19
- readonly groups?: readonly string[]
20
+ readonly tiers?: readonly string[]
20
21
  readonly entries?: readonly string[]
21
22
  readonly reason?: string
22
23
  }
@@ -73,7 +74,9 @@ export function readAudit(layout: Layout): readonly AuditRecord[] {
73
74
  }
74
75
 
75
76
  function writeAnchor(layout: Layout, last: AuditRecord): void {
76
- ensureDir(layout.vault)
77
+ // The anchors live in the committed vault: a pulled symlink there must not redirect this append.
78
+ assertNoSymlinks(dirname(layout.vault), relative(dirname(layout.vault), layout.anchorsFile))
79
+ ensureDir(dirname(layout.anchorsFile))
77
80
  appendLine(layout.anchorsFile, JSON.stringify({ seq: last.seq, hash: last.hash, at: last.at }))
78
81
  }
79
82
 
@@ -116,12 +119,14 @@ export function verifyAudit(layout: Layout): AuditVerdict {
116
119
  heads.set(record.seq, hash)
117
120
  prev = hash
118
121
  }
119
- const anchors = existsSync(layout.anchorsFile)
120
- ? readFileSync(layout.anchorsFile, 'utf8')
121
- .split('\n')
122
- .filter((line) => line !== '')
123
- .map((line) => AnchorSchema.parse(JSON.parse(line)))
124
- : []
122
+ const anchors = [layout.legacyAnchorsFile, layout.anchorsFile].flatMap((file) =>
123
+ existsSync(file)
124
+ ? readFileSync(file, 'utf8')
125
+ .split('\n')
126
+ .filter((line) => line !== '')
127
+ .map((line) => AnchorSchema.parse(JSON.parse(line)))
128
+ : [],
129
+ )
125
130
  const broken = anchors.find((anchor) => heads.get(anchor.seq) !== anchor.hash)
126
131
  if (broken !== undefined)
127
132
  return { ok: false, reason: `local log no longer matches the anchor at record ${broken.seq}` }
@@ -1,42 +1,71 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
1
4
  import { defineCommand } from 'citty'
2
5
 
3
6
  import { verifyAudit } from '../../audit/log'
4
- import { adoptCertWrites } from '../../core/adopt'
7
+ import { Admin } from '../../core/admin'
8
+ import { adoptCertWrites, type ExpiredPin } from '../../core/adopt'
5
9
  import { doctor as runDoctor } from '../../core/doctor'
6
- import { initVault } from '../../core/init'
7
- import { layoutFrom, openAdmin, openDirect } from '../context'
10
+ import { TypeVaultError } from '../../core/errors'
11
+ import { founderOf, initGlobalVault, initLocalVault } from '../../core/init'
12
+ import { globalLayout, type Layout, LOCAL_VAULT_DIR, localLayout } from '../../core/layout'
13
+ import { parseEntryName } from '../../core/naming'
14
+ import { Vault } from '../../core/vault'
15
+ import { stopDaemon } from '../../daemon/spawn'
16
+ import { openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
8
17
  import { csv, note, print, table } from '../output'
18
+ import { ensureIdentity, identityArgs } from './members'
9
19
 
10
20
  export const init = defineCommand({
11
- meta: { name: 'init', description: 'Create a vault and its operator key' },
12
- async run() {
13
- const layout = layoutFrom(process.env)
14
- await initVault(layout.root)
15
- print(`vault created at ${layout.root}`)
21
+ meta: { name: 'init', description: 'Create a vault you own (and your identity, the first time)' },
22
+ args: identityArgs,
23
+ async run({ args }) {
24
+ const env = process.env
25
+ const founder = founderOf(await ensureIdentity(env, args))
26
+ const global = wantsGlobal(env)
27
+ const dir = join(process.cwd(), LOCAL_VAULT_DIR)
28
+ await stopStaleDaemon(global ? globalLayout(env) : localLayout(dir, env))
29
+ const { layout, owner } = global ? await initGlobalVault(founder, env) : await initLocalVault(dir, founder, env)
30
+ await new Admin(await Vault.open(layout, [owner], env)).addTier(STARTER_TIER)
31
+ print(`vault created at ${layout.vault} with tier "${STARTER_TIER}", owned by ${founder.name}`)
16
32
  note(
17
- `operator key: ${layout.operatorKey}\nBack it up offline: it is the only recovery path. Only vault/ is safe to commit.`,
33
+ global
34
+ ? 'It holds no key in the clear: safe to sync with git.'
35
+ : `Commit ${LOCAL_VAULT_DIR}/: it holds no key in the clear.`,
18
36
  )
19
- note('next: typevault group add <name>, then typevault set <name> --type ... --group <name> --stdin')
37
+ note('next: typevault set <name> --stdin (more tiers: typevault tier add <name>)')
20
38
  },
21
39
  })
22
40
 
41
+ /** A daemon still running here served a vault that no longer exists; a new vault can't start beside it. */
42
+ async function stopStaleDaemon(layout: Layout): Promise<void> {
43
+ if (existsSync(layout.ownerFile)) return
44
+ await stopDaemon(layout).catch((error: unknown) => {
45
+ if (!(error instanceof TypeVaultError && error.code === 'not_found')) throw error
46
+ })
47
+ }
48
+
49
+ /** Created by `init` so `set` and `grant` work before any tier design; as the only tier, `set` picks it. */
50
+ const STARTER_TIER = 'default'
51
+
23
52
  const named = { name: { type: 'positional', required: true } } as const
24
53
  const pair = {
25
- group: { type: 'positional', required: true },
54
+ tier: { type: 'positional', required: true },
26
55
  included: { type: 'positional', required: true },
27
56
  } as const
28
57
 
29
- export const group = defineCommand({
30
- meta: { name: 'group', description: 'Manage groups (operator)' },
58
+ export const tier = defineCommand({
59
+ meta: { name: 'tier', description: 'Manage tiers (owner)' },
31
60
  subCommands: {
32
61
  ls: defineCommand({
33
62
  meta: { name: 'ls' },
34
63
  async run() {
35
- const groups = Object.entries((await openDirect(process.env)).state.groups)
64
+ const tiers = Object.entries((await openPublic(process.env)).state.tiers)
36
65
  print(
37
66
  table([
38
- ['GROUP', 'GEN', 'INCLUDES'],
39
- ...groups.map(([name, g]) => [name, String(g.gen), g.includes.join(', ')]),
67
+ ['TIER', 'GEN', 'INCLUDES'],
68
+ ...tiers.map(([name, g]) => [name, String(g.gen), g.includes.join(', ')]),
40
69
  ]),
41
70
  )
42
71
  },
@@ -44,65 +73,70 @@ export const group = defineCommand({
44
73
  add: defineCommand({
45
74
  meta: { name: 'add' },
46
75
  args: named,
47
- run: async ({ args }) => (await openAdmin(process.env)).addGroup(args.name),
76
+ run: async ({ args }) => (await openAdmin(process.env)).addTier(args.name),
48
77
  }),
49
78
  rm: defineCommand({
50
79
  meta: { name: 'rm' },
51
80
  args: named,
52
- run: async ({ args }) => (await openAdmin(process.env)).removeGroup(args.name),
81
+ run: async ({ args }) => (await openAdmin(process.env)).removeTier(args.name),
53
82
  }),
54
83
  include: defineCommand({
55
- meta: { name: 'include', description: '<group> reaches everything <included> reaches' },
84
+ meta: { name: 'include', description: '<tier> reaches everything <included> reaches' },
56
85
  args: pair,
57
- run: async ({ args }) => (await openAdmin(process.env)).include(args.group, args.included),
86
+ run: async ({ args }) => (await openAdmin(process.env)).include(args.tier, args.included),
58
87
  }),
59
88
  exclude: defineCommand({
60
- meta: { name: 'exclude', description: 'Drop an include and rotate the included group' },
89
+ meta: { name: 'exclude', description: 'Drop an include and rotate the included tier' },
61
90
  args: pair,
62
91
  async run({ args }) {
63
- printRotation(args.included, await (await openAdmin(process.env)).exclude(args.group, args.included))
92
+ printRotation(args.included, await (await openAdmin(process.env)).exclude(args.tier, args.included))
64
93
  },
65
94
  }),
66
95
  },
67
96
  })
68
97
 
69
- function printRotation(groupName: string, affected: readonly string[]): void {
70
- print(`rotated ${groupName}`)
98
+ function parseExpiredPin(input: string): ExpiredPin {
99
+ const at = input.lastIndexOf('@')
100
+ const digest = at === -1 ? '' : input.slice(at + 1)
101
+ if (!/^[0-9a-f]{16}$/.test(digest))
102
+ throw new TypeVaultError('invalid', `--adopt-expired expects <name>@<digest> as doctor lists it, got "${input}"`)
103
+ return { name: parseEntryName(input.slice(0, at)), digest }
104
+ }
105
+
106
+ function printRotation(tierName: string, affected: readonly string[]): void {
107
+ print(`rotated ${tierName}`)
71
108
  if (affected.length === 0) return
72
109
  note('Git history keeps the old ciphertext. Rotate these secrets at their source, then re-set them:')
73
110
  for (const name of affected) note(` ${name}`)
74
111
  }
75
112
 
76
113
  export const key = defineCommand({
77
- meta: { name: 'key', description: 'Export or rotate group keys (operator)' },
114
+ meta: { name: 'key', description: 'Rotate tier keys (owner)' },
78
115
  subCommands: {
79
- export: defineCommand({
80
- meta: { name: 'export', description: 'Print a group key for a launcher, CI secret or daemon (TYPEVAULT_KEY)' },
81
- args: named,
82
- run: async ({ args }) => print(await (await openAdmin(process.env)).exportKey(args.name)),
83
- }),
84
116
  rotate: defineCommand({
85
117
  meta: { name: 'rotate', description: 'New key generation; flags every secret the old key reached' },
86
118
  args: named,
87
- run: async ({ args }) => printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name)),
119
+ async run({ args }) {
120
+ printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name))
121
+ },
88
122
  }),
89
123
  },
90
124
  })
91
125
 
92
126
  export const ceiling = defineCommand({
93
- meta: { name: 'ceiling', description: 'The most an admin socket may grant (operator)' },
127
+ meta: { name: 'ceiling', description: 'The most an admin socket may grant (owner)' },
94
128
  subCommands: {
95
129
  ls: defineCommand({
96
130
  meta: { name: 'ls' },
97
131
  async run() {
98
- const ceilings = Object.entries((await openDirect(process.env)).state.ceilings)
99
- print(table([['SOCKET', 'GROUP'], ...ceilings]))
132
+ const ceilings = Object.entries((await openPublic(process.env)).state.ceilings)
133
+ print(table([['SOCKET', 'TIER'], ...ceilings]))
100
134
  },
101
135
  }),
102
136
  set: defineCommand({
103
137
  meta: { name: 'set' },
104
- args: { name: { type: 'positional', required: true }, group: { type: 'positional', required: true } },
105
- run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.group),
138
+ args: { name: { type: 'positional', required: true }, tier: { type: 'positional', required: true } },
139
+ run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.tier),
106
140
  }),
107
141
  rm: defineCommand({
108
142
  meta: { name: 'rm' },
@@ -113,14 +147,14 @@ export const ceiling = defineCommand({
113
147
  })
114
148
 
115
149
  export const signer = defineCommand({
116
- meta: { name: 'signer', description: 'Extra keys allowed to sign entries (operator)' },
150
+ meta: { name: 'signer', description: 'Extra keys allowed to sign entries (owner)' },
117
151
  subCommands: {
118
152
  ls: defineCommand({
119
153
  meta: { name: 'ls' },
120
154
  async run() {
121
- const signers = Object.entries((await openDirect(process.env)).state.signers)
155
+ const signers = Object.entries((await openPublic(process.env)).state.signers)
122
156
  print(
123
- table([['ID', 'GROUPS', 'PUBLIC KEY'], ...signers.map(([id, s]) => [id, s.groups.join(','), s.signPublic])]),
157
+ table([['ID', 'TIERS', 'PUBLIC KEY'], ...signers.map(([id, s]) => [id, s.tiers.join(','), s.signPublic])]),
124
158
  )
125
159
  },
126
160
  }),
@@ -129,9 +163,9 @@ export const signer = defineCommand({
129
163
  args: {
130
164
  id: { type: 'positional', required: true },
131
165
  publicKey: { type: 'positional', required: true, description: 'Base64 Ed25519 public key' },
132
- groups: { type: 'string', required: true, description: 'Comma-separated groups, or *' },
166
+ tiers: { type: 'string', required: true, description: 'Comma-separated tiers, or *' },
133
167
  },
134
- run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.groups)),
168
+ run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.tiers)),
135
169
  }),
136
170
  rm: defineCommand({
137
171
  meta: { name: 'rm' },
@@ -146,22 +180,28 @@ export const doctor = defineCommand({
146
180
  args: {
147
181
  fix: { type: 'boolean' },
148
182
  'adopt-expired': {
149
- type: 'boolean',
150
- description: 'Also keep sealed-grant writes whose certificate expired before adoption',
183
+ type: 'string',
184
+ description:
185
+ 'Comma-separated <name>@<digest> of sealed-grant writes to keep although their certificate expired before adoption, as `doctor --fix` lists them (nothing proves when they were written)',
151
186
  },
152
187
  },
153
188
  async run({ args }) {
154
189
  const vault = await openDirect(process.env)
155
- if (args.fix === true)
156
- for (const name of await adoptCertWrites(vault, { expired: args['adopt-expired'] === true }))
157
- print(`adopted sealed write: ${name}`)
190
+ if (args.fix === true) {
191
+ const adoption = await adoptCertWrites(vault, { expired: csv(args['adopt-expired'] ?? '').map(parseExpiredPin) })
192
+ for (const name of adoption.adopted) print(`adopted sealed write: ${name}`)
193
+ for (const write of adoption.expired)
194
+ print(
195
+ `expired sealed write: ${write.name} rev ${write.rev} at ${write.at} (its certificate expired before adoption; keep this exact write with \`--adopt-expired ${write.name}@${write.digest}\` only if you know it was written in time)`,
196
+ )
197
+ }
158
198
  const report = await runDoctor(vault, args.fix === true)
159
199
  for (const problem of report.problems) print(`problem: ${problem.file}: ${problem.reason}`)
160
200
  for (const file of report.mergesResolved) print(`merged: ${file}`)
161
201
  for (const dup of report.duplicatesRemoved) print(`${args.fix === true ? 'removed' : 'duplicate'}: ${dup}`)
162
202
  for (const dup of report.duplicatesKept)
163
203
  print(
164
- `same name in several groups: ${dup} (if the groups are unrelated, reads of it fail: keep one with \`typevault rm <name> --group <g>\`)`,
204
+ `same name in several tiers: ${dup} (if the tiers are unrelated, reads of it fail: keep one with \`typevault rm <name> --tier <g>\`)`,
165
205
  )
166
206
  for (const name of report.needsRotation) print(`needs rotation: ${name}`)
167
207
  const audit = verifyAudit(vault.layout)
@@ -1,15 +1,15 @@
1
- import { existsSync, readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
3
-
4
1
  import { defineCommand } from 'citty'
5
2
  import { z } from 'zod'
6
3
 
7
- import { TypeVaultError } from '../../core/errors'
4
+ import { machineKeys } from '../../access/keys'
5
+ import { parseTtl } from '../../access/scope'
6
+ import { decodeSecretKey } from '../../core/crypto'
7
+ import { localLayout } from '../../core/layout'
8
8
  import { isDaemonAlive } from '../../daemon/client'
9
9
  import { startDaemon } from '../../daemon/daemon'
10
- import { ensureDaemon } from '../../daemon/spawn'
11
- import { adminCall, layoutFrom } from '../context'
12
- import { note, print } from '../output'
10
+ import { ensureDaemon, stopDaemon } from '../../daemon/spawn'
11
+ import { adminCall, DEFAULT_SESSION_MS, layoutFrom } from '../context'
12
+ import { note, print, readStdin } from '../output'
13
13
 
14
14
  const port = (value: string | undefined): number | undefined =>
15
15
  value === undefined || value === '' ? undefined : z.coerce.number().int().parse(value)
@@ -19,23 +19,45 @@ export const daemon = defineCommand({
19
19
  subCommands: {
20
20
  run: defineCommand({
21
21
  meta: { name: 'run', description: 'Run in the foreground' },
22
- async run() {
22
+ args: {
23
+ 'key-stdin': { type: 'boolean', description: 'Read an unlocked member key from stdin (used by unlock)' },
24
+ ttl: { type: 'string', description: 'Stop after this long, e.g. 8h (used by unlock)' },
25
+ vault: {
26
+ type: 'string',
27
+ description: 'The project vault to serve, instead of the one found here (used by unlock)',
28
+ },
29
+ 'source-lock': {
30
+ type: 'string',
31
+ description: 'Serve only while the daemon holding this lock runs (used to share a session with a worktree)',
32
+ },
33
+ },
34
+ async run({ args }) {
23
35
  const env = process.env
24
36
  const promptPort = port(env['TYPEVAULT_PROMPT_PORT'])
25
37
  const publicUrl = env['TYPEVAULT_PUBLIC_URL']
38
+ const fromStdin = args['key-stdin'] === true
39
+ const ttlMs = args.ttl === undefined ? undefined : parseTtl(args.ttl)
40
+ const sourceLock = args['source-lock']
26
41
  const running = await startDaemon({
27
- root: layoutFrom(env).root,
42
+ layout: args.vault === undefined ? layoutFrom(env) : localLayout(args.vault, env),
28
43
  env,
44
+ keys: fromStdin ? [decodeSecretKey(await readStdin())] : machineKeys(env),
29
45
  prompt: {
30
46
  ...(promptPort === undefined ? {} : { port: promptPort }),
31
47
  ...(publicUrl === undefined ? {} : { publicUrl }),
32
48
  },
49
+ ...(fromStdin
50
+ ? { session: { ttlMs: ttlMs ?? DEFAULT_SESSION_MS, ...(sourceLock === undefined ? {} : { sourceLock }) } }
51
+ : {}),
33
52
  })
34
- note(`typevault daemon ready (admin sockets: ${running.ceilings.map((c) => c.name).join(', ')})`)
53
+ note(`typevault daemon ready (admin sockets: ${running.ceilings.map((c) => c.name).join(', ') || 'none'})`)
35
54
  const { promise, resolve } = Promise.withResolvers<void>()
36
55
  process.once('SIGINT', resolve)
37
56
  process.once('SIGTERM', resolve)
57
+ void running.stopRequested.then(resolve)
58
+ const expiry = ttlMs === undefined ? undefined : setTimeout(resolve, ttlMs)
38
59
  await promise
60
+ clearTimeout(expiry)
39
61
  await running.stop()
40
62
  },
41
63
  }),
@@ -45,11 +67,7 @@ export const daemon = defineCommand({
45
67
  }),
46
68
  stop: defineCommand({
47
69
  meta: { name: 'stop' },
48
- async run() {
49
- const pidFile = join(layoutFrom(process.env).run, 'daemon.pid')
50
- if (!existsSync(pidFile)) throw new TypeVaultError('not_found', 'no daemon is running')
51
- process.kill(z.coerce.number().int().parse(readFileSync(pidFile, 'utf8')), 'SIGTERM')
52
- },
70
+ run: async () => stopDaemon(layoutFrom(process.env)),
53
71
  }),
54
72
  status: defineCommand({
55
73
  meta: { name: 'status' },