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.
Files changed (57) hide show
  1. package/README.md +13 -12
  2. package/package.json +2 -2
  3. package/src/access/env.ts +3 -3
  4. package/src/access/schemas.ts +3 -1
  5. package/src/access/scope.ts +7 -2
  6. package/src/access/scoped.ts +47 -10
  7. package/src/access/sealed-access.ts +12 -1
  8. package/src/access/sealed.ts +25 -12
  9. package/src/access/types.ts +7 -0
  10. package/src/audit/log.ts +15 -4
  11. package/src/cli/commands/admin.ts +7 -2
  12. package/src/cli/commands/daemon.ts +10 -3
  13. package/src/cli/commands/entries.ts +21 -7
  14. package/src/cli/commands/grant.ts +12 -2
  15. package/src/cli/commands/members.ts +40 -14
  16. package/src/cli/commands/run.ts +141 -44
  17. package/src/cli/context.ts +14 -4
  18. package/src/cli/index.ts +6 -1
  19. package/src/cli/output.ts +5 -1
  20. package/src/cli/web-prompt.ts +28 -14
  21. package/src/core/admin.ts +23 -6
  22. package/src/core/doctor.ts +6 -7
  23. package/src/core/errors.ts +2 -2
  24. package/src/core/holder.ts +25 -9
  25. package/src/core/identity.ts +5 -3
  26. package/src/core/json-file.ts +20 -0
  27. package/src/core/layout.ts +51 -8
  28. package/src/core/naming.ts +40 -32
  29. package/src/core/payload.ts +7 -3
  30. package/src/core/revisions.ts +3 -2
  31. package/src/core/state.ts +16 -8
  32. package/src/core/txn.ts +4 -3
  33. package/src/core/vault.ts +45 -5
  34. package/src/core/version.ts +9 -0
  35. package/src/core/worktrees.ts +18 -6
  36. package/src/daemon/agent-routes.ts +80 -3
  37. package/src/daemon/client.ts +20 -2
  38. package/src/daemon/daemon.ts +9 -2
  39. package/src/daemon/grants.ts +4 -3
  40. package/src/daemon/http.ts +8 -2
  41. package/src/daemon/live-access.ts +19 -0
  42. package/src/daemon/protocol.ts +7 -0
  43. package/src/daemon/requests.ts +65 -36
  44. package/src/daemon/spawn.ts +68 -14
  45. package/src/import/1password-live.ts +55 -16
  46. package/src/import/1password.ts +6 -4
  47. package/src/import/bitwarden.ts +3 -8
  48. package/src/import/dotenv.ts +2 -1
  49. package/src/import/keepass.ts +4 -5
  50. package/src/import/lastpass.ts +0 -1
  51. package/src/import/shared.ts +57 -5
  52. package/src/import/types.ts +1 -1
  53. package/src/prompt/index.ts +121 -64
  54. package/src/prompt/page.ts +8 -0
  55. package/src/prompt/types.ts +4 -1
  56. package/src/redact/index.ts +48 -12
  57. package/src/redact/scrub-file.ts +15 -7
@@ -41,7 +41,10 @@ export async function callDaemon<T>(
41
41
  signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
42
42
  })
