convex-secret-store 0.2.0 → 0.3.0-rc.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 (92) hide show
  1. package/README.md +135 -465
  2. package/dist/base64.d.ts.map +1 -1
  3. package/dist/base64.js +1 -0
  4. package/dist/base64.js.map +1 -1
  5. package/dist/client/errors.d.ts.map +1 -1
  6. package/dist/client/errors.js +1 -0
  7. package/dist/client/errors.js.map +1 -1
  8. package/dist/client/operations.d.ts +10 -5
  9. package/dist/client/operations.d.ts.map +1 -1
  10. package/dist/client/operations.js +30 -6
  11. package/dist/client/operations.js.map +1 -1
  12. package/dist/client/types.d.ts +2 -5
  13. package/dist/client/types.d.ts.map +1 -1
  14. package/dist/component/_generated/api.d.ts +4 -0
  15. package/dist/component/_generated/api.d.ts.map +1 -1
  16. package/dist/component/_generated/api.js.map +1 -1
  17. package/dist/component/_generated/component.d.ts +4 -2
  18. package/dist/component/_generated/component.d.ts.map +1 -1
  19. package/dist/component/_generated/server.d.ts +6 -1
  20. package/dist/component/_generated/server.d.ts.map +1 -1
  21. package/dist/component/_generated/server.js +2 -1
  22. package/dist/component/_generated/server.js.map +1 -1
  23. package/dist/component/cleanup.d.ts +12 -15
  24. package/dist/component/cleanup.d.ts.map +1 -1
  25. package/dist/component/cleanup.js +48 -23
  26. package/dist/component/cleanup.js.map +1 -1
  27. package/dist/component/convex.config.d.ts +10 -12
  28. package/dist/component/convex.config.d.ts.map +1 -1
  29. package/dist/component/convex.config.js +10 -12
  30. package/dist/component/convex.config.js.map +1 -1
  31. package/dist/component/crypto.d.ts +24 -0
  32. package/dist/component/crypto.d.ts.map +1 -1
  33. package/dist/component/crypto.js +24 -0
  34. package/dist/component/crypto.js.map +1 -1
  35. package/dist/component/expiry.d.ts +7 -0
  36. package/dist/component/expiry.d.ts.map +1 -1
  37. package/dist/component/expiry.js +41 -1
  38. package/dist/component/expiry.js.map +1 -1
  39. package/dist/component/filters.d.ts +16 -0
  40. package/dist/component/filters.d.ts.map +1 -0
  41. package/dist/component/filters.js +10 -0
  42. package/dist/component/filters.js.map +1 -0
  43. package/dist/component/keys.js +1 -1
  44. package/dist/component/keys.js.map +1 -1
  45. package/dist/component/lib.d.ts +17 -21
  46. package/dist/component/lib.d.ts.map +1 -1
  47. package/dist/component/lib.js +113 -103
  48. package/dist/component/lib.js.map +1 -1
  49. package/dist/component/rotation.d.ts +48 -0
  50. package/dist/component/rotation.d.ts.map +1 -0
  51. package/dist/component/rotation.js +179 -0
  52. package/dist/component/rotation.js.map +1 -0
  53. package/dist/component/schema.d.ts +9 -6
  54. package/dist/component/schema.d.ts.map +1 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/envelope.d.ts +7 -0
  58. package/dist/envelope.d.ts.map +1 -0
  59. package/dist/envelope.js +7 -0
  60. package/dist/envelope.js.map +1 -0
  61. package/dist/keys-format.d.ts +7 -7
  62. package/dist/keys-format.js +12 -12
  63. package/dist/keys-format.js.map +1 -1
  64. package/package.json +44 -40
  65. package/src/base64.ts +1 -0
  66. package/src/client/errors.ts +5 -1
  67. package/src/client/operations.ts +33 -6
  68. package/src/client/types.ts +2 -4
  69. package/src/component/_generated/api.ts +4 -0
  70. package/src/component/_generated/component.ts +16 -2
  71. package/src/component/_generated/server.ts +8 -2
  72. package/src/component/cleanup.ts +57 -25
  73. package/src/component/convex.config.ts +10 -12
  74. package/src/component/crypto.ts +24 -0
  75. package/src/component/expiry.ts +53 -1
  76. package/src/component/filters.ts +29 -0
  77. package/src/component/keys.ts +1 -1
  78. package/src/component/lib.ts +135 -111
  79. package/src/component/rotation.ts +204 -0
  80. package/src/component/schema.ts +3 -0
  81. package/src/envelope.ts +11 -0
  82. package/src/keys-format.ts +12 -12
  83. package/src/test.ts +10 -5
  84. package/src/client/index.test.ts +0 -207
  85. package/src/client/setup.test.ts +0 -26
  86. package/src/component/cleanup.test.ts +0 -106
  87. package/src/component/crypto.test.ts +0 -150
  88. package/src/component/expiry.test.ts +0 -44
  89. package/src/component/keys.test.ts +0 -108
  90. package/src/component/lib.test.ts +0 -747
  91. package/src/component/setup.test.ts +0 -11
  92. package/src/keys-format.test.ts +0 -129
