@vllnt/convex-api-keys 0.4.0-canary.d1df60e → 0.4.0-canary.efaba72

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.
package/README.md CHANGED
@@ -1,176 +1,365 @@
1
- <!-- Badges -->
2
-
3
- [![Convex Component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
4
- [![npm version](https://img.shields.io/npm/v/@vllnt/convex-api-keys.svg)](https://www.npmjs.com/package/@vllnt/convex-api-keys)
5
- [![CI](https://github.com/vllnt/convex-api-keys/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-api-keys/actions/workflows/ci.yml)
6
- [![License](https://img.shields.io/npm/l/@vllnt/convex-api-keys.svg)](./LICENSE)
7
-
8
1
  # @vllnt/convex-api-keys
9
2
 
10
- Secure API key management as a
11
- [Convex component](https://docs.convex.dev/components) — create, validate,
12
- revoke, rotate, and track usage with built-in auth boundaries and structured
13
- audit logging.
14
-
15
- ```ts
16
- const apiKeys = new ApiKeys(components.apiKeys, { prefix: "myapp" });
17
- const { key, keyId } = await apiKeys.create(ctx, {
18
- name: "SDK Key",
19
- ownerId: orgId,
20
- });
21
- const result = await apiKeys.validate(ctx, { key: bearerToken });
22
- // result.valid → { keyId, ownerId, scopes, ... } | result.reason
23
- ```
24
-
25
- ## Features
3
+ Convex component to create, validate, revoke and rotate API keys, stored as SHA-256 hashes, with owner scoping, scopes, expiry, use limits and usage counts.
26
4
 
27
- - **Secure by default** — SHA-256 hashed storage, constant-time comparison,
28
- prefix-indexed O(1) lookup, server-side secret generation.
29
- - **Owner checks** — key-management methods match the supplied `ownerId`; the
30
- host still authenticates and authorizes callers. `configure` is a separate
31
- host-admin-only surface.
32
- - **Key types** — `secret` and `publishable` keys with type-encoded prefixes.
33
- - **Finite-use keys** — `remaining` counter with atomic decrement for
34
- one-time-use tokens.
35
- - **Disable / enable** — reversible pause without revoking.
36
- - **Read-only status check** — `matchStatus` reports a key's stored status (or
37
- `null`) without the `validate` write, for refusing dead keys cheaply.
38
- - **Rotation** — configurable grace period (60s–30d) where both old and new keys
39
- are valid.
40
- - **Bulk revoke by tag, tags & environments, multi-tenant scoping, usage
41
- tracking, input validation, structured audit logging.**
42
-
43
- ## Installation
5
+ ## For coding agents
44
6
 
45
- Requires `convex@^1.45.0`.
7
+ `node_modules/@vllnt/convex-api-keys/` holds `docs/API.md`, `CHANGELOG.md`,
8
+ `llms.txt` and the TypeScript source in `src/`, all matching the installed
9
+ version. Read them before writing code against this package.
10
+
11
+ ## When to use
12
+
13
+ - Use it when a Convex app issues API keys to its users or organizations and
14
+ checks them on each request.
15
+ - Use it when keys need scopes, tags, an environment, an expiry, a use limit,
16
+ rotation with a grace period, or per-key usage counts.
17
+ - Use it when one deployment holds keys for many tenants and every key-level
18
+ admin call must match the key's `ownerId`.
19
+ - Do not use it when the token is short-lived and shown once (invite or reset
20
+ links): use
21
+ [`@vllnt/convex-tokens`](https://oss.vllnt.com/packages/convex-tokens).
22
+ - Do not use it when you need user sign-in sessions or OAuth: use
23
+ [Convex Auth](https://labs.convex.dev/auth) or your identity provider.
24
+ - Do not use it when you need request rate limiting: use
25
+ [`@convex-dev/rate-limiter`](https://github.com/convex/rate-limiter);
26
+ this package has none.
27
+
28
+ ## Install
46
29
 
47
30
  ```bash
48
31
  npm install convex @vllnt/convex-api-keys
49
32
  ```
50
33
 
51
- Prereleases are published under the `canary` dist-tag
52
- (`npm install @vllnt/convex-api-keys@canary`); pin the resolved version for
53
- reproducible installs.
34
+ ## Quick start
54
35
 
55
- Register in your `convex/convex.config.ts`:
36
+ Mount the component, then create and check keys from your own functions.
56
37
 
57
38
  ```ts
39
+ // convex/convex.config.ts
58
40
  import { defineApp } from "convex/server";
59
41
  import apiKeys from "@vllnt/convex-api-keys/convex.config";
60
42
 
61
43
  const app = defineApp();
62
44
  app.use(apiKeys);
45
+
63
46
  export default app;
64
47
  ```
65
48
 
66
- > **Rate limiting** is your responsibility — add `@convex-dev/rate-limiter` at
67
- > your HTTP action/mutation layer where you have real caller context (IP, auth,
68
- > plan tier). The component has none. Scope enforcement is yours too: `validate`
69
- > returns the key's `scopes`; check them before acting.
70
-
71
- ## For coding agents
72
-
73
- The npm package bundles its docs at `node_modules/@vllnt/convex-api-keys/`:
74
- `docs/API.md`, `CHANGELOG.md`, `llms.txt` and the TypeScript source in `src/`.
75
- They match the installed version. Read them before writing code against this
76
- package.
77
-
78
- ## Usage
79
-
80
- Expose a host mutation that derives ownership from authenticated identity:
81
-
82
49
  ```ts
83
50
  // convex/keys.ts
51
+ import { v } from "convex/values";
84
52
  import { ApiKeys } from "@vllnt/convex-api-keys";
85
53
  import { components } from "./_generated/api";
86
54
  import { mutation } from "./_generated/server";
87
- import { v } from "convex/values";
88
55
 
89
- const apiKeys = new ApiKeys(components.apiKeys);
56
+ const apiKeys = new ApiKeys(components.apiKeys, { prefix: "myapp" });
90
57
 
91
- export const create = mutation({
58
+ export const createKey = mutation({
92
59
  args: { name: v.string() },
93
60
  handler: async (ctx, { name }) => {
94
61
  const identity = await ctx.auth.getUserIdentity();
95
62
  if (!identity) throw new Error("Unauthenticated");
96
- return apiKeys.create(ctx, { name, ownerId: identity.tokenIdentifier });
63
+ // `key` is returned only here; the component stores its SHA-256 hash.
64
+ return await apiKeys.create(ctx, {
65
+ name,
66
+ ownerId: identity.tokenIdentifier,
67
+ });
68
+ },
69
+ });
70
+
71
+ export const checkKey = mutation({
72
+ args: { key: v.string() },
73
+ handler: async (ctx, { key }) => {
74
+ const result = await apiKeys.validate(ctx, { key });
75
+ if (!result.valid) return { ok: false as const, reason: result.reason };
76
+ return {
77
+ ok: true as const,
78
+ ownerId: result.ownerId,
79
+ scopes: result.scopes,
80
+ };
97
81
  },
98
82
  });
99
83
  ```
100
84
 
101
- Show the returned raw key only to its owner; do not log or persist it. For
102
- shared organization ownership, replace this mapping with a host authorization
103
- check. The following calls illustrate the API inside authorized server handlers:
85
+ Run `npx convex dev` once after adding the component so `components.apiKeys`
86
+ exists in `convex/_generated/api`.
87
+
88
+ ## API
89
+
90
+ Full reference: [docs/API.md](./docs/API.md).
91
+
92
+ | Export | Import path | What it is |
93
+ | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- |
94
+ | [`ApiKeys`](./docs/API.md#apikeys-class) | `@vllnt/convex-api-keys` | Client class; `new ApiKeys(components.apiKeys, config?)` |
95
+ | [`create(ctx, options)`](./docs/API.md#createctx-options) | method | Mutation: new key, returns `{ keyId, key }` once |
96
+ | [`validate(ctx, { key })`](./docs/API.md#validatectx--key-) | method | Mutation: check a key, count one use, return `ValidationResult` |
97
+ | [`matchStatus(ctx, { key })`](./docs/API.md#matchstatusctx--key-) | method | Query: stored status or `null`; writes nothing |
98
+ | [`revoke(ctx, { keyId, ownerId })`](./docs/API.md#revokectx--keyid-ownerid-) | method | Mutation: make a key `revoked` (no-op for final keys) |
99
+ | [`revokeByTag(ctx, { ownerId, tag })`](./docs/API.md#revokebytagctx--ownerid-tag-) | method | Mutation: revoke an owner's keys with a tag, returns `{ revokedCount }` |
100
+ | [`rotate(ctx, { keyId, ownerId, gracePeriodMs? })`](./docs/API.md#rotatectx--keyid-ownerid-graceperiodms-) | method | Mutation: new key; old key valid for the grace period |
101
+ | [`update(ctx, { keyId, ownerId, ... })`](./docs/API.md#updatectx--keyid-ownerid-name-scopes-tags-metadata-) | method | Mutation: change `name`, `scopes`, `tags`, `metadata` |
102
+ | [`disable(ctx, { keyId, ownerId })`](./docs/API.md#disablectx--keyid-ownerid-) | method | Mutation: pause an `active` key |
103
+ | [`enable(ctx, { keyId, ownerId })`](./docs/API.md#enablectx--keyid-ownerid-) | method | Mutation: resume a `disabled` key |
104
+ | [`list(ctx, { ownerId, env?, status?, limit? })`](./docs/API.md#listctx--ownerid-env-status-limit-) | method | Query: up to `limit` (default 100) keys, no cursor |
105
+ | [`listByTag(ctx, { ownerId, tag, limit? })`](./docs/API.md#listbytagctx--ownerid-tag-limit-) | method | Query: up to `limit` (default 100) keys with a tag, no cursor |
106
+ | [`getUsage(ctx, { keyId, ownerId })`](./docs/API.md#getusagectx--keyid-ownerid-) | method | Query: `{ total, remaining? }` |
107
+ | [`configure(ctx, { ... })`](./docs/API.md#configurectx--cleanupintervalms-defaultexpiryms-) | method | Mutation: store config values (currently unused) |
108
+ | [`ApiKeysConfig`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: `{ prefix?, defaultType? }` |
109
+ | [`CreateKeyOptions`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: options of `create` |
110
+ | [`CreateKeyResult`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: `{ keyId, key }` |
111
+ | [`ValidationResult`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: result of `validate`, narrow on `valid` |
112
+ | [`ValidationFailureReason`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: `reason` when `valid` is `false` |
113
+ | [`KeyMetadata`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: one entry of `list` / `listByTag` |
114
+ | [`UsageStats`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: result of `getUsage` |
115
+ | [`RotateResult`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: `{ newKeyId, newKey, oldKeyExpiresAt }` |
116
+ | [`KeyType`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: `"secret" \| "publishable"` |
117
+ | [`KeyStatus`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: the six stored statuses |
118
+ | [`RunMutationCtx`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: any ctx with `runMutation` |
119
+ | [`RunQueryCtx`](./docs/API.md#types) | `@vllnt/convex-api-keys` | Type: any ctx with `runQuery` |
120
+ | [default export](./docs/API.md#package-exports) | `@vllnt/convex-api-keys/convex.config` | Component definition for `app.use()` |
121
+ | [`register(t, name?)`](./docs/API.md#package-exports) | `@vllnt/convex-api-keys/test` | Mount the component in `convex-test` |
122
+ | [default export](./docs/API.md#package-exports) | `@vllnt/convex-api-keys/test` | `{ register, schema, modules }` |
123
+ | [`ComponentApi`](./docs/API.md#package-exports) | `@vllnt/convex-api-keys/_generated/component` | Type of `components.apiKeys` |
124
+
125
+ ## Common tasks
126
+
127
+ ### Check a bearer key in an HTTP action
104
128
 
105
129
  ```ts
130
+ // convex/http.ts
131
+ import { httpRouter } from "convex/server";
106
132
  import { ApiKeys } from "@vllnt/convex-api-keys";
107
133
  import { components } from "./_generated/api";
134
+ import { httpAction } from "./_generated/server";
108
135
 
109
- const apiKeys = new ApiKeys(components.apiKeys, {
110
- prefix: "myapp", // key prefix (default: "vk")
111
- defaultType: "secret",
136
+ const apiKeys = new ApiKeys(components.apiKeys, { prefix: "myapp" });
137
+ const http = httpRouter();
138
+
139
+ http.route({
140
+ path: "/v1/orders",
141
+ method: "GET",
142
+ handler: httpAction(async (ctx, request) => {
143
+ const header = request.headers.get("Authorization") ?? "";
144
+ const key = header.startsWith("Bearer ")
145
+ ? header.slice("Bearer ".length)
146
+ : "";
147
+ const result = await apiKeys.validate(ctx, { key });
148
+ if (!result.valid) return new Response("Unauthorized", { status: 401 });
149
+ // The component returns scopes; enforcing them is up to you.
150
+ if (!result.scopes.includes("read:orders")) {
151
+ return new Response("Forbidden", { status: 403 });
152
+ }
153
+ return new Response(JSON.stringify({ ownerId: result.ownerId }), {
154
+ headers: { "Content-Type": "application/json" },
155
+ });
156
+ }),
112
157
  });
113
158
 
114
- // Create — secret material is generated server-side, returned once.
115
- const { key, keyId } = await apiKeys.create(ctx, {
116
- name: "Production SDK Key",
117
- ownerId: orgId,
118
- type: "secret",
119
- scopes: ["read:users", "write:orders"],
120
- tags: ["sdk", "v2"],
121
- env: "live",
122
- });
123
- // key = "myapp_secret_live_a1b2c3d4_<64-char-hex>"
159
+ export default http;
160
+ ```
161
+
162
+ ### Manage an owner's keys
163
+
164
+ ```ts
165
+ // convex/manageKeys.ts
166
+ import { v } from "convex/values";
167
+ import type { Auth } from "convex/server";
168
+ import { ApiKeys } from "@vllnt/convex-api-keys";
169
+ import { components } from "./_generated/api";
170
+ import { mutation, query } from "./_generated/server";
124
171
 
125
- // Validate — track usage and narrow on `valid`.
126
- const result = await apiKeys.validate(ctx, { key: bearerToken });
127
- if (!result.valid) {
128
- // result.reason: "malformed" | "not_found" | "revoked" | "expired" | "exhausted" | "disabled"
129
- return new Response("Unauthorized", { status: 401 });
172
+ const apiKeys = new ApiKeys(components.apiKeys, { prefix: "myapp" });
173
+
174
+ async function ownerOf(ctx: { auth: Auth }): Promise<string> {
175
+ const identity = await ctx.auth.getUserIdentity();
176
+ if (!identity) throw new Error("Unauthenticated");
177
+ return identity.tokenIdentifier;
130
178
  }
131
- const { ownerId, scopes, tags, env, type, metadata, remaining } = result;
179
+
180
+ export const createLimitedKey = mutation({
181
+ args: { name: v.string() },
182
+ handler: async (ctx, { name }) =>
183
+ await apiKeys.create(ctx, {
184
+ name,
185
+ ownerId: await ownerOf(ctx),
186
+ type: "secret",
187
+ env: "test",
188
+ scopes: ["read:orders"],
189
+ tags: ["ci"],
190
+ remaining: 1000,
191
+ expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
192
+ }),
193
+ });
194
+
195
+ export const listKeys = query({
196
+ args: {},
197
+ handler: async (ctx) =>
198
+ await apiKeys.list(ctx, { ownerId: await ownerOf(ctx), status: "active" }),
199
+ });
200
+
201
+ export const rotateKey = mutation({
202
+ args: { keyId: v.string() },
203
+ handler: async (ctx, { keyId }) =>
204
+ await apiKeys.rotate(ctx, {
205
+ keyId,
206
+ ownerId: await ownerOf(ctx),
207
+ gracePeriodMs: 24 * 60 * 60 * 1000,
208
+ }),
209
+ });
210
+
211
+ export const revokeKey = mutation({
212
+ args: { keyId: v.string() },
213
+ handler: async (ctx, { keyId }) =>
214
+ await apiKeys.revoke(ctx, { keyId, ownerId: await ownerOf(ctx) }),
215
+ });
216
+
217
+ export const revokeTag = mutation({
218
+ args: { tag: v.string() },
219
+ handler: async (ctx, { tag }) =>
220
+ await apiKeys.revokeByTag(ctx, { ownerId: await ownerOf(ctx), tag }),
221
+ });
222
+
223
+ export const pauseKey = mutation({
224
+ args: { keyId: v.string(), paused: v.boolean() },
225
+ handler: async (ctx, { keyId, paused }) => {
226
+ const ownerId = await ownerOf(ctx);
227
+ if (paused) await apiKeys.disable(ctx, { keyId, ownerId });
228
+ else await apiKeys.enable(ctx, { keyId, ownerId });
229
+ },
230
+ });
231
+
232
+ export const renameKey = mutation({
233
+ args: { keyId: v.string(), name: v.string() },
234
+ handler: async (ctx, { keyId, name }) =>
235
+ await apiKeys.update(ctx, { keyId, ownerId: await ownerOf(ctx), name }),
236
+ });
237
+
238
+ export const keyUsage = query({
239
+ args: { keyId: v.string() },
240
+ handler: async (ctx, { keyId }) =>
241
+ await apiKeys.getUsage(ctx, { keyId, ownerId: await ownerOf(ctx) }),
242
+ });
132
243
  ```
133
244
 
134
- See [docs/API.md](docs/API.md) for the full method reference, key format, and
135
- lifecycle.
136
-
137
- ## API Reference
138
-
139
- | Method | Ctx | Description |
140
- | ------------------------------------------------- | -------- | -------------------------------------- |
141
- | `create(ctx, options)` | mutation | Create a new API key |
142
- | `validate(ctx, { key })` | mutation | Validate and track usage |
143
- | `revoke(ctx, { keyId, ownerId })` | mutation | Permanently revoke a key |
144
- | `revokeByTag(ctx, { ownerId, tag })` | mutation | Bulk revoke by tag |
145
- | `rotate(ctx, { keyId, ownerId, gracePeriodMs? })` | mutation | Rotate with grace period |
146
- | `update(ctx, { keyId, ownerId, name?, ... })` | mutation | Update metadata in-place |
147
- | `disable(ctx, { keyId, ownerId })` | mutation | Temporarily disable |
148
- | `enable(ctx, { keyId, ownerId })` | mutation | Re-enable a disabled key |
149
- | `configure(ctx, { ... })` | mutation | Runtime config (admin-only) |
150
- | `list(ctx, { ownerId, env?, status?, limit? })` | query | Bounded array (default 100; no cursor) |
151
- | `listByTag(ctx, { ownerId, tag, limit? })` | query | Filter by tag |
152
- | `matchStatus(ctx, { key })` | query | Stored status or null; no usage write |
153
- | `getUsage(ctx, { keyId, ownerId })` | query | Usage counter (O(1)) |
154
-
155
- `list` and `listByTag` return bounded arrays, not cursor-based pages; repeated
156
- calls do not advance through the remaining keys. Authorize reads and mutations
157
- in the host before supplying an `ownerId`.
158
-
159
- Full reference: [docs/API.md](docs/API.md).
245
+ ### Read a key's status inside a query
160
246
 
161
- ## Security
247
+ `validate` is a mutation (it counts a use). In a query, use `matchStatus`; it
248
+ writes nothing and reads the stored status only.
162
249
 
163
- - Protects against **accidental cross-tenant bugs in honest host apps** — the
164
- `ownerId` check does NOT defend against a compromised host passing a forged
165
- `ownerId`.
166
- - Derive `ownerId` from your own auth layer (e.g. `ctx.auth.getUserIdentity()`)
167
- before passing it in.
168
- - Raw keys are never stored — only the SHA-256 hash; the raw value is returned
169
- once at creation.
250
+ ```ts
251
+ // convex/keyStatus.ts
252
+ import { v } from "convex/values";
253
+ import { ApiKeys } from "@vllnt/convex-api-keys";
254
+ import { components } from "./_generated/api";
255
+ import { query } from "./_generated/server";
256
+
257
+ const apiKeys = new ApiKeys(components.apiKeys, { prefix: "myapp" });
170
258
 
171
- See [docs/API.md](docs/API.md).
259
+ export const keyStatus = query({
260
+ args: { key: v.string() },
261
+ handler: async (ctx, { key }) => {
262
+ const status = await apiKeys.matchStatus(ctx, { key });
263
+ // "active" and "rotating" can be past their expiry until validate() runs.
264
+ return status === "active" || status === "rotating"
265
+ ? "maybe-valid"
266
+ : (status ?? "unknown");
267
+ },
268
+ });
269
+ ```
172
270
 
173
- ## Testing your app
271
+ ## Errors and fixes
272
+
273
+ `validate` never throws for a bad key; it returns `{ valid: false, reason }`.
274
+ Every other method throws an `Error` with one of these messages. Match with
275
+ `message.includes(...)` inside your own Convex function: Convex can prefix the
276
+ text (for example `Uncaught Error: `), and a client of a production
277
+ deployment receives a generic `Server Error` message instead, because these are
278
+ not `ConvexError`s (see
279
+ [Convex error handling](https://docs.convex.dev/functions/error-handling#differences-in-error-reporting-between-dev-and-prod)).
280
+
281
+ | Error or `reason` | Cause | Fix |
282
+ | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- |
283
+ | `reason: "malformed"` | The string is not `{prefix}_{type}_{env}_{8 chars}_{64 chars}` | Send the full key as returned by `create` or `rotate` |
284
+ | `reason: "not_found"` | No stored key has this prefix and hash (also a 64-character secret that is not hex) | The key was mistyped or never existed; ask for a new key |
285
+ | `reason: "revoked"` | The key was revoked | Issue a new key with `create` |
286
+ | `reason: "disabled"` | The key was paused with `disable` | Call `enable`, or issue a new key |
287
+ | `reason: "expired"` | `expiresAt` passed, or a rotated key's grace period ended | Use the key returned by `rotate`, or issue a new key |
288
+ | `reason: "exhausted"` | `remaining` reached 0 | Issue a new key with a new `remaining` |
289
+ | `key not found` | No key has this `keyId` | Pass a `keyId` from `create`, `rotate` or `list` |
290
+ | `unauthorized: key does not belong to owner` | `ownerId` differs from the key's owner | Pass the same `ownerId` that created the key |
291
+ | `ownerId must not be empty` | `create` got `ownerId: ""` | Derive `ownerId` from your auth layer |
292
+ | `name must not be empty` | `create` or `update` got `name: ""` | Pass a non-empty name |
293
+ | `name must be <= 256 characters` | `name` is longer than 256 characters | Shorten it |
294
+ | `Invalid keyPrefix "<prefix>": must match ^[a-zA-Z0-9]+$ (alphanumeric only, no underscores)` | `ApiKeysConfig.prefix` has other characters | Use letters and digits only |
295
+ | `keyPrefix must be <= 256 characters` | `prefix` is longer than 256 characters | Shorten it |
296
+ | `Invalid env "<env>": must match ^[a-zA-Z0-9-]+$ (no underscores — would break key parsing)` | `env` is empty or has an underscore or other characters | Use letters, digits and `-` |
297
+ | `env must be <= 256 characters` | `env` is longer than 256 characters | Shorten it |
298
+ | `Invalid tag "<tag>": must be alphanumeric with hyphens, starting with alphanumeric` | A tag (or `revokeByTag`'s `tag`) is empty or has other characters | Use letters, digits and `-`, starting with a letter or digit |
299
+ | `tags must have <= 20 entries (got <n>)` | More than 20 tags | Pass at most 20 |
300
+ | `scopes must have <= 50 entries (got <n>)` | More than 50 scopes | Pass at most 50 |
301
+ | `metadata must be <= 4096 bytes (got <n>)` | `JSON.stringify(metadata)` is longer than 4096 characters | Store less, or keep a reference to your own table |
302
+ | `expiresAt must be in the future (finite timestamp)` | `expiresAt` is in the past, `NaN` or `Infinity` | Pass a future `Date.now()`-style timestamp in ms |
303
+ | `remaining must be > 0 (finite integer)` | `remaining` is 0, negative, fractional, `NaN` or `Infinity` | Pass a positive integer, or leave it out for unlimited use |
304
+ | `limit must be a positive integer` | `list` / `listByTag` got `limit` ≤ 0, fractional, `NaN` or `Infinity` | Pass a positive integer, or leave it out (default 100) |
305
+ | `cannot rotate a terminal key` | The key is `revoked`, `expired` or `exhausted` | Issue a new key with `create` |
306
+ | `can only rotate active keys` | The key is `disabled` or already `rotating` | `enable` it first, or rotate the newest key |
307
+ | `cannot rotate finite-use keys` | The key has `remaining` | Create a new key with the remaining quota, then `revoke` the old one |
308
+ | `cannot rotate an expired key` | The key is past `expiresAt` but not yet marked `expired` | Issue a new key with `create` |
309
+ | `gracePeriodMs must be between 60000 (60s) and 2592000000 (30 days)` | `gracePeriodMs` is out of range or `NaN` | Pass 60,000 to 2,592,000,000, or leave it out (default 1 hour) |
310
+ | `cannot update terminal key` | `update` on a `revoked`, `expired` or `exhausted` key | Issue a new key instead |
311
+ | `can only disable active keys` | `disable` on a key that is not `active` or `disabled` | Only pause active keys |
312
+ | `can only enable disabled keys` | `enable` on a key that is not `disabled` or `active` | Only resume disabled keys |
313
+ | `cleanupIntervalMs must be > 0 (finite number)` | `configure` got 0, negative, `NaN` or `Infinity` | Pass a positive finite number |
314
+ | `defaultExpiryMs must be > 0 (finite number)` | `configure` got 0, negative, `NaN` or `Infinity` | Pass a positive finite number |
315
+ | Argument validation error (message from Convex) | An argument does not match its validator, e.g. a `keyId` that is not an `apiKeys` id; Convex rejects the call before the handler runs | Pass `keyId` values returned by this component |
316
+
317
+ ## Limits and gotchas
318
+
319
+ - The raw key is returned once, by `create` or `rotate`. Only its SHA-256 hash
320
+ is stored; a lost key cannot be recovered.
321
+ - Defaults: `prefix` `"vk"`, `type` `"secret"`, `env` `"live"`, `gracePeriodMs`
322
+ 1 hour, `limit` 100.
323
+ - Limits: `name`, `prefix` and `env` 256 characters; `metadata` 4096 characters
324
+ of JSON; 50 `scopes`; 20 `tags`; `gracePeriodMs` 60 seconds to 30 days.
325
+ - Key format: `{prefix}_{secret|pub}_{env}_{8 chars}_{64 chars}`. Keys are
326
+ generated with a hex secret, but parsing checks only the secret's length: a
327
+ 64-character secret that is not hex returns `not_found`. `prefix` and `env` cannot
328
+ contain `_`.
329
+ - Expiry is checked by `validate`. Until it runs, a key past `expiresAt` (or a
330
+ rotated key past its grace period) is stored as `active` / `rotating`, so
331
+ `matchStatus` and `list` show that status, and `revoke` / `revokeByTag` still
332
+ revoke it.
333
+ - `validate` is a mutation: it counts a use, decrements `remaining`, and updates
334
+ `lastUsedAt` at most once a minute. Call it from a mutation, action or HTTP
335
+ action, not a query.
336
+ - Does nothing, without an error: `revoke` on a `revoked`, `expired` or
337
+ `exhausted` key; `disable` on a `disabled` key; `enable` on an `active` key.
338
+ - `configure` only stores `cleanupIntervalMs` and `defaultExpiryMs`. No cleanup
339
+ job runs and `create` does not apply `defaultExpiryMs`; pass `expiresAt`
340
+ instead.
341
+ - `list` and `listByTag` return at most `limit` keys and have no cursor; calling
342
+ again returns the same keys.
343
+ - Rotation only works on `active` keys without `remaining` that are not past
344
+ `expiresAt`.
345
+ - The component has no rate limiting and does not enforce scopes: `validate`
346
+ returns `scopes`, and your code decides.
347
+ - `ownerId` is an opaque string you pass in. The component checks that it
348
+ matches the key's owner; it does not authenticate the caller.
349
+
350
+ ## Compatibility
351
+
352
+ - Peer dependency: `convex@^1.45.0` (0.2.0 required `^1.36.1`, 0.1.0 `^1.33.0`).
353
+ - Runtime dependency: `@convex-dev/sharded-counter` (mounted as a child
354
+ component for usage counts).
355
+ - The client works in Convex queries, mutations, actions and HTTP actions (any
356
+ `ctx` with `runQuery` / `runMutation`). Component functions run in the Convex
357
+ runtime.
358
+ - `@vllnt/convex-api-keys/test` is TypeScript source that needs `convex-test`,
359
+ `vitest` with Vite's `import.meta.glob`, and `@convex-dev/sharded-counter`.
360
+ - ESM only. `engines.node`: `>=18`.
361
+
362
+ ## Testing
174
363
 
175
364
  `@vllnt/convex-api-keys/test` exports `register(t, name = "apiKeys")` to mount
176
365
  the component in a `convex-test` instance. It needs `convex-test`, `vitest`
@@ -178,29 +367,38 @@ the component in a `convex-test` instance. It needs `convex-test`, `vitest`
178
367
  `/test` helper) installed in the consuming app:
179
368
 
180
369
  ```ts
370
+ // convex/keys.test.ts
181
371
  /// <reference types="vite/client" />
182
372
  import { convexTest } from "convex-test";
373
+ import { expect, test } from "vitest";
183
374
  import { register } from "@vllnt/convex-api-keys/test";
184
375
  import shardedCounterTest from "@convex-dev/sharded-counter/test";
185
376
  import schema from "./schema";
186
377
 
187
- const t = convexTest(schema, import.meta.glob("./**/*.ts"));
188
- register(t, "apiKeys");
189
- shardedCounterTest.register(t, "apiKeys/shardedCounter");
378
+ test("mounts the component", async () => {
379
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
380
+ register(t, "apiKeys");
381
+ shardedCounterTest.register(t, "apiKeys/shardedCounter");
382
+ expect(await t.run(async () => "ready")).toBe("ready");
383
+ });
190
384
  ```
191
385
 
386
+ ## Security
387
+
388
+ - Protects against **accidental cross-tenant bugs in honest host apps** — the
389
+ `ownerId` check does NOT defend against a compromised host passing a forged
390
+ `ownerId`.
391
+ - Derive `ownerId` from your own auth layer (e.g. `ctx.auth.getUserIdentity()`)
392
+ before passing it in.
393
+ - Raw keys are never stored — only the SHA-256 hash; the raw value is returned
394
+ once at creation. Lookup uses an 8-character indexed prefix and a
395
+ constant-time hash comparison.
396
+
397
+ See [docs/API.md](./docs/API.md#security-model).
398
+
192
399
  ## Related packages
193
400
 
194
- - [`@vllnt/convex-tokens`](https://www.npmjs.com/package/@vllnt/convex-tokens) —
195
- short-lived tokens shown once, with a TTL that always expires and revoke (for
196
- example invite or reset links). Use convex-api-keys for long-lived keys with
197
- rotation, usage counts and per-owner listing.
198
- - [`@vllnt/convex-permissions`](https://www.npmjs.com/package/@vllnt/convex-permissions)
199
- — role-based access control. Use it to decide what a validated key's owner may
200
- do; this package only returns the key's `scopes`.
201
- - [`@vllnt/convex-quota`](https://www.npmjs.com/package/@vllnt/convex-quota) —
202
- allowances that reset on a schedule (per day, week, month). Use it for per-key
203
- plan limits; `remaining` here is a one-off counter that never resets.
401
+ None. No other @vllnt package is used at runtime or in tests; `@vllnt/eslint-config` and `@vllnt/typescript` are development tools only.
204
402
 
205
403
  ## Contributing
206
404
 
@@ -208,17 +406,19 @@ See
208
406
  [CONTRIBUTING.md](https://github.com/vllnt/convex-api-keys/blob/main/CONTRIBUTING.md)
209
407
  for development setup, testing, and PR guidelines.
210
408
 
211
- ## Author
212
-
213
- Built by [bntvllnt](https://github.com/bntvllnt) ·
214
- [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
409
+ ## Links
215
410
 
216
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
411
+ - Docs and changelog: [oss.vllnt.com/packages/convex-api-keys](https://oss.vllnt.com/packages/convex-api-keys) · [release feed](https://oss.vllnt.com/packages/convex-api-keys/rss.xml)
412
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
413
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-api-keys) · [issues](https://github.com/vllnt/convex-api-keys/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-api-keys)
414
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
415
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
416
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
217
417
 
218
418
  ## License
219
419
 
220
- MIT — see [LICENSE](LICENSE).
420
+ MIT — see [LICENSE](./LICENSE).
221
421
 
222
422
  ---
223
423
 
224
- Part of vllnt oss: https://oss.vllnt.com
424
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-api-keys) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)