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.
Files changed (72) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +7 -7
  7. package/src/access/scoped.ts +100 -44
  8. package/src/access/sealed-access.ts +45 -23
  9. package/src/access/sealed.ts +33 -21
  10. package/src/access/types.ts +25 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +14 -9
  13. package/src/cli/commands/admin.ts +87 -47
  14. package/src/cli/commands/daemon.ts +33 -15
  15. package/src/cli/commands/entries.ts +166 -55
  16. package/src/cli/commands/grant.ts +12 -20
  17. package/src/cli/commands/members.ts +281 -0
  18. package/src/cli/commands/run.ts +61 -24
  19. package/src/cli/context.ts +155 -15
  20. package/src/cli/index.ts +27 -4
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +65 -0
  23. package/src/core/admin.ts +125 -74
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +9 -9
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +6 -0
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +84 -0
  31. package/src/core/identity.ts +130 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/keyring.ts +100 -56
  34. package/src/core/layout.ts +145 -26
  35. package/src/core/lock.ts +128 -16
  36. package/src/core/naming.ts +146 -49
  37. package/src/core/password.ts +111 -0
  38. package/src/core/payload.ts +42 -38
  39. package/src/core/revisions.ts +8 -4
  40. package/src/core/rotate.ts +59 -42
  41. package/src/core/state.ts +88 -48
  42. package/src/core/txn.ts +5 -4
  43. package/src/core/vault.ts +108 -46
  44. package/src/core/worktrees.ts +39 -0
  45. package/src/daemon/admin-routes.ts +33 -21
  46. package/src/daemon/agent-routes.ts +29 -11
  47. package/src/daemon/client.ts +15 -0
  48. package/src/daemon/daemon.ts +210 -32
  49. package/src/daemon/grants.ts +21 -4
  50. package/src/daemon/http.ts +3 -0
  51. package/src/daemon/live-access.ts +4 -4
  52. package/src/daemon/protocol.ts +17 -12
  53. package/src/daemon/requests.ts +17 -22
  54. package/src/daemon/spawn.ts +188 -9
  55. package/src/export/1password.ts +157 -0
  56. package/src/import/1password-live.ts +399 -0
  57. package/src/import/1password.ts +26 -5
  58. package/src/import/bitwarden.ts +3 -3
  59. package/src/import/csv.ts +1 -1
  60. package/src/import/dotenv.ts +2 -2
  61. package/src/import/index.ts +1 -0
  62. package/src/import/keepass.ts +2 -2
  63. package/src/import/lastpass.ts +2 -2
  64. package/src/import/shared.ts +67 -10
  65. package/src/import/typeclaw.ts +2 -2
  66. package/src/import/types.ts +1 -1
  67. package/src/index.ts +58 -0
  68. package/src/owner.ts +156 -0
  69. package/src/prompt/browser.ts +48 -15
  70. package/src/prompt/page.ts +19 -11
  71. package/src/prompt/styles.ts +64 -34
  72. package/src/prompt/types.ts +3 -3