package/README.md CHANGED
@@ -5,519 +5,189 @@
5
5
 
6
6
  <!-- START: Include on https://convex.dev/components -->
7
7
 
8
- A [Convex](https://convex.dev) component for encrypted secret storage with
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.
12
-
13
- ```ts
14
- const saved = await secrets.put(ctx, {
15
- namespace: "acme:production",
16
- name: "openai",
17
- value: process.env.OPENAI_API_KEY!,
18
- metadata: { owner: "platform" },
19
- });
20
-
21
- const loaded = await secrets.get(ctx, {
22
- namespace: "acme:production",
23
- name: "openai",
24
- });
25
-
26
- if (loaded.ok) {
27
- // loaded.value -> plaintext
28
- }
29
- ```
30
-
31
- Found a bug? Feature request?
32
- [File it here](https://github.com/gaganref/convex-secret-store/issues).
33
-
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
44
-
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).
48
-
49
- ## Installation
50
-
51
- ```sh
52
- npm install convex-secret-store
53
- ```
54
-
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`:
57
-
58
- ```ts
59
- // convex/convex.config.ts
60
- import { defineApp } from "convex/server";
61
- import { v } from "convex/values";
62
- import { defineKeys } from "convex-secret-store";
63
- import secretStore from "convex-secret-store/convex.config";
64
-
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
- });
78
-
79
- export default app;
80
- ```
81
-
82
- Generate a KEK and set it on the deployment:
83
-
84
- ```sh
85
- openssl rand -base64 32 # 32 bytes, canonical 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:
90
-
91
- ```ts
92
- // convex/secrets.ts
93
- import { SecretStore } from "convex-secret-store";
94
- import { components } from "./_generated/api.js";
95
-
96
- export const secrets = new SecretStore<
97
- `${string}:${"production" | "testing"}`,
98
- { owner?: string; label?: string }
99
- >(components.secretStore);
100
- ```
101
-
102
- Use it from any query, mutation, or action:
103
-
104
- ```ts
105
- import { action } from "./_generated/server.js";
106
- import { secrets } from "./secrets.js";
107
-
108
- export const callOpenAI = action({
109
- handler: async (ctx) => {
110
- const apiKey = await secrets.getOrThrow(ctx, {
111
- namespace: "acme:production",
112
- name: "openai",
113
- });
114
- return await fetch("https://api.openai.com/v1/...", {
115
- headers: { Authorization: `Bearer ${apiKey.value}` },
116
- });
117
- },
118
- });
119
- ```
120
-
121
- ## Key configuration
122
-
123
- ### `SECRET_STORE_KEYS`
8
+ Store API keys, tokens and other secrets in your Convex app, encrypted at rest,
9
+ with key rotation, expiry and an audit log.
124
10
 
