(opts: {
request: Request;
env: ApiKeyAuthBindings;
client?: VerifyApiKeyClient;
ctx?: ExecutionContext;
})
| 200 | } |
| 201 | |
| 202 | export async function authenticateApiKeyRequest(opts: { |
| 203 | request: Request; |
| 204 | env: ApiKeyAuthBindings; |
| 205 | client?: VerifyApiKeyClient; |
| 206 | ctx?: ExecutionContext; |
| 207 | }): Promise<ApiKeyAuthResult | null> { |
| 208 | const rawApiKey = extractApiKey(opts.request); |
| 209 | if (!rawApiKey) return null; |
| 210 | |
| 211 | const client: VerifyApiKeyClient = |
| 212 | opts.client ?? |
| 213 | (createApiKeyAuth(opts.env, opts.ctx) as unknown as VerifyApiKeyClient); |
| 214 | const keyResult = await client.api.verifyApiKey({ |
| 215 | body: { key: rawApiKey }, |
| 216 | }); |
| 217 | |
| 218 | if (!keyResult.valid || !keyResult.key) return null; |
| 219 | |
| 220 | const key = keyResult.key; |
| 221 | const keyId = typeof key.id === "string" ? key.id : undefined; |
| 222 | if (!keyId) return null; |
| 223 | |
| 224 | const db = drizzle(opts.env.DB, { schema }); |
| 225 | const userId = typeof key.userId === "string" ? key.userId : undefined; |
| 226 | const byopClientKey = alias(schema.apikey, "byop_client_key"); |
| 227 | const [apiKeyExtra, userData] = await Promise.all([ |
| 228 | db |
| 229 | .select({ |
| 230 | pollenBalance: schema.apikey.pollenBalance, |
| 231 | byopClientKeyId: schema.apikey.byopClientKeyId, |
| 232 | byopClientName: byopClientKey.name, |
| 233 | byopClientUserId: byopClientKey.userId, |
| 234 | }) |
| 235 | .from(schema.apikey) |
| 236 | .leftJoin( |
| 237 | byopClientKey, |
| 238 | eq(byopClientKey.id, schema.apikey.byopClientKeyId), |
| 239 | ) |
| 240 | .where(eq(schema.apikey.id, keyId)) |
| 241 | .get(), |
| 242 | userId |
| 243 | ? db |
| 244 | .select() |
| 245 | .from(schema.user) |
| 246 | .where(eq(schema.user.id, userId)) |
| 247 | .get() |
| 248 | : null, |
| 249 | ]); |
| 250 | |
| 251 | if (userData) { |
| 252 | assertNotBanned(userData); |
| 253 | } |
| 254 | assertStagingAccess(opts.env, userData); |
| 255 | |
| 256 | return { |
| 257 | user: userData ?? undefined, |
| 258 | apiKey: { |
| 259 | id: keyId, |
no test coverage detected