| [d49b60b] | 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 | */
|
|---|
| 14 | import express from 'express';
|
|---|
| 15 | import db from '../config/database.js';
|
|---|
| 16 | import OAuth from '../services/OAuthService.js';
|
|---|
| 17 | import { requireAuth } from '../middleware/auth.js';
|
|---|
| 18 | import { renderPage } from '../middleware/render.js';
|
|---|
| 19 | import PermissionsService from '../services/PermissionsService.js';
|
|---|
| 20 | import { apEnabled } from '../services/SettingsService.js';
|
|---|
| 21 |
|
|---|
| 22 | const router = express.Router();
|
|---|
| 23 | router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
|
|---|
| 24 |
|
|---|
| 25 | const 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.
|
|---|
| 28 | function 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.
|
|---|
| 38 | function 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).
|
|---|
| 49 | function 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 ────────────────────────────────────────────
|
|---|
| 55 | router.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 ────────────────────────────────
|
|---|
| 71 | router.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 ────────────────────────────────────────
|
|---|
| 78 | router.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 |
|
|---|
| 96 | router.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 ───────────────────────────────────────────────────────
|
|---|
| 117 | router.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 |
|
|---|
| 130 | export default router;
|
|---|