125
- The component declares one required env var, `SECRET_STORE_KEYS`. Its value is a
126
- delimited string of versioned KEKs:
11
+ The component encrypts each value with keys you keep in your deployment's
12
+ environment variables, so a copy of the database alone cannot reveal it. Only
13
+ your own Convex functions can call the component, so your code decides who reads
14
+ which secret.
127
15
 
128
- ```
129
- 1:<base64>,2:<base64>
130
- ```
131
-
132
- Each entry is `version:value`. Each KEK value must be a canonical 32-byte
133
- standard base64 string (44 chars ending in `=`) — the output of
134
- `openssl rand -base64 32`.
135
-
136
- You can build the value with `defineKeys` (typed, eagerly validated):
137
-
138
- ```ts
139
- defineKeys({
140
- 1: process.env.MY_APP_KEK_V1!,
141
- 2: process.env.MY_APP_KEK_V2!,
142
- })
143
- ```
144
-
145
- …or set it directly on the deployment for hosts that don't want a builder:
146
-
147
- ```sh
148
- npx convex env set SECRET_STORE_KEYS "1:AQEB...,2:AgIC..."
149
- ```
150
-
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.
154
-
155
- Duplicate versions are caught at compile time when you use `defineKeys` (object
156
- literals reject duplicate keys: `error TS1117`).
16
+ ## When to use it
157
17
 
158
- ### `SECRET_STORE_DEFAULT_TTL_MS` (optional)
18
+ | You need | Use |
19
+ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
20
+ | Secrets your users or tenants add at runtime, such as a customer's key | This component |
21
+ | To rotate the encryption key without rewriting every value | This component |
22
+ | A record of when each secret was created, changed or deleted | This component |
23
+ | A few fixed keys that only you set, such as your own OpenAI key | Plain [Convex environment variables](https://docs.convex.dev/production/environment-variables) |
24
+ | Protection from someone with access to your Convex deployment | A dedicated secrets manager. This component cannot give you that, because its keys live in the deployment. |
159
25
 
160
- If set, `put` resolves an omitted `ttlMs` to `now + SECRET_STORE_DEFAULT_TTL_MS`.
161
- See [Expiry](#expiry) below.
26
+ ## Quick start
162
27
 
163
- ## API
28
+ You need a Convex project on `convex` 1.39 or later.
164
29
 
165
- ### `SecretStore`
30
+ 1. Install the package.
166
31
 
167
- ```ts
168
- new SecretStore<
169
- Namespace extends string = string,
170
- Metadata extends Record<string, unknown> = Record<string, unknown>,
171
- >(components.secretStore)
172
- ```
173
-
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.
177
-
178
- ### `put`
179
-
180
- ```ts
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,
187
- });
188
- // → { secretId, createdAt, updatedAt, expiresAt?, isNew }
189
- ```
190
-
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).
193
-
194
- ### `get`
195
-
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
- ```
201
-
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)).
205
-
206
- ### `getOrThrow`
207
-
208
- ```ts
209
- await secrets.getOrThrow(ctx, { namespace?, name });
210
- // → { value, metadata, expiresAt?, updatedAt }
211
- // throws ConvexError with code "not_found" | "expired" | "key_unavailable"
212
- ```
32
+ ```sh
33
+ npm install convex-secret-store
34
+ ```
213
35
 
214
- Convenience for call sites that treat any failure as exceptional.
36
+ 2. Mount the component in `convex/convex.config.ts` and pass it your keys.
215
37
 
216
- > No dedicated `has` is exposed. For "does X exist?" checks, derive from `get`:
217
- > `const present = (await secrets.get(ctx, { name })).ok`.
38
+ ```ts
39
+ import { defineApp } from "convex/server";
40
+ import { v } from "convex/values";
41
+ import secretStore from "convex-secret-store/convex.config";
218
42
 
219
- ### `update`
43
+ const app = defineApp({
44
+ env: { SECRET_STORE_KEYS: v.string() },
45
+ });
220
46
 
221
- ```ts
222
- await secrets.update(ctx, {
223
- namespace?, name,
224
- metadata?: Metadata | null,
225
- ttlMs?: number | null,
226
- });
227
- // → { updated, updatedAt?, expiresAt? }
228
- ```
47
+ app.use(secretStore, {
48
+ env: { SECRET_STORE_KEYS: app.env.SECRET_STORE_KEYS },
49
+ });
229
50
 
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`).
51
+ export default app;
52
+ ```
234
53
 
235
- ### `remove`
54
+ 3. Create a key and set it on your deployment. Each entry is `version:value`,
55
+ and the value is 32 random bytes in base64.
236
56
 
237
- ```ts
238
- await secrets.remove(ctx, { namespace?, name });
239
- // → { removed: boolean }
240
- ```
57
+ ```sh
58
+ npx convex env set SECRET_STORE_KEYS "1:$(openssl rand -base64 32)"
59
+ npx convex dev
60
+ ```
241
61
 
242
- ### `list`
62
+ You should see `Convex functions ready!`. If the variable is missing, the
63
+ push stops and names the variable to set.
243
64
 
244
- ```ts
245
- await secrets.list(ctx, {
246
- namespace?,
247
- paginationOpts: { numItems, cursor },
248
- order?: "asc" | "desc",
249
- });
250
- ```
65
+ 4. Create the client once, in `convex/secrets.ts`.
251
66
 
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`.
255
-
256
- ### `listEvents`
257
-
258
- ```ts
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?,
267
- });
268
- ```
67
+ ```ts
68
+ import { SecretStore } from "convex-secret-store";
69
+ import { components } from "./_generated/api.js";
269
70
 
