typevault 0.6.0 → 0.7.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 +1 -1
- package/src/access/scoped.ts +10 -6
- package/src/access/sealed-access.ts +9 -5
- package/src/access/sealed.ts +12 -8
- package/src/audit/log.ts +71 -18
- package/src/cli/commands/admin.ts +2 -1
- package/src/cli/commands/grant.ts +7 -1
- package/src/cli/commands/members.ts +22 -6
- package/src/cli/context.ts +13 -6
- package/src/cli/index.ts +5 -3
- package/src/core/admin.ts +33 -16
- package/src/core/entries.ts +7 -2
- package/src/core/init.ts +2 -1
- package/src/core/keyring.ts +5 -1
- package/src/core/layout.ts +13 -11
- package/src/core/owner-trust.ts +97 -0
- package/src/core/rotate.ts +67 -6
- package/src/core/secure-enclave.ts +61 -17
- package/src/core/state.ts +21 -23
- package/src/core/touch-id.ts +6 -0
- package/src/core/vault.ts +46 -10
- package/src/daemon/admin-routes.ts +23 -15
- package/src/daemon/agent-routes.ts +11 -7
- package/src/daemon/daemon.ts +19 -6
- package/src/daemon/requests.ts +35 -23
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
|
|
6
|
+
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
7
|
+
import { canonicalJson, utf8 } from './encoding'
|
|
8
|
+
import { TypeVaultError } from './errors'
|
|
9
|
+
import { atomicWrite, ensureDir } from './fsx'
|
|
10
|
+
import { readJsonFile } from './json-file'
|
|
11
|
+
import type { Layout } from './layout'
|
|
12
|
+
import { holdLock } from './lock'
|
|
13
|
+
|
|
14
|
+
export const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
|
|
15
|
+
const Link = z.object({ from: z.string(), to: PublicKeySchema, sig: z.string() })
|
|
16
|
+
const AuditChain = z.object({ chain: z.string(), sig: z.string() })
|
|
17
|
+
const Owner = PublicKeySchema.extend({ handovers: z.array(Link).default([]), audit: AuditChain.optional() })
|
|
18
|
+
type Link = z.infer<typeof Link>
|
|
19
|
+
type AuditChain = z.infer<typeof AuditChain>
|
|
20
|
+
export type Owner = z.infer<typeof Owner>
|
|
21
|
+
const Trust = z.object({ ownerSignPublic: z.string() })
|
|
22
|
+
|
|
23
|
+
const linkBytes = (from: string, to: PublicKey) => utf8(canonicalJson({ purpose: 'typevault:handover', from, to }))
|
|
24
|
+
const auditBytes = (chain: string, signPublic: string) =>
|
|
25
|
+
utf8(canonicalJson({ purpose: 'typevault:audit-chain', chain, signPublic }))
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The vault's audit identity: its first owner key, which names the state-directory audit chain. Each owner signs it
|
|
29
|
+
* again, so a machine that trusts the current owner trusts it without trusting the history in between. Until the first
|
|
30
|
+
* rotation it is the current owner key itself.
|
|
31
|
+
*/
|
|
32
|
+
export const auditChainOf = (owner: Owner): string => owner.audit?.chain ?? owner.signPublic
|
|
33
|
+
|
|
34
|
+
/** The audit identity `chain`, endorsed by the owner `key` that holds `signPublic`. */
|
|
35
|
+
export const signAuditChain = (chain: string, key: SecretKey, signPublic: string): AuditChain => ({
|
|
36
|
+
chain,
|
|
37
|
+
sig: sign(key.signSecret, auditBytes(chain, signPublic)),
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
export function handover(from: Owner, signing: SecretKey, to: PublicKey): readonly Link[] {
|
|
41
|
+
return [
|
|
42
|
+
...from.handovers,
|
|
43
|
+
{ from: from.signPublic, to, sig: sign(signing.signSecret, linkBytes(from.signPublic, to)) },
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function ownerDoc(key: PublicKey, handovers: readonly Link[] = [], audit?: AuditChain): string {
|
|
48
|
+
return `${JSON.stringify({ v: 1, ...key, handovers, ...(audit === undefined ? {} : { audit }) }, null, 2)}\n`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readOwner(layout: Layout): Owner {
|
|
52
|
+
return readOwnerFile(layout.ownerFile)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function readOwnerFile(path: string): Owner {
|
|
56
|
+
if (!existsSync(path)) throw new TypeVaultError('not_found', `no vault at ${dirname(path)} (run typevault init)`)
|
|
57
|
+
const owner = readJsonFile(path, Owner)
|
|
58
|
+
const seen = new Set([owner.signPublic])
|
|
59
|
+
let expected = owner.signPublic
|
|
60
|
+
for (const { from, to, sig } of owner.handovers.toReversed()) {
|
|
61
|
+
if (to.signPublic !== expected || seen.has(from) || !verifySignature(from, linkBytes(from, to), sig)) {
|
|
62
|
+
throw new TypeVaultError('tampered', 'invalid vault owner handover')
|
|
63
|
+
}
|
|
64
|
+
seen.add(from)
|
|
65
|
+
expected = from
|
|
66
|
+
}
|
|
67
|
+
const last = owner.handovers.at(-1)
|
|
68
|
+
if (last !== undefined && last.to.recipient !== owner.recipient)
|
|
69
|
+
throw new TypeVaultError('tampered', 'invalid handover recipient')
|
|
70
|
+
if (owner.audit === undefined) {
|
|
71
|
+
if (owner.handovers.length > 0)
|
|
72
|
+
throw new TypeVaultError('tampered', 'a rotated owner.json must sign its audit chain')
|
|
73
|
+
} else if (!verifySignature(owner.signPublic, auditBytes(owner.audit.chain, owner.signPublic), owner.audit.sig)) {
|
|
74
|
+
throw new TypeVaultError('tampered', 'invalid vault audit chain signature')
|
|
75
|
+
}
|
|
76
|
+
return owner
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Both pins are forward-only. A static deployment pin may be an ancestor, but cannot override a newer local pin. */
|
|
80
|
+
export function trustOwner(layout: Layout, owner: Owner, pinned: string | undefined): void {
|
|
81
|
+
const endorses = (key: string) => key === owner.signPublic || owner.handovers.some(({ from }) => from === key)
|
|
82
|
+
if (pinned && !endorses(pinned)) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
|
|
83
|
+
const local = () => (existsSync(layout.trustFile) ? readJsonFile(layout.trustFile, Trust).ownerSignPublic : undefined)
|
|
84
|
+
if (local() === owner.signPublic) return
|
|
85
|
+
// Different processes may finish verifying different generations concurrently. Never overwrite a newer pin.
|
|
86
|
+
ensureDir(layout.root, 0o700)
|
|
87
|
+
const release = holdLock(`${layout.trustFile}.lock`)
|
|
88
|
+
if (!release) throw new TypeVaultError('locked', 'another process is updating owner trust; retry')
|
|
89
|
+
try {
|
|
90
|
+
const current = local()
|
|
91
|
+
if (current !== undefined && !endorses(current))
|
|
92
|
+
throw new TypeVaultError('tampered', 'vault owner changed without a trusted handover')
|
|
93
|
+
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
94
|
+
} finally {
|
|
95
|
+
release()
|
|
96
|
+
}
|
|
97
|
+
}
|
package/src/core/rotate.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
|
|
1
3
|
import { encodeSecretKey, generateSecretKey, publicKeyOf, seal, type SecretKey } from './crypto'
|
|
2
|
-
import { utf8 } from './encoding'
|
|
4
|
+
import { canonicalJson, utf8 } from './encoding'
|
|
3
5
|
import { sealEntry, type SignerRef, signerOf } from './entries'
|
|
4
6
|
import { TypeVaultError } from './errors'
|
|
5
|
-
import { wrapPath } from './keyring'
|
|
6
|
-
import {
|
|
7
|
+
import { ownerWrapPath, wrapPath } from './keyring'
|
|
8
|
+
import { auditChainOf, handover, ownerDoc, readOwner, signAuditChain } from './owner-trust'
|
|
9
|
+
import { type Tier, tiersDoc, includersOf, reach, type VaultState, membersDoc, signersDoc, ceilingsDoc } from './state'
|
|
7
10
|
import type { Txn } from './txn'
|
|
8
|
-
import type { Vault } from './vault'
|
|
11
|
+
import type { ScanProblem, StoredEntry, Vault } from './vault'
|
|
9
12
|
|
|
10
13
|
export type RotateContext = {
|
|
11
14
|
readonly vault: Vault
|
|
@@ -17,6 +20,51 @@ export type RotateContext = {
|
|
|
17
20
|
readonly exposed: boolean
|
|
18
21
|
}
|
|
19
22
|
|
|
23
|
+
export async function rotateOwner(context: RotateContext): Promise<readonly string[]> {
|
|
24
|
+
const { vault, state, txn } = context
|
|
25
|
+
// Git doesn't take the vault lock, so owner.json can change under a rotation. The handover extends the owner document
|
|
26
|
+
// this rotation validated, and is staged only while owner.json still is exactly that document.
|
|
27
|
+
const previous = { recipient: state.owner.recipient, signPublic: state.owner.signPublic, handovers: state.handovers }
|
|
28
|
+
const unchanged = () => {
|
|
29
|
+
const current = readOwner(vault.layout)
|
|
30
|
+
const { recipient, signPublic, handovers } = current
|
|
31
|
+
if (
|
|
32
|
+
canonicalJson({ recipient, signPublic, handovers }) !== canonicalJson(previous) ||
|
|
33
|
+
auditChainOf(current) !== state.origin
|
|
34
|
+
)
|
|
35
|
+
throw new TypeVaultError('conflict', 'owner.json changed while rotating the owner key; pull and retry')
|
|
36
|
+
}
|
|
37
|
+
unchanged()
|
|
38
|
+
const owner = await generateSecretKey({ kind: 'owner' })
|
|
39
|
+
const pub = await publicKeyOf(owner)
|
|
40
|
+
const encoded = utf8(encodeSecretKey(owner))
|
|
41
|
+
for (const [name, member] of Object.entries(state.members)) {
|
|
42
|
+
if (member.owner) txn.put(ownerWrapPath(name), await seal([member.recipient], encoded))
|
|
43
|
+
}
|
|
44
|
+
txn.put('members.json', membersDoc(state.members, owner, state.seqs.members + 1))
|
|
45
|
+
txn.put('signers.json', signersDoc(state.signers, owner, state.seqs.signers + 1))
|
|
46
|
+
txn.put('ceilings.json', ceilingsDoc(state.ceilings, owner, state.seqs.ceilings + 1))
|
|
47
|
+
const affected = await rotateTiers({ ...context, owner, state: { ...state, owner: pub } }, Object.keys(state.tiers))
|
|
48
|
+
unchanged()
|
|
49
|
+
// The new owner endorses the same audit chain, so the vault's committed audit anchors keep their name.
|
|
50
|
+
const audit = signAuditChain(state.origin, owner, pub.signPublic)
|
|
51
|
+
txn.put('owner.json', ownerDoc(pub, handover(previous, context.owner, pub), audit))
|
|
52
|
+
return affected
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const unaccountedEntryFiles = (
|
|
56
|
+
vault: Vault,
|
|
57
|
+
entries: readonly StoredEntry[],
|
|
58
|
+
problems: readonly ScanProblem[],
|
|
59
|
+
): readonly string[] => {
|
|
60
|
+
const accounted = new Set([
|
|
61
|
+
...entries.map(({ envelope }) => `${envelope.id}.json`),
|
|
62
|
+
...problems.map(({ file }) => file),
|
|
63
|
+
])
|
|
64
|
+
const files = existsSync(vault.layout.entries) ? readdirSync(vault.layout.entries) : []
|
|
65
|
+
return files.filter((file) => file.endsWith('.json') && !accounted.has(file))
|
|
66
|
+
}
|
|
67
|
+
|
|
20
68
|
const signedBy = (signer: SignerRef, tier: string): boolean =>
|
|
21
69
|
(signer.kind === 'tier' && signer.tier === tier) ||
|
|
22
70
|
(signer.kind === 'cert' && signer.cert.issuer.kind === 'tier' && signer.cert.issuer.tier === tier)
|
|
@@ -29,7 +77,8 @@ const signedBy = (signer: SignerRef, tier: string): boolean =>
|
|
|
29
77
|
*/
|
|
30
78
|
export async function rotateTiers(context: RotateContext, names: readonly string[]): Promise<readonly string[]> {
|
|
31
79
|
const { vault, owner, state, txn, exposed } = context
|
|
32
|
-
|
|
80
|
+
const ownerChanged = state.owner.signPublic !== vault.state.owner.signPublic
|
|
81
|
+
if (names.length === 0 && !ownerChanged) return []
|
|
33
82
|
const rotated = new Map<string, { readonly key: SecretKey; readonly tier: Tier }>()
|
|
34
83
|
for (const name of new Set(names)) {
|
|
35
84
|
const meta = state.tiers[name]
|
|
@@ -71,7 +120,19 @@ export async function rotateTiers(context: RotateContext, names: readonly string
|
|
|
71
120
|
const reached = new Set([...rotated.keys()].flatMap((name) => [...reach(state.tiers, name)]))
|
|
72
121
|
const affected: string[] = []
|
|
73
122
|
const now = new Date().toISOString()
|
|
74
|
-
const { entries } = await vault.scan()
|
|
123
|
+
const { entries, problems } = await vault.scan()
|
|
124
|
+
// A scan leaves out entries no held key opens. An owner rotation must re-seal every one of them, or the ones it misses
|
|
125
|
+
// stay sealed to the old keys alone, so each entry file has to be read or reported.
|
|
126
|
+
const unopened = ownerChanged ? unaccountedEntryFiles(vault, entries, problems) : []
|
|
127
|
+
if (ownerChanged && problems.length + unopened.length > 0) {
|
|
128
|
+
const files = [...problems, ...unopened.map((file) => ({ file, reason: 'its tier key cannot be opened' }))]
|
|
129
|
+
.map(({ file, reason }) => `${file} (${reason})`)
|
|
130
|
+
.join(', ')
|
|
131
|
+
throw new TypeVaultError(
|
|
132
|
+
'tampered',
|
|
133
|
+
`cannot rotate the owner while entries are unreadable: ${files}. Run typevault doctor; move a file you can't vouch for out of entries/ (or restore it from git), then retry`,
|
|
134
|
+
)
|
|
135
|
+
}
|
|
75
136
|
for (const { envelope, payload } of entries) {
|
|
76
137
|
const reachable = reached.has(envelope.tier)
|
|
77
138
|
if (!reachable && ![...rotated.keys()].some((name) => signedBy(envelope.signer, name))) continue
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { dlopen, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'
|
|
2
|
-
import {
|
|
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
|
|
49
|
-
* in a child started
|
|
50
|
-
*
|
|
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 =
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
|
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: [
|
package/src/core/state.ts
CHANGED
|
@@ -5,9 +5,9 @@ import { z } from 'zod'
|
|
|
5
5
|
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
6
6
|
import { canonicalJson, type Json, utf8 } from './encoding'
|
|
7
7
|
import { TypeVaultError } from './errors'
|
|
8
|
-
import { atomicWrite, ensureDir } from './fsx'
|
|
9
8
|
import { readJsonFile } from './json-file'
|
|
10
9
|
import type { Layout } from './layout'
|
|
10
|
+
import { auditChainOf, type Owner, PublicKeySchema, readOwner as verifiedOwner, trustOwner } from './owner-trust'
|
|
11
11
|
import { RevisionMarks } from './revisions'
|
|
12
12
|
|
|
13
13
|
export type Tier = {
|
|
@@ -42,6 +42,10 @@ export type ManifestSeqs = {
|
|
|
42
42
|
|
|
43
43
|
export type VaultState = {
|
|
44
44
|
readonly owner: PublicKey
|
|
45
|
+
/** The vault's first owner key, its audit identity: signed by the current owner and pinned on this machine. */
|
|
46
|
+
readonly origin: string
|
|
47
|
+
/** The verified handover chain that led to `owner`. */
|
|
48
|
+
readonly handovers: Owner['handovers']
|
|
45
49
|
/** Each manifest's sequence number: every signed change bumps it, and a lower one is a rollback. */
|
|
46
50
|
readonly seqs: ManifestSeqs
|
|
47
51
|
readonly tiers: Tiers
|
|
@@ -61,7 +65,6 @@ export function parseMemberName(name: string): string {
|
|
|
61
65
|
return name
|
|
62
66
|
}
|
|
63
67
|
|
|
64
|
-
const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
|
|
65
68
|
const TierSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
|
|
66
69
|
const seq = z.number().int().positive()
|
|
67
70
|
const TiersBody = z.object({ v: z.literal(1), seq, tiers: z.record(z.string(), TierSchema) })
|
|
@@ -83,7 +86,6 @@ const SignersBody = z.object({
|
|
|
83
86
|
signers: z.record(z.string(), z.object({ signPublic: z.string(), tiers: z.array(z.string()) })),
|
|
84
87
|
})
|
|
85
88
|
const CeilingsBody = z.object({ v: z.literal(1), seq, ceilings: z.record(z.string(), z.string()) })
|
|
86
|
-
const TrustSchema = z.object({ ownerSignPublic: z.string() })
|
|
87
89
|
|
|
88
90
|
export const signedDoc = (body: Json, key: SecretKey): string =>
|
|
89
91
|
`${JSON.stringify({ body, sig: sign(key.signSecret, utf8(canonicalJson(body))) }, null, 2)}\n`
|
|
@@ -106,24 +108,6 @@ function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: P
|
|
|
106
108
|
return parsed.data
|
|
107
109
|
}
|
|
108
110
|
|
|
109
|
-
/** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
|
|
110
|
-
function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<string, string | undefined>>): void {
|
|
111
|
-
const pinned = env['TYPEVAULT_OWNER']
|
|
112
|
-
if (pinned !== undefined && pinned !== '') {
|
|
113
|
-
if (pinned !== owner.signPublic) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
|
|
114
|
-
return
|
|
115
|
-
}
|
|
116
|
-
if (!existsSync(layout.trustFile)) {
|
|
117
|
-
ensureDir(layout.root, 0o700)
|
|
118
|
-
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
119
|
-
return
|
|
120
|
-
}
|
|
121
|
-
const trust = readJsonFile(layout.trustFile, TrustSchema)
|
|
122
|
-
if (trust.ownerSignPublic !== owner.signPublic) {
|
|
123
|
-
throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
111
|
export function readOwner(layout: Layout): PublicKey {
|
|
128
112
|
if (!existsSync(layout.ownerFile))
|
|
129
113
|
throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
|
|
@@ -131,14 +115,25 @@ export function readOwner(layout: Layout): PublicKey {
|
|
|
131
115
|
}
|
|
132
116
|
|
|
133
117
|
export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
|
|
134
|
-
const owner =
|
|
135
|
-
checkTrust(layout, owner, env)
|
|
118
|
+
const owner = verifiedOwner(layout)
|
|
136
119
|
const tiers = readSigned(layout.tiersFile, TiersBody, owner)
|
|
137
120
|
const members = readSigned(layout.membersFile, MembersBody, owner)
|
|
138
121
|
const signers = readSigned(layout.signersFile, SignersBody, owner)
|
|
139
122
|
const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, owner)
|
|
140
123
|
// An older, still validly signed manifest from git history would resurrect removed signers or ceilings.
|
|
141
124
|
const marks = new RevisionMarks(layout.revisionsFile)
|
|
125
|
+
if (!marks.accept('owner:handovers', owner.handovers.length)) {
|
|
126
|
+
throw new TypeVaultError('tampered', 'owner.json has fewer handovers than this machine has seen')
|
|
127
|
+
}
|
|
128
|
+
// The current owner signs the audit chain, so trusting that owner authenticates it. A machine also pins the first
|
|
129
|
+
// chain it trusted, so no later owner.json can move its audit anchors elsewhere.
|
|
130
|
+
const auditChain = auditChainOf(owner)
|
|
131
|
+
const pinned = `owner:audit:${auditChain}`
|
|
132
|
+
if (!marks.allows('owner:audit', 0) && marks.allows(pinned, 0)) {
|
|
133
|
+
throw new TypeVaultError('tampered', 'owner.json names a different audit chain than this machine trusted')
|
|
134
|
+
}
|
|
135
|
+
marks.accept('owner:audit', 1)
|
|
136
|
+
marks.accept(pinned, 1)
|
|
142
137
|
for (const [name, doc] of [
|
|
143
138
|
['tiers', tiers],
|
|
144
139
|
['members', members],
|
|
@@ -152,9 +147,12 @@ export function loadState(layout: Layout, env: Readonly<Record<string, string |
|
|
|
152
147
|
)
|
|
153
148
|
}
|
|
154
149
|
}
|
|
150
|
+
trustOwner(layout, owner, env['TYPEVAULT_OWNER'])
|
|
155
151
|
marks.save()
|
|
156
152
|
return {
|
|
157
153
|
owner,
|
|
154
|
+
origin: auditChain,
|
|
155
|
+
handovers: owner.handovers,
|
|
158
156
|
seqs: { tiers: tiers.seq, members: members.seq, signers: signers.seq, ceilings: ceilings.seq },
|
|
159
157
|
tiers: tiers.tiers,
|
|
160
158
|
members: members.members,
|
package/src/core/touch-id.ts
CHANGED
|
@@ -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))
|
package/src/core/vault.ts
CHANGED
|
@@ -86,9 +86,29 @@ export function resolveName(tiers: Tiers, copies: readonly StoredEntry[]): Store
|
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
/** An opened vault directory plus the keys this process holds. All reads and writes go through the vault lock. */
|
|
89
|
+
const pendingTxn = (layout: Layout): boolean => existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Runs `read` under the shared vault lock, never on a half-applied transaction: a rotation re-signs manifests and wraps
|
|
93
|
+
* before owner.json, so an unlocked or unrecovered read could mix generations. A transaction left by a writer that died
|
|
94
|
+
* is rolled forward first; one that appears while waiting for the lock sends the read around again.
|
|
95
|
+
*/
|
|
96
|
+
export async function readSnapshot<T>(layout: Layout, env: Env, read: () => Promise<T>): Promise<T> {
|
|
97
|
+
// Recovery rewrites the journal, and the vault lock doesn't reach another host sharing this state directory.
|
|
98
|
+
refuseForeignDaemon(layout, env)
|
|
99
|
+
for (;;) {
|
|
100
|
+
if (pendingTxn(layout)) await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
|
|
101
|
+
const snapshot = await withLock(layout.lockFile, 'shared', async () =>
|
|
102
|
+
pendingTxn(layout) ? undefined : { value: await read() },
|
|
103
|
+
)
|
|
104
|
+
if (snapshot !== undefined) return snapshot.value
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
89
108
|
export class Vault {
|
|
90
109
|
readonly layout: Layout
|
|
91
110
|
readonly #keys: readonly SecretKey[]
|
|
111
|
+
readonly #openedOwner: string
|
|
92
112
|
readonly #env: Env
|
|
93
113
|
readonly #member: string | undefined
|
|
94
114
|
#state: VaultState
|
|
@@ -98,6 +118,7 @@ export class Vault {
|
|
|
98
118
|
this.layout = layout
|
|
99
119
|
this.#keys = keys
|
|
100
120
|
this.#env = env
|
|
121
|
+
this.#openedOwner = state.owner.signPublic
|
|
101
122
|
this.#member = member
|
|
102
123
|
this.#state = state
|
|
103
124
|
this.#keyring = new Keyring(layout, state, keys)
|
|
@@ -105,21 +126,24 @@ export class Vault {
|
|
|
105
126
|
|
|
106
127
|
/** Opens the vault with `keys`. An owner member's key also brings the owner key it unwraps. */
|
|
107
128
|
static async open(layout: Layout, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
await
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
|
|
116
|
-
return new Vault(layout, all, env, state, member?.name)
|
|
129
|
+
return readSnapshot(layout, env, async () => {
|
|
130
|
+
const state = loadState(layout, env)
|
|
131
|
+
const owner = await unwrapOwner(layout, state, keys)
|
|
132
|
+
const [member] = await heldMembers(state, keys)
|
|
133
|
+
const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
|
|
134
|
+
return new Vault(layout, all, env, state, member?.name)
|
|
135
|
+
})
|
|
117
136
|
}
|
|
118
137
|
|
|
119
138
|
get state(): VaultState {
|
|
120
139
|
return this.#state
|
|
121
140
|
}
|
|
122
141
|
|
|
142
|
+
/** The audit anchors file this vault's validated state names: the only one its audit writes checkpoint to. */
|
|
143
|
+
get anchorsFile(): string {
|
|
144
|
+
return this.layout.anchorsFileFor(this.#state.origin)
|
|
145
|
+
}
|
|
146
|
+
|
|
123
147
|
get keyring(): Keyring {
|
|
124
148
|
return this.#keyring
|
|
125
149
|
}
|
|
@@ -135,8 +159,20 @@ export class Vault {
|
|
|
135
159
|
|
|
136
160
|
/** Re-reads owner-signed state; call after another process may have changed it. */
|
|
137
161
|
refresh(): void {
|
|
162
|
+
this.reload()
|
|
163
|
+
if (this.#state.owner.signPublic !== this.#openedOwner) {
|
|
164
|
+
throw new TypeVaultError(
|
|
165
|
+
'locked',
|
|
166
|
+
'the vault owner rotated; reopen the vault (for a session, run typevault lock then typevault unlock)',
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Apply committed state without transferring an already-open handle's authority across a handover. */
|
|
172
|
+
reload(): void {
|
|
138
173
|
this.#state = loadState(this.layout, this.#env)
|
|
139
|
-
|
|
174
|
+
const keys = this.#state.owner.signPublic === this.#openedOwner ? this.#keys : []
|
|
175
|
+
this.#keyring = new Keyring(this.layout, this.#state, keys)
|
|
140
176
|
}
|
|
141
177
|
|
|
142
178
|
/** Every entry this process can open. Untrustworthy files are reported, never returned. */
|
|
@@ -66,13 +66,17 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
66
66
|
label: body.label,
|
|
67
67
|
ceiling: ceiling.name,
|
|
68
68
|
})
|
|
69
|
-
await appendAudit(
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
69
|
+
await appendAudit(
|
|
70
|
+
context.vault.layout,
|
|
71
|
+
{
|
|
72
|
+
action: 'grant.issue',
|
|
73
|
+
mode: 'live',
|
|
74
|
+
grant: record.id,
|
|
75
|
+
label: record.label,
|
|
76
|
+
tiers: record.tiers,
|
|
77
|
+
},
|
|
78
|
+
context.vault.anchorsFile,
|
|
79
|
+
)
|
|
76
80
|
return json({ token, id: record.id, exp: record.exp })
|
|
77
81
|
},
|
|
78
82
|
'/v1/grants': async () => json(context.grants.list().filter(ownedBy(ceiling, await currentTier(context, ceiling)))),
|
|
@@ -84,14 +88,18 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
|
|
|
84
88
|
(record) => owned(record) && (record.id === id || (label !== undefined && record.label === label)),
|
|
85
89
|
)
|
|
86
90
|
for (const grant of revoked) context.sessions.delete(grant)
|
|
87
|
-
await appendAudit(
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
91
|
+
await appendAudit(
|
|
92
|
+
context.vault.layout,
|
|
93
|
+
{
|
|
94
|
+
action: 'grant.revoke',
|
|
95
|
+
mode: 'live',
|
|
96
|
+
entries: [],
|
|
97
|
+
tiers: [],
|
|
98
|
+
...(label === undefined ? {} : { label }),
|
|
99
|
+
...(id === undefined ? {} : { grant: id }),
|
|
100
|
+
},
|
|
101
|
+
context.vault.anchorsFile,
|
|
102
|
+
)
|
|
95
103
|
return json({ revoked })
|
|
96
104
|
},
|
|
97
105
|
'/v1/audit': async (request) => {
|
|
@@ -167,13 +167,17 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
167
167
|
ceiling: grant.record.ceiling,
|
|
168
168
|
})
|
|
169
169
|
const { record } = issued
|
|
170
|
-
await appendAudit(
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
170
|
+
await appendAudit(
|
|
171
|
+
context.vault.layout,
|
|
172
|
+
{
|
|
173
|
+
action: 'grant.derive',
|
|
174
|
+
mode: 'live',
|
|
175
|
+
grant: record.id,
|
|
176
|
+
label: record.label,
|
|
177
|
+
tiers: record.tiers,
|
|
178
|
+
},
|
|
179
|
+
context.vault.anchorsFile,
|
|
180
|
+
)
|
|
177
181
|
return json({ token: issued.token, id: record.id, exp: record.exp })
|
|
178
182
|
},
|
|
179
183
|
'/v1/request': async (request) => {
|