typevault 0.4.0 → 0.6.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
@@ -16,7 +16,8 @@
16
16
  },
17
17
  "files": [
18
18
  "src",
19
- "!**/*.test.ts"
19
+ "!**/*.test.ts",
20
+ "!**/*.harness.ts"
20
21
  ],
21
22
  "type": "module",
22
23
  "exports": {
@@ -13,7 +13,7 @@ const SummaryShape = {
13
13
  needsRotation: z.boolean(),
14
14
  }
15
15
 
16
- export const EntrySummarySchema = z.object(SummaryShape)
16
+ export const EntrySummarySchema = z.object({ ...SummaryShape, fieldNames: z.array(z.string()) })
17
17
  export const EntryValueSchema = z.object({
18
18
  ...SummaryShape,
19
19
  id: z.string(),
@@ -106,6 +106,7 @@ export class SealedAccess implements Access {
106
106
  tags: payload.tags,
107
107
  rotated: payload.rotated,
108
108
  needsRotation: false,
109
+ fieldNames: Object.keys(payload.fields),
109
110
  }
110
111
  }
111
112
 
@@ -11,9 +11,11 @@ export type EntrySummary = {
11
11
  readonly tags: readonly string[]
12
12
  readonly rotated: string
13
13
  readonly needsRotation: boolean
14
+ /** Names only: listing never hands out values. */
15
+ readonly fieldNames: readonly string[]
14
16
  }
15
17
 
16
- export type EntryValue = EntrySummary & {
18
+ export type EntryValue = Omit<EntrySummary, 'fieldNames'> & {
17
19
  readonly id: string
18
20
  readonly created: string
19
21
  readonly fields: Readonly<Record<string, Field>>
@@ -93,6 +95,7 @@ export const toSummary = (value: EntryValue): EntrySummary => ({
93
95
  tags: value.tags,
94
96
  rotated: value.rotated,
95
97
  needsRotation: value.needsRotation,
98
+ fieldNames: Object.keys(value.fields),
96
99
  })
97
100
 
98
101
  /** Whether `signer` is at least as privileged as a reader holding `ownTiers`. */
@@ -8,7 +8,7 @@ import { TypeVaultError } from '../../core/errors'
8
8
  import { localLayout } from '../../core/layout'
9
9
  import { isDaemonAlive } from '../../daemon/client'
10
10
  import { startDaemon } from '../../daemon/daemon'
11
- import { ensureDaemon, stopDaemon } from '../../daemon/spawn'
11
+ import { ensureDaemon, restartDaemon, stopDaemon } from '../../daemon/spawn'
12
12
  import { adminCall, DEFAULT_SESSION_MS, layoutFrom } from '../context'
13
13
  import { note, print, readStdin } from '../output'
14
14
 
@@ -76,6 +76,10 @@ export const daemon = defineCommand({
76
76
  meta: { name: 'stop' },
77
77
  run: async () => stopDaemon(layoutFrom(process.env)),
78
78
  }),
79
+ restart: defineCommand({
80
+ meta: { name: 'restart' },
81
+ run: async () => restartDaemon(layoutFrom(process.env), process.env),
82
+ }),
79
83
  status: defineCommand({
80
84
  meta: { name: 'status' },
81
85
  async run() {
@@ -20,8 +20,9 @@ import {
20
20
  } from '../../core/naming'
21
21
  import { FieldSchema } from '../../core/payload'
22
22
  import { parseTotpSeed, totpCode, totpRemainingSeconds } from '../../otp/totp'
23
- import { accessOf, resolveAccess } from '../context'
23
+ import { accessOf, getEntry, resolveAccess } from '../context'
24
24
  import { csv, note, print, readStdin, repeated, table } from '../output'
25
+ import { promptHidden } from '../password'
25
26
  import { openBrowser, promptFields } from '../web-prompt'
26
27
 
27
28
  /** Runs after the listing it annotates. */
@@ -44,10 +45,14 @@ export const ls = defineCommand({
44
45
  e.tier,
45
46
  `r${e.rev}`,
46
47
  e.rotated.slice(0, 10),
48
+ e.fieldNames.join(','),
47
49
  e.needsRotation ? 'needs-rotation' : '',
48
50
  ])
49
51
  print(
50
- table([['NAME', 'TIER', 'REV', 'ROTATED', ''], ...rows.sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? ''))]),
52
+ table([
53
+ ['NAME', 'TIER', 'REV', 'ROTATED', 'FIELDS', ''],
54
+ ...rows.sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? '')),
55
+ ]),
51
56
  )
52
57
  },
53
58
  })