270
- `secretId` cannot combine with `namespace`/`name`/`type`; `name` and `type`
271
- cannot combine with each other.
71
+ export const secrets = new SecretStore(components.secretStore);
72
+ ```
272
73
 
273
- ### `rotate`
74
+ 5. Save a secret and read it back, in `convex/demo.ts`.
274
75
 
275
- ```ts
276
- await secrets.rotate(ctx);
277
- // → { rotated, skipped, isDone }
278
- ```
76
+ ```ts
77
+ import { v } from "convex/values";
78
+ import { internalMutation, internalQuery } from "./_generated/server.js";
79
+ import { secrets } from "./secrets.js";
80
+
81
+ export const save = internalMutation({
82
+ args: { value: v.string() },
83
+ handler: async (ctx, { value }) => {
84
+ await secrets.put(ctx, { namespace: "acme", name: "openai", value });
85
+ },
86
+ });
279
87
 
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.
88
+ export const check = internalQuery({
89
+ args: {},
90
+ handler: async (ctx) => {
91
+ const result = await secrets.get(ctx, {
92
+ namespace: "acme",
93
+ name: "openai",
94
+ });
95
+ return result.ok ? "found" : result.reason;
96
+ },
97
+ });
98
+ ```
283
99
 
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.
100
+ ```sh
101
+ npx convex run demo:save '{"value":"sk-test"}'
102
+ npx convex run demo:check
103
+ ```
289
104
 
290
- ### `isRotationComplete`
105
+ The second command prints `"found"`. Before a public function passes a
106
+ namespace to `secrets`, check that the caller may use it. The
107
+ [security model](https://github.com/gaganref/convex-secret-store/blob/main/docs/security.md)
108
+ explains why.
291
109
 
292
- ```ts
293
- await secrets.isRotationComplete(ctx);
294
- // → boolean
295
- ```
110
+ ## Common questions
296
111
 
297
- `true` when every secret is on the active KEK version. Use this as the gate
298
- before retiring an old key.
112
+ **I set `SECRET_STORE_KEYS` with `npx convex env set`, and the push still
113
+ fails.**
299
114
 
300
- ### `cleanupSecrets` / `cleanupEvents`
115
+ The component reads the variable only through your app config. Declare it in
116
+ `defineApp({ env })` and pass `app.env.SECRET_STORE_KEYS`, as in step 2.
301
117
 
302
- ```ts
303
- await secrets.cleanupSecrets(ctx, { retentionMs? }); // default 30 days
304
- await secrets.cleanupEvents(ctx, { retentionMs? }); // default 180 days
305
- ```
118
+ **An older guide passes keys to
119
+ `new SecretStore(components.secretStore, { keys })`.**
306
120
 
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.
121
+ That was the 0.1 API. Since 0.2, keys live in `SECRET_STORE_KEYS`, and the
122
+ client takes only the component.
310
123
 
311
- ## Expiry
124
+ **How do I move to a new key?**
312
125
 
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
- ```
126
+ Add a new version and keep the old one, for example
127
+ `npx convex env set SECRET_STORE_KEYS "1:<old>,2:<new>"`. New writes use the
128
+ highest version right away. Call `secrets.rotate(ctx)` once, wait until
129
+ `secrets.isRotationComplete(ctx)` returns `true`, then set the variable to the
130
+ new key only. The
131
+ [keys guide](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/keys.md)
132
+ has the full steps.
319
133
 
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.
134
+ **What happens if I remove a key that secrets still use?**
323
135
 
