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
package/README.md CHANGED
@@ -1,14 +1,30 @@
1
- # typevault
1
+ # TypeVault
2
2
 
3
- A CLI-first secrets vault for agents. `.env` exposes too much; password managers are too heavy.
3
+ **Secrets for agents, not for transcripts.** A CLI-first vault that gives each agent session only the secrets its
4
+ grant allows. Values reach programs, never the model, and every read is logged.
4
5
 
5
- > Each session gets exactly the secrets its grant allows, every read leaves a trail, and secrets stay out of transcripts.
6
+ [![npm version](https://img.shields.io/npm/v/typevault?color=cb3837&logo=npm)](https://www.npmjs.com/package/typevault) [![MIT license](https://img.shields.io/badge/license-MIT-blue)](#license)
6
7
 
7
- - **Git-friendly:** the vault is a directory of age-encrypted, signed files. Only `vault/` is safe to commit, and it is.
8
- - **Groups are keys:** each group has a keypair; groups can include others (`trusted` includes `member`). Access is enforced by cryptography, not by checks.
9
- - **Grants, not keys:** agents hold short-lived grants. A daemon holds the keys, serves values and audits every read.
10
- - **No human in the loop:** an operator-signed ceiling caps what each admin socket may grant.
11
- - **Reading = using:** if a grant can use a secret it can read it, so put secrets in a group only if that group may see them.
8
+ <picture>
9
+ <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/overview-dark.png">
10
+ <img alt="An agent session reads through the daemon with a grant; the daemon holds the unlocked keys, decrypts the vault committed in git and logs every read" src="docs/diagrams/overview-light.png">
11
+ </picture>
12
+
13
+ ## Why TypeVault
14
+
15
+ | | |
16
+ | ---------------------- | -------------------------------------------------------------------------------------------------- |
17
+ | **Grants, not keys** | Agents get a short-lived grant scoped to tiers, names and a TTL. Revoking it takes effect at once. |
18
+ | **Tiers are keys** | Each tier has its own keypair, so access comes from holding a key, not from a permission check. |
19
+ | **Your own key** | Every person and machine has its own key. Nobody passes a shared key or password around. |
20
+ | **Commit it to git** | `.typevault/` holds only ciphertext, wrapped keys and signed files. Rollbacks are refused. |
21
+ | **Out of transcripts** | `run` passes secrets as env vars and redacts the output. The model never sees a value. |
22
+ | **Ask a human** | A one-time link where the browser encrypts the value before it is sent. |
23
+ | **Audited** | Every read through a live grant is logged with its label and reason, in a verifiable hash chain. |
24
+ | **Imports** | 1Password straight from the app, plus `.env`, Bitwarden, LastPass, KeePass and CSV. |
25
+
26
+ TypeVault is general-purpose: any agent runtime can use it. [TypeClaw](https://github.com/typeclaw/typeclaw) is its
27
+ first consumer, sandboxing each session and mounting only the agent socket.
12
28
 
13
29
  ## Install
14
30
 
@@ -16,59 +32,46 @@ A CLI-first secrets vault for agents. `.env` exposes too much; password managers
16
32
  bun add -g typevault
17
33
  ```
18
34
 
19
- ## Quick start
35
+ Requires Bun ≥ 1.3.
20
36
 
21
- ```sh
22
- typevault init # creates ~/.config/typevault (TYPEVAULT_DIR overrides)
23
- typevault group add member
24
- typevault group add trusted
25
- typevault group include trusted member # trusted reaches everything member reaches
37
+ ## Quickstart
26
38
 
27
- printf '%s' "$OPENAI_KEY" | typevault set openai --type api_key --group member --stdin
28
- typevault set github/bot --type password --group member --field username=bot --stdin < password.txt
29
- echo '{"access_token":"…","refresh_token":"…"}' | typevault set google --type oauth --group member --stdin-json
39
+ ```sh
40
+ typevault init # creates .typevault/ here; the first time, also your password and Secret Key
41
+ typevault unlock # once per session (8h by default); your agents read through it
30
42
 
31
- # Hand an agent a grant instead of a key (the daemon starts automatically)
32
- export TYPEVAULT_GRANT=$(typevault grant --group member --label session:abc)
43
+ printf '%s' "$OPENAI_KEY" | typevault set typevault://openai --preset api_key --stdin
44
+ typevault set typevault://anthropic --preset api_key # from a terminal: type it in a one-time local page
33
45
 
34
- typevault ls
35
- typevault run -- psql # secrets arrive as env vars; output is redacted
36
- typevault run --only github/bot -- agent-browser fill @e3 "$GITHUB_BOT_PASSWORD"
46
+ export TYPEVAULT_GRANT=$(typevault grant --tier default --label session:abc)
47
+ typevault run -- ./deploy.sh # OPENAI and ANTHROPIC arrive as env vars; output is redacted
48
+ typevault whoami # live grant, sealed grant, unlocked session or machine key
37
49
  ```
38
50
 
39
- ## Naming
40
-
41
- `<service>[/<account>]#<field>`: `openai`, `github/bot#password`, `github/personal#totp`.
42
- No environments, no domains, no group in the name. Fields come from the type:
43
-
44
- | Type | Fields (default first) |
45
- | ---------- | ---------------------------------------------------------------------------- |
46
- | `password` | password, username, totp, url |
47
- | `api_key` | key |
48
- | `oauth` | access_token, refresh_token, expires_at, token_url, client_id, client_secret |
49
- | `ssh` | private_key, public_key |
50
- | `totp` | seed |
51
- | `note` | text |
52
-
53
- Env names are derived: `github/bot#password` becomes `GITHUB_BOT_PASSWORD`. Override the main field's name with `--env`.
54
- In `run`, TOTP fields carry the current code, never the seed. Secret fields are never accepted as `--field` arguments
55
- (they would land in `ps` and shell history): pass them with `--stdin` or `--stdin-json`.
56
-
57
- ### What `run` loads
58
-
59
- A lower group can write entries a higher group reads, so `run` only loads, in bulk, entries from the groups the
60
- caller holds directly. An entry from an included group is loaded only when `--only` names it exactly
61
- (`--only github/bot`, not `--only 'github/*'`). Two entries setting the same variable is an error, and variables that
62
- change how programs load code or route traffic (`PATH`, `LD_*`, `NODE_OPTIONS`, `GIT_*`, `HTTPS_PROXY`, ...) are never set
63
- from the vault. The child never receives `TYPEVAULT_*` variables.
64
-
65
- An entry from an included group keeps its `--env` override only when the operator, or a key at least as privileged as
66
- the caller, wrote it; otherwise it gets the derived name. The operator holds no group directly, so the operator's own `run` loads only what `--only` names.
67
-
68
- When the same name exists in several groups, the copy in the higher group wins; timestamps never decide. If two
69
- unrelated groups hold it, reads of that name fail until the operator keeps one: `typevault rm <name> --group <g>`.
70
-
71
- ## Grants
51
+ Commands use the nearest project vault, like `bun` and `npm`; `-g` selects the global one in `~/.typevault`.
52
+
53
+ ## How it works
54
+
55
+ ### Grants
56
+
57
+ An issuer (you, TypeClaw or CI) mints a grant, and the agent reads through it. The daemon checks every read against
58
+ the grant, logs it, and refuses it once the grant is revoked, along with every grant derived from it.
59
+
60
+ ```mermaid
61
+ sequenceDiagram
62
+ participant I as Issuer
63
+ participant D as Daemon
64
+ participant A as Agent
65
+ I->>D: grant --tier member --only 'typevault://github/*' --ttl 30m --label ci:deploy
66
+ Note over I,D: through its admin socket, never above its ceiling
67
+ D-->>I: live grant (tvl1.…)
68
+ I->>A: TYPEVAULT_GRANT
69
+ A->>D: read typevault://github/bot, with a reason
70
+ D->>D: check tiers, names and TTL, then log the read
71
+ D-->>A: value, into run's child only
72
+ I->>D: grant revoke --label ci:deploy
73
+ A-xD: the next read is refused, as are reads with derived grants
74
+ ```
72
75
 
73
76
  | | Live (default) | Sealed (`--sealed`) |
74
77
  | ---------------- | ----------------------------- | ------------------------------ |
@@ -77,93 +80,131 @@ unrelated groups hold it, reads of that name fail until the operator keeps one:
77
80
  | TTL / revocation | enforced / instant | advisory / impossible |
78
81
  | Use for | laptops, containers, typeclaw | CI, one-shot containers |
79
82
 
80
- A sealed grant can write, within its groups and `--only`, until its certificate expires by the **reader's** clock.
81
- A daemon (every minute) or `typevault doctor --fix` adopts those writes by re-signing them. Writes nobody adopts
82
- before expiry stop being trusted; the operator can still keep them with `typevault doctor --fix --adopt-expired`.
83
+ More: [grants, ceilings and the SDK](docs/grants.md).
84
+
85
+ ### Tiers and members
86
+
87
+ A secret is encrypted to its tier. Tier keys are wrapped to members, and a person's member key is sealed by their
88
+ password and a Secret Key that stays on their device. Adding or removing a member rotates every tier they reach.
89
+
90
+ <picture>
91
+ <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/keys-dark.png">
92
+ <img alt="A person's password and Secret Key unseal their member key, which unwraps tier keys; a tier key unwraps the tiers it includes and decrypts its entries" src="docs/diagrams/keys-light.png">
93
+ </picture>
83
94
 
84
95
  ```sh
85
- typevault grant --group member --only 'github/*' --ttl 30m --label ci:deploy
86
- typevault grant ls
87
- typevault grant revoke --label ci:deploy # also revokes grants derived from it
88
- TYPEVAULT_GRANT=@/run/agent/grant typevault get github/bot
96
+ typevault tier add trusted
97
+ typevault tier include trusted default # trusted reaches everything default reaches
98
+ typevault join # a teammate, in their clone: prints the line below
99
+ typevault member add bob tvp1:... --tier default # rotates every tier bob reaches
100
+ typevault join --machine --name ci # CI or an agent host: no password, its own key
89
101
  ```
90
102
 
91
- `TYPEVAULT_GRANT` takes a live grant (`tvl1.…`), a sealed one (`tvg1:…`) or `@path` to a file holding either.
92
- Without it, the CLI uses local keys (direct mode: the operator, or a launcher with `TYPEVAULT_KEY`).
103
+ More: [vaults, members and git history](docs/vaults-and-members.md).
93
104
 
94
- ### Ceilings
105
+ ### Running with secrets
95
106
 
96
- Each admin socket (`run/admin-<name>.sock`) may issue grants only up to its ceiling, signed by the operator:
107
+ `run` loads what the grant reaches as env vars, never sets loader variables like `PATH` or `NODE_OPTIONS`, and
108
+ redacts the child's output. A variable whose value is a `typevault://` reference gets that field, so you pick the name.
97
109
 
98
- ```sh
99
- typevault ceiling set bot member # admin-bot.sock can grant member and below
100
- TYPEVAULT_CEILING=bot typevault grant --group member
110
+ ```mermaid
111
+ flowchart LR
112
+ agent[Agent] -- "typevault run -- ./deploy.sh" --> load["Load entries and typevault:// references"]
113
+ daemon[Daemon] -- "values, through the grant" --> load
114
+ load -- "env vars, never PATH, NODE_OPTIONS, ..." --> child["./deploy.sh"]
115
+ child -- "stdout, stderr" --> redact[Redact values]
116
+ redact -- "masked output" --> transcript[Agent's transcript]
101
117
  ```
102
118
 
103
- The socket is the caller's identity, so protect it with file permissions or by mounting it only where it belongs.
104
- A capped socket lists and revokes only the grants it issued, and only the uncapped operator socket reads the audit trail.
105
- Processes under one OS user that can reach the same socket share its ceiling; per-session enforcement needs isolation
106
- (typeclaw sandboxes each session and mounts only the agent socket).
119
+ ```sh
120
+ DATABASE_URL=typevault://postgres/prod#url typevault run -- ./migrate.sh
121
+ typevault run --only typevault://github/bot -- ./login.sh
122
+ ```
107
123
 
108
- ## Asking a human for a secret
124
+ More: [naming, field types and what `run` loads](docs/entries.md).
125
+
126
+ ### Asking a human
127
+
128
+ `typevault request` gives the agent a one-time URL and a match code to pass on. The browser encrypts the value
129
+ before sending it, so tunnels and proxies carry only ciphertext.
130
+
131
+ ```mermaid
132
+ sequenceDiagram
133
+ participant A as Agent
134
+ participant D as Daemon
135
+ actor H as Human
136
+ participant B as Browser
137
+ A->>D: request resend --preset api_key --reason "…"
138
+ D-->>A: one-time URL and match code
139
+ A->>H: URL and match code
140
+ H->>B: opens the URL, checks the code, enters the value
141
+ B->>B: encrypts to the tier
142
+ B->>D: ciphertext only, safe through tunnels and proxies
143
+ D->>D: decrypts, checks it is the requested entry, re-encrypts, signs, stores
144
+ D-->>A: stored as typevault://resend, the value never comes back
145
+ ```
109
146
 
110
147
  ```sh
111
- typevault request resend --type api_key --reason "send the weekly digest"
148
+ typevault request resend --preset api_key --reason "send the weekly digest"
112
149
  ```
113
150
 
114
- The daemon serves a one-time page (`TYPEVAULT_PROMPT_PORT`, `TYPEVAULT_PUBLIC_URL` for tunnels). The browser encrypts the
115
- value to the group before submitting, so the plaintext never reaches the server, logs or the model.
151
+ <picture>
152
+ <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/prompt-dark.png">
153
+ <img width="480" alt="The secret request page: the entry name, the agent's reason, who asked and which tier can read it, the match code to compare with the chat, a secret field and an Encrypt and submit button" src="docs/diagrams/prompt-light.png">
154
+ </picture>
116
155
 
117
- ## Redaction
156
+ ## SDK
118
157
 
119
- - `typevault run` redacts its child's stdout and stderr by default.
120
- - `cmd | typevault redact` scrubs anything your grant has read.
121
- - `typevault scrub <files>` rewrites transcripts in place.
122
- - `typevault get` prints the value on purpose; prefer `run`.
158
+ The same access, in-process (Bun only):
123
159
 
124
- ## Operator tasks
160
+ ```ts
161
+ import { createClient, parseEntryName } from 'typevault'
162
+ import { createAdmin } from 'typevault/admin'
163
+ import { createRedactor } from 'typevault/redact'
125
164
 
126
- ```sh
127
- typevault key export member # TYPEVAULT_KEY for a CI launcher or remote daemon
128
- typevault key rotate member # new generation; lists every secret to rotate at its source
129
- typevault group exclude trusted member # drop an include (rotates member)
130
- typevault signer add ci-bot <ed25519-public-key> --groups member
131
- typevault import 1password export.1pux --group member
132
- typevault doctor --fix # verify signatures, resolve git merges and duplicates
133
- typevault audit --verify
165
+ // An issuer issues a grant within its socket's ceiling...
166
+ const grant = await createAdmin({ ceiling: 'bot' }).grant({ tiers: ['member'], ttl: '30m', label: 'session:abc' })
167
+
168
+ // ...and the agent side reads through it (live via the daemon, or sealed in-process).
169
+ const vault = await createClient({ grant })
170
+ const { fields } = await vault.get(parseEntryName('typevault://openai'), 'send the weekly digest')
171
+
172
+ // Nothing is redacted for you: scrub anything that can reach output.
173
+ const redactor = createRedactor(await vault.readValues())
134
174
  ```
135
175
 
136
- Operator key rotation and recovery are manual: back up `keys/operator.key` offline.
176
+ Options: [SDK options](docs/grants.md#sdk-options). [`skills/typevault`](./skills/typevault) teaches coding agents to
177
+ use grants, `run` and references.
137
178
 
138
- ## Layout
179
+ ## Documentation
139
180
 
140
- ```
141
- $TYPEVAULT_DIR/
142
- vault/ # ciphertext only, safe to commit
143
- entries/ # one signed file per entry, opaque names
144
- groups/ # wrapped group keys
145
- groups.json signers.json ceilings.json # operator-signed
146
- operator.json audit-anchors.jsonl
147
- keys/ # private keys (0600), never commit
148
- audit/ # full local audit log
149
- run/ # sockets, lock, grants, staged transactions, revision high-water marks
150
- ```
181
+ - [Vaults and members](docs/vaults-and-members.md): project and global vaults, unlocking, joining, git history
182
+ - [Entries and `run`](docs/entries.md): naming, field types and presets, env names, references, redaction
183
+ - [Grants](docs/grants.md): live and sealed grants, ceilings, asking a human, SDK options
184
+ - [Owner tasks and imports](docs/owner-tasks.md): rotation, audit, identity backup, 1Password and file imports
185
+ - [Reference](docs/reference.md): environment variables, on-disk layout, known limits
151
186
 
152
- ## Git history
187
+ ## Development
153
188
 
154
- Old ciphertext stays in history forever. If a key leaks, rotate the key **and** every secret it could reach.
155
- Removing an entry does not remove it from history.
189
+ ```sh
190
+ git clone https://github.com/typeclaw/typevault
191
+ cd typevault
192
+ bun install
193
+ bun test
194
+ ```
156
195
 
157
- Every old revision is still validly signed, so each machine remembers the newest revision it has seen of every entry
158
- and manifest, and every entry it deleted, and refuses older or deleted ones restored from history. A fresh clone trusts
159
- what it first sees.
196
+ Pre-commit checks (all must pass):
197
+
198
+ ```sh
199
+ bun run typecheck
200
+ bun run lint
201
+ bun run format:check
202
+ ```
160
203
 
161
- ## Known limits
204
+ ## Acknowledgments
162
205
 
163
- - Redaction is best effort: values shorter than 4 characters, hex or composed encodings (such as HTTP Basic auth) can slip
164
- through. Prefer `run` over `get`.
165
- - The local audit chain is unkeyed: a process running as the same user can rewrite records since the last anchor.
166
- - Same-user processes that can reach one admin socket share its ceiling; isolate sessions to enforce more.
206
+ - **Encryption** is [age](https://age-encryption.org), via [age-encryption](https://github.com/FiloSottile/typage) by [@FiloSottile](https://github.com/FiloSottile).
207
+ - **Signatures and hashing** come from [@noble/curves](https://github.com/paulmillr/noble-curves) and [@noble/hashes](https://github.com/paulmillr/noble-hashes) by [@paulmillr](https://github.com/paulmillr).
167
208
 
168
209
  ## License
169
210
 
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI-first secrets vault for agents",
5
+ "homepage": "https://github.com/typeclaw/typevault#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/typeclaw/typevault/issues"
8
+ },
5
9
  "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/typeclaw/typevault.git"
13
+ },
6
14
  "bin": {
7
15
  "typevault": "src/cli/index.ts"
8
16
  },
@@ -12,7 +20,10 @@
12
20
  ],
13
21
  "type": "module",
14
22
  "exports": {
15
- ".": "./src/index.ts"
23
+ ".": "./src/index.ts",
24
+ "./admin": "./src/admin.ts",
25
+ "./owner": "./src/owner.ts",
26
+ "./redact": "./src/redact/index.ts"
16
27
  },
17
28
  "scripts": {
18
29
  "typecheck": "tsc --noEmit",
@@ -23,6 +34,7 @@
23
34
  "test": "bun test"
24
35
  },
25
36
  "dependencies": {
37
+ "@1password/sdk": "^0.5.0",
26
38
  "@noble/curves": "^2.4.0",
27
39
  "@noble/hashes": "^2.4.0",
28
40
  "@scure/base": "^2.4.0",
package/src/access/env.ts CHANGED
@@ -1,26 +1,36 @@
1
1
  import { TypeVaultError } from '../core/errors'
2
- import { deriveEnvName, isReservedEnvName, primaryField } from '../core/naming'
2
+ import {
3
+ deriveEnvName,
4
+ type EntryName,
5
+ entryPattern,
6
+ defaultField,
7
+ defaultFieldOf,
8
+ type Field,
9
+ fieldValue,
10
+ fieldStrings,
11
+ resolveField,
12
+ hasRefScheme,
13
+ isReservedEnvName,
14
+ parseEntryRef,
15
+ } from '../core/naming'
3
16
  import { parseTotpSeed, totpCode } from '../otp/totp'
4
17
  import type { EntryValue } from './types'
5
18
 
6
- const isTotpField = (value: EntryValue, field: string): boolean =>
7
- (value.type === 'totp' && field === 'seed') || (value.type === 'password' && field === 'totp')
8
-
9
19
  /**
10
- * Which entries `run` may put in a child's env. A lower group can write entries a higher one reads, so only the
11
- * runner's own groups load in bulk; an entry from an included group loads only when `--only` names it exactly.
20
+ * Which entries `run` may put in a child's env. A lower tier can write entries a higher one reads, so only the
21
+ * runner's own tiers load in bulk; an entry from an included tier loads only when `--only` names it exactly.
12
22
  */
13
- export type EnvPolicy = { readonly ownGroups: readonly string[]; readonly explicit: readonly string[] }
23
+ export type EnvPolicy = { readonly ownTiers: readonly string[]; readonly explicit: readonly string[] }
14
24
 
15
25
  export const explicitNames = (only: readonly string[]): readonly string[] =>
16
- only.filter((pattern) => !/[*?[\]{}]/.test(pattern))
26
+ only.filter((pattern) => !/[*?[\]{}]/.test(pattern)).map(entryPattern)
17
27
 
18
28
  export const envEligible = (value: EntryValue, policy: EnvPolicy): boolean =>
19
- policy.ownGroups.includes(value.group) || policy.explicit.includes(value.name)
29
+ policy.ownTiers.includes(value.tier) || policy.explicit.includes(value.name)
20
30
 
21
31
  /**
22
32
  * The environment `typevault run` gives a child: one variable per non-empty field, named by the entry's
23
- * `--env` override (primary field) or derived from the name. TOTP fields load the current code, never the seed.
33
+ * `--env` override (default field) or derived from the name. TOTP fields load the current code, never the seed.
24
34
  * Two entries producing the same variable is a conflict, never a silent override.
25
35
  */
26
36
  export function envFor(values: readonly EntryValue[], now: Date, policy: EnvPolicy): Readonly<Record<string, string>> {
@@ -28,24 +38,74 @@ export function envFor(values: readonly EntryValue[], now: Date, policy: EnvPoli
28
38
  const owner = new Map<string, string>()
29
39
  for (const value of values.filter((candidate) => envEligible(candidate, policy))) {
30
40
  for (const [field, raw] of Object.entries(value.fields)) {
31
- if (raw === '') continue
32
- // An entry from an included group may pick its variable name only if its writer is at least as privileged
41
+ if (fieldValue(raw) === '') continue
42
+ // An entry from an included tier may pick its variable name only if its writer is at least as privileged
33
43
  // as the runner; otherwise it gets the derived name, so a lower writer can't aim it at OPENAI_BASE_URL.
34
44
  const ownOverride =
35
45
  value.env !== undefined &&
36
- field === primaryField(value.type) &&
37
- (policy.ownGroups.includes(value.group) || value.trustedWriter === true)
46
+ (policy.ownTiers.includes(value.tier) || value.trustedWriter === true) &&
47
+ field === defaultFieldOf(value.fields)
38
48
  const name = ownOverride && value.env !== undefined ? value.env : deriveEnvName(value.name, field)
39
- if (isReservedEnvName(name)) continue
49
+ if (name === undefined || isReservedEnvName(name)) continue
40
50
  const previous = owner.get(name)
41
51
  if (previous !== undefined) throw new TypeVaultError('conflict', `${previous} and ${value.name} both set ${name}`)
42
52
  owner.set(name, value.name)
43
- env[name] = isTotpField(value, field) ? totpCode(parseTotpSeed(raw), now) : raw
53
+ env[name] = readField(raw, now)
44
54
  }
45
55
  }
46
56
  return env
47
57
  }
48
58
 
59
+ export type ResolvedRefs = { readonly env: Readonly<Record<string, string>>; readonly values: readonly EntryValue[] }
60
+
61
+ /**
62
+ * Replaces each variable whose whole value is a `typevault://` reference (`FOO=typevault://github/bot#password`)
63
+ * with the referenced field, the default one when none is named. The caller picked the variable, but a lower tier
64
+ * can still write the value, so loader variables are refused here as they are for entries.
65
+ */
66
+ export async function resolveEnvRefs(
67
+ env: Readonly<Record<string, string | undefined>>,
68
+ get: (name: EntryName) => Promise<EntryValue>,
69
+ now: Date,
70
+ ): Promise<ResolvedRefs> {
71
+ const resolved: Record<string, string> = {}
72
+ const values: EntryValue[] = []
73
+ for (const [variable, raw] of Object.entries(env)) {
74
+ if (raw === undefined || !hasRefScheme(raw)) continue
75
+ // Programs read some of these in lowercase too (curl's http_proxy), so the check ignores case.
76
+ if (isReservedEnvName(variable.toUpperCase()))
77
+ throw new TypeVaultError('invalid', `${variable} is reserved: run never sets it from the vault`)
78
+ const ref = parseEntryRef(raw)
79
+ const value = await get(ref.name)
80
+ const wanted = ref.field ?? defaultField(value.fields, value.name)
81
+ const secret = resolveField(value.fields, wanted)
82
+ if (secret === undefined) throw new TypeVaultError('not_found', `${value.name} has no field "${wanted}"`)
83
+ resolved[variable] = readField(secret, now)
84
+ values.push(value)
85
+ }
86
+ return { env: resolved, values }
87
+ }
88
+
49
89
  /** Secret values handed to the child: the injected env values plus TOTP seeds, for redaction. */
50
90
  export const secretValues = (values: readonly EntryValue[]): readonly string[] =>
51
- values.flatMap((value) => Object.values(value.fields).filter((raw) => raw !== ''))
91
+ values.flatMap((value) =>
92
+ Object.values(value.fields)
93
+ .flatMap(fieldStrings)
94
+ .filter((raw) => raw !== ''),
95
+ )
96
+
97
+ function readField(field: Field, now: Date): string {
98
+ switch (field.type) {
99
+ case 'totp':
100
+ return totpCode(parseTotpSeed(field.value), now)
101
+ case 'secret':
102
+ case 'text':
103
+ case 'oauth':
104
+ return fieldValue(field)
105
+ default:
106
+ return assertNever(field)
107
+ }
108
+ }
109
+ function assertNever(value: never): never {
110
+ throw new TypeVaultError('invalid', `unexpected field ${JSON.stringify(value)}`)
111
+ }
@@ -1,18 +1,18 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
3
-
4
1
  import { decodeSecretKey, type SecretKey } from '../core/crypto'
5
- import type { Layout } from '../core/layout'
2
+ import { TypeVaultError } from '../core/errors'
3
+ import { readIdentity } from '../core/identity'
6
4
 
7
- /** `TYPEVAULT_KEY` alone when set; otherwise the operator key and group keys in the key directory. */
8
- export function loadLocalKeys(layout: Layout, env: Readonly<Record<string, string | undefined>>): readonly SecretKey[] {
5
+ /**
6
+ * The member keys this process holds without anyone typing a password: `TYPEVAULT_KEY`, else a machine identity.
7
+ * A human identity yields nothing here; it is unlocked once with `typevault unlock`.
8
+ */
9
+ export function machineKeys(env: Readonly<Record<string, string | undefined>>): readonly SecretKey[] {
9
10
  const explicit = env['TYPEVAULT_KEY']
10
- if (explicit !== undefined && explicit !== '') return [decodeSecretKey(explicit)]
11
- const operator = existsSync(layout.operatorKey) ? [decodeSecretKey(readFileSync(layout.operatorKey, 'utf8'))] : []
12
- const groups = existsSync(layout.groupKeys)
13
- ? readdirSync(layout.groupKeys)
14
- .filter((file) => file.endsWith('.key'))
15
- .map((file) => decodeSecretKey(readFileSync(join(layout.groupKeys, file), 'utf8')))
16
- : []
17
- return [...operator, ...groups]
11
+ if (explicit !== undefined && explicit !== '') {
12
+ const key = decodeSecretKey(explicit)
13
+ if (key.role.kind !== 'member') throw new TypeVaultError('invalid', 'TYPEVAULT_KEY must be a member key')
14
+ return [key]
15
+ }
16
+ const identity = readIdentity(env)
17
+ return identity?.kind === 'machine' ? [decodeSecretKey(identity.key)] : []
18
18
  }
@@ -1,12 +1,12 @@
1
1
  import { z } from 'zod'
2
2
 
3
- import { type EntryType, isEntryType, parseEntryName } from '../core/naming'
3
+ import { parseEntryName } from '../core/naming'
4
+ import { FieldsSchema } from '../core/payload'
4
5
  import type { EntrySummary, EntryValue } from './types'
5
6
 
6
7
  const SummaryShape = {
7
8
  name: z.string().transform((name) => parseEntryName(name)),
8
- type: z.string().refine(isEntryType),
9
- group: z.string(),
9
+ tier: z.string(),
10
10
  rev: z.number().int(),
11
11
  tags: z.array(z.string()),
12
12
  rotated: z.string(),
@@ -18,26 +18,20 @@ export const EntryValueSchema = z.object({
18
18
  ...SummaryShape,
19
19
  id: z.string(),
20
20
  created: z.string(),
21
- fields: z.record(z.string(), z.string()),
21
+ fields: FieldsSchema,
22
22
  env: z.string().optional(),
23
23
  origin: z.string().optional(),
24
24
  trustedWriter: z.boolean().optional(),
25
25
  })
26
26
 
27
- const entryType = (type: string): EntryType => {
28
- if (isEntryType(type)) return type
29
- throw new TypeError(`unknown entry type ${type}`)
30
- }
31
-
32
27
  export function toSummaryValue(parsed: z.infer<typeof EntrySummarySchema>): EntrySummary {
33
- return { ...parsed, type: entryType(parsed.type) }
28
+ return parsed
34
29
  }
35
30
 
36
31
  export function toEntryValue(parsed: z.infer<typeof EntryValueSchema>): EntryValue {
37
- const { env, origin, type, trustedWriter, ...rest } = parsed
32
+ const { env, origin, trustedWriter, ...rest } = parsed
38
33
  return {
39
34
  ...rest,
40
- type: entryType(type),
41
35
  ...(env === undefined ? {} : { env }),
42
36
  ...(origin === undefined ? {} : { origin }),
43
37
  ...(trustedWriter === undefined ? {} : { trustedWriter }),
@@ -1,20 +1,20 @@
1
1
  import { TypeVaultError } from '../core/errors'
2
2
  import { type EntryName, matchesOnly } from '../core/naming'
3
- import { reachesGroup, type VaultState } from '../core/state'
3
+ import { reachesTier, type VaultState } from '../core/state'
4
4
 
5
- /** What one grant allows: entries in groups it reaches, optionally narrowed by name patterns. */
6
- export type GrantScope = { readonly groups: readonly string[]; readonly only: readonly string[] }
5
+ /** What one grant allows: entries in tiers it reaches, optionally narrowed by name patterns. */
6
+ export type GrantScope = { readonly tiers: readonly string[]; readonly only: readonly string[] }
7
7
 
8
8
  /** A derived grant must satisfy its own scope and every ancestor's. Empty chain = direct mode, everything. */
9
9
  export type ScopeChain = readonly GrantScope[]
10
10
 
11
- export const allowsGroup = (chain: ScopeChain, state: VaultState, group: string): boolean =>
12
- chain.every((scope) => reachesGroup(state.groups, scope.groups, group))
11
+ export const allowsTier = (chain: ScopeChain, state: VaultState, tier: string): boolean =>
12
+ chain.every((scope) => reachesTier(state.tiers, scope.tiers, tier))
13
13
 
14
- export const allowsEntry = (chain: ScopeChain, state: VaultState, group: string, name: EntryName): boolean =>
14
+ export const allowsEntry = (chain: ScopeChain, state: VaultState, tier: string, name: EntryName): boolean =>
15
15
  chain.every(
16
16
  (scope) =>
17
- reachesGroup(state.groups, scope.groups, group) && (scope.only.length === 0 || matchesOnly(name, scope.only)),
17
+ reachesTier(state.tiers, scope.tiers, tier) && (scope.only.length === 0 || matchesOnly(name, scope.only)),
18
18
  )
19
19
 
20
20
  const UNITS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const
@@ -31,8 +31,13 @@ export function parseTtl(text: string): number {
31
31
  case 's':
32
32
  case 'm':
33
33
  case 'h':
34
- case 'd':
35
- return amount * UNITS[unit]
34
+ case 'd': {
35
+ const ms = amount * UNITS[unit]
36
+ if (ms <= 0 || ms > 3650 * UNITS.d) {
37
+ throw new TypeVaultError('invalid', 'TTL must be greater than zero and at most 3650 days')
38
+ }
39
+ return ms
40
+ }
36
41
  default:
37
42
  throw new TypeVaultError('invalid', `invalid TTL unit "${unit}"`)
38
43
  }