typevault 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -115
- package/package.json +14 -2
- package/src/access/env.ts +77 -17
- package/src/access/keys.ts +14 -14
- package/src/access/schemas.ts +6 -12
- package/src/access/scope.ts +14 -9
- package/src/access/scoped.ts +118 -44
- package/src/access/sealed-access.ts +50 -23
- package/src/access/sealed.ts +56 -31
- package/src/access/types.ts +27 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +28 -12
- package/src/cli/commands/admin.ts +93 -48
- package/src/cli/commands/daemon.ts +42 -17
- package/src/cli/commands/entries.ts +195 -60
- package/src/cli/commands/grant.ts +24 -22
- package/src/cli/commands/members.ts +307 -0
- package/src/cli/commands/run.ts +191 -44
- package/src/cli/context.ts +163 -15
- package/src/cli/index.ts +33 -5
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +79 -0
- package/src/core/admin.ts +144 -76
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +15 -16
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +8 -2
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +87 -0
- package/src/core/identity.ts +132 -0
- package/src/core/init.ts +73 -23
- package/src/core/json-file.ts +20 -0
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +143 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +150 -50
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +11 -6
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +102 -54
- package/src/core/txn.ts +9 -7
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +51 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +31 -11
- package/src/daemon/client.ts +24 -2
- package/src/daemon/daemon.ts +218 -33
- package/src/daemon/grants.ts +25 -7
- package/src/daemon/http.ts +11 -2
- package/src/daemon/live-access.ts +8 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +75 -51
- package/src/daemon/spawn.ts +218 -9
- package/src/export/1password.ts +157 -0
- package/src/import/1password-live.ts +399 -0
- package/src/import/1password.ts +26 -5
- package/src/import/bitwarden.ts +3 -3
- package/src/import/csv.ts +1 -1
- package/src/import/dotenv.ts +4 -3
- package/src/import/index.ts +1 -0
- package/src/import/keepass.ts +2 -2
- package/src/import/lastpass.ts +2 -2
- package/src/import/shared.ts +67 -10
- package/src/import/typeclaw.ts +2 -2
- package/src/import/types.ts +1 -1
- package/src/index.ts +58 -0
- package/src/owner.ts +156 -0
- package/src/prompt/browser.ts +48 -15
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +27 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +7 -4
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
import { TypeVaultError } from '../core/errors'
|
|
4
|
+
import { connectDesktop, type OnePasswordVia, type RunOp, spawnOp } from '../import/1password-live'
|
|
5
|
+
import { parseJson } from '../import/shared'
|
|
6
|
+
|
|
7
|
+
export type KeyItem = {
|
|
8
|
+
readonly title: string
|
|
9
|
+
readonly credential: string
|
|
10
|
+
readonly details: Readonly<Record<string, string>>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type ExportOptions = {
|
|
14
|
+
/** Unset picks whatever is reachable: the `op` CLI when installed, else the desktop SDK. */
|
|
15
|
+
readonly via?: OnePasswordVia
|
|
16
|
+
readonly account?: string
|
|
17
|
+
readonly vault: string
|
|
18
|
+
readonly replace?: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type WriterField = { readonly id: string; readonly title: string; readonly value: string; readonly concealed: boolean }
|
|
22
|
+
|
|
23
|
+
export type SdkWriter = {
|
|
24
|
+
readonly vaults: { list(): Promise<readonly { readonly id: string; readonly title: string }[]> }
|
|
25
|
+
readonly items: {
|
|
26
|
+
list(vaultId: string): Promise<readonly { readonly id: string; readonly title: string }[]>
|
|
27
|
+
create(params: { vaultId: string; title: string; tags: string[]; fields: WriterField[] }): Promise<unknown>
|
|
28
|
+
archive(vaultId: string, itemId: string): Promise<void>
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type ConnectWriter = (account: string) => Promise<SdkWriter>
|
|
33
|
+
|
|
34
|
+
export const EXPORT_TAG = 'typevault'
|
|
35
|
+
|
|
36
|
+
export const identityTitle = (name: string): string => `TypeVault identity ${name}`
|
|
37
|
+
|
|
38
|
+
/** Stores `item` in 1Password and returns the transport used. Archives replaced items only after the new one exists. */
|
|
39
|
+
export async function export1Password(
|
|
40
|
+
item: KeyItem,
|
|
41
|
+
options: ExportOptions,
|
|
42
|
+
deps: {
|
|
43
|
+
readonly runOp?: RunOp
|
|
44
|
+
readonly connect?: ConnectWriter
|
|
45
|
+
readonly hasOp?: () => boolean
|
|
46
|
+
} = {},
|
|
47
|
+
): Promise<OnePasswordVia> {
|
|
48
|
+
const via = options.via ?? ((deps.hasOp ?? (() => Bun.which('op') !== null))() ? 'op' : 'sdk')
|
|
49
|
+
if (via === 'op') await exportOp(item, options, deps.runOp ?? spawnOp)
|
|
50
|
+
else {
|
|
51
|
+
if (options.account === undefined) {
|
|
52
|
+
throw new TypeVaultError('invalid', '--account is required with --via sdk (the account name shown in 1Password)')
|
|
53
|
+
}
|
|
54
|
+
await exportSdk(item, options, await (deps.connect ?? connectWriter)(options.account))
|
|
55
|
+
}
|
|
56
|
+
return via
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const fieldsOf = (item: KeyItem): WriterField[] => [
|
|
60
|
+
{ id: 'credential', title: 'credential', value: item.credential, concealed: true },
|
|
61
|
+
...Object.entries(item.details).map(([title, value]) => ({
|
|
62
|
+
id: title.replaceAll(' ', '_'),
|
|
63
|
+
title,
|
|
64
|
+
value,
|
|
65
|
+
concealed: false,
|
|
66
|
+
})),
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
const refuseExisting = (item: KeyItem, vault: string): never => {
|
|
70
|
+
throw new TypeVaultError(
|
|
71
|
+
'conflict',
|
|
72
|
+
`1Password vault "${vault}" already has "${item.title}"; pass --replace to archive it and store the new key`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const OpAccountsSchema = z.array(z.object({}).loose())
|
|
77
|
+
const OpItemsSchema = z.array(z.object({ id: z.string(), title: z.string() }))
|
|
78
|
+
const OpVaultsSchema = z.array(z.object({ id: z.string(), name: z.string() }))
|
|
79
|
+
|
|
80
|
+
async function exportOp(item: KeyItem, options: ExportOptions, runOp: RunOp): Promise<void> {
|
|
81
|
+
if (options.account === undefined) {
|
|
82
|
+
const accounts = parseJson(await runOp(['account', 'list', '--format', 'json']), OpAccountsSchema, 'op')
|
|
83
|
+
// With several accounts, op's default is easy to forget: a key must never land in the wrong one.
|
|
84
|
+
if (accounts.length > 1) {
|
|
85
|
+
throw new TypeVaultError('invalid', 'several 1Password accounts are signed in; pass --account')
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const account = options.account === undefined ? [] : ['--account', options.account]
|
|
89
|
+
const vaults = parseJson(await runOp(['vault', 'list', '--format', 'json', ...account]), OpVaultsSchema, 'op')
|
|
90
|
+
const vault = resolveVault(
|
|
91
|
+
vaults.map(({ id, name }) => ({ id, title: name })),
|
|
92
|
+
options.vault,
|
|
93
|
+
)
|
|
94
|
+
const scope = ['--vault', vault.id, ...account]
|
|
95
|
+
const listed = parseJson(await runOp(['item', 'list', '--format', 'json', ...scope]), OpItemsSchema, 'op')
|
|
96
|
+
const existing = listed.filter((entry) => entry.title === item.title)
|
|
97
|
+
if (existing.length > 0 && options.replace !== true) refuseExisting(item, options.vault)
|
|
98
|
+
const template = {
|
|
99
|
+
title: item.title,
|
|
100
|
+
category: 'API_CREDENTIAL',
|
|
101
|
+
tags: [EXPORT_TAG],
|
|
102
|
+
fields: fieldsOf(item).map((field) => ({
|
|
103
|
+
id: field.id,
|
|
104
|
+
label: field.title,
|
|
105
|
+
type: field.concealed ? 'CONCEALED' : 'STRING',
|
|
106
|
+
value: field.value,
|
|
107
|
+
})),
|
|
108
|
+
}
|
|
109
|
+
// The template goes through stdin: the key never appears in argv, where other processes could read it.
|
|
110
|
+
await runOp(['item', 'create', '-', '--format', 'json', ...scope], JSON.stringify(template))
|
|
111
|
+
for (const entry of existing) await runOp(['item', 'delete', entry.id, '--archive', ...scope])
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function exportSdk(item: KeyItem, options: ExportOptions, client: SdkWriter): Promise<void> {
|
|
115
|
+
const vault = resolveVault(await client.vaults.list(), options.vault)
|
|
116
|
+
const existing = (await client.items.list(vault.id)).filter((entry) => entry.title === item.title)
|
|
117
|
+
if (existing.length > 0 && options.replace !== true) refuseExisting(item, options.vault)
|
|
118
|
+
await client.items.create({ vaultId: vault.id, title: item.title, tags: [EXPORT_TAG], fields: fieldsOf(item) })
|
|
119
|
+
for (const entry of existing) await client.items.archive(vault.id, entry.id)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function resolveVault<V extends { readonly id: string; readonly title: string }>(
|
|
123
|
+
vaults: readonly V[],
|
|
124
|
+
wanted: string,
|
|
125
|
+
): V {
|
|
126
|
+
const byId = vaults.find((vault) => vault.id === wanted)
|
|
127
|
+
if (byId !== undefined) return byId
|
|
128
|
+
const byTitle = vaults.filter((vault) => vault.title === wanted)
|
|
129
|
+
const [only] = byTitle
|
|
130
|
+
if (only === undefined) throw new TypeVaultError('not_found', `1Password vault "${wanted}" was not found`)
|
|
131
|
+
// A key must never land in a vault picked by list order, which may be one shared with other people.
|
|
132
|
+
if (byTitle.length > 1) {
|
|
133
|
+
throw new TypeVaultError('conflict', `several 1Password vaults are named "${wanted}"; pass the vault id instead`)
|
|
134
|
+
}
|
|
135
|
+
return only
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const connectWriter: ConnectWriter = async (account) => {
|
|
139
|
+
const sdk = await import('@1password/sdk')
|
|
140
|
+
const client = await connectDesktop(account)
|
|
141
|
+
return {
|
|
142
|
+
vaults: client.vaults,
|
|
143
|
+
items: {
|
|
144
|
+
list: (vaultId) => client.items.list(vaultId),
|
|
145
|
+
create: (params) =>
|
|
146
|
+
client.items.create({
|
|
147
|
+
...params,
|
|
148
|
+
category: sdk.ItemCategory.ApiCredentials,
|
|
149
|
+
fields: params.fields.map(({ concealed, ...field }) => ({
|
|
150
|
+
...field,
|
|
151
|
+
fieldType: concealed ? sdk.ItemFieldType.Concealed : sdk.ItemFieldType.Text,
|
|
152
|
+
})),
|
|
153
|
+
}),
|
|
154
|
+
archive: (vaultId, itemId) => client.items.archive(vaultId, itemId),
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -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
|
package/src/import/1password.ts
CHANGED
|
@@ -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
|
-
|
|
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 {
|
|
128
|
+
return { preset: 'note', fields: { $default: item.details.notesPlain } }
|
|
108
129
|
case '112':
|
|
109
|
-
return {
|
|
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
|
-
|
|
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']),
|
package/src/import/bitwarden.ts
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
})),
|
package/src/import/dotenv.ts
CHANGED
|
@@ -8,11 +8,12 @@ import type { ImportResult } from './types'
|
|
|
8
8
|
const VariableSchema = z.object({ name: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), value: z.string() }).readonly()
|
|
9
9
|
|
|
10
10
|
export function parseDotenv(text: string): ImportResult {
|
|
11
|
+
const variables = new Map(parseDotenvVariables(text).map((variable) => [variable.name, variable]))
|
|
11
12
|
return collectEntries(
|
|
12
|
-
|
|
13
|
+
[...variables.values()].map(({ name, value }) => ({
|
|
13
14
|
title: name,
|
|
14
|
-
|
|
15
|
-
fields: {
|
|
15
|
+
preset: 'api_key',
|
|
16
|
+
fields: { $default: value },
|
|
16
17
|
...(isUsableEnvName(name) ? { env: name } : {}),
|
|
17
18
|
})),
|
|
18
19
|
)
|
package/src/import/index.ts
CHANGED
|
@@ -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()
|