typevault 0.5.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.5.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": {
@@ -22,6 +22,7 @@ import { FieldSchema } from '../../core/payload'
22
22
  import { parseTotpSeed, totpCode, totpRemainingSeconds } from '../../otp/totp'
23
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. */
@@ -131,7 +132,7 @@ export const set = defineCommand({
131
132
  meta: {
132
133
  name: 'set',
133
134
  description:
134
- '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.',
135
136
  },
136
137
  args: {
137
138
  name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
@@ -143,6 +144,7 @@ export const set = defineCommand({
143
144
  },
144
145
  field: { type: 'string', description: 'k=v, repeatable (writes text fields; use stdin for secrets)' },
145
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' },
146
148
  web: {
147
149
  type: 'boolean',
148
150
  description: 'Type the fields in a local one-time browser page (default for a new entry from a terminal)',
@@ -166,9 +168,18 @@ export const set = defineCommand({
166
168
  const given = parseFields(repeated(rawArgs, '--field'), { ...known, ...suggested })
167
169
  const tier = args.tier ?? existing?.tier ?? process.env['TYPEVAULT_TIER']
168
170
  const target = preset?.input ?? defaultFieldOf(previous) ?? '$default'
171
+ if (args.prompt) checkPrompt(args, target, suggested[target] ?? previous[target]?.type)
169
172
  const stdin = args.stdin || args['stdin-json'] ? await readStdin() : undefined
170
173
  if (args.stdin && stdin === '') throw new TypeVaultError('invalid', '--stdin did not contain a value')
171
- 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
+ : {}
172
183
  const typed: Record<string, Field> = {}
173
184
  for (const [field, value] of Object.entries(fromStdin)) {
174
185
  if (typeof value !== 'string') {
@@ -198,7 +209,8 @@ export const set = defineCommand({
198
209
  throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
199
210
  }
200
211
  }
201
- 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)
202
214
  const fromWeb = web
203
215
  ? await promptFields(
204
216
  { name, preset: args.preset === undefined ? undefined : parsePreset(args.preset), tier },
@@ -234,6 +246,27 @@ export const set = defineCommand({
234
246
  },
235
247
  })
236
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
+
237
270
  function showPrompt(url: string, code: string): void {
238
271
  note(`Enter the secret at ${url}\nMatch code: ${code} (the page shows the same code)`)
239
272
  if (!openBrowser(url)) note('could not open a browser; open the link yourself')
@@ -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() {
@@ -11,7 +11,13 @@ 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'
16
22
  import type { EntryName } from '../core/naming'
17
23
  import { loadState } from '../core/state'
@@ -62,13 +68,28 @@ export async function openDirect(env: Env): Promise<Vault> {
62
68
  if (machine.length === 0 && identity === undefined) {
63
69
  throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
64
70
  }
65
- const keys = machine.length > 0 ? machine : [await unlockHuman(identity, passwords())]
71
+ const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords())]
66
72
  return Vault.open(layout, keys, env)
67
73
  }
68
74
 
69
- 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> {
70
80
  if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
71
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
+ }
72
93
  return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
73
94
  }
74
95
 
@@ -80,7 +101,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
80
101
  const layout = layoutFrom(env)
81
102
  if (await hasSession(layout)) return false
82
103
  const identity = readIdentity(env)
83
- const key = await unlockHuman(identity, passwords)
104
+ const key = await unlockHuman(env, identity, passwords)
84
105
  const vault = await Vault.open(layout, [key], env)
85
106
  if (vault.member === undefined) {
86
107
  throw new TypeVaultError(
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)),