typevault 0.2.0 → 0.4.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 +13 -12
- package/package.json +2 -2
- package/src/access/env.ts +3 -3
- package/src/access/schemas.ts +3 -1
- package/src/access/scope.ts +7 -2
- package/src/access/scoped.ts +47 -10
- package/src/access/sealed-access.ts +12 -1
- package/src/access/sealed.ts +25 -12
- package/src/access/types.ts +7 -0
- package/src/audit/log.ts +15 -4
- package/src/cli/commands/admin.ts +7 -2
- package/src/cli/commands/daemon.ts +10 -3
- package/src/cli/commands/entries.ts +21 -7
- package/src/cli/commands/grant.ts +12 -2
- package/src/cli/commands/members.ts +40 -14
- package/src/cli/commands/run.ts +141 -44
- package/src/cli/context.ts +14 -4
- package/src/cli/index.ts +6 -1
- package/src/cli/output.ts +5 -1
- package/src/cli/web-prompt.ts +28 -14
- package/src/core/admin.ts +23 -6
- package/src/core/doctor.ts +6 -7
- package/src/core/errors.ts +2 -2
- package/src/core/holder.ts +25 -9
- package/src/core/identity.ts +5 -3
- package/src/core/json-file.ts +20 -0
- package/src/core/layout.ts +51 -8
- package/src/core/naming.ts +40 -32
- package/src/core/payload.ts +7 -3
- package/src/core/revisions.ts +3 -2
- package/src/core/state.ts +16 -8
- package/src/core/txn.ts +4 -3
- package/src/core/vault.ts +45 -5
- package/src/core/version.ts +9 -0
- package/src/core/worktrees.ts +18 -6
- package/src/daemon/agent-routes.ts +80 -3
- package/src/daemon/client.ts +20 -2
- package/src/daemon/daemon.ts +9 -2
- package/src/daemon/grants.ts +4 -3
- package/src/daemon/http.ts +8 -2
- package/src/daemon/live-access.ts +19 -0
- package/src/daemon/protocol.ts +7 -0
- package/src/daemon/requests.ts +65 -36
- package/src/daemon/spawn.ts +68 -14
- package/src/import/1password-live.ts +55 -16
- package/src/import/1password.ts +6 -4
- package/src/import/bitwarden.ts +3 -8
- package/src/import/dotenv.ts +2 -1
- package/src/import/keepass.ts +4 -5
- package/src/import/lastpass.ts +0 -1
- package/src/import/shared.ts +57 -5
- package/src/import/types.ts +1 -1
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +8 -0
- package/src/prompt/types.ts +4 -1
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
package/src/cli/commands/run.ts
CHANGED
|
@@ -1,18 +1,35 @@
|
|
|
1
|
+
import { pipeline } from 'node:stream/promises'
|
|
2
|
+
|
|
1
3
|
import { defineCommand } from 'citty'
|
|
2
4
|
import { z } from 'zod'
|
|
3
5
|
|
|
4
6
|
import { envEligible, envFor, explicitNames, resolveEnvRefs, secretValues } from '../../access/env'
|
|
5
|
-
import { appendAudit } from '../../audit/log'
|
|
6
|
-
import { signerOf } from '../../core/entries'
|
|
7
7
|
import { TypeVaultError } from '../../core/errors'
|
|
8
|
-
import { ENTRY_NAME_SYNTAX } from '../../core/naming'
|
|
8
|
+
import { ENTRY_NAME_SYNTAX, matchesOnly } from '../../core/naming'
|
|
9
9
|
import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
|
|
10
10
|
import { createRedactor, type Redactor, scrubFile } from '../../redact'
|
|
11
|
-
import {
|
|
11
|
+
import { resolveAccess } from '../context'
|
|
12
12
|
import { csv, note, print, readStdin, repeated } from '../output'
|
|
13
13
|
|
|
14
|
-
async function pump(
|
|
15
|
-
|
|
14
|
+
async function pump(
|
|
15
|
+
stream: ReadableStream<Uint8Array>,
|
|
16
|
+
redactor: Redactor,
|
|
17
|
+
sink: NodeJS.WriteStream,
|
|
18
|
+
onClosed: () => void = () => {},
|
|
19
|
+
): Promise<void> {
|
|
20
|
+
const isClosed = (error: unknown): boolean =>
|
|
21
|
+
error instanceof Error && 'code' in error && (error.code === 'EPIPE' || error.code === 'ENOTCONN')
|
|
22
|
+
const onError = (error: Error) => {
|
|
23
|
+
if (isClosed(error)) onClosed()
|
|
24
|
+
}
|
|
25
|
+
sink.on('error', onError)
|
|
26
|
+
try {
|
|
27
|
+
await pipeline(stream.pipeThrough(redactor.stream()), sink, { end: false })
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (!isClosed(error)) throw error
|
|
30
|
+
} finally {
|
|
31
|
+
sink.off('error', onError)
|
|
32
|
+
}
|
|
16
33
|
}
|
|
17
34
|
|
|
18
35
|
export const run = defineCommand({
|
|
@@ -27,8 +44,10 @@ export const run = defineCommand({
|
|
|
27
44
|
if (command.length === 0)
|
|
28
45
|
throw new TypeVaultError('invalid', 'usage: typevault run [--only ...] -- <command> [args...]')
|
|
29
46
|
const access = (await resolveAccess(process.env)).access
|
|
30
|
-
const only =
|
|
47
|
+
const only = repeated(rawArgs.slice(0, dash), '--only').flatMap(csv)
|
|
31
48
|
const values = await access.values(only, args.reason)
|
|
49
|
+
const unmatched = only.filter((pattern) => !values.some((value) => matchesOnly(value.name, [pattern])))
|
|
50
|
+
if (unmatched.length > 0) note(`warning: --only matched no entries: ${unmatched.join(', ')}`)
|
|
32
51
|
const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
|
|
33
52
|
const env = envFor(values, new Date(), policy)
|
|
34
53
|
// The child gets its secrets, never the key or grant that opens the vault.
|
|
@@ -41,20 +60,60 @@ export const run = defineCommand({
|
|
|
41
60
|
if (skipped.length > 0) note(`not loaded (from included tiers; name them in --only): ${skipped.join(', ')}`)
|
|
42
61
|
const clash = Object.keys(refs.env).find((name) => Object.hasOwn(env, name))
|
|
43
62
|
if (clash !== undefined)
|
|
44
|
-
throw new TypeVaultError('conflict', `${clash} is both a
|
|
63
|
+
throw new TypeVaultError('conflict', `${clash} is both a typevault:// reference and an entry's variable`)
|
|
45
64
|
const redactor = createRedactor([
|
|
46
65
|
...secretValues([...values, ...refs.values]),
|
|
47
66
|
...Object.values(env),
|
|
48
67
|
...Object.values(refs.env),
|
|
49
68
|
])
|
|
50
|
-
const child =
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
69
|
+
const child = (() => {
|
|
70
|
+
try {
|
|
71
|
+
return Bun.spawn(command, {
|
|
72
|
+
env: { ...inherited, ...env, ...refs.env },
|
|
73
|
+
// Own the group so descendants receive forwarded signals, and terminal Ctrl-C reaches them only once.
|
|
74
|
+
detached: process.platform !== 'win32',
|
|
75
|
+
stdin: 'inherit',
|
|
76
|
+
stdout: 'pipe',
|
|
77
|
+
stderr: 'pipe',
|
|
78
|
+
})
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EACCES')) {
|
|
81
|
+
note(error.message)
|
|
82
|
+
return error.code === 'ENOENT' ? 127 : 126
|
|
83
|
+
}
|
|
84
|
+
throw error
|
|
85
|
+
}
|
|
86
|
+
})()
|
|
87
|
+
if (typeof child === 'number') {
|
|
88
|
+
process.exitCode = child
|
|
89
|
+
return
|
|
90
|
+
}
|
|
91
|
+
const signals = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
|
|
92
|
+
const forward = (signal: NodeJS.Signals): void => {
|
|
93
|
+
if (process.platform === 'win32') {
|
|
94
|
+
child.kill(signal)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
process.kill(-child.pid, signal)
|
|
99
|
+
} catch (error) {
|
|
100
|
+
// The group may have exited before its exit notification was handled.
|
|
101
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// A closed reader must not leave the child or its descendants blocked on their output pipes.
|
|
105
|
+
const onClosed = () => forward('SIGKILL')
|
|
106
|
+
for (const signal of signals) process.on(signal, forward)
|
|
107
|
+
try {
|
|
108
|
+
const [code] = await Promise.all([
|
|
109
|
+
child.exited,
|
|
110
|
+
pump(child.stdout, redactor, process.stdout, onClosed),
|
|
111
|
+
pump(child.stderr, redactor, process.stderr, onClosed),
|
|
112
|
+
])
|
|
113
|
+
process.exitCode = code
|
|
114
|
+
} finally {
|
|
115
|
+
for (const signal of signals) process.off(signal, forward)
|
|
116
|
+
}
|
|
58
117
|
},
|
|
59
118
|
})
|
|
60
119
|
|
|
@@ -65,6 +124,12 @@ async function redactorFor(): Promise<Redactor> {
|
|
|
65
124
|
resolved.kind === 'direct'
|
|
66
125
|
? secretValues(await resolved.access.values([], 'redact'))
|
|
67
126
|
: await resolved.access.readValues()
|
|
127
|
+
if (!values.some((value) => Array.from(value).length >= 4)) {
|
|
128
|
+
throw new TypeVaultError(
|
|
129
|
+
'unavailable',
|
|
130
|
+
'No redactable values are available; use the still-active grant that read the secrets',
|
|
131
|
+
)
|
|
132
|
+
}
|
|
68
133
|
return createRedactor(values)
|
|
69
134
|
}
|
|
70
135
|
|
|
@@ -83,14 +148,62 @@ export const scrub = defineCommand({
|
|
|
83
148
|
},
|
|
84
149
|
args: { files: { type: 'positional', description: 'Files to scrub', required: true } },
|
|
85
150
|
async run({ args, rawArgs }) {
|
|
86
|
-
const
|
|
87
|
-
const
|
|
151
|
+
const dash = rawArgs.indexOf('--')
|
|
152
|
+
const before = dash === -1 ? rawArgs : rawArgs.slice(0, dash)
|
|
153
|
+
const option = before.find((arg) => arg.startsWith('-'))
|
|
154
|
+
if (option !== undefined) throw new TypeVaultError('invalid', `Unknown scrub option: ${option}`)
|
|
155
|
+
const files = dash === -1 ? before : [...before, ...rawArgs.slice(dash + 1)]
|
|
88
156
|
if (files.length === 0) throw new TypeVaultError('invalid', `usage: typevault scrub <file>... (got ${args.files})`)
|
|
89
|
-
|
|
157
|
+
const redactor = await redactorFor()
|
|
158
|
+
for (const file of files) {
|
|
159
|
+
try {
|
|
160
|
+
if (await scrubFile(file, redactor)) print(file)
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (!(error instanceof TypeVaultError)) throw error
|
|
163
|
+
note(`typevault: ${error.message}`)
|
|
164
|
+
process.exitCode = 1
|
|
165
|
+
}
|
|
166
|
+
}
|
|
90
167
|
},
|
|
91
168
|
})
|
|
92
169
|
|
|
93
|
-
const RequestResponse = z.object({ id: z.string(), url: z.string(), code: z.string() })
|
|
170
|
+
const RequestResponse = z.object({ id: z.string(), url: z.string(), code: z.string(), expiresAt: z.number() })
|
|
171
|
+
const RequestDone = z.object({ stored: z.string() })
|
|
172
|
+
const REQUEST_POLL_MS = 30_000
|
|
173
|
+
|
|
174
|
+
type RequestWaitAccess = {
|
|
175
|
+
call<T>(path: string, body: unknown, schema: z.ZodType<T>, timeoutMs?: number): Promise<T>
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
type RequestWait = {
|
|
179
|
+
readonly id: string
|
|
180
|
+
readonly expiresAt: number
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
type RequestWaitOptions = {
|
|
184
|
+
readonly pollMs?: number
|
|
185
|
+
readonly now?: () => number
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function waitForRequest(
|
|
189
|
+
access: RequestWaitAccess,
|
|
190
|
+
request: RequestWait,
|
|
191
|
+
options: RequestWaitOptions = {},
|
|
192
|
+
): Promise<z.infer<typeof RequestDone>> {
|
|
193
|
+
const now = options.now ?? Date.now
|
|
194
|
+
const pollMs = options.pollMs ?? REQUEST_POLL_MS
|
|
195
|
+
while (true) {
|
|
196
|
+
const remaining = request.expiresAt - now()
|
|
197
|
+
if (remaining <= 0) throw new TypeVaultError('expired', 'the request expired')
|
|
198
|
+
try {
|
|
199
|
+
return await access.call('/v1/request/wait', { id: request.id }, RequestDone, Math.min(pollMs, remaining))
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error instanceof TypeVaultError && error.cause instanceof Error && error.cause.name === 'TimeoutError')
|
|
202
|
+
continue
|
|
203
|
+
throw error
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
94
207
|
|
|
95
208
|
export const request = defineCommand({
|
|
96
209
|
meta: { name: 'request', description: 'Ask a human for a secret through a one-time web page (live grants)' },
|
|
@@ -112,12 +225,7 @@ export const request = defineCommand({
|
|
|
112
225
|
}
|
|
113
226
|
const opened = await resolved.access.call('/v1/request', body, RequestResponse)
|
|
114
227
|
print(`Send this link to the human: ${opened.url}\nMatch code: ${opened.code} (post it in the chat too)`)
|
|
115
|
-
const done = await resolved.access
|
|
116
|
-
'/v1/request/wait',
|
|
117
|
-
{ id: opened.id },
|
|
118
|
-
z.object({ stored: z.string() }),
|
|
119
|
-
11 * 60_000,
|
|
120
|
-
)
|
|
228
|
+
const done = await waitForRequest(resolved.access, opened)
|
|
121
229
|
print(`stored as ${done.stored}`)
|
|
122
230
|
},
|
|
123
231
|
})
|
|
@@ -129,7 +237,7 @@ const isVia = (value: string): value is OnePasswordVia => ONEPASSWORD_VIAS.some(
|
|
|
129
237
|
export const importCommand = defineCommand({
|
|
130
238
|
meta: {
|
|
131
239
|
name: 'import',
|
|
132
|
-
description: 'Import a password-manager export, or 1Password directly, into a tier (
|
|
240
|
+
description: 'Import a password-manager export, or 1Password directly, into a tier (one transaction)',
|
|
133
241
|
},
|
|
134
242
|
args: {
|
|
135
243
|
source: { type: 'positional', required: true, description: SOURCES.join(' | ') },
|
|
@@ -152,7 +260,10 @@ export const importCommand = defineCommand({
|
|
|
152
260
|
}
|
|
153
261
|
const via = args.via ?? 'sdk'
|
|
154
262
|
if (!isVia(via)) throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
|
|
155
|
-
const
|
|
263
|
+
const resolved = await resolveAccess(process.env)
|
|
264
|
+
if (resolved.kind === 'sealed') {
|
|
265
|
+
throw new TypeVaultError('unavailable', 'import needs an unlocked vault or a live grant, not a sealed grant')
|
|
266
|
+
}
|
|
156
267
|
const password = args['password-stdin'] ? await readStdin() : undefined
|
|
157
268
|
const result =
|
|
158
269
|
args.path === undefined
|
|
@@ -163,22 +274,8 @@ export const importCommand = defineCommand({
|
|
|
163
274
|
tags: repeated(rawArgs, '--tag'),
|
|
164
275
|
})
|
|
165
276
|
: await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
|
|
166
|
-
const
|
|
167
|
-
const stored = await vault.putMany(
|
|
168
|
-
result.entries.map((entry) => ({ ...entry, tier })),
|
|
169
|
-
async (target) => {
|
|
170
|
-
const key = vault.keyring.owner ?? (await vault.keyring.unlock(target))
|
|
171
|
-
if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${target}"`)
|
|
172
|
-
return signerOf(key)
|
|
173
|
-
},
|
|
174
|
-
)
|
|
175
|
-
await appendAudit(vault.layout, {
|
|
176
|
-
action: 'import',
|
|
177
|
-
mode: 'direct',
|
|
178
|
-
tiers: [tier],
|
|
179
|
-
entries: stored.map((e) => e.payload.name),
|
|
180
|
-
})
|
|
277
|
+
const stored = await resolved.access.importEntries(result.entries, args.tier)
|
|
181
278
|
for (const warning of result.warnings) note(`warning: ${warning}`)
|
|
182
|
-
note(`imported ${stored.length} entries into ${tier}`)
|
|
279
|
+
note(`imported ${stored.length} entries into ${args.tier}`)
|
|
183
280
|
},
|
|
184
281
|
})
|
package/src/cli/context.ts
CHANGED
|
@@ -27,7 +27,10 @@ export type Env = Readonly<Record<string, string | undefined>>
|
|
|
27
27
|
const isSet = (value: string | undefined): boolean => value !== undefined && value !== ''
|
|
28
28
|
|
|
29
29
|
/** `-g` (`TYPEVAULT_GLOBAL`) or an explicit `TYPEVAULT_DIR` selects the global vault; otherwise the project's. */
|
|
30
|
-
export const wantsGlobal = (env: Env): boolean =>
|
|
30
|
+
export const wantsGlobal = (env: Env): boolean => {
|
|
31
|
+
const global = env['TYPEVAULT_GLOBAL']?.toLowerCase()
|
|
32
|
+
return (isSet(global) && global !== '0' && global !== 'false') || isSet(env['TYPEVAULT_DIR'])
|
|
33
|
+
}
|
|
31
34
|
|
|
32
35
|
/** The selected vault, or undefined when no project vault is found from `cwd`. Never falls back to the global one. */
|
|
33
36
|
export function findLayout(env: Env, cwd: string = process.cwd()): Layout | undefined {
|
|
@@ -114,9 +117,14 @@ async function shareWorktreeSession(layout: Layout, env: Env): Promise<boolean>
|
|
|
114
117
|
const [unlocked] = await worktreeSessions(layout, env)
|
|
115
118
|
if (unlocked === undefined) return false
|
|
116
119
|
const token = readFileSync(unlocked.sessionFile, 'utf8').trim()
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
+
try {
|
|
121
|
+
await callDaemon(unlocked.agentSocket, '/v1/attach', { vault: layout.vault }, z.object({ ok: z.literal(true) }), {
|
|
122
|
+
token,
|
|
123
|
+
})
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof TypeVaultError) return false
|
|
126
|
+
throw error
|
|
127
|
+
}
|
|
120
128
|
return true
|
|
121
129
|
}
|
|
122
130
|
|
|
@@ -179,6 +187,8 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
|
179
187
|
if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
180
188
|
await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
|
|
181
189
|
}
|
|
190
|
+
// A session daemon from another release fails here instead of misreading this CLI's requests.
|
|
191
|
+
await ensureDaemon(layout, env)
|
|
182
192
|
return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
|
|
183
193
|
}
|
|
184
194
|
|
package/src/cli/index.ts
CHANGED
|
@@ -75,6 +75,11 @@ if (wantsUsage) {
|
|
|
75
75
|
}
|
|
76
76
|
// citty's usage errors (unknown command, missing argument): its own runner prints usage for them.
|
|
77
77
|
if (error instanceof Error && error.name === 'CLIError') await runMain(main)
|
|
78
|
-
else
|
|
78
|
+
else {
|
|
79
|
+
const message = error instanceof Error ? error.message : 'unexpected error'
|
|
80
|
+
process.stderr.write(`typevault: ${message.replaceAll(/[\r\n]+/g, ' ')}\n`)
|
|
81
|
+
if (process.env['TYPEVAULT_DEBUG'] === '1') console.error(error)
|
|
82
|
+
process.exit(1)
|
|
83
|
+
}
|
|
79
84
|
}
|
|
80
85
|
}
|
package/src/cli/output.ts
CHANGED
|
@@ -14,7 +14,11 @@ export function table(rows: readonly (readonly string[])[]): string {
|
|
|
14
14
|
)
|
|
15
15
|
return rows
|
|
16
16
|
.map((row) =>
|
|
17
|
-
row
|
|
17
|
+
row
|
|
18
|
+
.map((cell, index) =>
|
|
19
|
+
index === row.length - 1 ? cell : cell + ' '.repeat((widths[index] ?? 0) - Bun.stringWidth(cell)),
|
|
20
|
+
)
|
|
21
|
+
.join(' '),
|
|
18
22
|
)
|
|
19
23
|
.join('\n')
|
|
20
24
|
}
|
package/src/cli/web-prompt.ts
CHANGED
|
@@ -22,27 +22,41 @@ export type WebEntry = {
|
|
|
22
22
|
export async function promptFields(
|
|
23
23
|
entry: WebEntry,
|
|
24
24
|
show: (url: string, code: string) => void,
|
|
25
|
+
options: { readonly ttlMs?: number } = {},
|
|
25
26
|
): Promise<Record<string, Field>> {
|
|
26
27
|
const identity = await generateX25519Identity()
|
|
27
28
|
const server = await startPromptServer()
|
|
28
29
|
try {
|
|
29
30
|
const code = matchCode()
|
|
30
|
-
const handle = server.open(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
31
|
+
const handle = server.open(
|
|
32
|
+
{
|
|
33
|
+
name: entry.name,
|
|
34
|
+
...(entry.preset === undefined ? {} : { preset: entry.preset }),
|
|
35
|
+
tier: entry.tier ?? 'your default tier',
|
|
36
|
+
reason: `Store ${entry.name} from your terminal`,
|
|
37
|
+
requester: 'typevault set',
|
|
38
|
+
code,
|
|
39
|
+
recipients: [await identityToRecipient(identity)],
|
|
40
|
+
expiresAt: new Date(Date.now() + (options.ttlMs ?? TTL_MS)),
|
|
41
|
+
},
|
|
42
|
+
{ validate: true },
|
|
43
|
+
)
|
|
40
44
|
show(handle.url, code)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
try {
|
|
46
|
+
const payload = decodePayload(await unseal([identity], await handle.done))
|
|
47
|
+
if (payload.name !== entry.name) {
|
|
48
|
+
throw new TypeVaultError('tampered', 'the submitted secret does not match this entry')
|
|
49
|
+
}
|
|
50
|
+
await handle.accept()
|
|
51
|
+
return { ...payload.fields }
|
|
52
|
+
} catch (error) {
|
|
53
|
+
await handle.reject(
|
|
54
|
+
error instanceof TypeVaultError
|
|
55
|
+
? error
|
|
56
|
+
: new TypeVaultError('unavailable', 'the submitted secret could not be read'),
|
|
57
|
+
)
|
|
58
|
+
throw error
|
|
44
59
|
}
|
|
45
|
-
return { ...payload.fields }
|
|
46
60
|
} finally {
|
|
47
61
|
await server.stop()
|
|
48
62
|
}
|
package/src/core/admin.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal, type SecretKey } from './crypto'
|
|
2
|
-
import { utf8 } from './encoding'
|
|
2
|
+
import { fromBase64, utf8 } from './encoding'
|
|
3
3
|
import { signerOf } from './entries'
|
|
4
4
|
import { TypeVaultError } from './errors'
|
|
5
5
|
import { ownerWrapPath, wrapPath } from './keyring'
|
|
@@ -128,11 +128,14 @@ export class Admin {
|
|
|
128
128
|
return affected
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
-
/**
|
|
131
|
+
/** Rotates every tier `name` reaches. Returns their entry names, now flagged for rotation at the source. */
|
|
132
132
|
async rotate(name: string): Promise<readonly string[]> {
|
|
133
133
|
let affected: readonly string[] = []
|
|
134
134
|
await this.#mutate(async (state, txn) => {
|
|
135
|
-
affected = await rotateTiers(
|
|
135
|
+
affected = await rotateTiers(
|
|
136
|
+
{ vault: this.#vault, owner: this.#owner, state, txn, exposed: true },
|
|
137
|
+
reachOf(state, [name]),
|
|
138
|
+
)
|
|
136
139
|
})
|
|
137
140
|
return affected
|
|
138
141
|
}
|
|
@@ -178,17 +181,30 @@ export class Admin {
|
|
|
178
181
|
return affected
|
|
179
182
|
}
|
|
180
183
|
|
|
181
|
-
setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
|
|
182
|
-
|
|
184
|
+
async setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
|
|
185
|
+
const name = parseTierName(id)
|
|
186
|
+
let key: Uint8Array
|
|
187
|
+
try {
|
|
188
|
+
key = fromBase64(signPublic)
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error instanceof Error) throw new TypeVaultError('invalid', 'signer public key is not valid base64')
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
if (key.length !== 32) throw new TypeVaultError('invalid', 'signer public key must be 32 bytes')
|
|
194
|
+
if (tiers.length === 0) throw new TypeVaultError('invalid', 'signer needs at least one tier')
|
|
195
|
+
await this.#mutate(async (state, txn) => {
|
|
196
|
+
const unknown = tiers.find((tier) => tier !== '*' && state.tiers[tier] === undefined)
|
|
197
|
+
if (unknown !== undefined) throw new TypeVaultError('not_found', `no tier "${unknown}"`)
|
|
183
198
|
txn.put(
|
|
184
199
|
'signers.json',
|
|
185
|
-
signersDoc({ ...state.signers, [
|
|
200
|
+
signersDoc({ ...state.signers, [name]: { signPublic, tiers } }, this.#owner, state.seqs.signers + 1),
|
|
186
201
|
)
|
|
187
202
|
})
|
|
188
203
|
}
|
|
189
204
|
|
|
190
205
|
removeSigner(id: string): Promise<void> {
|
|
191
206
|
return this.#mutate(async (state, txn) => {
|
|
207
|
+
if (state.signers[id] === undefined) throw new TypeVaultError('not_found', `no signer "${id}"`)
|
|
192
208
|
const { [id]: _removed, ...rest } = state.signers
|
|
193
209
|
txn.put('signers.json', signersDoc(rest, this.#owner, state.seqs.signers + 1))
|
|
194
210
|
})
|
|
@@ -206,6 +222,7 @@ export class Admin {
|
|
|
206
222
|
|
|
207
223
|
removeCeiling(name: string): Promise<void> {
|
|
208
224
|
return this.#mutate(async (state, txn) => {
|
|
225
|
+
if (state.ceilings[name] === undefined) throw new TypeVaultError('not_found', `no ceiling "${name}"`)
|
|
209
226
|
const { [name]: _removed, ...rest } = state.ceilings
|
|
210
227
|
txn.put('ceilings.json', ceilingsDoc(rest, this.#owner, state.seqs.ceilings + 1))
|
|
211
228
|
})
|
package/src/core/doctor.ts
CHANGED
|
@@ -15,7 +15,7 @@ export type DoctorReport = {
|
|
|
15
15
|
readonly needsRotation: readonly string[]
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const CONFLICT = /^<<<<<<< [^\n]*\n([\s\S]*?)^=======\n([\s\S]*?)^>>>>>>> [^\n]*\n?/
|
|
18
|
+
const CONFLICT = /^<<<<<<< [^\n]*\n([\s\S]*?)^=======\n([\s\S]*?)^>>>>>>> [^\n]*\n?/gm
|
|
19
19
|
|
|
20
20
|
function parseSide(text: string): Envelope | undefined {
|
|
21
21
|
try {
|
|
@@ -31,12 +31,11 @@ function parseSide(text: string): Envelope | undefined {
|
|
|
31
31
|
function resolveMerge(vault: Vault, file: string): boolean {
|
|
32
32
|
const path = join(vault.layout.entries, file)
|
|
33
33
|
const text = readFileSync(path, 'utf8')
|
|
34
|
-
const
|
|
35
|
-
if (
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
.map((side) => parseSide(before + side + after))
|
|
34
|
+
const ours = text.replace(CONFLICT, '$1')
|
|
35
|
+
if (ours === text) return false
|
|
36
|
+
const theirs = text.replace(CONFLICT, '$2')
|
|
37
|
+
const sides = [ours, theirs]
|
|
38
|
+
.map(parseSide)
|
|
40
39
|
.filter((side): side is Envelope => side !== undefined && verifyEnvelope(side, vault.state) === undefined)
|
|
41
40
|
const winner = sides.reduce<Envelope | undefined>(
|
|
42
41
|
(best, side) =>
|
package/src/core/errors.ts
CHANGED
|
@@ -17,8 +17,8 @@ export type ErrorCode =
|
|
|
17
17
|
export class TypeVaultError extends Error {
|
|
18
18
|
readonly code: ErrorCode
|
|
19
19
|
|
|
20
|
-
constructor(code: ErrorCode, message: string) {
|
|
21
|
-
super(message)
|
|
20
|
+
constructor(code: ErrorCode, message: string, options?: ErrorOptions) {
|
|
21
|
+
super(message, options)
|
|
22
22
|
this.name = 'TypeVaultError'
|
|
23
23
|
this.code = code
|
|
24
24
|
}
|
package/src/core/holder.ts
CHANGED
|
@@ -1,16 +1,24 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { hostname } from 'node:os'
|
|
2
3
|
|
|
3
4
|
import { z } from 'zod'
|
|
4
5
|
|
|
5
6
|
import { randomHex } from './crypto'
|
|
6
7
|
import { TypeVaultError } from './errors'
|
|
8
|
+
import { readJsonFile } from './json-file'
|
|
7
9
|
import { hostId, type Layout } from './layout'
|
|
8
10
|
|
|
9
11
|
type Env = Readonly<Record<string, string | undefined>>
|
|
10
12
|
|
|
11
13
|
const CLAIM_ATTEMPTS = 3
|
|
12
14
|
|
|
13
|
-
const HolderSchema = z.object({
|
|
15
|
+
const HolderSchema = z.object({
|
|
16
|
+
host: z.string(),
|
|
17
|
+
name: z.string(),
|
|
18
|
+
pid: z.number().int(),
|
|
19
|
+
token: z.string(),
|
|
20
|
+
at: z.string(),
|
|
21
|
+
})
|
|
14
22
|
type Holder = z.infer<typeof HolderSchema>
|
|
15
23
|
|
|
16
24
|
export type DaemonClaim = {
|
|
@@ -36,7 +44,13 @@ export function refuseForeignDaemon(layout: Layout, env: Env): void {
|
|
|
36
44
|
*/
|
|
37
45
|
export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
|
|
38
46
|
const token = randomHex(8)
|
|
39
|
-
const record = JSON.stringify({
|
|
47
|
+
const record = JSON.stringify({
|
|
48
|
+
host: hostId(env),
|
|
49
|
+
name: hostname(),
|
|
50
|
+
pid: process.pid,
|
|
51
|
+
token,
|
|
52
|
+
at: new Date().toISOString(),
|
|
53
|
+
})
|
|
40
54
|
for (let attempt = 0; ; attempt++) {
|
|
41
55
|
try {
|
|
42
56
|
writeFileSync(layout.daemonHolder, record, { flag: 'wx', mode: 0o600 })
|
|
@@ -62,22 +76,24 @@ export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
|
|
|
62
76
|
|
|
63
77
|
function readHolder(layout: Layout): Holder | undefined {
|
|
64
78
|
if (!existsSync(layout.daemonHolder)) return undefined
|
|
65
|
-
let text: string
|
|
66
79
|
try {
|
|
67
|
-
|
|
80
|
+
return readJsonFile(layout.daemonHolder, HolderSchema)
|
|
68
81
|
} catch (error) {
|
|
69
82
|
if (isCode(error, 'ENOENT')) return undefined
|
|
83
|
+
if (error instanceof TypeVaultError && error.code === 'tampered') {
|
|
84
|
+
throw new TypeVaultError(
|
|
85
|
+
'tampered',
|
|
86
|
+
`${layout.daemonHolder} is malformed; if its daemon is gone for good, delete this file and retry`,
|
|
87
|
+
)
|
|
88
|
+
}
|
|
70
89
|
throw error
|
|
71
90
|
}
|
|
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
91
|
}
|
|
76
92
|
|
|
77
93
|
const inUse = (layout: Layout, holder: Holder): TypeVaultError =>
|
|
78
94
|
new TypeVaultError(
|
|
79
95
|
'in_use',
|
|
80
|
-
`a typevault daemon on another machine (${holder.
|
|
96
|
+
`a typevault daemon on another machine (${holder.name}, 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
97
|
)
|
|
82
98
|
|
|
83
99
|
const isCode = (error: unknown, code: string): boolean =>
|
package/src/core/identity.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
|
|
4
4
|
import { z } from 'zod'
|
|
@@ -13,7 +13,8 @@ import {
|
|
|
13
13
|
} from './crypto'
|
|
14
14
|
import { fromBase64Url, fromUtf8, toBase64Url, utf8 } from './encoding'
|
|
15
15
|
import { TypeVaultError } from './errors'
|
|
16
|
-
import { assertNoSymlinks, atomicWrite } from './fsx'
|
|
16
|
+
import { assertNoSymlinks, atomicWrite, ensureDir } from './fsx'
|
|
17
|
+
import { readJsonFile } from './json-file'
|
|
17
18
|
import { configDir, type Layout } from './layout'
|
|
18
19
|
import { generateSecretKeyCode, openWithPassword, sealWithPassword } from './password'
|
|
19
20
|
import { type MemberKind, parseMemberName } from './state'
|
|
@@ -61,10 +62,11 @@ export const identityPath = (env: Env): string => join(configDir(env), 'identity
|
|
|
61
62
|
|
|
62
63
|
export function readIdentity(env: Env): Identity | undefined {
|
|
63
64
|
const path = identityPath(env)
|
|
64
|
-
return existsSync(path) ?
|
|
65
|
+
return existsSync(path) ? readJsonFile(path, IdentitySchema) : undefined
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
export function writeIdentity(env: Env, identity: Identity): void {
|
|
69
|
+
ensureDir(configDir(env), 0o700)
|
|
68
70
|
atomicWrite(identityPath(env), `${JSON.stringify(identity, null, 2)}\n`, 0o600)
|
|
69
71
|
}
|
|
70
72
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
|
|
5
|
+
import { TypeVaultError } from './errors'
|
|
6
|
+
|
|
7
|
+
/** Syntax and schema failures in persisted state are corruption, never request-body errors. */
|
|
8
|
+
export function parseJsonText<T>(path: string, text: string, schema: z.ZodType<T>): T {
|
|
9
|
+
try {
|
|
10
|
+
return schema.parse(JSON.parse(text))
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (error instanceof SyntaxError || error instanceof z.ZodError) {
|
|
13
|
+
throw new TypeVaultError('tampered', `${path} is malformed; repair or restore this file before retrying`)
|
|
14
|
+
}
|
|
15
|
+
throw error
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const readJsonFile = <T>(path: string, schema: z.ZodType<T>): T =>
|
|
20
|
+
parseJsonText(path, readFileSync(path, 'utf8'), schema)
|