@gaganref/convex-api-keys 0.1.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.
- package/LICENSE +201 -0
- package/README.md +419 -0
- package/dist/client/_generated/_ignore.d.ts +1 -0
- package/dist/client/_generated/_ignore.d.ts.map +1 -0
- package/dist/client/_generated/_ignore.js +3 -0
- package/dist/client/_generated/_ignore.js.map +1 -0
- package/dist/client/crypto.d.ts +4 -0
- package/dist/client/crypto.d.ts.map +1 -0
- package/dist/client/crypto.js +48 -0
- package/dist/client/crypto.js.map +1 -0
- package/dist/client/errors.d.ts +32 -0
- package/dist/client/errors.d.ts.map +1 -0
- package/dist/client/errors.js +43 -0
- package/dist/client/errors.js.map +1 -0
- package/dist/client/index.d.ts +7 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +4 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/operations.d.ts +240 -0
- package/dist/client/operations.d.ts.map +1 -0
- package/dist/client/operations.js +700 -0
- package/dist/client/operations.js.map +1 -0
- package/dist/client/options.d.ts +79 -0
- package/dist/client/options.d.ts.map +1 -0
- package/dist/client/options.js +51 -0
- package/dist/client/options.js.map +1 -0
- package/dist/client/types.d.ts +269 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +24 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +40 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +253 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +121 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +78 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/cleanup.d.ts +29 -0
- package/dist/component/cleanup.d.ts.map +1 -0
- package/dist/component/cleanup.js +70 -0
- package/dist/component/cleanup.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +3 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/crons.d.ts +3 -0
- package/dist/component/crons.d.ts.map +1 -0
- package/dist/component/crons.js +7 -0
- package/dist/component/crons.js.map +1 -0
- package/dist/component/lib.d.ts +323 -0
- package/dist/component/lib.d.ts.map +1 -0
- package/dist/component/lib.js +659 -0
- package/dist/component/lib.js.map +1 -0
- package/dist/component/schema.d.ts +82 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +38 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/sweep.d.ts +27 -0
- package/dist/component/sweep.d.ts.map +1 -0
- package/dist/component/sweep.js +94 -0
- package/dist/component/sweep.js.map +1 -0
- package/dist/shared.d.ts +11 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +11 -0
- package/dist/shared.js.map +1 -0
- package/package.json +116 -0
- package/src/client/__tests__/contracts.test.ts +109 -0
- package/src/client/__tests__/errors.test.ts +133 -0
- package/src/client/__tests__/hooks.test.ts +154 -0
- package/src/client/__tests__/operations.test.ts +742 -0
- package/src/client/__tests__/setup.test.ts +31 -0
- package/src/client/_generated/_ignore.ts +1 -0
- package/src/client/crypto.ts +64 -0
- package/src/client/errors.ts +67 -0
- package/src/client/index.ts +44 -0
- package/src/client/operations.ts +881 -0
- package/src/client/options.ts +146 -0
- package/src/client/types.ts +313 -0
- package/src/component/__tests__/cleanup.test.ts +472 -0
- package/src/component/__tests__/lib.test.ts +676 -0
- package/src/component/__tests__/setup.test.ts +11 -0
- package/src/component/_generated/api.ts +56 -0
- package/src/component/_generated/component.ts +300 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +156 -0
- package/src/component/cleanup.ts +85 -0
- package/src/component/convex.config.ts +3 -0
- package/src/component/crons.ts +20 -0
- package/src/component/lib.ts +843 -0
- package/src/component/schema.ts +49 -0
- package/src/component/sweep.ts +117 -0
- package/src/shared.ts +18 -0
- package/src/test.ts +18 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
# Convex API Keys
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/js/@gaganref%2Fconvex-api-keys)
|
|
4
|
+
|
|
5
|
+
<!-- START: Include on https://convex.dev/components -->
|
|
6
|
+
|
|
7
|
+
A [Convex](https://convex.dev) component for API key management. Create,
|
|
8
|
+
validate, rotate, and revoke API keys with built-in expiry, idle timeout,
|
|
9
|
+
permissions, metadata, and audit logging.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
const result = await apiKeys.create(ctx, {
|
|
13
|
+
name: "Backend Server",
|
|
14
|
+
permissions: { scope: ["read", "write"] },
|
|
15
|
+
});
|
|
16
|
+
// result.token → "ak_7Kf9..."
|
|
17
|
+
|
|
18
|
+
const check = await apiKeys.validate(ctx, { token: "ak_7Kf9..." });
|
|
19
|
+
if (check.ok) {
|
|
20
|
+
// check.keyId, check.permissions, check.metadata
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Found a bug? Feature request?
|
|
25
|
+
[File it here](https://github.com/gaganref/convex-api-keys/issues).
|
|
26
|
+
|
|
27
|
+
## Pre-requisite: Convex
|
|
28
|
+
|
|
29
|
+
You'll need an existing Convex project to use this component. Convex is a hosted
|
|
30
|
+
backend platform, including a database, serverless functions, and a ton more
|
|
31
|
+
you'd need to build a production app. If you haven't used Convex before, the
|
|
32
|
+
[Convex tutorial](https://docs.convex.dev/get-started) is a great place to
|
|
33
|
+
start.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
npm install @gaganref/convex-api-keys
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Create a `convex.config.ts` file in your app's `convex/` folder and install the
|
|
42
|
+
component by calling `use`:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// convex/convex.config.ts
|
|
46
|
+
import { defineApp } from "convex/server";
|
|
47
|
+
import apiKeys from "@gaganref/convex-api-keys/convex.config.js";
|
|
48
|
+
|
|
49
|
+
const app = defineApp();
|
|
50
|
+
app.use(apiKeys);
|
|
51
|
+
|
|
52
|
+
export default app;
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
56
|
+
|
|
57
|
+
Instantiate the client in a shared file:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// convex/apiKeys.ts
|
|
61
|
+
import { ApiKeys } from "@gaganref/convex-api-keys";
|
|
62
|
+
import { components } from "./_generated/api.js";
|
|
63
|
+
|
|
64
|
+
export const apiKeys = new ApiKeys(components.apiKeys);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Use it in your mutations and queries:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// convex/myFunctions.ts
|
|
71
|
+
import { mutation, query } from "./_generated/server.js";
|
|
72
|
+
import { v } from "convex/values";
|
|
73
|
+
import { apiKeys } from "./apiKeys.js";
|
|
74
|
+
|
|
75
|
+
export const createKey = mutation({
|
|
76
|
+
args: { name: v.string() },
|
|
77
|
+
handler: async (ctx, args) => {
|
|
78
|
+
return await apiKeys.create(ctx, { name: args.name });
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export const validateKey = query({
|
|
83
|
+
args: { token: v.string() },
|
|
84
|
+
handler: async (ctx, args) => {
|
|
85
|
+
return await apiKeys.validate(ctx, { token: args.token });
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Typed Options
|
|
91
|
+
|
|
92
|
+
The `ApiKeys` class accepts a generic parameter for type-safe namespaces,
|
|
93
|
+
permissions, metadata, and required fields:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
export const apiKeys = new ApiKeys<{
|
|
97
|
+
namespace: `${string}:${"production" | "testing"}`;
|
|
98
|
+
requireName: true;
|
|
99
|
+
metadata: { source: string };
|
|
100
|
+
permissions: { scope: Array<"read" | "write" | "admin"> };
|
|
101
|
+
}>(components.apiKeys, {
|
|
102
|
+
permissionDefaults: {
|
|
103
|
+
scope: ["read"],
|
|
104
|
+
},
|
|
105
|
+
keyDefaults: {
|
|
106
|
+
prefix: "sk_",
|
|
107
|
+
ttlMs: 90 * 24 * 60 * 60 * 1000, // 90 days
|
|
108
|
+
idleTimeoutMs: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
109
|
+
},
|
|
110
|
+
logLevel: "debug",
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Type options:
|
|
115
|
+
|
|
116
|
+
- `namespace` — any `string` subtype. When set, `namespace` becomes required in
|
|
117
|
+
`create` args.
|
|
118
|
+
- `requireName` — set to `true` to require `name` in `create` args.
|
|
119
|
+
- `metadata` — shape of the metadata object stored with each key.
|
|
120
|
+
- `permissions` — shape of the permissions object. Values must be `string[]`
|
|
121
|
+
subtypes.
|
|
122
|
+
|
|
123
|
+
> **Note:** These are **compile-time type constraints only**, not runtime
|
|
124
|
+
> validators. The underlying database stores flexible types:
|
|
125
|
+
>
|
|
126
|
+
> - `namespace` → `v.optional(v.string())`
|
|
127
|
+
> - `permissions` → `v.optional(v.record(v.string(), v.array(v.string())))`
|
|
128
|
+
> - `metadata` → `v.optional(v.record(v.string(), v.any()))`
|
|
129
|
+
>
|
|
130
|
+
> If you change your type options after keys have been created, existing data is
|
|
131
|
+
> not automatically migrated — ensure your new types are backwards-compatible
|
|
132
|
+
> with stored data.
|
|
133
|
+
|
|
134
|
+
## Usage
|
|
135
|
+
|
|
136
|
+
### Create
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
const key = await apiKeys.create(ctx, {
|
|
140
|
+
name: "My API Key",
|
|
141
|
+
namespace: "acme:production",
|
|
142
|
+
permissions: { scope: ["read", "write"] },
|
|
143
|
+
metadata: { source: "dashboard" },
|
|
144
|
+
ttlMs: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
145
|
+
idleTimeoutMs: 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
146
|
+
prefix: "sk_live_", // override default prefix
|
|
147
|
+
});
|
|
148
|
+
// key.keyId — unique identifier
|
|
149
|
+
// key.token — plaintext token (only available at creation time)
|
|
150
|
+
// key.tokenPrefix — e.g. "sk_live_"
|
|
151
|
+
// key.tokenLast4 — last 4 chars for display
|
|
152
|
+
// key.createdAt — timestamp
|
|
153
|
+
// key.expiresAt — timestamp or undefined
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Validate
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const result = await apiKeys.validate(ctx, { token: "sk_live_7Kf9..." });
|
|
160
|
+
if (result.ok) {
|
|
161
|
+
// result.keyId, result.namespace, result.permissions, result.metadata
|
|
162
|
+
} else {
|
|
163
|
+
// result.reason: "not_found" | "revoked" | "expired" | "idle_timeout"
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Validation is a **read-only query** by design — it does not update the key's
|
|
168
|
+
`lastUsedAt` timestamp. This keeps validation fast and side-effect-free. Call
|
|
169
|
+
`touch` separately after you have fully authorized the request (e.g. after
|
|
170
|
+
checking permissions) to keep idle timeout tracking accurate.
|
|
171
|
+
|
|
172
|
+
### Touch
|
|
173
|
+
|
|
174
|
+
Update the `lastUsedAt` timestamp to keep idle timeout tracking accurate. Call
|
|
175
|
+
this after you have fully authorized the request — not immediately after
|
|
176
|
+
`validate`, but after any additional permission checks or business logic:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
const result = await apiKeys.validate(ctx, { token });
|
|
180
|
+
if (!result.ok) {
|
|
181
|
+
throw new Error(`Invalid key: ${result.reason}`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Check application-level permissions, enforce business rules, etc.
|
|
185
|
+
|
|
186
|
+
// Only touch after the request is fully authorized
|
|
187
|
+
await apiKeys.touch(ctx, { keyId: result.keyId });
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Get Key
|
|
191
|
+
|
|
192
|
+
Retrieve full details for a single key by ID:
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const result = await apiKeys.getKey(ctx, { keyId: "..." });
|
|
196
|
+
if (result.ok) {
|
|
197
|
+
// result.keyId, result.name, result.namespace, result.permissions
|
|
198
|
+
// result.metadata, result.effectiveStatus, result.expiresAt, etc.
|
|
199
|
+
} else {
|
|
200
|
+
// result.reason: "not_found"
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### List Keys
|
|
205
|
+
|
|
206
|
+
Paginated listing with optional namespace and status filters:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
const page = await apiKeys.listKeys(ctx, {
|
|
210
|
+
namespace: "acme:production",
|
|
211
|
+
status: "active", // or "revoked"
|
|
212
|
+
order: "desc",
|
|
213
|
+
paginationOpts: { numItems: 20, cursor: null },
|
|
214
|
+
});
|
|
215
|
+
// page.page — array of key summaries
|
|
216
|
+
// page.isDone, page.continueCursor — pagination controls
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Update
|
|
220
|
+
|
|
221
|
+
Update a key's name, metadata, expiry, or idle timeout:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
const result = await apiKeys.update(ctx, {
|
|
225
|
+
keyId: "...",
|
|
226
|
+
name: "Renamed Key",
|
|
227
|
+
metadata: { source: "updated" },
|
|
228
|
+
expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000,
|
|
229
|
+
maxIdleMs: 24 * 60 * 60 * 1000,
|
|
230
|
+
});
|
|
231
|
+
// result.ok — true on success
|
|
232
|
+
// result.reason — "not_found" or "already_revoked" on failure
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Pass `null` to `expiresAt` or `maxIdleMs` to remove them entirely.
|
|
236
|
+
|
|
237
|
+
### Invalidate (Revoke)
|
|
238
|
+
|
|
239
|
+
Revoke a single key:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
const result = await apiKeys.invalidate(ctx, {
|
|
243
|
+
keyId: "...",
|
|
244
|
+
reason: "compromised",
|
|
245
|
+
metadata: { revokedBy: "admin" },
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### Invalidate All (Bulk Revoke)
|
|
250
|
+
|
|
251
|
+
Revoke all active keys, optionally scoped by namespace and creation time:
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
const result = await apiKeys.invalidateAll(ctx, {
|
|
255
|
+
namespace: "acme:production",
|
|
256
|
+
before: Date.now(), // only keys created before this timestamp
|
|
257
|
+
reason: "security rotation",
|
|
258
|
+
});
|
|
259
|
+
// result.processed, result.revoked, result.pages
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
### Refresh (Rotate)
|
|
263
|
+
|
|
264
|
+
Atomically revoke an existing key and create a new one with the same
|
|
265
|
+
configuration:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
const result = await apiKeys.refresh(ctx, {
|
|
269
|
+
keyId: "...",
|
|
270
|
+
prefix: "sk_live_",
|
|
271
|
+
reason: "scheduled rotation",
|
|
272
|
+
});
|
|
273
|
+
if (result.ok) {
|
|
274
|
+
// result.token — new plaintext token
|
|
275
|
+
// result.keyId — new key ID
|
|
276
|
+
// result.replacedKeyId — old key ID
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### List Events (Audit Log)
|
|
281
|
+
|
|
282
|
+
Paginated event log scoped by namespace or by individual key:
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
// All events in a namespace
|
|
286
|
+
const events = await apiKeys.listEvents(ctx, {
|
|
287
|
+
namespace: "acme:production",
|
|
288
|
+
paginationOpts: { numItems: 50, cursor: null },
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
// Events for a specific key
|
|
292
|
+
const keyEvents = await apiKeys.listKeyEvents(ctx, {
|
|
293
|
+
keyId: "...",
|
|
294
|
+
paginationOpts: { numItems: 50, cursor: null },
|
|
295
|
+
});
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### Cleanup
|
|
299
|
+
|
|
300
|
+
Hard-delete revoked keys and their audit events after a retention period. It is
|
|
301
|
+
recommended to schedule this as a cron job:
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
// convex/cleanup.ts
|
|
305
|
+
import { internalMutation } from "./_generated/server.js";
|
|
306
|
+
import { apiKeys } from "./apiKeys.js";
|
|
307
|
+
|
|
308
|
+
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
309
|
+
|
|
310
|
+
export const cleanupExpiredKeys = internalMutation({
|
|
311
|
+
args: {},
|
|
312
|
+
handler: async (ctx) => {
|
|
313
|
+
return await apiKeys.cleanupExpired(ctx, { retentionMs: RETENTION_MS });
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
// convex/crons.ts
|
|
320
|
+
import { cronJobs } from "convex/server";
|
|
321
|
+
import { internal } from "./_generated/api.js";
|
|
322
|
+
|
|
323
|
+
const crons = cronJobs();
|
|
324
|
+
crons.interval(
|
|
325
|
+
"cleanup expired api keys",
|
|
326
|
+
{ hours: 24 },
|
|
327
|
+
internal.cleanup.cleanupExpiredKeys,
|
|
328
|
+
);
|
|
329
|
+
export default crons;
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
## Automatic Expiry (Sweep)
|
|
333
|
+
|
|
334
|
+
The component includes built-in cron jobs that run every hour to:
|
|
335
|
+
|
|
336
|
+
- **Sweep expired keys** — revokes active keys past their `expiresAt` timestamp.
|
|
337
|
+
- **Sweep idle keys** — revokes active keys that haven't been touched within
|
|
338
|
+
their `maxIdleMs` window.
|
|
339
|
+
|
|
340
|
+
Both sweeps use cursor-based pagination so they handle any number of keys
|
|
341
|
+
without stalling. No additional setup is required — the crons are registered
|
|
342
|
+
automatically when the component is installed.
|
|
343
|
+
|
|
344
|
+
## Configuration Options
|
|
345
|
+
|
|
346
|
+
Pass options when instantiating `ApiKeys`:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
new ApiKeys(components.apiKeys, {
|
|
350
|
+
permissionDefaults: { scope: ["read"] },
|
|
351
|
+
keyDefaults: {
|
|
352
|
+
prefix: "ak_", // token prefix (default: "ak_")
|
|
353
|
+
ttlMs: null, // absolute expiry in ms (default: null)
|
|
354
|
+
idleTimeoutMs: null, // idle timeout in ms (default: null)
|
|
355
|
+
},
|
|
356
|
+
logLevel: "warn", // "debug" | "warn" | "error" | "none"
|
|
357
|
+
});
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
### onInvalidate Hook
|
|
361
|
+
|
|
362
|
+
Register a hook that fires whenever a key is invalidated, refreshed, or bulk
|
|
363
|
+
invalidated. The hook is called inline via `ctx.runMutation` and failures are
|
|
364
|
+
swallowed so they don't affect the main operation:
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
// convex/apiKeys.ts
|
|
368
|
+
import { ApiKeys } from "@gaganref/convex-api-keys";
|
|
369
|
+
import { components, internal } from "./_generated/api.js";
|
|
370
|
+
|
|
371
|
+
export const apiKeys = new ApiKeys(components.apiKeys).withHooks({
|
|
372
|
+
onInvalidate: internal.hooks.onInvalidate,
|
|
373
|
+
});
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
// convex/hooks.ts
|
|
378
|
+
import { internalMutation } from "./_generated/server.js";
|
|
379
|
+
import { onInvalidateHookPayloadValidator } from "@gaganref/convex-api-keys";
|
|
380
|
+
|
|
381
|
+
export const onInvalidate = internalMutation({
|
|
382
|
+
args: { event: onInvalidateHookPayloadValidator },
|
|
383
|
+
handler: async (ctx, { event }) => {
|
|
384
|
+
// event.trigger: "invalidate" | "refresh" | "invalidateAll"
|
|
385
|
+
// event.keyId, event.reason, etc.
|
|
386
|
+
console.log("Key invalidated:", event);
|
|
387
|
+
},
|
|
388
|
+
});
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
## Security Model
|
|
392
|
+
|
|
393
|
+
- **Hash-only storage** — Plaintext tokens are never stored. Only a SHA-256 hash
|
|
394
|
+
is persisted; the plaintext is returned once at creation/rotation time.
|
|
395
|
+
- **256-bit entropy** — Tokens are generated with 32 bytes of cryptographically
|
|
396
|
+
random data via the Web Crypto API.
|
|
397
|
+
- **Prefix-based identification** — Token prefixes (e.g. `sk_live_`) allow
|
|
398
|
+
identifying key type without exposing the secret.
|
|
399
|
+
- **Last-4 display** — Only the last 4 characters are stored for display in
|
|
400
|
+
dashboards and logs.
|
|
401
|
+
|
|
402
|
+
## Example App
|
|
403
|
+
|
|
404
|
+
See the [example/](./example) directory for a full API keys dashboard built with
|
|
405
|
+
React, Tailwind CSS, and shadcn/ui that demonstrates all features of this
|
|
406
|
+
component.
|
|
407
|
+
|
|
408
|
+
> **Security note:** The Quick Start examples above export public mutations and
|
|
409
|
+
> queries for simplicity. In production, you should gate key management
|
|
410
|
+
> operations behind an authentication layer (e.g. Convex Auth, Clerk, Workos)
|
|
411
|
+
> and verify the caller has appropriate permissions before creating, revoking,
|
|
412
|
+
> or listing keys.
|
|
413
|
+
|
|
414
|
+
```sh
|
|
415
|
+
npm i
|
|
416
|
+
npm run dev
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
<!-- END: Include on https://convex.dev/components -->
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=_ignore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_ignore.d.ts","sourceRoot":"","sources":["../../../src/client/_generated/_ignore.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_ignore.js","sourceRoot":"","sources":["../../../src/client/_generated/_ignore.ts"],"names":[],"mappings":";AAAA,kEAAkE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/client/crypto.ts"],"names":[],"mappings":"AAIA,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,CAG5E;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAMpE;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,UAEvC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { runtimeUnavailableError } from "./errors.js";
|
|
2
|
+
const textEncoder = new TextEncoder();
|
|
3
|
+
export function generateToken(prefix, keyLengthBytes) {
|
|
4
|
+
const bytes = randomBytes(keyLengthBytes);
|
|
5
|
+
return `${prefix}${base64UrlEncode(bytes)}`;
|
|
6
|
+
}
|
|
7
|
+
export async function sha256Base64Url(value) {
|
|
8
|
+
const hash = await getSubtleOrThrow().digest("SHA-256", textEncoder.encode(value));
|
|
9
|
+
return base64UrlEncode(new Uint8Array(hash));
|
|
10
|
+
}
|
|
11
|
+
export function tokenLast4(token) {
|
|
12
|
+
return token.slice(-4);
|
|
13
|
+
}
|
|
14
|
+
function randomBytes(length) {
|
|
15
|
+
const crypto = getCryptoOrThrow();
|
|
16
|
+
const bytes = new Uint8Array(length);
|
|
17
|
+
crypto.getRandomValues(bytes);
|
|
18
|
+
return bytes;
|
|
19
|
+
}
|
|
20
|
+
function getSubtleOrThrow() {
|
|
21
|
+
const subtle = getCryptoOrThrow().subtle;
|
|
22
|
+
if (!subtle) {
|
|
23
|
+
throw runtimeUnavailableError("Web Crypto API subtle crypto is not available");
|
|
24
|
+
}
|
|
25
|
+
return subtle;
|
|
26
|
+
}
|
|
27
|
+
function getCryptoOrThrow() {
|
|
28
|
+
const crypto = globalThis.crypto;
|
|
29
|
+
if (!crypto) {
|
|
30
|
+
throw runtimeUnavailableError("Web Crypto API is not available in this runtime");
|
|
31
|
+
}
|
|
32
|
+
return crypto;
|
|
33
|
+
}
|
|
34
|
+
function base64UrlEncode(bytes) {
|
|
35
|
+
let binary = "";
|
|
36
|
+
for (const byte of bytes) {
|
|
37
|
+
binary += String.fromCharCode(byte);
|
|
38
|
+
}
|
|
39
|
+
if (typeof globalThis.btoa !== "function") {
|
|
40
|
+
throw runtimeUnavailableError("Base64 encoding is not available in this runtime");
|
|
41
|
+
}
|
|
42
|
+
return globalThis
|
|
43
|
+
.btoa(binary)
|
|
44
|
+
.replace(/\+/g, "-")
|
|
45
|
+
.replace(/\//g, "_")
|
|
46
|
+
.replace(/=+$/g, "");
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=crypto.js.map
|