typevault 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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.0",
3
+ "version": "0.4.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",
@@ -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
  }
@@ -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
- async #write(input: SetInput, tier: string): Promise<EntrySummary> {
204
- if (
205
- !allowsTier(this.#chain, this.#vault.state, tier) ||
206
- !allowsEntry(this.#chain, this.#vault.state, tier, input.name)
207
- ) {
208
- throw new TypeVaultError('denied', `this grant cannot write ${input.name} in tier "${tier}"`)
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`)
@@ -133,7 +133,13 @@ export class SealedAccess implements Access {
133
133
 
134
134
  async move(from: EntryName, to: EntryName): Promise<void> {
135
135
  const entry = this.#entry(from)
136
- await this.set({ name: to, fields: entry.fields, tier: entry.tier, tags: entry.tags })
136
+ await this.set({
137
+ name: to,
138
+ fields: entry.fields,
139
+ tier: entry.tier,
140
+ tags: entry.tags,
141
+ ...(entry.source === undefined ? {} : { source: entry.source }),
142
+ })
137
143
  await this.remove(from)
138
144
  }
139
145
 
@@ -19,6 +19,7 @@ export type EntryValue = EntrySummary & {
19
19
  readonly fields: Readonly<Record<string, Field>>
20
20
  readonly env?: string
21
21
  readonly origin?: string
22
+ readonly source?: string
22
23
  /** Written by the owner or by a key that reaches all of the reader's own tiers: its `--env` override counts. */
23
24
  readonly trustedWriter?: boolean
24
25
  }
@@ -29,6 +30,8 @@ export type SetInput = {
29
30
  readonly tier?: string | undefined
30
31
  readonly env?: string | undefined
31
32
  readonly origin?: string | undefined
33
+ /** Kept by a blind writer (a sealed grant) that moves an imported entry. */
34
+ readonly source?: string | undefined
32
35
  readonly tags?: readonly string[] | undefined
33
36
  readonly ifRev?: number | undefined
34
37
  }
@@ -44,6 +47,7 @@ export function entryInputOf(input: SetInput, tier: string) {
44
47
  tier,
45
48
  ...(input.env === undefined ? {} : { env: input.env }),
46
49
  ...(input.origin === undefined ? {} : { origin: input.origin }),
50
+ ...(input.source === undefined ? {} : { source: input.source }),
47
51
  ...(input.tags === undefined ? {} : { tags: input.tags }),
48
52
  }
49
53
  }
@@ -78,6 +82,7 @@ export function toValue(tier: string, id: string, rev: number, payload: EntryPay
78
82
  fields: payload.fields,
79
83
  ...(payload.env === undefined ? {} : { env: payload.env }),
80
84
  ...(payload.origin === undefined ? {} : { origin: payload.origin }),
85
+ ...(payload.source === undefined ? {} : { source: payload.source }),
81
86
  }
82
87
  }
83
88
 
@@ -24,19 +24,9 @@ import { accessOf, 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. A daemon from before an upgrade lacks the route, and its listing is still good. */
27
+ /** Runs after the listing it annotates. */
28
28
  async function noteUnreadableEntries(access: Access): Promise<void> {
29
- let unreadable: number
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
  }
@@ -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 { openDirect, resolveAccess } from '../context'
11
+ import { resolveAccess } from '../context'
14
12
  import { csv, note, print, readStdin, repeated } from '../output'
15
13
 
16
14
  async function pump(
@@ -239,7 +237,7 @@ const isVia = (value: string): value is OnePasswordVia => ONEPASSWORD_VIAS.some(
239
237
  export const importCommand = defineCommand({
240
238
  meta: {
241
239
  name: 'import',
242
- description: 'Import a password-manager export, or 1Password directly, into a tier (owner, one transaction)',
240
+ description: 'Import a password-manager export, or 1Password directly, into a tier (one transaction)',
243
241
  },
244
242
  args: {
245
243
  source: { type: 'positional', required: true, description: SOURCES.join(' | ') },
@@ -262,7 +260,10 @@ export const importCommand = defineCommand({
262
260
  }
263
261
  const via = args.via ?? 'sdk'
264
262
  if (!isVia(via)) throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
265
- const vault = await openDirect(process.env)
263
+ const resolved = await resolveAccess(process.env)
264
+ if (resolved.kind === 'sealed') {
265
+ throw new TypeVaultError('unavailable', 'import needs an unlocked vault or a live grant, not a sealed grant')
266
+ }
266
267
  const password = args['password-stdin'] ? await readStdin() : undefined
267
268
  const result =
268
269
  args.path === undefined
@@ -273,22 +274,8 @@ export const importCommand = defineCommand({
273
274
  tags: repeated(rawArgs, '--tag'),
274
275
  })
275
276
  : await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
276
- const tier = args.tier
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
- })
277
+ const stored = await resolved.access.importEntries(result.entries, args.tier)
291
278
  for (const warning of result.warnings) note(`warning: ${warning}`)
292
- note(`imported ${stored.length} entries into ${tier}`)
279
+ note(`imported ${stored.length} entries into ${args.tier}`)
293
280
  },
294
281
  })
@@ -187,6 +187,8 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
187
187
  if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
188
188
  await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
189
189
  }
190
+ // A session daemon from another release fails here instead of misreading this CLI's requests.
191
+ await ensureDaemon(layout, env)
190
192
  return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
191
193
  }
192
194
 
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.map((cell, index) => (index === row.length - 1 ? cell : cell.padEnd(widths[index] ?? 0))).join(' '),
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
  }
@@ -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({ host: z.string(), pid: z.number().int(), token: z.string(), at: z.string() })
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({ host: hostId(env), pid: process.pid, token, at: new Date().toISOString() })
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.host}, 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})`,
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 =>
@@ -1,4 +1,5 @@
1
- import { existsSync, realpathSync } from 'node:fs'
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
- /** This machine, as daemon holders and audit anchors name it: `TYPEVAULT_HOST_ID`, else the hostname. */
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
- return explicit !== undefined && explicit !== '' ? explicit : hostname()
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
  /**
@@ -21,8 +21,17 @@ export function parsePreset(value: string): Preset {
21
21
 
22
22
  export type EntryName = string & { readonly __brand: 'EntryName' }
23
23
 
24
- const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
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 => input.trim().replace(REF_SCHEME, '').toLowerCase()
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
- /** Parses `[typevault://]<service>[/<account>]`. Names are case-insensitive, stored lowercase and without the scheme. */
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((segment) => SEGMENT.test(segment))) {
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 [a-z0-9-])`,
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 name): such a field is reachable only
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
- if (field === '$default') return name.toUpperCase().replace(/[/-]/g, '_')
163
- const suffix = field
164
- .normalize('NFKD')
165
- .replace(/\p{M}/gu, '')
166
- .toUpperCase()
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 : `${name.toUpperCase().replace(/[/-]/g, '_')}_${suffix}`
183
+ return suffix === '' ? undefined : `${base}_${suffix}`
170
184
  }
171
185
 
172
- /** Turns arbitrary text (an import title, a vault name) into a valid name segment. */
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 {
@@ -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
  }
package/src/core/vault.ts CHANGED
@@ -37,6 +37,7 @@ export type EntryBase = {
37
37
  readonly rev: number
38
38
  readonly created: string
39
39
  readonly rotated: string
40
+ readonly source?: string
40
41
  }
41
42
 
42
43
  export type PutOptions = { readonly ifRev?: number; readonly base?: EntryBase }
@@ -47,6 +48,7 @@ export type EntryInput = {
47
48
  readonly tier: string
48
49
  readonly env?: string
49
50
  readonly origin?: string
51
+ readonly source?: string
50
52
  readonly tags?: readonly string[]
51
53
  }
52
54
 
@@ -217,6 +219,7 @@ export class Vault {
217
219
  }
218
220
  const now = new Date().toISOString()
219
221
  const changed = found === undefined || !sameFields(found.payload.fields, input.fields)
222
+ const source = input.source ?? prior?.source
220
223
  const payload: EntryPayload = {
221
224
  v: 1,
222
225
  name: input.name,
@@ -226,9 +229,12 @@ export class Vault {
226
229
  rotated: changed ? now : (prior?.rotated ?? now),
227
230
  ...(input.env === undefined ? {} : { env: input.env }),
228
231
  ...(input.origin === undefined ? {} : { origin: input.origin }),
232
+ ...(source === undefined ? {} : { source }),
229
233
  ...(changed || found?.payload.needsRotation !== true ? {} : { needsRotation: true }),
230
234
  }
231
- const id = entryIdIn(signer.ref, input.tier, input.name, prior?.id)
235
+ // A renamed entry gets a fresh id, as in `move`: a grant issued for the old name must not follow it.
236
+ const renamed = found !== undefined && found.payload.name !== input.name
237
+ const id = entryIdIn(signer.ref, input.tier, input.name, renamed ? undefined : prior?.id)
232
238
  const draft = { id, tier: input.tier, rev: currentRev + 1, at: now, payload }
233
239
  return { envelope: await sealEntry(draft, this.#state, signer), payload }
234
240
  }
@@ -253,21 +259,55 @@ export class Vault {
253
259
  })
254
260
  }
255
261
 
256
- /** Writes many entries as one transaction (an import): all of them land, or none do. */
262
+ /**
263
+ * Writes many entries as one transaction (an import): all of them land, or none do. An input with a `source` takes
264
+ * over the entry imported from that item, renaming it when the item was renamed; a name held by another item's
265
+ * entry is a conflict, never overwritten. An entry it would replace that `allows` refuses fails the whole import.
266
+ */
257
267
  putMany(
258
268
  inputs: readonly EntryInput[],
259
269
  signerFor: (tier: string) => Promise<SignerContext>,
270
+ allows: (found: StoredEntry) => boolean = () => true,
260
271
  ): Promise<readonly StoredEntry[]> {
261
272
  return withLock(this.layout.lockFile, 'exclusive', async () => {
262
273
  const { entries } = await this.scan()
263
274
  const txn = new Txn()
264
275
  const stored: StoredEntry[] = []
265
276
  const retiered: string[] = []
266
- for (const input of inputs) {
267
- const found = resolveName(
277
+ const byName = (name: EntryName) =>
278
+ resolveName(
268
279
  this.#state.tiers,
269
- entries.filter((entry) => entry.payload.name === input.name),
280
+ entries.filter((entry) => entry.payload.name === name),
270
281
  )
282
+ const bySource = (source: string | undefined) =>
283
+ source === undefined
284
+ ? undefined
285
+ : resolveName(
286
+ this.#state.tiers,
287
+ entries.filter((entry) => entry.payload.source === source),
288
+ )
289
+ const matches = inputs.map((input) => ({ input, held: byName(input.name), own: bySource(input.source) }))
290
+ // An entry this import renames frees its old name, so two items may trade names in one import.
291
+ const claimed = new Set(matches.flatMap(({ own }) => (own === undefined ? [] : [own.envelope.id])))
292
+ const targets = matches.map(({ input, held, own }) => {
293
+ const other =
294
+ held !== undefined && held.envelope.id !== own?.envelope.id && !claimed.has(held.envelope.id)
295
+ ? held
296
+ : undefined
297
+ // An entry with no source (written by hand, or by an older import) is taken over only by a new item.
298
+ if (other !== undefined && (own !== undefined || other.payload.source !== undefined)) {
299
+ throw new TypeVaultError(
300
+ 'conflict',
301
+ `${input.name} already holds another entry; rename or remove it, then import again`,
302
+ )
303
+ }
304
+ const found = own ?? other
305
+ if (found !== undefined && !allows(found)) {
306
+ throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
307
+ }
308
+ return { input, found }
309
+ })
310
+ for (const { input, found } of targets) {
271
311
  const signer = await signerFor(input.tier)
272
312
  const entry = await this.#draft(input, found, {}, signer)
273
313
  txn.put(`entries/${entry.envelope.id}.json`, `${JSON.stringify(entry.envelope, null, 2)}\n`)
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod'
2
+
3
+ /**
4
+ * This release's version, read once when the module loads: a daemon reports it, so a CLI from another release knows
5
+ * not to talk to it. Read any later, an idle daemon would report the version of a package upgraded under it.
6
+ */
7
+ export const PACKAGE_VERSION = z
8
+ .object({ version: z.string() })
9
+ .parse(await Bun.file(new URL('../../package.json', import.meta.url)).json()).version
@@ -1,11 +1,26 @@
1
+ import { randomBytes } from 'node:crypto'
2
+
1
3
  import { parseTtl } from '../access/scope'
2
4
  import { ScopedVault } from '../access/scoped'
3
5
  import { appendAudit } from '../audit/log'
4
6
  import { TypeVaultError } from '../core/errors'
5
7
  import type { Vault } from '../core/vault'
8
+ import { PACKAGE_VERSION } from '../core/version'
6
9
  import { type GrantStore, type ResolvedGrant, SESSION_CEILING } from './grants'
7
10
  import { type Handler, json, parseBody } from './http'
8
- import { AttachBody, DeriveBody, MoveBody, NameBody, RequestBody, SetBody, ValuesBody, WaitBody } from './protocol'
11
+ import {
12
+ AttachBody,
13
+ DeriveBody,
14
+ ImportBody,
15
+ ImportEntries,
16
+ ImportStageBody,
17
+ MoveBody,
18
+ NameBody,
19
+ RequestBody,
20
+ SetBody,
21
+ ValuesBody,
22
+ WaitBody,
23
+ } from './protocol'
9
24
  import type { PromptRequests } from './requests'
10
25
 
11
26
  export type DaemonContext = {
@@ -45,11 +60,33 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
45
60
  return { grant, access }
46
61
  }
47
62
 
63
+ type StagedImport = {
64
+ readonly grant: string
65
+ readonly parts: Uint8Array[]
66
+ bytes: number
67
+ exp: number
68
+ }
69
+
70
+ /** What staged imports may hold in memory at once, across every grant. */
71
+ const MAX_STAGED_BYTES = 64 << 20
72
+ const STAGED_TTL_MS = 10 * 60_000
73
+
48
74
  /** Routes on the agent socket. Every call needs a live grant; none can create a grant from nothing. */
49
75
  export function agentRoutes(context: DaemonContext): Readonly<Record<string, Handler>> {
76
+ // An import, or even one entry, can exceed a request body, so its serialized JSON arrives in chunks and is written
77
+ // by one final call, all or nothing.
78
+ const staged = new Map<string, StagedImport>()
79
+ const stagedBy = (upload: string, grant: string): StagedImport => {
80
+ const found = staged.get(upload)
81
+ if (found === undefined || found.grant !== grant || found.exp <= Date.now()) {
82
+ throw new TypeVaultError('not_found', 'no such import upload (it may have expired)')
83
+ }
84
+ return found
85
+ }
50
86
  return {
51
- // The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names.
52
- '/v1/ping': async () => json({ ok: true, pid: process.pid }),
87
+ // The PID lets `stopDaemon` signal exactly the process that answers here, never one a stale PID file names. The
88
+ // version lets a CLI from another release tell this daemon isn't its own.
89
+ '/v1/ping': async () => json({ ok: true, pid: process.pid, version: PACKAGE_VERSION }),
53
90
  '/v1/whoami': async (request) => {
54
91
  const { grant, access } = session(context, request)
55
92
  const { hash: _hash, ...record } = grant.record
@@ -67,6 +104,44 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
67
104
  return json(await session(context, request).access.values(only, reason))
68
105
  },
69
106
  '/v1/set': async (request) => json(await session(context, request).access.set(await parseBody(request, SetBody))),
107
+ '/v1/import/stage': async (request) => {
108
+ const { grant } = session(context, request)
109
+ const body = await parseBody(request, ImportStageBody)
110
+ const now = Date.now()
111
+ for (const [id, upload] of staged) if (upload.exp <= now) staged.delete(id)
112
+ const part = Buffer.from(body.chunk, 'base64')
113
+ const bytes = part.byteLength
114
+ const held = [...staged.values()].reduce((sum, upload) => sum + upload.bytes, 0)
115
+ if (held + bytes > MAX_STAGED_BYTES) throw new TypeVaultError('invalid', 'this import is too large (over 64 MiB)')
116
+ const id = body.upload ?? randomBytes(16).toString('base64url')
117
+ const upload =
118
+ body.upload === undefined
119
+ ? { grant: grant.record.id, parts: [], bytes: 0, exp: 0 }
120
+ : stagedBy(id, grant.record.id)
121
+ upload.parts.push(part)
122
+ upload.bytes += bytes
123
+ upload.exp = now + STAGED_TTL_MS
124
+ staged.set(id, upload)
125
+ return json({ upload: id })
126
+ },
127
+ '/v1/import': async (request) => {
128
+ const { grant, access } = session(context, request)
129
+ const { upload, tier } = await parseBody(request, ImportBody)
130
+ const { parts } = stagedBy(upload, grant.record.id)
131
+ staged.delete(upload)
132
+ let value: unknown
133
+ try {
134
+ value = JSON.parse(Buffer.concat(parts).toString('utf8'))
135
+ } catch (error) {
136
+ if (error instanceof SyntaxError) throw new TypeVaultError('invalid', 'the staged import is not JSON')
137
+ throw error
138
+ }
139
+ const entries = ImportEntries.safeParse(value)
140
+ if (!entries.success) {
141
+ throw new TypeVaultError('invalid', `bad import: ${entries.error.issues[0]?.message ?? 'invalid'}`)
142
+ }
143
+ return json(await access.importEntries(entries.data, tier))
144
+ },
70
145
  '/v1/remove': async (request) => {
71
146
  const { name, tier } = await parseBody(request, NameBody)
72
147
  await session(context, request).access.remove(name, tier)
@@ -75,6 +75,17 @@ export async function servingPid(socket: string): Promise<number | undefined> {
75
75
  }
76
76
  }
77
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
+
78
89
  export async function isDaemonAlive(socket: string): Promise<boolean> {
79
90
  try {
80
91
  await callDaemon(socket, '/v1/ping', {}, z.object({ ok: z.literal(true) }), { timeoutMs: 1_000 })
@@ -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 {
@@ -44,6 +47,18 @@ export class LiveAccess implements Access {
44
47
  return toSummaryValue(await this.call('/v1/set', input, EntrySummarySchema))
45
48
  }
46
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
+
47
62
  async remove(name: EntryName, tier?: string): Promise<void> {
48
63
  await this.call('/v1/remove', { name, ...(tier === undefined ? {} : { tier }) }, Ok)
49
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(),
@@ -13,7 +13,8 @@ import { ensureDir } from '../core/fsx'
13
13
  import { claimDaemon, type DaemonClaim, refuseForeignDaemon } from '../core/holder'
14
14
  import { configDir, type Layout } from '../core/layout'
15
15
  import { holdLock, isLockHeld } from '../core/lock'
16
- import { callDaemon, isDaemonAlive, servingPid } from './client'
16
+ import { PACKAGE_VERSION } from '../core/version'
17
+ import { callDaemon, isDaemonAlive, servingPid, servingVersion } from './client'
17
18
 
18
19
  type Env = Readonly<Record<string, string | undefined>>
19
20
 
@@ -26,14 +27,37 @@ export const LOCKED_MESSAGE = 'the vault is locked: ask a human to run `typevaul
26
27
  /**
27
28
  * Starts the daemon in the background if it isn't running, like gpg-agent. Only a machine member can start one
28
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.
29
33
  */
30
34
  export async function ensureDaemon(layout: Layout, env: Env): Promise<void> {
31
- 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
+ }
32
48
  if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
33
49
  refuseForeignDaemon(layout, env)
34
50
  await startBackground(layout, env, [process.execPath, CLI, 'daemon', 'run', ...vaultArgs(layout)])
35
51
  }
36
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
+
37
61
  /**
38
62
  * Starts an unlocked session daemon holding `key`, handed over stdin so it never shows up in argv or env. With
39
63
  * `sourceLock`, the session is another one's, shared with a worktree: it serves only while that one's daemon holds
@@ -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
  }
@@ -6,9 +6,9 @@ import type { ImportResult } from './types'
6
6
 
7
7
  const TextSchema = z.string().nullish()
8
8
  const ItemSchema = z.object({
9
+ id: TextSchema,
9
10
  type: z.number().int(),
10
11
  name: z.string(),
11
- folderId: TextSchema,
12
12
  notes: TextSchema,
13
13
  login: z
14
14
  .object({
@@ -20,10 +20,7 @@ const ItemSchema = z.object({
20
20
  .nullish(),
21
21
  sshKey: z.object({ privateKey: TextSchema, publicKey: TextSchema }).nullish(),
22
22
  })
23
- const ExportSchema = z.object({
24
- folders: z.array(z.object({ id: z.string(), name: z.string() })).default([]),
25
- items: z.array(ItemSchema),
26
- })
23
+ const ExportSchema = z.object({ items: z.array(ItemSchema) })
27
24
 
28
25
  export function parseBitwarden(text: string): ImportResult {
29
26
  const raw = parseJson(text, z.object({ encrypted: z.boolean().optional() }).passthrough(), 'Bitwarden')
@@ -31,12 +28,10 @@ export function parseBitwarden(text: string): ImportResult {
31
28
  throw new TypeVaultError('invalid', 'encrypted Bitwarden exports are not supported; export unencrypted JSON')
32
29
  }
33
30
  const data = parseExternal(raw, ExportSchema, 'Bitwarden')
34
- const folders = new Map(data.folders.map((folder) => [folder.id, folder.name]))
35
31
  const items: ImportItem[] = []
36
32
  const warnings: string[] = []
37
33
  for (const item of data.items) {
38
- const container = item.folderId ? folders.get(item.folderId) : undefined
39
- const common = { title: item.name, ...(container === undefined ? {} : { container }) }
34
+ const common = { title: item.name, ...(item.id ? { source: `bitwarden:${item.id}` } : {}) }
40
35
  switch (item.type) {
41
36
  case 1: {
42
37
  const url = item.login?.uris?.find((uri) => uri.uri)?.uri ?? undefined
@@ -38,9 +38,8 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
38
38
  }
39
39
  const items: ImportItem[] = []
40
40
  const warnings: string[] = []
41
- const visit = (group: KdbxGroup, root: boolean) => {
41
+ const visit = (group: KdbxGroup) => {
42
42
  if (group.uuid.equals(db.meta.recycleBinUuid)) return
43
- const container = root ? undefined : parseExternal(group.name, z.string().optional(), 'KeePass group')
44
43
  for (const entry of group.entries) {
45
44
  const fields = parseExternal(
46
45
  Object.fromEntries(
@@ -62,12 +61,12 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
62
61
  ? { username: fields['UserName'], password: fields['Password'], url, totp: fields['otp'] }
63
62
  : { $default: fields['Notes'] },
64
63
  tags: parseExternal(entry.tags, z.array(z.string()).readonly(), 'KeePass tags'),
65
- ...(container === undefined ? {} : { container }),
64
+ source: `keepass:${entry.uuid.id}`,
66
65
  ...(url === undefined ? {} : { url }),
67
66
  })
68
67
  }
69
- for (const child of group.groups) visit(child, false)
68
+ for (const child of group.groups) visit(child)
70
69
  }
71
- for (const group of db.groups) visit(group, true)
70
+ for (const group of db.groups) visit(group)
72
71
  return collectEntries(items, warnings)
73
72
  }
@@ -20,7 +20,6 @@ export function parseLastpass(text: string): ImportResult {
20
20
  return [
21
21
  {
22
22
  title: row['name'] ?? '',
23
- container: row['grouping'] ?? '',
24
23
  preset: note ? ('note' as const) : ('password' as const),
25
24
  fields: note
26
25
  ? { $default: extra }
@@ -1,10 +1,12 @@
1
1
  import { z } from 'zod'
2
2
 
3
+ import { sha256Hex } from '../core/crypto'
4
+ import { utf8 } from '../core/encoding'
3
5
  import { TypeVaultError } from '../core/errors'
4
6
  import {
5
7
  isFieldName,
8
+ type EntryName,
6
9
  parseEntryName,
7
- slugifySegment,
8
10
  PRESETS,
9
11
  type Preset,
10
12
  type Field,
@@ -15,22 +17,47 @@ import type { ImportedEntry, ImportResult } from './types'
15
17
 
16
18
  export type ImportItem = {
17
19
  readonly title: string
18
- readonly container?: string
20
+ /** The login on the service, naming the entry's account segment. Read from the `username` field when unset. */
21
+ readonly login?: string
19
22
  readonly preset: Preset
20
23
  readonly fields: Readonly<Record<string, string | Field | undefined>>
21
24
  readonly url?: string
22
25
  readonly tags?: readonly string[]
23
26
  readonly env?: string
27
+ /** The item's id in its password manager (`bitwarden:<id>`), when the source has stable ids. */
28
+ readonly source?: string
24
29
  }
