source: Klonkt/src/routes/oauth.js@ dd568e7

main
Last change on this file since dd568e7 was d49b60b, checked in by Robin <roboburr@…>, 7 weeks ago

Feature: OAuth 2.0 for ActivityPub C2S (phase 1 — auth handshake)

First half of AP Client-to-Server: the auth layer native/web clients (Shaer)
need before they can drive a Klonkt account. The AP spec's own C2S half is what
keeps this inside-spec instead of cloning Mastodon's REST API.

  • OAuthService: public-client OAuth (RFC 8252), PKCE S256 REQUIRED, no secrets. Dynamic registration (RFC 7591 subset) with strict redirect_uri validation (https / loopback http / reverse-DNS custom scheme). Single-use 10-min codes; tokens stored sha256-hashed; a token is scoped to one user + one site.
  • routes/oauth.js: /oauth/register, /oauth/authorize (session-authed consent screen picking the site), /oauth/token, and RFC 8414 server metadata at /.well-known/oauth-authorization-server. Redirect params are appended to the registered URI verbatim (no new URL() round-trip that would mangle a native custom scheme). Pre-redirect validation errors never bounce to an unvalidated URI (open-redirect guard).
  • Actor doc advertises oauthAuthorizationEndpoint/oauthTokenEndpoint/uploadMedia in endpoints{} — all AP-spec terms, added to the AS2 conformance allowlist — so clients discover paths instead of hardcoding them (Klonkt's /ap/users/:slug differs from the daemon's /actors/:name; discovery makes that irrelevant).
  • oauth_clients/oauth_codes/oauth_tokens tables (additive).
  • i18n NL/EN/DE for the consent screen.

