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.
- 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 +7 -7
- package/src/access/scoped.ts +100 -44
- package/src/access/sealed-access.ts +45 -23
- package/src/access/sealed.ts +33 -21
- package/src/access/types.ts +25 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +14 -9
- package/src/cli/commands/admin.ts +87 -47
- package/src/cli/commands/daemon.ts +33 -15
- package/src/cli/commands/entries.ts +166 -55
- package/src/cli/commands/grant.ts +12 -20
- package/src/cli/commands/members.ts +281 -0
- package/src/cli/commands/run.ts +61 -24
- package/src/cli/context.ts +155 -15
- package/src/cli/index.ts +27 -4
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +65 -0
- package/src/core/admin.ts +125 -74
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +9 -9
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +6 -0
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +84 -0
- package/src/core/identity.ts +130 -0
- package/src/core/init.ts +73 -23
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +145 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +146 -49
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +8 -4
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +88 -48
- package/src/core/txn.ts +5 -4
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +39 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +29 -11
- package/src/daemon/client.ts +15 -0
- package/src/daemon/daemon.ts +210 -32
- package/src/daemon/grants.ts +21 -4
- package/src/daemon/http.ts +3 -0
- package/src/daemon/live-access.ts +4 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +17 -22
- package/src/daemon/spawn.ts +188 -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 +2 -2
- 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/page.ts +19 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +3 -3
|
@@ -3,17 +3,25 @@ import { z } from 'zod'
|
|
|
3
3
|
|
|
4
4
|
import { TypeVaultError } from '../../core/errors'
|
|
5
5
|
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
ENTRY_NAME_SYNTAX,
|
|
7
|
+
ENTRY_REF_SYNTAX,
|
|
8
|
+
defaultField,
|
|
9
|
+
defaultFieldOf,
|
|
10
|
+
fieldValue,
|
|
11
|
+
resolveField,
|
|
12
|
+
type Field,
|
|
13
|
+
type FieldType,
|
|
14
|
+
PRESETS,
|
|
15
|
+
isFieldName,
|
|
16
|
+
parsePreset,
|
|
9
17
|
parseEntryName,
|
|
10
18
|
parseEntryRef,
|
|
11
|
-
parseEntryType,
|
|
12
|
-
primaryField,
|
|
13
19
|
} from '../../core/naming'
|
|
20
|
+
import { FieldSchema } from '../../core/payload'
|
|
14
21
|
import { parseTotpSeed, totpCode, totpRemainingSeconds } from '../../otp/totp'
|
|
15
22
|
import { accessOf, resolveAccess } from '../context'
|
|
16
23
|
import { csv, note, print, readStdin, repeated, table } from '../output'
|
|
24
|
+
import { openBrowser, promptFields } from '../web-prompt'
|
|
17
25
|
|
|
18
26
|
export const ls = defineCommand({
|
|
19
27
|
meta: { name: 'ls', description: 'List the entries your grant reaches' },
|
|
@@ -23,71 +31,108 @@ export const ls = defineCommand({
|
|
|
23
31
|
if (args.json) return print(JSON.stringify(entries, null, 2))
|
|
24
32
|
const rows = entries.map((e) => [
|
|
25
33
|
e.name,
|
|
26
|
-
e.
|
|
27
|
-
e.group,
|
|
34
|
+
e.tier,
|
|
28
35
|
`r${e.rev}`,
|
|
29
36
|
e.rotated.slice(0, 10),
|
|
30
37
|
e.needsRotation ? 'needs-rotation' : '',
|
|
31
38
|
])
|
|
32
39
|
print(
|
|
33
|
-
table([
|
|
34
|
-
['NAME', 'TYPE', 'GROUP', 'REV', 'ROTATED', ''],
|
|
35
|
-
...rows.sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? '')),
|
|
36
|
-
]),
|
|
40
|
+
table([['NAME', 'TIER', 'REV', 'ROTATED', ''], ...rows.sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? ''))]),
|
|
37
41
|
)
|
|
38
42
|
},
|
|
39
43
|
})
|
|
40
44
|
|
|
41
45
|
export const get = defineCommand({
|
|
42
|
-
meta: {
|
|
46
|
+
meta: {
|
|
47
|
+
name: 'get',
|
|
48
|
+
description: 'Print a field. Secret fields need --reveal (they land in your transcript: prefer `typevault run`)',
|
|
49
|
+
},
|
|
43
50
|
args: {
|
|
44
|
-
ref: { type: 'positional', description:
|
|
51
|
+
ref: { type: 'positional', description: ENTRY_REF_SYNTAX, required: true },
|
|
45
52
|
reason: { type: 'string', description: 'Why you need it (audited)' },
|
|
46
|
-
json: { type: 'boolean', description: 'Print every field as JSON' },
|
|
53
|
+
json: { type: 'boolean', description: 'Print every field as JSON (secret fields redacted unless --reveal)' },
|
|
54
|
+
reveal: { type: 'boolean', description: 'Print secret fields in plaintext' },
|
|
47
55
|
},
|
|
48
56
|
async run({ args }) {
|
|
49
57
|
const ref = parseEntryRef(args.ref)
|
|
50
58
|
const value = await (await accessOf(process.env)).get(ref.name, args.reason)
|
|
51
|
-
if (args.json)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
59
|
+
if (args.json) {
|
|
60
|
+
const fields = Object.fromEntries(
|
|
61
|
+
Object.entries(value.fields).map(([field, secret]) => [
|
|
62
|
+
field,
|
|
63
|
+
{ ...secret, value: args.reveal || secret.type === 'text' ? secret.value : '<redacted>' },
|
|
64
|
+
]),
|
|
65
|
+
)
|
|
66
|
+
if (!args.reveal) note('secret fields are redacted; pass --reveal to print them')
|
|
67
|
+
return print(JSON.stringify(fields, null, 2))
|
|
68
|
+
}
|
|
69
|
+
const wanted = ref.field ?? defaultField(value.fields, value.name)
|
|
70
|
+
const secret = resolveField(value.fields, wanted)
|
|
71
|
+
if (secret === undefined) {
|
|
72
|
+
throw new TypeVaultError('not_found', `${value.name} has no field "${wanted}"`)
|
|
73
|
+
}
|
|
74
|
+
if (!args.reveal && secret.type !== 'text') {
|
|
75
|
+
throw new TypeVaultError(
|
|
76
|
+
'denied',
|
|
77
|
+
`${value.name}#${wanted} is secret. Use \`typevault run\` to pass it to a command, ` +
|
|
78
|
+
'or --reveal to print it (it lands in logs and transcripts)',
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
print(fieldValue(secret))
|
|
56
82
|
},
|
|
57
83
|
})
|
|
58
84
|
|
|
59
|
-
|
|
60
|
-
|
|
85
|
+
/** `--field` values land in `ps` and shell history, so a field the preset or entry types as anything but text is refused. */
|
|
86
|
+
function parseFields(
|
|
87
|
+
pairs: readonly string[],
|
|
88
|
+
known: Readonly<Record<string, FieldType | undefined>>,
|
|
89
|
+
): Record<string, Field> {
|
|
61
90
|
return Object.fromEntries(
|
|
62
91
|
pairs.map((pair) => {
|
|
63
92
|
const eq = pair.indexOf('=')
|
|
64
93
|
const field = eq === -1 ? '' : pair.slice(0, eq)
|
|
65
|
-
if (!
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
throw new TypeVaultError('invalid', `pass ${field} on stdin (--stdin or --stdin-json), not as an argument`)
|
|
94
|
+
if (!isFieldName(field)) throw new TypeVaultError('invalid', `--field expects name=value, got "${field}"`)
|
|
95
|
+
if ((known[field] ?? 'text') !== 'text') {
|
|
96
|
+
throw new TypeVaultError('invalid', `pass "${field}" on stdin (--stdin or --stdin-json), not as an argument`)
|
|
69
97
|
}
|
|
70
|
-
return [field, pair.slice(eq + 1)]
|
|
98
|
+
return [field, { type: 'text', value: pair.slice(eq + 1) }]
|
|
71
99
|
}),
|
|
72
100
|
)
|
|
73
101
|
}
|
|
74
102
|
|
|
75
|
-
function parseFieldsJson(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
103
|
+
function parseFieldsJson(text: string): Record<string, string | Field> {
|
|
104
|
+
let value: unknown
|
|
105
|
+
try {
|
|
106
|
+
value = JSON.parse(text)
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof SyntaxError) throw new TypeVaultError('invalid', 'invalid fields JSON')
|
|
109
|
+
throw error
|
|
110
|
+
}
|
|
111
|
+
const fields = z.record(z.string().refine(isFieldName), z.union([z.string(), FieldSchema])).safeParse(value)
|
|
112
|
+
if (!fields.success) throw new TypeVaultError('invalid', 'invalid fields JSON')
|
|
113
|
+
return fields.data
|
|
81
114
|
}
|
|
82
115
|
|
|
83
116
|
export const set = defineCommand({
|
|
84
|
-
meta: {
|
|
117
|
+
meta: {
|
|
118
|
+
name: 'set',
|
|
119
|
+
description:
|
|
120
|
+
'Create or update an entry. Pipe the secret on stdin with --stdin, or type it in a browser with --web.',
|
|
121
|
+
},
|
|
85
122
|
args: {
|
|
86
|
-
name: { type: 'positional', description:
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
123
|
+
name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
|
|
124
|
+
preset: { type: 'string', description: 'password | api_key | oauth | ssh | totp | note' },
|
|
125
|
+
'stdin-json': { type: 'boolean', description: 'Read a JSON object of strings or typed fields from stdin' },
|
|
126
|
+
tier: {
|
|
127
|
+
type: 'string',
|
|
128
|
+
description: "Tier (defaults to $TYPEVAULT_TIER, else your grant's tier, else the only tier you reach)",
|
|
129
|
+
},
|
|
130
|
+
field: { type: 'string', description: 'k=v, repeatable (writes text fields; use stdin for secrets)' },
|
|
90
131
|
stdin: { type: 'boolean', description: 'Read the main secret field from stdin' },
|
|
132
|
+
web: {
|
|
133
|
+
type: 'boolean',
|
|
134
|
+
description: 'Type the fields in a local one-time browser page (default for a new entry from a terminal)',
|
|
135
|
+
},
|
|
91
136
|
env: { type: 'string', description: 'Env var name for the main field in `run`' },
|
|
92
137
|
origin: { type: 'string', description: 'Site this login is for (a hint, never a block)' },
|
|
93
138
|
tag: { type: 'string', description: 'Comma-separated tags' },
|
|
@@ -98,47 +143,102 @@ export const set = defineCommand({
|
|
|
98
143
|
const access = await accessOf(process.env)
|
|
99
144
|
const name = parseEntryName(args.name)
|
|
100
145
|
const existing = (await access.list()).find((entry) => entry.name === name)
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
const
|
|
146
|
+
const preset = args.preset === undefined ? undefined : PRESETS[parsePreset(args.preset)]
|
|
147
|
+
// --replace never reads the old fields: the read would refresh OAuth credentials that are being replaced.
|
|
148
|
+
const previous =
|
|
149
|
+
existing === undefined || args.replace ? {} : (await access.get(name, 'merge fields for set')).fields
|
|
150
|
+
const suggested: Readonly<Record<string, FieldType>> = preset?.fields ?? {}
|
|
151
|
+
const known = Object.fromEntries(Object.entries(previous).map(([field, value]) => [field, value.type]))
|
|
152
|
+
const given = parseFields(repeated(rawArgs, '--field'), { ...known, ...suggested })
|
|
153
|
+
const tier = args.tier ?? existing?.tier ?? process.env['TYPEVAULT_TIER']
|
|
154
|
+
const target = preset?.input ?? defaultFieldOf(previous) ?? '$default'
|
|
104
155
|
const fromStdin = args['stdin-json']
|
|
105
|
-
? parseFieldsJson(
|
|
156
|
+
? parseFieldsJson(await readStdin())
|
|
106
157
|
: args.stdin
|
|
107
|
-
? { [
|
|
158
|
+
? { [target]: await readStdin() }
|
|
108
159
|
: {}
|
|
109
|
-
const
|
|
110
|
-
const
|
|
160
|
+
const typed: Record<string, Field> = {}
|
|
161
|
+
for (const [field, value] of Object.entries(fromStdin)) {
|
|
162
|
+
if (typeof value !== 'string') {
|
|
163
|
+
typed[field] = value
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
const type = suggested[field] ?? previous[field]?.type ?? 'secret'
|
|
167
|
+
switch (type) {
|
|
168
|
+
case 'oauth': {
|
|
169
|
+
if (!args.stdin || args['stdin-json'])
|
|
170
|
+
throw new TypeVaultError('invalid', 'OAuth values need --stdin-json with a typed oauth field object')
|
|
171
|
+
try {
|
|
172
|
+
typed[field] = FieldSchema.parse({ type, value: JSON.parse(value) })
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (error instanceof SyntaxError || error instanceof z.ZodError)
|
|
175
|
+
throw new TypeVaultError('invalid', 'OAuth stdin needs a JSON object with an access_token')
|
|
176
|
+
throw error
|
|
177
|
+
}
|
|
178
|
+
break
|
|
179
|
+
}
|
|
180
|
+
case 'secret':
|
|
181
|
+
case 'text':
|
|
182
|
+
case 'totp':
|
|
183
|
+
typed[field] = { type, value }
|
|
184
|
+
break
|
|
185
|
+
default:
|
|
186
|
+
throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const web = args.web ?? (existing === undefined && !args.stdin && !args['stdin-json'] && process.stdin.isTTY)
|
|
190
|
+
const fromWeb = web
|
|
191
|
+
? await promptFields(
|
|
192
|
+
{ name, preset: args.preset === undefined ? undefined : parsePreset(args.preset), tier },
|
|
193
|
+
showPrompt,
|
|
194
|
+
)
|
|
195
|
+
: {}
|
|
196
|
+
const fields = { ...given, ...typed, ...fromWeb }
|
|
197
|
+
const merged = { ...(args.replace ? {} : previous), ...fields }
|
|
198
|
+
if (args.env !== undefined && defaultFieldOf(merged) === undefined) {
|
|
199
|
+
throw new TypeVaultError(
|
|
200
|
+
'invalid',
|
|
201
|
+
'--env names the default field, but this entry has several fields and no $default',
|
|
202
|
+
)
|
|
203
|
+
}
|
|
111
204
|
const ifRev = args['if-rev'] === undefined ? undefined : z.coerce.number().int().parse(args['if-rev'])
|
|
112
205
|
const tags = csv(args.tag)
|
|
113
206
|
const stored = await access.set({
|
|
114
207
|
name,
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
group: args.group ?? existing?.group,
|
|
208
|
+
fields: merged,
|
|
209
|
+
tier,
|
|
118
210
|
env: args.env,
|
|
119
211
|
origin: args.origin,
|
|
120
212
|
...(tags.length === 0 ? {} : { tags }),
|
|
121
213
|
ifRev,
|
|
122
214
|
})
|
|
123
|
-
note(`stored ${stored.name} in ${stored.
|
|
215
|
+
note(`stored ${stored.name} in ${stored.tier} (r${stored.rev})`)
|
|
124
216
|
},
|
|
125
217
|
})
|
|
126
218
|
|
|
219
|
+
function showPrompt(url: string, code: string): void {
|
|
220
|
+
note(`Enter the secret at ${url}\nMatch code: ${code} (the page shows the same code)`)
|
|
221
|
+
if (!openBrowser(url)) note('could not open a browser; open the link yourself')
|
|
222
|
+
}
|
|
223
|
+
|
|
127
224
|
export const rm = defineCommand({
|
|
128
225
|
meta: { name: 'rm', description: 'Remove an entry' },
|
|
129
226
|
args: {
|
|
130
|
-
name: { type: 'positional', required: true },
|
|
131
|
-
|
|
227
|
+
name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
|
|
228
|
+
tier: { type: 'string', description: 'Remove the copy in this tier (settles a name held by unrelated tiers)' },
|
|
132
229
|
},
|
|
133
230
|
async run({ args }) {
|
|
134
|
-
await (await accessOf(process.env)).remove(parseEntryName(args.name), args.
|
|
231
|
+
await (await accessOf(process.env)).remove(parseEntryName(args.name), args.tier)
|
|
135
232
|
note(`removed ${args.name}. Git history still holds its old ciphertext: rotate the secret if it mattered.`)
|
|
136
233
|
},
|
|
137
234
|
})
|
|
138
235
|
|
|
139
236
|
export const mv = defineCommand({
|
|
140
237
|
meta: { name: 'mv', description: 'Rename an entry' },
|
|
141
|
-
args: {
|
|
238
|
+
args: {
|
|
239
|
+
from: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
|
|
240
|
+
to: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
|
|
241
|
+
},
|
|
142
242
|
async run({ args }) {
|
|
143
243
|
await (await accessOf(process.env)).move(parseEntryName(args.from), parseEntryName(args.to))
|
|
144
244
|
},
|
|
@@ -146,10 +246,21 @@ export const mv = defineCommand({
|
|
|
146
246
|
|
|
147
247
|
export const otp = defineCommand({
|
|
148
248
|
meta: { name: 'otp', description: 'Print the current TOTP code' },
|
|
149
|
-
args: { name: { type: 'positional', required: true }, reason: { type: 'string' } },
|
|
249
|
+
args: { name: { type: 'positional', description: ENTRY_REF_SYNTAX, required: true }, reason: { type: 'string' } },
|
|
150
250
|
async run({ args }) {
|
|
151
|
-
const
|
|
152
|
-
const
|
|
251
|
+
const ref = parseEntryRef(args.name)
|
|
252
|
+
const value = await (await accessOf(process.env)).get(ref.name, args.reason)
|
|
253
|
+
const fallback = defaultFieldOf(value.fields)
|
|
254
|
+
const totps = Object.values(value.fields).filter((candidate) => candidate.type === 'totp')
|
|
255
|
+
const field =
|
|
256
|
+
ref.field !== undefined
|
|
257
|
+
? resolveField(value.fields, ref.field)
|
|
258
|
+
: fallback !== undefined && value.fields[fallback]?.type === 'totp'
|
|
259
|
+
? value.fields[fallback]
|
|
260
|
+
: totps.length === 1
|
|
261
|
+
? totps[0]
|
|
262
|
+
: undefined
|
|
263
|
+
const seed = field?.type === 'totp' ? field.value : undefined
|
|
153
264
|
if (seed === undefined || seed === '') throw new TypeVaultError('not_found', `${value.name} has no TOTP seed`)
|
|
154
265
|
const params = parseTotpSeed(seed)
|
|
155
266
|
const now = new Date()
|
|
@@ -3,24 +3,16 @@ import { watch } from 'node:fs'
|
|
|
3
3
|
import { defineCommand } from 'citty'
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { machineKeys } from '../../access/keys'
|
|
7
7
|
import { parseTtl } from '../../access/scope'
|
|
8
8
|
import { issueSealedGrant } from '../../access/sealed'
|
|
9
|
+
import { GrantInfoSchema, IssuedSchema } from '../../admin'
|
|
9
10
|
import { readAudit, verifyAudit } from '../../audit/log'
|
|
10
11
|
import { TypeVaultError } from '../../core/errors'
|
|
11
12
|
import { adminCall, layoutFrom, openDirect } from '../context'
|
|
12
13
|
import { csv, print, table } from '../output'
|
|
13
14
|
|
|
14
|
-
const
|
|
15
|
-
const GrantList = z.array(
|
|
16
|
-
z.object({
|
|
17
|
-
id: z.string(),
|
|
18
|
-
label: z.string(),
|
|
19
|
-
groups: z.array(z.string()),
|
|
20
|
-
only: z.array(z.string()),
|
|
21
|
-
exp: z.string(),
|
|
22
|
-
}),
|
|
23
|
-
)
|
|
15
|
+
const GrantList = z.array(GrantInfoSchema)
|
|
24
16
|
|
|
25
17
|
export const grant = defineCommand({
|
|
26
18
|
meta: {
|
|
@@ -30,7 +22,7 @@ export const grant = defineCommand({
|
|
|
30
22
|
args: {
|
|
31
23
|
action: { type: 'positional', required: false, description: 'ls | revoke' },
|
|
32
24
|
id: { type: 'positional', required: false },
|
|
33
|
-
|
|
25
|
+
tier: { type: 'string', description: 'Comma-separated tiers' },
|
|
34
26
|
only: { type: 'string', description: 'Comma-separated names or globs' },
|
|
35
27
|
ttl: { type: 'string', default: '1h' },
|
|
36
28
|
label: { type: 'string', description: 'Who this is for, e.g. session:abc or ci:deploy' },
|
|
@@ -43,8 +35,8 @@ export const grant = defineCommand({
|
|
|
43
35
|
const grants = await adminCall(env, '/v1/grants', {}, GrantList)
|
|
44
36
|
return print(
|
|
45
37
|
table([
|
|
46
|
-
['ID', 'LABEL', '
|
|
47
|
-
...grants.map((g) => [g.id, g.label, g.
|
|
38
|
+
['ID', 'LABEL', 'TIERS', 'ONLY', 'EXPIRES'],
|
|
39
|
+
...grants.map((g) => [g.id, g.label, g.tiers.join(','), g.only.join(','), g.exp]),
|
|
48
40
|
]),
|
|
49
41
|
)
|
|
50
42
|
}
|
|
@@ -62,15 +54,15 @@ export const grant = defineCommand({
|
|
|
62
54
|
default:
|
|
63
55
|
throw new TypeVaultError('invalid', `unknown grant action "${args.action}"`)
|
|
64
56
|
}
|
|
65
|
-
const
|
|
66
|
-
if (
|
|
67
|
-
const request = {
|
|
68
|
-
//
|
|
69
|
-
if (args.sealed &&
|
|
57
|
+
const tiers = csv(args.tier)
|
|
58
|
+
if (tiers.length === 0) throw new TypeVaultError('invalid', 'grant needs --tier')
|
|
59
|
+
const request = { tiers, only: csv(args.only), ttl: args.ttl, label: args.label ?? 'unlabeled' }
|
|
60
|
+
// An issuer holding a key (CI) seals locally; everything else asks the daemon within its ceiling.
|
|
61
|
+
if (args.sealed && machineKeys(env).length > 0) {
|
|
70
62
|
const vault = await openDirect(env)
|
|
71
63
|
return print(await issueSealedGrant(vault, { ...request, ttlMs: parseTtl(args.ttl) }))
|
|
72
64
|
}
|
|
73
|
-
print((await adminCall(env, '/v1/grant', { ...request, sealed: args.sealed === true },
|
|
65
|
+
print((await adminCall(env, '/v1/grant', { ...request, sealed: args.sealed === true }, IssuedSchema)).token)
|
|
74
66
|
},
|
|
75
67
|
})
|
|
76
68
|
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { userInfo } from 'node:os'
|
|
3
|
+
|
|
4
|
+
import { defineCommand } from 'citty'
|
|
5
|
+
|
|
6
|
+
import { parseTtl } from '../../access/scope'
|
|
7
|
+
import { publicKeyOf } from '../../core/crypto'
|
|
8
|
+
import { TypeVaultError } from '../../core/errors'
|
|
9
|
+
import { atomicWrite } from '../../core/fsx'
|
|
10
|
+
import {
|
|
11
|
+
createIdentity,
|
|
12
|
+
decodeMemberPublic,
|
|
13
|
+
encodeMemberPublic,
|
|
14
|
+
type Identity,
|
|
15
|
+
memberPublicOfIdentity,
|
|
16
|
+
openMemberKey,
|
|
17
|
+
readIdentity,
|
|
18
|
+
sealedCopyPath,
|
|
19
|
+
sealMemberKey,
|
|
20
|
+
writeIdentity,
|
|
21
|
+
} from '../../core/identity'
|
|
22
|
+
import { vaultIdOf } from '../../core/layout'
|
|
23
|
+
import { Vault } from '../../core/vault'
|
|
24
|
+
import { stopDaemon } from '../../daemon/spawn'
|
|
25
|
+
import { export1Password, identityTitle } from '../../export/1password'
|
|
26
|
+
import { ONEPASSWORD_VIAS } from '../../import/1password-live'
|
|
27
|
+
import {
|
|
28
|
+
DEFAULT_SESSION_MS,
|
|
29
|
+
findLayout,
|
|
30
|
+
layoutFrom,
|
|
31
|
+
openAdmin,
|
|
32
|
+
openPublic,
|
|
33
|
+
unlockSession,
|
|
34
|
+
worktreeSessions,
|
|
35
|
+
type Env,
|
|
36
|
+
} from '../context'
|
|
37
|
+
import { csv, note, print, table } from '../output'
|
|
38
|
+
import { newPassword, passwords } from '../password'
|
|
39
|
+
|
|
40
|
+
export const identityArgs = {
|
|
41
|
+
name: { type: 'string', description: 'Your member name, the first time (default: your OS user name)' },
|
|
42
|
+
machine: { type: 'boolean', description: 'A machine identity (CI, an agent host): no password, key kept here' },
|
|
43
|
+
} as const
|
|
44
|
+
|
|
45
|
+
type IdentityArgs = {
|
|
46
|
+
readonly name?: string | undefined
|
|
47
|
+
readonly machine?: boolean | undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** This device's identity, created on first use. A new human identity prints its Secret Key once. */
|
|
51
|
+
export async function ensureIdentity(env: Env, args: IdentityArgs): Promise<Identity> {
|
|
52
|
+
const existing = readIdentity(env)
|
|
53
|
+
if (existing !== undefined) {
|
|
54
|
+
if (args.name !== undefined && args.name !== existing.name) {
|
|
55
|
+
throw new TypeVaultError('conflict', `this device is already "${existing.name}"`)
|
|
56
|
+
}
|
|
57
|
+
return existing
|
|
58
|
+
}
|
|
59
|
+
const kind = args.machine === true ? 'machine' : 'human'
|
|
60
|
+
const name = args.name ?? defaultName()
|
|
61
|
+
const password = kind === 'human' ? await newPassword(passwords()) : undefined
|
|
62
|
+
const { identity } = await createIdentity(name, kind, password)
|
|
63
|
+
writeIdentity(env, identity)
|
|
64
|
+
if (identity.kind === 'human') {
|
|
65
|
+
note(`created identity "${name}". Your Secret Key:\n\n ${identity.secretKey}\n`)
|
|
66
|
+
note('Save it with your password (a password manager, or on paper): on a new device both are needed to')
|
|
67
|
+
note('get back in (`typevault identity restore`). It stays on this device; never commit it.')
|
|
68
|
+
} else note(`created machine identity "${name}"`)
|
|
69
|
+
return identity
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const defaultName = (): string =>
|
|
73
|
+
userInfo()
|
|
74
|
+
.username.toLowerCase()
|
|
75
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
76
|
+
.replace(/^-+|-+$/g, '') || 'me'
|
|
77
|
+
|
|
78
|
+
export const joinCommand = defineCommand({
|
|
79
|
+
meta: { name: 'join', description: 'Ask to join this vault: prints the line an owner runs to add you' },
|
|
80
|
+
args: identityArgs,
|
|
81
|
+
async run({ args }) {
|
|
82
|
+
const env = process.env
|
|
83
|
+
const layout = layoutFrom(env)
|
|
84
|
+
const identity = await ensureIdentity(env, args)
|
|
85
|
+
const vault = await Vault.open(layout, [], env)
|
|
86
|
+
if (vault.state.members[identity.name] !== undefined) return print(`"${identity.name}" is already a member`)
|
|
87
|
+
if (identity.kind === 'human') {
|
|
88
|
+
const copy = sealedCopyPath(layout, identity.name)
|
|
89
|
+
atomicWrite(copy, identity.sealedKey)
|
|
90
|
+
note(`wrote ${copy} (sealed by your password); commit it`)
|
|
91
|
+
}
|
|
92
|
+
note('ask an owner to run:')
|
|
93
|
+
print(
|
|
94
|
+
`typevault member add ${identity.name} ${encodeMemberPublic(memberPublicOfIdentity(identity))} --tier <tiers>`,
|
|
95
|
+
)
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
export const member = defineCommand({
|
|
100
|
+
meta: { name: 'member', description: 'Who can open this vault: people and machines (owner)' },
|
|
101
|
+
subCommands: {
|
|
102
|
+
ls: defineCommand({
|
|
103
|
+
meta: { name: 'ls' },
|
|
104
|
+
async run() {
|
|
105
|
+
const env = process.env
|
|
106
|
+
const { members } = (await openPublic(env)).state
|
|
107
|
+
print(
|
|
108
|
+
table([
|
|
109
|
+
['MEMBER', 'KIND', 'OWNER', 'TIERS'],
|
|
110
|
+
...Object.entries(members).map(([name, m]) => [name, m.kind, m.owner ? 'yes' : '', m.tiers.join(', ')]),
|
|
111
|
+
]),
|
|
112
|
+
)
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
add: defineCommand({
|
|
116
|
+
meta: { name: 'add', description: 'Add a member from the line `typevault join` printed; rotates their tiers' },
|
|
117
|
+
args: {
|
|
118
|
+
name: { type: 'positional', required: true },
|
|
119
|
+
publicKey: { type: 'positional', required: true, description: 'tvp1:... from `typevault join`' },
|
|
120
|
+
tier: { type: 'string', description: 'Comma-separated tiers whose keys they get' },
|
|
121
|
+
owner: { type: 'boolean', description: 'Also an owner: manages tiers, members and grants' },
|
|
122
|
+
},
|
|
123
|
+
async run({ args }) {
|
|
124
|
+
const tiers = csv(args.tier)
|
|
125
|
+
if (tiers.length === 0 && args.owner !== true)
|
|
126
|
+
throw new TypeVaultError('invalid', 'member add needs --tier or --owner')
|
|
127
|
+
const pub = decodeMemberPublic(args.publicKey)
|
|
128
|
+
await (await openAdmin(process.env)).addMember(args.name, { ...pub, owner: args.owner === true, tiers })
|
|
129
|
+
print(`added ${pub.kind} member ${args.name}${tiers.length === 0 ? '' : ` (rotated ${tiers.join(', ')})`}`)
|
|
130
|
+
note('commit the vault so they can pull it')
|
|
131
|
+
},
|
|
132
|
+
}),
|
|
133
|
+
rm: defineCommand({
|
|
134
|
+
meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
|
|
135
|
+
args: { name: { type: 'positional', required: true } },
|
|
136
|
+
async run({ args }) {
|
|
137
|
+
const affected = await (await openAdmin(process.env)).removeMember(args.name)
|
|
138
|
+
print(`removed ${args.name}`)
|
|
139
|
+
if (affected.length === 0) return
|
|
140
|
+
note('They may have kept what they read. Rotate these secrets at their source, then re-set them:')
|
|
141
|
+
for (const name of affected) note(` ${name}`)
|
|
142
|
+
},
|
|
143
|
+
}),
|
|
144
|
+
},
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
export const identity = defineCommand({
|
|
148
|
+
meta: { name: 'identity', description: "This device's member identity" },
|
|
149
|
+
subCommands: {
|
|
150
|
+
show: defineCommand({
|
|
151
|
+
meta: { name: 'show', description: 'Your name, kind and public key (safe to share)' },
|
|
152
|
+
run() {
|
|
153
|
+
const current = readIdentity(process.env)
|
|
154
|
+
if (current === undefined) throw new TypeVaultError('not_found', 'no identity yet (run typevault init or join)')
|
|
155
|
+
print(
|
|
156
|
+
table([
|
|
157
|
+
['NAME', current.name],
|
|
158
|
+
['KIND', current.kind],
|
|
159
|
+
['PUBLIC KEY', encodeMemberPublic(memberPublicOfIdentity(current))],
|
|
160
|
+
]),
|
|
161
|
+
)
|
|
162
|
+
},
|
|
163
|
+
}),
|
|
164
|
+
restore: defineCommand({
|
|
165
|
+
meta: { name: 'restore', description: 'Set up a new device from your Secret Key, password and this vault' },
|
|
166
|
+
args: { name: { type: 'positional', required: true } },
|
|
167
|
+
async run({ args }) {
|
|
168
|
+
const env = process.env
|
|
169
|
+
if (readIdentity(env) !== undefined) throw new TypeVaultError('conflict', 'this device already has an identity')
|
|
170
|
+
const layout = layoutFrom(env)
|
|
171
|
+
const copy = sealedCopyPath(layout, args.name)
|
|
172
|
+
if (!existsSync(copy)) throw new TypeVaultError('not_found', `this vault has no sealed key for "${args.name}"`)
|
|
173
|
+
const source = passwords()
|
|
174
|
+
const secretKey = await source.ask('Secret Key: ')
|
|
175
|
+
const sealedKey = readFileSync(copy, 'utf8')
|
|
176
|
+
const key = await openMemberKey(sealedKey, await source.ask('Password: '), secretKey)
|
|
177
|
+
const pub = await publicKeyOf(key)
|
|
178
|
+
const listed = (await Vault.open(layout, [], env)).state.members[args.name]
|
|
179
|
+
if (key.role.kind !== 'member' || key.role.name !== args.name || listed?.recipient !== pub.recipient) {
|
|
180
|
+
throw new TypeVaultError('tampered', `the sealed key does not belong to member "${args.name}"`)
|
|
181
|
+
}
|
|
182
|
+
writeIdentity(env, { v: 1, kind: 'human', name: args.name, secretKey, sealedKey, ...pub })
|
|
183
|
+
print(`restored identity "${args.name}"`)
|
|
184
|
+
},
|
|
185
|
+
}),
|
|
186
|
+
export: defineCommand({
|
|
187
|
+
meta: { name: 'export', description: 'Store your Secret Key (or a machine key) in 1Password' },
|
|
188
|
+
args: {
|
|
189
|
+
to: { type: 'string', required: true, description: '1password' },
|
|
190
|
+
via: { type: 'string', description: `${ONEPASSWORD_VIAS.join(' | ')} (default: op when installed, else sdk)` },
|
|
191
|
+
account: { type: 'string', description: '1Password account (required with sdk or several op accounts)' },
|
|
192
|
+
vault: { type: 'string', required: true, description: '1Password vault' },
|
|
193
|
+
title: { type: 'string', description: 'Item title (default: TypeVault identity <name>)' },
|
|
194
|
+
replace: { type: 'boolean', description: 'Archive an existing item with the same title' },
|
|
195
|
+
},
|
|
196
|
+
async run({ args }) {
|
|
197
|
+
if (args.to !== '1password') throw new TypeVaultError('invalid', '--to must be 1password')
|
|
198
|
+
const via = ONEPASSWORD_VIAS.find((candidate) => candidate === args.via)
|
|
199
|
+
if (args.via !== undefined && via === undefined) {
|
|
200
|
+
throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
|
|
201
|
+
}
|
|
202
|
+
const current = readIdentity(process.env)
|
|
203
|
+
if (current === undefined) throw new TypeVaultError('not_found', 'no identity yet (run typevault init or join)')
|
|
204
|
+
const item = {
|
|
205
|
+
title: args.title ?? identityTitle(current.name),
|
|
206
|
+
credential: current.kind === 'human' ? current.secretKey : current.key,
|
|
207
|
+
details: {
|
|
208
|
+
name: current.name,
|
|
209
|
+
kind: current.kind,
|
|
210
|
+
'public key': encodeMemberPublic(memberPublicOfIdentity(current)),
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
const used = await export1Password(item, {
|
|
214
|
+
...(via === undefined ? {} : { via }),
|
|
215
|
+
...(args.account === undefined ? {} : { account: args.account }),
|
|
216
|
+
vault: args.vault,
|
|
217
|
+
replace: args.replace === true,
|
|
218
|
+
})
|
|
219
|
+
print(`stored "${item.title}" in 1Password vault "${args.vault}" (via ${used})`)
|
|
220
|
+
if (current.kind === 'machine') note(`use it: TYPEVAULT_KEY="op://${args.vault}/${item.title}/credential"`)
|
|
221
|
+
},
|
|
222
|
+
}),
|
|
223
|
+
},
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
const MAX_TIMER_MS = 2 ** 31 - 1
|
|
227
|
+
|
|
228
|
+
export const unlock = defineCommand({
|
|
229
|
+
meta: { name: 'unlock', description: 'Unlock this vault for a while, so you and your agents can use it' },
|
|
230
|
+
args: { for: { type: 'string', default: '8h', description: 'How long, e.g. 30m, 8h' } },
|
|
231
|
+
async run({ args }) {
|
|
232
|
+
const env = process.env
|
|
233
|
+
const ttlMs = args.for === undefined ? DEFAULT_SESSION_MS : parseTtl(args.for)
|
|
234
|
+
if (ttlMs > MAX_TIMER_MS) throw new TypeVaultError('invalid', '--for is too long (at most 24 days)')
|
|
235
|
+
const started = await unlockSession(env, passwords(), ttlMs)
|
|
236
|
+
const id = vaultIdOf((await openPublic(env)).state.owner.signPublic)
|
|
237
|
+
print(started ? `unlocked vault ${id} for ${args.for}` : `vault ${id} is already unlocked`)
|
|
238
|
+
},
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
export const lock = defineCommand({
|
|
242
|
+
meta: { name: 'lock', description: 'Lock this vault now: stops the daemon and ends every session' },
|
|
243
|
+
async run() {
|
|
244
|
+
const layout = findLayout(process.env)
|
|
245
|
+
if (layout === undefined) throw new TypeVaultError('not_found', 'no vault here')
|
|
246
|
+
// A session unlocked in another worktree would only be shared here again on the next read.
|
|
247
|
+
const worktrees = await worktreeSessions(layout, process.env)
|
|
248
|
+
let locked = false
|
|
249
|
+
for (const target of [...worktrees, layout]) {
|
|
250
|
+
locked =
|
|
251
|
+
(await stopDaemon(target).then(
|
|
252
|
+
() => true,
|
|
253
|
+
(error: unknown) => {
|
|
254
|
+
if (error instanceof TypeVaultError && error.code === 'not_found') return false
|
|
255
|
+
throw error
|
|
256
|
+
},
|
|
257
|
+
)) || locked
|
|
258
|
+
}
|
|
259
|
+
print(locked ? 'locked' : 'already locked')
|
|
260
|
+
},
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
export const passwd = defineCommand({
|
|
264
|
+
meta: { name: 'passwd', description: 'Change your password (your key and every vault stay the same)' },
|
|
265
|
+
async run() {
|
|
266
|
+
const env = process.env
|
|
267
|
+
const current = readIdentity(env)
|
|
268
|
+
if (current?.kind !== 'human') throw new TypeVaultError('invalid', 'only a human identity has a password')
|
|
269
|
+
const source = passwords()
|
|
270
|
+
const key = await openMemberKey(current.sealedKey, await source.ask('Current password: '), current.secretKey)
|
|
271
|
+
const sealedKey = await sealMemberKey(key, await newPassword(source), current.secretKey)
|
|
272
|
+
writeIdentity(env, { ...current, sealedKey })
|
|
273
|
+
print('password changed')
|
|
274
|
+
const layout = findLayout(env)
|
|
275
|
+
const copy = layout === undefined ? undefined : sealedCopyPath(layout, current.name)
|
|
276
|
+
if (copy !== undefined && existsSync(copy)) {
|
|
277
|
+
atomicWrite(copy, sealedKey)
|
|
278
|
+
note(`updated ${copy}; commit it. Other vaults pick up the change on your next unlock there.`)
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
})
|