convex-secret-store 0.1.0 → 0.2.1

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 (108) hide show
  1. package/README.md +342 -416
  2. package/dist/base64.d.ts +8 -0
  3. package/dist/base64.d.ts.map +1 -0
  4. package/dist/{client/base64.js → base64.js} +11 -6
  5. package/dist/base64.js.map +1 -0
  6. package/dist/client/errors.d.ts +17 -13
  7. package/dist/client/errors.d.ts.map +1 -1
  8. package/dist/client/errors.js +24 -26
  9. package/dist/client/errors.js.map +1 -1
  10. package/dist/client/index.d.ts +5 -4
  11. package/dist/client/index.d.ts.map +1 -1
  12. package/dist/client/index.js +2 -1
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/operations.d.ts +45 -62
  15. package/dist/client/operations.d.ts.map +1 -1
  16. package/dist/client/operations.js +121 -338
  17. package/dist/client/operations.js.map +1 -1
  18. package/dist/client/types.d.ts +93 -95
  19. package/dist/client/types.d.ts.map +1 -1
  20. package/dist/component/_generated/api.d.ts +8 -0
  21. package/dist/component/_generated/api.d.ts.map +1 -1
  22. package/dist/component/_generated/api.js.map +1 -1
  23. package/dist/component/_generated/component.d.ts +11 -56
  24. package/dist/component/_generated/component.d.ts.map +1 -1
  25. package/dist/component/_generated/server.d.ts +9 -0
  26. package/dist/component/_generated/server.d.ts.map +1 -1
  27. package/dist/component/_generated/server.js +1 -0
  28. package/dist/component/_generated/server.js.map +1 -1
  29. package/dist/component/cleanup.d.ts +9 -8
  30. package/dist/component/cleanup.d.ts.map +1 -1
  31. package/dist/component/cleanup.js +56 -67
  32. package/dist/component/cleanup.js.map +1 -1
  33. package/dist/component/convex.config.d.ts +27 -1
  34. package/dist/component/convex.config.d.ts.map +1 -1
  35. package/dist/component/convex.config.js +30 -1
  36. package/dist/component/convex.config.js.map +1 -1
  37. package/dist/{client → component}/crypto.d.ts +12 -0
  38. package/dist/component/crypto.d.ts.map +1 -0
  39. package/dist/{client → component}/crypto.js +21 -4
  40. package/dist/component/crypto.js.map +1 -0
  41. package/dist/component/events.d.ts +18 -0
  42. package/dist/component/events.d.ts.map +1 -0
  43. package/dist/component/events.js +17 -0
  44. package/dist/component/events.js.map +1 -0
  45. package/dist/component/expiry.d.ts +21 -0
  46. package/dist/component/expiry.d.ts.map +1 -0
  47. package/dist/component/expiry.js +36 -0
  48. package/dist/component/expiry.js.map +1 -0
  49. package/dist/component/filters.d.ts +16 -0
  50. package/dist/component/filters.d.ts.map +1 -0
  51. package/dist/component/filters.js +10 -0
  52. package/dist/component/filters.js.map +1 -0
  53. package/dist/component/keys.d.ts +33 -0
  54. package/dist/component/keys.d.ts.map +1 -0
  55. package/dist/component/keys.js +127 -0
  56. package/dist/component/keys.js.map +1 -0
  57. package/dist/component/lib.d.ts +90 -86
  58. package/dist/component/lib.d.ts.map +1 -1
  59. package/dist/component/lib.js +403 -369
  60. package/dist/component/lib.js.map +1 -1
  61. package/dist/component/schema.d.ts +13 -14
  62. package/dist/component/schema.d.ts.map +1 -1
  63. package/dist/component/schema.js +9 -14
  64. package/dist/component/schema.js.map +1 -1
  65. package/dist/keys-format.d.ts +56 -0
  66. package/dist/keys-format.d.ts.map +1 -0
  67. package/dist/keys-format.js +134 -0
  68. package/dist/keys-format.js.map +1 -0
  69. package/dist/shared.d.ts +8 -1
  70. package/dist/shared.d.ts.map +1 -1
  71. package/dist/shared.js +8 -1
  72. package/dist/shared.js.map +1 -1
  73. package/package.json +43 -39
  74. package/src/{client/base64.ts → base64.ts} +12 -6
  75. package/src/client/errors.ts +51 -61
  76. package/src/client/index.ts +12 -12
  77. package/src/client/operations.ts +153 -432
  78. package/src/client/types.ts +127 -162
  79. package/src/component/_generated/api.ts +8 -0
  80. package/src/component/_generated/component.ts +14 -60
  81. package/src/component/_generated/server.ts +9 -0
  82. package/src/component/cleanup.ts +62 -91
  83. package/src/component/convex.config.ts +30 -1
  84. package/src/{client → component}/crypto.ts +22 -4
  85. package/src/component/events.ts +29 -0
  86. package/src/component/expiry.ts +41 -0
  87. package/src/component/filters.ts +29 -0
  88. package/src/component/keys.ts +147 -0
  89. package/src/component/lib.ts +446 -469
  90. package/src/component/schema.ts +9 -14
  91. package/src/keys-format.ts +167 -0
  92. package/src/shared.ts +9 -2
  93. package/src/test.ts +10 -5
  94. package/dist/client/base64.d.ts +0 -3
  95. package/dist/client/base64.d.ts.map +0 -1
  96. package/dist/client/base64.js.map +0 -1
  97. package/dist/client/crypto.d.ts.map +0 -1
  98. package/dist/client/crypto.js.map +0 -1
  99. package/dist/client/options.d.ts +0 -27
  100. package/dist/client/options.d.ts.map +0 -1
  101. package/dist/client/options.js +0 -66
  102. package/dist/client/options.js.map +0 -1
  103. package/src/client/index.test.ts +0 -480
  104. package/src/client/options.ts +0 -110
  105. package/src/client/setup.test.ts +0 -26
  106. package/src/component/cleanup.test.ts +0 -91
  107. package/src/component/lib.test.ts +0 -202
  108. package/src/component/setup.test.ts +0 -11
