typevault 0.6.0 → 0.6.1

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.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
@@ -21,6 +21,7 @@ import {
21
21
  import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/layout'
22
22
  import type { EntryName } from '../core/naming'
23
23
  import { loadState } from '../core/state'
24
+ import { touchIdAvailable } from '../core/touch-id'
24
25
  import { Vault } from '../core/vault'
25
26
  import { worktreeVaults } from '../core/worktrees'
26
27
  import { callDaemon, isDaemonAlive } from '../daemon/client'
@@ -75,11 +76,17 @@ export async function openDirect(env: Env): Promise<Vault> {
75
76
  /**
76
77
  * 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
78
  * ID fails) their password. Without a terminal it stays the password's error, so an agent can't raise the dialog.
79
+ * At a Mac with Touch ID that they haven't turned on, the password prompt suggests it.
78
80
  */
79
81
  export async function unlockHuman(env: Env, identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
80
82
  if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
81
83
  if (identity.kind === 'machine') return unlockIdentity(identity)
82
- if (identity.touchId !== undefined && process.platform === 'darwin' && process.stdin.isTTY && !passwordsFromStdin()) {
84
+ const atThisMac = process.platform === 'darwin' && process.stdin.isTTY === true && !passwordsFromStdin()
85
+ if (identity.touchId === undefined) {
86
+ // The tip is optional: a probe that fails must not stand between the person and their password prompt.
87
+ const tip = atThisMac && (await touchIdAvailable().catch(() => false))
88
+ if (tip) note('tip: skip the password next time with `typevault touch-id enable`')
89
+ } else if (atThisMac) {
83
90
  try {
84
91
  return await unlockIdentityWithTouchId(env, identity, identity.touchId)
85
92
  } catch (error) {
@@ -1,5 +1,5 @@
1
1
  import { dlopen, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'
2
- import { existsSync, linkSync, renameSync, rmSync, statSync } from 'node:fs'
2
+ import { copyFileSync, existsSync, renameSync, rmSync, statSync, utimesSync } from 'node:fs'
3
3
  import { basename, dirname, join } from 'node:path'
4
4
 
5
5
  import { z } from 'zod'
@@ -29,6 +29,7 @@ const CF_NUMBER_SINT32 = 3
29
29
  const ACCESS_PRIVATE_KEY_USAGE = 1 << 30
30
30
  const ACCESS_BIOMETRY_CURRENT_SET = 1 << 3
31
31
  const TOKEN_OBJECT_ID = 'toid'
32
+ const POLICY_BIOMETRICS = 1
32
33
  /** errSecUserCanceled and LAErrorUserCancel / LAErrorSystemCancel / LAErrorAppCancel. */
33
34
  const CANCELLED = new Set([-128, -2, -4, -9])
34
35
 
@@ -42,12 +43,20 @@ export function createEnclaveKey(): EnclaveKey {
42
43
  return { handle: dataBytes(handle), publicKey: publicKeyBytes(key) }
43
44
  }
44
45
 
46
+ /** Whether this Mac has a Touch ID sensor with a finger enrolled. Asks nothing: no dialog shows. */
47
+ export function hasTouchId(): boolean {
48
+ if (process.platform !== 'darwin') return false
49
+ const { objc, canEvaluatePolicy } = frameworks()
50
+ const selector = objc.sel_registerName(cstring('canEvaluatePolicy:error:'))
51
+ return canEvaluatePolicy(newAuthenticationContext(), selector, POLICY_BIOMETRICS, null)
52
+ }
53
+
45
54
  const ENCLAVE_MODULE = import.meta.path
46
55
 
47
56
  /**
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.
57
+ * The Touch ID dialog is titled with the code-signing identifier of the program asking, which under npm is `bun`. So
58
+ * the exchange runs in a child started from a copy of this bun re-signed (ad hoc) as `typevault`; where no such copy
59
+ * can be made, it runs here and the dialog says bun.
51
60
  */
52
61
  export async function exchangeWithEnclave(
53
62
  env: Env,
@@ -56,7 +65,7 @@ export async function exchangeWithEnclave(
56
65
  reason: string,
57
66
  ): Promise<Uint8Array> {
58
67
  requireMac()
59
- const runner = typevaultNamedRuntime(env)
68
+ const runner = await typevaultSignedRuntime(env)
60
69
  if (runner === undefined) return exchangeHere(handle, ephemeral, reason)
61
70
  const request = JSON.stringify({ handle: toBase64(handle), peer: toBase64(ephemeral), reason })
62
71
  const child = Bun.spawn([runner, ENCLAVE_MODULE], {
@@ -77,17 +86,43 @@ export async function exchangeWithEnclave(
77
86
  return fromBase64(out.trim())
78
87
  }
79
88
 
80
- function typevaultNamedRuntime(env: Env): string | undefined {
81
- if (basename(process.execPath) === 'typevault') return undefined
82
- const link = join(configDir(env), 'bin', 'typevault')
89
+ /**
90
+ * The copy keeps the source's mtime (to the millisecond, as far as `utimes` takes it), so a bun upgrade (new mtime) or
91
+ * an old hard link (same inode) is replaced. Each call signs its own temporary copy, so overlapping calls never publish
92
+ * a file another call is still signing.
93
+ */
94
+ export async function typevaultSignedRuntime(env: Env, source = process.execPath): Promise<string | undefined> {
95
+ if (basename(source) === 'typevault') return undefined
96
+ const runtime = join(configDir(env), 'bin', 'typevault')
83
97
  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
98
+ const original = statSync(source)
99
+ if (existsSync(runtime)) {
100
+ const current = statSync(runtime)
101
+ if (current.ino !== original.ino && Math.trunc(current.mtimeMs) === Math.trunc(original.mtimeMs)) return runtime
102
+ }
103
+ ensureDir(dirname(runtime), 0o700)
104
+ const pending = `${runtime}.${crypto.randomUUID()}`
105
+ copyFileSync(source, pending)
106
+ const signing = Bun.spawn(
107
+ [
108
+ '/usr/bin/codesign',
109
+ '--force',
110
+ '--sign',
111
+ '-',
112
+ '--identifier',
113
+ 'typevault',
114
+ '--preserve-metadata=entitlements,flags',
115
+ pending,
116
+ ],
117
+ { stdout: 'ignore', stderr: 'ignore' },
118
+ )
119
+ if ((await signing.exited) !== 0) {
120
+ rmSync(pending, { force: true })
121
+ return undefined
122
+ }
123
+ utimesSync(pending, original.atime, original.mtime)
124
+ renameSync(pending, runtime)
125
+ return runtime
91
126
  } catch (error) {
92
127
  if (error instanceof Error && 'code' in error) return undefined
93
128
  throw error
@@ -151,12 +186,17 @@ function enclaveAttributes(privateEntries: readonly Entry[], context?: Ref): Ref
151
186
  /** An LAContext whose reason the Touch ID dialog shows: "<app> is trying to <reason>." */
152
187
  function authenticationContext(reason: string): Ref {
153
188
  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')
189
+ const context = newAuthenticationContext()
156
190
  setObject(context, objc.sel_registerName(cstring('setLocalizedReason:')), cfString(reason))
157
191
  return context
158
192
  }
159
193
 
194
+ function newAuthenticationContext(): Ref {
195
+ const { objc } = frameworks()
196
+ const allocated = objc.objc_msgSend(objc.objc_getClass(cstring('LAContext')), objc.sel_registerName(cstring('alloc')))
197
+ return check(objc.objc_msgSend(allocated, objc.sel_registerName(cstring('init'))), 'set up Touch ID')
198
+ }
199
+
160
200
  function publicKeyBytes(key: Ref): Uint8Array {
161
201
  const { sec } = frameworks()
162
202
  const publicKey = check(sec.SecKeyCopyPublicKey(key), 'read the Secure Enclave public key')
@@ -265,6 +305,9 @@ function load() {
265
305
  const setObject = dlopen(LIBOBJC, {
266
306
  objc_msgSend: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void },
267
307
  }).symbols.objc_msgSend
308
+ const canEvaluatePolicy = dlopen(LIBOBJC, {
309
+ objc_msgSend: { args: [FFIType.ptr, FFIType.ptr, FFIType.i64, FFIType.ptr], returns: FFIType.bool },
310
+ }).symbols.objc_msgSend
268
311
  libSystem.dlopen(cstring(LOCAL_AUTHENTICATION), RTLD_NOW)
269
312
  const securityHandle = libSystem.dlopen(cstring(SECURITY), RTLD_NOW)
270
313
  const coreHandle = libSystem.dlopen(cstring(CORE_FOUNDATION), RTLD_NOW)
@@ -279,6 +322,7 @@ function load() {
279
322
  sec,
280
323
  objc,
281
324
  setObject,
325
+ canEvaluatePolicy,
282
326
  constant: (name: string): Ref => valueAt(address(securityHandle, name)),
283
327
  coreConstant: (name: string): Ref => valueAt(address(coreHandle, name)),
284
328
  dictionaryCallbacks: [
@@ -75,6 +75,12 @@ export async function enableTouchId(env: Env, plaintext: Uint8Array): Promise<To
75
75
  return seal
76
76
  }
77
77
 
78
+ /** Whether this Mac could unlock with Touch ID: a sensor and an enrolled finger. Shows no dialog. */
79
+ export async function touchIdAvailable(): Promise<boolean> {
80
+ const { hasTouchId } = await import('./secure-enclave')
81
+ return hasTouchId()
82
+ }
83
+
78
84
  export async function openWithTouchId(env: Env, seal: TouchIdSeal, reason = 'unlock your vault'): Promise<Uint8Array> {
79
85
  const { exchangeWithEnclave } = await import('./secure-enclave')
80
86
  return openFromEnclave(seal, (handle, ephemeral) => exchangeWithEnclave(env, handle, ephemeral, reason))