25
30
 
26
31
  export function collectEntries(items: readonly ImportItem[], warnings: readonly string[] = []): ImportResult {
27
32
  const entries: ImportedEntry[] = []
28
33
  const messages = [...warnings]
29
34
  const used = new Set<string>()
35
+ const accounts = new Map<string, string>()
36
+ // A login whose name mixes scripts still keeps its entries apart, under a stable stand-in, rather than taking down
37
+ // every item signed in with it.
38
+ const accountSegment = (raw: string): string => {
39
+ const known = accounts.get(raw)
40
+ if (known !== undefined) return known
41
+ let segment = toSegment(raw)
42
+ if (segment !== '' && entryNameOf(segment) === undefined) {
43
+ const standIn = sha256Hex(utf8(segment)).slice(0, 8)
44
+ messages.push(`"${raw}" makes no usable name segment; its entries use "${standIn}"`)
45
+ segment = standIn
46
+ }
47
+ accounts.set(raw, segment)
48
+ return segment
49
+ }
30
50
  for (const item of items) {
31
- const service = slugifySegment(item.title)
32
- const base = item.container ? `${service}/${slugifySegment(item.container)}` : service
33
- let name = base
51
+ const title = toSegment(item.title)
52
+ // The account segment names the login on the service, never the password manager's vault or folder.
53
+ const account = accountSegment(item.login ?? loginOf(item.fields) ?? '')
54
+ // Collisions are checked on the canonical name, so two spellings of one name can't land on the same entry.
55
+ const base = entryNameOf(account === '' ? title : `${title}/${account}`)
56
+ if (base === undefined) {
57
+ messages.push(`skipped "${item.title}": its title makes no usable entry name`)
58
+ continue
59
+ }
60
+ let name: string = base
34
61
  let suffix = 2
35
62
  while (used.has(name)) name = `${base}-${suffix++}`
36
63
  used.add(name)
@@ -68,12 +95,37 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
68
95
  fields,
69
96
  tags: item.tags ?? [],
70
97
  ...(origin === undefined ? {} : { origin }),
98
+ ...(item.source === undefined ? {} : { source: item.source }),
71
99
  ...(item.env === undefined ? {} : { env: item.env }),
72
100
  })
