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.
Files changed (76) 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 +14 -9
  7. package/src/access/scoped.ts +118 -44
  8. package/src/access/sealed-access.ts +50 -23
  9. package/src/access/sealed.ts +56 -31
  10. package/src/access/types.ts +27 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +28 -12
  13. package/src/cli/commands/admin.ts +93 -48
  14. package/src/cli/commands/daemon.ts +42 -17
  15. package/src/cli/commands/entries.ts +195 -60
  16. package/src/cli/commands/grant.ts +24 -22
  17. package/src/cli/commands/members.ts +307 -0
  18. package/src/cli/commands/run.ts +191 -44
  19. package/src/cli/context.ts +163 -15
  20. package/src/cli/index.ts +33 -5
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +79 -0
  23. package/src/core/admin.ts +144 -76
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +15 -16
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +8 -2
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +87 -0
  31. package/src/core/identity.ts +132 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/json-file.ts +20 -0
  34. package/src/core/keyring.ts +100 -56
  35. package/src/core/layout.ts +143 -26
  36. package/src/core/lock.ts +128 -16
  37. package/src/core/naming.ts +150 -50
  38. package/src/core/password.ts +111 -0
  39. package/src/core/payload.ts +42 -38
  40. package/src/core/revisions.ts +11 -6
  41. package/src/core/rotate.ts +59 -42
  42. package/src/core/state.ts +102 -54
  43. package/src/core/txn.ts +9 -7
  44. package/src/core/vault.ts +108 -46
  45. package/src/core/worktrees.ts +51 -0
  46. package/src/daemon/admin-routes.ts +33 -21
  47. package/src/daemon/agent-routes.ts +31 -11
  48. package/src/daemon/client.ts +24 -2
  49. package/src/daemon/daemon.ts +218 -33
  50. package/src/daemon/grants.ts +25 -7
  51. package/src/daemon/http.ts +11 -2
  52. package/src/daemon/live-access.ts +8 -4
  53. package/src/daemon/protocol.ts +17 -12
  54. package/src/daemon/requests.ts +75 -51
  55. package/src/daemon/spawn.ts +218 -9
  56. package/src/export/1password.ts +157 -0
  57. package/src/import/1password-live.ts +399 -0
  58. package/src/import/1password.ts +26 -5
  59. package/src/import/bitwarden.ts +3 -3
  60. package/src/import/csv.ts +1 -1
  61. package/src/import/dotenv.ts +4 -3
  62. package/src/import/index.ts +1 -0
  63. package/src/import/keepass.ts +2 -2
  64. package/src/import/lastpass.ts +2 -2
  65. package/src/import/shared.ts +67 -10
  66. package/src/import/typeclaw.ts +2 -2
  67. package/src/import/types.ts +1 -1
  68. package/src/index.ts +58 -0
  69. package/src/owner.ts +156 -0
  70. package/src/prompt/browser.ts +48 -15
  71. package/src/prompt/index.ts +121 -64
  72. package/src/prompt/page.ts +27 -11
  73. package/src/prompt/styles.ts +64 -34
  74. package/src/prompt/types.ts +7 -4
  75. package/src/redact/index.ts +48 -12
  76. package/src/redact/scrub-file.ts +15 -7
@@ -1,13 +1,12 @@
1
1
  import type { SignerRef } from '../core/entries'
2
2
  import { TypeVaultError } from '../core/errors'
3
- import { type EntryName, type EntryType, isReservedEnvName } from '../core/naming'
3
+ import { type EntryName, type Field, isReservedEnvName } from '../core/naming'
4
4
  import type { EntryPayload } from '../core/payload'
5
- import { reachesGroup, type VaultState } from '../core/state'
5
+ import { reachesTier, type VaultState } from '../core/state'
6
6
 
