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/core/layout.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
1
2
|
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
2
3
|
import { homedir, hostname } from 'node:os'
|
|
3
4
|
import { dirname, join, resolve } from 'node:path'
|
|
4
5
|
|
|
6
|
+
import { z } from 'zod'
|
|
7
|
+
|
|
5
8
|
import { sha256Hex } from './crypto'
|
|
6
9
|
import { utf8 } from './encoding'
|
|
7
|
-
import {
|
|
10
|
+
import { readJsonFile } from './json-file'
|
|
8
11
|
|
|
9
12
|
export type Layout = {
|
|
10
13
|
/** `global`: one vault per user, `~/.typevault/`. `local`: a `.typevault/` committed in a project. */
|
|
@@ -87,10 +90,54 @@ const setting = (env: Env, name: string): string | undefined => {
|
|
|
87
90
|
return value !== undefined && value !== '' ? resolve(value) : undefined
|
|
88
91
|
}
|
|
89
92
|
|
|
90
|
-
|
|
93
|
+
let detectedHost: string | undefined
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* This machine, as daemon holders and audit anchors name it: `TYPEVAULT_HOST_ID`, else a hash of its machine ID, else
|
|
97
|
+
* the hostname. The hostname alone won't do where it can change under a running daemon (macOS takes it from the network).
|
|
98
|
+
*/
|
|
91
99
|
export function hostId(env: Env = process.env): string {
|
|
92
100
|
const explicit = env['TYPEVAULT_HOST_ID']
|
|
93
|
-
|
|
101
|
+
if (explicit !== undefined && explicit !== '') return explicit
|
|
102
|
+
detectedHost ??= hashedMachineId() ?? hostname()
|
|
103
|
+
return detectedHost
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Hashed because anchor file names are committed, and a machine ID is not meant to leave its machine.
|
|
107
|
+
function hashedMachineId(): string | undefined {
|
|
108
|
+
const id = readMachineId()
|
|
109
|
+
return id === undefined ? undefined : shortHash(`typevault-host\0${id}`)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function readMachineId(): string | undefined {
|
|
113
|
+
switch (process.platform) {
|
|
114
|
+
case 'darwin':
|
|
115
|
+
return readDarwinPlatformUuid()
|
|
116
|
+
case 'linux':
|
|
117
|
+
return readLinuxMachineId()
|
|
118
|
+
default:
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Undefined when the file gives no ID: missing or unreadable (a container), or not yet set up (`uninitialized`). */
|
|
124
|
+
export function readLinuxMachineId(path = '/etc/machine-id'): string | undefined {
|
|
125
|
+
try {
|
|
126
|
+
const id = readFileSync(path, 'utf8').trim()
|
|
127
|
+
return id === '' || id === 'uninitialized' ? undefined : id
|
|
128
|
+
} catch {
|
|
129
|
+
return undefined
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function readDarwinPlatformUuid(): string | undefined {
|
|
134
|
+
try {
|
|
135
|
+
const output = execFileSync('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8' })
|
|
136
|
+
return /"IOPlatformUUID" = "([^"]+)"/.exec(output)?.[1]
|
|
137
|
+
} catch {
|
|
138
|
+
// A sandbox can deny the lookup: fall back to the hostname rather than refuse to open any vault.
|
|
139
|
+
return undefined
|
|
140
|
+
}
|
|
94
141
|
}
|
|
95
142
|
|
|
96
143
|
/**
|
|
@@ -111,11 +158,7 @@ function vaultLayout(scope: Layout['scope'], dir: string, env: Env): Layout {
|
|
|
111
158
|
}
|
|
112
159
|
|
|
113
160
|
function ownerSignPublic(vault: string): string {
|
|
114
|
-
|
|
115
|
-
if (typeof owner !== 'object' || owner === null || !('signPublic' in owner) || typeof owner.signPublic !== 'string') {
|
|
116
|
-
throw new TypeVaultError('tampered', `${join(vault, 'owner.json')} is malformed`)
|
|
117
|
-
}
|
|
118
|
-
return owner.signPublic
|
|
161
|
+
return readJsonFile(join(vault, 'owner.json'), z.object({ signPublic: z.string() })).signPublic
|
|
119
162
|
}
|
|
120
163
|
|
|
121
164
|
// A home directory reached through a symlink (macOS's /tmp, say) is still the same directory.
|
package/src/core/naming.ts
CHANGED
|
@@ -21,33 +21,47 @@ export function parsePreset(value: string): Preset {
|
|
|
21
21
|
|
|
22
22
|
export type EntryName = string & { readonly __brand: 'EntryName' }
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
// `-` and `.` only join two other characters, so a segment never starts, ends or doubles them.
|
|
25
|
+
const SEGMENT = /^[\p{L}\p{N}@+](?:[\p{L}\p{M}\p{N}@+]|[.-](?=[\p{L}\p{N}@+]))*$/u
|
|
26
|
+
const LETTER_OR_DIGIT = /[\p{L}\p{N}]/u
|
|
25
27
|
const MAX_SEGMENTS = 2
|
|
28
|
+
const LATIN = /\p{Script=Latin}/u
|
|
29
|
+
// Letters of a script other than Latin and the CJK ones written beside it. Mixed into Latin, they make lookalikes
|
|
30
|
+
// such as a Cyrillic "а" in "github". Script_Extensions keeps shared CJK letters such as the long-vowel mark "ー".
|
|
31
|
+
const NOT_WITH_LATIN =
|
|
32
|
+
/[^\P{L}\p{Script=Latin}\p{scx=Han}\p{scx=Hangul}\p{scx=Hiragana}\p{scx=Katakana}\p{scx=Bopomofo}]/u
|
|
33
|
+
const isSegment = (segment: string): boolean =>
|
|
34
|
+
SEGMENT.test(segment) && LETTER_OR_DIGIT.test(segment) && !(LATIN.test(segment) && NOT_WITH_LATIN.test(segment))
|
|
26
35
|
|
|
27
36
|
/**
|
|
28
|
-
* The one way to point at an entry: `
|
|
29
|
-
*
|
|
30
|
-
*
|
|
37
|
+
* The one way to point at an entry: `typevault://<service>[/<account>][#<field>]`. The scheme may be left out
|
|
38
|
+
* (`github/bot#password`) as shorthand. Every name, `--only` pattern and env reference goes through the parsers
|
|
39
|
+
* below.
|
|
31
40
|
*/
|
|
32
|
-
export const ENTRY_NAME_SYNTAX = '
|
|
41
|
+
export const ENTRY_NAME_SYNTAX = 'typevault://<service>[/<account>]'
|
|
33
42
|
export const ENTRY_REF_SYNTAX = `${ENTRY_NAME_SYNTAX}[#<field>]`
|
|
34
43
|
|
|
35
|
-
const REF_SCHEME = /^
|
|
44
|
+
const REF_SCHEME = /^typevault:\/\//i
|
|
36
45
|
|
|
37
|
-
/** True when `input` carries the `
|
|
46
|
+
/** True when `input` carries the `typevault://` scheme, as an env value `run` resolves. */
|
|
38
47
|
export const hasRefScheme = (input: string): boolean => REF_SCHEME.test(input.trim())
|
|
39
48
|
|
|
40
|
-
/** An `--only` pattern (a name or a glob) in the form names are stored in: no scheme, lowercase. */
|
|
41
|
-
export const entryPattern = (input: string): string =>
|
|
49
|
+
/** An `--only` pattern (a name or a glob) in the form names are stored in: no scheme, lowercase, NFC. */
|
|
50
|
+
export const entryPattern = (input: string): string =>
|
|
51
|
+
input.trim().replace(REF_SCHEME, '').toLowerCase().normalize('NFC')
|
|
42
52
|
|
|
43
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* Parses `[typevault://]<service>[/<account>]`. Names are case-insensitive, stored lowercase, NFC and without the
|
|
55
|
+
* scheme. A segment is letters and digits of any script with `@`, `+`, and `-` or `.` between them, but never Latin
|
|
56
|
+
* mixed with a script other than Chinese, Japanese or Korean.
|
|
57
|
+
*/
|
|
44
58
|
export function parseEntryName(input: string): EntryName {
|
|
45
59
|
const name = entryPattern(input)
|
|
46
60
|
const segments = name.split('/')
|
|
47
|
-
if (segments.length > MAX_SEGMENTS || !segments.every(
|
|
61
|
+
if (segments.length > MAX_SEGMENTS || !segments.every(isSegment)) {
|
|
48
62
|
throw new TypeVaultError(
|
|
49
63
|
'invalid',
|
|
50
|
-
`invalid entry name "${input}" (expected ${ENTRY_NAME_SYNTAX}, segments
|
|
64
|
+
`invalid entry name "${input}" (expected ${ENTRY_NAME_SYNTAX}, segments of letters, digits, @ + - ., Latin mixed only with CJK)`,
|
|
51
65
|
)
|
|
52
66
|
}
|
|
53
67
|
return name as EntryName
|
|
@@ -68,7 +82,7 @@ export const isFieldName = (field: string): boolean =>
|
|
|
68
82
|
field.trim() === field &&
|
|
69
83
|
!/[\p{Cc}=]/u.test(field)
|
|
70
84
|
|
|
71
|
-
/** Parses `[
|
|
85
|
+
/** Parses `[typevault://]<service>[/<account>][#<field>]`. The field is everything after the first `#`. */
|
|
72
86
|
export function parseEntryRef(input: string): EntryRef {
|
|
73
87
|
const hash = input.indexOf('#')
|
|
74
88
|
if (hash === -1) return { name: parseEntryName(input), field: undefined }
|
|
@@ -155,30 +169,21 @@ function assertNever(value: never): never {
|
|
|
155
169
|
|
|
156
170
|
/**
|
|
157
171
|
* `github/bot` + `password` becomes `GITHUB_BOT_PASSWORD`, and `Secret Access Key` becomes `..._SECRET_ACCESS_KEY`.
|
|
158
|
-
* Undefined when no letter or digit of the field survives (a non-Latin
|
|
159
|
-
* through a `
|
|
172
|
+
* Undefined when the name has a letter outside Latin, or no letter or digit of the field survives (a non-Latin
|
|
173
|
+
* field): such an entry or field is reachable only through a `typevault://` ref.
|
|
160
174
|
*/
|
|
161
175
|
export function deriveEnvName(name: EntryName, field: string): string | undefined {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
176
|
+
const prefix = foldUpper(name)
|
|
177
|
+
if (!/^[A-Z0-9/.@+-]+$/.test(prefix)) return undefined
|
|
178
|
+
const base = prefix.replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')
|
|
179
|
+
if (field === '$default') return base
|
|
180
|
+
const suffix = foldUpper(field)
|
|
167
181
|
.replace(/[^A-Z0-9]+/g, '_')
|
|
168
182
|
.replace(/^_+|_+$/g, '')
|
|
169
|
-
return suffix === '' ? undefined : `${
|
|
183
|
+
return suffix === '' ? undefined : `${base}_${suffix}`
|
|
170
184
|
}
|
|
171
185
|
|
|
172
|
-
|
|
173
|
-
export function slugifySegment(raw: string): string {
|
|
174
|
-
const slug = raw
|
|
175
|
-
.normalize('NFKD')
|
|
176
|
-
.replace(/\p{M}/gu, '')
|
|
177
|
-
.toLowerCase()
|
|
178
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
179
|
-
.replace(/^-+|-+$/g, '')
|
|
180
|
-
return slug === '' ? 'item' : slug
|
|
181
|
-
}
|
|
186
|
+
const foldUpper = (text: string): string => text.normalize('NFKD').replace(/\p{M}/gu, '').toUpperCase()
|
|
182
187
|
|
|
183
188
|
/** True when `name` matches any `--only` pattern (exact names or globs such as `github/*`). */
|
|
184
189
|
export function matchesOnly(name: EntryName, patterns: readonly string[]): boolean {
|
|
@@ -197,9 +202,12 @@ const RESERVED_ENV = new RegExp(
|
|
|
197
202
|
'EDITOR|VISUAL|PAGER|BROWSER|MANPAGER|LESS\\w*|SSH_ASKPASS\\w*|SSH_AUTH_SOCK|GIT_\\w*',
|
|
198
203
|
// interpreters and loaders
|
|
199
204
|
'NODE_OPTIONS|NODE_PATH|NODE_EXTRA_CA_CERTS|PYTHONPATH|PYTHONHOME|PYTHONSTARTUP|RUBYOPT|RUBYLIB|PERL5OPT|PERL5LIB|PERLLIB',
|
|
205
|
+
'NODE_TLS_REJECT_UNAUTHORIZED|CLASSPATH|GEM_PATH|GEM_HOME|GCONV_PATH',
|
|
200
206
|
'JAVA_TOOL_OPTIONS|_JAVA_OPTIONS|JDK_JAVA_OPTIONS|LD_\\w*|DYLD_\\w*|BUN_\\w*|NPM_CONFIG_\\w*',
|
|
201
207
|
// where traffic goes and which certificates it trusts
|
|
202
|
-
'
|
|
208
|
+
'\\w*_PROXY|SOCKS_\\w*|\\w*_CA_BUNDLE|\\w*_CA_CERTS|\\w*CERT_FILE|SSL_CERT_DIR|SSLKEYLOGFILE',
|
|
209
|
+
// tool config directories, without reserving unrelated names such as CUSTOMER_HOME
|
|
210
|
+
'CURL_HOME|WGETRC',
|
|
203
211
|
// package managers and toolchains that fetch or run code
|
|
204
212
|
'PIP_\\w*|UV_\\w*|CARGO_\\w*|RUSTC_WRAPPER|RUSTC|GOFLAGS|GOPROXY|GONOSUMDB|GOPRIVATE|DOCKER_HOST|DOCKER_CONFIG',
|
|
205
213
|
'TYPEVAULT_\\w*',
|
package/src/core/payload.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type EntryPayload = {
|
|
|
11
11
|
readonly fields: Readonly<Record<string, Field>>
|
|
12
12
|
readonly env?: string
|
|
13
13
|
readonly origin?: string
|
|
14
|
+
/** The password-manager item an import took this entry from, so a later import finds it after a rename. */
|
|
15
|
+
readonly source?: string
|
|
14
16
|
readonly tags: readonly string[]
|
|
15
17
|
readonly created: string
|
|
16
18
|
readonly rotated: string
|
|
@@ -42,6 +44,7 @@ const PayloadSchema = z
|
|
|
42
44
|
.regex(/^[A-Z_][A-Z0-9_]*$/)
|
|
43
45
|
.optional(),
|
|
44
46
|
origin: z.string().optional(),
|
|
47
|
+
source: z.string().optional(),
|
|
45
48
|
tags: z.array(z.string()),
|
|
46
49
|
created: z.iso.datetime(),
|
|
47
50
|
rotated: z.iso.datetime(),
|
|
@@ -53,13 +56,13 @@ function parsePayload(value: unknown, code: 'invalid' | 'tampered'): z.infer<typ
|
|
|
53
56
|
const parsed = PayloadSchema.safeParse(value)
|
|
54
57
|
if (!parsed.success)
|
|
55
58
|
throw new TypeVaultError(code, `malformed entry payload: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
|
|
56
|
-
const { env } = parsed.data
|
|
57
|
-
if (env !== undefined && !isUsableEnvName(env)) throw new TypeVaultError(code, `${env} is not a usable env name`)
|
|
58
59
|
return parsed.data
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
export function encodePayload(payload: EntryPayload): Uint8Array {
|
|
62
63
|
parsePayload(payload, 'invalid')
|
|
64
|
+
const { env } = payload
|
|
65
|
+
if (env !== undefined && !isUsableEnvName(env)) throw new TypeVaultError('invalid', `${env} is not a usable env name`)
|
|
63
66
|
return utf8(JSON.stringify(payload))
|
|
64
67
|
}
|
|
65
68
|
|
|
@@ -72,12 +75,13 @@ export function decodePayload(bytes: Uint8Array): EntryPayload {
|
|
|
72
75
|
throw new TypeVaultError('tampered', 'entry payload is not JSON')
|
|
73
76
|
throw error
|
|
74
77
|
}
|
|
75
|
-
const { name, env, origin, needsRotation, ...rest } = parsePayload(value, 'tampered')
|
|
78
|
+
const { name, env, origin, source, needsRotation, ...rest } = parsePayload(value, 'tampered')
|
|
76
79
|
return {
|
|
77
80
|
...rest,
|
|
78
81
|
name: parseEntryName(name),
|
|
79
82
|
...(env === undefined ? {} : { env }),
|
|
80
83
|
...(origin === undefined ? {} : { origin }),
|
|
84
|
+
...(source === undefined ? {} : { source }),
|
|
81
85
|
...(needsRotation === undefined ? {} : { needsRotation }),
|
|
82
86
|
}
|
|
83
87
|
}
|
package/src/core/revisions.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
|
|
3
3
|
import { z } from 'zod'
|
|
4
4
|
|
|
5
5
|
import { atomicWrite } from './fsx'
|
|
6
|
+
import { readJsonFile } from './json-file'
|
|
6
7
|
|
|
7
8
|
const MarksSchema = z.record(z.string(), z.number().int())
|
|
8
9
|
|
|
@@ -17,7 +18,7 @@ export class RevisionMarks {
|
|
|
17
18
|
|
|
18
19
|
constructor(path: string) {
|
|
19
20
|
this.#path = path
|
|
20
|
-
this.#marks = existsSync(path) ?
|
|
21
|
+
this.#marks = existsSync(path) ? readJsonFile(path, MarksSchema) : {}
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/** False when `rev` is older than a revision already seen for `id`. */
|
package/src/core/state.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
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
|
|
|
@@ -96,11 +97,13 @@ export const ceilingsDoc = (ceilings: VaultState['ceilings'], key: SecretKey, se
|
|
|
96
97
|
signedDoc({ v: 1, seq, ceilings }, key)
|
|
97
98
|
|
|
98
99
|
function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: PublicKey): T {
|
|
99
|
-
const doc = z.object({ body: z.json(), sig: z.string() })
|
|
100
|
+
const doc = readJsonFile(path, z.object({ body: z.json(), sig: z.string() }))
|
|
100
101
|
if (!verifySignature(owner.signPublic, utf8(canonicalJson(doc.body)), doc.sig)) {
|
|
101
102
|
throw new TypeVaultError('tampered', `${path} is not signed by the vault owner`)
|
|
102
103
|
}
|
|
103
|
-
|
|
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
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
/** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
|
|
@@ -111,19 +114,24 @@ function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<strin
|
|
|
111
114
|
return
|
|
112
115
|
}
|
|
113
116
|
if (!existsSync(layout.trustFile)) {
|
|
117
|
+
ensureDir(layout.root, 0o700)
|
|
114
118
|
atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
|
|
115
119
|
return
|
|
116
120
|
}
|
|
117
|
-
const trust =
|
|
121
|
+
const trust = readJsonFile(layout.trustFile, TrustSchema)
|
|
118
122
|
if (trust.ownerSignPublic !== owner.signPublic) {
|
|
119
123
|
throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
|
|
120
124
|
}
|
|
121
125
|
}
|
|
122
126
|
|
|
123
|
-
export function
|
|
127
|
+
export function readOwner(layout: Layout): PublicKey {
|
|
124
128
|
if (!existsSync(layout.ownerFile))
|
|
125
129
|
throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
|
|
126
|
-
|
|
130
|
+
return readJsonFile(layout.ownerFile, PublicKeySchema)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
|
|
134
|
+
const owner = readOwner(layout)
|
|
127
135
|
checkTrust(layout, owner, env)
|
|
128
136
|
const tiers = readSigned(layout.tiersFile, TiersBody, owner)
|
|
129
137
|
const members = readSigned(layout.membersFile, MembersBody, owner)
|
package/src/core/txn.ts
CHANGED
|
@@ -4,9 +4,10 @@ import { dirname, isAbsolute, join, normalize, sep } from 'node:path'
|
|
|
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'
|
|
@@ -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,7 +64,7 @@ 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))
|
package/src/core/vault.ts
CHANGED
|
@@ -37,6 +37,7 @@ export type EntryBase = {
|
|
|
37
37
|
readonly rev: number
|
|
38
38
|
readonly created: string
|
|
39
39
|
readonly rotated: string
|
|
40
|
+
readonly source?: string
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
export type PutOptions = { readonly ifRev?: number; readonly base?: EntryBase }
|
|
@@ -47,6 +48,7 @@ export type EntryInput = {
|
|
|
47
48
|
readonly tier: string
|
|
48
49
|
readonly env?: string
|
|
49
50
|
readonly origin?: string
|
|
51
|
+
readonly source?: string
|
|
50
52
|
readonly tags?: readonly string[]
|
|
51
53
|
}
|
|
52
54
|
|
|
@@ -217,6 +219,7 @@ export class Vault {
|
|
|
217
219
|
}
|
|
218
220
|
const now = new Date().toISOString()
|
|
219
221
|
const changed = found === undefined || !sameFields(found.payload.fields, input.fields)
|
|
222
|
+
const source = input.source ?? prior?.source
|
|
220
223
|
const payload: EntryPayload = {
|
|
221
224
|
v: 1,
|
|
222
225
|
name: input.name,
|
|
@@ -226,9 +229,12 @@ export class Vault {
|
|
|
226
229
|
rotated: changed ? now : (prior?.rotated ?? now),
|
|
227
230
|
...(input.env === undefined ? {} : { env: input.env }),
|
|
228
231
|
...(input.origin === undefined ? {} : { origin: input.origin }),
|
|
232
|
+
...(source === undefined ? {} : { source }),
|
|
229
233
|
...(changed || found?.payload.needsRotation !== true ? {} : { needsRotation: true }),
|
|
230
234
|
}
|
|
231
|
-
|
|
235
|
+
// A renamed entry gets a fresh id, as in `move`: a grant issued for the old name must not follow it.
|
|
236
|
+
const renamed = found !== undefined && found.payload.name !== input.name
|
|
237
|
+
const id = entryIdIn(signer.ref, input.tier, input.name, renamed ? undefined : prior?.id)
|
|
232
238
|
const draft = { id, tier: input.tier, rev: currentRev + 1, at: now, payload }
|
|
233
239
|
return { envelope: await sealEntry(draft, this.#state, signer), payload }
|
|
234
240
|
}
|
|
@@ -253,21 +259,55 @@ export class Vault {
|
|
|
253
259
|
})
|
|
254
260
|
}
|
|
255
261
|
|
|
256
|
-
/**
|
|
262
|
+
/**
|
|
263
|
+
* Writes many entries as one transaction (an import): all of them land, or none do. An input with a `source` takes
|
|
264
|
+
* over the entry imported from that item, renaming it when the item was renamed; a name held by another item's
|
|
265
|
+
* entry is a conflict, never overwritten. An entry it would replace that `allows` refuses fails the whole import.
|
|
266
|
+
*/
|
|
257
267
|
putMany(
|
|
258
268
|
inputs: readonly EntryInput[],
|
|
259
269
|
signerFor: (tier: string) => Promise<SignerContext>,
|
|
270
|
+
allows: (found: StoredEntry) => boolean = () => true,
|
|
260
271
|
): Promise<readonly StoredEntry[]> {
|
|
261
272
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
262
273
|
const { entries } = await this.scan()
|
|
263
274
|
const txn = new Txn()
|
|
264
275
|
const stored: StoredEntry[] = []
|
|
265
276
|
const retiered: string[] = []
|
|
266
|
-
|
|
267
|
-
|
|
277
|
+
const byName = (name: EntryName) =>
|
|
278
|
+
resolveName(
|
|
268
279
|
this.#state.tiers,
|
|
269
|
-
entries.filter((entry) => entry.payload.name ===
|
|
280
|
+
entries.filter((entry) => entry.payload.name === name),
|
|
270
281
|
)
|
|
282
|
+
const bySource = (source: string | undefined) =>
|
|
283
|
+
source === undefined
|
|
284
|
+
? undefined
|
|
285
|
+
: resolveName(
|
|
286
|
+
this.#state.tiers,
|
|
287
|
+
entries.filter((entry) => entry.payload.source === source),
|
|
288
|
+
)
|
|
289
|
+
const matches = inputs.map((input) => ({ input, held: byName(input.name), own: bySource(input.source) }))
|
|
290
|
+
// An entry this import renames frees its old name, so two items may trade names in one import.
|
|
291
|
+
const claimed = new Set(matches.flatMap(({ own }) => (own === undefined ? [] : [own.envelope.id])))
|
|
292
|
+
const targets = matches.map(({ input, held, own }) => {
|
|
293
|
+
const other =
|
|
294
|
+
held !== undefined && held.envelope.id !== own?.envelope.id && !claimed.has(held.envelope.id)
|
|
295
|
+
? held
|
|
296
|
+
: undefined
|
|
297
|
+
// An entry with no source (written by hand, or by an older import) is taken over only by a new item.
|
|
298
|
+
if (other !== undefined && (own !== undefined || other.payload.source !== undefined)) {
|
|
299
|
+
throw new TypeVaultError(
|
|
300
|
+
'conflict',
|
|
301
|
+
`${input.name} already holds another entry; rename or remove it, then import again`,
|
|
302
|
+
)
|
|
303
|
+
}
|
|
304
|
+
const found = own ?? other
|
|
305
|
+
if (found !== undefined && !allows(found)) {
|
|
306
|
+
throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
|
|
307
|
+
}
|
|
308
|
+
return { input, found }
|
|
309
|
+
})
|
|
310
|
+
for (const { input, found } of targets) {
|
|
271
311
|
const signer = await signerFor(input.tier)
|
|
272
312
|
const entry = await this.#draft(input, found, {}, signer)
|
|
273
313
|
txn.put(`entries/${entry.envelope.id}.json`, `${JSON.stringify(entry.envelope, null, 2)}\n`)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* This release's version, read once when the module loads: a daemon reports it, so a CLI from another release knows
|
|
5
|
+
* not to talk to it. Read any later, an idle daemon would report the version of a package upgraded under it.
|
|
6
|
+
*/
|
|
7
|
+
export const PACKAGE_VERSION = z
|
|
8
|
+
.object({ version: z.string() })
|
|
9
|
+
.parse(await Bun.file(new URL('../../package.json', import.meta.url)).json()).version
|
package/src/core/worktrees.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
-
import { dirname, join, relative } from 'node:path'
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
3
3
|
|
|
4
4
|
/** git's own variables (set inside hooks, say) would point it at another repository than the vault's. */
|
|
5
5
|
const gitEnv = (): Record<string, string | undefined> =>
|
|
@@ -29,11 +29,23 @@ export async function worktreeVaults(vault: string): Promise<readonly string[]>
|
|
|
29
29
|
if (top === undefined || top === '') return []
|
|
30
30
|
const path = relative(realpathSync(top), own)
|
|
31
31
|
const listed = (await git(dirname(own), ['worktree', 'list', '--porcelain'])) ?? ''
|
|
32
|
-
|
|
32
|
+
const checkouts = listed
|
|
33
33
|
.split('\n')
|
|
34
34
|
.filter((line) => line.startsWith('worktree '))
|
|
35
|
-
.map((line) =>
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
.map((line) => line.slice('worktree '.length))
|
|
36
|
+
if (!checkouts.some((checkout) => existsSync(checkout) && realpathSync(checkout) === realpathSync(top))) return []
|
|
37
|
+
const common = (await git(dirname(own), ['rev-parse', '--git-common-dir']))?.trim()
|
|
38
|
+
if (common === undefined) return []
|
|
39
|
+
const repository = realpathSync(resolve(dirname(own), common))
|
|
40
|
+
const vaults: string[] = []
|
|
41
|
+
for (const checkout of checkouts) {
|
|
42
|
+
const candidate = join(checkout, path)
|
|
43
|
+
if (!existsSync(join(candidate, 'owner.json')) || realpathSync(candidate) === own) continue
|
|
44
|
+
// A copied .git can still list the original repository's worktrees. They must point back to this repository.
|
|
45
|
+
const other = (await git(checkout, ['rev-parse', '--git-common-dir']))?.trim()
|
|
46
|
+
if (other !== undefined && realpathSync(resolve(checkout, other)) === repository) {
|
|
47
|
+
vaults.push(realpathSync(candidate))
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return vaults
|
|
39
51
|
}
|
|
@@ -1,11 +1,26 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
|
|
1
3
|
import { parseTtl } from '../access/scope'
|
|
2
4
|
import { ScopedVault } from '../access/scoped'
|
|
3
5
|
import { appendAudit } from '../audit/log'
|
|
4
6
|
import { TypeVaultError } from '../core/errors'
|
|
5
7
|
import type { Vault } from '../core/vault'
|
|
8
|
+
import { PACKAGE_VERSION } from '../core/version'
|
|
6
9
|
import { type GrantStore, type ResolvedGrant, SESSION_CEILING } from './grants'
|
|
7
10
|
import { type Handler, json, parseBody } from './http'
|
|
8
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
AttachBody,
|
|
13
|
+
DeriveBody,
|
|
14
|
+
ImportBody,
|
|
15
|
+
ImportEntries,
|
|
16
|
+
ImportStageBody,
|
|
17
|
+
MoveBody,
|
|
18
|
+
NameBody,
|
|
19
|
+
RequestBody,
|
|
20
|
+
SetBody,
|
|
21
|
+
ValuesBody,
|
|
22
|
+
WaitBody,
|
|
23
|
+
} from './protocol'
|
|
9
24
|
import type { PromptRequests } from './requests'
|
|
10
25
|
|
|
11
26
|
export type DaemonContext = {
|
|
@@ -37,6 +52,7 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
37
52
|
mode: 'live',
|
|
38
53
|
grant: record.id,
|
|
39
54
|
label: record.label,
|
|
55
|
+
owner: isSession && record.parent === undefined && context.vault.keyring.owner !== undefined,
|
|
40
56
|
ownTiers: isSession ? (context.sessionTiers ?? []) : record.tiers,
|
|
41
57
|
...(isSession || record.tiers[0] === undefined ? {} : { defaultTier: record.tiers[0] }),
|
|
42
58
|
})
|
|
@@ -44,11 +60,33 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
|
|
|
44
60
|
return { grant, access }
|
|
45
61
|
}
|
|
46
62
|
|
|
63
|
+
type StagedImport = {
|
|
64
|
+
readonly grant: string
|
|
65
|
+
readonly parts: Uint8Array[]
|
|
66
|
+
bytes: number
|
|
67
|
+
exp: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What staged imports may hold in memory at once, across every grant. */
|
|
71
|
+
const MAX_STAGED_BYTES = 64 << 20
|
|
72
|
+
const STAGED_TTL_MS = 10 * 60_000
|
|
73
|
+
|
|
47
74
|
/** Routes on the agent socket. Every call needs a live grant; none can create a grant from nothing. */
|
|
48
75
|
export function agentRoutes(context: DaemonContext): Readonly<Record<string, Handler>> {
|
|
76
|
+
// An import, or even one entry, can exceed a request body, so its serialized JSON arrives in chunks and is written
|
|
77
|
+
// by one final call, all or nothing.
|
|
78
|
+
const staged = new Map<string, StagedImport>()
|
|
79
|
+
const stagedBy = (upload: string, grant: string): StagedImport => {
|
|
80
|
+
const found = staged.get(upload)
|
|
81
|
+
if (found === undefined || found.grant !== grant || found.exp <= Date.now()) {
|
|
82
|
+
throw new TypeVaultError('not_found', 'no such import upload (it may have expired)')
|
|
83
|
+
}
|
|
84
|
+
return found
|
|
85
|
+
}
|
|
49
86
|
return {
|
|
50
|
-
// The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names.
|
|
51
|
-
|
|
87
|
+
// The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names. The
|
|
88
|
+
// version lets a CLI from another release tell this daemon isn't its own.
|
|
89
|
+
'/v1/ping': async () => json({ ok: true, pid: process.pid, version: PACKAGE_VERSION }),
|
|
52
90
|
'/v1/whoami': async (request) => {
|
|
53
91
|
const { grant, access } = session(context, request)
|
|
54
92
|
const { hash: _hash, ...record } = grant.record
|
|
@@ -56,6 +94,7 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
56
94
|
return json({ ...record, ownTiers: await access.ownTiers() })
|
|
57
95
|
},
|
|
58
96
|
'/v1/list': async (request) => json(await session(context, request).access.list()),
|
|
97
|
+
'/v1/unreadable': async (request) => json({ count: await session(context, request).access.unreadableEntries() }),
|
|
59
98
|
'/v1/get': async (request) => {
|
|
60
99
|
const { name, reason } = await parseBody(request, NameBody)
|
|
61
100
|
return json(await session(context, request).access.get(name, reason))
|
|
@@ -65,6 +104,44 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
|
|
|
65
104
|
return json(await session(context, request).access.values(only, reason))
|
|
66
105
|
},
|
|
67
106
|
'/v1/set': async (request) => json(await session(context, request).access.set(await parseBody(request, SetBody))),
|
|
107
|
+
'/v1/import/stage': async (request) => {
|
|
108
|
+
const { grant } = session(context, request)
|
|
109
|
+
const body = await parseBody(request, ImportStageBody)
|
|
110
|
+
const now = Date.now()
|
|
111
|
+
for (const [id, upload] of staged) if (upload.exp <= now) staged.delete(id)
|
|
112
|
+
const part = Buffer.from(body.chunk, 'base64')
|
|
113
|
+
const bytes = part.byteLength
|
|
114
|
+
const held = [...staged.values()].reduce((sum, upload) => sum + upload.bytes, 0)
|
|
115
|
+
if (held + bytes > MAX_STAGED_BYTES) throw new TypeVaultError('invalid', 'this import is too large (over 64 MiB)')
|
|
116
|
+
const id = body.upload ?? randomBytes(16).toString('base64url')
|
|
117
|
+
const upload =
|
|
118
|
+
body.upload === undefined
|
|
119
|
+
? { grant: grant.record.id, parts: [], bytes: 0, exp: 0 }
|
|
120
|
+
: stagedBy(id, grant.record.id)
|
|
121
|
+
upload.parts.push(part)
|
|
122
|
+
upload.bytes += bytes
|
|
123
|
+
upload.exp = now + STAGED_TTL_MS
|
|
124
|
+
staged.set(id, upload)
|
|
125
|
+
return json({ upload: id })
|
|
126
|
+
},
|
|
127
|
+
'/v1/import': async (request) => {
|
|
128
|
+
const { grant, access } = session(context, request)
|
|
129
|
+
const { upload, tier } = await parseBody(request, ImportBody)
|
|
130
|
+
const { parts } = stagedBy(upload, grant.record.id)
|
|
131
|
+
staged.delete(upload)
|
|
132
|
+
let value: unknown
|
|
133
|
+
try {
|
|
134
|
+
value = JSON.parse(Buffer.concat(parts).toString('utf8'))
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error instanceof SyntaxError) throw new TypeVaultError('invalid', 'the staged import is not JSON')
|
|
137
|
+
throw error
|
|
138
|
+
}
|
|
139
|
+
const entries = ImportEntries.safeParse(value)
|
|
140
|
+
if (!entries.success) {
|
|
141
|
+
throw new TypeVaultError('invalid', `bad import: ${entries.error.issues[0]?.message ?? 'invalid'}`)
|
|
142
|
+
}
|
|
143
|
+
return json(await access.importEntries(entries.data, tier))
|
|
144
|
+
},
|
|
68
145
|
'/v1/remove': async (request) => {
|
|
69
146
|
const { name, tier } = await parseBody(request, NameBody)
|
|
70
147
|
await session(context, request).access.remove(name, tier)
|