@@ -0,0 +1,399 @@
1
+ import type { Client } from '@1password/sdk'
2
+ import { z } from 'zod'
3
+
4
+ import { TypeVaultError } from '../core/errors'
5
+ import { findField, type Field } from '../core/naming'
6
+ import { collectEntries, parseExternal, parseJson, withCustomFields, type ImportItem } from './shared'
7
+ import type { ImportResult } from './types'
8
+
9
+ export const ONEPASSWORD_VIAS = ['sdk', 'op'] as const
10
+ export type OnePasswordVia = (typeof ONEPASSWORD_VIAS)[number]
11
+
12
+ /** Several values of one filter match any of them; different filters must all match. */
13
+ export type OnePasswordOptions = {
14
+ readonly via: OnePasswordVia
15
+ readonly accounts?: readonly string[]
16
+ readonly vaults?: readonly string[]
17
+ readonly tags?: readonly string[]
18
+ }
19
+
20
+ /** Runs `op` with `args`; `input` is piped to stdin, so secrets never land in argv. */
21
+ export type RunOp = (args: readonly string[], input?: string) => Promise<string>
22
+
23
+ export type SdkClient = {
24
+ readonly vaults: { list(): Promise<readonly { readonly id: string; readonly title: string }[]> }
25
+ readonly items: {
26
+ list(
27
+ vaultId: string,
28
+ ...filters: { type: 'ByState'; content: { active: boolean; archived: boolean } }[]
29
+ ): Promise<readonly { readonly id: string; readonly tags: readonly string[] }[]>
30
+ getAll(
31
+ vaultId: string,
32
+ itemIds: string[],
33
+ ): Promise<{ readonly individualResponses: readonly { readonly content?: unknown; readonly error?: unknown }[] }>
34
+ }
35
+ }
36
+
37
+ export type ConnectSdk = (account: string) => Promise<SdkClient>
38
+
39
+ const UNSUPPORTED = 'skipped unsupported 1Password item category'
40
+ // Field types kept as custom fields; dates, menus, addresses and keys don't read as one string.
41
+ const OP_TEXT_TYPES: ReadonlySet<string> = new Set(['STRING', 'CONCEALED', 'URL', 'EMAIL', 'PHONE', 'OTP'])
42
+ const SDK_TEXT_TYPES: ReadonlySet<string> = new Set(['Text', 'Concealed', 'Url', 'Email', 'Phone', 'Totp'])
43
+
44
+ export async function read1Password(
45
+ options: OnePasswordOptions,
46
+ deps: { readonly runOp?: RunOp; readonly connectSdk?: ConnectSdk } = {},
47
+ ): Promise<ImportResult> {
48
+ const accounts = options.accounts ?? []
49
+ const filters: Filters = { vaults: options.vaults ?? [], tags: options.tags ?? [] }
50
+ // `op --tags` takes a comma-separated list, so one tag can't hold a comma.
51
+ if (filters.tags.some((tag) => tag === '' || tag.includes(','))) {
52
+ throw new TypeVaultError('invalid', '--tag values must be non-empty and contain no comma')
53
+ }
54
+ const collected: Collected = { items: [], warnings: [], matchedVaults: new Set() }
55
+ if (options.via === 'op') {
56
+ const runOp = deps.runOp ?? spawnOp
57
+ for (const account of accounts.length === 0 ? [undefined] : accounts) {
58
+ await readOp(account, filters, runOp, collected)
59
+ }
60
+ } else {
61
+ if (accounts.length === 0) {
62
+ throw new TypeVaultError('invalid', '--account is required with --via sdk (the account name shown in 1Password)')
63
+ }
64
+ const connect = deps.connectSdk ?? connectDesktopSdk
65
+ for (const account of accounts) await readSdk(account, filters, connect, collected)
66
+ }
67
+ // A vault may live in only one of several accounts, so a requested vault is missing only if no account had it.
68
+ const missing = filters.vaults.find((vault) => !collected.matchedVaults.has(vault))
69
+ if (missing !== undefined) throw new TypeVaultError('not_found', `1Password vault "${missing}" was not found`)
70
+ return collectEntries(collected.items, collected.warnings)
71
+ }
72
+
73
+ type Filters = { readonly vaults: readonly string[]; readonly tags: readonly string[] }
74
+ type Collected = { readonly items: ImportItem[]; readonly warnings: string[]; readonly matchedVaults: Set<string> }
75
+
76
+ const OpVaultListSchema = z.array(z.object({ id: z.string(), name: z.string().default('') }))
77
+ const OpListSchema = z.array(
78
+ z.object({ id: z.string(), vault: z.object({ id: z.string() }), tags: z.array(z.string()).default([]) }),
79
+ )
80
+ const OpItemSchema = z.object({
81
+ title: z.string(),
82
+ category: z.string(),
83
+ vault: z.object({ name: z.string() }),
84
+ tags: z.array(z.string()).default([]),
85
+ urls: z.array(z.object({ href: z.string(), primary: z.boolean().optional() })).default([]),
86
+ fields: z
87
+ .array(
88
+ z.object({
89
+ id: z.string().default(''),
90
+ type: z.string().default(''),
91
+ purpose: z.string().optional(),
92
+ label: z.string().default(''),
93
+ value: z.string().optional(),
94
+ ssh_formats: z.object({ openssh: z.object({ value: z.string() }).optional() }).optional(),
95
+ }),
96
+ )
97
+ .default([]),
98
+ })
99
+
100
+ async function readOp(
101
+ accountName: string | undefined,
102
+ filters: Filters,
103
+ runOp: RunOp,
104
+ collected: Collected,
105
+ ): Promise<void> {
106
+ const account = accountName === undefined ? [] : ['--account', accountName]
107
+ const tags = filters.tags.length === 0 ? [] : ['--tags', filters.tags.join(',')]
108
+ let scopes: readonly (readonly string[])[] = [[]]
109
+ if (filters.vaults.length > 0) {
110
+ const vaults = parseJson(await runOp(['vault', 'list', '--format', 'json', ...account]), OpVaultListSchema, 'op')
111
+ scopes = vaults
112
+ .filter((vault) => matchVault(vault.id, vault.name, filters.vaults, collected.matchedVaults))
113
+ .map((vault) => ['--vault', vault.id])
114
+ }
115
+ for (const scope of scopes) {
116
+ const listed = parseJson(
117
+ await runOp(['item', 'list', '--format', 'json', ...scope, ...tags, ...account]),
118
+ OpListSchema,
119
+ 'op',
120
+ )
121
+ // `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 })
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ function mapOpItem(item: z.infer<typeof OpItemSchema>): Omit<ImportItem, 'title'> | undefined {
136
+ const mapped = mapOpTemplate(item)
137
+ if (mapped === undefined) return undefined
138
+ // Built-in fields (username, password, notes) carry a purpose; custom ones don't.
139
+ const labeled = item.fields
140
+ .filter((field) => field.purpose === undefined && OP_TEXT_TYPES.has(field.type))
141
+ .map(
142
+ (field) =>
143
+ [
144
+ field.label,
145
+ field.value === undefined
146
+ ? undefined
147
+ : {
148
+ type:
149
+ field.type === 'CONCEALED'
150
+ ? ('secret' as const)
151
+ : field.type === 'OTP'
152
+ ? ('totp' as const)
153
+ : ('text' as const),
154
+ value: field.value,
155
+ },
156
+ ] as const,
157
+ )
158
+ return { ...mapped, fields: withCustomFields(mapped.fields, labeled) }
159
+ }
160
+
161
+ function mapOpTemplate(item: z.infer<typeof OpItemSchema>): Omit<ImportItem, 'title'> | undefined {
162
+ const value = (match: (field: (typeof item.fields)[number]) => boolean) => item.fields.find(match)?.value
163
+ const named = (names: readonly string[]) =>
164
+ value((field) => names.includes(field.id.toLowerCase()) || names.includes(field.label.toLowerCase()))
165
+ const url = (item.urls.find((link) => link.primary) ?? item.urls[0])?.href
166
+ switch (item.category) {
167
+ case 'LOGIN':
168
+ case 'PASSWORD':
169
+ return {
170
+ preset: 'password',
171
+ fields: {
172
+ username: value((field) => field.purpose === 'USERNAME'),
173
+ password: value((field) => field.purpose === 'PASSWORD'),
174
+ totp: value((field) => field.type === 'OTP'),
175
+ url,
176
+ },
177
+ ...(url === undefined ? {} : { url }),
178
+ }
179
+ case 'SECURE_NOTE':
180
+ return { preset: 'note', fields: { $default: value((field) => field.purpose === 'NOTES') } }
181
+ case 'API_CREDENTIAL':
182
+ return { preset: 'api_key', fields: { $default: named(['credential', 'api key', 'api_key', 'key']) } }
183
+ case 'SSH_KEY': {
184
+ const key = item.fields.find((field) => field.type === 'SSHKEY')
185
+ return {
186
+ preset: 'ssh',
187
+ fields: {
188
+ private_key: key?.ssh_formats?.openssh?.value ?? key?.value,
189
+ public_key: named(['public_key', 'public key']),
190
+ },
191
+ }
192
+ }
193
+ default:
194
+ return undefined
195
+ }
196
+ }
197
+
198
+ /** True when a vault is wanted by id or name, recording which requested vaults it answers to. */
199
+ function matchVault(id: string, name: string, wanted: readonly string[], matched: Set<string>): boolean {
200
+ if (wanted.length === 0) return true
201
+ const hits = wanted.filter((value) => value === id || value === name)
202
+ for (const hit of hits) matched.add(hit)
203
+ return hits.length > 0
204
+ }
205
+
206
+ /**
207
+ * Which fields an item's tags select under `--tag`: every field when it carries one of the tags, only the named ones
208
+ * for `<tag>/<field>` tags, and undefined when it carries neither.
209
+ */
210
+ function tagSelection(tags: readonly string[], wanted: readonly string[]): 'all' | readonly string[] | undefined {
211
+ if (wanted.length === 0 || wanted.some((tag) => tags.includes(tag))) return 'all'
212
+ const fields = tags.flatMap((value) =>
213
+ wanted.flatMap((tag) => (value.startsWith(`${tag}/`) ? [value.slice(tag.length + 1)] : [])),
214
+ )
215
+ return fields.length === 0 ? undefined : [...new Set(fields)]
216
+ }
217
+
218
+ /** Narrows a mapped item to the fields its tags select, matched by stored name ignoring case, and drops the field tags. */
219
+ function selectFields(
220
+ mapped: Omit<ImportItem, 'title'>,
221
+ title: string,
222
+ tags: readonly string[],
223
+ wanted: readonly string[],
224
+ warnings: string[],
225
+ ): Omit<ImportItem, 'title'> | undefined {
226
+ const selection = tagSelection(tags, wanted)
227
+ // Listing and fetching aren't atomic: an item untagged in between is skipped, never imported whole.
228
+ if (selection === undefined) {
229
+ warnings.push(`${title}: skipped, it no longer carries the tag`)
230
+ return undefined
231
+ }
232
+ const kept = tags.filter((value) => !wanted.some((tag) => value.startsWith(`${tag}/`)))
233
+ if (selection === 'all') return { ...mapped, tags: kept }
234
+ const fields: Record<string, string | Field> = {}
235
+ for (const wanted of selection) {
236
+ // Resolve the name against every mapped field, empty ones included, so an empty canonical field is never
237
+ // stood in for by a custom one that differs only in case.
238
+ const field = findField(mapped.fields, wanted)
239
+ const value = field === undefined ? undefined : mapped.fields[field]
240
+ if (field === undefined || value === undefined || value === '')
241
+ warnings.push(`${title}: no single field "${wanted}" to import`)
242
+ else fields[field] = value
243
+ }
244
+ if (Object.keys(fields).length === 0) {
245
+ warnings.push(`${title}: skipped, none of its tagged fields were found`)
246
+ return undefined
247
+ }
248
+ return { ...mapped, fields, tags: kept }
249
+ }
250
+
251
+ export const spawnOp: RunOp = async (args, input) => {
252
+ let child: Bun.Subprocess<'ignore' | Blob, 'pipe', 'pipe'>
253
+ try {
254
+ const stdin = input === undefined ? 'ignore' : new Blob([input])
255
+ child = Bun.spawn(['op', ...args], { stdin, stdout: 'pipe', stderr: 'pipe' })
256
+ } catch (error) {
257
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
258
+ throw new TypeVaultError('unavailable', '1Password CLI (op) was not found; install it or use --via sdk')
259
+ }
260
+ throw error
261
+ }
262
+ const [stdout, stderr, code] = await Promise.all([
263
+ new Response(child.stdout).text(),
264
+ new Response(child.stderr).text(),
265
+ child.exited,
266
+ ])
267
+ if (code !== 0) throw new TypeVaultError('unavailable', `op ${args[0]} ${args[1]} failed: ${stderr.trim()}`)
268
+ return stdout
269
+ }
270
+
271
+ const SdkItemSchema = z.object({
272
+ title: z.string(),
273
+ category: z.string(),
274
+ notes: z.string().default(''),
275
+ tags: z.array(z.string()).default([]),
276
+ websites: z.array(z.object({ url: z.string() })).default([]),
277
+ fields: z
278
+ .array(
279
+ z.object({
280
+ id: z.string().default(''),
281
+ title: z.string().default(''),
282
+ fieldType: z.string(),
283
+ value: z.string().default(''),
284
+ details: z
285
+ .object({ type: z.string(), content: z.object({ publicKey: z.string().optional() }).optional() })
286
+ .optional(),
287
+ }),
288
+ )
289
+ .default([]),
290
+ })
291
+
292
+ async function readSdk(account: string, filters: Filters, connect: ConnectSdk, collected: Collected): Promise<void> {
293
+ const client = await connect(account)
294
+ const vaults = (await client.vaults.list()).filter((vault) =>
295
+ matchVault(vault.id, vault.title, filters.vaults, collected.matchedVaults),
296
+ )
297
+ const { items, warnings } = collected
298
+ for (const vault of vaults) {
299
+ const listed = (
300
+ await client.items.list(vault.id, { type: 'ByState', content: { active: true, archived: false } })
301
+ ).filter((item) => tagSelection(item.tags, filters.tags) !== undefined)
302
+ if (listed.length === 0) continue
303
+ const fetched = await client.items.getAll(
304
+ vault.id,
305
+ listed.map((item) => item.id),
306
+ )
307
+ for (const response of fetched.individualResponses) {
308
+ if (response.content === undefined) {
309
+ warnings.push('skipped a 1Password item that could not be read')
310
+ continue
311
+ }
312
+ const item = parseExternal(response.content, SdkItemSchema, '1Password SDK')
313
+ const mapped = mapSdkItem(item)
314
+ if (mapped === undefined) warnings.push(UNSUPPORTED)
315
+ else {
316
+ const selected = selectFields(mapped, item.title, item.tags, filters.tags, warnings)
317
+ if (selected !== undefined) items.push({ ...selected, title: item.title, container: vault.title })
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ function mapSdkItem(item: z.infer<typeof SdkItemSchema>): Omit<ImportItem, 'title'> | undefined {
324
+ const mapped = mapSdkTemplate(item)
325
+ if (mapped === undefined) return undefined
326
+ const labeled = item.fields
327
+ .filter((field) => SDK_TEXT_TYPES.has(field.fieldType))
328
+ .map(
329
+ (field) =>
330
+ [
331
+ field.title,
332
+ {
333
+ type:
334
+ field.fieldType === 'Concealed'
335
+ ? ('secret' as const)
336
+ : field.fieldType === 'Totp'
337
+ ? ('totp' as const)
338
+ : ('text' as const),
339
+ value: field.value,
340
+ },
341
+ ] as const,
342
+ )
343
+ return { ...mapped, fields: withCustomFields(mapped.fields, labeled) }
344
+ }
345
+
346
+ function mapSdkTemplate(item: z.infer<typeof SdkItemSchema>): Omit<ImportItem, 'title'> | undefined {
347
+ const field = (match: (field: (typeof item.fields)[number]) => boolean) => item.fields.find(match)
348
+ const named = (names: readonly string[]) =>
349
+ field((value) => names.includes(value.id.toLowerCase()) || names.includes(value.title.toLowerCase()))?.value
350
+ const url = item.websites[0]?.url
351
+ switch (item.category) {
352
+ case 'Login':
353
+ case 'Password':
354
+ return {
355
+ preset: 'password',
356
+ fields: {
357
+ username: named(['username']),
358
+ password: named(['password']),
359
+ totp: field((value) => value.fieldType === 'Totp')?.value,
360
+ url,
361
+ },
362
+ ...(url === undefined ? {} : { url }),
363
+ }
364
+ case 'SecureNote':
365
+ return { preset: 'note', fields: { $default: item.notes } }
366
+ case 'ApiCredentials':
367
+ return { preset: 'api_key', fields: { $default: named(['credential', 'api key', 'api_key', 'key']) } }
368
+ case 'SshKey': {
369
+ const key = field((value) => value.fieldType === 'SshKey')
370
+ return { preset: 'ssh', fields: { private_key: key?.value, public_key: key?.details?.content?.publicKey } }
371
+ }
372
+ default:
373
+ return undefined
374
+ }
375
+ }
376
+
377
+ /** A full 1Password SDK client through the desktop app, for reads and writes. */
378
+ export async function connectDesktop(account: string): Promise<Client> {
379
+ // Loaded on demand: the SDK ships a large WebAssembly core that no other command needs.
380
+ const sdk = await import('@1password/sdk')
381
+ const { version } = z
382
+ .object({ version: z.string() })
383
+ .parse(await Bun.file(new URL('../../package.json', import.meta.url)).json())
384
+ try {
385
+ return await sdk.createClient({
386
+ auth: new sdk.DesktopAuth(account),
387
+ integrationName: 'typevault',
388
+ integrationVersion: version,
389
+ })
390
+ } catch (error) {
391
+ const message = error instanceof Error ? error.message : String(error)
392
+ throw new TypeVaultError(
393
+ 'unavailable',
394
+ `could not connect to the 1Password app (is Settings > Developer > Integrate with other apps on?): ${message}`,
395
+ )
396
+ }
397
+ }
398
+
399
+ const connectDesktopSdk: ConnectSdk = connectDesktop
@@ -2,7 +2,7 @@ import { strFromU8, unzipSync } from 'fflate'
2
2
  import { z } from 'zod'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
- import { collectEntries, parseExternal, parseJson, type ImportItem } from './shared'
5
+ import { collectEntries, parseExternal, parseJson, withCustomFields, type ImportItem } from './shared'
6
6
  import type { ImportResult } from './types'
7
7
 
8
8
  const KeySchema = z.object({
@@ -82,6 +82,27 @@ export function parse1Password(bytes: Uint8Array): ImportResult {
82
82
  }
83
83
 
84
84
  function mapItem(item: z.infer<typeof ItemSchema>): Omit<ImportItem, 'title'> | undefined {
85
+ const mapped = mapTemplate(item)
86
+ if (mapped === undefined) return undefined
87
+ const labeled = item.details.sections
88
+ .flatMap((section) => section.fields)
89
+ .map(
90
+ (field) =>
91
+ [
92
+ field.title,
93
+ field.value.concealed !== undefined
94
+ ? { type: 'secret' as const, value: field.value.concealed }
95
+ : field.value.totp !== undefined
96
+ ? { type: 'totp' as const, value: field.value.totp }
97
+ : field.value.string === undefined
98
+ ? undefined
99
+ : { type: 'text' as const, value: field.value.string },
100
+ ] as const,
101
+ )
102
+ return { ...mapped, fields: withCustomFields(mapped.fields, labeled) }
103
+ }
104
+
105
+ function mapTemplate(item: z.infer<typeof ItemSchema>): Omit<ImportItem, 'title'> | undefined {
85
106
  const sections = item.details.sections.flatMap((section) => section.fields)
86
107
  const field = (names: readonly string[]) =>
87
108
  sections.find((value) => names.includes(value.id.toLowerCase()) || names.includes(value.title.toLowerCase()))
@@ -93,7 +114,7 @@ function mapItem(item: z.infer<typeof ItemSchema>): Omit<ImportItem, 'title'> |
93
114
  case '001':
94
115
  case '005':
95
116
  return {
96
- type: 'password',
117
+ preset: 'password',
97
118
  fields: {
98
119
  username:
99
120
  item.details.loginFields.find((value) => value.designation === 'username')?.value ?? text(['username']),
@@ -104,13 +125,13 @@ function mapItem(item: z.infer<typeof ItemSchema>): Omit<ImportItem, 'title'> |
104
125
  },
105
126
  }
106
127
  case '003':
107
- return { type: 'note', fields: { text: item.details.notesPlain } }
128
+ return { preset: 'note', fields: { $default: item.details.notesPlain } }
108
129
  case '112':
109
- return { type: 'api_key', fields: { key: text(['credential', 'api key', 'api_key', 'key']) } }
130
+ return { preset: 'api_key', fields: { $default: text(['credential', 'api key', 'api_key', 'key']) } }
110
131
  case '114': {
111
132
  const key = sections.find((value) => value.value.sshKey !== undefined)?.value.sshKey
112
133
  return {
113
- type: 'ssh',
134
+ preset: 'ssh',
114
135
  fields: {
115
136
  private_key: key?.metadata?.privateKey ?? key?.privateKey ?? text(['private_key', 'private key']),
116
137
  public_key: key?.publicKey ?? key?.metadata?.publicKey ?? text(['public_key', 'public key']),
@@ -42,7 +42,7 @@ export function parseBitwarden(text: string): ImportResult {
42
42
  const url = item.login?.uris?.find((uri) => uri.uri)?.uri ?? undefined
43
43
  items.push({
44
44
  ...common,
45
- type: 'password',
45
+ preset: 'password',
46
46
  fields: {
47
47
  username: item.login?.username ?? undefined,
48
48
  password: item.login?.password ?? undefined,
@@ -54,12 +54,12 @@ export function parseBitwarden(text: string): ImportResult {
54
54
  break
55
55
  }
56
56
  case 2:
57
- items.push({ ...common, type: 'note', fields: { text: item.notes ?? undefined } })
57
+ items.push({ ...common, preset: 'note', fields: { $default: item.notes ?? undefined } })
58
58
  break
59
59
  case 5:
60
60
  items.push({
61
61
  ...common,
62
- type: 'ssh',
62
+ preset: 'ssh',
63
63
  fields: {
64
64
  private_key: item.sshKey?.privateKey ?? undefined,
65
65
  public_key: item.sshKey?.publicKey ?? undefined,
package/src/import/csv.ts CHANGED
@@ -12,7 +12,7 @@ export function parseCsv(text: string): ImportResult {
12
12
  return collectEntries(
13
13
  records.map((row) => ({
14
14
  title: row[title] ?? '',
15
- type: 'password',
15
+ preset: 'password',
16
16
  fields: { username: row['username'], password: row['password'], url: row['url'], totp: row['otpauth'] },
17
17
  ...(row['url'] === undefined ? {} : { url: row['url'] }),
18
18
  })),
@@ -11,8 +11,8 @@ export function parseDotenv(text: string): ImportResult {
11
11
  return collectEntries(
12
12
  parseDotenvVariables(text).map(({ name, value }) => ({
13
13
  title: name,
14
- type: 'api_key',
15
- fields: { key: value },
14
+ preset: 'api_key',
15
+ fields: { $default: value },
16
16
  ...(isUsableEnvName(name) ? { env: name } : {}),
17
17
  })),
18
18
  )
@@ -15,6 +15,7 @@ import { parseTypeclaw } from './typeclaw'
15
15
  import type { ImportResult, ImportSource } from './types'
16
16
 
17
17
  export type { ImportedEntry, ImportResult, ImportSource } from './types'
18
+ export { ONEPASSWORD_VIAS, read1Password, type OnePasswordOptions, type OnePasswordVia } from './1password-live'
18
19
 
19
20
  const SourceSchema = z.enum(['dotenv', 'typeclaw', '1password', 'bitwarden', 'lastpass', 'keepass', 'csv'])
20
21
  const InputSchema = z.object({ path: z.string().min(1), password: z.string().optional() }).readonly()
@@ -57,10 +57,10 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
57
57
  const url = fields['URL']
58
58
  items.push({
59
59
  title: fields['Title'] ?? '',
60
- type: login ? 'password' : 'note',
60
+ preset: login ? 'password' : 'note',
61
61
  fields: login
62
62
  ? { username: fields['UserName'], password: fields['Password'], url, totp: fields['otp'] }
63
- : { text: fields['Notes'] },
63
+ : { $default: fields['Notes'] },
64
64
  tags: parseExternal(entry.tags, z.array(z.string()).readonly(), 'KeePass tags'),
65
65
  ...(container === undefined ? {} : { container }),
66
66
  ...(url === undefined ? {} : { url }),
@@ -21,9 +21,9 @@ export function parseLastpass(text: string): ImportResult {
21
21
  {
22
22
  title: row['name'] ?? '',
23
23
  container: row['grouping'] ?? '',
24
- type: note ? ('note' as const) : ('password' as const),
24
+ preset: note ? ('note' as const) : ('password' as const),
25
25
  fields: note
26
- ? { text: extra }
26
+ ? { $default: extra }
27
27
  : { username: row['username'], password: row['password'], totp: row['totp'], url: row['url'] },
28
28
  ...(note || row['url'] === undefined ? {} : { url: row['url'] }),
29
29
  },
@@ -1,14 +1,23 @@
1
1
  import { z } from 'zod'
2
2
 
3
3
  import { TypeVaultError } from '../core/errors'
4
- import { ENTRY_TYPES, parseEntryName, slugifySegment, type EntryType } from '../core/naming'
4
+ import {
5
+ isFieldName,
6
+ parseEntryName,
7
+ slugifySegment,
8
+ PRESETS,
9
+ type Preset,
10
+ type Field,
11
+ type FieldType,
12
+ fieldStrings,
13
+ } from '../core/naming'
5
14
  import type { ImportedEntry, ImportResult } from './types'
6
15
 
7
16
  export type ImportItem = {
8
17
  readonly title: string
9
18
  readonly container?: string
10
- readonly type: EntryType
11
- readonly fields: Readonly<Record<string, string | undefined>>
19
+ readonly preset: Preset
20
+ readonly fields: Readonly<Record<string, string | Field | undefined>>
12
21
  readonly url?: string
13
22
  readonly tags?: readonly string[]
14
23
  readonly env?: string
@@ -26,17 +35,36 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
26
35
  while (used.has(name)) name = `${base}-${suffix++}`
27
36
  used.add(name)
28
37
  if (name !== base) messages.push(`name collision: "${base}" renamed to "${name}"`)
29
- const allowed: readonly string[] = ENTRY_TYPES[item.type].fields
30
- const fields = Object.fromEntries(
31
- Object.entries(item.fields).filter(
32
- (pair): pair is [string, string] => allowed.includes(pair[0]) && pair[1] !== undefined && pair[1] !== '',
33
- ),
34
- )
38
+ const fields: Record<string, Field> = {}
39
+ for (const [field, value] of Object.entries(item.fields)) {
40
+ if (
41
+ value === undefined ||
42
+ value === '' ||
43
+ (typeof value !== 'string' && fieldStrings(value).every((part) => part === ''))
44
+ )
45
+ continue
46
+ if (isFieldName(field)) {
47
+ if (typeof value === 'string') {
48
+ const types: Readonly<Record<string, FieldType>> = PRESETS[item.preset].fields
49
+ const type = types[field] ?? 'secret'
50
+ switch (type) {
51
+ case 'secret':
52
+ case 'text':
53
+ case 'totp':
54
+ fields[field] = { type, value }
55
+ break
56
+ case 'oauth':
57
+ throw new TypeVaultError('invalid', 'OAuth import requires typed fields')
58
+ default:
59
+ throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
60
+ }
61
+ } else fields[field] = value
62
+ } else messages.push(`${name}: skipped a field with an unusable name`)
63
+ }
35
64
  const url = item.url === undefined ? null : URL.parse(item.url)
36
65
  const origin = url && (url.protocol === 'http:' || url.protocol === 'https:') ? url.origin : undefined
37
66
  entries.push({
38
67
  name: parseEntryName(name),
39
- type: item.type,
40
68
  fields,
41
69
  tags: item.tags ?? [],
42
70
  ...(origin === undefined ? {} : { origin }),
@@ -46,6 +74,35 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
46
74
  return { entries, warnings: messages }
47
75
  }
48
76
 
77
+ /**
78
+ * The template fields plus every labeled field the mapper didn't place, kept under its own label. A value already
79
+ * in a template field is skipped, so an API credential's `credential` doesn't land twice.
80
+ */
81
+ export function withCustomFields(
82
+ mapped: Readonly<Record<string, string | Field | undefined>>,
83
+ labeled: readonly (readonly [label: string, value: string | Field | undefined])[],
84
+ ): Record<string, string | Field | undefined> {
85
+ const used = new Set(
86
+ Object.values(mapped).flatMap((value) =>
87
+ value === undefined ? [] : typeof value === 'string' ? [value] : fieldStrings(value),
88
+ ),
89
+ )
90
+ const custom: Record<string, string | Field> = {}
91
+ for (const [label, value] of labeled) {
92
+ const field = label.trim()
93
+ if (
94
+ field === '' ||
95
+ value === undefined ||
96
+ value === '' ||
97
+ (typeof value === 'string' ? used.has(value) : fieldStrings(value).every((part) => used.has(part)))
98
+ )
99
+ continue
100
+ if (Object.hasOwn(mapped, field) || Object.hasOwn(custom, field)) continue
101
+ custom[field] = value
102
+ }
103
+ return { ...custom, ...mapped }
104
+ }
105
+
49
106
  export function parseJson<T>(text: string, schema: z.ZodType<T>, format: string): T {
50
107
  let value: unknown
51
108
  try {
@@ -11,8 +11,8 @@ export function parseTypeclaw(text: string): ImportResult {
11
11
  .filter(({ name }) => name.startsWith(PREFIX) && name.length > PREFIX.length)
12
12
  .map(({ name, value }) => ({
13
13
  title: name.slice(PREFIX.length),
14
- type: 'password',
15
- fields: { password: value },
14
+ preset: 'api_key',
15
+ fields: { $default: value },
16
16
  ...(isUsableEnvName(name) ? { env: name } : {}),
17
17
  })),
18
18
  )
@@ -1,6 +1,6 @@
1
1
  import type { EntryPayload } from '../core/payload'
2
2
 
3
- export type ImportedEntry = Pick<EntryPayload, 'name' | 'type' | 'fields' | 'origin' | 'tags' | 'env'>
3
+ export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'tags' | 'env'>
4
4
 
5
5
  export type ImportResult = {
6
6
  readonly entries: readonly ImportedEntry[]