typevault 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -115
- package/package.json +14 -2
- package/src/access/env.ts +77 -17
- package/src/access/keys.ts +14 -14
- package/src/access/schemas.ts +6 -12
- package/src/access/scope.ts +7 -7
- package/src/access/scoped.ts +100 -44
- package/src/access/sealed-access.ts +45 -23
- package/src/access/sealed.ts +33 -21
- package/src/access/types.ts +25 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +14 -9
- package/src/cli/commands/admin.ts +87 -47
- package/src/cli/commands/daemon.ts +33 -15
- package/src/cli/commands/entries.ts +166 -55
- package/src/cli/commands/grant.ts +12 -20
- package/src/cli/commands/members.ts +281 -0
- package/src/cli/commands/run.ts +61 -24
- package/src/cli/context.ts +155 -15
- package/src/cli/index.ts +27 -4
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +65 -0
- package/src/core/admin.ts +125 -74
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +9 -9
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +6 -0
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +84 -0
- package/src/core/identity.ts +130 -0
- package/src/core/init.ts +73 -23
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +145 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +146 -49
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +8 -4
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +88 -48
- package/src/core/txn.ts +5 -4
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +39 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +29 -11
- package/src/daemon/client.ts +15 -0
- package/src/daemon/daemon.ts +210 -32
- package/src/daemon/grants.ts +21 -4
- package/src/daemon/http.ts +3 -0
- package/src/daemon/live-access.ts +4 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +17 -22
- package/src/daemon/spawn.ts +188 -9
- package/src/export/1password.ts +157 -0
- package/src/import/1password-live.ts +399 -0
- package/src/import/1password.ts +26 -5
- package/src/import/bitwarden.ts +3 -3
- package/src/import/csv.ts +1 -1
- package/src/import/dotenv.ts +2 -2
- package/src/import/index.ts +1 -0
- package/src/import/keepass.ts +2 -2
- package/src/import/lastpass.ts +2 -2
- package/src/import/shared.ts +67 -10
- package/src/import/typeclaw.ts +2 -2
- package/src/import/types.ts +1 -1
- package/src/index.ts +58 -0
- package/src/owner.ts +156 -0
- package/src/prompt/browser.ts +48 -15
- package/src/prompt/page.ts +19 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +3 -3
package/src/daemon/protocol.ts
CHANGED
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { isPreset, parseEntryName } from '../core/naming'
|
|
4
|
+
import { FieldsSchema } from '../core/payload'
|
|
4
5
|
|
|
5
6
|
const name = z.string().transform((value) => parseEntryName(value))
|
|
6
|
-
const
|
|
7
|
+
const preset = z.string().refine(isPreset, 'unknown preset').optional()
|
|
7
8
|
const reason = z.string().max(500).optional()
|
|
9
|
+
/** Every request under a grant matches against its `only` patterns, so a grant may not carry an unbounded list. */
|
|
10
|
+
const only = z.array(z.string().max(256)).max(100).default([])
|
|
11
|
+
/** Every request under a grant checks its tiers too, so they are capped like `only`. */
|
|
12
|
+
const tiers = z.array(z.string().max(256)).max(100)
|
|
8
13
|
|
|
9
|
-
export const NameBody = z.object({ name, reason,
|
|
10
|
-
export const ValuesBody = z.object({ only
|
|
14
|
+
export const NameBody = z.object({ name, reason, tier: z.string().optional() })
|
|
15
|
+
export const ValuesBody = z.object({ only, reason })
|
|
11
16
|
export const SetBody = z.object({
|
|
12
17
|
name,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
group: z.string().optional(),
|
|
18
|
+
fields: FieldsSchema,
|
|
19
|
+
tier: z.string().optional(),
|
|
16
20
|
env: z
|
|
17
21
|
.string()
|
|
18
22
|
.regex(/^[A-Z_][A-Z0-9_]*$/)
|
|
@@ -23,16 +27,17 @@ export const SetBody = z.object({
|
|
|
23
27
|
})
|
|
24
28
|
export const MoveBody = z.object({ from: name, to: name })
|
|
25
29
|
export const DeriveBody = z.object({
|
|
26
|
-
|
|
27
|
-
only
|
|
30
|
+
tiers: tiers.optional(),
|
|
31
|
+
only,
|
|
28
32
|
ttl: z.string().optional(),
|
|
29
33
|
label: z.string().max(200).optional(),
|
|
30
34
|
})
|
|
31
|
-
export const RequestBody = z.object({ name,
|
|
35
|
+
export const RequestBody = z.object({ name, preset, tier: z.string().optional(), reason: z.string().min(1).max(500) })
|
|
32
36
|
export const WaitBody = z.object({ id: z.string() })
|
|
37
|
+
export const AttachBody = z.object({ vault: z.string() })
|
|
33
38
|
export const GrantBody = z.object({
|
|
34
|
-
|
|
35
|
-
only
|
|
39
|
+
tiers: tiers.min(1),
|
|
40
|
+
only,
|
|
36
41
|
ttl: z.string().default('1h'),
|
|
37
42
|
label: z.string().max(200).default('unlabeled'),
|
|
38
43
|
sealed: z.boolean().default(false),
|
package/src/daemon/requests.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { appendAudit } from '../audit/log'
|
|
|
4
4
|
import { randomToken } from '../core/crypto'
|
|
5
5
|
import { unseal } from '../core/crypto'
|
|
6
6
|
import { TypeVaultError } from '../core/errors'
|
|
7
|
-
import type { EntryName,
|
|
7
|
+
import type { EntryName, Preset } from '../core/naming'
|
|
8
8
|
import { decodePayload } from '../core/payload'
|
|
9
9
|
import type { Vault } from '../core/vault'
|
|
10
10
|
import { type PromptServer, startPromptServer } from '../prompt'
|
|
@@ -24,12 +24,12 @@ export type RequestSession = {
|
|
|
24
24
|
|
|
25
25
|
export type RequestInput = {
|
|
26
26
|
readonly name: EntryName
|
|
27
|
-
readonly
|
|
28
|
-
readonly
|
|
27
|
+
readonly preset?: Preset | undefined
|
|
28
|
+
readonly tier?: string | undefined
|
|
29
29
|
readonly reason: string
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
const matchCode = (): string =>
|
|
32
|
+
export const matchCode = (): string =>
|
|
33
33
|
[...crypto.getRandomValues(new Uint8Array(6))].map((byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length]).join('')
|
|
34
34
|
|
|
35
35
|
type Pending = { readonly owner: string; readonly stored: Promise<EntryName> }
|
|
@@ -55,42 +55,37 @@ export class PromptRequests {
|
|
|
55
55
|
async open(session: RequestSession, input: RequestInput): Promise<{ id: string; url: string; code: string }> {
|
|
56
56
|
const { chain, grant } = session
|
|
57
57
|
const state = this.#vault.state
|
|
58
|
-
const
|
|
59
|
-
const meta =
|
|
60
|
-
if (
|
|
61
|
-
throw new TypeVaultError('denied', `this grant cannot store ${input.name} in
|
|
58
|
+
const tier = input.tier ?? grant.tiers[0]
|
|
59
|
+
const meta = tier === undefined ? undefined : state.tiers[tier]
|
|
60
|
+
if (tier === undefined || meta === undefined || !allowsEntry(chain, state, tier, input.name)) {
|
|
61
|
+
throw new TypeVaultError('denied', `this grant cannot store ${input.name} in tier "${tier ?? '?'}"`)
|
|
62
62
|
}
|
|
63
63
|
const existing = await this.#vault.find(input.name)
|
|
64
|
-
if (existing !== undefined && !allowsEntry(chain, state, existing.envelope.
|
|
64
|
+
if (existing !== undefined && !allowsEntry(chain, state, existing.envelope.tier, input.name)) {
|
|
65
65
|
throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
|
|
66
66
|
}
|
|
67
67
|
const code = matchCode()
|
|
68
68
|
const handle = (await this.#prompt()).open({
|
|
69
69
|
name: input.name,
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
...(input.preset === undefined ? {} : { preset: input.preset }),
|
|
71
|
+
tier,
|
|
72
72
|
reason: input.reason,
|
|
73
73
|
requester: grant.label,
|
|
74
74
|
code,
|
|
75
|
-
recipients: [meta.recipient, state.
|
|
75
|
+
recipients: [meta.recipient, state.owner.recipient],
|
|
76
76
|
expiresAt: new Date(Date.now() + TTL_MS),
|
|
77
77
|
})
|
|
78
78
|
// Whoever holds the URL can submit, the requesting agent included, so the daemon checks what it got instead
|
|
79
79
|
// of signing it blind: it must be exactly the requested entry, and the grant must still be live.
|
|
80
80
|
const stored = handle.done.then(async (ciphertext) => {
|
|
81
|
-
const key = (await this.#vault.keyring.unlock(
|
|
82
|
-
if (key === undefined) throw new TypeVaultError('denied', `no key here can read
|
|
81
|
+
const key = (await this.#vault.keyring.unlock(tier)) ?? this.#vault.keyring.owner
|
|
82
|
+
if (key === undefined) throw new TypeVaultError('denied', `no key here can read tier "${tier}"`)
|
|
83
83
|
const payload = decodePayload(await unseal([key.identity], ciphertext))
|
|
84
|
-
if (
|
|
85
|
-
payload.name !== input.name ||
|
|
86
|
-
payload.type !== input.type ||
|
|
87
|
-
payload.env !== undefined ||
|
|
88
|
-
payload.needsRotation !== undefined
|
|
89
|
-
) {
|
|
84
|
+
if (payload.name !== input.name || payload.env !== undefined || payload.needsRotation !== undefined) {
|
|
90
85
|
throw new TypeVaultError('tampered', 'the submitted secret does not match the request')
|
|
91
86
|
}
|
|
92
87
|
if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
|
|
93
|
-
await session.access.set({ name: input.name,
|
|
88
|
+
await session.access.set({ name: input.name, fields: payload.fields, tier })
|
|
94
89
|
await appendAudit(this.#vault.layout, {
|
|
95
90
|
action: 'request.stored',
|
|
96
91
|
mode: 'live',
|
|
@@ -116,7 +111,7 @@ export class PromptRequests {
|
|
|
116
111
|
grant: grant.id,
|
|
117
112
|
label: grant.label,
|
|
118
113
|
entries: [input.name],
|
|
119
|
-
|
|
114
|
+
tiers: [tier],
|
|
120
115
|
reason: input.reason,
|
|
121
116
|
})
|
|
122
117
|
return { id: handle.id, url: handle.url, code }
|
package/src/daemon/spawn.ts
CHANGED
|
@@ -1,26 +1,205 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
+
import { closeSync, existsSync, openSync, readFileSync, rmSync } from 'node:fs'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
2
5
|
|
|
6
|
+
import { z } from 'zod'
|
|
7
|
+
|
|
8
|
+
import { machineKeys } from '../access/keys'
|
|
9
|
+
import { encodeSecretKey, type SecretKey } from '../core/crypto'
|
|
3
10
|
import { TypeVaultError } from '../core/errors'
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
11
|
+
import { ensureDir } from '../core/fsx'
|
|
12
|
+
import { refuseForeignDaemon } from '../core/holder'
|
|
13
|
+
import { configDir, type Layout } from '../core/layout'
|
|
14
|
+
import { isLockHeld } from '../core/lock'
|
|
15
|
+
import { callDaemon, isDaemonAlive, servingPid } from './client'
|
|
16
|
+
|
|
17
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
6
18
|
|
|
7
19
|
const START_TIMEOUT_MS = 10_000
|
|
8
20
|
const POLL_MS = 50
|
|
9
|
-
const CLI = new URL('../cli/index.ts', import.meta.url)
|
|
21
|
+
const CLI = fileURLToPath(new URL('../cli/index.ts', import.meta.url))
|
|
10
22
|
|
|
11
|
-
|
|
12
|
-
|
|
23
|
+
export const LOCKED_MESSAGE = 'the vault is locked: ask a human to run `typevault unlock`'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Starts the daemon in the background if it isn't running, like gpg-agent. Only a machine member can start one
|
|
27
|
+
* unattended; a human's daemon is started by `typevault unlock`, so a locked vault stays locked.
|
|
28
|
+
*/
|
|
29
|
+
export async function ensureDaemon(layout: Layout, env: Env): Promise<void> {
|
|
13
30
|
if (await isDaemonAlive(layout.agentSocket)) return
|
|
14
|
-
|
|
31
|
+
if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
32
|
+
refuseForeignDaemon(layout, env)
|
|
33
|
+
await startBackground(layout, env, [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout)])
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Starts an unlocked session daemon holding `key`, handed over stdin so it never shows up in argv or env. With
|
|
38
|
+
* `sourceLock`, the session is another one's, shared with a worktree: it serves only while that one's daemon holds
|
|
39
|
+
* this lock, so it ends with it however that daemon ends.
|
|
40
|
+
*/
|
|
41
|
+
export async function startSession(
|
|
42
|
+
layout: Layout,
|
|
43
|
+
env: Env,
|
|
44
|
+
key: SecretKey,
|
|
45
|
+
ttlMs: number,
|
|
46
|
+
sourceLock?: string,
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
const ttl = `${Math.ceil(ttlMs / 1000)}s`
|
|
49
|
+
const command = [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout), '--key-stdin', '--ttl', ttl]
|
|
50
|
+
if (sourceLock !== undefined) command.push('--source-lock', sourceLock)
|
|
51
|
+
// A token left by a daemon that died would pass for this session's before it writes its own.
|
|
52
|
+
rmSync(layout.sessionFile, { force: true })
|
|
53
|
+
await startBackground(layout, env, command, encodeSecretKey(key))
|
|
54
|
+
// The agent socket answers before the session's grant is written, and a caller reads that grant next.
|
|
55
|
+
const deadline = Date.now() + START_TIMEOUT_MS
|
|
56
|
+
while (!existsSync(layout.sessionFile)) {
|
|
57
|
+
if (Date.now() > deadline) throw new TypeVaultError('unavailable', 'the unlocked session did not start')
|
|
58
|
+
await Bun.sleep(POLL_MS)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Stops this checkout's daemon and waits until it is gone, cleanup included: until it releases `run/daemon.lock`.
|
|
64
|
+
* Only the process that answers on the checkout's socket is signaled, by the PID it reports itself, so a stale PID
|
|
65
|
+
* file can never aim the signal at an unrelated process.
|
|
66
|
+
*/
|
|
67
|
+
export async function stopDaemon(layout: Layout): Promise<void> {
|
|
68
|
+
const serving = await servingPid(layout.agentSocket)
|
|
69
|
+
if (!isLockHeld(layout.daemonLock)) {
|
|
70
|
+
const pidFile = join(layout.run, 'daemon.pid')
|
|
71
|
+
if (serving !== undefined || (await isDaemonAlive(layout.agentSocket))) {
|
|
72
|
+
// Something answers but holds no daemon lock: a daemon from an older release. It can't be identified safely.
|
|
73
|
+
throw new TypeVaultError(
|
|
74
|
+
'conflict',
|
|
75
|
+
`a typevault daemon from an older release is running here; stop it (its PID is in ${pidFile}) and retry`,
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
// No lock and no socket, yet the PID file names a live process: an older daemon still cleaning up, or an
|
|
79
|
+
// unrelated process that reused a stale PID. Neither can be told apart safely, so nothing is signaled or replaced.
|
|
80
|
+
const pid = pidIn(pidFile)
|
|
81
|
+
if (pid !== undefined && isRunning(pid)) {
|
|
82
|
+
throw new TypeVaultError(
|
|
83
|
+
'conflict',
|
|
84
|
+
`${pidFile} names a running process (pid ${pid}) that holds no daemon lock: if it is an older typevault daemon, wait for it to exit or stop it; if not, delete ${pidFile}`,
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
throw new TypeVaultError('not_found', 'no daemon is running')
|
|
88
|
+
}
|
|
89
|
+
// With the lock held but no socket answering, the daemon is already shutting down: another signal would only cut
|
|
90
|
+
// its cleanup short, so this just waits.
|
|
91
|
+
if (serving !== undefined) await tellToStop(layout, serving)
|
|
92
|
+
const deadline = Date.now() + STOP_TIMEOUT_MS
|
|
93
|
+
while (isLockHeld(layout.daemonLock)) {
|
|
94
|
+
if (Date.now() > deadline) {
|
|
95
|
+
throw new TypeVaultError('unavailable', `the typevault daemon did not stop (${layout.daemonLock} is still held)`)
|
|
96
|
+
}
|
|
97
|
+
await Bun.sleep(POLL_MS)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function pidIn(pidFile: string): number | undefined {
|
|
102
|
+
if (!existsSync(pidFile)) return undefined
|
|
103
|
+
const pid = Number.parseInt(readFileSync(pidFile, 'utf8'), 10)
|
|
104
|
+
return Number.isInteger(pid) && pid > 0 ? pid : undefined
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isRunning(pid: number): boolean {
|
|
108
|
+
try {
|
|
109
|
+
process.kill(pid, 0)
|
|
110
|
+
return true
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (error instanceof Error && 'code' in error && error.code === 'ESRCH') return false
|
|
113
|
+
throw error
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* SIGTERM on Unix. Windows has no catchable signal (process.kill terminates outright, skipping cleanup), so there the
|
|
119
|
+
* daemon is asked over its control socket, which only this host's user reaches (sandboxes get the agent socket).
|
|
120
|
+
*/
|
|
121
|
+
async function tellToStop(layout: Layout, pid: number): Promise<void> {
|
|
122
|
+
if (process.platform === 'win32') {
|
|
123
|
+
try {
|
|
124
|
+
await callDaemon(layout.controlSocket, '/v1/shutdown', {}, z.object({ ok: z.literal(true) }), {
|
|
125
|
+
timeoutMs: 1_000,
|
|
126
|
+
})
|
|
127
|
+
} catch (error) {
|
|
128
|
+
// It closed its socket since answering: it is already stopping.
|
|
129
|
+
if (!(error instanceof TypeVaultError)) throw error
|
|
130
|
+
}
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
process.kill(pid, 'SIGTERM')
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const STOP_TIMEOUT_MS = 5_000
|
|
141
|
+
|
|
142
|
+
const isSet = (value: string | undefined): boolean => value !== undefined && value !== ''
|
|
143
|
+
|
|
144
|
+
const vaultArgs = (layout: Layout): readonly string[] =>
|
|
145
|
+
layout.scope === 'local' ? ['--vault', resolve(layout.vault)] : []
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Runs `command` detached as this checkout's daemon and waits until the agent socket answers. Exported for tests,
|
|
149
|
+
* which stand in their own daemon.
|
|
150
|
+
*/
|
|
151
|
+
export async function startBackground(
|
|
152
|
+
layout: Layout,
|
|
153
|
+
env: Env,
|
|
154
|
+
command: readonly string[],
|
|
155
|
+
stdin?: string,
|
|
156
|
+
): Promise<void> {
|
|
157
|
+
ensureDir(layout.run, 0o700)
|
|
158
|
+
// A background daemon has no terminal: its output goes to a log, so a failed start can say why.
|
|
159
|
+
const logPath = join(layout.run, 'daemon.log')
|
|
160
|
+
const log = openSync(logPath, 'w', 0o600)
|
|
161
|
+
// The child starts in its private run directory, never the project's: Bun reads bunfig.toml (a preload) and .env from
|
|
162
|
+
// its directory, and anyone who can edit a checkout (an agent) could have it read the key off stdin. So it is handed
|
|
163
|
+
// the vault by path. Its private state is where this process resolved it: `env` may lack the HOME this process fell
|
|
164
|
+
// back to.
|
|
165
|
+
// An explicit state or run directory may be relative to this process's directory, which the child doesn't share.
|
|
166
|
+
const childEnv = {
|
|
167
|
+
...env,
|
|
168
|
+
XDG_CONFIG_HOME: dirname(configDir(env)),
|
|
169
|
+
...(isSet(env['TYPEVAULT_STATE_DIR']) ? { TYPEVAULT_STATE_DIR: layout.root } : {}),
|
|
170
|
+
...(isSet(env['TYPEVAULT_RUN_DIR']) ? { TYPEVAULT_RUN_DIR: layout.sockets } : {}),
|
|
171
|
+
}
|
|
172
|
+
const [executable = process.execPath, ...args] = command
|
|
173
|
+
const child = spawn(executable, args, {
|
|
15
174
|
detached: true,
|
|
16
|
-
stdio: 'ignore',
|
|
17
|
-
|
|
175
|
+
stdio: [stdin === undefined ? 'ignore' : 'pipe', log, log],
|
|
176
|
+
cwd: layout.run,
|
|
177
|
+
env: layout.scope === 'local' ? childEnv : { ...childEnv, TYPEVAULT_DIR: resolve(layout.vault) },
|
|
18
178
|
})
|
|
179
|
+
closeSync(log)
|
|
180
|
+
if (stdin !== undefined) child.stdin?.end(stdin)
|
|
19
181
|
child.unref()
|
|
20
182
|
const deadline = Date.now() + START_TIMEOUT_MS
|
|
21
183
|
while (Date.now() < deadline) {
|
|
22
184
|
if (await isDaemonAlive(layout.agentSocket)) return
|
|
185
|
+
// A daemon that dies on startup won't come up later, so its exit ends the wait, unless another start holds the
|
|
186
|
+
// daemon lock: this child lost a race to it, and the winner may still be opening its vault before it serves.
|
|
187
|
+
const exited = child.exitCode !== null || child.signalCode !== null
|
|
188
|
+
if (exited && !isLockHeld(layout.daemonLock)) break
|
|
23
189
|
await Bun.sleep(POLL_MS)
|
|
24
190
|
}
|
|
25
|
-
|
|
191
|
+
// Two starts racing: the one that loses exits with a conflict while the other's daemon is already serving.
|
|
192
|
+
if (await isDaemonAlive(layout.agentSocket)) return
|
|
193
|
+
throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath)}`)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The first line the daemon wrote before dying, with where to read the rest. */
|
|
197
|
+
function whyNotStarted(logPath: string): string {
|
|
198
|
+
const first = existsSync(logPath)
|
|
199
|
+
? readFileSync(logPath, 'utf8')
|
|
200
|
+
.split('\n')
|
|
201
|
+
.map((line) => line.trim())
|
|
202
|
+
.find((line) => line !== '')
|
|
203
|
+
: undefined
|
|
204
|
+
return first === undefined ? `no output (see ${logPath})` : `${first} (full log: ${logPath})`
|
|
26
205
|
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
import { TypeVaultError } from '../core/errors'
|
|
4
|
+
import { connectDesktop, type OnePasswordVia, type RunOp, spawnOp } from '../import/1password-live'
|
|
5
|
+
import { parseJson } from '../import/shared'
|
|
6
|
+
|
|
7
|
+
export type KeyItem = {
|
|
8
|
+
readonly title: string
|
|
9
|
+
readonly credential: string
|
|
10
|
+
readonly details: Readonly<Record<string, string>>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type ExportOptions = {
|
|
14
|
+
/** Unset picks whatever is reachable: the `op` CLI when installed, else the desktop SDK. */
|
|
15
|
+
readonly via?: OnePasswordVia
|
|
16
|
+
readonly account?: string
|
|
17
|
+
readonly vault: string
|
|
18
|
+
readonly replace?: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type WriterField = { readonly id: string; readonly title: string; readonly value: string; readonly concealed: boolean }
|
|
22
|
+
|
|
23
|
+
export type SdkWriter = {
|
|
24
|
+
readonly vaults: { list(): Promise<readonly { readonly id: string; readonly title: string }[]> }
|
|
25
|
+
readonly items: {
|
|
26
|
+
list(vaultId: string): Promise<readonly { readonly id: string; readonly title: string }[]>
|
|
27
|
+
create(params: { vaultId: string; title: string; tags: string[]; fields: WriterField[] }): Promise<unknown>
|
|
28
|
+
archive(vaultId: string, itemId: string): Promise<void>
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type ConnectWriter = (account: string) => Promise<SdkWriter>
|
|
33
|
+
|
|
34
|
+
export const EXPORT_TAG = 'typevault'
|
|
35
|
+
|
|
36
|
+
export const identityTitle = (name: string): string => `TypeVault identity ${name}`
|
|
37
|
+
|
|
38
|
+
/** Stores `item` in 1Password and returns the transport used. Archives replaced items only after the new one exists. */
|
|
39
|
+
export async function export1Password(
|
|
40
|
+
item: KeyItem,
|
|
41
|
+
options: ExportOptions,
|
|
42
|
+
deps: {
|
|
43
|
+
readonly runOp?: RunOp
|
|
44
|
+
readonly connect?: ConnectWriter
|
|
45
|
+
readonly hasOp?: () => boolean
|
|
46
|
+
} = {},
|
|
47
|
+
): Promise<OnePasswordVia> {
|
|
48
|
+
const via = options.via ?? ((deps.hasOp ?? (() => Bun.which('op') !== null))() ? 'op' : 'sdk')
|
|
49
|
+
if (via === 'op') await exportOp(item, options, deps.runOp ?? spawnOp)
|
|
50
|
+
else {
|
|
51
|
+
if (options.account === undefined) {
|
|
52
|
+
throw new TypeVaultError('invalid', '--account is required with --via sdk (the account name shown in 1Password)')
|
|
53
|
+
}
|
|
54
|
+
await exportSdk(item, options, await (deps.connect ?? connectWriter)(options.account))
|
|
55
|
+
}
|
|
56
|
+
return via
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const fieldsOf = (item: KeyItem): WriterField[] => [
|
|
60
|
+
{ id: 'credential', title: 'credential', value: item.credential, concealed: true },
|
|
61
|
+
...Object.entries(item.details).map(([title, value]) => ({
|
|
62
|
+
id: title.replaceAll(' ', '_'),
|
|
63
|
+
title,
|
|
64
|
+
value,
|
|
65
|
+
concealed: false,
|
|
66
|
+
})),
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
const refuseExisting = (item: KeyItem, vault: string): never => {
|
|
70
|
+
throw new TypeVaultError(
|
|
71
|
+
'conflict',
|
|
72
|
+
`1Password vault "${vault}" already has "${item.title}"; pass --replace to archive it and store the new key`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const OpAccountsSchema = z.array(z.object({}).loose())
|
|
77
|
+
const OpItemsSchema = z.array(z.object({ id: z.string(), title: z.string() }))
|
|
78
|
+
const OpVaultsSchema = z.array(z.object({ id: z.string(), name: z.string() }))
|
|
79
|
+
|
|
80
|
+
async function exportOp(item: KeyItem, options: ExportOptions, runOp: RunOp): Promise<void> {
|
|
81
|
+
if (options.account === undefined) {
|
|
82
|
+
const accounts = parseJson(await runOp(['account', 'list', '--format', 'json']), OpAccountsSchema, 'op')
|
|
83
|
+
// With several accounts, op's default is easy to forget: a key must never land in the wrong one.
|
|
84
|
+
if (accounts.length > 1) {
|
|
85
|
+
throw new TypeVaultError('invalid', 'several 1Password accounts are signed in; pass --account')
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const account = options.account === undefined ? [] : ['--account', options.account]
|
|
89
|
+
const vaults = parseJson(await runOp(['vault', 'list', '--format', 'json', ...account]), OpVaultsSchema, 'op')
|
|
90
|
+
const vault = resolveVault(
|
|
91
|
+
vaults.map(({ id, name }) => ({ id, title: name })),
|
|
92
|
+
options.vault,
|
|
93
|
+
)
|
|
94
|
+
const scope = ['--vault', vault.id, ...account]
|
|
95
|
+
const listed = parseJson(await runOp(['item', 'list', '--format', 'json', ...scope]), OpItemsSchema, 'op')
|
|
96
|
+
const existing = listed.filter((entry) => entry.title === item.title)
|
|
97
|
+
if (existing.length > 0 && options.replace !== true) refuseExisting(item, options.vault)
|
|
98
|
+
const template = {
|
|
99
|
+
title: item.title,
|
|
100
|
+
category: 'API_CREDENTIAL',
|
|
101
|
+
tags: [EXPORT_TAG],
|
|
102
|
+
fields: fieldsOf(item).map((field) => ({
|
|
103
|
+
id: field.id,
|
|
104
|
+
label: field.title,
|
|
105
|
+
type: field.concealed ? 'CONCEALED' : 'STRING',
|
|
106
|
+
value: field.value,
|
|
107
|
+
})),
|
|
108
|
+
}
|
|
109
|
+
// The template goes through stdin: the key never appears in argv, where other processes could read it.
|
|
110
|
+
await runOp(['item', 'create', '-', '--format', 'json', ...scope], JSON.stringify(template))
|
|
111
|
+
for (const entry of existing) await runOp(['item', 'delete', entry.id, '--archive', ...scope])
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function exportSdk(item: KeyItem, options: ExportOptions, client: SdkWriter): Promise<void> {
|
|
115
|
+
const vault = resolveVault(await client.vaults.list(), options.vault)
|
|
116
|
+
const existing = (await client.items.list(vault.id)).filter((entry) => entry.title === item.title)
|
|
117
|
+
if (existing.length > 0 && options.replace !== true) refuseExisting(item, options.vault)
|
|
118
|
+
await client.items.create({ vaultId: vault.id, title: item.title, tags: [EXPORT_TAG], fields: fieldsOf(item) })
|
|
119
|
+
for (const entry of existing) await client.items.archive(vault.id, entry.id)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function resolveVault<V extends { readonly id: string; readonly title: string }>(
|
|
123
|
+
vaults: readonly V[],
|
|
124
|
+
wanted: string,
|
|
125
|
+
): V {
|
|
126
|
+
const byId = vaults.find((vault) => vault.id === wanted)
|
|
127
|
+
if (byId !== undefined) return byId
|
|
128
|
+
const byTitle = vaults.filter((vault) => vault.title === wanted)
|
|
129
|
+
const [only] = byTitle
|
|
130
|
+
if (only === undefined) throw new TypeVaultError('not_found', `1Password vault "${wanted}" was not found`)
|
|
131
|
+
// A key must never land in a vault picked by list order, which may be one shared with other people.
|
|
132
|
+
if (byTitle.length > 1) {
|
|
133
|
+
throw new TypeVaultError('conflict', `several 1Password vaults are named "${wanted}"; pass the vault id instead`)
|
|
134
|
+
}
|
|
135
|
+
return only
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const connectWriter: ConnectWriter = async (account) => {
|
|
139
|
+
const sdk = await import('@1password/sdk')
|
|
140
|
+
const client = await connectDesktop(account)
|
|
141
|
+
return {
|
|
142
|
+
vaults: client.vaults,
|
|
143
|
+
items: {
|
|
144
|
+
list: (vaultId) => client.items.list(vaultId),
|
|
145
|
+
create: (params) =>
|
|
146
|
+
client.items.create({
|
|
147
|
+
...params,
|
|
148
|
+
category: sdk.ItemCategory.ApiCredentials,
|
|
149
|
+
fields: params.fields.map(({ concealed, ...field }) => ({
|
|
150
|
+
...field,
|
|
151
|
+
fieldType: concealed ? sdk.ItemFieldType.Concealed : sdk.ItemFieldType.Text,
|
|
152
|
+
})),
|
|
153
|
+
}),
|
|
154
|
+
archive: (vaultId, itemId) => client.items.archive(vaultId, itemId),
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
}
|