43
43
  } catch (error) {
44
- if (error instanceof Error && error.name !== 'TimeoutError') {
44
+ if (error instanceof Error) {
45
+ if (error.name === 'TimeoutError') {
46
+ throw new TypeVaultError('unavailable', 'the typevault daemon request timed out', { cause: error })
47
+ }
45
48
  throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`)
46
49
  }
47
50
  throw error
@@ -53,7 +56,11 @@ export async function callDaemon<T>(
53
56
  ? new TypeVaultError(toCode(parsed.data.error.code), parsed.data.error.message)
54
57
  : new TypeVaultError('unavailable', `daemon answered ${response.status}`)
55
58
  }
56
- return schema.parse(payload)
59
+ const parsed = schema.safeParse(payload)
60
+ if (!parsed.success) {
61
+ throw new TypeVaultError('unavailable', 'the running typevault daemon does not match this CLI: restart it')
62
+ }
63
+ return parsed.data
57
64
  }
58
65
 
59
66
  /** The PID of the daemon answering on `socket`, or undefined when none answers (or it is too old to say). */
@@ -68,6 +75,17 @@ export async function servingPid(socket: string): Promise<number | undefined> {
68
75
  }
69
76
  }
70
77
 
78
+ /** The version the daemon answering on `socket` reports: undefined when none answers, null when it is too old to say. */
79
+ export async function servingVersion(socket: string): Promise<string | null | undefined> {
80
+ const Ping = z.object({ ok: z.literal(true), version: z.string().optional() })
81
+ try {
82
+ return (await callDaemon(socket, '/v1/ping', {}, Ping, { timeoutMs: 1_000 })).version ?? null
83
+ } catch (error) {
84
+ if (error instanceof TypeVaultError || (error instanceof Error && error.name === 'TimeoutError')) return undefined
85
+ throw error
86
+ }
87
+ }
88
+
71
89
  export async function isDaemonAlive(socket: string): Promise<boolean> {
72
90
  try {
73
91
  await callDaemon(socket, '/v1/ping', {}, z.object({ ok: z.literal(true) }), { timeoutMs: 1_000 })
@@ -9,7 +9,7 @@ import { atomicWrite, ensureDir } from '../core/fsx'
9
9
  import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
10
10
  import { type Layout, localLayout } from '../core/layout'
11
11
  import { holdLock, isLockHeld } from '../core/lock'
12
- import { loadState } from '../core/state'
12
+ import { loadState, readOwner } from '../core/state'
13
13
  import { Vault } from '../core/vault'
14
14
  import { worktreeVaults } from '../core/worktrees'
15
15
  import { adminRoutes, type Ceiling } from './admin-routes'
@@ -129,9 +129,13 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
129
129
  attaching.delete(started)
130
130
  }
131
131
  }
132
+ const grants = new GrantStore(layout.grantsFile)
133
+ // A session ends with its daemon, however that daemon ended: one killed before its cleanup left both of these.
134
+ grants.revoke((record) => record.ceiling === SESSION_CEILING)
135
+ rmSync(layout.sessionFile, { force: true })
132
136
  const context: DaemonContext = {
133
137
  vault,
134
- grants: new GrantStore(layout.grantsFile),
138
+ grants,
135
139
  sessions: new Map(),
136
140
  requests: new PromptRequests(vault, options.prompt ?? {}),
137
141
  ...(options.session === undefined
@@ -238,6 +242,9 @@ async function worktreeLayout(vault: Vault, env: DaemonOptions['env'], target: s
238
242
  throw new TypeVaultError('denied', `${target} is not this vault in a worktree of its repository`)
239
243
  }
240
244
  const layout = localLayout(target, env)
245
+ if (readOwner(layout).signPublic !== vault.state.owner.signPublic) {
246
+ throw new TypeVaultError('tampered', "this worktree's vault has a different owner")
247
+ }
241
248
  loadState(layout, { ...env, TYPEVAULT_OWNER: vault.state.owner.signPublic })
242
249
  return layout
243
250
  }
@@ -1,5 +1,5 @@
1
1
  import { timingSafeEqual } from 'node:crypto'
2
- import { existsSync, readFileSync } from 'node:fs'
2
+ import { existsSync } from 'node:fs'
3
3
 
4
4
  import { z } from 'zod'
5
5
 
@@ -8,6 +8,7 @@ import { randomHex, randomToken, sha256Hex } from '../core/crypto'
8
8
  import { utf8 } from '../core/encoding'
9
9
  import { TypeVaultError } from '../core/errors'
10
10
  import { atomicWrite } from '../core/fsx'
11
+ import { readJsonFile } from '../core/json-file'
11
12
 
12
13
  const RecordSchema = z.object({
13
14
  id: z.string(),
@@ -45,7 +46,7 @@ export const SESSION_CEILING = ':session'
45
46
  export const MAX_CHAIN = 8
46
47
 
47
48
  /**
48
- * Live grants, persisted (hashed) so a daemon restart doesn't cut sessions off.
49
+ * Live grants, persisted (hashed) so a daemon restart doesn't cut issued grants off. `typevault lock` ends them.
49
50
  * A token is `tvl1.<id>.<secret>`; only sha256(secret) is stored.
50
51
  */
51
52
  export class GrantStore {
@@ -54,7 +55,7 @@ export class GrantStore {
54
55
 
55
56
  constructor(path: string) {
56
57
  this.#path = path
57
- this.#records = existsSync(path) ? z.array(RecordSchema).parse(JSON.parse(readFileSync(path, 'utf8'))) : []
58
+ this.#records = existsSync(path) ? readJsonFile(path, z.array(RecordSchema)) : []
58
59
  }
59
60
 
60
61
  #save(): void {
@@ -30,7 +30,14 @@ export function errorResponse(error: unknown): Response {
30
30
 
31
31
  export async function parseBody<T>(request: Request, schema: z.ZodType<T>): Promise<T> {
32
32
  const text = await request.text()
33
- const parsed = schema.safeParse(text === '' ? {} : JSON.parse(text))
33
+ let body: unknown
34
+ try {
35
+ body = text === '' ? {} : JSON.parse(text)
36
+ } catch (error) {
37
+ if (error instanceof SyntaxError) throw new TypeVaultError('invalid', 'request body is not JSON')
38
+ throw error
39
+ }
40
+ const parsed = schema.safeParse(body)
34
41
  if (!parsed.success)
35
42
  throw new TypeVaultError('invalid', `bad request: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
36
43
  return parsed.data
@@ -47,7 +54,6 @@ export function router(routes: Readonly<Record<string, Handler>>): (request: Req
47
54
  try {
48
55
  return await handler(request)
49
56
  } catch (error) {
50
- if (error instanceof SyntaxError) return errorResponse(new TypeVaultError('invalid', 'request body is not JSON'))
51
57
  return errorResponse(error)
52
58
  }
53
59
  }
@@ -6,6 +6,9 @@ import type { EntryName } from '../core/naming'
6
6
  import { callDaemon } from './client'
7
7
 
8
8
  const Ok = z.object({ ok: z.literal(true) })
9
+ const Staged = z.object({ upload: z.string() })
10
+ /** Keeps each staged chunk, once base64-encoded, well under the daemon's 1 MiB request limit. */
11
+ const IMPORT_CHUNK_BYTES = 512 * 1024
9
12
 
10
13
  /** Access through a live grant: every call goes to the daemon, which checks, audits and decrypts. */
11
14
  export class LiveAccess implements Access {
@@ -28,6 +31,10 @@ export class LiveAccess implements Access {
28
31
  return (await this.call('/v1/list', {}, z.array(EntrySummarySchema))).map(toSummaryValue)
29
32
  }
30
33
 
34
+ async unreadableEntries(): Promise<number> {
35
+ return (await this.call('/v1/unreadable', {}, z.object({ count: z.number().int() }))).count
36
+ }
37
+
31
38
  async get(name: EntryName, reason?: string): Promise<EntryValue> {
32
39
  return toEntryValue(await this.call('/v1/get', { name, reason }, EntryValueSchema))
33
40
  }
@@ -40,6 +47,18 @@ export class LiveAccess implements Access {
40
47
  return toSummaryValue(await this.call('/v1/set', input, EntrySummarySchema))
41
48
  }
42
49
 
50
+ /** Stages the serialized inputs in chunks, so no entry has to fit in one request, then writes them in one transaction. */
51
+ async importEntries(inputs: readonly SetInput[], tier: string): Promise<readonly EntrySummary[]> {
52
+ const serialized = Buffer.from(JSON.stringify(inputs))
53
+ let upload: string | undefined
54
+ for (let at = 0; at < serialized.byteLength; at += IMPORT_CHUNK_BYTES) {
55
+ const chunk = serialized.subarray(at, at + IMPORT_CHUNK_BYTES).toString('base64')
56
+ upload = (await this.call('/v1/import/stage', { ...(upload === undefined ? {} : { upload }), chunk }, Staged))
57
+ .upload
58
+ }
59
+ return (await this.call('/v1/import', { upload, tier }, z.array(EntrySummarySchema))).map(toSummaryValue)
60
+ }
61
+
43
62
  async remove(name: EntryName, tier?: string): Promise<void> {
44
63
  await this.call('/v1/remove', { name, ...(tier === undefined ? {} : { tier }) }, Ok)
45
64
  }
@@ -25,6 +25,13 @@ export const SetBody = z.object({
25
25
  tags: z.array(z.string()).optional(),
26
26
  ifRev: z.number().int().nonnegative().optional(),
27
27
  })
28
+ /** The entries an import writes, sent as staged chunks of their serialized JSON. */
29
+ export const ImportEntries = z.array(
30
+ SetBody.omit({ tier: true, ifRev: true }).extend({ source: z.string().optional() }),
31
+ )
32
+ /** One base64 chunk of an import, staged until `ImportBody` commits it; the first chunk starts a new upload. */
33
+ export const ImportStageBody = z.object({ upload: z.string().max(64).optional(), chunk: z.base64() })
34
+ export const ImportBody = z.object({ upload: z.string().max(64), tier: z.string() })
28
35
  export const MoveBody = z.object({ from: name, to: name })
29
36
  export const DeriveBody = z.object({
30
37
  tiers: tiers.optional(),
@@ -47,12 +47,17 @@ export class PromptRequests {
47
47
  }
48
48
 
49
49
  #prompt(): Promise<PromptServer> {
50
- const server = this.#server ?? startPromptServer(this.#options)
51
- this.#server = server
52
- return server
50
+ this.#server ??= startPromptServer(this.#options).catch((error: unknown) => {
51
+ this.#server = undefined
52
+ throw error
53
+ })
54
+ return this.#server
53
55
  }
54
56
 
55
- async open(session: RequestSession, input: RequestInput): Promise<{ id: string; url: string; code: string }> {
57
+ async open(
58
+ session: RequestSession,
59
+ input: RequestInput,
60
+ ): Promise<{ id: string; url: string; code: string; expiresAt: number }> {
56
61
  const { chain, grant } = session
57
62
  const state = this.#vault.state
58
63
  const tier = input.tier ?? grant.tiers[0]
@@ -65,35 +70,59 @@ export class PromptRequests {
65
70
  throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
66
71
  }
67
72
  const code = matchCode()
68
- const handle = (await this.#prompt()).open({
69
- name: input.name,
70
- ...(input.preset === undefined ? {} : { preset: input.preset }),
71
- tier,
72
- reason: input.reason,
73
- requester: grant.label,
74
- code,
75
- recipients: [meta.recipient, state.owner.recipient],
76
- expiresAt: new Date(Date.now() + TTL_MS),
77
- })
73
+ const expiresAt = Date.now() + TTL_MS
74
+ const handle = (await this.#prompt()).open(
75
+ {
76
+ name: input.name,
77
+ ...(input.preset === undefined ? {} : { preset: input.preset }),
78
+ tier,
79
+ reason: input.reason,
80
+ requester: grant.label,
81
+ code,
82
+ recipients: [meta.recipient, state.owner.recipient],
83
+ expiresAt: new Date(expiresAt),
84
+ },
85
+ { validate: true },
86
+ )
78
87
  // Whoever holds the URL can submit, the requesting agent included, so the daemon checks what it got instead
79
88
  // of signing it blind: it must be exactly the requested entry, and the grant must still be live.
80
89
  const stored = handle.done.then(async (ciphertext) => {
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
- const payload = decodePayload(await unseal([key.identity], ciphertext))
84
- if (payload.name !== input.name || payload.env !== undefined || payload.needsRotation !== undefined) {
85
- throw new TypeVaultError('tampered', 'the submitted secret does not match the request')
90
+ try {
91
+ const key = (await this.#vault.keyring.unlock(tier)) ?? this.#vault.keyring.owner
92
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can read tier "${tier}"`)
93
+ const payload = decodePayload(await unseal([key.identity], ciphertext))
94
+ if (payload.name !== input.name || payload.env !== undefined || payload.needsRotation !== undefined) {
95
+ throw new TypeVaultError('tampered', 'the submitted secret does not match the request')
96
+ }
97
+ if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
98
+ await session.access.set({ name: input.name, fields: payload.fields, tier })
99
+ await appendAudit(this.#vault.layout, {
100
+ action: 'request.stored',
101
+ mode: 'live',
102
+ grant: grant.id,
103
+ label: grant.label,
104
+ entries: [input.name],
105
+ })
106
+ await handle.accept()
107
+ return input.name
108
+ } catch (error) {
109
+ const rejected =
110
+ error instanceof TypeVaultError
111
+ ? error
112
+ : new TypeVaultError('unavailable', 'the submitted secret could not be stored')
113
+ try {
114
+ await appendAudit(this.#vault.layout, {
115
+ action: 'request.rejected',
116
+ mode: 'live',
117
+ grant: grant.id,
118
+ label: grant.label,
119
+ entries: [input.name],
120
+ })
121
+ } finally {
122
+ await handle.reject(rejected)
123
+ }
124
+ throw error
86
125
  }
87
- if (!session.isLive()) throw new TypeVaultError('denied', 'the requesting grant is no longer live')
88
- await session.access.set({ name: input.name, fields: payload.fields, tier })
89
- await appendAudit(this.#vault.layout, {
90
- action: 'request.stored',
91
- mode: 'live',
92
- grant: grant.id,
93
- label: grant.label,
94
- entries: [input.name],
95
- })
96
- return input.name
97
126
  })
98
127
  // Forget the request a while after it settles, whether or not anyone waits for it.
99
128
  const forget = (): void => {
@@ -114,21 +143,21 @@ export class PromptRequests {
114
143
  tiers: [tier],
115
144
  reason: input.reason,
116
145
  })
117
- return { id: handle.id, url: handle.url, code }
146
+ return { id: handle.id, url: handle.url, code, expiresAt }
118
147
  }
119
148
 
120
149
  async wait(grantId: string, id: string): Promise<EntryName> {
121
150
  const pending = this.#pending.get(id)
122
151
  if (pending === undefined || pending.owner !== grantId) throw new TypeVaultError('not_found', 'no such request')
123
- try {
124
- return await pending.stored
125
- } finally {
126
- this.#pending.delete(id)
127
- }
152
+ return pending.stored
128
153
  }
129
154
 
130
155
  async stop(): Promise<void> {
131
- if (this.#server !== undefined) await (await this.#server).stop()
156
+ // A failed startup has no listener to stop, including one still settling when shutdown begins.
157
+ await this.#server?.then(
158
+ (server) => server.stop(),
159
+ () => undefined,
160
+ )
132
161
  }
133
162
  }
134
163
 
@@ -1,18 +1,20 @@
1
1
  import { spawn } from 'node:child_process'
2
- import { closeSync, existsSync, openSync, readFileSync, rmSync } from 'node:fs'
2
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, statSync } from 'node:fs'
3
3
  import { dirname, join, resolve } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
 
6
6
  import { z } from 'zod'
7
7
 
8
8
  import { machineKeys } from '../access/keys'
9
+ import { appendAudit } from '../audit/log'
9
10
  import { encodeSecretKey, type SecretKey } from '../core/crypto'
10
11
  import { TypeVaultError } from '../core/errors'
11
12
  import { ensureDir } from '../core/fsx'
12
- import { refuseForeignDaemon } from '../core/holder'
13
+ import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
13
14
  import { configDir, type Layout } from '../core/layout'
14
- import { isLockHeld } from '../core/lock'
15
- import { callDaemon, isDaemonAlive, servingPid } from './client'
15
+ import { holdLock, isLockHeld } from '../core/lock'
16
+ import { PACKAGE_VERSION } from '../core/version'
17
+ import { callDaemon, isDaemonAlive, servingPid, servingVersion } from './client'
16
18
 
17
19
  type Env = Readonly<Record<string, string | undefined>>
18
20
 
@@ -25,14 +27,37 @@ export const LOCKED_MESSAGE = 'the vault is locked: ask a human to run `typevaul
25
27
  /**
26
28
  * Starts the daemon in the background if it isn't running, like gpg-agent. Only a machine member can start one
27
29
  * unattended; a human's daemon is started by `typevault unlock`, so a locked vault stays locked.
30
+ *
31
+ * A daemon from another release is replaced when it is a machine member's and this process can start one. An
32
+ * unlocked session is never replaced: its key is gone with it, and only its human can type the password again.
28
33
  */
29
34
  export async function ensureDaemon(layout: Layout, env: Env): Promise<void> {
30
- if (await isDaemonAlive(layout.agentSocket)) return
35
+ const running = await servingVersion(layout.agentSocket)
36
+ if (running !== undefined) {
37
+ if (running === PACKAGE_VERSION) return
38
+ if (existsSync(layout.sessionFile) || machineKeys(env).length === 0) {
39
+ throw versionMismatch(layout, running, PACKAGE_VERSION)
40
+ }
41
+ try {
42
+ await stopDaemon(layout)
43
+ } catch (error) {
44
+ // Another command replacing it at the same time already stopped it.
45
+ if (!(error instanceof TypeVaultError && error.code === 'not_found')) throw error
46
+ }
47
+ }
31
48
  if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
32
49
  refuseForeignDaemon(layout, env)
33
50
  await startBackground(layout, env, [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout)])
34
51
  }
35
52
 
53
+ function versionMismatch(layout: Layout, running: string | null, version: string): TypeVaultError {
54
+ const from = running === null ? 'is from an older release' : `is version ${running}`
55
+ const fix = existsSync(layout.sessionFile)
56
+ ? 'run `typevault lock`, then `typevault unlock`'
57
+ : 'run `typevault daemon stop`; a machine member starts the new one'
58
+ return new TypeVaultError('conflict', `the running typevault daemon ${from}, not ${version}: ${fix}`)
59
+ }
60
+
36
61
  /**
37
62
  * Starts an unlocked session daemon holding `key`, handed over stdin so it never shows up in argv or env. With
38
63
  * `sourceLock`, the session is another one's, shared with a worktree: it serves only while that one's daemon holds
@@ -98,6 +123,30 @@ export async function stopDaemon(layout: Layout): Promise<void> {
98
123
  }
99
124
  }
100
125
 
126
+ /**
127
+ * What `typevault lock` does once the daemon is gone: no live grant comes back with the next unlock. Under the daemon
128
+ * lock and a claim on the state directory, so no daemon, on this machine or one sharing the directory, can start in
129
+ * between and write back the grants it just loaded. The file is deleted rather than parsed, which is also how a damaged
130
+ * one is cleared.
131
+ */
132
+ export async function endLiveGrants(layout: Layout, env: Env): Promise<void> {
133
+ if (!existsSync(layout.grantsFile) && !existsSync(layout.sessionFile)) return
134
+ const release = holdLock(layout.daemonLock)
135
+ if (release === undefined) {
136
+ throw new TypeVaultError('conflict', 'a typevault daemon started here while locking; run `typevault lock` again')
137
+ }
138
+ let claim: DaemonClaim | undefined
139
+ try {
140
+ claim = claimDaemon(layout, env)
141
+ rmSync(layout.grantsFile, { force: true })
142
+ rmSync(layout.sessionFile, { force: true })
143
+ await appendAudit(layout, { action: 'grant.revoke', mode: 'live', reason: 'typevault lock' })
144
+ } finally {
145
+ claim?.release()
146
+ release()
147
+ }
148
+ }
149
+
101
150
  function pidIn(pidFile: string): number | undefined {
102
151
  if (!existsSync(pidFile)) return undefined
103
152
  const pid = Number.parseInt(readFileSync(pidFile, 'utf8'), 10)
@@ -157,7 +206,8 @@ export async function startBackground(
157
206
  ensureDir(layout.run, 0o700)
158
207
  // A background daemon has no terminal: its output goes to a log, so a failed start can say why.
159
208
  const logPath = join(layout.run, 'daemon.log')
160
- const log = openSync(logPath, 'w', 0o600)
209
+ const logOffset = existsSync(logPath) ? statSync(logPath).size : 0
210
+ const log = openSync(logPath, 'a', 0o600)
161
211
  // The child starts in its private run directory, never the project's: Bun reads bunfig.toml (a preload) and .env from
162
212
  // its directory, and anyone who can edit a checkout (an agent) could have it read the key off stdin. So it is handed
163
213
  // the vault by path. Its private state is where this process resolved it: `env` may lack the HOME this process fell
@@ -190,16 +240,20 @@ export async function startBackground(
190
240
  }
191
241
  // Two starts racing: the one that loses exits with a conflict while the other's daemon is already serving.
192
242
  if (await isDaemonAlive(layout.agentSocket)) return
193
- throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath)}`)
243
+ throw new TypeVaultError('unavailable', `the typevault daemon did not start: ${whyNotStarted(logPath, logOffset)}`)
194
244
  }
195
245
 
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')
246
+ /** Prefer the current start's cause over a runtime's source excerpt, with where to read the rest. */
247
+ function whyNotStarted(logPath: string, offset: number): string {
248
+ const lines = existsSync(logPath)
249
+ ? readFileSync(logPath)
250
+ .subarray(offset)
251
+ .toString('utf8')
200
252
  .split('\n')
201
253
  .map((line) => line.trim())
202
- .find((line) => line !== '')
203
- : undefined
204
- return first === undefined ? `no output (see ${logPath})` : `${first} (full log: ${logPath})`
254
+ .filter((line) => line !== '')
255
+ : []
256
+ const first = lines.find((line) => line.startsWith('typevault:') || /^\w*error:/i.test(line)) ?? lines[0]
257
+ const message = first?.replace(/^typevault:\s*/, '')
258
+ return message === undefined ? `no output (see ${logPath})` : `${message} (full log: ${logPath})`
205
259
  }
@@ -3,7 +3,7 @@ import { z } from 'zod'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
5
  import { findField, type Field } from '../core/naming'
6
- import { collectEntries, parseExternal, parseJson, withCustomFields, type ImportItem } from './shared'
6
+ import { collectEntries, loginOf, parseExternal, parseJson, withCustomFields, type ImportItem } from './shared'
7
7
  import type { ImportResult } from './types'
8
8
 
9
9
  export const ONEPASSWORD_VIAS = ['sdk', 'op'] as const
@@ -37,6 +37,9 @@ export type SdkClient = {
37
37
  export type ConnectSdk = (account: string) => Promise<SdkClient>
38
38
 
39
39
  const UNSUPPORTED = 'skipped unsupported 1Password item category'
40
+ // Each `op item get` is its own process and each SDK vault read a round trip, so a few run at once; more would
41
+ // mostly queue behind the desktop app and risk 1Password's rate limits.
42
+ const CONCURRENCY = 8
40
43
  // Field types kept as custom fields; dates, menus, addresses and keys don't read as one string.
41
44
  const OP_TEXT_TYPES: ReadonlySet<string> = new Set(['STRING', 'CONCEALED', 'URL', 'EMAIL', 'PHONE', 'OTP'])
42
45
  const SDK_TEXT_TYPES: ReadonlySet<string> = new Set(['Text', 'Concealed', 'Url', 'Email', 'Phone', 'Totp'])
@@ -112,24 +115,48 @@ async function readOp(
112
115
  .filter((vault) => matchVault(vault.id, vault.name, filters.vaults, collected.matchedVaults))
113
116
  .map((vault) => ['--vault', vault.id])
114
117
  }
118
+ const listed: z.infer<typeof OpListSchema> = []
115
119
  for (const scope of scopes) {
116
- const listed = parseJson(
120
+ const items = parseJson(
117
121
  await runOp(['item', 'list', '--format', 'json', ...scope, ...tags, ...account]),
118
122
  OpListSchema,
119
123
  'op',
120
124
  )
121
125
  // `op --tags` also matches nested tags (`tag/child`): those name the fields to import.
122
- for (const entry of listed.filter((item) => tagSelection(item.tags, filters.tags) !== undefined)) {
123
- const args = ['item', 'get', entry.id, '--vault', entry.vault.id, '--reveal', '--format', 'json', ...account]
124
- const item = parseJson(await runOp(args), OpItemSchema, 'op')
125
- const mapped = mapOpItem(item)
126
- if (mapped === undefined) collected.warnings.push(UNSUPPORTED)
127
- else {
128
- const selected = selectFields(mapped, item.title, item.tags, filters.tags, collected.warnings)
129
- if (selected !== undefined) collected.items.push({ ...selected, title: item.title, container: item.vault.name })
126
+ listed.push(...items.filter((item) => tagSelection(item.tags, filters.tags) !== undefined))
127
+ }
128
+ const fetched = await mapLimit(listed, CONCURRENCY, async (entry) => {
129
+ const args = ['item', 'get', entry.id, '--vault', entry.vault.id, '--reveal', '--format', 'json', ...account]
130
+ return { ...parseJson(await runOp(args), OpItemSchema, 'op'), id: entry.id, vaultId: entry.vault.id }
131
+ })
132
+ for (const item of fetched) {
133
+ const mapped = mapOpItem(item)
134
+ if (mapped === undefined) collected.warnings.push(UNSUPPORTED)
135
+ else {
136
+ const selected = selectFields(mapped, item.title, item.tags, filters.tags, collected.warnings)
137
+ if (selected !== undefined)
138
+ collected.items.push({ ...selected, title: item.title, source: onePasswordSource(item.vaultId, item.id) })
139
+ }
140
+ }
141
+ }
142
+
143
+ /** Maps `values` with at most `limit` calls in flight, keeping input order; stops starting new calls on a failure. */
144
+ async function mapLimit<T, R>(values: readonly T[], limit: number, map: (value: T) => Promise<R>): Promise<R[]> {
145
+ const results: R[] = []
146
+ let next = 0
147
+ const worker = async () => {
148
+ while (next < values.length) {
149
+ const index = next++
150
+ try {
151
+ results[index] = await map(values[index] as T)
152
+ } catch (error) {
153
+ next = values.length
154
+ throw error
130
155
  }
131
156
  }
132
157
  }
158
+ await Promise.all(Array.from({ length: Math.min(limit, values.length) }, worker))
159
+ return results
133
160
  }
134
161
 
135
162
  function mapOpItem(item: z.infer<typeof OpItemSchema>): Omit<ImportItem, 'title'> | undefined {
@@ -195,6 +222,8 @@ function mapOpTemplate(item: z.infer<typeof OpItemSchema>): Omit<ImportItem, 'ti
195
222
  }
196
223
  }
197
224
 
225
+ /** An item's source id. 1Password item ids are unique only within their vault, so the vault id comes with it. */
226
+ export const onePasswordSource = (vaultId: string, itemId: string): string => `1password:${vaultId}/${itemId}`
198
227
  /** True when a vault is wanted by id or name, recording which requested vaults it answers to. */
199
228
  function matchVault(id: string, name: string, wanted: readonly string[], matched: Set<string>): boolean {
200
229
  if (wanted.length === 0) return true
@@ -245,7 +274,8 @@ function selectFields(
245
274
  warnings.push(`${title}: skipped, none of its tagged fields were found`)
246
275
  return undefined
247
276
  }
248
- return { ...mapped, fields, tags: kept }
277
+ // The entry keeps its login-based name even when the username field itself isn't selected.
278
+ return { ...mapped, fields, tags: kept, login: loginOf(mapped.fields) ?? '' }
249
279
  }
250
280
 
251
281
  export const spawnOp: RunOp = async (args, input) => {
@@ -269,6 +299,7 @@ export const spawnOp: RunOp = async (args, input) => {
269
299
  }
270
300
 
271
301
  const SdkItemSchema = z.object({
302
+ id: z.string().optional(),
272
303
  title: z.string(),
273
304
  category: z.string(),
274
305
  notes: z.string().default(''),
@@ -295,16 +326,19 @@ async function readSdk(account: string, filters: Filters, connect: ConnectSdk, c
295
326
  matchVault(vault.id, vault.title, filters.vaults, collected.matchedVaults),
296
327
  )
297
328
  const { items, warnings } = collected
298
- for (const vault of vaults) {
329
+ const fetched = await mapLimit(vaults, CONCURRENCY, async (vault) => {
299
330
  const listed = (
300
331
  await client.items.list(vault.id, { type: 'ByState', content: { active: true, archived: false } })
301
332
  ).filter((item) => tagSelection(item.tags, filters.tags) !== undefined)
302
- if (listed.length === 0) continue
303
- const fetched = await client.items.getAll(
333
+ if (listed.length === 0) return []
334
+ const read = await client.items.getAll(
304
335
  vault.id,
305
336
  listed.map((item) => item.id),
306
337
  )
307
- for (const response of fetched.individualResponses) {
338
+ return read.individualResponses
339
+ })
340
+ for (const [index, vault] of vaults.entries()) {
341
+ for (const response of fetched[index] ?? []) {
308
342
  if (response.content === undefined) {
309
343
  warnings.push('skipped a 1Password item that could not be read')
310
344
  continue
@@ -314,7 +348,12 @@ async function readSdk(account: string, filters: Filters, connect: ConnectSdk, c
314
348
  if (mapped === undefined) warnings.push(UNSUPPORTED)
315
349
  else {
316
350
  const selected = selectFields(mapped, item.title, item.tags, filters.tags, warnings)
317
- if (selected !== undefined) items.push({ ...selected, title: item.title, container: vault.title })
351
+ if (selected !== undefined)
352
+ items.push({
353
+ ...selected,
354
+ title: item.title,
355
+ ...(item.id === undefined ? {} : { source: onePasswordSource(vault.id, item.id) }),
356
+ })
318
357
  }
319
358
  }
320
359
  }
@@ -2,6 +2,7 @@ import { strFromU8, unzipSync } from 'fflate'
2
2
  import { z } from 'zod'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
+ import { onePasswordSource } from './1password-live'
5
6
  import { collectEntries, parseExternal, parseJson, withCustomFields, type ImportItem } from './shared'
6
7
  import type { ImportResult } from './types'
7
8
 
@@ -21,6 +22,7 @@ const FieldSchema = z.object({
21
22
  }),
22
23
  })
23
24
  const ItemSchema = z.object({
25
+ uuid: z.string().optional(),
24
26
  categoryUuid: z.string(),
25
27
  state: z.string().optional(),
26
28
  overview: z.object({ title: z.string(), url: z.string().optional(), tags: z.array(z.string()).default([]) }),
@@ -35,8 +37,7 @@ const ExportSchema = z.object({
35
37
  z.object({
36
38
  vaults: z.array(
37
39
  z.object({
38
- attrs: z.object({ name: z.string().optional() }).optional(),
39
- name: z.string().optional(),
40
+ attrs: z.object({ uuid: z.string().optional() }).optional(),
40
41
  items: z.array(ItemSchema),
41
42
  }),
42
43
  ),
@@ -67,13 +68,14 @@ export function parse1Password(bytes: Uint8Array): ImportResult {
67
68
  warnings.push('skipped unsupported 1Password item category')
68
69
  continue
69
70
  }
70
- const container = vault.attrs?.name ?? vault.name
71
71
  items.push({
72
72
  ...mapped,
73
73
  title: item.overview.title,
74
74
  tags: item.overview.tags,
75
- ...(container === undefined ? {} : { container }),
76
75
  ...(item.overview.url === undefined ? {} : { url: item.overview.url }),
76
+ ...(item.uuid === undefined || vault.attrs?.uuid === undefined
77
+ ? {}
78
+ : { source: onePasswordSource(vault.attrs.uuid, item.uuid) }),
77
79
  })
78
80
  }
79
81
  }