324
- ## Key rotation
136
+ Those secrets read as `key_unavailable`, and rotation leaves them alone.
137
+ `secrets.orphanKeyVersions(ctx)` lists the missing versions. Add the key back,
138
+ and the secrets read again.
325
139
 
326
- Rotation is a deploy-time exercise. The component drains in the background once
327
- triggered.
140
+ **Can I read these secrets outside Convex?**
328
141
 
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:
372
-
373
- ```ts
374
- // convex/cleanup.ts
375
- import { internalMutation } from "./_generated/server.js";
376
- import { secrets } from "./secrets.js";
377
-
378
- export const cleanupSecrets = internalMutation({
379
- handler: (ctx) => secrets.cleanupSecrets(ctx),
380
- });
381
- export const cleanupEvents = internalMutation({
382
- handler: (ctx) => secrets.cleanupEvents(ctx),
383
- });
384
- ```
142
+ Yes. `convex-secret-store/envelope` has the same encryption with no Convex
143
+ dependency, so a Worker or a script can read and write compatible values. See
144
+ [using it outside Convex](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/outside-convex.md).
385
145
 
386
- ```ts
387
- // convex/crons.ts
388
- import { cronJobs } from "convex/server";
389
- import { internal } from "./_generated/api.js";
146
+ **Are names and metadata encrypted?**
390
147
 
391
- const crons = cronJobs();
392
- crons.interval("cleanup expired secrets", { hours: 24 }, internal.cleanup.cleanupSecrets);
393
- crons.interval("cleanup audit events", { hours: 24 }, internal.cleanup.cleanupEvents);
394
- export default crons;
395
- ```
148
+ No. Only the value is encrypted. Names, namespaces, metadata, expiry times and
149
+ audit events are stored as plain text, so keep sensitive data out of them.
396
150
 
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:
151
+ ## How you know it's working
399
152
 
