@vllnt/convex-api-keys 0.1.0-canary.f67cc26
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 +190 -0
- package/README.md +227 -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/index.d.ts +67 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +93 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +68 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +41 -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 +146 -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/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +12 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/mutations.d.ts +94 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +456 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +49 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +147 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +70 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +43 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validators.d.ts +3 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +4 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/log.d.ts +11 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +15 -0
- package/dist/log.js.map +1 -0
- package/dist/shared.d.ts +26 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +60 -0
- package/dist/shared.js.map +1 -0
- package/package.json +96 -0
- package/src/client/_generated/_ignore.ts +1 -0
- package/src/client/index.ts +185 -0
- package/src/client/types.ts +77 -0
- package/src/component/_generated/api.ts +57 -0
- package/src/component/_generated/component.ts +200 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +156 -0
- package/src/component/convex.config.ts +14 -0
- package/src/component/mutations.ts +511 -0
- package/src/component/queries.ts +162 -0
- package/src/component/schema.ts +45 -0
- package/src/component/validators.ts +4 -0
- package/src/log.test.ts +52 -0
- package/src/log.ts +24 -0
- package/src/shared.test.ts +126 -0
- package/src/shared.ts +121 -0
- package/src/test.ts +15 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated utilities for implementing server-side Convex query and mutation functions.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ActionBuilder,
|
|
13
|
+
HttpActionBuilder,
|
|
14
|
+
MutationBuilder,
|
|
15
|
+
QueryBuilder,
|
|
16
|
+
GenericActionCtx,
|
|
17
|
+
GenericMutationCtx,
|
|
18
|
+
GenericQueryCtx,
|
|
19
|
+
GenericDatabaseReader,
|
|
20
|
+
GenericDatabaseWriter,
|
|
21
|
+
} from "convex/server";
|
|
22
|
+
import {
|
|
23
|
+
actionGeneric,
|
|
24
|
+
httpActionGeneric,
|
|
25
|
+
queryGeneric,
|
|
26
|
+
mutationGeneric,
|
|
27
|
+
internalActionGeneric,
|
|
28
|
+
internalMutationGeneric,
|
|
29
|
+
internalQueryGeneric,
|
|
30
|
+
} from "convex/server";
|
|
31
|
+
import type { DataModel } from "./dataModel.js";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Define a query in this Convex app's public API.
|
|
35
|
+
*
|
|
36
|
+
* This function will be allowed to read your Convex database and will be accessible from the client.
|
|
37
|
+
*
|
|
38
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
39
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
40
|
+
*/
|
|
41
|
+
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Define a query that is only accessible from other Convex functions (but not from the client).
|
|
45
|
+
*
|
|
46
|
+
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
|
|
47
|
+
*
|
|
48
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
49
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
50
|
+
*/
|
|
51
|
+
export const internalQuery: QueryBuilder<DataModel, "internal"> =
|
|
52
|
+
internalQueryGeneric;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Define a mutation in this Convex app's public API.
|
|
56
|
+
*
|
|
57
|
+
* This function will be allowed to modify your Convex database and will be accessible from the client.
|
|
58
|
+
*
|
|
59
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
60
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
61
|
+
*/
|
|
62
|
+
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Define a mutation that is only accessible from other Convex functions (but not from the client).
|
|
66
|
+
*
|
|
67
|
+
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
|
|
68
|
+
*
|
|
69
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
70
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
71
|
+
*/
|
|
72
|
+
export const internalMutation: MutationBuilder<DataModel, "internal"> =
|
|
73
|
+
internalMutationGeneric;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Define an action in this Convex app's public API.
|
|
77
|
+
*
|
|
78
|
+
* An action is a function which can execute any JavaScript code, including non-deterministic
|
|
79
|
+
* code and code with side-effects, like calling third-party services.
|
|
80
|
+
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
|
|
81
|
+
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
|
|
82
|
+
*
|
|
83
|
+
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
|
|
84
|
+
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
|
|
85
|
+
*/
|
|
86
|
+
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Define an action that is only accessible from other Convex functions (but not from the client).
|
|
90
|
+
*
|
|
91
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
|
|
92
|
+
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
|
|
93
|
+
*/
|
|
94
|
+
export const internalAction: ActionBuilder<DataModel, "internal"> =
|
|
95
|
+
internalActionGeneric;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Define an HTTP action.
|
|
99
|
+
*
|
|
100
|
+
* The wrapped function will be used to respond to HTTP requests received
|
|
101
|
+
* by a Convex deployment if the requests matches the path and method where
|
|
102
|
+
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
|
|
103
|
+
*
|
|
104
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument
|
|
105
|
+
* and a Fetch API `Request` object as its second.
|
|
106
|
+
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
|
|
107
|
+
*/
|
|
108
|
+
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A set of services for use within Convex query functions.
|
|
112
|
+
*
|
|
113
|
+
* The query context is passed as the first argument to any Convex query
|
|
114
|
+
* function run on the server.
|
|
115
|
+
*
|
|
116
|
+
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
|
|
117
|
+
*/
|
|
118
|
+
export type QueryCtx = GenericQueryCtx<DataModel>;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A set of services for use within Convex mutation functions.
|
|
122
|
+
*
|
|
123
|
+
* The mutation context is passed as the first argument to any Convex mutation
|
|
124
|
+
* function run on the server.
|
|
125
|
+
*
|
|
126
|
+
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
|
|
127
|
+
*/
|
|
128
|
+
export type MutationCtx = GenericMutationCtx<DataModel>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A set of services for use within Convex action functions.
|
|
132
|
+
*
|
|
133
|
+
* The action context is passed as the first argument to any Convex action
|
|
134
|
+
* function run on the server.
|
|
135
|
+
*/
|
|
136
|
+
export type ActionCtx = GenericActionCtx<DataModel>;
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* An interface to read from the database within Convex query functions.
|
|
140
|
+
*
|
|
141
|
+
* The two entry points are {@link DatabaseReader.get}, which fetches a single
|
|
142
|
+
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
|
|
143
|
+
* building a query.
|
|
144
|
+
*/
|
|
145
|
+
export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* An interface to read from and write to the database within Convex mutation
|
|
149
|
+
* functions.
|
|
150
|
+
*
|
|
151
|
+
* Convex guarantees that all writes within a single mutation are
|
|
152
|
+
* executed atomically, so you never have to worry about partial writes leaving
|
|
153
|
+
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
|
|
154
|
+
* for the guarantees Convex provides your functions.
|
|
155
|
+
*/
|
|
156
|
+
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineComponent } from "convex/server";
|
|
2
|
+
import rateLimiter from "@convex-dev/rate-limiter/convex.config.js";
|
|
3
|
+
import shardedCounter from "@convex-dev/sharded-counter/convex.config.js";
|
|
4
|
+
import aggregate from "@convex-dev/aggregate/convex.config.js";
|
|
5
|
+
import crons from "@convex-dev/crons/convex.config.js";
|
|
6
|
+
|
|
7
|
+
const component = defineComponent("apiKeys");
|
|
8
|
+
|
|
9
|
+
component.use(rateLimiter);
|
|
10
|
+
component.use(shardedCounter);
|
|
11
|
+
component.use(aggregate, { name: "usageAggregate" });
|
|
12
|
+
component.use(crons);
|
|
13
|
+
|
|
14
|
+
export default component;
|
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { mutation } from "./_generated/server.js";
|
|
3
|
+
import { components } from "./_generated/api.js";
|
|
4
|
+
import { RateLimiter, MINUTE, HOUR } from "@convex-dev/rate-limiter";
|
|
5
|
+
import { ShardedCounter } from "@convex-dev/sharded-counter";
|
|
6
|
+
import {
|
|
7
|
+
KEY_STATUS,
|
|
8
|
+
KEY_TYPE,
|
|
9
|
+
TERMINAL_STATUSES,
|
|
10
|
+
parseKeyString,
|
|
11
|
+
timingSafeEqual,
|
|
12
|
+
sha256Hex,
|
|
13
|
+
validateTags,
|
|
14
|
+
KEY_PREFIX_SEPARATOR,
|
|
15
|
+
} from "../shared.js";
|
|
16
|
+
import { createLogger } from "../log.js";
|
|
17
|
+
import { jsonValue } from "./validators.js";
|
|
18
|
+
import type { KeyStatus } from "../shared.js";
|
|
19
|
+
|
|
20
|
+
const log = createLogger("api-keys");
|
|
21
|
+
|
|
22
|
+
const rateLimiter = new RateLimiter(components.rateLimiter, {
|
|
23
|
+
createKey: { kind: "fixed window", rate: 100, period: HOUR },
|
|
24
|
+
validateKey: { kind: "token bucket", rate: 1000, period: MINUTE },
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const counter = new ShardedCounter(components.shardedCounter);
|
|
28
|
+
|
|
29
|
+
export const create = mutation({
|
|
30
|
+
args: {
|
|
31
|
+
name: v.string(),
|
|
32
|
+
ownerId: v.string(),
|
|
33
|
+
type: v.optional(KEY_TYPE),
|
|
34
|
+
scopes: v.optional(v.array(v.string())),
|
|
35
|
+
tags: v.optional(v.array(v.string())),
|
|
36
|
+
env: v.optional(v.string()),
|
|
37
|
+
metadata: v.optional(jsonValue),
|
|
38
|
+
remaining: v.optional(v.number()),
|
|
39
|
+
expiresAt: v.optional(v.number()),
|
|
40
|
+
keyPrefix: v.optional(v.string()),
|
|
41
|
+
lookupPrefix: v.string(),
|
|
42
|
+
secretHex: v.string(),
|
|
43
|
+
hash: v.string(),
|
|
44
|
+
},
|
|
45
|
+
returns: v.object({
|
|
46
|
+
keyId: v.id("apiKeys"),
|
|
47
|
+
key: v.string(),
|
|
48
|
+
}),
|
|
49
|
+
handler: async (ctx, args) => {
|
|
50
|
+
if (args.expiresAt !== undefined && args.expiresAt <= Date.now()) {
|
|
51
|
+
throw new Error("expiresAt must be in the future");
|
|
52
|
+
}
|
|
53
|
+
if (args.remaining !== undefined && args.remaining <= 0) {
|
|
54
|
+
throw new Error("remaining must be > 0");
|
|
55
|
+
}
|
|
56
|
+
if (args.tags) {
|
|
57
|
+
validateTags(args.tags);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
await rateLimiter.limit(ctx, "createKey", {
|
|
61
|
+
key: args.ownerId,
|
|
62
|
+
throws: true,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const type = args.type ?? "secret";
|
|
66
|
+
const env = args.env ?? "live";
|
|
67
|
+
const prefix = args.keyPrefix ?? "vk";
|
|
68
|
+
const typeShort = type === "publishable" ? "pub" : "secret";
|
|
69
|
+
|
|
70
|
+
const keyId = await ctx.db.insert("apiKeys", {
|
|
71
|
+
hash: args.hash,
|
|
72
|
+
lookupPrefix: args.lookupPrefix,
|
|
73
|
+
keyPrefix: prefix,
|
|
74
|
+
type,
|
|
75
|
+
env,
|
|
76
|
+
ownerId: args.ownerId,
|
|
77
|
+
name: args.name,
|
|
78
|
+
scopes: args.scopes ?? [],
|
|
79
|
+
tags: args.tags ?? [],
|
|
80
|
+
status: "active",
|
|
81
|
+
metadata: args.metadata,
|
|
82
|
+
remaining: args.remaining,
|
|
83
|
+
expiresAt: args.expiresAt,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
87
|
+
keyId,
|
|
88
|
+
ownerId: args.ownerId,
|
|
89
|
+
eventType: "key.created",
|
|
90
|
+
timestamp: Date.now(),
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const rawKey = [prefix, typeShort, env, args.lookupPrefix, args.secretHex].join(
|
|
94
|
+
KEY_PREFIX_SEPARATOR,
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
log.info("key created", { keyId, ownerId: args.ownerId, type, env });
|
|
98
|
+
return { keyId, key: rawKey };
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
export const validate = mutation({
|
|
103
|
+
args: {
|
|
104
|
+
key: v.string(),
|
|
105
|
+
},
|
|
106
|
+
returns: v.union(
|
|
107
|
+
v.object({
|
|
108
|
+
valid: v.literal(true),
|
|
109
|
+
keyId: v.id("apiKeys"),
|
|
110
|
+
ownerId: v.string(),
|
|
111
|
+
type: KEY_TYPE,
|
|
112
|
+
env: v.string(),
|
|
113
|
+
scopes: v.array(v.string()),
|
|
114
|
+
tags: v.array(v.string()),
|
|
115
|
+
metadata: v.optional(jsonValue),
|
|
116
|
+
remaining: v.optional(v.number()),
|
|
117
|
+
}),
|
|
118
|
+
v.object({
|
|
119
|
+
valid: v.literal(false),
|
|
120
|
+
reason: v.string(),
|
|
121
|
+
retryAfter: v.optional(v.number()),
|
|
122
|
+
}),
|
|
123
|
+
),
|
|
124
|
+
handler: async (ctx, { key }) => {
|
|
125
|
+
const parsed = parseKeyString(key);
|
|
126
|
+
if (!parsed.valid) {
|
|
127
|
+
return { valid: false as const, reason: "malformed" };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const candidates = await ctx.db
|
|
131
|
+
.query("apiKeys")
|
|
132
|
+
.withIndex("by_lookup_prefix", (q) => q.eq("lookupPrefix", parsed.lookupPrefix))
|
|
133
|
+
.collect();
|
|
134
|
+
|
|
135
|
+
if (candidates.length === 0) {
|
|
136
|
+
return { valid: false as const, reason: "not_found" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const keyHash = await sha256Hex(key);
|
|
140
|
+
|
|
141
|
+
let matchedKey = null;
|
|
142
|
+
for (const candidate of candidates) {
|
|
143
|
+
if (timingSafeEqual(candidate.hash, keyHash)) {
|
|
144
|
+
matchedKey = candidate;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (!matchedKey) {
|
|
150
|
+
return { valid: false as const, reason: "not_found" };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
|
|
155
|
+
if (matchedKey.status === "revoked") {
|
|
156
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
157
|
+
keyId: matchedKey._id,
|
|
158
|
+
ownerId: matchedKey.ownerId,
|
|
159
|
+
eventType: "key.validate_failed",
|
|
160
|
+
reason: "revoked",
|
|
161
|
+
timestamp: now,
|
|
162
|
+
});
|
|
163
|
+
return { valid: false as const, reason: "revoked" };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (matchedKey.status === "disabled") {
|
|
167
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
168
|
+
keyId: matchedKey._id,
|
|
169
|
+
ownerId: matchedKey.ownerId,
|
|
170
|
+
eventType: "key.validate_failed",
|
|
171
|
+
reason: "disabled",
|
|
172
|
+
timestamp: now,
|
|
173
|
+
});
|
|
174
|
+
return { valid: false as const, reason: "disabled" };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (matchedKey.status === "exhausted") {
|
|
178
|
+
return { valid: false as const, reason: "exhausted" };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (matchedKey.expiresAt && matchedKey.expiresAt <= now) {
|
|
182
|
+
await ctx.db.patch(matchedKey._id, { status: "expired" });
|
|
183
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
184
|
+
keyId: matchedKey._id,
|
|
185
|
+
ownerId: matchedKey.ownerId,
|
|
186
|
+
eventType: "key.expired",
|
|
187
|
+
timestamp: now,
|
|
188
|
+
});
|
|
189
|
+
return { valid: false as const, reason: "expired" };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (
|
|
193
|
+
matchedKey.status === "rotating" &&
|
|
194
|
+
matchedKey.gracePeriodEnd &&
|
|
195
|
+
matchedKey.gracePeriodEnd <= now
|
|
196
|
+
) {
|
|
197
|
+
await ctx.db.patch(matchedKey._id, { status: "expired" });
|
|
198
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
199
|
+
keyId: matchedKey._id,
|
|
200
|
+
ownerId: matchedKey.ownerId,
|
|
201
|
+
eventType: "key.expired",
|
|
202
|
+
reason: "grace_period_ended",
|
|
203
|
+
timestamp: now,
|
|
204
|
+
});
|
|
205
|
+
return { valid: false as const, reason: "expired" };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
let newRemaining = matchedKey.remaining;
|
|
209
|
+
if (matchedKey.remaining !== undefined) {
|
|
210
|
+
if (matchedKey.remaining <= 0) {
|
|
211
|
+
await ctx.db.patch(matchedKey._id, { status: "exhausted" });
|
|
212
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
213
|
+
keyId: matchedKey._id,
|
|
214
|
+
ownerId: matchedKey.ownerId,
|
|
215
|
+
eventType: "key.exhausted",
|
|
216
|
+
timestamp: now,
|
|
217
|
+
});
|
|
218
|
+
return { valid: false as const, reason: "exhausted" };
|
|
219
|
+
}
|
|
220
|
+
newRemaining = matchedKey.remaining - 1;
|
|
221
|
+
const updates: Record<string, unknown> = {
|
|
222
|
+
remaining: newRemaining,
|
|
223
|
+
lastUsedAt: now,
|
|
224
|
+
};
|
|
225
|
+
if (newRemaining === 0) {
|
|
226
|
+
updates.status = "exhausted";
|
|
227
|
+
}
|
|
228
|
+
await ctx.db.patch(matchedKey._id, updates);
|
|
229
|
+
|
|
230
|
+
if (newRemaining === 0) {
|
|
231
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
232
|
+
keyId: matchedKey._id,
|
|
233
|
+
ownerId: matchedKey.ownerId,
|
|
234
|
+
eventType: "key.exhausted",
|
|
235
|
+
timestamp: now,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
} else {
|
|
239
|
+
await ctx.db.patch(matchedKey._id, { lastUsedAt: now });
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const { ok, retryAfter } = await rateLimiter.limit(ctx, "validateKey", {
|
|
243
|
+
key: matchedKey._id,
|
|
244
|
+
throws: false,
|
|
245
|
+
});
|
|
246
|
+
if (!ok) {
|
|
247
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
248
|
+
keyId: matchedKey._id,
|
|
249
|
+
ownerId: matchedKey.ownerId,
|
|
250
|
+
eventType: "key.rate_limited",
|
|
251
|
+
timestamp: now,
|
|
252
|
+
});
|
|
253
|
+
return { valid: false as const, reason: "rate_limited", retryAfter };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
await counter.add(ctx, matchedKey._id, 1);
|
|
257
|
+
|
|
258
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
259
|
+
keyId: matchedKey._id,
|
|
260
|
+
ownerId: matchedKey.ownerId,
|
|
261
|
+
eventType: "key.validated",
|
|
262
|
+
timestamp: now,
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
valid: true as const,
|
|
267
|
+
keyId: matchedKey._id,
|
|
268
|
+
ownerId: matchedKey.ownerId,
|
|
269
|
+
type: matchedKey.type,
|
|
270
|
+
env: matchedKey.env,
|
|
271
|
+
scopes: matchedKey.scopes,
|
|
272
|
+
tags: matchedKey.tags,
|
|
273
|
+
metadata: matchedKey.metadata,
|
|
274
|
+
remaining: newRemaining,
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
export const revoke = mutation({
|
|
280
|
+
args: {
|
|
281
|
+
keyId: v.id("apiKeys"),
|
|
282
|
+
},
|
|
283
|
+
returns: v.null(),
|
|
284
|
+
handler: async (ctx, { keyId }) => {
|
|
285
|
+
const key = await ctx.db.get(keyId);
|
|
286
|
+
if (!key) {
|
|
287
|
+
throw new Error("key not found");
|
|
288
|
+
}
|
|
289
|
+
if (key.status === "revoked") {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
await ctx.db.patch(keyId, { status: "revoked", revokedAt: Date.now() });
|
|
293
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
294
|
+
keyId,
|
|
295
|
+
ownerId: key.ownerId,
|
|
296
|
+
eventType: "key.revoked",
|
|
297
|
+
timestamp: Date.now(),
|
|
298
|
+
});
|
|
299
|
+
log.info("key revoked", { keyId, ownerId: key.ownerId });
|
|
300
|
+
return null;
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
export const revokeByTag = mutation({
|
|
305
|
+
args: {
|
|
306
|
+
ownerId: v.string(),
|
|
307
|
+
tag: v.string(),
|
|
308
|
+
},
|
|
309
|
+
returns: v.object({ revokedCount: v.number() }),
|
|
310
|
+
handler: async (ctx, { ownerId, tag }) => {
|
|
311
|
+
const keys = await ctx.db
|
|
312
|
+
.query("apiKeys")
|
|
313
|
+
.withIndex("by_owner_status", (q) => q.eq("ownerId", ownerId).eq("status", "active"))
|
|
314
|
+
.collect();
|
|
315
|
+
|
|
316
|
+
let revokedCount = 0;
|
|
317
|
+
const now = Date.now();
|
|
318
|
+
for (const key of keys) {
|
|
319
|
+
if (key.tags.includes(tag)) {
|
|
320
|
+
await ctx.db.patch(key._id, { status: "revoked", revokedAt: now });
|
|
321
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
322
|
+
keyId: key._id,
|
|
323
|
+
ownerId,
|
|
324
|
+
eventType: "key.revoked",
|
|
325
|
+
reason: `bulk_revoke_by_tag:${tag}`,
|
|
326
|
+
timestamp: now,
|
|
327
|
+
});
|
|
328
|
+
revokedCount++;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return { revokedCount };
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
export const rotate = mutation({
|
|
336
|
+
args: {
|
|
337
|
+
keyId: v.id("apiKeys"),
|
|
338
|
+
gracePeriodMs: v.optional(v.number()),
|
|
339
|
+
lookupPrefix: v.string(),
|
|
340
|
+
secretHex: v.string(),
|
|
341
|
+
},
|
|
342
|
+
returns: v.object({
|
|
343
|
+
newKeyId: v.id("apiKeys"),
|
|
344
|
+
newKey: v.string(),
|
|
345
|
+
oldKeyExpiresAt: v.number(),
|
|
346
|
+
}),
|
|
347
|
+
handler: async (ctx, args) => {
|
|
348
|
+
const oldKey = await ctx.db.get(args.keyId);
|
|
349
|
+
if (!oldKey) {
|
|
350
|
+
throw new Error("key not found");
|
|
351
|
+
}
|
|
352
|
+
if (TERMINAL_STATUSES.has(oldKey.status as KeyStatus)) {
|
|
353
|
+
throw new Error("cannot rotate a terminal key");
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
const gracePeriodMs = args.gracePeriodMs ?? 3600000;
|
|
358
|
+
const gracePeriodEnd = now + gracePeriodMs;
|
|
359
|
+
|
|
360
|
+
await ctx.db.patch(args.keyId, {
|
|
361
|
+
status: "rotating",
|
|
362
|
+
gracePeriodEnd,
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
const typeShort = oldKey.type === "publishable" ? "pub" : "secret";
|
|
366
|
+
const rawKey = [
|
|
367
|
+
oldKey.keyPrefix,
|
|
368
|
+
typeShort,
|
|
369
|
+
oldKey.env,
|
|
370
|
+
args.lookupPrefix,
|
|
371
|
+
args.secretHex,
|
|
372
|
+
].join(KEY_PREFIX_SEPARATOR);
|
|
373
|
+
const hash = await sha256Hex(rawKey);
|
|
374
|
+
|
|
375
|
+
const newKeyId = await ctx.db.insert("apiKeys", {
|
|
376
|
+
hash,
|
|
377
|
+
lookupPrefix: args.lookupPrefix,
|
|
378
|
+
keyPrefix: oldKey.keyPrefix,
|
|
379
|
+
type: oldKey.type,
|
|
380
|
+
env: oldKey.env,
|
|
381
|
+
ownerId: oldKey.ownerId,
|
|
382
|
+
name: oldKey.name,
|
|
383
|
+
scopes: oldKey.scopes,
|
|
384
|
+
tags: oldKey.tags,
|
|
385
|
+
status: "active",
|
|
386
|
+
metadata: oldKey.metadata,
|
|
387
|
+
remaining: oldKey.remaining,
|
|
388
|
+
expiresAt: oldKey.expiresAt,
|
|
389
|
+
rotatedFromId: args.keyId,
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
393
|
+
keyId: args.keyId,
|
|
394
|
+
ownerId: oldKey.ownerId,
|
|
395
|
+
eventType: "key.rotated",
|
|
396
|
+
metadata: { newKeyId },
|
|
397
|
+
timestamp: now,
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
return { newKeyId, newKey: rawKey, oldKeyExpiresAt: gracePeriodEnd };
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
export const update = mutation({
|
|
405
|
+
args: {
|
|
406
|
+
keyId: v.id("apiKeys"),
|
|
407
|
+
name: v.optional(v.string()),
|
|
408
|
+
scopes: v.optional(v.array(v.string())),
|
|
409
|
+
tags: v.optional(v.array(v.string())),
|
|
410
|
+
metadata: v.optional(jsonValue),
|
|
411
|
+
},
|
|
412
|
+
returns: v.null(),
|
|
413
|
+
handler: async (ctx, { keyId, ...updates }) => {
|
|
414
|
+
const key = await ctx.db.get(keyId);
|
|
415
|
+
if (!key) {
|
|
416
|
+
throw new Error("key not found");
|
|
417
|
+
}
|
|
418
|
+
if (TERMINAL_STATUSES.has(key.status as KeyStatus)) {
|
|
419
|
+
throw new Error("cannot update terminal key");
|
|
420
|
+
}
|
|
421
|
+
if (updates.tags) {
|
|
422
|
+
validateTags(updates.tags);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const patch: Record<string, unknown> = {};
|
|
426
|
+
if (updates.name !== undefined) patch.name = updates.name;
|
|
427
|
+
if (updates.scopes !== undefined) patch.scopes = updates.scopes;
|
|
428
|
+
if (updates.tags !== undefined) patch.tags = updates.tags;
|
|
429
|
+
if (updates.metadata !== undefined) patch.metadata = updates.metadata;
|
|
430
|
+
|
|
431
|
+
if (Object.keys(patch).length > 0) {
|
|
432
|
+
await ctx.db.patch(keyId, patch);
|
|
433
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
434
|
+
keyId,
|
|
435
|
+
ownerId: key.ownerId,
|
|
436
|
+
eventType: "key.updated",
|
|
437
|
+
metadata: { fields: Object.keys(patch) },
|
|
438
|
+
timestamp: Date.now(),
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return null;
|
|
443
|
+
},
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
export const disable = mutation({
|
|
447
|
+
args: { keyId: v.id("apiKeys") },
|
|
448
|
+
returns: v.null(),
|
|
449
|
+
handler: async (ctx, { keyId }) => {
|
|
450
|
+
const key = await ctx.db.get(keyId);
|
|
451
|
+
if (!key) {
|
|
452
|
+
throw new Error("key not found");
|
|
453
|
+
}
|
|
454
|
+
if (key.status === "disabled") {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
if (key.status !== "active") {
|
|
458
|
+
throw new Error("can only disable active keys");
|
|
459
|
+
}
|
|
460
|
+
await ctx.db.patch(keyId, { status: "disabled" });
|
|
461
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
462
|
+
keyId,
|
|
463
|
+
ownerId: key.ownerId,
|
|
464
|
+
eventType: "key.disabled",
|
|
465
|
+
timestamp: Date.now(),
|
|
466
|
+
});
|
|
467
|
+
return null;
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
export const enable = mutation({
|
|
472
|
+
args: { keyId: v.id("apiKeys") },
|
|
473
|
+
returns: v.null(),
|
|
474
|
+
handler: async (ctx, { keyId }) => {
|
|
475
|
+
const key = await ctx.db.get(keyId);
|
|
476
|
+
if (!key) {
|
|
477
|
+
throw new Error("key not found");
|
|
478
|
+
}
|
|
479
|
+
if (key.status === "active") {
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
if (key.status !== "disabled") {
|
|
483
|
+
throw new Error("can only enable disabled keys");
|
|
484
|
+
}
|
|
485
|
+
await ctx.db.patch(keyId, { status: "active" });
|
|
486
|
+
await ctx.db.insert("apiKeyEvents", {
|
|
487
|
+
keyId,
|
|
488
|
+
ownerId: key.ownerId,
|
|
489
|
+
eventType: "key.enabled",
|
|
490
|
+
timestamp: Date.now(),
|
|
491
|
+
});
|
|
492
|
+
return null;
|
|
493
|
+
},
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
export const configure = mutation({
|
|
497
|
+
args: {
|
|
498
|
+
cleanupIntervalMs: v.optional(v.number()),
|
|
499
|
+
defaultExpiryMs: v.optional(v.number()),
|
|
500
|
+
},
|
|
501
|
+
returns: v.null(),
|
|
502
|
+
handler: async (ctx, args) => {
|
|
503
|
+
const existing = await ctx.db.query("config").first();
|
|
504
|
+
if (existing) {
|
|
505
|
+
await ctx.db.patch(existing._id, args);
|
|
506
|
+
} else {
|
|
507
|
+
await ctx.db.insert("config", args);
|
|
508
|
+
}
|
|
509
|
+
return null;
|
|
510
|
+
},
|
|
511
|
+
});
|