typevault 0.1.0 → 0.3.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/README.md +156 -115
- package/package.json +14 -2
- package/src/access/env.ts +77 -17
- package/src/access/keys.ts +14 -14
- package/src/access/schemas.ts +6 -12
- package/src/access/scope.ts +14 -9
- package/src/access/scoped.ts +118 -44
- package/src/access/sealed-access.ts +50 -23
- package/src/access/sealed.ts +56 -31
- package/src/access/types.ts +27 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +28 -12
- package/src/cli/commands/admin.ts +93 -48
- package/src/cli/commands/daemon.ts +42 -17
- package/src/cli/commands/entries.ts +195 -60
- package/src/cli/commands/grant.ts +24 -22
- package/src/cli/commands/members.ts +307 -0
- package/src/cli/commands/run.ts +191 -44
- package/src/cli/context.ts +163 -15
- package/src/cli/index.ts +33 -5
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +79 -0
- package/src/core/admin.ts +144 -76
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +15 -16
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +8 -2
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +87 -0
- package/src/core/identity.ts +132 -0
- package/src/core/init.ts +73 -23
- package/src/core/json-file.ts +20 -0
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +143 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +150 -50
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +11 -6
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +102 -54
- package/src/core/txn.ts +9 -7
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +51 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +31 -11
- package/src/daemon/client.ts +24 -2
- package/src/daemon/daemon.ts +218 -33
- package/src/daemon/grants.ts +25 -7
- package/src/daemon/http.ts +11 -2
- package/src/daemon/live-access.ts +8 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +75 -51
- package/src/daemon/spawn.ts +218 -9
- package/src/export/1password.ts +157 -0
- package/src/import/1password-live.ts +399 -0
- package/src/import/1password.ts +26 -5
- package/src/import/bitwarden.ts +3 -3
- package/src/import/csv.ts +1 -1
- package/src/import/dotenv.ts +4 -3
- package/src/import/index.ts +1 -0
- package/src/import/keepass.ts +2 -2
- package/src/import/lastpass.ts +2 -2
- package/src/import/shared.ts +67 -10
- package/src/import/typeclaw.ts +2 -2
- package/src/import/types.ts +1 -1
- package/src/index.ts +58 -0
- package/src/owner.ts +156 -0
- package/src/prompt/browser.ts +48 -15
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +27 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +7 -4
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
package/src/core/state.ts
CHANGED
|
@@ -1,100 +1,147 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
|
|
3
3
|
import { z } from 'zod'
|
|
4
4
|
|
|
5
5
|
import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
|
|
6
|
-
import { canonicalJson,
|
|
6
|
+
import { canonicalJson, type Json, utf8 } from './encoding'
|
|
7
7
|
import { TypeVaultError } from './errors'
|
|
8
|
-
import { atomicWrite } from './fsx'
|
|
8
|
+
import { atomicWrite, ensureDir } from './fsx'
|
|
9
|
+
import { readJsonFile } from './json-file'
|
|
9
10
|
import type { Layout } from './layout'
|
|
10
11
|
import { RevisionMarks } from './revisions'
|
|
11
12
|
|
|
12
|
-
export type
|
|
13
|
+
export type Tier = {
|
|
13
14
|
readonly includes: readonly string[]
|
|
14
15
|
readonly gen: number
|
|
15
16
|
readonly recipient: string
|
|
16
17
|
readonly signPublic: string
|
|
17
18
|
}
|
|
18
|
-
export type Signer = { readonly signPublic: string; readonly
|
|
19
|
-
export type
|
|
19
|
+
export type Signer = { readonly signPublic: string; readonly tiers: readonly string[] }
|
|
20
|
+
export type Tiers = Readonly<Record<string, Tier>>
|
|
20
21
|
|
|
21
|
-
/**
|
|
22
|
-
export type
|
|
22
|
+
/** A person (unlocks with a password) or a machine (holds its key directly). */
|
|
23
|
+
export type MemberKind = 'human' | 'machine'
|
|
24
|
+
export type Member = {
|
|
25
|
+
readonly kind: MemberKind
|
|
26
|
+
readonly recipient: string
|
|
27
|
+
readonly signPublic: string
|
|
28
|
+
/** Owners get the owner key wrapped to them. */
|
|
29
|
+
readonly owner: boolean
|
|
30
|
+
/** Tiers whose key is wrapped to this member. */
|
|
31
|
+
readonly tiers: readonly string[]
|
|
32
|
+
}
|
|
33
|
+
export type Members = Readonly<Record<string, Member>>
|
|
34
|
+
|
|
35
|
+
/** Everything public about a vault. Tiers, members, signers and ceilings are signed by the owner key. */
|
|
36
|
+
export type ManifestSeqs = {
|
|
37
|
+
readonly tiers: number
|
|
38
|
+
readonly members: number
|
|
39
|
+
readonly signers: number
|
|
40
|
+
readonly ceilings: number
|
|
41
|
+
}
|
|
23
42
|
|
|
24
43
|
export type VaultState = {
|
|
25
|
-
readonly
|
|
44
|
+
readonly owner: PublicKey
|
|
26
45
|
/** Each manifest's sequence number: every signed change bumps it, and a lower one is a rollback. */
|
|
27
46
|
readonly seqs: ManifestSeqs
|
|
28
|
-
readonly
|
|
47
|
+
readonly tiers: Tiers
|
|
48
|
+
readonly members: Members
|
|
29
49
|
readonly signers: Readonly<Record<string, Signer>>
|
|
30
50
|
readonly ceilings: Readonly<Record<string, string>>
|
|
31
51
|
}
|
|
32
52
|
|
|
33
|
-
const
|
|
34
|
-
export function
|
|
35
|
-
if (!
|
|
53
|
+
const TIER_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
54
|
+
export function parseTierName(name: string): string {
|
|
55
|
+
if (!TIER_NAME.test(name)) throw new TypeVaultError('invalid', `invalid tier name "${name}" (use [a-z0-9-])`)
|
|
56
|
+
return name
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function parseMemberName(name: string): string {
|
|
60
|
+
if (!TIER_NAME.test(name)) throw new TypeVaultError('invalid', `invalid member name "${name}" (use [a-z0-9-])`)
|
|
36
61
|
return name
|
|
37
62
|
}
|
|
38
63
|
|
|
39
64
|
const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
|
|
40
|
-
const
|
|
65
|
+
const TierSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
|
|
41
66
|
const seq = z.number().int().positive()
|
|
42
|
-
const
|
|
67
|
+
const TiersBody = z.object({ v: z.literal(1), seq, tiers: z.record(z.string(), TierSchema) })
|
|
68
|
+
const MembersBody = z.object({
|
|
69
|
+
v: z.literal(1),
|
|
70
|
+
seq,
|
|
71
|
+
members: z.record(
|
|
72
|
+
z.string(),
|
|
73
|
+
PublicKeySchema.extend({
|
|
74
|
+
kind: z.enum(['human', 'machine']),
|
|
75
|
+
owner: z.boolean(),
|
|
76
|
+
tiers: z.array(z.string()),
|
|
77
|
+
}),
|
|
78
|
+
),
|
|
79
|
+
})
|
|
43
80
|
const SignersBody = z.object({
|
|
44
81
|
v: z.literal(1),
|
|
45
82
|
seq,
|
|
46
|
-
signers: z.record(z.string(), z.object({ signPublic: z.string(),
|
|
83
|
+
signers: z.record(z.string(), z.object({ signPublic: z.string(), tiers: z.array(z.string()) })),
|
|
47
84
|
})
|
|
48
85
|
const CeilingsBody = z.object({ v: z.literal(1), seq, ceilings: z.record(z.string(), z.string()) })
|
|
49
|
-
const TrustSchema = z.object({
|
|
86
|
+
const TrustSchema = z.object({ ownerSignPublic: z.string() })
|
|
50
87
|
|
|
51
88
|
export const signedDoc = (body: Json, key: SecretKey): string =>
|
|
52
89
|
`${JSON.stringify({ body, sig: sign(key.signSecret, utf8(canonicalJson(body))) }, null, 2)}\n`
|
|
53
90
|
|
|
54
|
-
export const
|
|
91
|
+
export const tiersDoc = (tiers: Tiers, key: SecretKey, seq: number): string => signedDoc({ v: 1, seq, tiers }, key)
|
|
92
|
+
export const membersDoc = (members: Members, key: SecretKey, seq: number): string =>
|
|
93
|
+
signedDoc({ v: 1, seq, members }, key)
|
|
55
94
|
export const signersDoc = (signers: VaultState['signers'], key: SecretKey, seq: number): string =>
|
|
56
95
|
signedDoc({ v: 1, seq, signers }, key)
|
|
57
96
|
export const ceilingsDoc = (ceilings: VaultState['ceilings'], key: SecretKey, seq: number): string =>
|
|
58
97
|
signedDoc({ v: 1, seq, ceilings }, key)
|
|
59
98
|
|
|
60
|
-
function readSigned<T extends Json>(path: string, schema: z.ZodType<T>,
|
|
61
|
-
const doc = z.object({ body: z.json(), sig: z.string() })
|
|
62
|
-
if (!verifySignature(
|
|
63
|
-
throw new TypeVaultError('tampered', `${path} is not signed by the vault
|
|
99
|
+
function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: PublicKey): T {
|
|
100
|
+
const doc = readJsonFile(path, z.object({ body: z.json(), sig: z.string() }))
|
|
101
|
+
if (!verifySignature(owner.signPublic, utf8(canonicalJson(doc.body)), doc.sig)) {
|
|
102
|
+
throw new TypeVaultError('tampered', `${path} is not signed by the vault owner`)
|
|
64
103
|
}
|
|
65
|
-
|
|
104
|
+
const parsed = schema.safeParse(doc.body)
|
|
105
|
+
if (!parsed.success) throw new TypeVaultError('tampered', `${path} has a malformed manifest body`)
|
|
106
|
+
return parsed.data
|
|
66
107
|
}
|
|
67
108
|
|
|
68
|
-
/** The
|
|
69
|
-
function checkTrust(layout: Layout,
|
|
70
|
-
const pinned = env['
|
|
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']
|
|
71
112
|
if (pinned !== undefined && pinned !== '') {
|
|
72
|
-
if (pinned !==
|
|
73
|
-
throw new TypeVaultError('tampered', 'vault operator does not match TYPEVAULT_OPERATOR')
|
|
113
|
+
if (pinned !== owner.signPublic) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
|
|
74
114
|
return
|
|
75
115
|
}
|
|
76
116
|
if (!existsSync(layout.trustFile)) {
|
|
77
|
-
|
|
117
|
+
ensureDir(layout.root, 0o700)
|
|
118
|
+
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
78
119
|
return
|
|
79
120
|
}
|
|
80
|
-
const trust =
|
|
81
|
-
if (trust.
|
|
82
|
-
throw new TypeVaultError('tampered', 'vault
|
|
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')
|
|
83
124
|
}
|
|
84
125
|
}
|
|
85
126
|
|
|
127
|
+
export function readOwner(layout: Layout): PublicKey {
|
|
128
|
+
if (!existsSync(layout.ownerFile))
|
|
129
|
+
throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
|
|
130
|
+
return readJsonFile(layout.ownerFile, PublicKeySchema)
|
|
131
|
+
}
|
|
132
|
+
|
|
86
133
|
export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
const
|
|
93
|
-
const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, operator)
|
|
134
|
+
const owner = readOwner(layout)
|
|
135
|
+
checkTrust(layout, owner, env)
|
|
136
|
+
const tiers = readSigned(layout.tiersFile, TiersBody, owner)
|
|
137
|
+
const members = readSigned(layout.membersFile, MembersBody, owner)
|
|
138
|
+
const signers = readSigned(layout.signersFile, SignersBody, owner)
|
|
139
|
+
const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, owner)
|
|
94
140
|
// An older, still validly signed manifest from git history would resurrect removed signers or ceilings.
|
|
95
141
|
const marks = new RevisionMarks(layout.revisionsFile)
|
|
96
142
|
for (const [name, doc] of [
|
|
97
|
-
['
|
|
143
|
+
['tiers', tiers],
|
|
144
|
+
['members', members],
|
|
98
145
|
['signers', signers],
|
|
99
146
|
['ceilings', ceilings],
|
|
100
147
|
] as const) {
|
|
@@ -107,30 +154,31 @@ export function loadState(layout: Layout, env: Readonly<Record<string, string |
|
|
|
107
154
|
}
|
|
108
155
|
marks.save()
|
|
109
156
|
return {
|
|
110
|
-
|
|
111
|
-
seqs: {
|
|
112
|
-
|
|
157
|
+
owner,
|
|
158
|
+
seqs: { tiers: tiers.seq, members: members.seq, signers: signers.seq, ceilings: ceilings.seq },
|
|
159
|
+
tiers: tiers.tiers,
|
|
160
|
+
members: members.members,
|
|
113
161
|
signers: signers.signers,
|
|
114
162
|
ceilings: ceilings.ceilings,
|
|
115
163
|
}
|
|
116
164
|
}
|
|
117
165
|
|
|
118
|
-
/** Every
|
|
119
|
-
export function reach(
|
|
166
|
+
/** Every tier `name` reaches through includes, itself included. */
|
|
167
|
+
export function reach(tiers: Tiers, name: string): ReadonlySet<string> {
|
|
120
168
|
const seen = new Set<string>()
|
|
121
|
-
const visit = (
|
|
122
|
-
if (seen.has(
|
|
123
|
-
seen.add(
|
|
124
|
-
for (const included of
|
|
169
|
+
const visit = (tier: string): void => {
|
|
170
|
+
if (seen.has(tier)) return
|
|
171
|
+
seen.add(tier)
|
|
172
|
+
for (const included of tiers[tier]?.includes ?? []) visit(included)
|
|
125
173
|
}
|
|
126
174
|
visit(name)
|
|
127
175
|
return seen
|
|
128
176
|
}
|
|
129
177
|
|
|
130
|
-
export const
|
|
131
|
-
from.some((
|
|
178
|
+
export const reachesTier = (tiers: Tiers, from: readonly string[], target: string): boolean =>
|
|
179
|
+
from.some((tier) => tier === '*' || reach(tiers, tier).has(target))
|
|
132
180
|
|
|
133
|
-
export const includersOf = (
|
|
134
|
-
Object.entries(
|
|
135
|
-
.filter(([,
|
|
181
|
+
export const includersOf = (tiers: Tiers, name: string): readonly string[] =>
|
|
182
|
+
Object.entries(tiers)
|
|
183
|
+
.filter(([, tier]) => tier.includes.includes(name))
|
|
136
184
|
.map(([includer]) => includer)
|
package/src/core/txn.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync,
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
2
2
|
import { dirname, isAbsolute, join, normalize, sep } from 'node:path'
|
|
3
3
|
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
|
|
6
6
|
import { randomHex } from './crypto'
|
|
7
|
-
import {
|
|
7
|
+
import { utf8 } from './encoding'
|
|
8
8
|
import { TypeVaultError } from './errors'
|
|
9
9
|
import { assertNoSymlinks, atomicWrite, fsyncDir } from './fsx'
|
|
10
|
+
import { readJsonFile } from './json-file'
|
|
10
11
|
import type { Layout } from './layout'
|
|
11
12
|
|
|
12
13
|
const COMMITTED = 'COMMITTED'
|
|
@@ -14,7 +15,7 @@ const ManifestSchema = z.object({ puts: z.array(z.string()), removes: z.array(z.
|
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* A batch of vault file changes that lands all-or-nothing. Puts apply in insertion order and
|
|
17
|
-
* removes after them, so a caller flips a pointer file (
|
|
18
|
+
* removes after them, so a caller flips a pointer file (tiers.json) by putting it last.
|
|
18
19
|
* Mutable on purpose: it accumulates changes until `commitTxn`.
|
|
19
20
|
*/
|
|
20
21
|
export class Txn {
|
|
@@ -53,7 +54,7 @@ function checkRel(rel: string): string {
|
|
|
53
54
|
export function commitTxn(layout: Layout, txn: Txn): void {
|
|
54
55
|
if (txn.isEmpty) return
|
|
55
56
|
const dir = join(layout.txnDir, randomHex(8))
|
|
56
|
-
mkdirSync(join(dir, 'files'), { recursive: true })
|
|
57
|
+
mkdirSync(join(dir, 'files'), { recursive: true, mode: 0o700 })
|
|
57
58
|
const puts = [...txn.puts.keys()]
|
|
58
59
|
puts.forEach((rel, index) => atomicWrite(join(dir, 'files', String(index)), txn.puts.get(rel) ?? new Uint8Array()))
|
|
59
60
|
atomicWrite(join(dir, 'manifest.json'), JSON.stringify({ puts, removes: [...txn.removes] }))
|
|
@@ -63,15 +64,16 @@ export function commitTxn(layout: Layout, txn: Txn): void {
|
|
|
63
64
|
|
|
64
65
|
/** Idempotent: a crash halfway through is finished by running it again. */
|
|
65
66
|
function applyTxn(layout: Layout, dir: string): void {
|
|
66
|
-
const manifest =
|
|
67
|
+
const manifest = readJsonFile(join(dir, 'manifest.json'), ManifestSchema)
|
|
67
68
|
const touched = new Set<string>()
|
|
68
69
|
manifest.puts.forEach((rel, index) => {
|
|
69
70
|
const staged = join(dir, 'files', String(index))
|
|
70
71
|
if (!existsSync(staged)) return
|
|
71
72
|
assertNoSymlinks(layout.vault, checkRel(rel))
|
|
72
73
|
const target = join(layout.vault, checkRel(rel))
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
// Staging (run/) and the vault may sit on different filesystems, where rename fails: write the bytes in place.
|
|
75
|
+
atomicWrite(target, readFileSync(staged))
|
|
76
|
+
rmSync(staged)
|
|
75
77
|
touched.add(dirname(target))
|
|
76
78
|
})
|
|
77
79
|
for (const rel of manifest.removes) {
|
package/src/core/vault.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, lstatSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
2
|
-
import { join } from 'node:path'
|
|
2
|
+
import { basename, dirname, join } from 'node:path'
|
|
3
3
|
|
|
4
4
|
import { randomHex, type SecretKey } from './crypto'
|
|
5
5
|
import { fromUtf8 } from './encoding'
|
|
@@ -10,18 +10,21 @@ import {
|
|
|
10
10
|
openEntry,
|
|
11
11
|
sealEntry,
|
|
12
12
|
signCiphertext,
|
|
13
|
+
certEntryId,
|
|
13
14
|
type SignerContext,
|
|
15
|
+
type SignerRef,
|
|
14
16
|
verifyEnvelope,
|
|
15
17
|
} from './entries'
|
|
16
18
|
import { TypeVaultError } from './errors'
|
|
17
19
|
import { assertNoSymlinks, atomicWrite, fsyncDir } from './fsx'
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
+
import { refuseForeignDaemon } from './holder'
|
|
21
|
+
import { heldMembers, Keyring, unwrapOwner } from './keyring'
|
|
22
|
+
import type { Layout } from './layout'
|
|
20
23
|
import { withLock } from './lock'
|
|
21
|
-
import type { EntryName,
|
|
24
|
+
import type { EntryName, Field } from './naming'
|
|
22
25
|
import type { EntryPayload } from './payload'
|
|
23
26
|
import { RevisionMarks } from './revisions'
|
|
24
|
-
import { type
|
|
27
|
+
import { type Tiers, loadState, reach, type VaultState } from './state'
|
|
25
28
|
import { commitTxn, recoverTxns, Txn } from './txn'
|
|
26
29
|
|
|
27
30
|
export type StoredEntry = { readonly envelope: Envelope; readonly payload: EntryPayload }
|
|
@@ -40,9 +43,8 @@ export type PutOptions = { readonly ifRev?: number; readonly base?: EntryBase }
|
|
|
40
43
|
|
|
41
44
|
export type EntryInput = {
|
|
42
45
|
readonly name: EntryName
|
|
43
|
-
readonly
|
|
44
|
-
readonly
|
|
45
|
-
readonly group: string
|
|
46
|
+
readonly fields: Readonly<Record<string, Field>>
|
|
47
|
+
readonly tier: string
|
|
46
48
|
readonly env?: string
|
|
47
49
|
readonly origin?: string
|
|
48
50
|
readonly tags?: readonly string[]
|
|
@@ -59,24 +61,24 @@ function parseJson(bytes: Uint8Array): unknown {
|
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
63
|
|
|
62
|
-
const sameFields = (a: Readonly<Record<string,
|
|
64
|
+
const sameFields = (a: Readonly<Record<string, Field>>, b: Readonly<Record<string, Field>>): boolean =>
|
|
63
65
|
JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort())
|
|
64
66
|
|
|
65
67
|
/**
|
|
66
|
-
* The entry a name means when several files carry it. A copy in a
|
|
67
|
-
* lower
|
|
68
|
-
* higher revision wins. Copies in
|
|
68
|
+
* The entry a name means when several files carry it. A copy in a tier that reaches the other's tier wins, so a
|
|
69
|
+
* lower tier can never shadow a higher one (timestamps are writer-chosen and never decide). Within one tier the
|
|
70
|
+
* higher revision wins. Copies in tiers neither reaches are a conflict for `doctor`.
|
|
69
71
|
*/
|
|
70
|
-
export function resolveName(
|
|
72
|
+
export function resolveName(tiers: Tiers, copies: readonly StoredEntry[]): StoredEntry | undefined {
|
|
71
73
|
return copies.reduce<StoredEntry | undefined>((best, entry) => {
|
|
72
74
|
if (best === undefined) return entry
|
|
73
75
|
const [a, b] = [best.envelope, entry.envelope]
|
|
74
|
-
if (a.
|
|
75
|
-
if (reach(
|
|
76
|
-
if (reach(
|
|
76
|
+
if (a.tier === b.tier) return b.rev > a.rev || (b.rev === a.rev && b.id > a.id) ? entry : best
|
|
77
|
+
if (reach(tiers, a.tier).has(b.tier)) return best
|
|
78
|
+
if (reach(tiers, b.tier).has(a.tier)) return entry
|
|
77
79
|
throw new TypeVaultError(
|
|
78
80
|
'conflict',
|
|
79
|
-
`${entry.payload.name} exists in unrelated
|
|
81
|
+
`${entry.payload.name} exists in unrelated tiers "${a.tier}" and "${b.tier}" (run typevault doctor)`,
|
|
80
82
|
)
|
|
81
83
|
}, undefined)
|
|
82
84
|
}
|
|
@@ -86,23 +88,30 @@ export class Vault {
|
|
|
86
88
|
readonly layout: Layout
|
|
87
89
|
readonly #keys: readonly SecretKey[]
|
|
88
90
|
readonly #env: Env
|
|
91
|
+
readonly #member: string | undefined
|
|
89
92
|
#state: VaultState
|
|
90
93
|
#keyring: Keyring
|
|
91
94
|
|
|
92
|
-
private constructor(layout: Layout, keys: readonly SecretKey[], env: Env) {
|
|
95
|
+
private constructor(layout: Layout, keys: readonly SecretKey[], env: Env, state: VaultState, member?: string) {
|
|
93
96
|
this.layout = layout
|
|
94
97
|
this.#keys = keys
|
|
95
98
|
this.#env = env
|
|
96
|
-
this.#
|
|
97
|
-
this.#
|
|
99
|
+
this.#member = member
|
|
100
|
+
this.#state = state
|
|
101
|
+
this.#keyring = new Keyring(layout, state, keys)
|
|
98
102
|
}
|
|
99
103
|
|
|
100
|
-
|
|
101
|
-
|
|
104
|
+
/** Opens the vault with `keys`. An owner member's key also brings the owner key it unwraps. */
|
|
105
|
+
static async open(layout: Layout, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
|
|
106
|
+
refuseForeignDaemon(layout, env)
|
|
102
107
|
if (existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0) {
|
|
103
108
|
await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
|
|
104
109
|
}
|
|
105
|
-
|
|
110
|
+
const state = loadState(layout, env)
|
|
111
|
+
const owner = await unwrapOwner(layout, state, keys)
|
|
112
|
+
const [member] = await heldMembers(state, keys)
|
|
113
|
+
const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
|
|
114
|
+
return new Vault(layout, all, env, state, member?.name)
|
|
106
115
|
}
|
|
107
116
|
|
|
108
117
|
get state(): VaultState {
|
|
@@ -117,7 +126,12 @@ export class Vault {
|
|
|
117
126
|
return this.#keys
|
|
118
127
|
}
|
|
119
128
|
|
|
120
|
-
/**
|
|
129
|
+
/** The member this process acts as, when it holds a member key the vault lists. */
|
|
130
|
+
get member(): string | undefined {
|
|
131
|
+
return this.#member
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Re-reads owner-signed state; call after another process may have changed it. */
|
|
121
135
|
refresh(): void {
|
|
122
136
|
this.#state = loadState(this.layout, this.#env)
|
|
123
137
|
this.#keyring = new Keyring(this.layout, this.#state, this.#keys)
|
|
@@ -129,7 +143,7 @@ export class Vault {
|
|
|
129
143
|
this.refresh()
|
|
130
144
|
const entries: StoredEntry[] = []
|
|
131
145
|
const problems: ScanProblem[] = []
|
|
132
|
-
assertNoSymlinks(this.layout.
|
|
146
|
+
assertNoSymlinks(dirname(this.layout.vault), join(basename(this.layout.vault), 'entries'))
|
|
133
147
|
const files = existsSync(this.layout.entries) ? readdirSync(this.layout.entries) : []
|
|
134
148
|
const marks = new RevisionMarks(this.layout.revisionsFile)
|
|
135
149
|
for (const file of files.filter(
|
|
@@ -148,7 +162,13 @@ export class Vault {
|
|
|
148
162
|
problems.push({ file, reason })
|
|
149
163
|
continue
|
|
150
164
|
}
|
|
151
|
-
|
|
165
|
+
// Accepting expired certificates must not move the marks: a backdated high revision nobody adopts would
|
|
166
|
+
// otherwise lock out the trusted one.
|
|
167
|
+
const current =
|
|
168
|
+
options.acceptExpiredCerts === true
|
|
169
|
+
? marks.allows(parsed.data.id, parsed.data.rev)
|
|
170
|
+
: marks.accept(parsed.data.id, parsed.data.rev)
|
|
171
|
+
if (!current) {
|
|
152
172
|
problems.push({ file, reason: `revision ${parsed.data.rev} was replaced or deleted on this machine` })
|
|
153
173
|
continue
|
|
154
174
|
}
|
|
@@ -178,7 +198,7 @@ export class Vault {
|
|
|
178
198
|
async find(name: EntryName): Promise<StoredEntry | undefined> {
|
|
179
199
|
const { entries } = await this.scan()
|
|
180
200
|
return resolveName(
|
|
181
|
-
this.#state.
|
|
201
|
+
this.#state.tiers,
|
|
182
202
|
entries.filter((entry) => entry.payload.name === name),
|
|
183
203
|
)
|
|
184
204
|
}
|
|
@@ -200,7 +220,6 @@ export class Vault {
|
|
|
200
220
|
const payload: EntryPayload = {
|
|
201
221
|
v: 1,
|
|
202
222
|
name: input.name,
|
|
203
|
-
type: input.type,
|
|
204
223
|
fields: input.fields,
|
|
205
224
|
tags: input.tags ?? found?.payload.tags ?? [],
|
|
206
225
|
created: prior?.created ?? now,
|
|
@@ -209,7 +228,8 @@ export class Vault {
|
|
|
209
228
|
...(input.origin === undefined ? {} : { origin: input.origin }),
|
|
210
229
|
...(changed || found?.payload.needsRotation !== true ? {} : { needsRotation: true }),
|
|
211
230
|
}
|
|
212
|
-
const
|
|
231
|
+
const id = entryIdIn(signer.ref, input.tier, input.name, prior?.id)
|
|
232
|
+
const draft = { id, tier: input.tier, rev: currentRev + 1, at: now, payload }
|
|
213
233
|
return { envelope: await sealEntry(draft, this.#state, signer), payload }
|
|
214
234
|
}
|
|
215
235
|
|
|
@@ -219,11 +239,16 @@ export class Vault {
|
|
|
219
239
|
*/
|
|
220
240
|
put(input: EntryInput, signer: SignerContext, options: PutOptions = {}): Promise<StoredEntry> {
|
|
221
241
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
222
|
-
const
|
|
242
|
+
const found = await this.find(input.name)
|
|
243
|
+
const stored = await this.#draft(input, found, options, signer)
|
|
223
244
|
atomicWrite(
|
|
224
245
|
join(this.layout.entries, `${stored.envelope.id}.json`),
|
|
225
246
|
`${JSON.stringify(stored.envelope, null, 2)}\n`,
|
|
226
247
|
)
|
|
248
|
+
// A certificate may only replace the files it was issued with, never delete another one.
|
|
249
|
+
if (found !== undefined && found.envelope.id !== stored.envelope.id && signer.ref.kind !== 'cert') {
|
|
250
|
+
this.#unlink(found.envelope.id)
|
|
251
|
+
}
|
|
227
252
|
return stored
|
|
228
253
|
})
|
|
229
254
|
}
|
|
@@ -231,33 +256,40 @@ export class Vault {
|
|
|
231
256
|
/** Writes many entries as one transaction (an import): all of them land, or none do. */
|
|
232
257
|
putMany(
|
|
233
258
|
inputs: readonly EntryInput[],
|
|
234
|
-
signerFor: (
|
|
259
|
+
signerFor: (tier: string) => Promise<SignerContext>,
|
|
235
260
|
): Promise<readonly StoredEntry[]> {
|
|
236
261
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
237
262
|
const { entries } = await this.scan()
|
|
238
263
|
const txn = new Txn()
|
|
239
264
|
const stored: StoredEntry[] = []
|
|
265
|
+
const retiered: string[] = []
|
|
240
266
|
for (const input of inputs) {
|
|
241
267
|
const found = resolveName(
|
|
242
|
-
this.#state.
|
|
268
|
+
this.#state.tiers,
|
|
243
269
|
entries.filter((entry) => entry.payload.name === input.name),
|
|
244
270
|
)
|
|
245
|
-
const
|
|
271
|
+
const signer = await signerFor(input.tier)
|
|
272
|
+
const entry = await this.#draft(input, found, {}, signer)
|
|
246
273
|
txn.put(`entries/${entry.envelope.id}.json`, `${JSON.stringify(entry.envelope, null, 2)}\n`)
|
|
274
|
+
if (found !== undefined && found.envelope.id !== entry.envelope.id && signer.ref.kind !== 'cert') {
|
|
275
|
+
txn.remove(`entries/${found.envelope.id}.json`)
|
|
276
|
+
retiered.push(found.envelope.id)
|
|
277
|
+
}
|
|
247
278
|
stored.push(entry)
|
|
248
279
|
}
|
|
249
280
|
commitTxn(this.layout, txn)
|
|
281
|
+
for (const id of retiered) this.#tombstone(id)
|
|
250
282
|
return stored
|
|
251
283
|
})
|
|
252
284
|
}
|
|
253
285
|
|
|
254
|
-
/** Removes the entry `name` resolves to, or the copy in `
|
|
255
|
-
remove(name: EntryName,
|
|
286
|
+
/** Removes the entry `name` resolves to, or the copy in `tier` (how a cross-tier conflict is settled). */
|
|
287
|
+
remove(name: EntryName, tier?: string): Promise<StoredEntry> {
|
|
256
288
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
257
289
|
const existing =
|
|
258
|
-
|
|
290
|
+
tier === undefined
|
|
259
291
|
? await this.find(name)
|
|
260
|
-
: (await this.scan()).entries.find((entry) => entry.payload.name === name && entry.envelope.
|
|
292
|
+
: (await this.scan()).entries.find((entry) => entry.payload.name === name && entry.envelope.tier === tier)
|
|
261
293
|
if (existing === undefined) throw new TypeVaultError('not_found', `no entry named ${name}`)
|
|
262
294
|
rmSync(join(this.layout.entries, `${existing.envelope.id}.json`))
|
|
263
295
|
fsyncDir(this.layout.entries)
|
|
@@ -267,38 +299,68 @@ export class Vault {
|
|
|
267
299
|
}
|
|
268
300
|
|
|
269
301
|
/** Stores a payload encrypted elsewhere under `name`, replacing any entry of that name. */
|
|
270
|
-
putCiphertext(name: EntryName,
|
|
302
|
+
putCiphertext(name: EntryName, tier: string, ciphertext: Uint8Array, signer: SignerContext): Promise<Envelope> {
|
|
271
303
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
272
304
|
const existing = await this.find(name)
|
|
273
|
-
const
|
|
305
|
+
const id = entryIdIn(signer.ref, tier, name, existing?.envelope.id)
|
|
306
|
+
const draft = { id, tier, rev: (existing?.envelope.rev ?? 0) + 1 }
|
|
274
307
|
const envelope = signCiphertext({ ...draft, at: new Date().toISOString() }, ciphertext, this.#state, signer)
|
|
275
308
|
atomicWrite(join(this.layout.entries, `${envelope.id}.json`), `${JSON.stringify(envelope, null, 2)}\n`)
|
|
309
|
+
if (existing !== undefined && existing.envelope.id !== envelope.id && signer.ref.kind !== 'cert') {
|
|
310
|
+
this.#unlink(existing.envelope.id)
|
|
311
|
+
}
|
|
276
312
|
return envelope
|
|
277
313
|
})
|
|
278
314
|
}
|
|
279
315
|
|
|
280
|
-
/**
|
|
281
|
-
|
|
316
|
+
/**
|
|
317
|
+
* Deletes an entry file by id, for writers that can't read the entry (sealed grants).
|
|
318
|
+
* `allows` judges the verified envelope under the lock; the file stays unless it returns true.
|
|
319
|
+
*/
|
|
320
|
+
removeById(id: string, allows: (envelope: Envelope) => boolean): Promise<void> {
|
|
282
321
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
283
|
-
if (
|
|
322
|
+
if (!EnvelopeSchema.shape.id.safeParse(id).success) throw new TypeVaultError('invalid', 'invalid entry id')
|
|
323
|
+
this.refresh()
|
|
284
324
|
const path = join(this.layout.entries, `${id}.json`)
|
|
285
325
|
if (!existsSync(path)) throw new TypeVaultError('not_found', 'entry is already gone')
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
326
|
+
const parsed = EnvelopeSchema.safeParse(parseJson(readFileSync(path)))
|
|
327
|
+
if (!parsed.success || parsed.data.id !== id || verifyEnvelope(parsed.data, this.#state) !== undefined) {
|
|
328
|
+
throw new TypeVaultError('denied', 'refusing to remove an entry file that does not verify')
|
|
329
|
+
}
|
|
330
|
+
if (!allows(parsed.data)) throw new TypeVaultError('denied', 'this grant cannot remove that entry')
|
|
331
|
+
this.#unlink(id)
|
|
289
332
|
})
|
|
290
333
|
}
|
|
291
334
|
|
|
335
|
+
#unlink(id: string): void {
|
|
336
|
+
rmSync(join(this.layout.entries, `${id}.json`))
|
|
337
|
+
fsyncDir(this.layout.entries)
|
|
338
|
+
this.#tombstone(id)
|
|
339
|
+
}
|
|
340
|
+
|
|
292
341
|
move(from: EntryName, to: EntryName, signer: SignerContext): Promise<StoredEntry> {
|
|
293
342
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
294
343
|
const existing = await this.find(from)
|
|
295
344
|
if (existing === undefined) throw new TypeVaultError('not_found', `no entry named ${from}`)
|
|
296
345
|
if ((await this.find(to)) !== undefined) throw new TypeVaultError('conflict', `${to} already exists`)
|
|
297
346
|
const payload = { ...existing.payload, name: to }
|
|
298
|
-
const
|
|
347
|
+
const { tier } = existing.envelope
|
|
348
|
+
// A fresh id: a grant issued for the old name lists the old one, and must not follow the entry to its new name.
|
|
349
|
+
const draft = { id: entryIdIn(signer.ref, tier, to, undefined), tier, rev: existing.envelope.rev + 1 }
|
|
299
350
|
const envelope = await sealEntry({ ...draft, at: new Date().toISOString(), payload }, this.#state, signer)
|
|
300
351
|
atomicWrite(join(this.layout.entries, `${envelope.id}.json`), `${JSON.stringify(envelope, null, 2)}\n`)
|
|
352
|
+
this.#unlink(existing.envelope.id)
|
|
301
353
|
return { envelope, payload }
|
|
302
354
|
})
|
|
303
355
|
}
|
|
304
356
|
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* An entry keeps its id only within its tier: the id names the tier (see `verifyEnvelope`), so a retier mints a new one.
|
|
360
|
+
* A certificate keeps only an id it was issued with; a blind writer's `current` comes from a holder-editable bundle.
|
|
361
|
+
*/
|
|
362
|
+
const entryIdIn = (signer: SignerRef, tier: string, name: string, current: string | undefined): string => {
|
|
363
|
+
const kept = current?.startsWith(`${tier}.`) === true ? current : undefined
|
|
364
|
+
if (signer.kind !== 'cert') return kept ?? `${tier}.${randomHex(16)}`
|
|
365
|
+
return kept !== undefined && signer.cert.ids.includes(kept) ? kept : certEntryId(signer.cert, tier, name)
|
|
366
|
+
}
|