400
- ```ts
401
- import { components } from "./_generated/api.js";
153
+ - `secrets.get` returns `{ ok: true, value }` for a secret you saved.
154
+ - In the Convex dashboard, the component's `secrets` table shows ciphertext,
155
+ never your value.
156
+ - After a rotation, `secrets.isRotationComplete(ctx)` returns `true`.
157
+ - A secret with a `ttlMs` shows as expired on an open page, without a reload.
402
158
 
403
- crons.interval(
404
- "cleanup expired secrets",
405
- { hours: 24 },
406
- components.secretStore.cleanup.cleanupSecrets,
407
- { retentionMs: 30 * 24 * 60 * 60 * 1000 },
408
- );
409
- ```
159
+ ## Learn more
410
160
 
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.
414
-
415
- ## Optional: rotation safety-net cron
416
-
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:
423
-
424
- ```ts
425
- // convex/crons.ts (in addition to the cleanup crons above)
426
- import { components } from "./_generated/api.js";
427
-
428
- crons.interval(
429
- "secret-store rotation",
430
- { hours: 24 },
431
- components.secretStore.lib.rotate,
432
- {},
433
- );
434
- ```
161
+ - Guides:
162
+ [keys and rotation](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/keys.md),
163
+ [expiry](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/expiry.md),
164
+ [cleanup](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/cleanup.md),
165
+ [using it outside Convex](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/outside-convex.md)
166
+ and
167
+ [upgrading from 0.2](https://github.com/gaganref/convex-secret-store/blob/main/docs/guides/upgrading.md).
168
+ - [Reference](https://github.com/gaganref/convex-secret-store/blob/main/docs/reference.md)
169
+ lists every function with its arguments, results and errors.
170
+ - [Security model](https://github.com/gaganref/convex-secret-store/blob/main/docs/security.md)
171
+ covers what the encryption protects against and what it does not.
172
+ - The
173
+ [example app](https://github.com/gaganref/convex-secret-store/tree/main/example)
174
+ shows paging, rotation and cleanup in a small Vite app.
435
175
 
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.
440
-
441
- ## Errors
442
-
443
- Every backend failure surfaces as a `ConvexError` whose `data` carries a typed
444
- code:
445
-
446
- ```ts
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
- }
464
- ```
176
+ Found a bug, or want a feature?
177
+ [Open an issue](https://github.com/gaganref/convex-secret-store/issues).
465
178
 
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
- - **Audit events are advisory, not tamper-evident.** Events live in the same
486
- database as the secrets and have no append-only enforcement; treat them as a
487
- forensic trail visible to anyone with deployment access, not as evidence of
488
- record.
489
-
490
- See `docs/adr/0001-component-side-encryption.md` for the architecture trade-off.
491
-
492
- ## Example app
493
-
494
- The [`example/`](./example) directory contains a small Vite + Convex app:
495
-
496
- - **Secrets** — store, replace, preview (masked), and remove environment
497
- secrets
498
- - **Activity** — paginate the audit log
499
- - **Settings** — version counts per scope, rotation controls, cleanup buttons,
500
- and demo data seeding
501
-
502
- The example mounts the component with `defineKeys({ 1: process.env.MY_APP_KEK_V1!, 2: process.env.MY_APP_KEK_V2! })`,
503
- demonstrating the validated-env pattern.
504
-
505
- > **Note:** The example UI is intentionally simple and unauthenticated. In a
506
- > real app, gate secret read/write flows behind your auth and authorization
507
- > layer before exposing them to operators.
179
+ <!-- END: Include on https://convex.dev/components -->
508
180
 
509
181
  ## Development
510
182
 
511
183
  ```sh
512
184
  npm install
513
- npm run dev # backend + frontend together
514
- npm run build # build the published package
185
+ npm run dev
186
+ npm run build
187
+ npm test
515
188
  npm run typecheck
516
189
  npm run lint
517
- npm test
518
190
  ```
519
191
 
520
- Architectural decisions are recorded in [`docs/adr/`](./docs/adr).
521
- Domain terminology is in [`CONTEXT.md`](./CONTEXT.md).
522
-
523
- <!-- END: Include on https://convex.dev/components -->
192
+ Design decisions are in [`docs/adr/`](./docs/adr), and domain terms are in
193
+ [`CONTEXT.md`](./CONTEXT.md).
@@ -1 +1 @@
1
- {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAmBtD;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAYtD"}
1
+ {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAoBtD;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAYtD"}
package/dist/base64.js CHANGED
@@ -16,6 +16,7 @@ export function decodeBase64(input) {
16
16
  }
17
17
  }
18
18
  catch (error) {
19
+ // eslint-disable-next-line preserve-caught-error -- Preserve the existing error shape for package consumers.
19
20
  throw new Error(`invalid base64 input: ${String(error)}`);
20
21
  }
21
22
  throw new Error(UNAVAILABLE);