typevault 0.3.0 → 0.5.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 +3 -2
- package/package.json +2 -2
- package/src/access/schemas.ts +4 -2
- package/src/access/scoped.ts +25 -6
- package/src/access/sealed-access.ts +8 -1
- package/src/access/types.ts +9 -1
- package/src/cli/commands/daemon.ts +5 -1
- package/src/cli/commands/entries.ts +10 -16
- package/src/cli/commands/run.ts +11 -22
- package/src/cli/context.ts +46 -1
- package/src/cli/output.ts +5 -1
- package/src/core/holder.ts +16 -3
- package/src/core/layout.ts +48 -3
- package/src/core/naming.ts +29 -24
- package/src/core/payload.ts +5 -1
- package/src/core/vault.ts +45 -5
- package/src/core/version.ts +9 -0
- package/src/daemon/agent-routes.ts +78 -3
- package/src/daemon/client.ts +11 -0
- package/src/daemon/live-access.ts +15 -0
- package/src/daemon/protocol.ts +7 -0
- package/src/daemon/spawn.ts +47 -2
- 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/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/README.md
CHANGED
|
@@ -100,7 +100,8 @@ typevault member add bob tvp1:... --tier default # rotates every tier bob reache
|
|
|
100
100
|
typevault join --machine --name ci # CI or an agent host: no password, its own key
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
More: [vaults, members and git history](docs/vaults-and-members.md).
|
|
103
|
+
More: [vaults, members and git history](docs/vaults-and-members.md), and [working with a teammate](docs/vaults-and-members.md#working-with-a-teammate):
|
|
104
|
+
what each person does by hand.
|
|
104
105
|
|
|
105
106
|
### Running with secrets
|
|
106
107
|
|
|
@@ -190,7 +191,7 @@ use grants, `run` and references.
|
|
|
190
191
|
git clone https://github.com/typeclaw/typevault
|
|
191
192
|
cd typevault
|
|
192
193
|
bun install
|
|
193
|
-
bun test
|
|
194
|
+
bun run test
|
|
194
195
|
```
|
|
195
196
|
|
|
196
197
|
Pre-commit checks (all must pass):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typevault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "CLI-first secrets vault for agents",
|
|
5
5
|
"homepage": "https://github.com/typeclaw/typevault#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"format": "oxfmt --write .",
|
|
32
32
|
"format:check": "oxfmt --check .",
|
|
33
33
|
"check": "bun run typecheck && bun run lint && bun run format:check",
|
|
34
|
-
"test": "bun test"
|
|
34
|
+
"test": "bun test --parallel"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"@1password/sdk": "^0.5.0",
|
package/src/access/schemas.ts
CHANGED
|
@@ -13,7 +13,7 @@ const SummaryShape = {
|
|
|
13
13
|
needsRotation: z.boolean(),
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
export const EntrySummarySchema = z.object(SummaryShape)
|
|
16
|
+
export const EntrySummarySchema = z.object({ ...SummaryShape, fieldNames: z.array(z.string()) })
|
|
17
17
|
export const EntryValueSchema = z.object({
|
|
18
18
|
...SummaryShape,
|
|
19
19
|
id: z.string(),
|
|
@@ -21,6 +21,7 @@ export const EntryValueSchema = z.object({
|
|
|
21
21
|
fields: FieldsSchema,
|
|
22
22
|
env: z.string().optional(),
|
|
23
23
|
origin: z.string().optional(),
|
|
24
|
+
source: z.string().optional(),
|
|
24
25
|
trustedWriter: z.boolean().optional(),
|
|
25
26
|
})
|
|
26
27
|
|
|
@@ -29,11 +30,12 @@ export function toSummaryValue(parsed: z.infer<typeof EntrySummarySchema>): Entr
|
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
export function toEntryValue(parsed: z.infer<typeof EntryValueSchema>): EntryValue {
|
|
32
|
-
const { env, origin, trustedWriter, ...rest } = parsed
|
|
33
|
+
const { env, origin, source, trustedWriter, ...rest } = parsed
|
|
33
34
|
return {
|
|
34
35
|
...rest,
|
|
35
36
|
...(env === undefined ? {} : { env }),
|
|
36
37
|
...(origin === undefined ? {} : { origin }),
|
|
38
|
+
...(source === undefined ? {} : { source }),
|
|
37
39
|
...(trustedWriter === undefined ? {} : { trustedWriter }),
|
|
38
40
|
}
|
|
39
41
|
}
|
package/src/access/scoped.ts
CHANGED
|
@@ -200,13 +200,32 @@ export class ScopedVault implements Access {
|
|
|
200
200
|
throw new TypeVaultError('invalid', `choose a tier with --tier (one of: ${writable.join(', ')})${viaEnv}`)
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
203
|
+
/**
|
|
204
|
+
* Writes every input into `tier` as one transaction (an import): all of them land, or none do. As in `set`, the
|
|
205
|
+
* scope is checked under the write's lock against freshly read state.
|
|
206
|
+
*/
|
|
207
|
+
importEntries(inputs: readonly SetInput[], tier: string): Promise<readonly EntrySummary[]> {
|
|
208
|
+
return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
|
|
209
|
+
this.#vault.refresh()
|
|
210
|
+
for (const input of inputs) this.#checkWritable(input.name, tier)
|
|
211
|
+
const stored = await this.#vault.putMany(
|
|
212
|
+
inputs.map((input) => entryInputOf(input, tier)),
|
|
213
|
+
(target) => this.#signerFor(target),
|
|
214
|
+
(found) => this.#allows(found),
|
|
215
|
+
)
|
|
216
|
+
await this.#audit({ action: 'import', entries: stored.map((entry) => entry.payload.name), tiers: [tier] })
|
|
217
|
+
return stored.map((entry) => toSummary(valueOf(entry)))
|
|
218
|
+
})
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#checkWritable(name: EntryName, tier: string): void {
|
|
222
|
+
if (!allowsTier(this.#chain, this.#vault.state, tier) || !allowsEntry(this.#chain, this.#vault.state, tier, name)) {
|
|
223
|
+
throw new TypeVaultError('denied', `this grant cannot write ${name} in tier "${tier}"`)
|
|
209
224
|
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async #write(input: SetInput, tier: string): Promise<EntrySummary> {
|
|
228
|
+
this.#checkWritable(input.name, tier)
|
|
210
229
|
const existing = await this.#vault.find(input.name)
|
|
211
230
|
if (existing !== undefined && !this.#allows(existing)) {
|
|
212
231
|
throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
|
|
@@ -106,6 +106,7 @@ export class SealedAccess implements Access {
|
|
|
106
106
|
tags: payload.tags,
|
|
107
107
|
rotated: payload.rotated,
|
|
108
108
|
needsRotation: false,
|
|
109
|
+
fieldNames: Object.keys(payload.fields),
|
|
109
110
|
}
|
|
110
111
|
}
|
|
111
112
|
|
|
@@ -133,7 +134,13 @@ export class SealedAccess implements Access {
|
|
|
133
134
|
|
|
134
135
|
async move(from: EntryName, to: EntryName): Promise<void> {
|
|
135
136
|
const entry = this.#entry(from)
|
|
136
|
-
await this.set({
|
|
137
|
+
await this.set({
|
|
138
|
+
name: to,
|
|
139
|
+
fields: entry.fields,
|
|
140
|
+
tier: entry.tier,
|
|
141
|
+
tags: entry.tags,
|
|
142
|
+
...(entry.source === undefined ? {} : { source: entry.source }),
|
|
143
|
+
})
|
|
137
144
|
await this.remove(from)
|
|
138
145
|
}
|
|
139
146
|
|
package/src/access/types.ts
CHANGED
|
@@ -11,14 +11,17 @@ export type EntrySummary = {
|
|
|
11
11
|
readonly tags: readonly string[]
|
|
12
12
|
readonly rotated: string
|
|
13
13
|
readonly needsRotation: boolean
|
|
14
|
+
/** Names only: listing never hands out values. */
|
|
15
|
+
readonly fieldNames: readonly string[]
|
|
14
16
|
}
|
|
15
17
|
|
|
16
|
-
export type EntryValue = EntrySummary & {
|
|
18
|
+
export type EntryValue = Omit<EntrySummary, 'fieldNames'> & {
|
|
17
19
|
readonly id: string
|
|
18
20
|
readonly created: string
|
|
19
21
|
readonly fields: Readonly<Record<string, Field>>
|
|
20
22
|
readonly env?: string
|
|
21
23
|
readonly origin?: string
|
|
24
|
+
readonly source?: string
|
|
22
25
|
/** Written by the owner or by a key that reaches all of the reader's own tiers: its `--env` override counts. */
|
|
23
26
|
readonly trustedWriter?: boolean
|
|
24
27
|
}
|
|
@@ -29,6 +32,8 @@ export type SetInput = {
|
|
|
29
32
|
readonly tier?: string | undefined
|
|
30
33
|
readonly env?: string | undefined
|
|
31
34
|
readonly origin?: string | undefined
|
|
35
|
+
/** Kept by a blind writer (a sealed grant) that moves an imported entry. */
|
|
36
|
+
readonly source?: string | undefined
|
|
32
37
|
readonly tags?: readonly string[] | undefined
|
|
33
38
|
readonly ifRev?: number | undefined
|
|
34
39
|
}
|
|
@@ -44,6 +49,7 @@ export function entryInputOf(input: SetInput, tier: string) {
|
|
|
44
49
|
tier,
|
|
45
50
|
...(input.env === undefined ? {} : { env: input.env }),
|
|
46
51
|
...(input.origin === undefined ? {} : { origin: input.origin }),
|
|
52
|
+
...(input.source === undefined ? {} : { source: input.source }),
|
|
47
53
|
...(input.tags === undefined ? {} : { tags: input.tags }),
|
|
48
54
|
}
|
|
49
55
|
}
|
|
@@ -78,6 +84,7 @@ export function toValue(tier: string, id: string, rev: number, payload: EntryPay
|
|
|
78
84
|
fields: payload.fields,
|
|
79
85
|
...(payload.env === undefined ? {} : { env: payload.env }),
|
|
80
86
|
...(payload.origin === undefined ? {} : { origin: payload.origin }),
|
|
87
|
+
...(payload.source === undefined ? {} : { source: payload.source }),
|
|
81
88
|
}
|
|
82
89
|
}
|
|
83
90
|
|
|
@@ -88,6 +95,7 @@ export const toSummary = (value: EntryValue): EntrySummary => ({
|
|
|
88
95
|
tags: value.tags,
|
|
89
96
|
rotated: value.rotated,
|
|
90
97
|
needsRotation: value.needsRotation,
|
|
98
|
+
fieldNames: Object.keys(value.fields),
|
|
91
99
|
})
|
|
92
100
|
|
|
93
101
|
/** Whether `signer` is at least as privileged as a reader holding `ownTiers`. */
|
|
@@ -8,7 +8,7 @@ import { TypeVaultError } from '../../core/errors'
|
|
|
8
8
|
import { localLayout } from '../../core/layout'
|
|
9
9
|
import { isDaemonAlive } from '../../daemon/client'
|
|
10
10
|
import { startDaemon } from '../../daemon/daemon'
|
|
11
|
-
import { ensureDaemon, stopDaemon } from '../../daemon/spawn'
|
|
11
|
+
import { ensureDaemon, restartDaemon, stopDaemon } from '../../daemon/spawn'
|
|
12
12
|
import { adminCall, DEFAULT_SESSION_MS, layoutFrom } from '../context'
|
|
13
13
|
import { note, print, readStdin } from '../output'
|
|
14
14
|
|
|
@@ -76,6 +76,10 @@ export const daemon = defineCommand({
|
|
|
76
76
|
meta: { name: 'stop' },
|
|
77
77
|
run: async () => stopDaemon(layoutFrom(process.env)),
|
|
78
78
|
}),
|
|
79
|
+
restart: defineCommand({
|
|
80
|
+
meta: { name: 'restart' },
|
|
81
|
+
run: async () => restartDaemon(layoutFrom(process.env), process.env),
|
|
82
|
+
}),
|
|
79
83
|
status: defineCommand({
|
|
80
84
|
meta: { name: 'status' },
|
|
81
85
|
async run() {
|
|
@@ -20,23 +20,13 @@ import {
|
|
|
20
20
|
} from '../../core/naming'
|
|
21
21
|
import { FieldSchema } from '../../core/payload'
|
|
22
22
|
import { parseTotpSeed, totpCode, totpRemainingSeconds } from '../../otp/totp'
|
|
23
|
-
import { accessOf, resolveAccess } from '../context'
|
|
23
|
+
import { accessOf, getEntry, resolveAccess } from '../context'
|
|
24
24
|
import { csv, note, print, readStdin, repeated, table } from '../output'
|
|
25
25
|
import { openBrowser, promptFields } from '../web-prompt'
|
|
26
26
|
|
|
27
|
-
/** Runs after the listing it annotates.
|
|
27
|
+
/** Runs after the listing it annotates. */
|
|
28
28
|
async function noteUnreadableEntries(access: Access): Promise<void> {
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
unreadable = await access.unreadableEntries()
|
|
32
|
-
} catch (error) {
|
|
33
|
-
if (error instanceof TypeVaultError && error.code === 'not_found') {
|
|
34
|
-
return note(
|
|
35
|
-
'this daemon is too old to report entry files it skips: restart it (typevault daemon stop) to see them',
|
|
36
|
-
)
|
|
37
|
-
}
|
|
38
|
-
throw error
|
|
39
|
-
}
|
|
29
|
+
const unreadable = await access.unreadableEntries()
|
|
40
30
|
if (unreadable > 0)
|
|
41
31
|
note(`${unreadable} entry file(s) could not be trusted or read and are not listed: run typevault doctor`)
|
|
42
32
|
}
|
|
@@ -54,10 +44,14 @@ export const ls = defineCommand({
|
|
|
54
44
|
e.tier,
|
|
55
45
|
`r${e.rev}`,
|
|
56
46
|
e.rotated.slice(0, 10),
|
|
47
|
+
e.fieldNames.join(','),
|
|
57
48
|
e.needsRotation ? 'needs-rotation' : '',
|
|
58
49
|
])
|
|
59
50
|
print(
|
|
60
|
-
table([
|
|
51
|
+
table([
|
|
52
|
+
['NAME', 'TIER', 'REV', 'ROTATED', 'FIELDS', ''],
|
|
53
|
+
...rows.sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? '')),
|
|
54
|
+
]),
|
|
61
55
|
)
|
|
62
56
|
},
|
|
63
57
|
})
|
|
@@ -75,7 +69,7 @@ export const get = defineCommand({
|
|
|
75
69
|
},
|
|
76
70
|
async run({ args }) {
|
|
77
71
|
const ref = parseEntryRef(args.ref)
|
|
78
|
-
const value = await (await accessOf(process.env)
|
|
72
|
+
const value = await getEntry(await accessOf(process.env), ref.name, args.reason)
|
|
79
73
|
if (args.json) {
|
|
80
74
|
const fields = Object.fromEntries(
|
|
81
75
|
Object.entries(value.fields).map(([field, secret]) => [
|
|
@@ -273,7 +267,7 @@ export const otp = defineCommand({
|
|
|
273
267
|
args: { name: { type: 'positional', description: ENTRY_REF_SYNTAX, required: true }, reason: { type: 'string' } },
|
|
274
268
|
async run({ args }) {
|
|
275
269
|
const ref = parseEntryRef(args.name)
|
|
276
|
-
const value = await (await accessOf(process.env)
|
|
270
|
+
const value = await getEntry(await accessOf(process.env), ref.name, args.reason)
|
|
277
271
|
const fallback = defaultFieldOf(value.fields)
|
|
278
272
|
const totps = Object.values(value.fields).filter((candidate) => candidate.type === 'totp')
|
|
279
273
|
const field =
|
package/src/cli/commands/run.ts
CHANGED
|
@@ -4,13 +4,11 @@ import { defineCommand } from 'citty'
|
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
|
|
6
6
|
import { envEligible, envFor, explicitNames, resolveEnvRefs, secretValues } from '../../access/env'
|
|
7
|
-
import { appendAudit } from '../../audit/log'
|
|
8
|
-
import { signerOf } from '../../core/entries'
|
|
9
7
|
import { TypeVaultError } from '../../core/errors'
|
|
10
8
|
import { ENTRY_NAME_SYNTAX, matchesOnly } from '../../core/naming'
|
|
11
9
|
import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
|
|
12
10
|
import { createRedactor, type Redactor, scrubFile } from '../../redact'
|
|
13
|
-
import {
|
|
11
|
+
import { getEntry, inGlobalVault, resolveAccess } from '../context'
|
|
14
12
|
import { csv, note, print, readStdin, repeated } from '../output'
|
|
15
13
|
|
|
16
14
|
async function pump(
|
|
@@ -50,11 +48,13 @@ export const run = defineCommand({
|
|
|
50
48
|
const values = await access.values(only, args.reason)
|
|
51
49
|
const unmatched = only.filter((pattern) => !values.some((value) => matchesOnly(value.name, [pattern])))
|
|
52
50
|
if (unmatched.length > 0) note(`warning: --only matched no entries: ${unmatched.join(', ')}`)
|
|
51
|
+
const inGlobal = await inGlobalVault(process.env, explicitNames(unmatched))
|
|
52
|
+
if (inGlobal.length > 0) note(`the global vault has ${inGlobal.join(', ')}: rerun with -g`)
|
|
53
53
|
const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
|
|
54
54
|
const env = envFor(values, new Date(), policy)
|
|
55
55
|
// The child gets its secrets, never the key or grant that opens the vault.
|
|
56
56
|
const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('TYPEVAULT_')))
|
|
57
|
-
const refs = await resolveEnvRefs(inherited, (name) => access
|
|
57
|
+
const refs = await resolveEnvRefs(inherited, (name) => getEntry(access, name, args.reason), new Date())
|
|
58
58
|
const referenced = new Set(refs.values.map((value) => value.name))
|
|
59
59
|
const skipped = values
|
|
60
60
|
.filter((value) => !envEligible(value, policy) && !referenced.has(value.name))
|
|
@@ -239,7 +239,7 @@ const isVia = (value: string): value is OnePasswordVia => ONEPASSWORD_VIAS.some(
|
|
|
239
239
|
export const importCommand = defineCommand({
|
|
240
240
|
meta: {
|
|
241
241
|
name: 'import',
|
|
242
|
-
description: 'Import a password-manager export, or 1Password directly, into a tier (
|
|
242
|
+
description: 'Import a password-manager export, or 1Password directly, into a tier (one transaction)',
|
|
243
243
|
},
|
|
244
244
|
args: {
|
|
245
245
|
source: { type: 'positional', required: true, description: SOURCES.join(' | ') },
|
|
@@ -262,7 +262,10 @@ export const importCommand = defineCommand({
|
|
|
262
262
|
}
|
|
263
263
|
const via = args.via ?? 'sdk'
|
|
264
264
|
if (!isVia(via)) throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
|
|
265
|
-
const
|
|
265
|
+
const resolved = await resolveAccess(process.env)
|
|
266
|
+
if (resolved.kind === 'sealed') {
|
|
267
|
+
throw new TypeVaultError('unavailable', 'import needs an unlocked vault or a live grant, not a sealed grant')
|
|
268
|
+
}
|
|
266
269
|
const password = args['password-stdin'] ? await readStdin() : undefined
|
|
267
270
|
const result =
|
|
268
271
|
args.path === undefined
|
|
@@ -273,22 +276,8 @@ export const importCommand = defineCommand({
|
|
|
273
276
|
tags: repeated(rawArgs, '--tag'),
|
|
274
277
|
})
|
|
275
278
|
: await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
|
|
276
|
-
const
|
|
277
|
-
const stored = await vault.putMany(
|
|
278
|
-
result.entries.map((entry) => ({ ...entry, tier })),
|
|
279
|
-
async (target) => {
|
|
280
|
-
const key = vault.keyring.owner ?? (await vault.keyring.unlock(target))
|
|
281
|
-
if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${target}"`)
|
|
282
|
-
return signerOf(key)
|
|
283
|
-
},
|
|
284
|
-
)
|
|
285
|
-
await appendAudit(vault.layout, {
|
|
286
|
-
action: 'import',
|
|
287
|
-
mode: 'direct',
|
|
288
|
-
tiers: [tier],
|
|
289
|
-
entries: stored.map((e) => e.payload.name),
|
|
290
|
-
})
|
|
279
|
+
const stored = await resolved.access.importEntries(result.entries, args.tier)
|
|
291
280
|
for (const warning of result.warnings) note(`warning: ${warning}`)
|
|
292
|
-
note(`imported ${stored.length} entries into ${tier}`)
|
|
281
|
+
note(`imported ${stored.length} entries into ${args.tier}`)
|
|
293
282
|
},
|
|
294
283
|
})
|
package/src/cli/context.ts
CHANGED
|
@@ -6,13 +6,14 @@ import { machineKeys } from '../access/keys'
|
|
|
6
6
|
import { ScopedVault } from '../access/scoped'
|
|
7
7
|
import { readSealedGrant } from '../access/sealed'
|
|
8
8
|
import { SealedAccess } from '../access/sealed-access'
|
|
9
|
-
import type { Access } from '../access/types'
|
|
9
|
+
import type { Access, EntryValue } from '../access/types'
|
|
10
10
|
import { Admin } from '../core/admin'
|
|
11
11
|
import type { SecretKey } from '../core/crypto'
|
|
12
12
|
import { TypeVaultError } from '../core/errors'
|
|
13
13
|
import { atomicWrite } from '../core/fsx'
|
|
14
14
|
import { type Identity, readIdentity, sealedCopyPath, unlockIdentity } from '../core/identity'
|
|
15
15
|
import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/layout'
|
|
16
|
+
import type { EntryName } from '../core/naming'
|
|
16
17
|
import { loadState } from '../core/state'
|
|
17
18
|
import { Vault } from '../core/vault'
|
|
18
19
|
import { worktreeVaults } from '../core/worktrees'
|
|
@@ -187,6 +188,8 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
|
|
|
187
188
|
if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
188
189
|
await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
|
|
189
190
|
}
|
|
191
|
+
// A session daemon from another release fails here instead of misreading this CLI's requests.
|
|
192
|
+
await ensureDaemon(layout, env)
|
|
190
193
|
return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
|
|
191
194
|
}
|
|
192
195
|
|
|
@@ -198,6 +201,48 @@ function checkOwnerPin(layout: Layout, env: Env): void {
|
|
|
198
201
|
if (isSet(env['TYPEVAULT_OWNER'])) loadState(layout, env)
|
|
199
202
|
}
|
|
200
203
|
|
|
204
|
+
/**
|
|
205
|
+
* Which of `names` the global vault holds, when the project vault was asked. It asks only an already unlocked global
|
|
206
|
+
* session: never a password, a daemon start or a trust pin, and listing is not audited. Anything else answers none,
|
|
207
|
+
* so a miss points at `-g` only when the global vault really has the name.
|
|
208
|
+
*/
|
|
209
|
+
export async function inGlobalVault(env: Env, names: readonly string[]): Promise<readonly string[]> {
|
|
210
|
+
if (names.length === 0 || wantsGlobal(env) || isSet(env['TYPEVAULT_GRANT'])) return []
|
|
211
|
+
const layout = globalLayout(env)
|
|
212
|
+
if (!(await hasSession(layout))) return []
|
|
213
|
+
try {
|
|
214
|
+
const access = new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
|
|
215
|
+
const held = new Set<string>((await access.list()).map((entry) => entry.name))
|
|
216
|
+
return names.filter((name) => held.has(name))
|
|
217
|
+
} catch (error) {
|
|
218
|
+
// Only a hint: a session that ends meanwhile, or a daemon from another release, gives none.
|
|
219
|
+
if (error instanceof TypeVaultError || (error instanceof Error && 'code' in error && error.code === 'ENOENT')) {
|
|
220
|
+
return []
|
|
221
|
+
}
|
|
222
|
+
throw error
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** `access.get`, whose miss says so when the global vault has the name. */
|
|
227
|
+
export async function getEntry(access: Access, name: EntryName, reason?: string): Promise<EntryValue> {
|
|
228
|
+
try {
|
|
229
|
+
return await access.get(name, reason)
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (
|
|
232
|
+
error instanceof TypeVaultError &&
|
|
233
|
+
error.code === 'not_found' &&
|
|
234
|
+
(await inGlobalVault(process.env, [name])).length > 0
|
|
235
|
+
) {
|
|
236
|
+
throw new TypeVaultError(
|
|
237
|
+
'not_found',
|
|
238
|
+
`${error.message} in the project vault; the global vault has it: rerun with -g`,
|
|
239
|
+
{ cause: error },
|
|
240
|
+
)
|
|
241
|
+
}
|
|
242
|
+
throw error
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
201
246
|
/** How long an unlocked session lasts unless `unlock --for` says otherwise. */
|
|
202
247
|
export const DEFAULT_SESSION_MS = 8 * 60 * 60_000
|
|
203
248
|
|
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/core/holder.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { existsSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { hostname } from 'node:os'
|
|
2
3
|
|
|
3
4
|
import { z } from 'zod'
|
|
4
5
|
|
|
@@ -11,7 +12,13 @@ type Env = Readonly<Record<string, string | undefined>>
|
|
|
11
12
|
|
|
12
13
|
const CLAIM_ATTEMPTS = 3
|
|
13
14
|
|
|
14
|
-
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
|
+
})
|
|
15
22
|
type Holder = z.infer<typeof HolderSchema>
|
|
16
23
|
|
|
17
24
|
export type DaemonClaim = {
|
|
@@ -37,7 +44,13 @@ export function refuseForeignDaemon(layout: Layout, env: Env): void {
|
|
|
37
44
|
*/
|
|
38
45
|
export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
|
|
39
46
|
const token = randomHex(8)
|
|
40
|
-
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
|
+
})
|
|
41
54
|
for (let attempt = 0; ; attempt++) {
|
|
42
55
|
try {
|
|
43
56
|
writeFileSync(layout.daemonHolder, record, { flag: 'wx', mode: 0o600 })
|
|
@@ -80,7 +93,7 @@ function readHolder(layout: Layout): Holder | undefined {
|
|
|
80
93
|
const inUse = (layout: Layout, holder: Holder): TypeVaultError =>
|
|
81
94
|
new TypeVaultError(
|
|
82
95
|
'in_use',
|
|
83
|
-
`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})`,
|
|
84
97
|
)
|
|
85
98
|
|
|
86
99
|
const isCode = (error: unknown, code: string): boolean =>
|
package/src/core/layout.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
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
|
|
|
@@ -89,10 +90,54 @@ const setting = (env: Env, name: string): string | undefined => {
|
|
|
89
90
|
return value !== undefined && value !== '' ? resolve(value) : undefined
|
|
90
91
|
}
|
|
91
92
|
|
|
92
|
-
|
|
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
|
+
*/
|
|
93
99
|
export function hostId(env: Env = process.env): string {
|
|
94
100
|
const explicit = env['TYPEVAULT_HOST_ID']
|
|
95
|
-
|
|
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
|
+
}
|
|
96
141
|
}
|
|
97
142
|
|
|
98
143
|
/**
|
package/src/core/naming.ts
CHANGED
|
@@ -21,8 +21,17 @@ 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
37
|
* The one way to point at an entry: `typevault://<service>[/<account>][#<field>]`. The scheme may be left out
|
|
@@ -37,17 +46,22 @@ const REF_SCHEME = /^typevault:\/\//i
|
|
|
37
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
|
|
@@ -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 `typevault://` ref.
|
|
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 {
|
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(),
|
|
@@ -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
|
}
|