BlueGit

timfa filemanager

Files

filemanager / server / api / store.js

store.js

store.js 15.2 KiB Download Raw
1'use strict';
2
3// Storage for the public API: OAuth clients, grants (one per authorised
4// app/device or personal token), access tokens and authorization codes.
5// Secrets are only ever stored as SHA-256 hashes.
6
7const crypto = require('crypto');
8const { getDb } = require('../db');
9
10const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // 1 hour
11const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days, sliding
12const AUTH_CODE_TTL_MS = 10 * 60 * 1000;
13
14const SCOPES = ['files:read', 'files:write'];
15const SCOPE_DESCRIPTIONS = {
16 'files:read': 'List, read and download your files (everything you can see yourself)',
17 'files:write': 'Upload, create, rename, move and delete files and folders you can change yourself',
18};
19
20function initApiSchema (d)
21{
22 d.exec(`
23 CREATE TABLE IF NOT EXISTS api_clients (
24 client_id TEXT PRIMARY KEY,
25 name TEXT NOT NULL,
26 redirect_uris TEXT NOT NULL DEFAULT '[]',
27 created_by TEXT NOT NULL,
28 created_at INTEGER NOT NULL,
29 disabled_at INTEGER
30 );
31
32 CREATE TABLE IF NOT EXISTS api_grants (
33 id TEXT PRIMARY KEY,
34 username TEXT NOT NULL,
35 kind TEXT NOT NULL,
36 client_id TEXT,
37 name TEXT NOT NULL,
38 scopes TEXT NOT NULL,
39 created_at INTEGER NOT NULL,
40 last_used_at INTEGER,
41 last_used_ip TEXT,
42 expires_at INTEGER,
43 revoked_at INTEGER,
44 secret_hash TEXT,
45 refresh_hash TEXT,
46 refresh_expires_at INTEGER,
47 prev_refresh_hash TEXT
48 );
49 CREATE INDEX IF NOT EXISTS idx_api_grants_username ON api_grants(username);
50 CREATE UNIQUE INDEX IF NOT EXISTS idx_api_grants_secret ON api_grants(secret_hash);
51 CREATE UNIQUE INDEX IF NOT EXISTS idx_api_grants_refresh ON api_grants(refresh_hash);
52 CREATE INDEX IF NOT EXISTS idx_api_grants_prev_refresh ON api_grants(prev_refresh_hash);
53
54 CREATE TABLE IF NOT EXISTS api_access_tokens (
55 token_hash TEXT PRIMARY KEY,
56 grant_id TEXT NOT NULL,
57 expires_at INTEGER NOT NULL
58 );
59 CREATE INDEX IF NOT EXISTS idx_api_access_tokens_grant ON api_access_tokens(grant_id);
60
61 CREATE TABLE IF NOT EXISTS api_auth_codes (
62 code_hash TEXT PRIMARY KEY,
63 client_id TEXT NOT NULL,
64 username TEXT NOT NULL,
65 redirect_uri TEXT NOT NULL,
66 scopes TEXT NOT NULL,
67 code_challenge TEXT NOT NULL,
68 device_name TEXT NOT NULL,
69 expires_at INTEGER NOT NULL
70 );
71
72 CREATE TABLE IF NOT EXISTS api_entries (
73 root_key TEXT NOT NULL,
74 rel_path TEXT NOT NULL,
75 file_id TEXT NOT NULL,
76 is_dir INTEGER NOT NULL,
77 size INTEGER NOT NULL,
78 mtime_ms INTEGER NOT NULL,
79 version TEXT NOT NULL,
80 PRIMARY KEY (root_key, rel_path)
81 );
82
83 CREATE TABLE IF NOT EXISTS api_changes (
84 seq INTEGER PRIMARY KEY AUTOINCREMENT,
85 root_key TEXT NOT NULL,
86 change TEXT NOT NULL,
87 rel_path TEXT NOT NULL,
88 old_rel_path TEXT,
89 file_id TEXT NOT NULL,
90 is_dir INTEGER NOT NULL,
91 size INTEGER,
92 mtime_ms INTEGER,
93 version TEXT,
94 at INTEGER NOT NULL
95 );
96 CREATE INDEX IF NOT EXISTS idx_api_changes_root ON api_changes(root_key, seq);
97
98 CREATE TABLE IF NOT EXISTS api_scan_state (
99 root_key TEXT PRIMARY KEY,
100 generation TEXT NOT NULL,
101 last_scan_at INTEGER NOT NULL DEFAULT 0,
102 dirty INTEGER NOT NULL DEFAULT 1,
103 min_seq INTEGER NOT NULL DEFAULT 0
104 );
105
106 CREATE TABLE IF NOT EXISTS api_hashes (
107 abs_path TEXT PRIMARY KEY,
108 size INTEGER NOT NULL,
109 mtime_ms INTEGER NOT NULL,
110 sha256 TEXT NOT NULL
111 );
112
113 CREATE TABLE IF NOT EXISTS api_uploads (
114 id TEXT PRIMARY KEY,
115 grant_id TEXT NOT NULL,
116 username TEXT NOT NULL,
117 target TEXT NOT NULL,
118 size INTEGER NOT NULL,
119 received INTEGER NOT NULL DEFAULT 0,
120 sha256 TEXT,
121 mtime_ms INTEGER,
122 if_match TEXT,
123 if_none_match INTEGER NOT NULL DEFAULT 0,
124 overwrite INTEGER NOT NULL DEFAULT 0,
125 created_at INTEGER NOT NULL,
126 expires_at INTEGER NOT NULL
127 );
128 `);
129}
130
131function sha256Hex (value)
132{
133 return crypto.createHash('sha256').update(String(value)).digest('hex');
134}
135
136function randomToken (prefix, bytes = 32)
137{
138 return prefix + crypto.randomBytes(bytes).toString('base64url');
139}
140
141function now ()
142{
143 return Date.now();
144}
145
146function normalizeScopes (raw)
147{
148 const list = Array.isArray(raw) ? raw : String(raw || '').split(/[\s,]+/);
149 const out = [];
150 for (const s of list)
151 {
152 const v = String(s || '').trim();
153 if (!v) continue;
154 if (!SCOPES.includes(v)) return null;
155 if (!out.includes(v)) out.push(v);
156 }
157 // Write implies read: a sync client must see what it changes.
158 if (out.includes('files:write') && !out.includes('files:read')) out.unshift('files:read');
159 return out;
160}
161
162// ---------------------------------------------------------------------------
163// Clients
164// ---------------------------------------------------------------------------
165
166function parseClient (row)
167{
168 if (!row) return null;
169 let uris = [];
170 try { uris = JSON.parse(row.redirect_uris || '[]'); } catch { uris = []; }
171 return {
172 clientId: row.client_id,
173 name: row.name,
174 redirectUris: Array.isArray(uris) ? uris : [],
175 createdBy: row.created_by,
176 createdAt: row.created_at,
177 disabled: !!row.disabled_at,
178 };
179}
180
181function validateRedirectUri (uri)
182{
183 let u;
184 try { u = new URL(String(uri)); } catch { return false; }
185 if (u.hash) return false;
186 if (u.protocol === 'https:') return true;
187 if (u.protocol === 'http:') return u.hostname === '127.0.0.1' || u.hostname === '[::1]' || u.hostname === 'localhost';
188 // Private-use URI scheme for mobile/desktop apps (RFC 8252 7.1), e.g. com.example.app:/cb
189 return /^[a-z][a-z0-9+.-]*\.[a-z0-9+.-]+:$/i.test(u.protocol);
190}
191
192function createClient ({ name, redirectUris, createdBy })
193{
194 const clientId = 'fmc_' + crypto.randomBytes(12).toString('base64url');
195 getDb().prepare('INSERT INTO api_clients (client_id, name, redirect_uris, created_by, created_at) VALUES (?, ?, ?, ?, ?)')
196 .run([clientId, name, JSON.stringify(redirectUris), createdBy, now()]);
197 return getClient(clientId);
198}
199
200function getClient (clientId)
201{
202 return parseClient(getDb().prepare('SELECT * FROM api_clients WHERE client_id = ?').get([String(clientId || '')]));
203}
204
205function listClients ()
206{
207 return getDb().prepare('SELECT * FROM api_clients ORDER BY created_at').all().map(parseClient);
208}
209
210function deleteClient (clientId)
211{
212 const d = getDb();
213 d.prepare('UPDATE api_clients SET disabled_at = ? WHERE client_id = ? AND disabled_at IS NULL').run([now(), clientId]);
214 const grants = d.prepare('SELECT id FROM api_grants WHERE client_id = ? AND revoked_at IS NULL').all([clientId]);
215 for (const g of grants) revokeGrant(g.id);
216}
217
218/**
219 * RFC 8252 7.3: for loopback redirects the port may vary at request time.
220 */
221function redirectUriAllowed (client, uri)
222{
223 if (!client || !uri) return false;
224 if (client.redirectUris.includes(uri)) return true;
225 let req;
226 try { req = new URL(uri); } catch { return false; }
227 if (req.protocol !== 'http:' || !['127.0.0.1', '[::1]', 'localhost'].includes(req.hostname)) return false;
228 return client.redirectUris.some((reg) =>
229 {
230 try
231 {
232 const r = new URL(reg);
233 return r.protocol === 'http:' && r.hostname === req.hostname && r.pathname === req.pathname;
234 } catch { return false; }
235 });
236}
237
238// ---------------------------------------------------------------------------
239// Authorization codes
240// ---------------------------------------------------------------------------
241
242function createAuthCode ({ clientId, username, redirectUri, scopes, codeChallenge, deviceName })
243{
244 const code = randomToken('fmo_');
245 const d = getDb();
246 d.prepare('DELETE FROM api_auth_codes WHERE expires_at < ?').run([now()]);
247 d.prepare(`INSERT INTO api_auth_codes (code_hash, client_id, username, redirect_uri, scopes, code_challenge, device_name, expires_at)
248 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
249 .run([sha256Hex(code), clientId, username, redirectUri, scopes.join(' '), codeChallenge, deviceName, now() + AUTH_CODE_TTL_MS]);
250 return code;
251}
252
253/** Single use: the row is deleted whether or not the exchange succeeds. */
254function consumeAuthCode (code)
255{
256 const d = getDb();
257 const hash = sha256Hex(code || '');
258 const row = d.prepare('SELECT * FROM api_auth_codes WHERE code_hash = ?').get([hash]);
259 if (!row) return null;
260 d.prepare('DELETE FROM api_auth_codes WHERE code_hash = ?').run([hash]);
261 if (row.expires_at < now()) return null;
262 return row;
263}
264
265function pkceS256 (verifier)
266{
267 return crypto.createHash('sha256').update(String(verifier)).digest('base64url');
268}
269
270// ---------------------------------------------------------------------------
271// Grants and tokens
272// ---------------------------------------------------------------------------
273
274function issueTokensForGrant (grantId)
275{
276 const d = getDb();
277 const accessToken = randomToken('fma_');
278 const refreshToken = randomToken('fmr_');
279 const t = now();
280 d.prepare('DELETE FROM api_access_tokens WHERE expires_at < ?').run([t]);
281 d.prepare('INSERT INTO api_access_tokens (token_hash, grant_id, expires_at) VALUES (?, ?, ?)')
282 .run([sha256Hex(accessToken), grantId, t + ACCESS_TOKEN_TTL_MS]);
283 const g = d.prepare('SELECT refresh_hash FROM api_grants WHERE id = ?').get([grantId]);
284 d.prepare('UPDATE api_grants SET prev_refresh_hash = ?, refresh_hash = ?, refresh_expires_at = ? WHERE id = ?')
285 .run([g ? g.refresh_hash : null, sha256Hex(refreshToken), t + REFRESH_TOKEN_TTL_MS, grantId]);
286 return { accessToken, refreshToken, expiresIn: Math.floor(ACCESS_TOKEN_TTL_MS / 1000) };
287}
288
289function createOAuthGrant ({ username, clientId, name, scopes })
290{
291 const id = 'g_' + crypto.randomBytes(12).toString('base64url');
292 getDb().prepare('INSERT INTO api_grants (id, username, kind, client_id, name, scopes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
293 .run([id, username, 'oauth', clientId, name, scopes.join(' '), now()]);
294 return id;
295}
296
297function createPersonalToken ({ username, name, scopes, expiresAt })
298{
299 const id = 'g_' + crypto.randomBytes(12).toString('base64url');
300 const token = randomToken('fmp_');
301 getDb().prepare('INSERT INTO api_grants (id, username, kind, client_id, name, scopes, created_at, expires_at, secret_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
302 .run([id, username, 'personal', null, name, scopes.join(' '), now(), expiresAt || null, sha256Hex(token)]);
303 return { id, token };
304}
305
306function getGrant (id)
307{
308 return getDb().prepare('SELECT * FROM api_grants WHERE id = ?').get([String(id || '')]) || null;
309}
310
311/**
312 * Refresh token rotation with reuse detection: presenting an already rotated
313 * refresh token revokes the whole grant (it was probably stolen).
314 */
315function refreshGrant (clientId, refreshToken)
316{
317 const d = getDb();
318 const hash = sha256Hex(refreshToken || '');
319 const g = d.prepare('SELECT * FROM api_grants WHERE refresh_hash = ?').get([hash]);
320 if (!g)
321 {
322 const reused = d.prepare('SELECT id FROM api_grants WHERE prev_refresh_hash = ?').get([hash]);
323 if (reused) revokeGrant(reused.id);
324 return { error: 'invalid_grant' };
325 }
326 if (g.revoked_at || g.client_id !== clientId || !g.refresh_expires_at || g.refresh_expires_at < now())
327 {
328 return { error: 'invalid_grant' };
329 }
330 const client = getClient(g.client_id);
331 if (!client || client.disabled) return { error: 'invalid_grant' };
332 if (!userExists(g.username)) return { error: 'invalid_grant' };
333 return { grant: g, tokens: issueTokensForGrant(g.id) };
334}
335
336function revokeGrant (id)
337{
338 const d = getDb();
339 d.prepare('UPDATE api_grants SET revoked_at = ?, refresh_hash = NULL, prev_refresh_hash = NULL, secret_hash = NULL WHERE id = ? AND revoked_at IS NULL')
340 .run([now(), id]);
341 d.prepare('DELETE FROM api_access_tokens WHERE grant_id = ?').run([id]);
342 d.prepare('DELETE FROM api_uploads WHERE grant_id = ?').run([id]);
343}
344
345function revokeAllForUser (username)
346{
347 const rows = getDb().prepare('SELECT id FROM api_grants WHERE username = ? AND revoked_at IS NULL').all([username]);
348 for (const r of rows) revokeGrant(r.id);
349}
350
351/** Revoke by presenting either the access or the refresh token (RFC 7009). */
352function revokeByToken (token)
353{
354 const d = getDb();
355 const hash = sha256Hex(token || '');
356 const at = d.prepare('SELECT grant_id FROM api_access_tokens WHERE token_hash = ?').get([hash]);
357 if (at) { revokeGrant(at.grant_id); return true; }
358 const g = d.prepare('SELECT id FROM api_grants WHERE refresh_hash = ? OR secret_hash = ?').get([hash, hash]);
359 if (g) { revokeGrant(g.id); return true; }
360 return false;
361}
362
363function userExists (username)
364{
365 return !!getDb().prepare('SELECT 1 AS ok FROM users WHERE username = ?').get([username]);
366}
367
368/**
369 * Resolve a bearer token to { grant, scopes }. Returns null when the token is
370 * unknown, expired or revoked.
371 */
372function resolveBearer (token)
373{
374 const t = String(token || '');
375 if (!t) return null;
376 const d = getDb();
377 const hash = sha256Hex(t);
378 let grant = null;
379 if (t.startsWith('fma_'))
380 {
381 const row = d.prepare('SELECT grant_id, expires_at FROM api_access_tokens WHERE token_hash = ?').get([hash]);
382 if (!row || row.expires_at < now()) return null;
383 grant = getGrant(row.grant_id);
384 } else if (t.startsWith('fmp_'))
385 {
386 grant = d.prepare('SELECT * FROM api_grants WHERE secret_hash = ?').get([hash]) || null;
387 if (grant && grant.expires_at && grant.expires_at < now()) return null;
388 }
389 if (!grant || grant.revoked_at) return null;
390 if (grant.kind === 'oauth')
391 {
392 const client = getClient(grant.client_id);
393 if (!client || client.disabled) return null;
394 }
395 return { grant, scopes: String(grant.scopes || '').split(' ').filter(Boolean) };
396}
397
398function touchGrant (id, ip)
399{
400 const g = getGrant(id);
401 if (!g) return;
402 const t = now();
403 if (!g.last_used_at || t - g.last_used_at > 60 * 1000 || g.last_used_ip !== ip)
404 {
405 getDb().prepare('UPDATE api_grants SET last_used_at = ?, last_used_ip = ? WHERE id = ?').run([t, ip, id]);
406 }
407}
408
409function listGrantsForUser (username)
410{
411 return getDb().prepare(`SELECT g.*, c.name AS client_name FROM api_grants g LEFT JOIN api_clients c ON c.client_id = g.client_id
412 WHERE g.username = ? AND g.revoked_at IS NULL ORDER BY g.created_at DESC`)
413 .all([username])
414 .map((g) => ({
415 id: g.id,
416 kind: g.kind,
417 name: g.name,
418 clientId: g.client_id,
419 clientName: g.client_name || null,
420 scopes: String(g.scopes || '').split(' ').filter(Boolean),
421 createdAt: g.created_at,
422 lastUsedAt: g.last_used_at,
423 lastUsedIp: g.last_used_ip,
424 expiresAt: g.expires_at || (g.kind === 'oauth' ? g.refresh_expires_at : null),
425 }));
426}
427
428module.exports = {
429 SCOPES,
430 SCOPE_DESCRIPTIONS,
431 ACCESS_TOKEN_TTL_MS,
432 REFRESH_TOKEN_TTL_MS,
433 initApiSchema,
434 sha256Hex,
435 normalizeScopes,
436 validateRedirectUri,
437 createClient,
438 getClient,
439 listClients,
440 deleteClient,
441 redirectUriAllowed,
442 createAuthCode,
443 consumeAuthCode,
444 pkceS256,
445 createOAuthGrant,
446 createPersonalToken,
447 issueTokensForGrant,
448 refreshGrant,
449 revokeGrant,
450 revokeAllForUser,
451 revokeByToken,
452 resolveBearer,
453 touchGrant,
454 getGrant,
455 listGrantsForUser,
456 userExists,
457};