Files
sorsfonalak/crates/db/migrations/0049_mcp_oauth.sql
T

62 lines
2.7 KiB
SQL
Raw Normal View History

-- Claude (or another MCP client) connected to the admin tools through OAuth
-- (docs/mcp.md). An admin approves the connection on the site; the client
-- then holds a short access token and a refresh token. Every secret is
-- stored as its SHA-256 hash, like the sessions.
-- The clients that registered themselves (RFC 7591), only with an allowed
-- return address (Claude's callback, or a local one for Claude Code).
CREATE TABLE oauth_clients (
id text PRIMARY KEY,
name text NOT NULL CHECK (char_length(name) <= 100),
redirect_uris text[] NOT NULL,
-- NULL: a public client, proven by PKCE alone.
secret_hash bytea,
created_at timestamptz NOT NULL DEFAULT now(),
last_used_at timestamptz
);
-- One approved connection: who allowed which client. Revoking it ends all
-- of its tokens.
CREATE TABLE oauth_grants (
id uuid PRIMARY KEY,
client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
scope text NOT NULL,
-- The MCP server the tokens are for (RFC 8707).
resource text,
created_at timestamptz NOT NULL DEFAULT now(),
last_used_at timestamptz,
revoked_at timestamptz
);
CREATE INDEX oauth_grants_user_idx ON oauth_grants (user_id);
-- The one-time code the approval sends back to the client (10 minutes).
CREATE TABLE oauth_codes (
code_hash bytea PRIMARY KEY,
client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
redirect_uri text NOT NULL,
code_challenge text NOT NULL,
scope text NOT NULL,
resource text,
expires_at timestamptz NOT NULL,
used_at timestamptz,
-- The connection made with it: a second use of the code revokes it.
grant_id uuid REFERENCES oauth_grants (id) ON DELETE CASCADE
);
-- An access token (an hour) and its refresh token (30 days). A refresh makes
-- a new pair; the old refresh token sent again revokes the whole connection.
CREATE TABLE oauth_tokens (
id uuid PRIMARY KEY,
grant_id uuid NOT NULL REFERENCES oauth_grants (id) ON DELETE CASCADE,
access_hash bytea NOT NULL UNIQUE,
access_expires_at timestamptz NOT NULL,
refresh_hash bytea NOT NULL UNIQUE,
refresh_expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
refreshed_at timestamptz
);
CREATE INDEX oauth_tokens_grant_idx ON oauth_tokens (grant_id);
CREATE INDEX oauth_tokens_expiry_idx ON oauth_tokens (refresh_expires_at);