73
101
  }
74
102
  return { entries, warnings: messages }
75
103
  }
76
104
 
105
+ export function loginOf(fields: ImportItem['fields']): string | undefined {
106
+ const username = fields['username']
107
+ return typeof username === 'string' || username === undefined ? username : fieldStrings(username)[0]
108
+ }
109
+
110
+ /** A title or login as a name segment: lowercase, with each run of spaces and other punctuation one `-`. */
111
+ const toSegment = (raw: string): string =>
112
+ raw
113
+ .toLowerCase()
114
+ .normalize('NFC')
115
+ .replace(/[^\p{L}\p{M}\p{N}.@+]+/gu, '-')
116
+ .replace(/[.-]*-[.-]*/g, '-')
117
+ .replace(/\.{2,}/g, '.')
118
+ .replace(/^[.-]+|[.-]+$/g, '')
119
+
120
+ function entryNameOf(name: string): EntryName | undefined {
121
+ try {
122
+ return parseEntryName(name)
123
+ } catch (error) {
124
+ if (error instanceof TypeVaultError) return undefined
125
+ throw error
126
+ }
127
+ }
128
+
77
129
  /**
78
130
  * The template fields plus every labeled field the mapper didn't place, kept under its own label. A value already
79
131
  * in a template field is skipped, so an API credential's `credential` doesn't land twice.
@@ -1,6 +1,6 @@
1
1
  import type { EntryPayload } from '../core/payload'
2
2
 
3
- export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'tags' | 'env'>
3
+ export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'source' | 'tags' | 'env'>
4
4
 
5
5
  export type ImportResult = {
6
6
  readonly entries: readonly ImportedEntry[]