typevault 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +7 -7
  7. package/src/access/scoped.ts +100 -44
  8. package/src/access/sealed-access.ts +45 -23
  9. package/src/access/sealed.ts +33 -21
  10. package/src/access/types.ts +25 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +14 -9
  13. package/src/cli/commands/admin.ts +87 -47
  14. package/src/cli/commands/daemon.ts +33 -15
  15. package/src/cli/commands/entries.ts +166 -55
  16. package/src/cli/commands/grant.ts +12 -20
  17. package/src/cli/commands/members.ts +281 -0
  18. package/src/cli/commands/run.ts +61 -24
  19. package/src/cli/context.ts +155 -15
  20. package/src/cli/index.ts +27 -4
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +65 -0
  23. package/src/core/admin.ts +125 -74
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +9 -9
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +6 -0
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +84 -0
  31. package/src/core/identity.ts +130 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/keyring.ts +100 -56
  34. package/src/core/layout.ts +145 -26
  35. package/src/core/lock.ts +128 -16
  36. package/src/core/naming.ts +146 -49
  37. package/src/core/password.ts +111 -0
  38. package/src/core/payload.ts +42 -38
  39. package/src/core/revisions.ts +8 -4
  40. package/src/core/rotate.ts +59 -42
  41. package/src/core/state.ts +88 -48
  42. package/src/core/txn.ts +5 -4
  43. package/src/core/vault.ts +108 -46
  44. package/src/core/worktrees.ts +39 -0
  45. package/src/daemon/admin-routes.ts +33 -21
  46. package/src/daemon/agent-routes.ts +29 -11
  47. package/src/daemon/client.ts +15 -0
  48. package/src/daemon/daemon.ts +210 -32
  49. package/src/daemon/grants.ts +21 -4
  50. package/src/daemon/http.ts +3 -0
  51. package/src/daemon/live-access.ts +4 -4
  52. package/src/daemon/protocol.ts +17 -12
  53. package/src/daemon/requests.ts +17 -22
  54. package/src/daemon/spawn.ts +188 -9
  55. package/src/export/1password.ts +157 -0
  56. package/src/import/1password-live.ts +399 -0
  57. package/src/import/1password.ts +26 -5
  58. package/src/import/bitwarden.ts +3 -3
  59. package/src/import/csv.ts +1 -1
  60. package/src/import/dotenv.ts +2 -2
  61. package/src/import/index.ts +1 -0
  62. package/src/import/keepass.ts +2 -2
  63. package/src/import/lastpass.ts +2 -2
  64. package/src/import/shared.ts +67 -10
  65. package/src/import/typeclaw.ts +2 -2
  66. package/src/import/types.ts +1 -1
  67. package/src/index.ts +58 -0
  68. package/src/owner.ts +156 -0
  69. package/src/prompt/browser.ts +48 -15
  70. package/src/prompt/page.ts +19 -11
  71. package/src/prompt/styles.ts +64 -34
  72. package/src/prompt/types.ts +3 -3
@@ -1,25 +1,22 @@
1
1
  import { TypeVaultError } from './errors'
2
2
 
