BlueGit

timfa filemanager

Files

filemanager / server / api / oauth.js

oauth.js

oauth.js 12.6 KiB Download Raw
1'use strict';
2
3// OAuth 2.0 authorization server for the public API.
4// Authorization code flow with mandatory PKCE (S256) for public clients
5// (mobile/desktop/sync services; no client secrets), refresh token rotation,
6// token revocation (RFC 7009) and server metadata (RFC 8414).
7
8const express = require('express');
9const bcrypt = require('bcrypt');
10const store = require('./store');
11const { getDb } = require('../db');
12const { getClientIp } = require('../auth');
13const { publicBaseUrl, publicPathPrefix } = require('../public-url');
14
15const router = express.Router();
16const formParser = express.urlencoded({ extended: false, limit: '32kb' });
17const jsonParser = express.json({ limit: '32kb' });
18
19const LOGIN_FAIL_WINDOW_MS = 15 * 60 * 1000;
20const LOGIN_FAIL_MAX = 10;
21const loginFailures = new Map();
22
23function issuer (req)
24{
25 return publicBaseUrl(req);
26}
27
28function esc (v)
29{
30 return String(v == null ? '' : v)
31 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
32 .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
33}
34
35function noStore (res)
36{
37 res.set('Cache-Control', 'no-store');
38 res.set('Pragma', 'no-cache');
39}
40
41function pageHeaders (res)
42{
43 noStore(res);
44 res.set('X-Frame-Options', 'DENY');
45 res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
46 res.set('Referrer-Policy', 'no-referrer');
47}
48
49function tooManyFailures (key)
50{
51 const t = Date.now();
52 const list = (loginFailures.get(key) || []).filter((x) => t - x < LOGIN_FAIL_WINDOW_MS);
53 loginFailures.set(key, list);
54 return list.length >= LOGIN_FAIL_MAX;
55}
56
57function recordFailure (key)
58{
59 const list = loginFailures.get(key) || [];
60 list.push(Date.now());
61 loginFailures.set(key, list);
62 if (loginFailures.size > 10000) loginFailures.clear();
63}
64
65function resetLoginFailures ()
66{
67 loginFailures.clear();
68}
69
70/**
71 * Validates an authorization request. Returns { fatal } when we must NOT
72 * redirect (unknown client or redirect URI), { redirectError } for errors
73 * that go back to the client, or { request } when valid.
74 */
75function parseAuthorizeRequest (params)
76{
77 const clientId = String(params.client_id || '');
78 const redirectUri = String(params.redirect_uri || '');
79 const client = store.getClient(clientId);
80 if (!client || client.disabled) return { fatal: 'Unknown or disabled client_id.' };
81 if (!redirectUri || !store.redirectUriAllowed(client, redirectUri)) return { fatal: 'redirect_uri is not registered for this client.' };
82
83 const state = params.state != null ? String(params.state) : undefined;
84 const fail = (error, description) => ({ redirectError: { redirectUri, error, description, state } });
85
86 if (params.response_type !== 'code') return fail('unsupported_response_type', 'Only response_type=code is supported.');
87 const challenge = String(params.code_challenge || '');
88 if (!challenge) return fail('invalid_request', 'PKCE code_challenge is required.');
89 if (params.code_challenge_method !== 'S256') return fail('invalid_request', 'code_challenge_method must be S256.');
90 if (!/^[A-Za-z0-9_-]{43}$/.test(challenge)) return fail('invalid_request', 'Malformed code_challenge.');
91 const scopes = store.normalizeScopes(params.scope || 'files:read');
92 if (!scopes || !scopes.length) return fail('invalid_scope', `Allowed scopes: ${store.SCOPES.join(' ')}`);
93 const deviceName = String(params.device_name || '').trim().slice(0, 80) || client.name;
94
95 return { request: { client, clientId, redirectUri, state, scopes, codeChallenge: challenge, deviceName } };
96}
97
98function redirectWith (res, req, redirectUri, params)
99{
100 const u = new URL(redirectUri);
101 for (const [k, v] of Object.entries(params))
102 {
103 if (v !== undefined && v !== null) u.searchParams.set(k, v);
104 }
105 u.searchParams.set('iss', issuer(req));
106 noStore(res);
107 return res.redirect(302, u.toString());
108}
109
110function renderError (res, status, message)
111{
112 pageHeaders(res);
113 res.status(status).type('html').send(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Authorization error</title></head>
114<body style="font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem"><h1>Authorization error</h1><p>${esc(message)}</p></body></html>`);
115}
116
117function renderConsent (req, res, r, errorMessage, username)
118{
119 pageHeaders(res);
120 const hidden = {
121 response_type: 'code',
122 client_id: r.clientId,
123 redirect_uri: r.redirectUri,
124 scope: r.scopes.join(' '),
125 state: r.state,
126 code_challenge: r.codeChallenge,
127 code_challenge_method: 'S256',
128 device_name: r.deviceName,
129 };
130 const hiddenHtml = Object.entries(hidden)
131 .filter(([, v]) => v !== undefined)
132 .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('\n');
133 const scopeHtml = r.scopes.map((s) => `<li><strong>${esc(s)}</strong>: ${esc(store.SCOPE_DESCRIPTIONS[s])}</li>`).join('');
134 let host = r.redirectUri;
135 try { host = new URL(r.redirectUri).host || r.redirectUri; } catch { /* keep */ }
136 res.status(errorMessage ? 401 : 200).type('html').send(`<!doctype html>
137<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
138<title>Allow access to your files?</title>
139<style>
140body{font-family:system-ui,sans-serif;background:#f4f5f7;margin:0;padding:1rem}
141main{max-width:28rem;margin:2rem auto;background:#fff;border-radius:10px;padding:1.5rem;box-shadow:0 1px 4px #0002}
142label{display:block;margin:.6rem 0 .2rem}input[type=text],input[type=password]{width:100%;box-sizing:border-box;padding:.55rem;font-size:1rem}
143.err{background:#fdecea;color:#8a1c12;padding:.5rem .75rem;border-radius:6px}.btns{display:flex;gap:.5rem;margin-top:1rem}
144button{flex:1;padding:.65rem;font-size:1rem;border-radius:6px;border:1px solid #888;cursor:pointer}button.allow{background:#1f6feb;color:#fff;border-color:#1f6feb}
145small{color:#555}
146</style></head>
147<body><main>
148<h1 style="font-size:1.3rem">Allow <em>${esc(r.client.name)}</em> to access your files?</h1>
149<p>Device: <strong>${esc(r.deviceName)}</strong><br><small>After approval you will be sent back to ${esc(host)}.</small></p>
150<p>This app asks for:</p><ul>${scopeHtml}</ul>
151<p><small>The app can never see more than you can. You can revoke access at any time on the <em>Connected apps</em> page (${esc(publicBaseUrl(req))}/apps.html).</small></p>
152${errorMessage ? `<p class="err">${esc(errorMessage)}</p>` : ''}
153<form method="post" action="${esc(publicPathPrefix(req))}/oauth/authorize" autocomplete="on">
154${hiddenHtml}
155<label for="u">Username</label><input id="u" type="text" name="username" autocomplete="username" value="${esc(username || '')}">
156<label for="p">Password</label><input id="p" type="password" name="password" autocomplete="current-password">
157<div class="btns"><button type="submit" name="decision" value="deny">Deny</button><button class="allow" type="submit" name="decision" value="allow">Allow</button></div>
158</form></main></body></html>`);
159}
160
161router.get('/.well-known/oauth-authorization-server', (req, res) =>
162{
163 const base = issuer(req);
164 res.json({
165 issuer: base,
166 authorization_endpoint: `${base}/oauth/authorize`,
167 token_endpoint: `${base}/oauth/token`,
168 revocation_endpoint: `${base}/oauth/revoke`,
169 scopes_supported: store.SCOPES,
170 response_types_supported: ['code'],
171 grant_types_supported: ['authorization_code', 'refresh_token'],
172 code_challenge_methods_supported: ['S256'],
173 token_endpoint_auth_methods_supported: ['none'],
174 authorization_response_iss_parameter_supported: true,
175 service_documentation: `${base}/api/v1/openapi.json`,
176 });
177});
178
179router.get('/oauth/authorize', (req, res) =>
180{
181 const parsed = parseAuthorizeRequest(req.query);
182 if (parsed.fatal) return renderError(res, 400, parsed.fatal);
183 if (parsed.redirectError)
184 {
185 const e = parsed.redirectError;
186 return redirectWith(res, req, e.redirectUri, { error: e.error, error_description: e.description, state: e.state });
187 }
188 return renderConsent(req, res, parsed.request, null, '');
189});
190
191router.post('/oauth/authorize', formParser, async (req, res, next) =>
192{
193 try
194 {
195 const body = req.body || {};
196 const parsed = parseAuthorizeRequest(body);
197 if (parsed.fatal) return renderError(res, 400, parsed.fatal);
198 if (parsed.redirectError)
199 {
200 const e = parsed.redirectError;
201 return redirectWith(res, req, e.redirectUri, { error: e.error, error_description: e.description, state: e.state });
202 }
203 const r = parsed.request;
204 if (body.decision !== 'allow')
205 {
206 return redirectWith(res, req, r.redirectUri, { error: 'access_denied', error_description: 'The user denied access.', state: r.state });
207 }
208
209 const username = String(body.username || '').trim();
210 const password = String(body.password || '');
211 const ip = getClientIp(req);
212 const failKey = `${ip}|${username.toLowerCase()}`;
213 if (tooManyFailures(failKey) || tooManyFailures(ip))
214 {
215 return renderConsent(req, res, r, 'Too many failed attempts. Try again later.', username);
216 }
217
218 const row = username ? getDb().prepare('SELECT username, password_hash FROM users WHERE username = ?').get([username]) : null;
219 const ok = row ? await bcrypt.compare(password, row.password_hash) : false;
220 if (!ok)
221 {
222 recordFailure(failKey);
223 recordFailure(ip);
224 return renderConsent(req, res, r, 'Invalid username or password.', username);
225 }
226
227 const code = store.createAuthCode({
228 clientId: r.clientId,
229 username: row.username,
230 redirectUri: r.redirectUri,
231 scopes: r.scopes,
232 codeChallenge: r.codeChallenge,
233 deviceName: r.deviceName,
234 });
235 return redirectWith(res, req, r.redirectUri, { code, state: r.state });
236 } catch (err)
237 {
238 next(err);
239 }
240});
241
242function tokenError (res, status, error, description)
243{
244 noStore(res);
245 return res.status(status).json({ error, error_description: description });
246}
247
248function cors (req, res, next)
249{
250 res.set('Access-Control-Allow-Origin', '*');
251 res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
252 res.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
253 if (req.method === 'OPTIONS') return res.status(204).end();
254 next();
255}
256
257router.options('/oauth/token', cors);
258router.options('/oauth/revoke', cors);
259
260router.post('/oauth/token', cors, formParser, jsonParser, (req, res) =>
261{
262 const body = req.body || {};
263 if (req.get('authorization')) return tokenError(res, 400, 'invalid_client', 'Clients are public; do not send client credentials.');
264 const clientId = String(body.client_id || '');
265 const client = store.getClient(clientId);
266 if (!client || client.disabled) return tokenError(res, 401, 'invalid_client', 'Unknown client_id.');
267
268 if (body.grant_type === 'authorization_code')
269 {
270 const row = store.consumeAuthCode(String(body.code || ''));
271 if (!row || row.client_id !== clientId) return tokenError(res, 400, 'invalid_grant', 'Invalid or expired code.');
272 if (String(body.redirect_uri || '') !== row.redirect_uri) return tokenError(res, 400, 'invalid_grant', 'redirect_uri mismatch.');
273 const verifier = String(body.code_verifier || '');
274 if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier) || store.pkceS256(verifier) !== row.code_challenge)
275 {
276 return tokenError(res, 400, 'invalid_grant', 'PKCE verification failed.');
277 }
278 if (!store.userExists(row.username)) return tokenError(res, 400, 'invalid_grant', 'User no longer exists.');
279 const scopes = row.scopes.split(' ');
280 const grantId = store.createOAuthGrant({ username: row.username, clientId, name: row.device_name, scopes });
281 const t = store.issueTokensForGrant(grantId);
282 noStore(res);
283 return res.json({
284 access_token: t.accessToken,
285 token_type: 'Bearer',
286 expires_in: t.expiresIn,
287 refresh_token: t.refreshToken,
288 scope: scopes.join(' '),
289 grant_id: grantId,
290 });
291 }
292
293 if (body.grant_type === 'refresh_token')
294 {
295 const result = store.refreshGrant(clientId, String(body.refresh_token || ''));
296 if (result.error) return tokenError(res, 400, 'invalid_grant', 'Invalid, expired, reused or revoked refresh token.');
297 noStore(res);
298 return res.json({
299 access_token: result.tokens.accessToken,
300 token_type: 'Bearer',
301 expires_in: result.tokens.expiresIn,
302 refresh_token: result.tokens.refreshToken,
303 scope: result.grant.scopes,
304 grant_id: result.grant.id,
305 });
306 }
307
308 return tokenError(res, 400, 'unsupported_grant_type', 'Use authorization_code or refresh_token.');
309});
310
311router.post('/oauth/revoke', cors, formParser, jsonParser, (req, res) =>
312{
313 const token = String((req.body && req.body.token) || '');
314 if (token) store.revokeByToken(token);
315 noStore(res);
316 res.status(200).json({});
317});
318
319router.resetLoginFailures = resetLoginFailures;
320module.exports = router;