@@ -65,7 +70,7 @@ export const get = defineCommand({
65
70
  },
66
71
  async run({ args }) {
67
72
  const ref = parseEntryRef(args.ref)
68
- const value = await (await accessOf(process.env)).get(ref.name, args.reason)
73
+ const value = await getEntry(await accessOf(process.env), ref.name, args.reason)
69
74
  if (args.json) {
70
75
  const fields = Object.fromEntries(
71
76
  Object.entries(value.fields).map(([field, secret]) => [
@@ -127,7 +132,7 @@ export const set = defineCommand({
127
132
  meta: {
128
133
  name: 'set',
129
134
  description:
130
- 'Create or update an entry. Pipe the secret on stdin with --stdin, or type it in a browser with --web.',
135
+ 'Create or update an entry. Pipe the secret on stdin with --stdin, type it in a browser with --web, or in this terminal with --prompt.',
131
136
  },
132
137
  args: {
133
138
  name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
@@ -139,6 +144,7 @@ export const set = defineCommand({
139
144
  },
140
145
  field: { type: 'string', description: 'k=v, repeatable (writes text fields; use stdin for secrets)' },
141
146
  stdin: { type: 'boolean', description: 'Read the main secret field from stdin' },
147
+ prompt: { type: 'boolean', description: 'Type the main secret field in this terminal, hidden' },
142
148
  web: {
143
149
  type: 'boolean',
144
150
  description: 'Type the fields in a local one-time browser page (default for a new entry from a terminal)',
@@ -162,9 +168,18 @@ export const set = defineCommand({
162
168
  const given = parseFields(repeated(rawArgs, '--field'), { ...known, ...suggested })
163
169
  const tier = args.tier ?? existing?.tier ?? process.env['TYPEVAULT_TIER']
164
170
  const target = preset?.input ?? defaultFieldOf(previous) ?? '$default'
171
+ if (args.prompt) checkPrompt(args, target, suggested[target] ?? previous[target]?.type)
165
172
  const stdin = args.stdin || args['stdin-json'] ? await readStdin() : undefined
166
173
  if (args.stdin && stdin === '') throw new TypeVaultError('invalid', '--stdin did not contain a value')
167
- const fromStdin = args['stdin-json'] ? parseFieldsJson(stdin ?? '') : args.stdin ? { [target]: stdin ?? '' } : {}
174
+ const prompted = args.prompt ? await promptHidden(`Secret for ${name}#${target}: `) : undefined
175
+ if (prompted === '') throw new TypeVaultError('invalid', '--prompt did not get a value')
176
+ const fromStdin = args['stdin-json']
177
+ ? parseFieldsJson(stdin ?? '')
178
+ : args.stdin
179
+ ? { [target]: stdin ?? '' }
180
+ : prompted !== undefined
181
+ ? { [target]: prompted }
182
+ : {}
168
183
  const typed: Record<string, Field> = {}
169
184
  for (const [field, value] of Object.entries(fromStdin)) {
170
185
  if (typeof value !== 'string') {
@@ -194,7 +209,8 @@ export const set = defineCommand({
194
209
  throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
195
210
  }
196
211
  }
197
- const web = args.web ?? (existing === undefined && !args.stdin && !args['stdin-json'] && process.stdin.isTTY)
212
+ const web =
213
+ args.web ?? (existing === undefined && !args.stdin && !args['stdin-json'] && !args.prompt && process.stdin.isTTY)
198
214
  const fromWeb = web
199
215
  ? await promptFields(
200
216
  { name, preset: args.preset === undefined ? undefined : parsePreset(args.preset), tier },
@@ -230,6 +246,27 @@ export const set = defineCommand({
230
246
  },
231
247
  })
232
248
 
249
+ function checkPrompt(
250
+ args: {
251
+ readonly stdin?: boolean | undefined
252
+ readonly 'stdin-json'?: boolean | undefined
253
+ readonly web?: boolean | undefined
254
+ },
255
+ target: string,
256
+ type: FieldType | undefined,
257
+ ): void {
258
+ if (args.stdin || args['stdin-json'] || args.web)
259
+ throw new TypeVaultError('invalid', '--prompt cannot be combined with --stdin, --stdin-json or --web')
260
+ // Enter ends the prompt, so a pasted multi-line key would be cut at its first line.
261
+ if (type === 'oauth' || target === PRESETS.ssh.input)
262
+ throw new TypeVaultError(
263
+ 'invalid',
264
+ `pass ${type === 'oauth' ? 'OAuth JSON' : 'an SSH key'} with --stdin, not --prompt`,
265
+ )
266
+ if (!process.stdin.isTTY)
267
+ throw new TypeVaultError('invalid', '--prompt needs a terminal; pipe the secret with --stdin')
268
+ }
269
+
233
270
  function showPrompt(url: string, code: string): void {
234
271
  note(`Enter the secret at ${url}\nMatch code: ${code} (the page shows the same code)`)
235
272
  if (!openBrowser(url)) note('could not open a browser; open the link yourself')
@@ -263,7 +300,7 @@ export const otp = defineCommand({
263
300
  args: { name: { type: 'positional', description: ENTRY_REF_SYNTAX, required: true }, reason: { type: 'string' } },
264
301
  async run({ args }) {
265
302
  const ref = parseEntryRef(args.name)
266
- const value = await (await accessOf(process.env)).get(ref.name, args.reason)
303
+ const value = await getEntry(await accessOf(process.env), ref.name, args.reason)
267
304
  const fallback = defaultFieldOf(value.fields)
268
305
  const totps = Object.values(value.fields).filter((candidate) => candidate.type === 'totp')
269
306
  const field =
@@ -17,6 +17,7 @@ import {
17
17
  readIdentity,
18
18
  sealedCopyPath,
19
19
  sealMemberKey,
20
+ sealMemberKeyForTouchId,
20
21
  writeIdentity,
21
22
  } from '../../core/identity'
22
23
  import { type Layout, localLayout, vaultIdOf } from '../../core/layout'
@@ -286,6 +287,36 @@ export const lock = defineCommand({
286
287
  },
287
288
  })
288
289
 
290
+ export const touchId = defineCommand({
291
+ meta: { name: 'touch-id', description: 'Unlock with Touch ID on this Mac instead of typing your password' },
292
+ subCommands: {
293
+ enable: defineCommand({
294
+ meta: { name: 'enable', description: 'Turn on Touch ID unlock: asks for your password, then a touch' },
295
+ async run() {
296
+ const env = process.env
297
+ const current = readIdentity(env)
298
+ if (current?.kind !== 'human') throw new TypeVaultError('invalid', 'only a human identity has a password')
299
+ if (process.platform !== 'darwin') throw new TypeVaultError('unavailable', 'Touch ID unlock needs macOS')
300
+ const password = await passwords().ask(`Password for ${current.name}: `)
301
+ const key = await openMemberKey(current.sealedKey, password, current.secretKey)
302
+ writeIdentity(env, { ...current, touchId: await sealMemberKeyForTouchId(env, key) })
303
+ print('Touch ID unlock is on for this Mac; your password still works')
304
+ },
305
+ }),
306
+ disable: defineCommand({
307
+ meta: { name: 'disable', description: 'Turn off Touch ID unlock: back to your password' },
308
+ run() {
309
+ const env = process.env
310
+ const current = readIdentity(env)
311
+ if (current?.kind !== 'human' || current.touchId === undefined) return print('Touch ID unlock is already off')
312
+ const { touchId: _, ...rest } = current
313
+ writeIdentity(env, rest)
314
+ print('Touch ID unlock is off')
315
+ },
316
+ }),
317
+ },
318
+ })
319
+
289
320
  export const passwd = defineCommand({
290
321
  meta: { name: 'passwd', description: 'Change your password (your key and every vault stay the same)' },
291
322
  async run() {
@@ -8,7 +8,7 @@ import { TypeVaultError } from '../../core/errors'
8
8
  import { ENTRY_NAME_SYNTAX, matchesOnly } from '../../core/naming'
9
9
  import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
10
10
  import { createRedactor, type Redactor, scrubFile } from '../../redact'
11
- import { resolveAccess } from '../context'
11
+ import { getEntry, inGlobalVault, resolveAccess } from '../context'
12
12
  import { csv, note, print, readStdin, repeated } from '../output'
13
13
 
14
14
  async function pump(
@@ -48,11 +48,13 @@ export const run = defineCommand({
48
48
  const values = await access.values(only, args.reason)
49
49
  const unmatched = only.filter((pattern) => !values.some((value) => matchesOnly(value.name, [pattern])))
50
50
  if (unmatched.length > 0) note(`warning: --only matched no entries: ${unmatched.join(', ')}`)
51
+ const inGlobal = await inGlobalVault(process.env, explicitNames(unmatched))
52
+ if (inGlobal.length > 0) note(`the global vault has ${inGlobal.join(', ')}: rerun with -g`)
51
53
  const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
52
54
  const env = envFor(values, new Date(), policy)
53
55
  // The child gets its secrets, never the key or grant that opens the vault.
54
56
  const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('TYPEVAULT_')))
55
- const refs = await resolveEnvRefs(inherited, (name) => access.get(name, args.reason), new Date())
57
+ const refs = await resolveEnvRefs(inherited, (name) => getEntry(access, name, args.reason), new Date())
56
58
  const referenced = new Set(refs.values.map((value) => value.name))
57
59
  const skipped = values
58
60
  .filter((value) => !envEligible(value, policy) && !referenced.has(value.name))
@@ -6,13 +6,20 @@ import { machineKeys } from '../access/keys'
6
6
  import { ScopedVault } from '../access/scoped'
7
7
  import { readSealedGrant } from '../access/sealed'
8
8
  import { SealedAccess } from '../access/sealed-access'
9
- import type { Access } from '../access/types'
9
+ import type { Access, EntryValue } from '../access/types'
10
10
  import { Admin } from '../core/admin'
11
11
  import type { SecretKey } from '../core/crypto'
12
12
  import { TypeVaultError } from '../core/errors'
13
13
  import { atomicWrite } from '../core/fsx'
14
- import { type Identity, readIdentity, sealedCopyPath, unlockIdentity } from '../core/identity'
14
+ import {
15
+ type Identity,
16
+ readIdentity,
17
+ sealedCopyPath,
18
+ unlockIdentity,
19
+ unlockIdentityWithTouchId,
20
+ } from '../core/identity'
15
21
  import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/layout'
22
+ import type { EntryName } from '../core/naming'
16
23
  import { loadState } from '../core/state'
17
24
  import { Vault } from '../core/vault'
18
25
  import { worktreeVaults } from '../core/worktrees'
@@ -61,13 +68,28 @@ export async function openDirect(env: Env): Promise<Vault> {
61
68
  if (machine.length === 0 && identity === undefined) {
62
69
  throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
63
70
  }
64
- const keys = machine.length > 0 ? machine : [await unlockHuman(identity, passwords())]
71
+ const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords())]
65
72
  return Vault.open(layout, keys, env)
66
73
  }
67
74
 
68
- async function unlockHuman(identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
75
+ /**
76
+ * A person's member key: through Touch ID when they turned it on and are at this Mac's terminal, else (or when Touch
77
+ * ID fails) their password. Without a terminal it stays the password's error, so an agent can't raise the dialog.
78
+ */
79
+ export async function unlockHuman(env: Env, identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
69
80
  if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
70
81
  if (identity.kind === 'machine') return unlockIdentity(identity)
82
+ if (identity.touchId !== undefined && process.platform === 'darwin' && process.stdin.isTTY && !passwordsFromStdin()) {
83
+ try {
84
+ return await unlockIdentityWithTouchId(env, identity, identity.touchId)
85
+ } catch (error) {
86
+ if (!(error instanceof TypeVaultError)) throw error
87
+ note(`${error.message}; asking for your password instead`)
88
+ if (error.message !== 'Touch ID was cancelled') {
89
+ note('if your fingerprints changed, run `typevault touch-id enable` again')
90
+ }
91
+ }
92
+ }
71
93
  return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
72
94
  }
73
95
 
@@ -79,7 +101,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
79
101
  const layout = layoutFrom(env)
80
102
  if (await hasSession(layout)) return false
81
103
  const identity = readIdentity(env)
82
- const key = await unlockHuman(identity, passwords)
104
+ const key = await unlockHuman(env, identity, passwords)
83
105
  const vault = await Vault.open(layout, [key], env)
84
106
  if (vault.member === undefined) {
85
107
  throw new TypeVaultError(
@@ -200,6 +222,48 @@ function checkOwnerPin(layout: Layout, env: Env): void {
200
222
  if (isSet(env['TYPEVAULT_OWNER'])) loadState(layout, env)
201
223
  }
202
224
 
225
+ /**
226
+ * Which of `names` the global vault holds, when the project vault was asked. It asks only an already unlocked global
227
+ * session: never a password, a daemon start or a trust pin, and listing is not audited. Anything else answers none,
228
+ * so a miss points at `-g` only when the global vault really has the name.
229
+ */
230
+ export async function inGlobalVault(env: Env, names: readonly string[]): Promise<readonly string[]> {
231
+ if (names.length === 0 || wantsGlobal(env) || isSet(env['TYPEVAULT_GRANT'])) return []
232
+ const layout = globalLayout(env)
233
+ if (!(await hasSession(layout))) return []
234
+ try {
235
+ const access = new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
236
+ const held = new Set<string>((await access.list()).map((entry) => entry.name))
237
+ return names.filter((name) => held.has(name))
238
+ } catch (error) {
239
+ // Only a hint: a session that ends meanwhile, or a daemon from another release, gives none.
240
+ if (error instanceof TypeVaultError || (error instanceof Error && 'code' in error && error.code === 'ENOENT')) {
241
+ return []
242
+ }
243
+ throw error
244
+ }
245
+ }
246
+
247
+ /** `access.get`, whose miss says so when the global vault has the name. */
248
+ export async function getEntry(access: Access, name: EntryName, reason?: string): Promise<EntryValue> {
249
+ try {
250
+ return await access.get(name, reason)
251
+ } catch (error) {
252
+ if (
253
+ error instanceof TypeVaultError &&
254
+ error.code === 'not_found' &&
255
+ (await inGlobalVault(process.env, [name])).length > 0
256
+ ) {
257
+ throw new TypeVaultError(
258
+ 'not_found',
259
+ `${error.message} in the project vault; the global vault has it: rerun with -g`,
260
+ { cause: error },
261
+ )
262
+ }
263
+ throw error
264
+ }
265
+ }
266
+
203
267
  /** How long an unlocked session lasts unless `unlock --for` says otherwise. */
204
268
  export const DEFAULT_SESSION_MS = 8 * 60 * 60_000
205
269
 
package/src/cli/index.ts CHANGED
@@ -6,7 +6,7 @@ import { ceiling, doctor, tier, init, key, signer } from './commands/admin'
6
6
  import { daemon } from './commands/daemon'
7
7
  import { get, ls, mv, otp, rm, set, whoami } from './commands/entries'
8
8
  import { audit, grant } from './commands/grant'
9
- import { identity, joinCommand, lock, member, passwd, unlock } from './commands/members'
9
+ import { identity, joinCommand, lock, member, passwd, touchId, unlock } from './commands/members'
10
10
  import { importCommand, redact, request, run, scrub } from './commands/run'
11
11
  import { readPasswordsFromStdin } from './password'
12
12
 
@@ -27,6 +27,7 @@ const main = defineCommand({
27
27
  unlock,
28
28
  lock,
29
29
  passwd,
30
+ 'touch-id': touchId,
30
31
  tier,
31
32
  ceiling,
32
33
  signer,
@@ -35,7 +35,7 @@ export async function newPassword(source: Passwords): Promise<string> {
35
35
  return password
36
36
  }
37
37
 
38
- async function promptHidden(question: string): Promise<string> {
38
+ export async function promptHidden(question: string): Promise<string> {
39
39
  const { stdin, stderr } = process
40
40
  if (!stdin.isTTY) {
41
41
  throw new TypeVaultError(
@@ -43,8 +43,9 @@ async function promptHidden(question: string): Promise<string> {
43
43
  'no terminal to ask for your TypeVault password (pass --vault-password-stdin to pipe it)',
44
44
  )
45
45
  }
46
- stderr.write(question)
46
+ // Echo goes off before the question shows, so nothing typed once it appears reaches the screen.
47
47
  stdin.setRawMode(true)
48
+ stderr.write(question)
48
49
  stdin.resume()
49
50
  const { promise, resolve, reject } = Promise.withResolvers<string>()
50
51
  let typed = ''
@@ -18,6 +18,7 @@ import { readJsonFile } from './json-file'
18
18
  import { configDir, type Layout } from './layout'
19
19
  import { generateSecretKeyCode, openWithPassword, sealWithPassword } from './password'
20
20
  import { type MemberKind, parseMemberName } from './state'
21
+ import { enableTouchId, openWithTouchId, type TouchIdSeal, TouchIdSealSchema } from './touch-id'
21
22
 
22
23
  type Env = Readonly<Record<string, string | undefined>>
23
24
 
@@ -33,6 +34,8 @@ export type Identity = PublicKey &
33
34
  readonly name: string
34
35
  readonly secretKey: string
35
36
  readonly sealedKey: string
37
+ /** The member key sealed to this Mac's Secure Enclave, opened with Touch ID instead of the password. */
38
+ readonly touchId?: TouchIdSeal | undefined
36
39
  }
37
40
  | { readonly v: 1; readonly kind: 'machine'; readonly name: string; readonly key: string }
38
41
  )
@@ -47,6 +50,7 @@ const IdentitySchema = z.discriminatedUnion('kind', [
47
50
  name: z.string(),
48
51
  secretKey: z.string(),
49
52
  sealedKey: z.string(),
53
+ touchId: TouchIdSealSchema.optional(),
50
54
  ...PublicFields,
51
55
  }),
52
56
  z.object({ v: z.literal(1), kind: z.literal('machine'), name: z.string(), key: z.string(), ...PublicFields }),
@@ -117,6 +121,19 @@ export function unlockIdentity(identity: Identity, password?: string): Promise<S
117
121
  return openMemberKey(identity.sealedKey, password, identity.secretKey)
118
122
  }
119
123
 
124
+ export const sealMemberKeyForTouchId = (env: Env, key: SecretKey): Promise<TouchIdSeal> =>
125
+ enableTouchId(env, utf8(encodeSecretKey(key)))
126
+
127
+ /** The member key through Touch ID; it must be this identity's own, whatever identity.json was given. */
128
+ export async function unlockIdentityWithTouchId(env: Env, identity: Identity, seal: TouchIdSeal): Promise<SecretKey> {
129
+ const key = decodeSecretKey(fromUtf8(await openWithTouchId(env, seal)))
130
+ const pub = await publicKeyOf(key)
131
+ if (key.role.kind !== 'member' || pub.recipient !== identity.recipient || pub.signPublic !== identity.signPublic) {
132
+ throw new TypeVaultError('tampered', "the Touch ID copy is not this identity's key")
133
+ }
134
+ return key
135
+ }
136
+
120
137
  export const encodeMemberPublic = (member: MemberPublic): string =>
121
138
  PUBLIC_PREFIX + toBase64Url(utf8(JSON.stringify(member)))
122
139
 
@@ -0,0 +1,304 @@
1
+ import { dlopen, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'
2
+ import { existsSync, linkSync, renameSync, rmSync, statSync } from 'node:fs'
3
+ import { basename, dirname, join } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import { fromBase64, toBase64 } from './encoding'
8
+ import { TypeVaultError } from './errors'
9
+ import { ensureDir } from './fsx'
10
+ import { configDir } from './layout'
11
+
12
+ type Env = Readonly<Record<string, string | undefined>>
13
+
14
+ /**
15
+ * A P-256 key in this Mac's Secure Enclave that works only after Touch ID, through Security.framework. The private key
16
+ * never leaves the chip: `handle` is the enclave's own encrypted reference to it, safe to keep in a file. Loading it
17
+ * back uses the token object ID attribute (`toid`), the private attribute CryptoKit's SecureEnclave keys are built on.
18
+ * macOS only: nothing is loaded until a function here is called.
19
+ */
20
+ export type EnclaveKey = { readonly handle: Uint8Array; readonly publicKey: Uint8Array }
21
+
22
+ const SECURITY = '/System/Library/Frameworks/Security.framework/Security'
23
+ const CORE_FOUNDATION = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation'
24
+ const LOCAL_AUTHENTICATION = '/System/Library/Frameworks/LocalAuthentication.framework/LocalAuthentication'
25
+ const LIBOBJC = '/usr/lib/libobjc.A.dylib'
26
+ const RTLD_NOW = 2
27
+ const UTF8 = 0x08000100
28
+ const CF_NUMBER_SINT32 = 3
29
+ const ACCESS_PRIVATE_KEY_USAGE = 1 << 30
30
+ const ACCESS_BIOMETRY_CURRENT_SET = 1 << 3
31
+ const TOKEN_OBJECT_ID = 'toid'
32
+ /** errSecUserCanceled and LAErrorUserCancel / LAErrorSystemCancel / LAErrorAppCancel. */
33
+ const CANCELLED = new Set([-128, -2, -4, -9])
34
+
35
+ /** Creates a new enclave key that needs Touch ID (with the fingerprints enrolled now) for every use. */
36
+ export function createEnclaveKey(): EnclaveKey {
37
+ requireMac()
38
+ const { cf, sec } = frameworks()
39
+ const key = check(sec.SecKeyCreateRandomKey(enclaveAttributes([]), errorOut()), 'create a Secure Enclave key')
40
+ const attributes = check(sec.SecKeyCopyAttributes(key), 'read the Secure Enclave key')
41
+ const handle = check(cf.CFDictionaryGetValue(attributes, cfString(TOKEN_OBJECT_ID)), 'read the Secure Enclave key')
42
+ return { handle: dataBytes(handle), publicKey: publicKeyBytes(key) }
43
+ }
44
+
45
+ const ENCLAVE_MODULE = import.meta.path
46
+
47
+ /**
48
+ * The Touch ID dialog is titled with the name of the program asking, which under npm is `bun`. So the exchange runs
49
+ * in a child started through a hard link to this bun named `typevault`; where no such link can be made (another
50
+ * volume), it runs here and the dialog says bun.
51
+ */
52
+ export async function exchangeWithEnclave(
53
+ env: Env,
54
+ handle: Uint8Array,
55
+ ephemeral: Uint8Array,
56
+ reason: string,
57
+ ): Promise<Uint8Array> {
58
+ requireMac()
59
+ const runner = typevaultNamedRuntime(env)
60
+ if (runner === undefined) return exchangeHere(handle, ephemeral, reason)
61
+ const request = JSON.stringify({ handle: toBase64(handle), peer: toBase64(ephemeral), reason })
62
+ const child = Bun.spawn([runner, ENCLAVE_MODULE], {
63
+ env: { ...process.env },
64
+ stdin: new Blob([request]),
65
+ stdout: 'pipe',
66
+ stderr: 'pipe',
67
+ })
68
+ const [out, err, code] = await Promise.all([
69
+ new Response(child.stdout).text(),
70
+ new Response(child.stderr).text(),
71
+ child.exited,
72
+ ])
73
+ if (code !== 0) {
74
+ const message = err.trim().replace(/^denied: /, '')
75
+ throw new TypeVaultError('denied', message === '' ? 'Touch ID failed' : message)
76
+ }
77
+ return fromBase64(out.trim())
78
+ }
79
+
80
+ function typevaultNamedRuntime(env: Env): string | undefined {
81
+ if (basename(process.execPath) === 'typevault') return undefined
82
+ const link = join(configDir(env), 'bin', 'typevault')
83
+ try {
84
+ if (existsSync(link) && statSync(link).ino === statSync(process.execPath).ino) return link
85
+ ensureDir(dirname(link), 0o700)
86
+ const pending = `${link}.${process.pid}`
87
+ rmSync(pending, { force: true })
88
+ linkSync(process.execPath, pending)
89
+ renameSync(pending, link)
90
+ return link
91
+ } catch (error) {
92
+ if (error instanceof Error && 'code' in error) return undefined
93
+ throw error
94
+ }
95
+ }
96
+
97
+ /** ECDH between the enclave key and `peerPublic` (uncompressed P-256): the shared x coordinate. Asks for Touch ID. */
98
+ function exchangeHere(handle: Uint8Array, peerPublic: Uint8Array, reason: string): Uint8Array {
99
+ const { sec, constant } = frameworks()
100
+ const key = check(
101
+ sec.SecKeyCreateRandomKey(
102
+ enclaveAttributes([[cfString(TOKEN_OBJECT_ID), cfData(handle)]], authenticationContext(reason)),
103
+ errorOut(),
104
+ ),
105
+ 'load the Secure Enclave key',
106
+ )
107
+ const peerAttributes = dictionary([
108
+ [constant('kSecAttrKeyType'), constant('kSecAttrKeyTypeECSECPrimeRandom')],
109
+ [constant('kSecAttrKeyClass'), constant('kSecAttrKeyClassPublic')],
110
+ [constant('kSecAttrKeySizeInBits'), keySize()],
111
+ ])
112
+ const peer = check(sec.SecKeyCreateWithData(cfData(peerPublic), peerAttributes, errorOut()), 'read the peer key')
113
+ const algorithm = constant('kSecKeyAlgorithmECDHKeyExchangeStandard')
114
+ const shared = sec.SecKeyCopyKeyExchangeResult(key, algorithm, peer, dictionary([]), errorOut())
115
+ return dataBytes(check(shared, 'use the Secure Enclave key'))
116
+ }
117
+
118
+ function requireMac(): void {
119
+ if (process.platform !== 'darwin') throw new TypeVaultError('unavailable', 'Touch ID unlock needs macOS')
120
+ }
121
+
122
+ type Ref = Pointer | bigint
123
+ type Entry = readonly [Ref, Ref]
124
+
125
+ function enclaveAttributes(privateEntries: readonly Entry[], context?: Ref): Ref {
126
+ const { sec, constant, coreConstant } = frameworks()
127
+ const access = check(
128
+ sec.SecAccessControlCreateWithFlags(
129
+ null,
130
+ constant('kSecAttrAccessibleWhenUnlockedThisDeviceOnly'),
131
+ ACCESS_PRIVATE_KEY_USAGE | ACCESS_BIOMETRY_CURRENT_SET,
132
+ errorOut(),
133
+ ),
134
+ 'set up Touch ID access',
135
+ )
136
+ // Not permanent: the key never goes in the keychain, which would need an entitlement bun doesn't have.
137
+ const privateAttributes = dictionary([
138
+ [constant('kSecAttrIsPermanent'), coreConstant('kCFBooleanFalse')],
139
+ [constant('kSecAttrAccessControl'), access],
140
+ ...privateEntries,
141
+ ])
142
+ return dictionary([
143
+ [constant('kSecAttrKeyType'), constant('kSecAttrKeyTypeECSECPrimeRandom')],
144
+ [constant('kSecAttrKeySizeInBits'), keySize()],
145
+ [constant('kSecAttrTokenID'), constant('kSecAttrTokenIDSecureEnclave')],
146
+ [constant('kSecPrivateKeyAttrs'), privateAttributes],
147
+ ...(context === undefined ? [] : [[constant('kSecUseAuthenticationContext'), context] as const]),
148
+ ])
149
+ }
150
+
151
+ /** An LAContext whose reason the Touch ID dialog shows: "<app> is trying to <reason>." */
152
+ function authenticationContext(reason: string): Ref {
153
+ const { objc, setObject } = frameworks()
154
+ const allocated = objc.objc_msgSend(objc.objc_getClass(cstring('LAContext')), objc.sel_registerName(cstring('alloc')))
155
+ const context = check(objc.objc_msgSend(allocated, objc.sel_registerName(cstring('init'))), 'set up Touch ID')
156
+ setObject(context, objc.sel_registerName(cstring('setLocalizedReason:')), cfString(reason))
157
+ return context
158
+ }
159
+
160
+ function publicKeyBytes(key: Ref): Uint8Array {
161
+ const { sec } = frameworks()
162
+ const publicKey = check(sec.SecKeyCopyPublicKey(key), 'read the Secure Enclave public key')
163
+ return dataBytes(check(sec.SecKeyCopyExternalRepresentation(publicKey, errorOut()), 'read the public key'))
164
+ }
165
+
166
+ let lastError = new BigUint64Array(1)
167
+
168
+ function errorOut(): Ref {
169
+ lastError = new BigUint64Array(1)
170
+ return ptr(lastError)
171
+ }
172
+
173
+ function check(value: Ref | null, what: string): Ref {
174
+ if (value !== null) return value
175
+ const error = lastError[0] ?? 0n
176
+ if (error === 0n) throw new TypeVaultError('unavailable', `could not ${what}`)
177
+ const { cf } = frameworks()
178
+ if (CANCELLED.has(Number(cf.CFErrorGetCode(error)))) throw new TypeVaultError('denied', 'Touch ID was cancelled')
179
+ throw new TypeVaultError('denied', `could not ${what}: ${cfText(cf.CFErrorCopyDescription(error))}`)
180
+ }
181
+
182
+ function asPointer(ref: Ref): Pointer {
183
+ if (typeof ref === 'bigint') throw new TypeVaultError('unavailable', 'a pointer out of range')
184
+ return ref
185
+ }
186
+
187
+ const cstring = (text: string): Buffer => Buffer.from(`${text}\0`)
188
+
189
+ const cfString = (text: string): Ref =>
190
+ check(frameworks().cf.CFStringCreateWithCString(null, cstring(text), UTF8), 'make a string')
191
+
192
+ function cfText(value: Ref | null): string {
193
+ if (value === null) return 'unknown error'
194
+ const buffer = Buffer.alloc(1024)
195
+ return frameworks().cf.CFStringGetCString(value, buffer, buffer.length, UTF8)
196
+ ? buffer.toString('utf8', 0, buffer.indexOf(0))
197
+ : 'unknown error'
198
+ }
199
+
200
+ const cfData = (bytes: Uint8Array): Ref =>
201
+ check(frameworks().cf.CFDataCreate(null, ptr(bytes), bytes.length), 'copy bytes')
202
+
203
+ function dataBytes(data: Ref): Uint8Array {
204
+ const { cf } = frameworks()
205
+ const length = Number(cf.CFDataGetLength(data))
206
+ const start = check(cf.CFDataGetBytePtr(data), 'read bytes')
207
+ return new Uint8Array(toArrayBuffer(asPointer(start), 0, length)).slice()
208
+ }
209
+
210
+ function keySize(): Ref {
211
+ const bits = new Int32Array([256])
212
+ return check(frameworks().cf.CFNumberCreate(null, CF_NUMBER_SINT32, ptr(bits)), 'make a number')
213
+ }
214
+
215
+ function dictionary(entries: readonly Entry[]): Ref {
216
+ const { cf, dictionaryCallbacks } = frameworks()
217
+ const dict = check(cf.CFDictionaryCreateMutable(null, 0, ...dictionaryCallbacks), 'make a dictionary')
218
+ for (const [key, value] of entries) cf.CFDictionarySetValue(dict, key, value)
219
+ return dict
220
+ }
221
+
222
+ type Frameworks = ReturnType<typeof load>
223
+ let loaded: Frameworks | undefined
224
+ const frameworks = (): Frameworks => (loaded ??= load())
225
+
226
+ function load() {
227
+ const libSystem = dlopen('/usr/lib/libSystem.B.dylib', {
228
+ dlopen: { args: [FFIType.cstring, FFIType.i32], returns: FFIType.ptr },
229
+ dlsym: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.ptr },
230
+ }).symbols
231
+ const cf = dlopen(CORE_FOUNDATION, {
232
+ CFStringCreateWithCString: { args: [FFIType.ptr, FFIType.cstring, FFIType.u32], returns: FFIType.ptr },
233
+ CFStringGetCString: { args: [FFIType.ptr, FFIType.ptr, FFIType.i64, FFIType.u32], returns: FFIType.bool },
234
+ CFDictionaryCreateMutable: { args: [FFIType.ptr, FFIType.i64, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
235
+ CFDictionarySetValue: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void },
236
+ CFDictionaryGetValue: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
237
+ CFNumberCreate: { args: [FFIType.ptr, FFIType.i64, FFIType.ptr], returns: FFIType.ptr },
238
+ CFDataCreate: { args: [FFIType.ptr, FFIType.ptr, FFIType.i64], returns: FFIType.ptr },
239
+ CFDataGetLength: { args: [FFIType.ptr], returns: FFIType.i64 },
240
+ CFDataGetBytePtr: { args: [FFIType.ptr], returns: FFIType.ptr },
241
+ CFErrorGetCode: { args: [FFIType.ptr], returns: FFIType.i64 },
242
+ CFErrorCopyDescription: { args: [FFIType.ptr], returns: FFIType.ptr },
243
+ }).symbols
244
+ const sec = dlopen(SECURITY, {
245
+ SecAccessControlCreateWithFlags: {
246
+ args: [FFIType.ptr, FFIType.ptr, FFIType.u64, FFIType.ptr],
247
+ returns: FFIType.ptr,
248
+ },
249
+ SecKeyCreateRandomKey: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
250
+ SecKeyCreateWithData: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
251
+ SecKeyCopyAttributes: { args: [FFIType.ptr], returns: FFIType.ptr },
252
+ SecKeyCopyPublicKey: { args: [FFIType.ptr], returns: FFIType.ptr },
253
+ SecKeyCopyExternalRepresentation: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
254
+ SecKeyCopyKeyExchangeResult: {
255
+ args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr],
256
+ returns: FFIType.ptr,
257
+ },
258
+ }).symbols
259
+ const objc = dlopen(LIBOBJC, {
260
+ objc_getClass: { args: [FFIType.cstring], returns: FFIType.ptr },
261
+ sel_registerName: { args: [FFIType.cstring], returns: FFIType.ptr },
262
+ objc_msgSend: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
263
+ }).symbols
264
+ // objc_msgSend takes the signature of the method it calls, so a setter needs its own binding.
265
+ const setObject = dlopen(LIBOBJC, {
266
+ objc_msgSend: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void },
267
+ }).symbols.objc_msgSend
268
+ libSystem.dlopen(cstring(LOCAL_AUTHENTICATION), RTLD_NOW)
269
+ const securityHandle = libSystem.dlopen(cstring(SECURITY), RTLD_NOW)
270
+ const coreHandle = libSystem.dlopen(cstring(CORE_FOUNDATION), RTLD_NOW)
271
+ const address = (handle: Ref | null, name: string): Ref => {
272
+ const found = libSystem.dlsym(handle, cstring(name))
273
+ if (found === null) throw new TypeVaultError('unavailable', `Security.framework has no ${name}`)
274
+ return found
275
+ }
276
+ const valueAt = (at: Ref): Ref => read.u64(asPointer(at))
277
+ return {
278
+ cf,
279
+ sec,
280
+ objc,
281
+ setObject,
282
+ constant: (name: string): Ref => valueAt(address(securityHandle, name)),
283
+ coreConstant: (name: string): Ref => valueAt(address(coreHandle, name)),
284
+ dictionaryCallbacks: [
285
+ address(coreHandle, 'kCFTypeDictionaryKeyCallBacks'),
286
+ address(coreHandle, 'kCFTypeDictionaryValueCallBacks'),
287
+ ] as const,
288
+ }
289
+ }
290
+
291
+ const RequestSchema = z.object({ handle: z.string(), peer: z.string(), reason: z.string() })
292
+
293
+ // Run as its own process (see touch-id.ts) so the Touch ID dialog names the program that asks: reads one exchange
294
+ // request from stdin and prints the shared secret.
295
+ if (import.meta.main) {
296
+ const request = RequestSchema.parse(JSON.parse(await Bun.stdin.text()))
297
+ try {
298
+ process.stdout.write(toBase64(exchangeHere(fromBase64(request.handle), fromBase64(request.peer), request.reason)))
299
+ } catch (error) {
300
+ if (!(error instanceof TypeVaultError)) throw error
301
+ process.stderr.write(`${error.code}: ${error.message}\n`)
302
+ process.exitCode = 1
303
+ }
304
+ }
@@ -0,0 +1,86 @@
1
+ import { p256 } from '@noble/curves/nist.js'
2
+ import { hkdf } from '@noble/hashes/hkdf.js'
3
+ import { sha256 } from '@noble/hashes/sha2.js'
4
+ import { z } from 'zod'
5
+
6
+ import { fromBase64, toBase64, utf8 } from './encoding'
7
+ import { TypeVaultError } from './errors'
8
+
9
+ type Env = Readonly<Record<string, string | undefined>>
10
+
11
+ /**
12
+ * A secret sealed to a Secure Enclave key: an ephemeral P-256 key agrees a secret with the enclave key, and that
13
+ * secret seals the plaintext. Opening it needs the enclave, so this Mac and a touch of an enrolled finger.
14
+ */
15
+ export const TouchIdSealSchema = z.object({
16
+ handle: z.string(),
17
+ ephemeral: z.string(),
18
+ nonce: z.string(),
19
+ ciphertext: z.string(),
20
+ })
21
+ export type TouchIdSeal = z.infer<typeof TouchIdSealSchema>
22
+
23
+ /** The enclave side of the agreement: given the key's handle and the ephemeral public key, the shared x coordinate. */
24
+ export type EnclaveExchange = (handle: Uint8Array, ephemeral: Uint8Array) => Promise<Uint8Array>
25
+
26
+ export async function sealToEnclave(
27
+ plaintext: Uint8Array,
28
+ handle: Uint8Array,
29
+ enclavePublic: Uint8Array,
30
+ ): Promise<TouchIdSeal> {
31
+ const secret = p256.utils.randomSecretKey()
32
+ const ephemeral = p256.getPublicKey(secret, false)
33
+ const key = await sealingKey(p256.getSharedSecret(secret, enclavePublic).slice(1), ephemeral)
34
+ const nonce = crypto.getRandomValues(new Uint8Array(12))
35
+ const ciphertext = new Uint8Array(
36
+ await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, new Uint8Array(plaintext)),
37
+ )
38
+ return {
39
+ handle: toBase64(handle),
40
+ ephemeral: toBase64(ephemeral),
41
+ nonce: toBase64(nonce),
42
+ ciphertext: toBase64(ciphertext),
43
+ }
44
+ }
45
+
46
+ export async function openFromEnclave(seal: TouchIdSeal, exchange: EnclaveExchange): Promise<Uint8Array> {
47
+ const ephemeral = fromBase64(seal.ephemeral)
48
+ const key = await sealingKey(await exchange(fromBase64(seal.handle), ephemeral), ephemeral)
49
+ try {
50
+ return new Uint8Array(
51
+ await crypto.subtle.decrypt(
52
+ { name: 'AES-GCM', iv: new Uint8Array(fromBase64(seal.nonce)) },
53
+ key,
54
+ new Uint8Array(fromBase64(seal.ciphertext)),
55
+ ),
56
+ )
57
+ } catch (error) {
58
+ if (error instanceof Error) throw new TypeVaultError('denied', 'the Touch ID copy of your key does not open')
59
+ throw error
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Seals `plaintext` to a new Touch ID key on this Mac, and opens it once with a touch before returning, so a sensor
65
+ * or enclave that doesn't work shows up now rather than at the next unlock.
66
+ */
67
+ export async function enableTouchId(env: Env, plaintext: Uint8Array): Promise<TouchIdSeal> {
68
+ const { createEnclaveKey } = await import('./secure-enclave')
69
+ const { handle, publicKey } = createEnclaveKey()
70
+ const seal = await sealToEnclave(plaintext, handle, publicKey)
71
+ const opened = await openWithTouchId(env, seal, 'turn on Touch ID unlock')
72
+ if (toBase64(opened) !== toBase64(plaintext)) {
73
+ throw new TypeVaultError('unavailable', 'Touch ID opened something else than what was sealed')
74
+ }
75
+ return seal
76
+ }
77
+
78
+ export async function openWithTouchId(env: Env, seal: TouchIdSeal, reason = 'unlock your vault'): Promise<Uint8Array> {
79
+ const { exchangeWithEnclave } = await import('./secure-enclave')
80
+ return openFromEnclave(seal, (handle, ephemeral) => exchangeWithEnclave(env, handle, ephemeral, reason))
81
+ }
82
+
83
+ function sealingKey(shared: Uint8Array, ephemeral: Uint8Array): Promise<CryptoKey> {
84
+ const raw = hkdf(sha256, shared, ephemeral, utf8('typevault touch id'), 32)
85
+ return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
86
+ }
@@ -1,7 +1,7 @@
1
1
  import { chmodSync, existsSync, readdirSync, realpathSync, rmSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
 
4
- import { anchorAudit, appendAudit } from '../audit/log'
4
+ import { appendAudit } from '../audit/log'
5
5
  import { adoptCertWrites } from '../core/adopt'
6
6
  import { randomHex, type SecretKey } from '../core/crypto'
7
7
  import { TypeVaultError } from '../core/errors'
@@ -210,8 +210,6 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
210
210
 
211
211
  await Promise.all(servers.map((server) => server.stop(true)))
212
212
  await context.requests.stop()
213
- // A vault deleted under its daemon has nowhere left to anchor (and writing there would half re-create it).
214
- if (existsSync(layout.ownerFile)) await anchorAudit(layout)
215
213
  for (const file of [
216
214
  layout.agentSocket,
217
215
  ...ceilings.map((c) => layout.adminSocket(c.name)),
@@ -50,6 +50,27 @@ export async function ensureDaemon(layout: Layout, env: Env): Promise<void> {
50
50
  await startBackground(layout, env, [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout)])
51
51
  }
52
52
 
53
+ /**
54
+ * Stops this checkout's daemon, if running, and starts a fresh one. Only a machine member's daemon can come back on
55
+ * its own: an unlocked session's key would be gone with it, so that one is refused before anything stops.
56
+ */
57
+ export async function restartDaemon(layout: Layout, env: Env): Promise<void> {
58
+ // A token with no daemon answering was left by a killed session; the new daemon clears it on start.
59
+ if (existsSync(layout.sessionFile) && (await isDaemonAlive(layout.agentSocket))) {
60
+ throw new TypeVaultError(
61
+ 'conflict',
62
+ 'this daemon holds an unlocked session, which a restart would end: run `typevault lock`, then `typevault unlock`',
63
+ )
64
+ }
65
+ if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
66
+ try {
67
+ await stopDaemon(layout)
68
+ } catch (error) {
69
+ if (!(error instanceof TypeVaultError && error.code === 'not_found')) throw error
70
+ }
71
+ await ensureDaemon(layout, env)
72
+ }
73
+
53
74
  function versionMismatch(layout: Layout, running: string | null, version: string): TypeVaultError {
54
75
  const from = running === null ? 'is from an older release' : `is version ${running}`
55
76
  const fix = existsSync(layout.sessionFile)