typevault 0.5.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 +3 -2
- package/src/cli/commands/entries.ts +36 -3
- package/src/cli/commands/members.ts +31 -0
- package/src/cli/context.ts +32 -4
- package/src/cli/index.ts +2 -1
- package/src/cli/password.ts +3 -2
- package/src/core/identity.ts +17 -0
- package/src/core/secure-enclave.ts +348 -0
- package/src/core/touch-id.ts +92 -0
- package/src/daemon/daemon.ts +1 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typevault",
|
|
3
|
-
"version": "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": {
|
|
@@ -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,
|
|
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
|
|
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 =
|
|
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() {
|
package/src/cli/context.ts
CHANGED
|
@@ -11,10 +11,17 @@ 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 {
|
|
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'
|
|
24
|
+
import { touchIdAvailable } from '../core/touch-id'
|
|
18
25
|
import { Vault } from '../core/vault'
|
|
19
26
|
import { worktreeVaults } from '../core/worktrees'
|
|
20
27
|
import { callDaemon, isDaemonAlive } from '../daemon/client'
|
|
@@ -62,13 +69,34 @@ export async function openDirect(env: Env): Promise<Vault> {
|
|
|
62
69
|
if (machine.length === 0 && identity === undefined) {
|
|
63
70
|
throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
|
|
64
71
|
}
|
|
65
|
-
const keys = machine.length > 0 ? machine : [await unlockHuman(identity, passwords())]
|
|
72
|
+
const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords())]
|
|
66
73
|
return Vault.open(layout, keys, env)
|
|
67
74
|
}
|
|
68
75
|
|
|
69
|
-
|
|
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
|
|
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.
|
|
80
|
+
*/
|
|
81
|
+
export async function unlockHuman(env: Env, identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
|
|
70
82
|
if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
|
|
71
83
|
if (identity.kind === 'machine') return unlockIdentity(identity)
|
|
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) {
|
|
90
|
+
try {
|
|
91
|
+
return await unlockIdentityWithTouchId(env, identity, identity.touchId)
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (!(error instanceof TypeVaultError)) throw error
|
|
94
|
+
note(`${error.message}; asking for your password instead`)
|
|
95
|
+
if (error.message !== 'Touch ID was cancelled') {
|
|
96
|
+
note('if your fingerprints changed, run `typevault touch-id enable` again')
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
72
100
|
return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
|
|
73
101
|
}
|
|
74
102
|
|
|
@@ -80,7 +108,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
|
|
|
80
108
|
const layout = layoutFrom(env)
|
|
81
109
|
if (await hasSession(layout)) return false
|
|
82
110
|
const identity = readIdentity(env)
|
|
83
|
-
const key = await unlockHuman(identity, passwords)
|
|
111
|
+
const key = await unlockHuman(env, identity, passwords)
|
|
84
112
|
const vault = await Vault.open(layout, [key], env)
|
|
85
113
|
if (vault.member === undefined) {
|
|
86
114
|
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,
|
package/src/cli/password.ts
CHANGED
|
@@ -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
|
-
|
|
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 = ''
|
package/src/core/identity.ts
CHANGED
|
@@ -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,348 @@
|
|
|
1
|
+
import { dlopen, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'
|
|
2
|
+
import { copyFileSync, existsSync, renameSync, rmSync, statSync, utimesSync } 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
|
+
const POLICY_BIOMETRICS = 1
|
|
33
|
+
/** errSecUserCanceled and LAErrorUserCancel / LAErrorSystemCancel / LAErrorAppCancel. */
|
|
34
|
+
const CANCELLED = new Set([-128, -2, -4, -9])
|
|
35
|
+
|
|
36
|
+
/** Creates a new enclave key that needs Touch ID (with the fingerprints enrolled now) for every use. */
|
|
37
|
+
export function createEnclaveKey(): EnclaveKey {
|
|
38
|
+
requireMac()
|
|
39
|
+
const { cf, sec } = frameworks()
|
|
40
|
+
const key = check(sec.SecKeyCreateRandomKey(enclaveAttributes([]), errorOut()), 'create a Secure Enclave key')
|
|
41
|
+
const attributes = check(sec.SecKeyCopyAttributes(key), 'read the Secure Enclave key')
|
|
42
|
+
const handle = check(cf.CFDictionaryGetValue(attributes, cfString(TOKEN_OBJECT_ID)), 'read the Secure Enclave key')
|
|
43
|
+
return { handle: dataBytes(handle), publicKey: publicKeyBytes(key) }
|
|
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
|
+
|
|
54
|
+
const ENCLAVE_MODULE = import.meta.path
|
|
55
|
+
|
|
56
|
+
/**
|
|
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.
|
|
60
|
+
*/
|
|
61
|
+
export async function exchangeWithEnclave(
|
|
62
|
+
env: Env,
|
|
63
|
+
handle: Uint8Array,
|
|
64
|
+
ephemeral: Uint8Array,
|
|
65
|
+
reason: string,
|
|
66
|
+
): Promise<Uint8Array> {
|
|
67
|
+
requireMac()
|
|
68
|
+
const runner = await typevaultSignedRuntime(env)
|
|
69
|
+
if (runner === undefined) return exchangeHere(handle, ephemeral, reason)
|
|
70
|
+
const request = JSON.stringify({ handle: toBase64(handle), peer: toBase64(ephemeral), reason })
|
|
71
|
+
const child = Bun.spawn([runner, ENCLAVE_MODULE], {
|
|
72
|
+
env: { ...process.env },
|
|
73
|
+
stdin: new Blob([request]),
|
|
74
|
+
stdout: 'pipe',
|
|
75
|
+
stderr: 'pipe',
|
|
76
|
+
})
|
|
77
|
+
const [out, err, code] = await Promise.all([
|
|
78
|
+
new Response(child.stdout).text(),
|
|
79
|
+
new Response(child.stderr).text(),
|
|
80
|
+
child.exited,
|
|
81
|
+
])
|
|
82
|
+
if (code !== 0) {
|
|
83
|
+
const message = err.trim().replace(/^denied: /, '')
|
|
84
|
+
throw new TypeVaultError('denied', message === '' ? 'Touch ID failed' : message)
|
|
85
|
+
}
|
|
86
|
+
return fromBase64(out.trim())
|
|
87
|
+
}
|
|
88
|
+
|
|
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')
|
|
97
|
+
try {
|
|
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
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof Error && 'code' in error) return undefined
|
|
128
|
+
throw error
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** ECDH between the enclave key and `peerPublic` (uncompressed P-256): the shared x coordinate. Asks for Touch ID. */
|
|
133
|
+
function exchangeHere(handle: Uint8Array, peerPublic: Uint8Array, reason: string): Uint8Array {
|
|
134
|
+
const { sec, constant } = frameworks()
|
|
135
|
+
const key = check(
|
|
136
|
+
sec.SecKeyCreateRandomKey(
|
|
137
|
+
enclaveAttributes([[cfString(TOKEN_OBJECT_ID), cfData(handle)]], authenticationContext(reason)),
|
|
138
|
+
errorOut(),
|
|
139
|
+
),
|
|
140
|
+
'load the Secure Enclave key',
|
|
141
|
+
)
|
|
142
|
+
const peerAttributes = dictionary([
|
|
143
|
+
[constant('kSecAttrKeyType'), constant('kSecAttrKeyTypeECSECPrimeRandom')],
|
|
144
|
+
[constant('kSecAttrKeyClass'), constant('kSecAttrKeyClassPublic')],
|
|
145
|
+
[constant('kSecAttrKeySizeInBits'), keySize()],
|
|
146
|
+
])
|
|
147
|
+
const peer = check(sec.SecKeyCreateWithData(cfData(peerPublic), peerAttributes, errorOut()), 'read the peer key')
|
|
148
|
+
const algorithm = constant('kSecKeyAlgorithmECDHKeyExchangeStandard')
|
|
149
|
+
const shared = sec.SecKeyCopyKeyExchangeResult(key, algorithm, peer, dictionary([]), errorOut())
|
|
150
|
+
return dataBytes(check(shared, 'use the Secure Enclave key'))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function requireMac(): void {
|
|
154
|
+
if (process.platform !== 'darwin') throw new TypeVaultError('unavailable', 'Touch ID unlock needs macOS')
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type Ref = Pointer | bigint
|
|
158
|
+
type Entry = readonly [Ref, Ref]
|
|
159
|
+
|
|
160
|
+
function enclaveAttributes(privateEntries: readonly Entry[], context?: Ref): Ref {
|
|
161
|
+
const { sec, constant, coreConstant } = frameworks()
|
|
162
|
+
const access = check(
|
|
163
|
+
sec.SecAccessControlCreateWithFlags(
|
|
164
|
+
null,
|
|
165
|
+
constant('kSecAttrAccessibleWhenUnlockedThisDeviceOnly'),
|
|
166
|
+
ACCESS_PRIVATE_KEY_USAGE | ACCESS_BIOMETRY_CURRENT_SET,
|
|
167
|
+
errorOut(),
|
|
168
|
+
),
|
|
169
|
+
'set up Touch ID access',
|
|
170
|
+
)
|
|
171
|
+
// Not permanent: the key never goes in the keychain, which would need an entitlement bun doesn't have.
|
|
172
|
+
const privateAttributes = dictionary([
|
|
173
|
+
[constant('kSecAttrIsPermanent'), coreConstant('kCFBooleanFalse')],
|
|
174
|
+
[constant('kSecAttrAccessControl'), access],
|
|
175
|
+
...privateEntries,
|
|
176
|
+
])
|
|
177
|
+
return dictionary([
|
|
178
|
+
[constant('kSecAttrKeyType'), constant('kSecAttrKeyTypeECSECPrimeRandom')],
|
|
179
|
+
[constant('kSecAttrKeySizeInBits'), keySize()],
|
|
180
|
+
[constant('kSecAttrTokenID'), constant('kSecAttrTokenIDSecureEnclave')],
|
|
181
|
+
[constant('kSecPrivateKeyAttrs'), privateAttributes],
|
|
182
|
+
...(context === undefined ? [] : [[constant('kSecUseAuthenticationContext'), context] as const]),
|
|
183
|
+
])
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** An LAContext whose reason the Touch ID dialog shows: "<app> is trying to <reason>." */
|
|
187
|
+
function authenticationContext(reason: string): Ref {
|
|
188
|
+
const { objc, setObject } = frameworks()
|
|
189
|
+
const context = newAuthenticationContext()
|
|
190
|
+
setObject(context, objc.sel_registerName(cstring('setLocalizedReason:')), cfString(reason))
|
|
191
|
+
return context
|
|
192
|
+
}
|
|
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
|
+
|
|
200
|
+
function publicKeyBytes(key: Ref): Uint8Array {
|
|
201
|
+
const { sec } = frameworks()
|
|
202
|
+
const publicKey = check(sec.SecKeyCopyPublicKey(key), 'read the Secure Enclave public key')
|
|
203
|
+
return dataBytes(check(sec.SecKeyCopyExternalRepresentation(publicKey, errorOut()), 'read the public key'))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
let lastError = new BigUint64Array(1)
|
|
207
|
+
|
|
208
|
+
function errorOut(): Ref {
|
|
209
|
+
lastError = new BigUint64Array(1)
|
|
210
|
+
return ptr(lastError)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function check(value: Ref | null, what: string): Ref {
|
|
214
|
+
if (value !== null) return value
|
|
215
|
+
const error = lastError[0] ?? 0n
|
|
216
|
+
if (error === 0n) throw new TypeVaultError('unavailable', `could not ${what}`)
|
|
217
|
+
const { cf } = frameworks()
|
|
218
|
+
if (CANCELLED.has(Number(cf.CFErrorGetCode(error)))) throw new TypeVaultError('denied', 'Touch ID was cancelled')
|
|
219
|
+
throw new TypeVaultError('denied', `could not ${what}: ${cfText(cf.CFErrorCopyDescription(error))}`)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function asPointer(ref: Ref): Pointer {
|
|
223
|
+
if (typeof ref === 'bigint') throw new TypeVaultError('unavailable', 'a pointer out of range')
|
|
224
|
+
return ref
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const cstring = (text: string): Buffer => Buffer.from(`${text}\0`)
|
|
228
|
+
|
|
229
|
+
const cfString = (text: string): Ref =>
|
|
230
|
+
check(frameworks().cf.CFStringCreateWithCString(null, cstring(text), UTF8), 'make a string')
|
|
231
|
+
|
|
232
|
+
function cfText(value: Ref | null): string {
|
|
233
|
+
if (value === null) return 'unknown error'
|
|
234
|
+
const buffer = Buffer.alloc(1024)
|
|
235
|
+
return frameworks().cf.CFStringGetCString(value, buffer, buffer.length, UTF8)
|
|
236
|
+
? buffer.toString('utf8', 0, buffer.indexOf(0))
|
|
237
|
+
: 'unknown error'
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const cfData = (bytes: Uint8Array): Ref =>
|
|
241
|
+
check(frameworks().cf.CFDataCreate(null, ptr(bytes), bytes.length), 'copy bytes')
|
|
242
|
+
|
|
243
|
+
function dataBytes(data: Ref): Uint8Array {
|
|
244
|
+
const { cf } = frameworks()
|
|
245
|
+
const length = Number(cf.CFDataGetLength(data))
|
|
246
|
+
const start = check(cf.CFDataGetBytePtr(data), 'read bytes')
|
|
247
|
+
return new Uint8Array(toArrayBuffer(asPointer(start), 0, length)).slice()
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function keySize(): Ref {
|
|
251
|
+
const bits = new Int32Array([256])
|
|
252
|
+
return check(frameworks().cf.CFNumberCreate(null, CF_NUMBER_SINT32, ptr(bits)), 'make a number')
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function dictionary(entries: readonly Entry[]): Ref {
|
|
256
|
+
const { cf, dictionaryCallbacks } = frameworks()
|
|
257
|
+
const dict = check(cf.CFDictionaryCreateMutable(null, 0, ...dictionaryCallbacks), 'make a dictionary')
|
|
258
|
+
for (const [key, value] of entries) cf.CFDictionarySetValue(dict, key, value)
|
|
259
|
+
return dict
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
type Frameworks = ReturnType<typeof load>
|
|
263
|
+
let loaded: Frameworks | undefined
|
|
264
|
+
const frameworks = (): Frameworks => (loaded ??= load())
|
|
265
|
+
|
|
266
|
+
function load() {
|
|
267
|
+
const libSystem = dlopen('/usr/lib/libSystem.B.dylib', {
|
|
268
|
+
dlopen: { args: [FFIType.cstring, FFIType.i32], returns: FFIType.ptr },
|
|
269
|
+
dlsym: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.ptr },
|
|
270
|
+
}).symbols
|
|
271
|
+
const cf = dlopen(CORE_FOUNDATION, {
|
|
272
|
+
CFStringCreateWithCString: { args: [FFIType.ptr, FFIType.cstring, FFIType.u32], returns: FFIType.ptr },
|
|
273
|
+
CFStringGetCString: { args: [FFIType.ptr, FFIType.ptr, FFIType.i64, FFIType.u32], returns: FFIType.bool },
|
|
274
|
+
CFDictionaryCreateMutable: { args: [FFIType.ptr, FFIType.i64, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
275
|
+
CFDictionarySetValue: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void },
|
|
276
|
+
CFDictionaryGetValue: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
277
|
+
CFNumberCreate: { args: [FFIType.ptr, FFIType.i64, FFIType.ptr], returns: FFIType.ptr },
|
|
278
|
+
CFDataCreate: { args: [FFIType.ptr, FFIType.ptr, FFIType.i64], returns: FFIType.ptr },
|
|
279
|
+
CFDataGetLength: { args: [FFIType.ptr], returns: FFIType.i64 },
|
|
280
|
+
CFDataGetBytePtr: { args: [FFIType.ptr], returns: FFIType.ptr },
|
|
281
|
+
CFErrorGetCode: { args: [FFIType.ptr], returns: FFIType.i64 },
|
|
282
|
+
CFErrorCopyDescription: { args: [FFIType.ptr], returns: FFIType.ptr },
|
|
283
|
+
}).symbols
|
|
284
|
+
const sec = dlopen(SECURITY, {
|
|
285
|
+
SecAccessControlCreateWithFlags: {
|
|
286
|
+
args: [FFIType.ptr, FFIType.ptr, FFIType.u64, FFIType.ptr],
|
|
287
|
+
returns: FFIType.ptr,
|
|
288
|
+
},
|
|
289
|
+
SecKeyCreateRandomKey: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
290
|
+
SecKeyCreateWithData: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
291
|
+
SecKeyCopyAttributes: { args: [FFIType.ptr], returns: FFIType.ptr },
|
|
292
|
+
SecKeyCopyPublicKey: { args: [FFIType.ptr], returns: FFIType.ptr },
|
|
293
|
+
SecKeyCopyExternalRepresentation: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
294
|
+
SecKeyCopyKeyExchangeResult: {
|
|
295
|
+
args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr],
|
|
296
|
+
returns: FFIType.ptr,
|
|
297
|
+
},
|
|
298
|
+
}).symbols
|
|
299
|
+
const objc = dlopen(LIBOBJC, {
|
|
300
|
+
objc_getClass: { args: [FFIType.cstring], returns: FFIType.ptr },
|
|
301
|
+
sel_registerName: { args: [FFIType.cstring], returns: FFIType.ptr },
|
|
302
|
+
objc_msgSend: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
|
|
303
|
+
}).symbols
|
|
304
|
+
// objc_msgSend takes the signature of the method it calls, so a setter needs its own binding.
|
|
305
|
+
const setObject = dlopen(LIBOBJC, {
|
|
306
|
+
objc_msgSend: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void },
|
|
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
|
|
311
|
+
libSystem.dlopen(cstring(LOCAL_AUTHENTICATION), RTLD_NOW)
|
|
312
|
+
const securityHandle = libSystem.dlopen(cstring(SECURITY), RTLD_NOW)
|
|
313
|
+
const coreHandle = libSystem.dlopen(cstring(CORE_FOUNDATION), RTLD_NOW)
|
|
314
|
+
const address = (handle: Ref | null, name: string): Ref => {
|
|
315
|
+
const found = libSystem.dlsym(handle, cstring(name))
|
|
316
|
+
if (found === null) throw new TypeVaultError('unavailable', `Security.framework has no ${name}`)
|
|
317
|
+
return found
|
|
318
|
+
}
|
|
319
|
+
const valueAt = (at: Ref): Ref => read.u64(asPointer(at))
|
|
320
|
+
return {
|
|
321
|
+
cf,
|
|
322
|
+
sec,
|
|
323
|
+
objc,
|
|
324
|
+
setObject,
|
|
325
|
+
canEvaluatePolicy,
|
|
326
|
+
constant: (name: string): Ref => valueAt(address(securityHandle, name)),
|
|
327
|
+
coreConstant: (name: string): Ref => valueAt(address(coreHandle, name)),
|
|
328
|
+
dictionaryCallbacks: [
|
|
329
|
+
address(coreHandle, 'kCFTypeDictionaryKeyCallBacks'),
|
|
330
|
+
address(coreHandle, 'kCFTypeDictionaryValueCallBacks'),
|
|
331
|
+
] as const,
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const RequestSchema = z.object({ handle: z.string(), peer: z.string(), reason: z.string() })
|
|
336
|
+
|
|
337
|
+
// Run as its own process (see touch-id.ts) so the Touch ID dialog names the program that asks: reads one exchange
|
|
338
|
+
// request from stdin and prints the shared secret.
|
|
339
|
+
if (import.meta.main) {
|
|
340
|
+
const request = RequestSchema.parse(JSON.parse(await Bun.stdin.text()))
|
|
341
|
+
try {
|
|
342
|
+
process.stdout.write(toBase64(exchangeHere(fromBase64(request.handle), fromBase64(request.peer), request.reason)))
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (!(error instanceof TypeVaultError)) throw error
|
|
345
|
+
process.stderr.write(`${error.code}: ${error.message}\n`)
|
|
346
|
+
process.exitCode = 1
|
|
347
|
+
}
|
|
348
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
/** 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
|
+
|
|
84
|
+
export async function openWithTouchId(env: Env, seal: TouchIdSeal, reason = 'unlock your vault'): Promise<Uint8Array> {
|
|
85
|
+
const { exchangeWithEnclave } = await import('./secure-enclave')
|
|
86
|
+
return openFromEnclave(seal, (handle, ephemeral) => exchangeWithEnclave(env, handle, ephemeral, reason))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sealingKey(shared: Uint8Array, ephemeral: Uint8Array): Promise<CryptoKey> {
|
|
90
|
+
const raw = hkdf(sha256, shared, ephemeral, utf8('typevault touch id'), 32)
|
|
91
|
+
return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
|
|
92
|
+
}
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -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 {
|
|
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)),
|