typevault 0.1.0 → 0.2.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 +7 -7
- package/src/access/scoped.ts +100 -44
- package/src/access/sealed-access.ts +45 -23
- package/src/access/sealed.ts +33 -21
- package/src/access/types.ts +25 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +14 -9
- package/src/cli/commands/admin.ts +87 -47
- package/src/cli/commands/daemon.ts +33 -15
- package/src/cli/commands/entries.ts +166 -55
- package/src/cli/commands/grant.ts +12 -20
- package/src/cli/commands/members.ts +281 -0
- package/src/cli/commands/run.ts +61 -24
- package/src/cli/context.ts +155 -15
- package/src/cli/index.ts +27 -4
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +65 -0
- package/src/core/admin.ts +125 -74
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +9 -9
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +6 -0
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +84 -0
- package/src/core/identity.ts +130 -0
- package/src/core/init.ts +73 -23
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +145 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +146 -49
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +8 -4
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +88 -48
- package/src/core/txn.ts +5 -4
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +39 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +29 -11
- package/src/daemon/client.ts +15 -0
- package/src/daemon/daemon.ts +210 -32
- package/src/daemon/grants.ts +21 -4
- package/src/daemon/http.ts +3 -0
- package/src/daemon/live-access.ts +4 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +17 -22
- package/src/daemon/spawn.ts +188 -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 +2 -2
- 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/page.ts +19 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +3 -3
package/src/core/entries.ts
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
|
|
3
|
-
import { seal, type SecretKey, sign, unseal, verifySignature } from './crypto'
|
|
3
|
+
import { seal, type SecretKey, sha256Hex, sign, unseal, verifySignature } from './crypto'
|
|
4
4
|
import { canonicalJson, fromBase64, type Json, toBase64, utf8 } from './encoding'
|
|
5
5
|
import { TypeVaultError } from './errors'
|
|
6
6
|
import type { Keyring } from './keyring'
|
|
7
7
|
import { matchesOnly } from './naming'
|
|
8
8
|
import { decodePayload, encodePayload, type EntryPayload } from './payload'
|
|
9
|
-
import { reach,
|
|
9
|
+
import { reach, reachesTier, type VaultState } from './state'
|
|
10
10
|
|
|
11
11
|
const IssuerSchema = z.discriminatedUnion('kind', [
|
|
12
|
-
z.object({ kind: z.literal('
|
|
13
|
-
z.object({ kind: z.literal('
|
|
12
|
+
z.object({ kind: z.literal('owner') }),
|
|
13
|
+
z.object({ kind: z.literal('tier'), tier: z.string(), gen: z.number().int().positive() }),
|
|
14
14
|
z.object({ kind: z.literal('signer'), id: z.string() }),
|
|
15
15
|
])
|
|
16
16
|
export const CertSchema = z.object({
|
|
17
17
|
signPublic: z.string(),
|
|
18
|
-
|
|
19
|
-
/** Name patterns the holder may write; empty means any name in its
|
|
18
|
+
tiers: z.array(z.string()),
|
|
19
|
+
/** Name patterns the holder may write; empty means any name in its tiers. */
|
|
20
20
|
only: z.array(z.string()),
|
|
21
|
+
/** Ids of the entries the grant was issued with: the only existing files it may replace or remove. */
|
|
22
|
+
ids: z.array(z.string()),
|
|
21
23
|
exp: z.iso.datetime(),
|
|
22
24
|
issuer: IssuerSchema,
|
|
23
25
|
sig: z.string(),
|
|
@@ -25,8 +27,8 @@ export const CertSchema = z.object({
|
|
|
25
27
|
const SignerSchema = z.union([IssuerSchema, z.object({ kind: z.literal('cert'), cert: CertSchema })])
|
|
26
28
|
export const EnvelopeSchema = z.object({
|
|
27
29
|
v: z.literal(1),
|
|
28
|
-
id: z.string().regex(/^[0-9a-f]{32}$/),
|
|
29
|
-
|
|
30
|
+
id: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\.[0-9a-f]{32}$/),
|
|
31
|
+
tier: z.string(),
|
|
30
32
|
gen: z.number().int().positive(),
|
|
31
33
|
rev: z.number().int().positive(),
|
|
32
34
|
at: z.iso.datetime(),
|
|
@@ -43,23 +45,25 @@ export type Envelope = z.infer<typeof EnvelopeSchema>
|
|
|
43
45
|
/** Who signs a write: a reference other readers can check plus the matching signing secret. */
|
|
44
46
|
export type SignerContext = { readonly ref: SignerRef; readonly signSecret: Uint8Array }
|
|
45
47
|
|
|
46
|
-
export
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
export function signerOf(key: SecretKey): SignerContext {
|
|
49
|
+
const { role } = key
|
|
50
|
+
// A member key only opens wraps; writes are signed by the tier or owner key it unwraps.
|
|
51
|
+
if (role.kind === 'member') throw new TypeVaultError('denied', 'a member key cannot sign entries')
|
|
52
|
+
return {
|
|
53
|
+
ref: role.kind === 'owner' ? { kind: 'owner' } : { kind: 'tier', tier: role.tier, gen: role.gen },
|
|
54
|
+
signSecret: key.signSecret,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
51
57
|
|
|
52
|
-
type Authority = { readonly signPublic: string; readonly
|
|
58
|
+
type Authority = { readonly signPublic: string; readonly tiers: readonly string[] }
|
|
53
59
|
|
|
54
60
|
function authorityOf(ref: IssuerRef, state: VaultState): Authority | undefined {
|
|
55
61
|
switch (ref.kind) {
|
|
56
|
-
case '
|
|
57
|
-
return { signPublic: state.
|
|
58
|
-
case '
|
|
59
|
-
const
|
|
60
|
-
return
|
|
61
|
-
? undefined
|
|
62
|
-
: { signPublic: group.signPublic, groups: [ref.group] }
|
|
62
|
+
case 'owner':
|
|
63
|
+
return { signPublic: state.owner.signPublic, tiers: ['*'] }
|
|
64
|
+
case 'tier': {
|
|
65
|
+
const tier = state.tiers[ref.tier]
|
|
66
|
+
return tier === undefined || tier.gen !== ref.gen ? undefined : { signPublic: tier.signPublic, tiers: [ref.tier] }
|
|
63
67
|
}
|
|
64
68
|
case 'signer':
|
|
65
69
|
return state.signers[ref.id]
|
|
@@ -72,12 +76,23 @@ function assertNever(value: never): never {
|
|
|
72
76
|
throw new TypeVaultError('invalid', `unexpected value ${JSON.stringify(value)}`)
|
|
73
77
|
}
|
|
74
78
|
|
|
79
|
+
/**
|
|
80
|
+
* The id a certificate writes a new entry under. Bound to the certificate and the name, so a holder can never aim a
|
|
81
|
+
* write at another entry's file: names are encrypted, so ids alone can't show which file holds what.
|
|
82
|
+
*/
|
|
83
|
+
export const certEntryId = (cert: Cert, tier: string, name: string): string =>
|
|
84
|
+
`${tier}.${sha256Hex(utf8(`${cert.sig}\n${name}`)).slice(0, 32)}`
|
|
85
|
+
|
|
86
|
+
export const certMayHold = (cert: Cert, id: string, tier: string, name: string): boolean =>
|
|
87
|
+
cert.ids.includes(id) || id === certEntryId(cert, tier, name)
|
|
88
|
+
|
|
75
89
|
const certBytes = (cert: Omit<Cert, 'sig'>): Uint8Array =>
|
|
76
90
|
utf8(
|
|
77
91
|
canonicalJson({
|
|
78
92
|
signPublic: cert.signPublic,
|
|
79
|
-
|
|
93
|
+
tiers: cert.tiers,
|
|
80
94
|
only: cert.only,
|
|
95
|
+
ids: cert.ids,
|
|
81
96
|
exp: cert.exp,
|
|
82
97
|
issuer: cert.issuer,
|
|
83
98
|
}),
|
|
@@ -90,37 +105,31 @@ export function issueCert(cert: Omit<Cert, 'sig' | 'issuer'>, issuer: SignerCont
|
|
|
90
105
|
}
|
|
91
106
|
|
|
92
107
|
const envelopeBytes = (envelope: Omit<Envelope, 'sig'>): Uint8Array => {
|
|
93
|
-
const { v, id,
|
|
94
|
-
const body: Json = { v, id,
|
|
108
|
+
const { v, id, tier, gen, rev, at, payload, signer } = envelope
|
|
109
|
+
const body: Json = { v, id, tier, gen, rev, at, payload, signer }
|
|
95
110
|
return utf8(canonicalJson(body))
|
|
96
111
|
}
|
|
97
112
|
|
|
98
|
-
/** Whether `signer` may sign entries of `
|
|
99
|
-
/** `now` is the reader's clock for certificate expiry; `null` skips that one check (explicit
|
|
113
|
+
/** Whether `signer` may sign entries of `tier`, judged only from owner-signed state. */
|
|
114
|
+
/** `now` is the reader's clock for certificate expiry; `null` skips that one check (explicit owner adoption). */
|
|
100
115
|
export function signerAuthority(
|
|
101
116
|
signer: SignerRef,
|
|
102
|
-
|
|
117
|
+
tier: string,
|
|
103
118
|
state: VaultState,
|
|
104
119
|
at: string,
|
|
105
120
|
now: number | null = Date.now(),
|
|
106
121
|
): string | undefined {
|
|
107
122
|
if (signer.kind !== 'cert') {
|
|
108
123
|
const authority = authorityOf(signer, state)
|
|
109
|
-
return authority !== undefined &&
|
|
110
|
-
? authority.signPublic
|
|
111
|
-
: undefined
|
|
124
|
+
return authority !== undefined && reachesTier(state.tiers, authority.tiers, tier) ? authority.signPublic : undefined
|
|
112
125
|
}
|
|
113
126
|
const { cert } = signer
|
|
114
127
|
const issuer = authorityOf(cert.issuer, state)
|
|
115
128
|
if (issuer === undefined || !verifySignature(issuer.signPublic, certBytes(cert), cert.sig)) return undefined
|
|
116
|
-
if (!cert.
|
|
129
|
+
if (!cert.tiers.every((g) => reachesTier(state.tiers, issuer.tiers, g))) return undefined
|
|
117
130
|
// Expiry is judged by the reader's clock: `at` is chosen by the holder, so it can't be trusted to bound it.
|
|
118
131
|
const exp = Date.parse(cert.exp)
|
|
119
|
-
if (
|
|
120
|
-
!cert.groups.some((g) => reach(state.groups, g).has(group)) ||
|
|
121
|
-
Date.parse(at) > exp ||
|
|
122
|
-
(now !== null && now > exp)
|
|
123
|
-
) {
|
|
132
|
+
if (!cert.tiers.some((g) => reach(state.tiers, g).has(tier)) || Date.parse(at) > exp || (now !== null && now > exp)) {
|
|
124
133
|
return undefined
|
|
125
134
|
}
|
|
126
135
|
return cert.signPublic
|
|
@@ -128,17 +137,17 @@ export function signerAuthority(
|
|
|
128
137
|
|
|
129
138
|
export type EntryDraft = {
|
|
130
139
|
readonly id: string
|
|
131
|
-
readonly
|
|
140
|
+
readonly tier: string
|
|
132
141
|
readonly rev: number
|
|
133
142
|
readonly at: string
|
|
134
143
|
readonly payload: EntryPayload
|
|
135
144
|
}
|
|
136
145
|
|
|
137
146
|
export async function sealEntry(draft: EntryDraft, state: VaultState, signer: SignerContext): Promise<Envelope> {
|
|
138
|
-
const
|
|
139
|
-
if (
|
|
140
|
-
const ciphertext = await seal([
|
|
141
|
-
return signCiphertext({ id: draft.id,
|
|
147
|
+
const tier = state.tiers[draft.tier]
|
|
148
|
+
if (tier === undefined) throw new TypeVaultError('not_found', `no tier "${draft.tier}"`)
|
|
149
|
+
const ciphertext = await seal([tier.recipient, state.owner.recipient], encodePayload(draft.payload))
|
|
150
|
+
return signCiphertext({ id: draft.id, tier: draft.tier, rev: draft.rev, at: draft.at }, ciphertext, state, signer)
|
|
142
151
|
}
|
|
143
152
|
|
|
144
153
|
/** Signs an envelope around a payload that was encrypted elsewhere (the secret-prompt page encrypts in the browser). */
|
|
@@ -148,12 +157,12 @@ export function signCiphertext(
|
|
|
148
157
|
state: VaultState,
|
|
149
158
|
signer: SignerContext,
|
|
150
159
|
): Envelope {
|
|
151
|
-
const
|
|
152
|
-
if (
|
|
153
|
-
if (signerAuthority(signer.ref, draft.
|
|
154
|
-
throw new TypeVaultError('denied', `this key cannot sign entries in
|
|
160
|
+
const tier = state.tiers[draft.tier]
|
|
161
|
+
if (tier === undefined) throw new TypeVaultError('not_found', `no tier "${draft.tier}"`)
|
|
162
|
+
if (signerAuthority(signer.ref, draft.tier, state, draft.at) === undefined) {
|
|
163
|
+
throw new TypeVaultError('denied', `this key cannot sign entries in tier "${draft.tier}"`)
|
|
155
164
|
}
|
|
156
|
-
const unsigned = { v: 1 as const, id: draft.id,
|
|
165
|
+
const unsigned = { v: 1 as const, id: draft.id, tier: draft.tier, gen: tier.gen, rev: draft.rev, at: draft.at }
|
|
157
166
|
const envelope = { ...unsigned, payload: toBase64(ciphertext), signer: signer.ref }
|
|
158
167
|
return { ...envelope, sig: sign(signer.signSecret, envelopeBytes(envelope)) }
|
|
159
168
|
}
|
|
@@ -164,28 +173,33 @@ const CLOCK_SKEW_MS = 5 * 60_000
|
|
|
164
173
|
export type VerifyOptions = { readonly acceptExpiredCerts?: boolean }
|
|
165
174
|
|
|
166
175
|
export function verifyEnvelope(envelope: Envelope, state: VaultState, options: VerifyOptions = {}): string | undefined {
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
169
|
-
|
|
176
|
+
const tier = state.tiers[envelope.tier]
|
|
177
|
+
if (tier === undefined) return `unknown tier "${envelope.tier}"`
|
|
178
|
+
// The id names its tier, so a file can only ever be replaced by a write its tier's signers could make.
|
|
179
|
+
if (!envelope.id.startsWith(`${envelope.tier}.`)) return `entry id does not belong to tier "${envelope.tier}"`
|
|
180
|
+
if (tier.gen !== envelope.gen) return `stale generation ${envelope.gen} (current ${tier.gen})`
|
|
170
181
|
if (Date.parse(envelope.at) > Date.now() + CLOCK_SKEW_MS) return 'timestamp is in the future'
|
|
171
182
|
const signPublic = signerAuthority(
|
|
172
183
|
envelope.signer,
|
|
173
|
-
envelope.
|
|
184
|
+
envelope.tier,
|
|
174
185
|
state,
|
|
175
186
|
envelope.at,
|
|
176
187
|
options.acceptExpiredCerts === true ? null : Date.now(),
|
|
177
188
|
)
|
|
178
|
-
if (signPublic === undefined) return 'signer is not allowed to write this
|
|
189
|
+
if (signPublic === undefined) return 'signer is not allowed to write this tier'
|
|
179
190
|
return verifySignature(signPublic, envelopeBytes(envelope), envelope.sig) ? undefined : 'bad signature'
|
|
180
191
|
}
|
|
181
192
|
|
|
182
193
|
export async function openEntry(envelope: Envelope, keyring: Keyring): Promise<EntryPayload | undefined> {
|
|
183
|
-
const key = await keyring.unlock(envelope.
|
|
194
|
+
const key = await keyring.unlock(envelope.tier)
|
|
184
195
|
if (key === undefined) return undefined
|
|
185
196
|
const payload = decodePayload(await unseal([key.identity], fromBase64(envelope.payload)))
|
|
186
197
|
const { signer } = envelope
|
|
187
198
|
if (signer.kind === 'cert' && signer.cert.only.length > 0 && !matchesOnly(payload.name, signer.cert.only)) {
|
|
188
199
|
throw new TypeVaultError('tampered', `${payload.name} is outside the writing grant's --only`)
|
|
189
200
|
}
|
|
201
|
+
if (signer.kind === 'cert' && !certMayHold(signer.cert, envelope.id, envelope.tier, payload.name)) {
|
|
202
|
+
throw new TypeVaultError('tampered', `${payload.name} took over an entry its writing grant was not issued`)
|
|
203
|
+
}
|
|
190
204
|
return payload
|
|
191
205
|
}
|
package/src/core/errors.ts
CHANGED
|
@@ -7,6 +7,12 @@ export type ErrorCode =
|
|
|
7
7
|
| 'expired'
|
|
8
8
|
| 'locked'
|
|
9
9
|
| 'unavailable'
|
|
10
|
+
/** Another machine's daemon is using this vault's state directory. */
|
|
11
|
+
| 'in_use'
|
|
12
|
+
/** No vault at the given directory. */
|
|
13
|
+
| 'no_vault'
|
|
14
|
+
/** A vault is there, but the key given is not one of its members. */
|
|
15
|
+
| 'not_member'
|
|
10
16
|
|
|
11
17
|
export class TypeVaultError extends Error {
|
|
12
18
|
readonly code: ErrorCode
|
package/src/core/fsx.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { closeSync,
|
|
1
|
+
import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs'
|
|
2
2
|
import { basename, dirname, join, sep } from 'node:path'
|
|
3
3
|
|
|
4
4
|
import { randomHex } from './crypto'
|
|
@@ -10,6 +10,8 @@ export const ensureDir = (path: string, mode = 0o755): void => {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export function fsyncDir(path: string): void {
|
|
13
|
+
// Windows can't open a directory as a file; NTFS journals the rename itself.
|
|
14
|
+
if (process.platform === 'win32') return
|
|
13
15
|
const fd = openSync(path, 'r')
|
|
14
16
|
try {
|
|
15
17
|
fsyncSync(fd)
|
|
@@ -42,7 +44,9 @@ export function assertNoSymlinks(base: string, rel: string): void {
|
|
|
42
44
|
let path = base
|
|
43
45
|
for (const part of rel.split(sep).filter((segment) => segment !== '')) {
|
|
44
46
|
path = join(path, part)
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
// lstat, not exists: a dangling symlink reads as missing yet a write through it creates its target.
|
|
48
|
+
const stat = lstatSync(path, { throwIfNoEntry: false })
|
|
49
|
+
if (stat === undefined) return
|
|
50
|
+
if (stat.isSymbolicLink()) throw new TypeVaultError('tampered', `${path} is a symlink`)
|
|
47
51
|
}
|
|
48
52
|
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
|
|
5
|
+
import { randomHex } from './crypto'
|
|
6
|
+
import { TypeVaultError } from './errors'
|
|
7
|
+
import { hostId, type Layout } from './layout'
|
|
8
|
+
|
|
9
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
10
|
+
|
|
11
|
+
const CLAIM_ATTEMPTS = 3
|
|
12
|
+
|
|
13
|
+
const HolderSchema = z.object({ host: z.string(), pid: z.number().int(), token: z.string(), at: z.string() })
|
|
14
|
+
type Holder = z.infer<typeof HolderSchema>
|
|
15
|
+
|
|
16
|
+
export type DaemonClaim = {
|
|
17
|
+
readonly release: () => void
|
|
18
|
+
readonly owns: () => boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* flock does not cross machines (a bind mount between macOS and a Linux VM, say), so whoever runs a daemon (or
|
|
23
|
+
* re-initializes the vault) also claims the state directory in `daemon.holder`, created exclusively. An opener on the
|
|
24
|
+
* same machine trusts the flock; one on another machine refuses while any claim from another host is there. Another
|
|
25
|
+
* machine's claim is never taken over: nothing here can tell a crashed daemon from a paused one, so a claim left by a
|
|
26
|
+
* crash stays until someone who knows that daemon is gone deletes it.
|
|
27
|
+
*/
|
|
28
|
+
export function refuseForeignDaemon(layout: Layout, env: Env): void {
|
|
29
|
+
const holder = readHolder(layout)
|
|
30
|
+
if (holder !== undefined && holder.host !== hostId(env)) throw inUse(layout, holder)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Claims the state directory for this process until `release`. The caller must hold `daemonLock`, so a claim this
|
|
35
|
+
* machine left behind belongs to a daemon that is gone, and is replaced. Another machine's claim fails with `in_use`.
|
|
36
|
+
*/
|
|
37
|
+
export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
|
|
38
|
+
const token = randomHex(8)
|
|
39
|
+
const record = JSON.stringify({ host: hostId(env), pid: process.pid, token, at: new Date().toISOString() })
|
|
40
|
+
for (let attempt = 0; ; attempt++) {
|
|
41
|
+
try {
|
|
42
|
+
writeFileSync(layout.daemonHolder, record, { flag: 'wx', mode: 0o600 })
|
|
43
|
+
break
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (!isCode(error, 'EEXIST')) throw error
|
|
46
|
+
}
|
|
47
|
+
const holder = readHolder(layout)
|
|
48
|
+
if (holder !== undefined && holder.host !== hostId(env)) throw inUse(layout, holder)
|
|
49
|
+
if (attempt + 1 >= CLAIM_ATTEMPTS) {
|
|
50
|
+
throw new TypeVaultError('in_use', `could not claim ${layout.root}: another process keeps claiming it`)
|
|
51
|
+
}
|
|
52
|
+
if (holder !== undefined) rmSync(layout.daemonHolder, { force: true })
|
|
53
|
+
}
|
|
54
|
+
const owns = (): boolean => readHolder(layout)?.token === token
|
|
55
|
+
return {
|
|
56
|
+
owns,
|
|
57
|
+
release: () => {
|
|
58
|
+
if (owns()) rmSync(layout.daemonHolder, { force: true })
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readHolder(layout: Layout): Holder | undefined {
|
|
64
|
+
if (!existsSync(layout.daemonHolder)) return undefined
|
|
65
|
+
let text: string
|
|
66
|
+
try {
|
|
67
|
+
text = readFileSync(layout.daemonHolder, 'utf8')
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (isCode(error, 'ENOENT')) return undefined
|
|
70
|
+
throw error
|
|
71
|
+
}
|
|
72
|
+
const parsed = HolderSchema.safeParse(JSON.parse(text))
|
|
73
|
+
if (!parsed.success) throw new TypeVaultError('tampered', `${layout.daemonHolder} is malformed`)
|
|
74
|
+
return parsed.data
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const inUse = (layout: Layout, holder: Holder): TypeVaultError =>
|
|
78
|
+
new TypeVaultError(
|
|
79
|
+
'in_use',
|
|
80
|
+
`a typevault daemon on another machine (${holder.host}, pid ${holder.pid}, since ${holder.at}) is using ${layout.root}; one machine at a time may use a state directory (if that daemon is gone for good, delete ${layout.daemonHolder})`,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
const isCode = (error: unknown, code: string): boolean =>
|
|
84
|
+
error instanceof Error && 'code' in error && error.code === code
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
decodeSecretKey,
|
|
8
|
+
encodeSecretKey,
|
|
9
|
+
generateSecretKey,
|
|
10
|
+
type PublicKey,
|
|
11
|
+
publicKeyOf,
|
|
12
|
+
type SecretKey,
|
|
13
|
+
} from './crypto'
|
|
14
|
+
import { fromBase64Url, fromUtf8, toBase64Url, utf8 } from './encoding'
|
|
15
|
+
import { TypeVaultError } from './errors'
|
|
16
|
+
import { assertNoSymlinks, atomicWrite } from './fsx'
|
|
17
|
+
import { configDir, type Layout } from './layout'
|
|
18
|
+
import { generateSecretKeyCode, openWithPassword, sealWithPassword } from './password'
|
|
19
|
+
import { type MemberKind, parseMemberName } from './state'
|
|
20
|
+
|
|
21
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Who this device acts as, in every vault. A human's member key is sealed by their password and Secret Key; a
|
|
25
|
+
* machine (CI, an agent host) has no one to type a password, so it holds its member key directly.
|
|
26
|
+
*/
|
|
27
|
+
export type Identity = PublicKey &
|
|
28
|
+
(
|
|
29
|
+
| {
|
|
30
|
+
readonly v: 1
|
|
31
|
+
readonly kind: 'human'
|
|
32
|
+
readonly name: string
|
|
33
|
+
readonly secretKey: string
|
|
34
|
+
readonly sealedKey: string
|
|
35
|
+
}
|
|
36
|
+
| { readonly v: 1; readonly kind: 'machine'; readonly name: string; readonly key: string }
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
export type MemberPublic = PublicKey & { readonly kind: MemberKind }
|
|
40
|
+
|
|
41
|
+
const PublicFields = { recipient: z.string(), signPublic: z.string() }
|
|
42
|
+
const IdentitySchema = z.discriminatedUnion('kind', [
|
|
43
|
+
z.object({
|
|
44
|
+
v: z.literal(1),
|
|
45
|
+
kind: z.literal('human'),
|
|
46
|
+
name: z.string(),
|
|
47
|
+
secretKey: z.string(),
|
|
48
|
+
sealedKey: z.string(),
|
|
49
|
+
...PublicFields,
|
|
50
|
+
}),
|
|
51
|
+
z.object({ v: z.literal(1), kind: z.literal('machine'), name: z.string(), key: z.string(), ...PublicFields }),
|
|
52
|
+
])
|
|
53
|
+
const MemberPublicSchema = z.object({
|
|
54
|
+
kind: z.enum(['human', 'machine']),
|
|
55
|
+
recipient: z.string().startsWith('age1'),
|
|
56
|
+
signPublic: z.string(),
|
|
57
|
+
})
|
|
58
|
+
const PUBLIC_PREFIX = 'tvp1:'
|
|
59
|
+
|
|
60
|
+
export const identityPath = (env: Env): string => join(configDir(env), 'identity.json')
|
|
61
|
+
|
|
62
|
+
export function readIdentity(env: Env): Identity | undefined {
|
|
63
|
+
const path = identityPath(env)
|
|
64
|
+
return existsSync(path) ? IdentitySchema.parse(JSON.parse(readFileSync(path, 'utf8'))) : undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function writeIdentity(env: Env, identity: Identity): void {
|
|
68
|
+
atomicWrite(identityPath(env), `${JSON.stringify(identity, null, 2)}\n`, 0o600)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function createIdentity(
|
|
72
|
+
rawName: string,
|
|
73
|
+
kind: MemberKind,
|
|
74
|
+
password?: string,
|
|
75
|
+
): Promise<{ readonly identity: Identity; readonly key: SecretKey }> {
|
|
76
|
+
const name = parseMemberName(rawName)
|
|
77
|
+
const key = await generateSecretKey({ kind: 'member', name })
|
|
78
|
+
const pub = await publicKeyOf(key)
|
|
79
|
+
if (kind === 'machine') return { identity: { v: 1, kind, name, key: encodeSecretKey(key), ...pub }, key }
|
|
80
|
+
if (password === undefined || password === '') throw new TypeVaultError('invalid', 'a human member needs a password')
|
|
81
|
+
const secretKey = generateSecretKeyCode()
|
|
82
|
+
const sealedKey = await sealMemberKey(key, password, secretKey)
|
|
83
|
+
return { identity: { v: 1, kind, name, secretKey, sealedKey, ...pub }, key }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const memberPublicOfIdentity = (identity: Identity): MemberPublic => ({
|
|
87
|
+
kind: identity.kind,
|
|
88
|
+
recipient: identity.recipient,
|
|
89
|
+
signPublic: identity.signPublic,
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Where a person's sealed member key is committed in a vault. The vault comes from git, so a planted symlink here
|
|
94
|
+
* must never steer a read or a write outside it (onto identity.json, say).
|
|
95
|
+
*/
|
|
96
|
+
export function sealedCopyPath(layout: Layout, name: string): string {
|
|
97
|
+
const rel = join('members', `${parseMemberName(name)}.key`)
|
|
98
|
+
assertNoSymlinks(layout.vault, rel)
|
|
99
|
+
return join(layout.vault, rel)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const sealMemberKey = (key: SecretKey, password: string, secretKey: string): Promise<string> =>
|
|
103
|
+
sealWithPassword(utf8(encodeSecretKey(key)), password, secretKey)
|
|
104
|
+
|
|
105
|
+
/** The member key inside a sealed copy (an identity's, or the one committed in a vault's members/). */
|
|
106
|
+
export async function openMemberKey(sealedKey: string, password: string, secretKey: string): Promise<SecretKey> {
|
|
107
|
+
const key = decodeSecretKey(fromUtf8(await openWithPassword(sealedKey, password, secretKey)))
|
|
108
|
+
if (key.role.kind !== 'member') throw new TypeVaultError('invalid', 'the sealed key is not a member key')
|
|
109
|
+
return key
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function unlockIdentity(identity: Identity, password?: string): Promise<SecretKey> {
|
|
113
|
+
if (identity.kind === 'machine') return Promise.resolve(decodeSecretKey(identity.key))
|
|
114
|
+
if (password === undefined) throw new TypeVaultError('locked', 'a password is needed to unlock this identity')
|
|
115
|
+
return openMemberKey(identity.sealedKey, password, identity.secretKey)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export const encodeMemberPublic = (member: MemberPublic): string =>
|
|
119
|
+
PUBLIC_PREFIX + toBase64Url(utf8(JSON.stringify(member)))
|
|
120
|
+
|
|
121
|
+
export function decodeMemberPublic(text: string): MemberPublic {
|
|
122
|
+
const trimmed = text.trim()
|
|
123
|
+
if (!trimmed.startsWith(PUBLIC_PREFIX)) throw new TypeVaultError('invalid', 'not a member public key (tvp1:...)')
|
|
124
|
+
try {
|
|
125
|
+
return MemberPublicSchema.parse(JSON.parse(fromUtf8(fromBase64Url(trimmed.slice(PUBLIC_PREFIX.length)))))
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof Error) throw new TypeVaultError('invalid', 'malformed member public key')
|
|
128
|
+
throw error
|
|
129
|
+
}
|
|
130
|
+
}
|
package/src/core/init.ts
CHANGED
|
@@ -1,30 +1,80 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs'
|
|
2
|
-
import { join } from 'node:path'
|
|
1
|
+
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
2
|
+
import { basename, dirname, join } from 'node:path'
|
|
3
3
|
|
|
4
|
-
import { encodeSecretKey, generateSecretKey, publicKeyOf, type SecretKey } from './crypto'
|
|
4
|
+
import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal, type SecretKey } from './crypto'
|
|
5
|
+
import { utf8 } from './encoding'
|
|
5
6
|
import { TypeVaultError } from './errors'
|
|
6
7
|
import { atomicWrite, ensureDir } from './fsx'
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { type Identity, type MemberPublic, memberPublicOfIdentity, sealedCopyPath } from './identity'
|
|
9
|
+
import { ownerWrapPath } from './keyring'
|
|
10
|
+
import { globalLayout, type Layout, localLayout } from './layout'
|
|
11
|
+
import { ceilingsDoc, membersDoc, parseMemberName, signersDoc, tiersDoc } from './state'
|
|
9
12
|
|
|
10
|
-
|
|
11
|
-
const ROOT_GITIGNORE = '/*\n!/vault/\n!/.gitignore\n'
|
|
13
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
12
14
|
|
|
13
|
-
/**
|
|
14
|
-
export
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
/** The first member, who becomes the owner. A human's password-sealed key is committed beside the vault. */
|
|
16
|
+
export type Founder = { readonly name: string; readonly member: MemberPublic; readonly sealedKey?: string }
|
|
17
|
+
|
|
18
|
+
export const founderOf = (identity: Identity): Founder => ({
|
|
19
|
+
name: identity.name,
|
|
20
|
+
member: memberPublicOfIdentity(identity),
|
|
21
|
+
...(identity.kind === 'human' ? { sealedKey: identity.sealedKey } : {}),
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
export type Created = { readonly layout: Layout; readonly owner: SecretKey }
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Creates an empty global vault owned by `founder`, all of it safe to commit. The owner key is never written down in
|
|
28
|
+
* the clear: it exists only wrapped to owner members, so the founder's password and Secret Key are the recovery path.
|
|
29
|
+
*/
|
|
30
|
+
export const initGlobalVault = (founder: Founder, env: Env = process.env): Promise<Created> =>
|
|
31
|
+
create(globalLayout(env), founder)
|
|
32
|
+
|
|
33
|
+
/** Creates an empty project vault at `dir`, all of it safe to commit. */
|
|
34
|
+
export const initLocalVault = (dir: string, founder: Founder, env: Env = process.env): Promise<Created> =>
|
|
35
|
+
create(localLayout(dir, env), founder)
|
|
36
|
+
|
|
37
|
+
async function create(layout: Layout, founder: Founder): Promise<Created> {
|
|
38
|
+
refuseExisting(layout.ownerFile, layout.vault)
|
|
39
|
+
return { layout, owner: await writeVault(layout, founder) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function refuseExisting(ownerFile: string, where: string): void {
|
|
43
|
+
if (existsSync(ownerFile)) throw new TypeVaultError('conflict', `a vault already exists at ${where}`)
|
|
44
|
+
// Pre-rename vaults are not migrated; init over one would keep its stale runtime state (revision marks).
|
|
45
|
+
if (existsSync(join(dirname(ownerFile), 'operator.json'))) {
|
|
46
|
+
throw new TypeVaultError(
|
|
47
|
+
'conflict',
|
|
48
|
+
`an old-format vault (operator.json) exists at ${where}; move it and its typevault root aside, then run init again`,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function writeVault(layout: Layout, founder: Founder): Promise<SecretKey> {
|
|
54
|
+
const name = parseMemberName(founder.name)
|
|
55
|
+
// A vault re-created at the same place reuses this checkout's state directory. Its runtime state (grants, a
|
|
56
|
+
// session token, revision marks) belongs to the old vault, so it goes; the trust pin is rewritten below. The daemon
|
|
57
|
+
// lock and claim stay: whoever initializes may hold them to keep a daemon from starting meanwhile.
|
|
58
|
+
const kept = new Set([basename(layout.daemonLock), basename(layout.daemonHolder)])
|
|
59
|
+
for (const name of existsSync(layout.run) ? readdirSync(layout.run) : []) {
|
|
60
|
+
if (!kept.has(name)) rmSync(join(layout.run, name), { recursive: true, force: true })
|
|
61
|
+
}
|
|
62
|
+
const ownerKey = await generateSecretKey({ kind: 'owner' })
|
|
63
|
+
const owner: PublicKey = await publicKeyOf(ownerKey)
|
|
64
|
+
const { kind, recipient, signPublic } = founder.member
|
|
65
|
+
for (const dir of [layout.audit, layout.run]) ensureDir(dir, 0o700)
|
|
18
66
|
ensureDir(layout.entries)
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
atomicWrite(layout.
|
|
25
|
-
atomicWrite(
|
|
26
|
-
atomicWrite(layout.
|
|
27
|
-
|
|
28
|
-
atomicWrite(layout.
|
|
29
|
-
|
|
67
|
+
atomicWrite(layout.tiersFile, tiersDoc({}, ownerKey, 1))
|
|
68
|
+
atomicWrite(
|
|
69
|
+
layout.membersFile,
|
|
70
|
+
membersDoc({ [name]: { kind, recipient, signPublic, owner: true, tiers: [] } }, ownerKey, 1),
|
|
71
|
+
)
|
|
72
|
+
atomicWrite(layout.signersFile, signersDoc({}, ownerKey, 1))
|
|
73
|
+
atomicWrite(layout.ceilingsFile, ceilingsDoc({}, ownerKey, 1))
|
|
74
|
+
atomicWrite(join(layout.vault, ownerWrapPath(name)), await seal([recipient], utf8(encodeSecretKey(ownerKey))))
|
|
75
|
+
if (founder.sealedKey !== undefined) atomicWrite(sealedCopyPath(layout, name), founder.sealedKey)
|
|
76
|
+
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
77
|
+
// owner.json last: its presence is what marks the directory as an initialized vault.
|
|
78
|
+
atomicWrite(layout.ownerFile, `${JSON.stringify({ v: 1, ...owner }, null, 2)}\n`)
|
|
79
|
+
return ownerKey
|
|
30
80
|
}
|