Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
8b4a8cc
docs(design): add the API keys design doc
sefk Nov 13, 2026
52b4511
docs(design): add Cloudflare integration to the API keys design
sefk Nov 13, 2026
f5bf85c
docs(design): link the Cloudflare question to its section
sefk Nov 13, 2026
4738788
docs(design): settle API key scope questions and add future features
sefk Nov 13, 2026
f202068
docs(design): add a table of contents to the API keys design
sefk Nov 13, 2026
f6ec3ca
docs(design): fold the key header choice into The Key section
sefk Nov 13, 2026
371cb5b
docs(design): proofread the API keys design
sefk Nov 13, 2026
1c59354
docs(design): proofread the revised API keys summary
sefk Nov 13, 2026
84dca90
docs(design): say key-specific access in the API keys summary
sefk Nov 13, 2026
1133905
docs(design): add alternatives considered to the API keys design
sefk Nov 13, 2026
173fb2a
docs(design): restructure API keys design into requirements, build an…
sefk Nov 14, 2026
043341f
docs(design): give each API key one rate limit
sefk Nov 14, 2026
12eb7f1
docs(design): revise API keys design after a review with Codex (#142)
sefk Nov 14, 2026
f67517a
docs(design): fail open when the API key store is unavailable
sefk Nov 14, 2026
314eed7
docs(design): address review of the API keys design
sefk Nov 16, 2026
5e6ae1f
docs(design): record the API key plugin spike results
sefk Nov 16, 2026
14efb73
feat(auth): add the API key plugin, table and account limit (#142)
sefk Nov 16, 2026
433f671
feat(proxy): add the API key parser and the key verifier (#142)
sefk Nov 16, 2026
cb3c4c9
feat(proxy): count calls with an API key against their account (#142)
sefk Nov 16, 2026
344b46a
feat(proxy): log API key usage from forward() (#142)
sefk Nov 16, 2026
aeedf46
feat(account): add an API keys page to the account menu (#142)
sefk Nov 16, 2026
34d1f30
feat(admin): add an API keys admin page, a proof of concept (#142)
sefk Nov 16, 2026
b0fa967
fix(auth): keep the prefix and three random characters as a key's sta…
sefk Nov 16, 2026
2fc9f89
fix(account): use a keyed /api/v1 path in the API key curl example (#…
sefk Nov 16, 2026
c13d579
feat(proxy): record a key's last use when a lookup finds it (#142)
sefk Nov 16, 2026
42a4a2f
chore(just): run the apis proxy, harness and dev server together
sefk Nov 16, 2026
3d7acb6
chore(just): color stack output by service and highlight errors
sefk Nov 16, 2026
f89466a
Merge branch 'chore/dev-stack' into feat/api-keys
sefk Nov 16, 2026
48941ff
docs(design): record local test results for API keys
sefk Nov 16, 2026
4976d0e
Merge the API keys implementation into the design branch (#142)
sefk Nov 16, 2026
6a4ea4b
docs(design): bring the API keys design up to date with the build
sefk Nov 16, 2026
343dff8
feat(account): link the API keys admin page from the account menu (#142)
sefk Nov 16, 2026
42e88ed
feat(proxy): vendor the invalid_api_key code (#142)
sefk Nov 16, 2026
a3a1641
fix(account): ask an API route whether the viewer is an admin (#142)
sefk Nov 16, 2026
39ac515
style(proxy): format access.ts with Prettier (#142)
sefk Nov 16, 2026
3341af2
test(auth): check the key hash with a known answer (#142)
sefk Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,31 @@ SENTRY_AUTH_TOKEN=
# RATE_LIMIT_PIN=10
# /mcp is higher because a vendor's address can carry many users.
# RATE_LIMIT_MCP=300
# A call with a valid API key (`Authorization: Bearer dfo_...` or `X-API-Key`)
# is counted against the key's account instead of its address: this many calls
# per window on each of /api and /mcp, for an account with no limit of its own
# (user.api_rate_limit). Keys are the proxy's own; the Studio ignores them.
# RATE_LIMIT_KEYED=600
# Emergency switch: false strips keys and counts every call by address.
# API_KEYS_ENABLED=true
# How many API keys one account may hold on /account/api-keys (default 5).
# Housekeeping, not security: the limit is per account, so a second key adds
# no calls.
# API_KEYS_MAX_PER_ACCOUNT=5
# Who may open /admin/api-keys, which lists every account's keys, makes and
# deletes keys and sets an account's limit (a proof of concept). Comma-
# separated emails, matched without regard to case against a signed-in user
# whose email is verified. Everyone else gets a 404. Unset or empty: no
# admins, so the page is closed to all.
# ADMIN_EMAILS=
# The harness's own token for its MCP server (MCP_API_TOKEN on dfo-ai);
# attached by the proxy so outside MCP clients don't need it. Unset: the
# caller's own Authorization header is passed through.
MCP_API_TOKEN=
# /mcp names each caller to dfo-ai, and the dfo-apis proxy to dfo-apis, as
# x-dfo-caller: ip:<digest>, an HMAC-SHA-256 of the client address (an IPv6
# address as its /64) keyed by this secret (e.g. openssl rand -hex 32). It
# address as its /64) keyed by this secret, or user:<digest> of the account for
# a call with an API key (e.g. openssl rand -hex 32). It
# must equal dfo-apis's DFO_CALLER_HMAC_KEY. If unset, no caller is sent and
# the site logs one warning.
CALLER_HMAC_KEY=
Expand Down
56 changes: 55 additions & 1 deletion db/auth-schema.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { relations } from 'drizzle-orm';
import { pgTable, text, timestamp, boolean, index } from 'drizzle-orm/pg-core';
import {
boolean,
index,
integer,
pgTable,
text,
timestamp,
uniqueIndex,
} from 'drizzle-orm/pg-core';

export const user = pgTable('user', {
id: text('id').primaryKey(),
Expand All @@ -15,6 +23,9 @@ export const user = pgTable('user', {
// Set when the account's deletion begins (`user.additionalFields` in
// src/lib/auth/auth.ts), so no share token is stored for it after.
deletingAt: timestamp('deleting_at', { withTimezone: true }),
// The account's own calls-per-window limit for API keys (`user.additionalFields`
// in src/lib/auth/auth.ts). Null is the deployment default (RATE_LIMIT_KEYED).
apiRateLimit: integer('api_rate_limit'),
});

export const session = pgTable(
Expand Down Expand Up @@ -76,6 +87,49 @@ export const verification = pgTable(
(table) => [index('verification_identifier_idx').on(table.identifier)],
);

/**
* The `@better-auth/api-key` plugin's table (its columns, as the plugin
* writes them). Differences from the plugin's own schema: `reference_id` has
* a foreign key to `user` that deletes an account's keys with the account
* (the plugin's owner may also be an organization, so it has none), and the
* index on `key`, the SHA-256 of the key, is unique. The proxy reads this
* table itself (src/lib/proxy/keyVerifier).
*/
export const apikey = pgTable(
'apikey',
{
id: text('id').primaryKey(),
configId: text('config_id').default('default').notNull(),
name: text('name'),
start: text('start'),
referenceId: text('reference_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
prefix: text('prefix'),
key: text('key').notNull(),
refillInterval: integer('refill_interval'),
refillAmount: integer('refill_amount'),
lastRefillAt: timestamp('last_refill_at'),
enabled: boolean('enabled').default(true),
rateLimitEnabled: boolean('rate_limit_enabled').default(true),
rateLimitTimeWindow: integer('rate_limit_time_window'),
rateLimitMax: integer('rate_limit_max'),
requestCount: integer('request_count').default(0),
remaining: integer('remaining'),
lastRequest: timestamp('last_request'),
expiresAt: timestamp('expires_at'),
createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp('updated_at').notNull(),
permissions: text('permissions'),
metadata: text('metadata'),
},
(table) => [
index('apikey_configId_idx').on(table.configId),
index('apikey_referenceId_idx').on(table.referenceId),
uniqueIndex('apikey_key_idx').on(table.key),
],
);

export const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account),
Expand Down
16 changes: 16 additions & 0 deletions db/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,19 @@ export function buildCounterPool(env: EnvLike = process.env): Pool {
statement_timeout: 400,
});
}

/**
* A small, bounded pool for the proxy's API key lookups (src/lib/proxy/
* keyVerifier), apart from the counters' so a slow key store does not slow
* the counts, and the other way round. A lookup gives up in 400 ms in
* Postgres, 500 ms in the client, or 1 s waiting for a connection, and the
* proxy then treats the key store as unavailable.
*/
export function buildKeyPool(env: EnvLike = process.env): Pool {
return buildRuntimePool(env, {
max: 2,
connectionTimeoutMillis: 1_000,
query_timeout: 500,
statement_timeout: 400,
});
}
30 changes: 30 additions & 0 deletions db/migrations/0025_api_keys.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
CREATE TABLE "apikey" (
"id" text PRIMARY KEY NOT NULL,
"config_id" text DEFAULT 'default' NOT NULL,
"name" text,
"start" text,
"reference_id" text NOT NULL,
"prefix" text,
"key" text NOT NULL,
"refill_interval" integer,
"refill_amount" integer,
"last_refill_at" timestamp,
"enabled" boolean DEFAULT true,
"rate_limit_enabled" boolean DEFAULT true,
"rate_limit_time_window" integer,
"rate_limit_max" integer,
"request_count" integer DEFAULT 0,
"remaining" integer,
"last_request" timestamp,
"expires_at" timestamp,
"created_at" timestamp NOT NULL,
"updated_at" timestamp NOT NULL,
"permissions" text,
"metadata" text
);
--> statement-breakpoint
ALTER TABLE "user" ADD COLUMN "api_rate_limit" integer;--> statement-breakpoint
ALTER TABLE "apikey" ADD CONSTRAINT "apikey_reference_id_user_id_fk" FOREIGN KEY ("reference_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "apikey_configId_idx" ON "apikey" USING btree ("config_id");--> statement-breakpoint
CREATE INDEX "apikey_referenceId_idx" ON "apikey" USING btree ("reference_id");--> statement-breakpoint
CREATE UNIQUE INDEX "apikey_key_idx" ON "apikey" USING btree ("key");
Loading
Loading