typevault 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/package.json +2 -2
- package/src/access/schemas.ts +4 -2
- package/src/access/scoped.ts +25 -6
- package/src/access/sealed-access.ts +8 -1
- package/src/access/types.ts +9 -1
- package/src/cli/commands/daemon.ts +5 -1
- package/src/cli/commands/entries.ts +10 -16
- package/src/cli/commands/run.ts +11 -22
- package/src/cli/context.ts +46 -1
- package/src/cli/output.ts +5 -1
- package/src/core/holder.ts +16 -3
- package/src/core/layout.ts +48 -3
- package/src/core/naming.ts +29 -24
- package/src/core/payload.ts +5 -1
- package/src/core/vault.ts +45 -5
- package/src/core/version.ts +9 -0
- package/src/daemon/agent-routes.ts +78 -3
- package/src/daemon/client.ts +11 -0
- package/src/daemon/live-access.ts +15 -0
- package/src/daemon/protocol.ts +7 -0
- package/src/daemon/spawn.ts +47 -2
- package/src/import/1password-live.ts +55 -16
- package/src/import/1password.ts +6 -4
- package/src/import/bitwarden.ts +3 -8
- package/src/import/keepass.ts +4 -5
- package/src/import/lastpass.ts +0 -1
- package/src/import/shared.ts +57 -5
- package/src/import/types.ts +1 -1
package/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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
267
|
-
|
|
277
|
+
const byName = (name: EntryName) =>
|
|
278
|
+
resolveName(
|
|
268
279
|
this.#state.tiers,
|
|
269
|
-
entries.filter((entry) => entry.payload.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 {
|
|
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
|
-
|
|
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)
|
package/src/daemon/client.ts
CHANGED
|
@@ -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
|
}
|
package/src/daemon/protocol.ts
CHANGED
|
@@ -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(),
|
package/src/daemon/spawn.ts
CHANGED
|
@@ -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 {
|
|
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,58 @@ 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
|
-
|
|
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
|
+
/**
|
|
54
|
+
* Stops this checkout's daemon, if running, and starts a fresh one. Only a machine member's daemon can come back on
|
|
55
|
+
* its own: an unlocked session's key would be gone with it, so that one is refused before anything stops.
|
|
56
|
+
*/
|
|
57
|
+
export async function restartDaemon(layout: Layout, env: Env): Promise<void> {
|
|
58
|
+
// A token with no daemon answering was left by a killed session; the new daemon clears it on start.
|
|
59
|
+
if (existsSync(layout.sessionFile) && (await isDaemonAlive(layout.agentSocket))) {
|
|
60
|
+
throw new TypeVaultError(
|
|
61
|
+
'conflict',
|
|
62
|
+
'this daemon holds an unlocked session, which a restart would end: run `typevault lock`, then `typevault unlock`',
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
if (machineKeys(env).length === 0) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
66
|
+
try {
|
|
67
|
+
await stopDaemon(layout)
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (!(error instanceof TypeVaultError && error.code === 'not_found')) throw error
|
|
70
|
+
}
|
|
71
|
+
await ensureDaemon(layout, env)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function versionMismatch(layout: Layout, running: string | null, version: string): TypeVaultError {
|
|
75
|
+
const from = running === null ? 'is from an older release' : `is version ${running}`
|
|
76
|
+
const fix = existsSync(layout.sessionFile)
|
|
77
|
+
? 'run `typevault lock`, then `typevault unlock`'
|
|
78
|
+
: 'run `typevault daemon stop`; a machine member starts the new one'
|
|
79
|
+
return new TypeVaultError('conflict', `the running typevault daemon ${from}, not ${version}: ${fix}`)
|
|
80
|
+
}
|
|
81
|
+
|
|
37
82
|
/**
|
|
38
83
|
* Starts an unlocked session daemon holding `key`, handed over stdin so it never shows up in argv or env. With
|
|
39
84
|
* `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
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
|
303
|
-
const
|
|
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
|
-
|
|
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)
|
|
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
|
}
|
package/src/import/1password.ts
CHANGED
|
@@ -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({
|
|
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
|
}
|
package/src/import/bitwarden.ts
CHANGED
|
@@ -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
|
|
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
|
package/src/import/keepass.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
64
|
+
source: `keepass:${entry.uuid.id}`,
|
|
66
65
|
...(url === undefined ? {} : { url }),
|
|
67
66
|
})
|
|
68
67
|
}
|
|
69
|
-
for (const child of group.groups) visit(child
|
|
68
|
+
for (const child of group.groups) visit(child)
|
|
70
69
|
}
|
|
71
|
-
for (const group of db.groups) visit(group
|
|
70
|
+
for (const group of db.groups) visit(group)
|
|
72
71
|
return collectEntries(items, warnings)
|
|
73
72
|
}
|
package/src/import/lastpass.ts
CHANGED