7 new OAuth tests (PKCE round-trip, replay protection, wrong-verifier reject,
bearer resolution incl. revoke, redirect-uri validation); 73 green. Verified
the full HTTP flow end to end (register → consent → code → token → bearer) and
that the raw Location header preserves the native redirect URI exactly. Beads:
klonkt-demo-srr. Next: klonkt-demo-1w4 (POST outbox accepts the activities).

Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 6.7 KB
Line 
1/**
2 * OAuth 2.0 routes for ActivityPub Client-to-Server (native/web clients).
3 *
4 * POST /oauth/register dynamic client registration (RFC 7591 subset)
5 * GET /.well-known/oauth-authorization-server server metadata (RFC 8414)
6 * GET /oauth/authorize consent screen (session-authenticated)
7 * POST /oauth/authorize user grants → redirect back with ?code
8 * POST /oauth/token code + PKCE verifier → bearer token
9 *
10 * Auth model: PUBLIC clients + PKCE only (see OAuthService). The consent screen
11 * reuses Klonkt's normal login session; the token it mints is scoped to one
12 * user + one of their sites.
13 */
14import express from 'express';
15import db from '../config/database.js';
16import OAuth from '../services/OAuthService.js';
17import { requireAuth } from '../middleware/auth.js';
18import { renderPage } from '../middleware/render.js';
19import PermissionsService from '../services/PermissionsService.js';
20import { apEnabled } from '../services/SettingsService.js';
21
22const router = express.Router();
23router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
24
25const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
26
27// Sites this user may post as (owner or co-admin). The consent screen lists these.
28function manageableSites(user) {
29 return db.prepare('SELECT id, slug, title, owner_id FROM sites ORDER BY created_at')
30 .all()
31 .filter((s) => PermissionsService.canAdminSite(user, s));
32}
33
34// Append query params to a redirect URI WITHOUT re-serializing it: native custom
35// schemes (com.shaer.app:/cb) get mangled by new URL().toString() (→ //cb/), and
36// RFC 6749 §4.1.2 says to append to the registered URI as-is. The URI is already
37// validated against the registered set before we ever call this.
38function redirectWith(redirectUri, params) {
39 const q = Object.entries(params)
40 .filter(([, v]) => v !== undefined && v !== null && v !== '')
41 .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
42 .join('&');
43 const sep = redirectUri.includes('?') ? '&' : '?';
44 return q ? `${redirectUri}${sep}${q}` : redirectUri;
45}
46
47// Bounce back to the client with an OAuth error (RFC 6749 §4.1.2.1) when we have
48// a validated redirect_uri; otherwise render a plain error (open-redirect guard).
49function authError(res, redirectUri, state, error, desc) {
50 if (redirectUri) return res.redirect(redirectWith(redirectUri, { error, error_description: desc, state }));
51 return res.status(400).json({ error, error_description: desc });
52}
53
54// ── RFC 8414: server metadata ────────────────────────────────────────────
55router.get('/.well-known/oauth-authorization-server', (req, res) => {
56 const base = baseUrl(req);
57 res.type('application/json').json({
58 issuer: base,
59 authorization_endpoint: `${base}/oauth/authorize`,
60 token_endpoint: `${base}/oauth/token`,
61 registration_endpoint: `${base}/oauth/register`,
62 response_types_supported: ['code'],
63 grant_types_supported: ['authorization_code'],
64 code_challenge_methods_supported: ['S256'],
65 token_endpoint_auth_methods_supported: ['none'],
66 scopes_supported: ['c2s'],
67 });
68});
69
70// ── RFC 7591: dynamic client registration ────────────────────────────────
71router.post('/oauth/register', (req, res) => {
72 const out = OAuth.registerClient({ client_name: req.body.client_name, redirect_uris: req.body.redirect_uris });
73 if (out.error) return res.status(400).json(out);
74 return res.status(201).json(out);
75});
76
77// ── Authorization: consent screen ────────────────────────────────────────
78router.get('/oauth/authorize', requireAuth, (req, res) => {
79 const { client_id, redirect_uri, response_type, code_challenge, code_challenge_method, scope, state } = req.query;
80 const client = OAuth.getClient(client_id);
81 // Pre-redirect validation errors must NOT bounce to an unvalidated URI.
82 if (!client) return res.status(400).json({ error: 'invalid_client' });
83 if (!client.redirect_uris.includes(String(redirect_uri || ''))) return res.status(400).json({ error: 'invalid_request', error_description: 'redirect_uri not registered' });
84 if (response_type !== 'code') return authError(res, redirect_uri, state, 'unsupported_response_type');
85 if (code_challenge_method !== 'S256' || !code_challenge) return authError(res, redirect_uri, state, 'invalid_request', 'PKCE S256 required');
86
87 const sites = manageableSites(req.session.user);
88 if (!sites.length) return authError(res, redirect_uri, state, 'access_denied', 'no manageable sites for this account');
89
90 return renderPage(req, res, 'pages/oauth-consent', {
91 pageTitleKey: 'oauth.title', bodyClass: 'on-special',
92 client, sites, params: { client_id, redirect_uri, code_challenge, scope: scope || 'c2s', state: state || '' },
93 });
94});
95
96router.post('/oauth/authorize', requireAuth, (req, res) => {
97 const { client_id, redirect_uri, code_challenge, scope, state, site_slug, decision } = req.body;
98 const client = OAuth.getClient(client_id);
99 if (!client || !client.redirect_uris.includes(String(redirect_uri || ''))) {
100 return res.status(400).json({ error: 'invalid_request', error_description: 'client/redirect mismatch' });
101 }
102 if (decision !== 'allow') return authError(res, redirect_uri, state, 'access_denied');
103
104 const site = db.prepare('SELECT id, slug, owner_id FROM sites WHERE slug = ?').get(String(site_slug || ''));
105 if (!site || !PermissionsService.canAdminSite(req.session.user, site)) {
106 return authError(res, redirect_uri, state, 'access_denied', 'not allowed to post as this site');
107 }
108 const out = OAuth.createCode({
109 clientId: client_id, userId: req.session.user.id, siteSlug: site.slug,
110 redirectUri: redirect_uri, codeChallenge: code_challenge, scope,
111 });
112 if (out.error) return authError(res, redirect_uri, state, out.error, out.error_description);
113 return res.redirect(redirectWith(redirect_uri, { code: out.code, state }));
114});
115
116// ── Token exchange ───────────────────────────────────────────────────────
117router.post('/oauth/token', (req, res) => {
118 res.set('Cache-Control', 'no-store');
119 if (req.body.grant_type !== 'authorization_code') {
120 return res.status(400).json({ error: 'unsupported_grant_type' });
121 }
122 const out = OAuth.exchangeCode({
123 code: req.body.code, client_id: req.body.client_id,
124 redirect_uri: req.body.redirect_uri, code_verifier: req.body.code_verifier,
125 });
126 if (out.error) return res.status(400).json(out);
127 return res.json(out);
128});
129
130export default router;
Note: See TracBrowser for help on using the repository browser.