package/README.md CHANGED
@@ -1,11 +1,14 @@
1
1
  # Convex Secret Store
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/convex-secret-store.svg)](https://badge.fury.io/js/convex-secret-store)
4
+ [![Convex Component](https://www.convex.dev/components/badge/convex-secret-store)](https://www.convex.dev/components/convex-secret-store)
4
5
 
5
6
  <!-- START: Include on https://convex.dev/components -->
6
7
 
7
8
  A [Convex](https://convex.dev) component for encrypted secret storage with
8
- versioned key rotation, expiry, audit logging, and a typed server-side client.
9
+ versioned key rotation, expiry, and append-only audit logging. Envelope
10
+ encryption runs inside the component; key-encryption keys (KEKs) are supplied
11
+ through Convex's typed component environment variables.
9
12
 
10
13
  ```ts
11
14
  const saved = await secrets.put(ctx, {
@@ -21,28 +24,27 @@ const loaded = await secrets.get(ctx, {
21
24
  });
22
25
 
23
26
  if (loaded.ok) {
24
- // loaded.value -> plaintext in memory
25
- // loaded.metadata -> plaintext metadata
27
+ // loaded.value -> plaintext
26
28
  }
27
29
  ```
28
30
 
29
- What this component gives you:
30
-
31
- - envelope encryption with a per-secret DEK and versioned KEKs
32
- - explicit key rotation without rewriting secret plaintext
33
- - expiry-aware reads and cleanup
34
- - append-only audit events for create, update, delete, and rotate operations
35
- - a typed `SecretStore` class for use in Convex queries, mutations, and actions
36
-
37
31
  Found a bug? Feature request?
38
32
  [File it here](https://github.com/gaganref/convex-secret-store/issues).
39
33
 
40
- ## Pre-requisite: Convex
34
+ ## What this gives you
35
+
36
+ - envelope encryption with a per-secret DEK and versioned KEKs
37
+ - explicit, in-place key rotation without rewriting secret plaintext
38
+ - expiry-aware reads, with separate `get` (Result) and `getOrThrow` ergonomics
39
+ - append-only audit events for `created`, `updated`, `deleted`, and `rotated`
40
+ - a typed `SecretStore` facade for Convex queries, mutations, and actions
41
+ - structured `ConvexError`s with stable codes — type-narrowed via `isSecretStoreError`
42
+
43
+ ## Pre-requisite
41
44
 
42
- You'll need an existing Convex project to use this component. Convex is a hosted
43
- backend platform, including a database, serverless functions, and the generated
44
- component wiring this package expects. If you haven't used Convex before, the
45
- [Convex tutorial](https://docs.convex.dev/get-started) is a good place to start.
45
+ A Convex project (`convex >= 1.39`, for typed component environment variables).
46
+ If you're new to Convex, start with the
47
+ [Convex tutorial](https://docs.convex.dev/get-started).
46
48
 
47
49
  ## Installation
48
50
 
@@ -50,555 +52,479 @@ component wiring this package expects. If you haven't used Convex before, the
50
52
  npm install convex-secret-store
51
53
  ```
52
54
 
53
- Install the component in your app's `convex.config.ts`:
55
+ Mount the component in your app's `convex.config.ts`. The simplest setup
56
+ declares the KEK as a validated app env var and reads it via `defineKeys`:
54
57
 
55
58
  ```ts
56
59
  // convex/convex.config.ts
57
60
  import { defineApp } from "convex/server";
58
- import secretStore from "convex-secret-store/convex.config.js";
61
+ import { v } from "convex/values";
62
+ import { defineKeys } from "convex-secret-store";
63
+ import secretStore from "convex-secret-store/convex.config";
59
64
 
60
- const app = defineApp();
61
- app.use(secretStore);
65
+ const app = defineApp({
66
+ env: {
67
+ MY_APP_KEK_V1: v.string(),
68
+ },
69
+ });
70
+
71
+ app.use(secretStore, {
72
+ env: {
73
+ SECRET_STORE_KEYS: defineKeys({
74
+ 1: process.env.MY_APP_KEK_V1!,
75
+ }),
76
+ },
77
+ });
62
78
 
63
79
  export default app;
64
80
  ```
65
81
 
66
- ## Quick Start
82
+ Generate a KEK and set it on the deployment:
67
83
 
68
- Create a shared `SecretStore` instance:
84
+ ```sh
85
+ openssl rand -base64 32 # 32 random bytes as base64
86
+ npx convex env set MY_APP_KEK_V1 "<paste the value>"
87
+ ```
88
+
89
+ Construct the typed facade once and re-export it:
69
90
 
70
91
  ```ts
71
92
  // convex/secrets.ts
72
93
  import { SecretStore } from "convex-secret-store";
73
94
  import { components } from "./_generated/api.js";
74
95
 
75
- export const secrets = new SecretStore<{
76
- namespace: `${string}:${"production" | "testing"}`;
77
- metadata: { owner?: string; label?: string; notes?: string };
78
- }>(components.secretStore, {
79
- keys: [
80
- { version: 2, value: process.env.SECRET_STORE_KEY_V2! },
81
- { version: 1, value: process.env.SECRET_STORE_KEY_V1! },
82
- ],
83
- });
96
+ export const secrets = new SecretStore<
97
+ `${string}:${"production" | "testing"}`,
98
+ { owner?: string; label?: string }
99
+ >(components.secretStore);
84
100
  ```
85
101
 
86
- Use it inside your Convex functions:
102
+ Use it from any query, mutation, or action:
87
103
 
88
104
  ```ts
89
- // convex/integrations.ts
90
- import { mutation, action } from "./_generated/server.js";
91
- import { v } from "convex/values";
105
+ import { action } from "./_generated/server.js";
92
106
  import { secrets } from "./secrets.js";
93
107
 
94
- export const putOpenAIKey = mutation({
95
- args: {
96
- workspace: v.string(),
97
- value: v.string(),
98
- },
99
- handler: async (ctx, args) => {
100
- return await secrets.put(ctx, {
101
- namespace: `${args.workspace}:production`,
108
+ export const callOpenAI = action({
109
+ handler: async (ctx) => {
110
+ const apiKey = await secrets.getOrThrow(ctx, {
111
+ namespace: "acme:production",
102
112
  name: "openai",
103
- value: args.value,
104
- metadata: { owner: "platform" },
105
113
  });
106
- },
107
- });
108
-
109
- export const callProvider = action({
110
- args: { workspace: v.string() },
111
- handler: async (ctx, args) => {
112
- const secret = await secrets.get(ctx, {
113
- namespace: `${args.workspace}:production`,
114
- name: "openai",
114
+ return await fetch("https://api.openai.com/v1/...", {
115
+ headers: { Authorization: `Bearer ${apiKey.value}` },
115
116
  });
116
-
117
- if (!secret.ok) {
118
- throw new Error(`Secret unavailable: ${secret.reason}`);
119
- }
120
-
121
- return {
122
- authHeaderPreview: `Bearer ${secret.value.slice(0, 4)}...`,
123
- };
124
117
  },
125
118
  });
126
119
  ```
127
120
 
128
- ## How It Works
129
-
130
- Each stored secret uses two encryption layers:
131
-
132
- - **DEK**: a fresh random data-encryption key generated per secret value
133
- - **KEK**: a longer-lived key-encryption key from your configured `keys`
134
-
135
- When you call `put`:
136
-
137
- 1. the plaintext value is encrypted with a fresh DEK
138
- 2. that DEK is wrapped with the active KEK
139
- 3. Convex stores:
140
- - `encryptedValue`
141
- - `iv`
142
- - `wrappedDEK`
143
- - `dekIv`
144
- - `keyVersion`
145
-
146
- When you call `get`:
147
-
148
- 1. the row is loaded from Convex
149
- 2. the stored `keyVersion` selects the correct KEK
150
- 3. the DEK is unwrapped
151
- 4. the secret value is decrypted in memory
152
-
153
- When you rotate keys:
154
-
155
- - the encrypted secret value does **not** change
156
- - only the wrapped DEK layer is re-encrypted under a newer KEK
157
-
158
- This is standard envelope-encryption behavior and keeps key rotation cheaper
159
- than full plaintext re-encryption.
160
-
161
- ## Key Material
121
+ ## Key configuration
162
122
 
163
- `keys` must contain base64-encoded 32-byte AES keys.
123
+ ### `SECRET_STORE_KEYS`
164
124
 
165
- Generate one with:
125
+ The component declares one required env var, `SECRET_STORE_KEYS`. Its value is a
126
+ delimited string of versioned KEKs:
166
127
 
167
- ```sh
168
- openssl rand -base64 32
128
+ ```
129
+ 1:<base64>,2:<base64>
169
130
  ```
170
131
 
171
- Rules:
132
+ Each entry is `version:value`. Each KEK value is 32 bytes in standard base64:
133
+ 44 characters ending in one `=`, which is what `openssl rand -base64 32`
134
+ prints.
172
135
 
173
- - the first entry is the active key used for new writes
174
- - later entries are decrypt-only keys used for old rows
175
- - versions must be unique non-negative integers
176
- - empty-string namespaces are rejected
136
+ You can build the value with `defineKeys` (typed, eagerly validated):
177
137
 
178
- ## Typed Options
138
+ ```ts
139
+ defineKeys({
140
+ 1: process.env.MY_APP_KEK_V1!,
141
+ 2: process.env.MY_APP_KEK_V2!,
142
+ })
143
+ ```
179
144
 
180
- The `SecretStore` class accepts a generic parameter for type-safe namespaces and
181
- metadata:
145
+ …or set it directly on the deployment for hosts that don't want a builder:
182
146
 
183
- ```ts
184
- export const secrets = new SecretStore<{
185
- namespace: `${string}:${"production" | "testing"}`;
186
- metadata: {
187
- owner?: string;
188
- label?: string;
189
- notes?: string;
190
- };
191
- }>(components.secretStore, {
192
- keys: [{ version: 1, value: process.env.SECRET_STORE_KEY_V1! }],
193
- defaults: {
194
- ttlMs: 30 * 24 * 60 * 60 * 1000,
195
- },
196
- logLevel: "warn",
197
- });
147
+ ```sh
148
+ npx convex env set SECRET_STORE_KEYS "1:AQEB...,2:AgIC..."
198
149
  ```
199
150
 
200
- Type options:
151
+ Either way, the **active key version is the highest configured version** — all
152
+ new writes use it. Older versions remain available for decrypting existing
153
+ rows.
201
154
 
202
- - `namespace` — any `string` subtype. When set, `namespace` becomes required on
203
- normal read/write/list operations.
204
- - `metadata` — shape of the plaintext metadata object stored with each secret.
155
+ Duplicate versions are caught at compile time when you use `defineKeys` (object
156
+ literals reject duplicate keys: `error TS1117`).
205
157
 
206
- > **Note:** These are compile-time type constraints only. Runtime storage is
207
- > still flexible:
208
- >
209
- > - `namespace` → `v.optional(v.string())`
210
- > - `metadata` → `v.optional(v.record(v.string(), v.any()))`
211
- >
212
- > Existing stored rows are not migrated if you later change your TypeScript
213
- > types.
158
+ ### `SECRET_STORE_DEFAULT_TTL_MS` (optional)
214
159
 
215
- ## Usage
160
+ If set, `put` resolves an omitted `ttlMs` to `now + SECRET_STORE_DEFAULT_TTL_MS`.
161
+ See [Expiry](#expiry) below.
216
162
 
217
- ### Put
163
+ ## API
218
164
 
219
- Encrypt and store a secret value:
165
+ ### `SecretStore`
220
166
 
221
167
  ```ts
222
- const result = await secrets.put(ctx, {
223
- namespace: "acme:production",
224
- name: "stripe",
225
- value: "sk_live_...",
226
- metadata: { owner: "billing" },
227
- ttlMs: 90 * 24 * 60 * 60 * 1000,
228
- });
168
+ new SecretStore<
169
+ Namespace extends string = string,
170
+ Metadata extends Record<string, unknown> = Record<string, unknown>,
171
+ >(components.secretStore)
229
172
  ```
230
173
 
231
- Notes:
174
+ The optional type parameters constrain the `namespace` shape and the `metadata`
175
+ record at compile time. They're a typing aid only — runtime storage stays a
176
+ plain string namespace and a freeform metadata record.
232
177
 
233
- - `ttlMs` is converted to an absolute `expiresAt`
234
- - when overwriting and omitting `metadata` or `ttlMs`, existing metadata and
235
- expiry are preserved
236
- - use `update(..., { metadata: null, expiresAt: null })` to clear optional
237
- fields
238
-
239
- ### Get
240
-
241
- Load and decrypt a secret:
178
+ ### `put`
242
179
 
243
180
  ```ts
244
- const result = await secrets.get(ctx, {
245
- namespace: "acme:production",
246
- name: "stripe",
181
+ await secrets.put(ctx, {
182
+ namespace?: Namespace,
183
+ name: string,
184
+ value: string, // plaintext; max 64 KiB
185
+ metadata?: Metadata | null,
186
+ ttlMs?: number | null,
247
187
  });
188
+ // → { secretId, createdAt, updatedAt, expiresAt?, isNew }
248
189
  ```
249
190
 
250
- `get` returns:
191
+ Encrypts and upserts by `namespace + name`. On overwrite, omitted `metadata` is
192
+ preserved and `null` clears it. Expiry is recomputed every write (see below).
251
193
 
252
- - `{ ok: true, value, metadata, expiresAt, updatedAt }`
253
- - `{ ok: false, reason: "not_found" | "expired" | "key_version_unavailable" }`
194
+ ### `get`
254
195
 
255
- `key_version_unavailable` means the row exists, but the runtime no longer has
256
- the KEK version needed to unwrap it.
196
+ ```ts
197
+ await secrets.get(ctx, { namespace?, name });
198
+ // → { ok: true, value, metadata, expiresAt?, updatedAt }
199
+ // | { ok: false, reason: "not_found" | "expired" | "key_unavailable" }
200
+ ```
257
201
 
258
- ### Has
202
+ Returns a discriminated result. `key_unavailable` means the row's `keyVersion`
203
+ is no longer in your configured `SECRET_STORE_KEYS` (you retired the key too
204
+ soon — see [Rotation](#key-rotation)).
259
205
 
260
- Check whether a usable secret exists:
206
+ ### `getOrThrow`
261
207
 
262
208
  ```ts
263
- const exists = await secrets.has(ctx, {
264
- namespace: "acme:production",
265
- name: "stripe",
266
- });
209
+ await secrets.getOrThrow(ctx, { namespace?, name });
210
+ // → { value, metadata, expiresAt?, updatedAt }
211
+ // throws ConvexError with code "not_found" | "expired" | "key_unavailable"
267
212
  ```
268
213
 
269
- Expired secrets return `false`.
214
+ Convenience for call sites that treat any failure as exceptional.
270
215
 
271
- ### Update
216
+ > No dedicated `has` is exposed. For "does X exist?" checks, derive from `get`:
217
+ > `const present = (await secrets.get(ctx, { name })).ok`.
272
218
 
273
- Update plaintext metadata or expiry without rewriting the encrypted value:
219
+ ### `update`
274
220
 
275
221
  ```ts
276
222
  await secrets.update(ctx, {
277
- namespace: "acme:production",
278
- name: "stripe",
279
- metadata: { owner: "finance", label: "primary" },
280
- expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000,
223
+ namespace?, name,
224
+ metadata?: Metadata | null,
225
+ ttlMs?: number | null,
281
226
  });
227
+ // → { updated, updatedAt?, expiresAt? }
282
228
  ```
283
229
 
284
- Pass `null` to clear metadata or expiry entirely.
285
-
286
- ### Remove
230
+ Edits `metadata` and/or expiry **without** re-encrypting the value. Omitted
231
+ fields are preserved; `null` clears. At least one of `metadata` or `ttlMs`
232
+ must be supplied — calling with neither throws `invalid_argument`.
233
+ `{ updated: false }` means the secret does not exist (symmetric with `remove`).
287
234
 
288
- Delete a secret and append a matching audit event:
235
+ ### `remove`
289
236
 
290
237
  ```ts
291
- await secrets.remove(ctx, {
292
- namespace: "acme:production",
293
- name: "stripe",
294
- });
238
+ await secrets.remove(ctx, { namespace?, name });
239
+ // → { removed: boolean }
295
240
  ```
296
241
 
297
- ### List
298
-
299
- Paginate secrets in one namespace:
242
+ ### `list`
300
243
 
301
244
  ```ts
302
- const page = await secrets.list(ctx, {
303
- namespace: "acme:production",
304
- order: "desc",
305
- paginationOpts: { numItems: 20, cursor: null },
245
+ await secrets.list(ctx, {
246
+ namespace?,
247
+ paginationOpts: { numItems, cursor },
248
+ order?: "asc" | "desc",
306
249
  });
307
250
  ```
308
251
 
309
- Notes:
310
-
311
- - rows are ordered by `updatedAt`
312
- - expired rows are still listed
313
- - each row includes `effectiveState: "active" | "expired"`
252
+ Paginates secrets in a namespace, newest-`updatedAt` first by default. Each row
253
+ carries `effectiveState: "active" | "expired"`. The decrypted value is never
254
+ returned by `list`.
314
255
 
315
- ### List Events
316
-
317
- Paginate audit events:
256
+ ### `listEvents`
318
257
 
319
258
  ```ts
320
- const events = await secrets.listEvents(ctx, {
321
- namespace: "acme:production",
322
- paginationOpts: { numItems: 50, cursor: null },
259
+ await secrets.listEvents(ctx, {
260
+ paginationOpts,
261
+ // one of:
262
+ secretId?,
263
+ namespace?, // omit for the default namespace
264
+ name?, // optionally narrows within `namespace`
265
+ type?: "created" | "updated" | "deleted" | "rotated", // optionally narrows within `namespace`
266
+ order?,
323
267
  });
324
268
  ```
325
269
 
326
- You can also filter by `name`, `type`, or by `secretId`.
327
-
328
- V1 restrictions:
329
-
330
- - `name` and `type` cannot be combined
331
- - when filtering by `name` or `type`, `namespace` is required
332
- - `secretId` cannot be combined with `namespace`, `name`, or `type`
270
+ `secretId` cannot combine with `namespace`/`name`/`type`; `name` and `type`
271
+ cannot combine with each other.
333
272
 
334
- ### Rotate Keys
335
-
336
- Rewrap old rows from one key version to the active version:
273
+ ### `rotate`
337
274
 
338
275
  ```ts
339
- const result = await secrets.rotateKeys(ctx, {
340
- fromVersion: 1,
341
- batchSize: 100,
342
- cursor: null,
343
- });
276
+ await secrets.rotate(ctx);
277
+ // → { rotated, skipped, isDone }
344
278
  ```
345
279
 
346
- Result fields:
347
-
348
- - `fromVersion`
349
- - `toVersion`
350
- - `processed`
351
- - `rotated`
352
- - `skipped`
353
- - `isDone`
354
- - `continueCursor`
355
-
356
- Important semantics:
357
-
358
- - rotation rewraps DEKs only
359
- - the encrypted secret plaintext is not rewritten
360
- - concurrent writes are protected with compare-and-swap checks
361
- - stale rows are skipped safely and can be retried in a later batch
362
- - do not remove an old KEK until rotation is fully drained
280
+ Rewraps each stale secret's DEK onto the active KEK version, in batches of 100
281
+ per transaction, **self-rescheduling** until the backlog drains. The secret
282
+ plaintext is never rewritten. Safe to call repeatedly.
363
283
 
364
- ### Cleanup Expired Secrets
284
+ `skipped` counts rows that reference a `keyVersion` no longer in
285
+ `SECRET_STORE_KEYS` — orphans from retiring a KEK too soon. They're left
286
+ untouched and logged. The chain stops rescheduling once only orphans remain
287
+ (otherwise it would spin); recover by re-adding the missing KEK and calling
288
+ `rotate` again, or by `remove`ing the orphan rows.
365
289
 
366
- Hard-delete secrets that have remained expired past the retention window:
290
+ ### `isRotationComplete`
367
291
 
368
292
  ```ts
369
- const result = await secrets.cleanupSecrets(ctx, {
370
- retentionMs: 30 * 24 * 60 * 60 * 1000,
371
- });
293
+ await secrets.isRotationComplete(ctx);
294
+ // → boolean
372
295
  ```
373
296
 
374
- What `cleanupSecrets` does:
375
-
376
- - deletes expired secret rows once they are older than the retention window
377
- - writes a final `deleted` audit event with `deletedReason: "expired_cleanup"`
378
- - processes up to 100 rows per run and automatically reschedules itself while
379
- backlog remains
297
+ `true` when every secret is on the active KEK version. Use this as the gate
298
+ before retiring an old key.
380
299
 
381
- ### Cleanup Audit Events
382
-
383
- Hard-delete audit events older than the retention window:
300
+ ### `cleanupSecrets` / `cleanupEvents`
384
301
 
385
302
  ```ts
386
- const result = await secrets.cleanupEvents(ctx, {
387
- retentionMs: 180 * 24 * 60 * 60 * 1000,
388
- });
303
+ await secrets.cleanupSecrets(ctx, { retentionMs? }); // default 30 days
304
+ await secrets.cleanupEvents(ctx, { retentionMs? }); // default 180 days
389
305
  ```
390
306
 
391
- What `cleanupEvents` does:
307
+ Hard-deletes expired secrets (and writes a `deleted` event with reason
308
+ `expired_cleanup`) / old audit events. Self-reschedules; suitable for a
309
+ recurring cron.
392
310
 
393
- - deletes audit rows independently from secret cleanup
394
- - lets audit history outlive expired secrets when you want longer retention
395
- - processes up to 100 rows per run and automatically reschedules itself while
396
- backlog remains
311
+ ## Expiry
397
312
 
398
- Recommended host-app pattern:
313
+ ```
314
+ expiresAt = now + ttlMs if ttlMs is a positive integer
315
+ = no expiry if ttlMs is null
316
+ = now + SECRET_STORE_DEFAULT_TTL_MS if ttlMs is omitted and a default is set
317
+ = no expiry otherwise
318
+ ```
319
+
320
+ `ttlMs` (and `SECRET_STORE_DEFAULT_TTL_MS`) must be a positive integer — `0`
321
+ is rejected. Expiry is **recomputed on every `put`** (ADR 0003); use `update`
322
+ to change expiry without rewriting the value.
323
+
324
+ ## Key rotation
325
+
326
+ Rotation is a deploy-time exercise. The component drains in the background once
327
+ triggered.
328
+
329
+ 1. **Deploy with a new key.** Add the new version to `defineApp({ env })` and
330
+ `defineKeys`, set the env var on the deployment, push:
331
+ ```ts
332
+ const app = defineApp({
333
+ env: {
334
+ MY_APP_KEK_V1: v.string(),
335
+ MY_APP_KEK_V2: v.string(),
336
+ },
337
+ });
338
+ app.use(secretStore, {
339
+ env: {
340
+ SECRET_STORE_KEYS: defineKeys({
341
+ 1: process.env.MY_APP_KEK_V1!,
342
+ 2: process.env.MY_APP_KEK_V2!,
343
+ }),
344
+ },
345
+ });
346
+ ```
347
+ ```sh
348
+ npx convex env set MY_APP_KEK_V2 "$(openssl rand -base64 32)"
349
+ npx convex deploy
350
+ ```
351
+ 2. **Trigger rotation.** Call `secrets.rotate(ctx)` once (from the dashboard, a
352
+ one-shot internal mutation, or a temporary cron during the drain window).
353
+ 3. **Verify drain.** Poll `secrets.isRotationComplete(ctx)` — when `true`, no
354
+ secret is still on an old key.
355
+ 4. **Retire the old key.** First remove it from `defineApp({ env })` and
356
+ `defineKeys`, then push, then `npx convex env remove MY_APP_KEK_V1`. The
357
+ order matters — Convex refuses to remove a deployment env var that's still
358
+ declared as required in the app definition.
359
+
360
+ A new `rotated` audit event is recorded per row.
361
+
362
+ > **KEK material is immutable per version.** To rotate, *add* a new version
363
+ > (`MY_APP_KEK_V2`) — never overwrite the material under an existing version
364
+ > number. Replacing the bytes under `MY_APP_KEK_V1` while rows still reference
365
+ > it is unsupported: reads of those rows will throw `decryption_failed`, and
366
+ > `rotate` will skip them with a warning. Recovery requires restoring the
367
+ > original material under that version, or `remove`-ing the affected rows.
368
+
369
+ ## Cleanup crons
370
+
371
+ Recommended permanent crons:
399
372
 
400
373
  ```ts
401
374
  // convex/cleanup.ts
402
- import { internalMutation } from "./_generated/server";
403
- import { secrets } from "./secrets";
375
+ import { internalMutation } from "./_generated/server.js";
376
+ import { secrets } from "./secrets.js";
404
377
 
405
378
  export const cleanupSecrets = internalMutation({
406
- handler: (ctx) =>
407
- secrets.cleanupSecrets(ctx, {
408
- retentionMs: 30 * 24 * 60 * 60 * 1000,
409
- }),
379
+ handler: (ctx) => secrets.cleanupSecrets(ctx),
410
380
  });
411
-
412
381
  export const cleanupEvents = internalMutation({
413
- handler: (ctx) =>
414
- secrets.cleanupEvents(ctx, {
415
- retentionMs: 180 * 24 * 60 * 60 * 1000,
416
- }),
382
+ handler: (ctx) => secrets.cleanupEvents(ctx),
417
383
  });
418
384
  ```
419
385
 
420
386
  ```ts
421
387
  // convex/crons.ts
422
388
  import { cronJobs } from "convex/server";
423
- import { internal } from "./_generated/api";
389
+ import { internal } from "./_generated/api.js";
424
390
 
425
391
  const crons = cronJobs();
426
-
427
- crons.interval(
428
- "cleanup expired secrets",
429
- { hours: 24 },
430
- internal.cleanup.cleanupSecrets,
431
- );
432
- crons.interval(
433
- "cleanup secret audit events",
434
- { hours: 24 },
435
- internal.cleanup.cleanupEvents,
436
- );
437
-
392
+ crons.interval("cleanup expired secrets", { hours: 24 }, internal.cleanup.cleanupSecrets);
393
+ crons.interval("cleanup audit events", { hours: 24 }, internal.cleanup.cleanupEvents);
438
394
  export default crons;
439
395
  ```
440
396
 
441
- ## Rotation Workflow
442
-
443
- `keys[0]` is the active write key. Any remaining entries are older decrypt-only
444
- keys.
397
+ If you'd rather skip the `cleanup.ts` wrapper, you can point `crons.interval`
398
+ directly at the component's function and pass `retentionMs` as a static arg:
445
399
 
446
400
  ```ts
447
- keys: [
448
- { version: 3, value: process.env.SECRET_STORE_KEY_V3! }, // active
449
- { version: 2, value: process.env.SECRET_STORE_KEY_V2! }, // decrypt-only
450
- { version: 1, value: process.env.SECRET_STORE_KEY_V1! }, // decrypt-only
451
- ];
452
- ```
453
-
454
- Recommended flow:
455
-
456
- 1. prepend a new key version to `keys`
457
- 2. deploy so new writes start using that version
458
- 3. run rotation for each older version you want to drain
459
- 4. keep old keys configured until those rows are fully rotated
460
- 5. deploy again with drained old versions removed
461
-
462
- Recommended host-app wrappers:
463
-
464
- See [`example/convex/rotate.ts`](./example/convex/rotate.ts) for a working
465
- version of this pattern.
466
-
467
- ```ts
468
- // convex/rotate.ts
469
- import { v } from "convex/values";
470
- import { internalAction, type ActionCtx } from "./_generated/server";
471
- import { secrets } from "./secrets";
472
-
473
- async function rotateVersion(ctx: ActionCtx, fromVersion: number) {
474
- let cursor: string | null = null;
475
-
476
- while (true) {
477
- const result = await secrets.rotateKeys(ctx, {
478
- fromVersion,
479
- batchSize: 100,
480
- cursor,
481
- });
482
-
483
- if (result.isDone) {
484
- return result;
485
- }
401
+ import { components } from "./_generated/api.js";
486
402
 
487
- cursor = result.continueCursor ?? null;
488
- }
489
- }
403
+ crons.interval(
404
+ "cleanup expired secrets",
405
+ { hours: 24 },
406
+ components.secretStore.cleanup.cleanupSecrets,
407
+ { retentionMs: 30 * 24 * 60 * 60 * 1000 },
408
+ );
409
+ ```
490
410
 
491
- export const rotateSecretStoreVersion = internalAction({
492
- args: { fromVersion: v.number() },
493
- handler: async (ctx, args) => {
494
- return await rotateVersion(ctx, args.fromVersion);
495
- },
496
- });
411
+ The wrapper above gets you cleaner names in logs and a place to hook in
412
+ behavior later (metrics, alerts); the direct form trades that for one fewer
413
+ file. Pick whichever your codebase prefers — both are supported.
497
414
 
498
- export const rotateSecretStoreToLatest = internalAction({
499
- handler: async (ctx) => {
500
- for (const fromVersion of [2, 1]) {
501
- await rotateVersion(ctx, fromVersion);
502
- }
503
- },
504
- });
505
- ```
415
+ ## Optional: rotation safety-net cron
506
416
 
507
- Optional temporary cron during a rotation window:
417
+ By default the recommended rotation flow is one-shot — call
418
+ `secrets.rotate(ctx)` once after deploying a new key, then poll
419
+ `isRotationComplete()` before retiring the old one (see
420
+ [Key rotation](#key-rotation)). If you'd rather not remember the manual step,
421
+ add a slow rotation cron as a safety net. It's a no-op when nothing's stale
422
+ (one indexed `.first()` query — cheap) and picks up any backlog automatically:
508
423
 
509
424
  ```ts
510
- // convex/crons.ts
511
- import { cronJobs } from "convex/server";
512
- import { internal } from "./_generated/api";
513
-
514
- const crons = cronJobs();
425
+ // convex/crons.ts (in addition to the cleanup crons above)
426
+ import { components } from "./_generated/api.js";
515
427
 
516
428
  crons.interval(
517
- "drain secret-store old keys",
518
- { minutes: 10 },
519
- internal.rotate.rotateSecretStoreToLatest,
429
+ "secret-store rotation",
430
+ { hours: 24 },
431
+ components.secretStore.lib.rotate,
432
+ {},
520
433
  );
521
-
522
- export default crons;
523
434
  ```
524
435
 
525
- Cleanup is a good permanent cron. Rotation is usually a temporary cron or a
526
- manual admin action during a migration window.
527
-
528
- This component does not use explicit locks during rotation. Instead, it uses
529
- optimistic concurrency checks so concurrent writes do not corrupt rows. If a row
530
- changes while rotation is in flight, the rewrap attempt is skipped safely and
531
- retried by a later pass. A restart scan may return `continueCursor: null`; keep
532
- looping until `isDone === true`.
533
-
534
- ## Security Model
535
-
536
- - **Envelope encryption** — each secret gets its own random DEK, wrapped by a
537
- configured KEK.
538
- - **Exact key version lookup** — reads use the stored `keyVersion`; they do not
539
- probe multiple keys.
540
- - **AAD binding** — ciphertext is bound to `namespace`, `name`, and
541
- `keyVersion`, so moving ciphertext between rows should fail authentication.
542
- - **No backend KEKs** — the Convex component stores ciphertext only. KEKs live
543
- in the host app runtime using the `SecretStore` client.
544
- - **Plaintext metadata** — `metadata`, `namespace`, `name`, expiry, and audit
545
- metadata are not encrypted.
436
+ **Cadence caveat.** Keep the interval at **≥ 24h**. At sub-hourly cadence a
437
+ cron tick may fire while a previous chain is still draining a large backlog,
438
+ spawning parallel chains that waste compute (no correctness issue, since the
439
+ slice is self-consuming, just noise). Daily or weekly is the right place.
546
440
 
547
- Important limitations:
441
+ ## Errors
548
442
 
549
- - this protects secrets at rest in Convex, not against a compromised app runtime
550
- - any code with access to your configured KEKs can decrypt secrets
551
- - plaintext exists in memory while your server-side code uses it
552
- - do not store sensitive data in metadata fields
553
-
554
- ## Configuration Options
555
-
556
- Pass options when constructing the client:
443
+ Every backend failure surfaces as a `ConvexError` whose `data` carries a typed
444
+ code:
557
445
 
558
446
  ```ts
559
- new SecretStore(components.secretStore, {
560
- keys: [{ version: 1, value: process.env.SECRET_STORE_KEY_V1! }],
561
- defaults: {
562
- ttlMs: null,
563
- },
564
- logLevel: "warn",
565
- });
447
+ import { isSecretStoreError, type SecretStoreErrorCode } from "convex-secret-store";
448
+
449
+ try {
450
+ await secrets.put(ctx, { name: "", value: "..." });
451
+ } catch (error) {
452
+ if (isSecretStoreError(error)) {
453
+ switch (error.data.code) {
454
+ case "invalid_argument": /* … */ break;
455
+ case "value_too_large": /* … */ break;
456
+ case "invalid_keys": /* deployment misconfigured */ break;
457
+ case "key_unavailable": /* row references a retired KEK */ break;
458
+ case "decryption_failed":/* tampering or corruption */ break;
459
+ case "not_found": /* getOrThrow on a missing secret */ break;
460
+ case "expired": /* getOrThrow on an expired secret */ break;
461
+ }
462
+ }
463
+ }
566
464
  ```
567
465
 
568
- Options:
569
-
570
- - `keys` — required versioned KEKs
571
- - `defaults.ttlMs` — default secret TTL in milliseconds
572
- - `logLevel` — `"debug" | "warn" | "error" | "none"`
573
-
574
- ## Example App
575
-
576
- See the [example/](./example) directory for a full reference app called **Secret
577
- Store**.
578
-
579
- It demonstrates:
580
-
581
- - `Secrets` — store, replace, preview, and remove environment secrets
582
- - `Activity` — audit history
583
- - `Settings` — key rotation, cleanup, and demo seeding flows
584
-
585
- > **Security note:** The example app keeps secret management intentionally
586
- > simple. In a real app, gate secret write/read flows behind your authentication
587
- > and authorization layer before exposing them to operators.
466
+ ## Security model
467
+
468
+ `convex-secret-store` provides encryption at rest *inside Convex* — protecting
469
+ against an attacker who gets the raw database without your deployment's
470
+ configuration. It is **not** a hardware-backed key store and does not protect
471
+ against any actor with deployment access:
472
+
473
+ - **KEKs live in the Convex deployment's env vars.** The component runs in your
474
+ Convex deployment; "encryption inside the component" and "encryption outside
475
+ the component" both run on Convex servers — there is no meaningful trust
476
+ boundary between them. Anyone who can read your Convex deployment env can
477
+ decrypt the data.
478
+ - **Supply-chain trust.** A malicious version of this package, if installed,
479
+ could exfiltrate decrypted plaintext. Pin the dependency and review updates.
480
+ - **AAD binding.** AES-256-GCM ciphertext binds `namespace`, `name`, and the
481
+ DEK's `keyVersion` as additional authenticated data, so ciphertext cannot be
482
+ relocated between rows.
483
+ - **Plaintext metadata.** `metadata`, `namespace`, `name`, expiry, and audit
484
+ events are not encrypted. Do not store sensitive data in metadata.
485
+ - **Your functions authorize, the component scopes.** The component trusts its
486
+ host app. Check that the caller may use a namespace before passing it to
487
+ `get`, `list`, or `listEvents`. Results never include rows outside the
488
+ namespace and filters you pass, whatever cursor the client sends.
489
+ - **Errors carry no key material or secret values.** A `getOrThrow` error
490
+ names the secret you asked for, so treat secret names in errors like any
491
+ other data you choose to show a client.
492
+ - **Audit events are advisory, not tamper-evident.** Events live in the same
493
+ database as the secrets and have no append-only enforcement; treat them as a
494
+ forensic trail visible to anyone with deployment access, not as evidence of
495
+ record.
496
+
497
+ See `docs/adr/0001-component-side-encryption.md` for the architecture trade-off.
498
+
499
+ ## Example app
500
+
501
+ The [`example/`](./example) directory contains a small Vite + Convex app:
502
+
503
+ - **Secrets** — store, replace, preview (masked), and remove environment
504
+ secrets
505
+ - **Activity** — paginate the audit log
506
+ - **Settings** — version counts per scope, rotation controls, cleanup buttons,
507
+ and demo data seeding
508
+
509
+ The example mounts the component with `defineKeys({ 1: process.env.MY_APP_KEK_V1!, 2: process.env.MY_APP_KEK_V2! })`,
510
+ demonstrating the validated-env pattern.
511
+
512
+ > **Note:** The example UI is intentionally simple and unauthenticated. In a
513
+ > real app, gate secret read/write flows behind your auth and authorization
514
+ > layer before exposing them to operators.
588
515
 
589
516
  ## Development
590
517
 
591
518
  ```sh
592
- npm i
593
- npm run dev
594
- ```
595
-
596
- Useful commands:
597
-
598
- ```sh
519
+ npm install
520
+ npm run dev # backend + frontend together
521
+ npm run build # build the published package
599
522
  npm run typecheck
600
523
  npm run lint
601
524
  npm test
602
525
  ```
603
526
 
527
+ Architectural decisions are recorded in [`docs/adr/`](./docs/adr).
528
+ Domain terminology is in [`CONTEXT.md`](./CONTEXT.md).
529
+
604
530
  <!-- END: Include on https://convex.dev/components -->