7
7
  export type EntrySummary = {
8
8
  readonly name: EntryName
9
- readonly type: EntryType
10
- readonly group: string
9
+ readonly tier: string
11
10
  readonly rev: number
12
11
  readonly tags: readonly string[]
13
12
  readonly rotated: string
@@ -17,18 +16,17 @@ export type EntrySummary = {
17
16
  export type EntryValue = EntrySummary & {
18
17
  readonly id: string
19
18
  readonly created: string
20
- readonly fields: Readonly<Record<string, string>>
19
+ readonly fields: Readonly<Record<string, Field>>
21
20
  readonly env?: string
22
21
  readonly origin?: string
23
- /** Written by the operator or by a key that reaches all of the reader's own groups: its `--env` override counts. */
22
+ /** Written by the owner or by a key that reaches all of the reader's own tiers: its `--env` override counts. */
24
23
  readonly trustedWriter?: boolean
25
24
  }
26
25
 
27
26
  export type SetInput = {
28
27
  readonly name: EntryName
29
- readonly type: EntryType
30
- readonly fields: Readonly<Record<string, string>>
31
- readonly group?: string | undefined
28
+ readonly fields: Readonly<Record<string, Field>>
29
+ readonly tier?: string | undefined
32
30
  readonly env?: string | undefined
33
31
  readonly origin?: string | undefined
34
32
  readonly tags?: readonly string[] | undefined
@@ -36,15 +34,14 @@ export type SetInput = {
36
34
  }
37
35
 
38
36
  /** The vault-level input for a write, without the optional keys a parsed request leaves undefined. */
39
- export function entryInputOf(input: SetInput, group: string) {
37
+ export function entryInputOf(input: SetInput, tier: string) {
40
38
  if (input.env !== undefined && isReservedEnvName(input.env)) {
41
39
  throw new TypeVaultError('invalid', `${input.env} is reserved: run never sets it from the vault`)
42
40
  }
43
41
  return {
44
42
  name: input.name,
45
- type: input.type,
46
43
  fields: input.fields,
47
- group,
44
+ tier,
48
45
  ...(input.env === undefined ? {} : { env: input.env }),
49
46
  ...(input.origin === undefined ? {} : { origin: input.origin }),
50
47
  ...(input.tags === undefined ? {} : { tags: input.tags }),
@@ -54,24 +51,25 @@ export function entryInputOf(input: SetInput, group: string) {
54
51
  /** What a CLI command can do with secrets, whether the values come from a daemon, a sealed grant or a local key. */
55
52
  export interface Access {
56
53
  list(): Promise<readonly EntrySummary[]>
54
+ /** How many entry files `list` left out because they don't verify or can't be read. */
55
+ unreadableEntries(): Promise<number>
57
56
  get(name: EntryName, reason?: string): Promise<EntryValue>
58
57
  values(only: readonly string[], reason?: string): Promise<readonly EntryValue[]>
59
58
  set(input: SetInput): Promise<EntrySummary>
60
- /** `group` picks one copy when a name exists in unrelated groups. */
61
- remove(name: EntryName, group?: string): Promise<void>
59
+ /** `tier` picks one copy when a name exists in unrelated tiers. */
60
+ remove(name: EntryName, tier?: string): Promise<void>
62
61
  move(from: EntryName, to: EntryName): Promise<void>
63
- /** The groups this caller holds directly (not through includes): what `run` loads in bulk. */
64
- ownGroups(): Promise<readonly string[]>
62
+ /** The tiers this caller holds directly (not through includes): what `run` loads in bulk. */
63
+ ownTiers(): Promise<readonly string[]>
65
64
  /** Every secret value this grant has handed out so far, for redaction. */
66
65
  readValues(): Promise<readonly string[]>
67
66
  }
68
67
 
69
- export function toValue(group: string, id: string, rev: number, payload: EntryPayload): EntryValue {
68
+ export function toValue(tier: string, id: string, rev: number, payload: EntryPayload): EntryValue {
70
69
  return {
71
70
  id,
72
71
  name: payload.name,
73
- type: payload.type,
74
- group,
72
+ tier,
75
73
  rev,
76
74
  tags: payload.tags,
77
75
  created: payload.created,
@@ -85,22 +83,21 @@ export function toValue(group: string, id: string, rev: number, payload: EntryPa
85
83
 
86
84
  export const toSummary = (value: EntryValue): EntrySummary => ({
87
85
  name: value.name,
88
- type: value.type,
89
- group: value.group,
86
+ tier: value.tier,
90
87
  rev: value.rev,
91
88
  tags: value.tags,
92
89
  rotated: value.rotated,
93
90
  needsRotation: value.needsRotation,
94
91
  })
95
92
 
96
- /** Whether `signer` is at least as privileged as a reader holding `ownGroups`. */
97
- export function writtenFromAbove(signer: SignerRef, state: VaultState, ownGroups: readonly string[]): boolean {
98
- if (signer.kind === 'operator') return true
99
- const groups =
100
- signer.kind === 'group'
101
- ? [signer.group]
93
+ /** Whether `signer` is at least as privileged as a reader holding `ownTiers`. */
94
+ export function writtenFromAbove(signer: SignerRef, state: VaultState, ownTiers: readonly string[]): boolean {
95
+ if (signer.kind === 'owner') return true
96
+ const tiers =
97
+ signer.kind === 'tier'
98
+ ? [signer.tier]
102
99
  : signer.kind === 'signer'
103
- ? (state.signers[signer.id]?.groups ?? [])
104
- : signer.cert.groups
105
- return ownGroups.length > 0 && ownGroups.every((own) => reachesGroup(state.groups, groups, own))
100
+ ? (state.signers[signer.id]?.tiers ?? [])
101
+ : signer.cert.tiers
102
+ return ownTiers.length > 0 && ownTiers.every((own) => reachesTier(state.tiers, tiers, own))
106
103
  }
package/src/admin.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { z } from 'zod'
2
+
3
+ import { adminCall, type Env } from './cli/context'
4
+
5
+ export const IssuedSchema = z.object({ token: z.string() })
6
+ export const GrantInfoSchema = z.object({
7
+ id: z.string(),
8
+ label: z.string(),
9
+ tiers: z.array(z.string()),
10
+ only: z.array(z.string()),
11
+ exp: z.string(),
12
+ })
13
+ const RevokedSchema = z.object({ revoked: z.array(z.string()) })
14
+
15
+ export type GrantInfo = z.infer<typeof GrantInfoSchema>
16
+
17
+ export type GrantRequest = {
18
+ readonly tiers: readonly string[]
19
+ /** Names or globs the grant is narrowed to. Empty means everything in `tiers`. */
20
+ readonly only?: readonly string[]
21
+ /** e.g. `30m`, `1h`. Defaults to `1h`. */
22
+ readonly ttl?: string
23
+ /** Who this is for, e.g. `session:abc`. Shows up in the audit trail. */
24
+ readonly label?: string
25
+ /** An offline bundle: no daemon needed to read, no revocation. */
26
+ readonly sealed?: boolean
27
+ }
28
+
29
+ export type AdminOptions = {
30
+ /** The global vault's directory. Defaults to `TYPEVAULT_DIR`; without one the vault is chosen like the CLI's. */
31
+ readonly dir?: string
32
+ /** Use the global vault instead of the project's, like the CLI's `-g`. Defaults to `TYPEVAULT_GLOBAL`. */
33
+ readonly global?: boolean
34
+ /** Which admin socket to use (`admin-<ceiling>.sock`). Defaults to `TYPEVAULT_CEILING`, else `default`. */
35
+ readonly ceiling?: string
36
+ /** The vault's private state (trust pin, audit, run). Defaults to `TYPEVAULT_STATE_DIR`, else this user's config. */
37
+ readonly stateDir?: string
38
+ /** Where the daemon's sockets live, for a `stateDir` too deep for one. Defaults to `TYPEVAULT_RUN_DIR`. */
39
+ readonly runDir?: string
40
+ /** Where the defaults above are read from. Defaults to `process.env`. */
41
+ readonly env?: Env
42
+ }
43
+
44
+ export type AdminClient = {
45
+ /** Issues a grant within this socket's ceiling and returns its token. */
46
+ grant(request: GrantRequest): Promise<string>
47
+ /** The grants this socket may see: all of them on an uncapped socket, its own otherwise. */
48
+ list(): Promise<readonly GrantInfo[]>
49
+ /** Revokes by id or label, along with grants derived from them. Returns the revoked ids. */
50
+ revoke(target: { readonly id: string } | { readonly label: string }): Promise<readonly string[]>
51
+ }
52
+
53
+ /** Grant management over an admin socket, the same calls `typevault grant` makes. Starts the daemon if needed. */
54
+ export function createAdmin(options: AdminOptions = {}): AdminClient {
55
+ const env: Env = {
56
+ ...(options.env ?? process.env),
57
+ ...(options.dir === undefined ? {} : { TYPEVAULT_DIR: options.dir }),
58
+ ...(options.global === undefined ? {} : { TYPEVAULT_GLOBAL: options.global ? '1' : '' }),
59
+ ...(options.ceiling === undefined ? {} : { TYPEVAULT_CEILING: options.ceiling }),
60
+ ...(options.stateDir === undefined ? {} : { TYPEVAULT_STATE_DIR: options.stateDir }),
61
+ ...(options.runDir === undefined ? {} : { TYPEVAULT_RUN_DIR: options.runDir }),
62
+ }
63
+ return {
64
+ grant: async (request) => (await adminCall(env, '/v1/grant', request, IssuedSchema)).token,
65
+ list: () => adminCall(env, '/v1/grants', {}, z.array(GrantInfoSchema)),
66
+ revoke: async (target) => (await adminCall(env, '/v1/revoke', target, RevokedSchema)).revoked,
67
+ }
68
+ }
package/src/audit/log.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import { appendFileSync, closeSync, existsSync, fsyncSync, openSync, readFileSync, readSync, statSync } from 'node:fs'
2
+ import { dirname, relative } from 'node:path'
2
3
 
3
4
  import { z } from 'zod'
4
5
 
5
6
  import { sha256Hex } from '../core/crypto'
6
7
  import { canonicalJson, type Json, utf8 } from '../core/encoding'
7
- import { ensureDir } from '../core/fsx'
8
+ import { TypeVaultError } from '../core/errors'
9
+ import { assertNoSymlinks, ensureDir } from '../core/fsx'
10
+ import { parseJsonText } from '../core/json-file'
8
11
  import type { Layout } from '../core/layout'
9
12
  import { withLock } from '../core/lock'
10
13
 
@@ -16,7 +19,7 @@ export type AuditEvent = {
16
19
  readonly mode: AuditMode
17
20
  readonly grant?: string
18
21
  readonly label?: string
19
- readonly groups?: readonly string[]
22
+ readonly tiers?: readonly string[]
20
23
  readonly entries?: readonly string[]
21
24
  readonly reason?: string
22
25
  }
@@ -56,7 +59,7 @@ function readLast(layout: Layout): AuditRecord | undefined {
56
59
  .split('\n')
57
60
  .filter((line) => line !== '')
58
61
  const last = lines.at(-1)
59
- if (lines.length > 1 && last !== undefined) return RecordSchema.parse(JSON.parse(last))
62
+ if (lines.length > 1 && last !== undefined) return parseJsonText(layout.auditLog, last, RecordSchema)
60
63
  } finally {
61
64
  closeSync(fd)
62
65
  }
@@ -69,11 +72,13 @@ export function readAudit(layout: Layout): readonly AuditRecord[] {
69
72
  return readFileSync(layout.auditLog, 'utf8')
70
73
  .split('\n')
71
74
  .filter((line) => line !== '')
72
- .map((line) => RecordSchema.parse(JSON.parse(line)))
75
+ .map((line) => parseJsonText(layout.auditLog, line, RecordSchema))
73
76
  }
74
77
 
75
78
  function writeAnchor(layout: Layout, last: AuditRecord): void {
76
- ensureDir(layout.vault)
79
+ // The anchors live in the committed vault: a pulled symlink there must not redirect this append.
80
+ assertNoSymlinks(dirname(layout.vault), relative(dirname(layout.vault), layout.anchorsFile))
81
+ ensureDir(dirname(layout.anchorsFile))
77
82
  appendLine(layout.anchorsFile, JSON.stringify({ seq: last.seq, hash: last.hash, at: last.at }))
78
83
  }
79
84
 
@@ -102,8 +107,17 @@ export type AuditVerdict =
102
107
  | { readonly ok: true; readonly records: number }
103
108
  | { readonly ok: false; readonly reason: string }
104
109
 
105
- /** Recomputes the chain and checks every anchor against it. */
110
+ /** Recomputes the chain and checks every anchor against it. A log too damaged to read fails the check. */
106
111
  export function verifyAudit(layout: Layout): AuditVerdict {
112
+ try {
113
+ return verifyChain(layout)
114
+ } catch (error) {
115
+ if (error instanceof TypeVaultError && error.code === 'tampered') return { ok: false, reason: error.message }
116
+ throw error
117
+ }
118
+ }
119
+
120
+ function verifyChain(layout: Layout): AuditVerdict {
107
121
  const records = readAudit(layout)
108
122
  let prev = GENESIS
109
123
  const heads = new Map<number, string>()
@@ -116,12 +130,14 @@ export function verifyAudit(layout: Layout): AuditVerdict {
116
130
  heads.set(record.seq, hash)
117
131
  prev = hash
118
132
  }
119
- const anchors = existsSync(layout.anchorsFile)
120
- ? readFileSync(layout.anchorsFile, 'utf8')
121
- .split('\n')
122
- .filter((line) => line !== '')
123
- .map((line) => AnchorSchema.parse(JSON.parse(line)))
124
- : []
133
+ const anchors = [layout.legacyAnchorsFile, layout.anchorsFile].flatMap((file) =>
134
+ existsSync(file)
135
+ ? readFileSync(file, 'utf8')
136
+ .split('\n')
137
+ .filter((line) => line !== '')
138
+ .map((line) => parseJsonText(file, line, AnchorSchema))
139
+ : [],
140
+ )
125
141
  const broken = anchors.find((anchor) => heads.get(anchor.seq) !== anchor.hash)
126
142
  if (broken !== undefined)
127
143
  return { ok: false, reason: `local log no longer matches the anchor at record ${broken.seq}` }
@@ -1,42 +1,72 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
1
4
  import { defineCommand } from 'citty'
2
5
 
3
6
  import { verifyAudit } from '../../audit/log'
4
- import { adoptCertWrites } from '../../core/adopt'
7
+ import { Admin } from '../../core/admin'
8
+ import { adoptCertWrites, type ExpiredPin } from '../../core/adopt'
5
9
  import { doctor as runDoctor } from '../../core/doctor'
6
- import { initVault } from '../../core/init'
7
- import { layoutFrom, openAdmin, openDirect } from '../context'
10
+ import { TypeVaultError } from '../../core/errors'
11
+ import { founderOf, initGlobalVault, initLocalVault } from '../../core/init'
12
+ import { globalLayout, type Layout, LOCAL_VAULT_DIR, localLayout } from '../../core/layout'
13
+ import { parseEntryName } from '../../core/naming'
14
+ import { Vault } from '../../core/vault'
15
+ import { GrantStore } from '../../daemon/grants'
16
+ import { stopDaemon } from '../../daemon/spawn'
17
+ import { layoutFrom, openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
8
18
  import { csv, note, print, table } from '../output'
19
+ import { ensureIdentity, identityArgs } from './members'
9
20
 
10
21
  export const init = defineCommand({
11
- meta: { name: 'init', description: 'Create a vault and its operator key' },
12
- async run() {
13
- const layout = layoutFrom(process.env)
14
- await initVault(layout.root)
15
- print(`vault created at ${layout.root}`)
22
+ meta: { name: 'init', description: 'Create a vault you own (and your identity, the first time)' },
23
+ args: identityArgs,
24
+ async run({ args }) {
25
+ const env = process.env
26
+ const founder = founderOf(await ensureIdentity(env, args))
27
+ const global = wantsGlobal(env)
28
+ const dir = join(process.cwd(), LOCAL_VAULT_DIR)
29
+ await stopStaleDaemon(global ? globalLayout(env) : localLayout(dir, env))
30
+ const { layout, owner } = global ? await initGlobalVault(founder, env) : await initLocalVault(dir, founder, env)
31
+ await new Admin(await Vault.open(layout, [owner], env)).addTier(STARTER_TIER)
32
+ print(`vault created at ${layout.vault} with tier "${STARTER_TIER}", owned by ${founder.name}`)
16
33
  note(
17
- `operator key: ${layout.operatorKey}\nBack it up offline: it is the only recovery path. Only vault/ is safe to commit.`,
34
+ global
35
+ ? 'It holds no key in the clear: safe to sync with git.'
36
+ : `Commit ${LOCAL_VAULT_DIR}/: it holds no key in the clear.`,
18
37
  )
19
- note('next: typevault group add <name>, then typevault set <name> --type ... --group <name> --stdin')
38
+ note('next: typevault set <name> --stdin (more tiers: typevault tier add <name>)')
20
39
  },
21
40
  })
22
41
 
42
+ /** A daemon still running here served a vault that no longer exists; a new vault can't start beside it. */
43
+ async function stopStaleDaemon(layout: Layout): Promise<void> {
44
+ if (existsSync(layout.ownerFile)) return
45
+ await stopDaemon(layout).catch((error: unknown) => {
46
+ if (!(error instanceof TypeVaultError && error.code === 'not_found')) throw error
47
+ })
48
+ }
49
+
50
+ /** Created by `init` so `set` and `grant` work before any tier design; as the only tier, `set` picks it. */
51
+ const STARTER_TIER = 'default'
52
+
23
53
  const named = { name: { type: 'positional', required: true } } as const
24
54
  const pair = {
25
- group: { type: 'positional', required: true },
55
+ tier: { type: 'positional', required: true },
26
56
  included: { type: 'positional', required: true },
27
57
  } as const
28
58
 
29
- export const group = defineCommand({
30
- meta: { name: 'group', description: 'Manage groups (operator)' },
59
+ export const tier = defineCommand({
60
+ meta: { name: 'tier', description: 'Manage tiers (owner)' },
31
61
  subCommands: {
32
62
  ls: defineCommand({
33
63
  meta: { name: 'ls' },
34
64
  async run() {
35
- const groups = Object.entries((await openDirect(process.env)).state.groups)
65
+ const tiers = Object.entries((await openPublic(process.env)).state.tiers)
36
66
  print(
37
67
  table([
38
- ['GROUP', 'GEN', 'INCLUDES'],
39
- ...groups.map(([name, g]) => [name, String(g.gen), g.includes.join(', ')]),
68
+ ['TIER', 'GEN', 'INCLUDES'],
69
+ ...tiers.map(([name, g]) => [name, String(g.gen), g.includes.join(', ')]),
40
70
  ]),
41
71
  )
42
72
  },
@@ -44,65 +74,73 @@ export const group = defineCommand({
44
74
  add: defineCommand({
45
75
  meta: { name: 'add' },
46
76
  args: named,
47
- run: async ({ args }) => (await openAdmin(process.env)).addGroup(args.name),
77
+ run: async ({ args }) => (await openAdmin(process.env)).addTier(args.name),
48
78
  }),
49
79
  rm: defineCommand({
50
80
  meta: { name: 'rm' },
51
81
  args: named,
52
- run: async ({ args }) => (await openAdmin(process.env)).removeGroup(args.name),
82
+ run: async ({ args }) => (await openAdmin(process.env)).removeTier(args.name),
53
83
  }),
54
84
  include: defineCommand({
55
- meta: { name: 'include', description: '<group> reaches everything <included> reaches' },
85
+ meta: { name: 'include', description: '<tier> reaches everything <included> reaches' },
56
86
  args: pair,
57
- run: async ({ args }) => (await openAdmin(process.env)).include(args.group, args.included),
87
+ run: async ({ args }) => (await openAdmin(process.env)).include(args.tier, args.included),
58
88
  }),
59
89
  exclude: defineCommand({
60
- meta: { name: 'exclude', description: 'Drop an include and rotate the included group' },
90
+ meta: { name: 'exclude', description: 'Drop an include and rotate the included tier' },
61
91
  args: pair,
62
92
  async run({ args }) {
63
- printRotation(args.included, await (await openAdmin(process.env)).exclude(args.group, args.included))
93
+ printRotation(args.included, await (await openAdmin(process.env)).exclude(args.tier, args.included))
64
94
  },
65
95
  }),
66
96
  },
67
97
  })
68
98
 
69
- function printRotation(groupName: string, affected: readonly string[]): void {
70
- print(`rotated ${groupName}`)
99
+ function parseExpiredPin(input: string): ExpiredPin {
100
+ const at = input.lastIndexOf('@')
101
+ const digest = at === -1 ? '' : input.slice(at + 1)
102
+ if (!/^[0-9a-f]{16}$/.test(digest))
103
+ throw new TypeVaultError('invalid', `--adopt-expired expects <name>@<digest> as doctor lists it, got "${input}"`)
104
+ return { name: parseEntryName(input.slice(0, at)), digest }
105
+ }
106
+
107
+ function printRotation(tierName: string, affected: readonly string[]): void {
108
+ print(`rotated ${tierName}`)
71
109
  if (affected.length === 0) return
72
110
  note('Git history keeps the old ciphertext. Rotate these secrets at their source, then re-set them:')
73
111
  for (const name of affected) note(` ${name}`)
74
112
  }
75
113
 
76
114
  export const key = defineCommand({
77
- meta: { name: 'key', description: 'Export or rotate group keys (operator)' },
115
+ meta: { name: 'key', description: 'Rotate tier keys (owner)' },
78
116
  subCommands: {
79
- export: defineCommand({
80
- meta: { name: 'export', description: 'Print a group key for a launcher, CI secret or daemon (TYPEVAULT_KEY)' },
81
- args: named,
82
- run: async ({ args }) => print(await (await openAdmin(process.env)).exportKey(args.name)),
83
- }),
84
117
  rotate: defineCommand({
85
- meta: { name: 'rotate', description: 'New key generation; flags every secret the old key reached' },
118
+ meta: {
119
+ name: 'rotate',
120
+ description: 'Rotate every reachable tier key; flag their secrets for rotation at source',
121
+ },
86
122
  args: named,
87
- run: async ({ args }) => printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name)),
123
+ async run({ args }) {
124
+ printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name))
125
+ },
88
126
  }),
89
127
  },
90
128
  })
91
129
 
92
130
  export const ceiling = defineCommand({
93
- meta: { name: 'ceiling', description: 'The most an admin socket may grant (operator)' },
131
+ meta: { name: 'ceiling', description: 'The most an admin socket may grant (owner)' },
94
132
  subCommands: {
95
133
  ls: defineCommand({
96
134
  meta: { name: 'ls' },
97
135
  async run() {
98
- const ceilings = Object.entries((await openDirect(process.env)).state.ceilings)
99
- print(table([['SOCKET', 'GROUP'], ...ceilings]))
136
+ const ceilings = Object.entries((await openPublic(process.env)).state.ceilings)
137
+ print(table([['SOCKET', 'TIER'], ...ceilings]))
100
138
  },
101
139
  }),
102
140
  set: defineCommand({
103
141
  meta: { name: 'set' },
104
- args: { name: { type: 'positional', required: true }, group: { type: 'positional', required: true } },
105
- run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.group),
142
+ args: { name: { type: 'positional', required: true }, tier: { type: 'positional', required: true } },
143
+ run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.tier),
106
144
  }),
107
145
  rm: defineCommand({
108
146
  meta: { name: 'rm' },
@@ -113,14 +151,14 @@ export const ceiling = defineCommand({
113
151
  })
114
152
 
115
153
  export const signer = defineCommand({
116
- meta: { name: 'signer', description: 'Extra keys allowed to sign entries (operator)' },
154
+ meta: { name: 'signer', description: 'Extra keys allowed to sign entries (owner)' },
117
155
  subCommands: {
118
156
  ls: defineCommand({
119
157
  meta: { name: 'ls' },
120
158
  async run() {
121
- const signers = Object.entries((await openDirect(process.env)).state.signers)
159
+ const signers = Object.entries((await openPublic(process.env)).state.signers)
122
160
  print(
123
- table([['ID', 'GROUPS', 'PUBLIC KEY'], ...signers.map(([id, s]) => [id, s.groups.join(','), s.signPublic])]),
161
+ table([['ID', 'TIERS', 'PUBLIC KEY'], ...signers.map(([id, s]) => [id, s.tiers.join(','), s.signPublic])]),
124
162
  )
125
163
  },
126
164
  }),
@@ -129,9 +167,9 @@ export const signer = defineCommand({
129
167
  args: {
130
168
  id: { type: 'positional', required: true },
131
169
  publicKey: { type: 'positional', required: true, description: 'Base64 Ed25519 public key' },
132
- groups: { type: 'string', required: true, description: 'Comma-separated groups, or *' },
170
+ tiers: { type: 'string', required: true, description: 'Comma-separated tiers, or *' },
133
171
  },
134
- run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.groups)),
172
+ run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.tiers)),
135
173
  }),
136
174
  rm: defineCommand({
137
175
  meta: { name: 'rm' },
@@ -146,22 +184,29 @@ export const doctor = defineCommand({
146
184
  args: {
147
185
  fix: { type: 'boolean' },
148
186
  'adopt-expired': {
149
- type: 'boolean',
150
- description: 'Also keep sealed-grant writes whose certificate expired before adoption',
187
+ type: 'string',
188
+ description:
189
+ 'Comma-separated <name>@<digest> of sealed-grant writes to keep although their certificate expired before adoption, as `doctor --fix` lists them (nothing proves when they were written)',
151
190
  },
152
191
  },
153
192
  async run({ args }) {
193
+ new GrantStore(layoutFrom(process.env).grantsFile)
154
194
  const vault = await openDirect(process.env)
155
- if (args.fix === true)
156
- for (const name of await adoptCertWrites(vault, { expired: args['adopt-expired'] === true }))
157
- print(`adopted sealed write: ${name}`)
195
+ if (args.fix === true) {
196
+ const adoption = await adoptCertWrites(vault, { expired: csv(args['adopt-expired'] ?? '').map(parseExpiredPin) })
197
+ for (const name of adoption.adopted) print(`adopted sealed write: ${name}`)
198
+ for (const write of adoption.expired)
199
+ print(
200
+ `expired sealed write: ${write.name} rev ${write.rev} at ${write.at} (its certificate expired before adoption; keep this exact write with \`--adopt-expired ${write.name}@${write.digest}\` only if you know it was written in time)`,
201
+ )
202
+ }
158
203
  const report = await runDoctor(vault, args.fix === true)
159
204
  for (const problem of report.problems) print(`problem: ${problem.file}: ${problem.reason}`)
160
205
  for (const file of report.mergesResolved) print(`merged: ${file}`)
161
206
  for (const dup of report.duplicatesRemoved) print(`${args.fix === true ? 'removed' : 'duplicate'}: ${dup}`)
162
207
  for (const dup of report.duplicatesKept)
163
208
  print(
164
- `same name in several groups: ${dup} (if the groups are unrelated, reads of it fail: keep one with \`typevault rm <name> --group <g>\`)`,
209
+ `same name in several tiers: ${dup} (if the tiers are unrelated, reads of it fail: keep one with \`typevault rm <name> --tier <g>\`)`,
165
210
  )
166
211
  for (const name of report.needsRotation) print(`needs rotation: ${name}`)
167
212
  const audit = verifyAudit(vault.layout)
@@ -1,41 +1,70 @@
1
- import { existsSync, readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
3
-
4
1
  import { defineCommand } from 'citty'
5
2
  import { z } from 'zod'
6
3
 
4
+ import { machineKeys } from '../../access/keys'
5
+ import { parseTtl } from '../../access/scope'
6
+ import { decodeSecretKey } from '../../core/crypto'
7
7
  import { TypeVaultError } from '../../core/errors'
8
+ import { localLayout } from '../../core/layout'
8
9
  import { isDaemonAlive } from '../../daemon/client'
9
10
  import { startDaemon } from '../../daemon/daemon'
10
- import { ensureDaemon } from '../../daemon/spawn'
11
- import { adminCall, layoutFrom } from '../context'
12
- import { note, print } from '../output'
11
+ import { ensureDaemon, stopDaemon } from '../../daemon/spawn'
12
+ import { adminCall, DEFAULT_SESSION_MS, layoutFrom } from '../context'
13
+ import { note, print, readStdin } from '../output'
13
14
 
14
- const port = (value: string | undefined): number | undefined =>
15
- value === undefined || value === '' ? undefined : z.coerce.number().int().parse(value)
15
+ function promptPortOf(value: string | undefined): number | undefined {
16
+ if (value === undefined || value === '') return undefined
17
+ const port = Number(value)
18
+ if (!Number.isInteger(port) || port < 0 || port > 65_535) {
19
+ throw new TypeVaultError('invalid', `TYPEVAULT_PROMPT_PORT must be a port number, not "${value}"`)
20
+ }
21
+ return port
22
+ }
16
23
 
17
24
  export const daemon = defineCommand({
18
25
  meta: { name: 'daemon', description: 'The background issuer (usually started automatically)' },
19
26
  subCommands: {
20
27
  run: defineCommand({
21
28
  meta: { name: 'run', description: 'Run in the foreground' },
22
- async run() {
29
+ args: {
30
+ 'key-stdin': { type: 'boolean', description: 'Read an unlocked member key from stdin (used by unlock)' },
31
+ ttl: { type: 'string', description: 'Stop after this long, e.g. 8h (used by unlock)' },
32
+ vault: {
33
+ type: 'string',
34
+ description: 'The project vault to serve, instead of the one found here (used by unlock)',
35
+ },
36
+ 'source-lock': {
37
+ type: 'string',
38
+ description: 'Serve only while the daemon holding this lock runs (used to share a session with a worktree)',
39
+ },
40
+ },
41
+ async run({ args }) {
23
42
  const env = process.env
24
- const promptPort = port(env['TYPEVAULT_PROMPT_PORT'])
43
+ const promptPort = promptPortOf(env['TYPEVAULT_PROMPT_PORT'])
25
44
  const publicUrl = env['TYPEVAULT_PUBLIC_URL']
45
+ const fromStdin = args['key-stdin'] === true
46
+ const ttlMs = args.ttl === undefined ? undefined : parseTtl(args.ttl)
47
+ const sourceLock = args['source-lock']
26
48
  const running = await startDaemon({
27
- root: layoutFrom(env).root,
49
+ layout: args.vault === undefined ? layoutFrom(env) : localLayout(args.vault, env),
28
50
  env,
51
+ keys: fromStdin ? [decodeSecretKey(await readStdin())] : machineKeys(env),
29
52
  prompt: {
30
53
  ...(promptPort === undefined ? {} : { port: promptPort }),
31
54
  ...(publicUrl === undefined ? {} : { publicUrl }),
32
55
  },
56
+ ...(fromStdin
57
+ ? { session: { ttlMs: ttlMs ?? DEFAULT_SESSION_MS, ...(sourceLock === undefined ? {} : { sourceLock }) } }
58
+ : {}),
33
59
  })
34
- note(`typevault daemon ready (admin sockets: ${running.ceilings.map((c) => c.name).join(', ')})`)
60
+ note(`typevault daemon ready (admin sockets: ${running.ceilings.map((c) => c.name).join(', ') || 'none'})`)
35
61
  const { promise, resolve } = Promise.withResolvers<void>()
36
62
  process.once('SIGINT', resolve)
37
63
  process.once('SIGTERM', resolve)
64
+ void running.stopRequested.then(resolve)
65
+ const expiry = ttlMs === undefined ? undefined : setTimeout(resolve, ttlMs)
38
66
  await promise
67
+ clearTimeout(expiry)
39
68
  await running.stop()
40
69
  },
41
70
  }),
@@ -45,11 +74,7 @@ export const daemon = defineCommand({
45
74
  }),
46
75
  stop: defineCommand({
47
76
  meta: { name: 'stop' },
48
- async run() {
49
- const pidFile = join(layoutFrom(process.env).run, 'daemon.pid')
50
- if (!existsSync(pidFile)) throw new TypeVaultError('not_found', 'no daemon is running')
51
- process.kill(z.coerce.number().int().parse(readFileSync(pidFile, 'utf8')), 'SIGTERM')
52
- },
77
+ run: async () => stopDaemon(layoutFrom(process.env)),
53
78
  }),
54
79
  status: defineCommand({
55
80
  meta: { name: 'status' },