3
- export const ENTRY_TYPES = {
4
- password: { fields: ['username', 'password', 'totp', 'url'], primary: 'password' },
5
- api_key: { fields: ['key'], primary: 'key' },
6
- oauth: {
7
- fields: ['access_token', 'refresh_token', 'expires_at', 'token_url', 'client_id', 'client_secret'],
8
- primary: 'access_token',
9
- },
10
- ssh: { fields: ['private_key', 'public_key'], primary: 'private_key' },
11
- totp: { fields: ['seed'], primary: 'seed' },
12
- note: { fields: ['text'], primary: 'text' },
13
- } as const
14
-
15
- export type EntryType = keyof typeof ENTRY_TYPES
16
- export const ENTRY_TYPE_NAMES: readonly string[] = Object.keys(ENTRY_TYPES)
17
-
18
- export const isEntryType = (value: string): value is EntryType => Object.hasOwn(ENTRY_TYPES, value)
19
-
20
- export function parseEntryType(value: string): EntryType {
21
- if (isEntryType(value)) return value
22
- throw new TypeVaultError('invalid', `unknown type "${value}" (expected one of: ${ENTRY_TYPE_NAMES.join(', ')})`)
3
+ export type FieldType = 'secret' | 'text' | 'totp' | 'oauth'
4
+ export type Field =
5
+ | { readonly type: 'secret' | 'text' | 'totp'; readonly value: string }
6
+ | { readonly type: 'oauth'; readonly value: Readonly<Record<string, string>> }
7
+ export const PRESETS = {
8
+ password: { fields: { username: 'text', password: 'secret', totp: 'totp', url: 'text' }, input: 'password' },
9
+ api_key: { fields: { $default: 'secret' }, input: '$default' },
10
+ oauth: { fields: { $default: 'oauth' }, input: '$default' },
11
+ ssh: { fields: { private_key: 'secret', public_key: 'text' }, input: 'private_key' },
12
+ totp: { fields: { $default: 'totp' }, input: '$default' },
13
+ note: { fields: { $default: 'secret' }, input: '$default' },
14
+ } as const satisfies Record<string, { readonly fields: Readonly<Record<string, FieldType>>; readonly input: string }>
15
+ export type Preset = keyof typeof PRESETS
16
+ export const isPreset = (value: string): value is Preset => Object.hasOwn(PRESETS, value)
17
+ export function parsePreset(value: string): Preset {
18
+ if (isPreset(value)) return value
19
+ throw new TypeVaultError('invalid', `unknown preset "${value}" (expected one of: ${Object.keys(PRESETS).join(', ')})`)
23
20
  }
24
21
 
25
22
  export type EntryName = string & { readonly __brand: 'EntryName' }
@@ -27,14 +24,30 @@ export type EntryName = string & { readonly __brand: 'EntryName' }
27
24
  const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
28
25
  const MAX_SEGMENTS = 2
29
26
 
30
- /** Parses `<service>[/<account>]`. Names are case-insensitive and stored lowercase. */
27
+ /**
28
+ * The one way to point at an entry: `tv://<service>[/<account>][#<field>]`. `typevault://` is an alias, and the
29
+ * scheme may be left out (`github/bot#password`) as shorthand. Every name, `--only` pattern and env reference goes
30
+ * through the parsers below.
31
+ */
32
+ export const ENTRY_NAME_SYNTAX = 'tv://<service>[/<account>]'
33
+ export const ENTRY_REF_SYNTAX = `${ENTRY_NAME_SYNTAX}[#<field>]`
34
+
35
+ const REF_SCHEME = /^(?:tv|typevault):\/\//i
36
+
37
+ /** True when `input` carries the `tv://` (or `typevault://`) scheme, as an env value `run` resolves. */
38
+ export const hasRefScheme = (input: string): boolean => REF_SCHEME.test(input.trim())
39
+
40
+ /** An `--only` pattern (a name or a glob) in the form names are stored in: no scheme, lowercase. */
41
+ export const entryPattern = (input: string): string => input.trim().replace(REF_SCHEME, '').toLowerCase()
42
+
43
+ /** Parses `[tv://]<service>[/<account>]`. Names are case-insensitive and stored lowercase, without the scheme. */
31
44
  export function parseEntryName(input: string): EntryName {
32
- const name = input.trim().toLowerCase()
45
+ const name = entryPattern(input)
33
46
  const segments = name.split('/')
34
47
  if (segments.length > MAX_SEGMENTS || !segments.every((segment) => SEGMENT.test(segment))) {
35
48
  throw new TypeVaultError(
36
49
  'invalid',
37
- `invalid entry name "${input}" (expected <service>[/<account>], segments [a-z0-9-])`,
50
+ `invalid entry name "${input}" (expected ${ENTRY_NAME_SYNTAX}, segments [a-z0-9-])`,
38
51
  )
39
52
  }
40
53
  return name as EntryName
@@ -42,35 +55,119 @@ export function parseEntryName(input: string): EntryName {
42
55
 
43
56
  export type EntryRef = { readonly name: EntryName; readonly field: string | undefined }
44
57
 
45
- /** Parses `<service>[/<account>][#<field>]`. */
58
+ const MAX_FIELD_LENGTH = 64
59
+
60
+ /**
61
+ * An entry may hold any field: up to 64 characters, no surrounding
62
+ * whitespace, no control characters and no `=` (which `--field name=value` splits on). Case is kept.
63
+ */
64
+ export const isFieldName = (field: string): boolean =>
65
+ (!field.startsWith('$') || field === '$default') &&
66
+ field !== '' &&
67
+ field.length <= MAX_FIELD_LENGTH &&
68
+ field.trim() === field &&
69
+ !/[\p{Cc}=]/u.test(field)
70
+
71
+ /** Parses `[tv://]<service>[/<account>][#<field>]`. The field is everything after the first `#`. */
46
72
  export function parseEntryRef(input: string): EntryRef {
47
73
  const hash = input.indexOf('#')
48
74
  if (hash === -1) return { name: parseEntryName(input), field: undefined }
49
- const field = input.slice(hash + 1).toLowerCase()
50
- if (!/^[a-z0-9_]+$/.test(field)) throw new TypeVaultError('invalid', `invalid field "${field}"`)
75
+ const field = input.slice(hash + 1)
76
+ if (field === '$default' || !isFieldName(field)) throw new TypeVaultError('invalid', `invalid field "${field}"`)
51
77
  return { name: parseEntryName(input.slice(0, hash)), field }
52
78
  }
53
79
 
54
- /** Fields that hold secrets: never accepted on the command line, where `ps` and shell history see them. */
55
- const SECRET_FIELDS: ReadonlySet<string> = new Set([
56
- 'password',
57
- 'totp',
58
- 'key',
59
- 'access_token',
60
- 'refresh_token',
61
- 'client_secret',
62
- 'private_key',
63
- 'seed',
64
- 'text',
65
- ])
66
- export const isSecretField = (field: string): boolean => SECRET_FIELDS.has(field)
67
-
68
- export const fieldsOf = (type: EntryType): readonly string[] => ENTRY_TYPES[type].fields
69
- export const primaryField = (type: EntryType): string => ENTRY_TYPES[type].primary
70
-
71
- /** `github/bot` + `password` becomes `GITHUB_BOT_PASSWORD`. */
72
- export const deriveEnvName = (name: EntryName, field: string): string =>
73
- `${name}_${field}`.toUpperCase().replace(/[/-]/g, '_')
80
+ /** The stored key `field` refers to: an exact match, else the only one equal ignoring case. */
81
+ export function findField(fields: Readonly<Record<string, unknown>>, field: string): string | undefined {
82
+ if (Object.hasOwn(fields, field)) return field
83
+ const matches = Object.keys(fields).filter((key) => key.toLowerCase() === field.toLowerCase())
84
+ return matches.length === 1 ? matches[0] : undefined
85
+ }
86
+
87
+ /** The field a reference without `#field` reads: `$default`, else the only field, else none. */
88
+ export function defaultFieldOf(fields: Readonly<Record<string, unknown>>): string | undefined {
89
+ if (Object.hasOwn(fields, '$default')) return '$default'
90
+ const names = Object.keys(fields)
91
+ return names.length === 1 ? names[0] : undefined
92
+ }
93
+
94
+ export function defaultField(fields: Readonly<Record<string, unknown>>, name = 'entry'): string {
95
+ const field = defaultFieldOf(fields)
96
+ if (field !== undefined) return field
97
+ const names = Object.keys(fields)
98
+ throw new TypeVaultError(
99
+ 'not_found',
100
+ names.length === 0 ? `${name} has no fields` : `${name} has several fields, name one: ${names.join(', ')}`,
101
+ )
102
+ }
103
+
104
+ /**
105
+ * The field `wanted` names, else a part of a compound field: `oauth.refresh_token`, or `refresh_token` alone for a
106
+ * part of the default field (which a ref can't name, since `#$default` is refused).
107
+ */
108
+ export function resolveField(fields: Readonly<Record<string, Field>>, wanted: string): Field | undefined {
109
+ const key = findField(fields, wanted)
110
+ if (key !== undefined) return fields[key]
111
+ const dot = wanted.lastIndexOf('.')
112
+ const parent = dot === -1 ? defaultFieldOf(fields) : findField(fields, wanted.slice(0, dot))
113
+ const field = parent === undefined ? undefined : fields[parent]
114
+ if (field === undefined) return undefined
115
+ switch (field.type) {
116
+ case 'oauth': {
117
+ const part = field.value[wanted.slice(dot + 1)]
118
+ return part === undefined ? undefined : { type: 'secret', value: part }
119
+ }
120
+ case 'secret':
121
+ case 'text':
122
+ case 'totp':
123
+ return undefined
124
+ default:
125
+ return assertNever(field)
126
+ }
127
+ }
128
+ export function fieldValue(field: Field): string {
129
+ switch (field.type) {
130
+ case 'oauth':
131
+ return field.value['access_token'] ?? ''
132
+ case 'secret':
133
+ case 'text':
134
+ case 'totp':
135
+ return field.value
136
+ default:
137
+ return assertNever(field)
138
+ }
139
+ }
140
+ export function fieldStrings(field: Field): readonly string[] {
141
+ switch (field.type) {
142
+ case 'oauth':
143
+ return Object.values(field.value)
144
+ case 'secret':
145
+ case 'text':
146
+ case 'totp':
147
+ return [field.value]
148
+ default:
149
+ return assertNever(field)
150
+ }
151
+ }
152
+ function assertNever(value: never): never {
153
+ throw new TypeVaultError('invalid', `unexpected field ${JSON.stringify(value)}`)
154
+ }
155
+
156
+ /**
157
+ * `github/bot` + `password` becomes `GITHUB_BOT_PASSWORD`, and `Secret Access Key` becomes `..._SECRET_ACCESS_KEY`.
158
+ * Undefined when no letter or digit of the field survives (a non-Latin name): such a field is reachable only
159
+ * through a `tv://` ref.
160
+ */
161
+ export function deriveEnvName(name: EntryName, field: string): string | undefined {
162
+ if (field === '$default') return name.toUpperCase().replace(/[/-]/g, '_')
163
+ const suffix = field
164
+ .normalize('NFKD')
165
+ .replace(/\p{M}/gu, '')
166
+ .toUpperCase()
167
+ .replace(/[^A-Z0-9]+/g, '_')
168
+ .replace(/^_+|_+$/g, '')
169
+ return suffix === '' ? undefined : `${name.toUpperCase().replace(/[/-]/g, '_')}_${suffix}`
170
+ }
74
171
 
75
172
  /** Turns arbitrary text (an import title, a vault name) into a valid name segment. */
76
173
  export function slugifySegment(raw: string): string {
@@ -85,12 +182,12 @@ export function slugifySegment(raw: string): string {
85
182
 
86
183
  /** True when `name` matches any `--only` pattern (exact names or globs such as `github/*`). */
87
184
  export function matchesOnly(name: EntryName, patterns: readonly string[]): boolean {
88
- return patterns.some((pattern) => new Bun.Glob(pattern.toLowerCase()).match(name))
185
+ return patterns.some((pattern) => new Bun.Glob(entryPattern(pattern)).match(name))
89
186
  }
90
187
 
91
188
  /**
92
- * Variables that change how the child or its interpreter loads code. A lower group can write entries a higher
93
- * group's `run` loads, so an entry must never set these, whether by --env override or by a derived name.
189
+ * Variables that change how the child or its interpreter loads code. A lower tier can write entries a higher
190
+ * tier's `run` loads, so an entry must never set these, whether by --env override or by a derived name.
94
191
  */
95
192
  const RESERVED_ENV = new RegExp(
96
193
  `^(${[
@@ -0,0 +1,111 @@
1
+ import { hkdf } from '@noble/hashes/hkdf.js'
2
+ import { sha256 } from '@noble/hashes/sha2.js'
3
+ import { base32nopad } from '@scure/base'
4
+ import { argon2id } from 'hash-wasm'
5
+ import { z } from 'zod'
6
+
7
+ import { fromBase64, toBase64, utf8 } from './encoding'
8
+ import { TypeVaultError } from './errors'
9
+
10
+ const SECRET_KEY_PREFIX = 'TVSK'
11
+ const SECRET_KEY_BYTES = 20
12
+ const KDF = { memorySize: 65_536, iterations: 3, parallelism: 1 } as const
13
+
14
+ const SealedSchema = z.object({
15
+ v: z.literal(1),
16
+ kdf: z.object({
17
+ name: z.literal('argon2id'),
18
+ salt: z.string(),
19
+ memorySize: z.number().int().positive(),
20
+ iterations: z.number().int().positive(),
21
+ parallelism: z.number().int().positive(),
22
+ }),
23
+ nonce: z.string(),
24
+ ciphertext: z.string(),
25
+ })
26
+
27
+ export function generateSecretKeyCode(): string {
28
+ const encoded = base32nopad.encode(crypto.getRandomValues(new Uint8Array(SECRET_KEY_BYTES)))
29
+ return [SECRET_KEY_PREFIX, ...(encoded.match(/.{1,8}/g) ?? [])].join('-')
30
+ }
31
+
32
+ /**
33
+ * Seals `plaintext` under a key derived from both the password and the Secret Key, like 1Password's two-secret
34
+ * derivation: the sealed blob can sit in git, because guessing the password offline is useless without the Secret Key.
35
+ */
36
+ export async function sealWithPassword(plaintext: Uint8Array, password: string, secretKey: string): Promise<string> {
37
+ const salt = crypto.getRandomValues(new Uint8Array(16))
38
+ const nonce = crypto.getRandomValues(new Uint8Array(12))
39
+ const key = await deriveKey(password, secretKey, salt, KDF)
40
+ const ciphertext = new Uint8Array(
41
+ await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, new Uint8Array(plaintext)),
42
+ )
43
+ const sealed: z.infer<typeof SealedSchema> = {
44
+ v: 1,
45
+ kdf: { name: 'argon2id', salt: toBase64(salt), ...KDF },
46
+ nonce: toBase64(nonce),
47
+ ciphertext: toBase64(ciphertext),
48
+ }
49
+ return `${JSON.stringify(sealed, null, 2)}\n`
50
+ }
51
+
52
+ /** Opens what `sealWithPassword` sealed; a wrong password or Secret Key is `denied`. */
53
+ export async function openWithPassword(sealed: string, password: string, secretKey: string): Promise<Uint8Array> {
54
+ const parsed = SealedSchema.safeParse(parseJson(sealed))
55
+ if (!parsed.success) throw new TypeVaultError('invalid', 'malformed sealed member key')
56
+ const { kdf, nonce, ciphertext } = parsed.data
57
+ const key = await deriveKey(password, secretKey, fromBase64(kdf.salt), kdf)
58
+ try {
59
+ return new Uint8Array(
60
+ await crypto.subtle.decrypt(
61
+ { name: 'AES-GCM', iv: new Uint8Array(fromBase64(nonce)) },
62
+ key,
63
+ new Uint8Array(fromBase64(ciphertext)),
64
+ ),
65
+ )
66
+ } catch (error) {
67
+ if (error instanceof Error) throw new TypeVaultError('denied', 'wrong password or Secret Key')
68
+ throw error
69
+ }
70
+ }
71
+
72
+ async function deriveKey(
73
+ password: string,
74
+ secretKey: string,
75
+ salt: Uint8Array,
76
+ params: { readonly memorySize: number; readonly iterations: number; readonly parallelism: number },
77
+ ): Promise<CryptoKey> {
78
+ const stretched = await argon2id({
79
+ password: password.normalize('NFKC'),
80
+ salt,
81
+ memorySize: params.memorySize,
82
+ iterations: params.iterations,
83
+ parallelism: params.parallelism,
84
+ hashLength: 32,
85
+ outputType: 'binary',
86
+ })
87
+ const secret = parseSecretKeyCode(secretKey)
88
+ const material = new Uint8Array([...stretched, ...secret])
89
+ const raw = hkdf(sha256, material, salt, utf8('typevault member key'), 32)
90
+ return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
91
+ }
92
+
93
+ function parseSecretKeyCode(text: string): Uint8Array {
94
+ const [prefix, ...groups] = text.trim().toUpperCase().split('-')
95
+ try {
96
+ const bytes = prefix === SECRET_KEY_PREFIX ? base32nopad.decode(groups.join('')) : undefined
97
+ if (bytes?.length === SECRET_KEY_BYTES) return bytes
98
+ } catch (error) {
99
+ if (!(error instanceof Error)) throw error
100
+ }
101
+ throw new TypeVaultError('invalid', 'not a TypeVault Secret Key (TVSK-...)')
102
+ }
103
+
104
+ function parseJson(text: string): unknown {
105
+ try {
106
+ return JSON.parse(text)
107
+ } catch (error) {
108
+ if (error instanceof SyntaxError) return undefined
109
+ throw error
110
+ }
111
+ }
@@ -2,14 +2,13 @@ import { z } from 'zod'
2
2
 
3
3
  import { fromUtf8, utf8 } from './encoding'
4
4
  import { TypeVaultError } from './errors'
5
- import { type EntryName, type EntryType, fieldsOf, isEntryType, isUsableEnvName, parseEntryName } from './naming'
5
+ import { type EntryName, type Field, isFieldName, isUsableEnvName, parseEntryName } from './naming'
6
6
 
7
- /** The plaintext sealed inside an entry file: everything except the group is secret. */
7
+ /** The plaintext sealed inside an entry file: everything except the tier is secret. */
8
8
  export type EntryPayload = {
9
9
  readonly v: 1
10
10
  readonly name: EntryName
11
- readonly type: EntryType
12
- readonly fields: Readonly<Record<string, string>>
11
+ readonly fields: Readonly<Record<string, Field>>
13
12
  readonly env?: string
14
13
  readonly origin?: string
15
14
  readonly tags: readonly string[]
@@ -18,38 +17,49 @@ export type EntryPayload = {
18
17
  readonly needsRotation?: boolean
19
18
  }
20
19
 
21
- const PayloadSchema = z.object({
22
- v: z.literal(1),
23
- name: z.string(),
24
- type: z.string().refine(isEntryType),
25
- fields: z.record(z.string(), z.string()),
26
- env: z
27
- .string()
28
- .regex(/^[A-Z_][A-Z0-9_]*$/)
29
- .optional(),
30
- origin: z.string().optional(),
31
- tags: z.array(z.string()),
32
- created: z.iso.datetime(),
33
- rotated: z.iso.datetime(),
34
- needsRotation: z.boolean().optional(),
35
- })
20
+ export const FieldSchema = z.discriminatedUnion('type', [
21
+ z.object({ type: z.literal('secret'), value: z.string() }).strict(),
22
+ z.object({ type: z.literal('text'), value: z.string() }).strict(),
23
+ z.object({ type: z.literal('totp'), value: z.string() }).strict(),
24
+ z
25
+ .object({
26
+ type: z.literal('oauth'),
27
+ value: z
28
+ .record(z.string(), z.string())
29
+ .refine((value) => typeof value['access_token'] === 'string', 'OAuth requires access_token'),
30
+ })
31
+ .strict(),
32
+ ])
33
+ export const FieldsSchema = z.record(z.string().refine(isFieldName), FieldSchema)
36
34
 
37
- /** Why a payload can't be stored, or undefined when it can. */
38
- function payloadProblem(value: unknown): string | undefined {
35
+ const PayloadSchema = z
36
+ .object({
37
+ v: z.literal(1),
38
+ name: z.string(),
39
+ fields: FieldsSchema,
40
+ env: z
41
+ .string()
42
+ .regex(/^[A-Z_][A-Z0-9_]*$/)
43
+ .optional(),
44
+ origin: z.string().optional(),
45
+ tags: z.array(z.string()),
46
+ created: z.iso.datetime(),
47
+ rotated: z.iso.datetime(),
48
+ needsRotation: z.boolean().optional(),
49
+ })
50
+ .strict()
51
+
52
+ function parsePayload(value: unknown, code: 'invalid' | 'tampered'): z.infer<typeof PayloadSchema> {
39
53
  const parsed = PayloadSchema.safeParse(value)
40
- if (!parsed.success) return parsed.error.issues[0]?.message ?? 'malformed'
41
- const { type, fields, env } = parsed.data
42
- if (!isEntryType(type)) return `unknown type "${type}"`
43
- const allowed = fieldsOf(type)
44
- const stray = Object.keys(fields).find((field) => !allowed.includes(field))
45
- if (stray !== undefined) return `${type} entries have no field "${stray}"`
46
- if (env !== undefined && !isUsableEnvName(env)) return `${env} is not a usable env name`
47
- return undefined
54
+ if (!parsed.success)
55
+ throw new TypeVaultError(code, `malformed entry payload: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
56
+ const { env } = parsed.data
57
+ if (env !== undefined && !isUsableEnvName(env)) throw new TypeVaultError(code, `${env} is not a usable env name`)
58
+ return parsed.data
48
59
  }
49
60
 
50
61
  export function encodePayload(payload: EntryPayload): Uint8Array {
51
- const problem = payloadProblem(payload)
52
- if (problem !== undefined) throw new TypeVaultError('invalid', problem)
62
+ parsePayload(payload, 'invalid')
53
63
  return utf8(JSON.stringify(payload))
54
64
  }
55
65
 
@@ -62,16 +72,10 @@ export function decodePayload(bytes: Uint8Array): EntryPayload {
62
72
  throw new TypeVaultError('tampered', 'entry payload is not JSON')
63
73
  throw error
64
74
  }
65
- const problem = payloadProblem(value)
66
- const parsed = PayloadSchema.safeParse(value)
67
- if (problem !== undefined || !parsed.success)
68
- throw new TypeVaultError('tampered', `malformed entry payload: ${problem ?? 'invalid'}`)
69
- const { name, type, env, origin, needsRotation, ...rest } = parsed.data
70
- if (!isEntryType(type)) throw new TypeVaultError('tampered', `unknown entry type "${type}"`)
75
+ const { name, env, origin, needsRotation, ...rest } = parsePayload(value, 'tampered')
71
76
  return {
72
77
  ...rest,
73
78
  name: parseEntryName(name),
74
- type,
75
79
  ...(env === undefined ? {} : { env }),
76
80
  ...(origin === undefined ? {} : { origin }),
77
81
  ...(needsRotation === undefined ? {} : { needsRotation }),
@@ -20,11 +20,15 @@ export class RevisionMarks {
20
20
  this.#marks = existsSync(path) ? MarksSchema.parse(JSON.parse(readFileSync(path, 'utf8'))) : {}
21
21
  }
22
22
 
23
- /** False when `rev` is older than a revision already seen for `id`; otherwise records it. */
23
+ /** False when `rev` is older than a revision already seen for `id`. */
24
+ allows(id: string, rev: number): boolean {
25
+ return rev >= (this.#marks[id] ?? 0)
26
+ }
27
+
28
+ /** Like `allows`, and records `rev` when it is. */
24
29
  accept(id: string, rev: number): boolean {
25
- const seen = this.#marks[id] ?? 0
26
- if (rev < seen) return false
27
- if (rev > seen) {
30
+ if (!this.allows(id, rev)) return false
31
+ if (rev > (this.#marks[id] ?? 0)) {
28
32
  this.#marks[id] = rev
29
33
  this.#dirty = true
30
34
  }
@@ -3,71 +3,88 @@ import { utf8 } from './encoding'
3
3
  import { sealEntry, type SignerRef, signerOf } from './entries'
4
4
  import { TypeVaultError } from './errors'
5
5
  import { wrapPath } from './keyring'
6
- import { type Group, groupsDoc, includersOf, reach, type VaultState } from './state'
6
+ import { type Tier, tiersDoc, includersOf, reach, type VaultState } from './state'
7
7
  import type { Txn } from './txn'
8
8
  import type { Vault } from './vault'
9
9
 
10
10
  export type RotateContext = {
11
11
  readonly vault: Vault
12
- readonly operator: SecretKey
12
+ readonly owner: SecretKey
13
+ /** The state the rotation is for: its members are who gets the new keys. */
13
14
  readonly state: VaultState
14
15
  readonly txn: Txn
16
+ /** Whether the old keys may have leaked, so every secret they reached must be rotated at its source. */
17
+ readonly exposed: boolean
15
18
  }
16
19
 
17
- const signedBy = (signer: SignerRef, group: string): boolean =>
18
- (signer.kind === 'group' && signer.group === group) ||
19
- (signer.kind === 'cert' && signer.cert.issuer.kind === 'group' && signer.cert.issuer.group === group)
20
+ const signedBy = (signer: SignerRef, tier: string): boolean =>
21
+ (signer.kind === 'tier' && signer.tier === tier) ||
22
+ (signer.kind === 'cert' && signer.cert.issuer.kind === 'tier' && signer.cert.issuer.tier === tier)
20
23
 
21
24
  /**
22
- * Stages a new key generation for `name` into `txn`: fresh wraps for the operator and every includer,
23
- * re-wraps of the groups it includes, re-sealed entries, and finally the generation flip in groups.json.
24
- * Entries the old key could reach are flagged `needsRotation`; their names are returned.
25
+ * Stages a new key generation for each of `names` into `txn`, all in one transaction: fresh wraps for the owner,
26
+ * every includer and every member holding the tier, re-wraps of the tiers each one includes, re-sealed entries, and
27
+ * finally the generation flip in tiers.json. When `exposed`, entries the old keys could reach are flagged
28
+ * `needsRotation` and their names returned.
25
29
  */
26
- export async function rotateGroup(context: RotateContext, name: string): Promise<readonly string[]> {
27
- const { vault, operator, state, txn } = context
28
- const meta = state.groups[name]
29
- if (meta === undefined) throw new TypeVaultError('not_found', `no group "${name}"`)
30
- const gen = meta.gen + 1
31
- const key = await generateSecretKey({ kind: 'group', group: name, gen })
32
- const updated: Group = { ...meta, gen, ...(await publicKeyOf(key)) }
33
- const next: VaultState = { ...state, groups: { ...state.groups, [name]: updated } }
34
- const encoded = utf8(encodeSecretKey(key))
35
-
36
- txn.put(wrapPath(name, gen, { kind: 'operator' }), await seal([state.operator.recipient], encoded))
37
- for (const includer of includersOf(state.groups, name)) {
38
- const holder = state.groups[includer]
39
- if (holder === undefined) continue
40
- txn.put(
41
- wrapPath(name, gen, { kind: 'group', group: includer, gen: holder.gen }),
42
- await seal([holder.recipient], encoded),
43
- )
30
+ export async function rotateTiers(context: RotateContext, names: readonly string[]): Promise<readonly string[]> {
31
+ const { vault, owner, state, txn, exposed } = context
32
+ if (names.length === 0) return []
33
+ const rotated = new Map<string, { readonly key: SecretKey; readonly tier: Tier }>()
34
+ for (const name of new Set(names)) {
35
+ const meta = state.tiers[name]
36
+ if (meta === undefined) throw new TypeVaultError('not_found', `no tier "${name}"`)
37
+ const key = await generateSecretKey({ kind: 'tier', tier: name, gen: meta.gen + 1 })
38
+ rotated.set(name, { key, tier: { ...meta, gen: meta.gen + 1, ...(await publicKeyOf(key)) } })
44
39
  }
45
- for (const included of meta.includes) {
46
- const includedKey = await vault.keyring.unlock(included)
47
- const includedGen = state.groups[included]?.gen
48
- if (includedKey === undefined || includedGen === undefined) continue
49
- const sealed = await seal([updated.recipient], utf8(encodeSecretKey(includedKey)))
50
- txn.put(wrapPath(included, includedGen, { kind: 'group', group: name, gen }), sealed)
51
- txn.remove(wrapPath(included, includedGen, { kind: 'group', group: name, gen: meta.gen }))
40
+ const tiers = { ...state.tiers, ...Object.fromEntries([...rotated].map(([name, { tier }]) => [name, tier])) }
41
+ const next: VaultState = { ...state, tiers }
42
+
43
+ for (const [name, { key, tier }] of rotated) {
44
+ const oldGen = state.tiers[name]?.gen ?? 0
45
+ const encoded = utf8(encodeSecretKey(key))
46
+ txn.put(wrapPath(name, tier.gen, { kind: 'owner' }), await seal([state.owner.recipient], encoded))
47
+ for (const includer of includersOf(tiers, name)) {
48
+ const holder = tiers[includer]
49
+ if (holder === undefined) continue
50
+ txn.put(
51
+ wrapPath(name, tier.gen, { kind: 'tier', tier: includer, gen: holder.gen }),
52
+ await seal([holder.recipient], encoded),
53
+ )
54
+ }
55
+ for (const [member, holder] of Object.entries(state.members)) {
56
+ if (!holder.tiers.includes(name)) continue
57
+ txn.put(wrapPath(name, tier.gen, { kind: 'member', name: member }), await seal([holder.recipient], encoded))
58
+ }
59
+ // An included tier rotated here already wrapped its new key to this tier's new key above.
60
+ for (const included of tier.includes.filter((other) => !rotated.has(other))) {
61
+ const includedKey = await vault.keyring.unlock(included)
62
+ const includedGen = state.tiers[included]?.gen
63
+ if (includedKey === undefined || includedGen === undefined) continue
64
+ const sealed = await seal([tier.recipient], utf8(encodeSecretKey(includedKey)))
65
+ txn.put(wrapPath(included, includedGen, { kind: 'tier', tier: name, gen: tier.gen }), sealed)
66
+ txn.remove(wrapPath(included, includedGen, { kind: 'tier', tier: name, gen: oldGen }))
67
+ }
68
+ txn.remove(`tiers/${name}/${oldGen}`)
52
69
  }
53
- txn.remove(`groups/${name}/${meta.gen}`)
54
70
 
55
- const reached = reach(state.groups, name)
71
+ const reached = new Set([...rotated.keys()].flatMap((name) => [...reach(state.tiers, name)]))
56
72
  const affected: string[] = []
57
73
  const now = new Date().toISOString()
58
74
  const { entries } = await vault.scan()
59
75
  for (const { envelope, payload } of entries) {
60
- const exposed = reached.has(envelope.group)
61
- if (!exposed && !signedBy(envelope.signer, name)) continue
62
- if (exposed) affected.push(payload.name)
63
- const draft = { id: envelope.id, group: envelope.group, rev: envelope.rev + 1, at: now }
76
+ const reachable = reached.has(envelope.tier)
77
+ if (!reachable && ![...rotated.keys()].some((name) => signedBy(envelope.signer, name))) continue
78
+ const flagged = exposed && reachable
79
+ if (flagged) affected.push(payload.name)
80
+ const draft = { id: envelope.id, tier: envelope.tier, rev: envelope.rev + 1, at: now }
64
81
  const resealed = await sealEntry(
65
- { ...draft, payload: exposed ? { ...payload, needsRotation: true } : payload },
82
+ { ...draft, payload: flagged ? { ...payload, needsRotation: true } : payload },
66
83
  next,
67
- signerOf(operator),
84
+ signerOf(owner),
68
85
  )
69
86
  txn.put(`entries/${envelope.id}.json`, `${JSON.stringify(resealed, null, 2)}\n`)
70
87
  }
71
- txn.put('groups.json', groupsDoc(next.groups, operator, state.seqs.groups + 1))
88
+ txn.put('tiers.json', tiersDoc(tiers, owner, state.seqs.tiers + 1))
72
89
  return affected.sort()
73
90
  }