'use strict'; // Storage for the public API: OAuth clients, grants (one per authorised // app/device or personal token), access tokens and authorization codes. // Secrets are only ever stored as SHA-256 hashes. const crypto = require('crypto'); const { getDb } = require('../db'); const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // 1 hour const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days, sliding const AUTH_CODE_TTL_MS = 10 * 60 * 1000; const SCOPES = ['files:read', 'files:write']; const SCOPE_DESCRIPTIONS = { 'files:read': 'List, read and download your files (everything you can see yourself)', 'files:write': 'Upload, create, rename, move and delete files and folders you can change yourself', }; function initApiSchema (d) { d.exec(` CREATE TABLE IF NOT EXISTS api_clients ( client_id TEXT PRIMARY KEY, name TEXT NOT NULL, redirect_uris TEXT NOT NULL DEFAULT '[]', created_by TEXT NOT NULL, created_at INTEGER NOT NULL, disabled_at INTEGER ); CREATE TABLE IF NOT EXISTS api_grants ( id TEXT PRIMARY KEY, username TEXT NOT NULL, kind TEXT NOT NULL, client_id TEXT, name TEXT NOT NULL, scopes TEXT NOT NULL, created_at INTEGER NOT NULL, last_used_at INTEGER, last_used_ip TEXT, expires_at INTEGER, revoked_at INTEGER, secret_hash TEXT, refresh_hash TEXT, refresh_expires_at INTEGER, prev_refresh_hash TEXT ); CREATE INDEX IF NOT EXISTS idx_api_grants_username ON api_grants(username); CREATE UNIQUE INDEX IF NOT EXISTS idx_api_grants_secret ON api_grants(secret_hash); CREATE UNIQUE INDEX IF NOT EXISTS idx_api_grants_refresh ON api_grants(refresh_hash); CREATE INDEX IF NOT EXISTS idx_api_grants_prev_refresh ON api_grants(prev_refresh_hash); CREATE TABLE IF NOT EXISTS api_access_tokens ( token_hash TEXT PRIMARY KEY, grant_id TEXT NOT NULL, expires_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_api_access_tokens_grant ON api_access_tokens(grant_id); CREATE TABLE IF NOT EXISTS api_auth_codes ( code_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, username TEXT NOT NULL, redirect_uri TEXT NOT NULL, scopes TEXT NOT NULL, code_challenge TEXT NOT NULL, device_name TEXT NOT NULL, expires_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS api_entries ( root_key TEXT NOT NULL, rel_path TEXT NOT NULL, file_id TEXT NOT NULL, is_dir INTEGER NOT NULL, size INTEGER NOT NULL, mtime_ms INTEGER NOT NULL, version TEXT NOT NULL, PRIMARY KEY (root_key, rel_path) ); CREATE TABLE IF NOT EXISTS api_changes ( seq INTEGER PRIMARY KEY AUTOINCREMENT, root_key TEXT NOT NULL, change TEXT NOT NULL, rel_path TEXT NOT NULL, old_rel_path TEXT, file_id TEXT NOT NULL, is_dir INTEGER NOT NULL, size INTEGER, mtime_ms INTEGER, version TEXT, at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_api_changes_root ON api_changes(root_key, seq); CREATE TABLE IF NOT EXISTS api_scan_state ( root_key TEXT PRIMARY KEY, generation TEXT NOT NULL, last_scan_at INTEGER NOT NULL DEFAULT 0, dirty INTEGER NOT NULL DEFAULT 1, min_seq INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS api_hashes ( abs_path TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ms INTEGER NOT NULL, sha256 TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS api_uploads ( id TEXT PRIMARY KEY, grant_id TEXT NOT NULL, username TEXT NOT NULL, target TEXT NOT NULL, size INTEGER NOT NULL, received INTEGER NOT NULL DEFAULT 0, sha256 TEXT, mtime_ms INTEGER, if_match TEXT, if_none_match INTEGER NOT NULL DEFAULT 0, overwrite INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); `); } function sha256Hex (value) { return crypto.createHash('sha256').update(String(value)).digest('hex'); } function randomToken (prefix, bytes = 32) { return prefix + crypto.randomBytes(bytes).toString('base64url'); } function now () { return Date.now(); } function normalizeScopes (raw) { const list = Array.isArray(raw) ? raw : String(raw || '').split(/[\s,]+/); const out = []; for (const s of list) { const v = String(s || '').trim(); if (!v) continue; if (!SCOPES.includes(v)) return null; if (!out.includes(v)) out.push(v); } // Write implies read: a sync client must see what it changes. if (out.includes('files:write') && !out.includes('files:read')) out.unshift('files:read'); return out; } // --------------------------------------------------------------------------- // Clients // --------------------------------------------------------------------------- function parseClient (row) { if (!row) return null; let uris = []; try { uris = JSON.parse(row.redirect_uris || '[]'); } catch { uris = []; } return { clientId: row.client_id, name: row.name, redirectUris: Array.isArray(uris) ? uris : [], createdBy: row.created_by, createdAt: row.created_at, disabled: !!row.disabled_at, }; } function validateRedirectUri (uri) { let u; try { u = new URL(String(uri)); } catch { return false; } if (u.hash) return false; if (u.protocol === 'https:') return true; if (u.protocol === 'http:') return u.hostname === '127.0.0.1' || u.hostname === '[::1]' || u.hostname === 'localhost'; // Private-use URI scheme for mobile/desktop apps (RFC 8252 7.1), e.g. com.example.app:/cb return /^[a-z][a-z0-9+.-]*\.[a-z0-9+.-]+:$/i.test(u.protocol); } function createClient ({ name, redirectUris, createdBy }) { const clientId = 'fmc_' + crypto.randomBytes(12).toString('base64url'); getDb().prepare('INSERT INTO api_clients (client_id, name, redirect_uris, created_by, created_at) VALUES (?, ?, ?, ?, ?)') .run([clientId, name, JSON.stringify(redirectUris), createdBy, now()]); return getClient(clientId); } function getClient (clientId) { return parseClient(getDb().prepare('SELECT * FROM api_clients WHERE client_id = ?').get([String(clientId || '')])); } function listClients () { return getDb().prepare('SELECT * FROM api_clients ORDER BY created_at').all().map(parseClient); } function deleteClient (clientId) { const d = getDb(); d.prepare('UPDATE api_clients SET disabled_at = ? WHERE client_id = ? AND disabled_at IS NULL').run([now(), clientId]); const grants = d.prepare('SELECT id FROM api_grants WHERE client_id = ? AND revoked_at IS NULL').all([clientId]); for (const g of grants) revokeGrant(g.id); } /** * RFC 8252 7.3: for loopback redirects the port may vary at request time. */ function redirectUriAllowed (client, uri) { if (!client || !uri) return false; if (client.redirectUris.includes(uri)) return true; let req; try { req = new URL(uri); } catch { return false; } if (req.protocol !== 'http:' || !['127.0.0.1', '[::1]', 'localhost'].includes(req.hostname)) return false; return client.redirectUris.some((reg) => { try { const r = new URL(reg); return r.protocol === 'http:' && r.hostname === req.hostname && r.pathname === req.pathname; } catch { return false; } }); } // --------------------------------------------------------------------------- // Authorization codes // --------------------------------------------------------------------------- function createAuthCode ({ clientId, username, redirectUri, scopes, codeChallenge, deviceName }) { const code = randomToken('fmo_'); const d = getDb(); d.prepare('DELETE FROM api_auth_codes WHERE expires_at < ?').run([now()]); d.prepare(`INSERT INTO api_auth_codes (code_hash, client_id, username, redirect_uri, scopes, code_challenge, device_name, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) .run([sha256Hex(code), clientId, username, redirectUri, scopes.join(' '), codeChallenge, deviceName, now() + AUTH_CODE_TTL_MS]); return code; } /** Single use: the row is deleted whether or not the exchange succeeds. */ function consumeAuthCode (code) { const d = getDb(); const hash = sha256Hex(code || ''); const row = d.prepare('SELECT * FROM api_auth_codes WHERE code_hash = ?').get([hash]); if (!row) return null; d.prepare('DELETE FROM api_auth_codes WHERE code_hash = ?').run([hash]); if (row.expires_at < now()) return null; return row; } function pkceS256 (verifier) { return crypto.createHash('sha256').update(String(verifier)).digest('base64url'); } // --------------------------------------------------------------------------- // Grants and tokens // --------------------------------------------------------------------------- function issueTokensForGrant (grantId) { const d = getDb(); const accessToken = randomToken('fma_'); const refreshToken = randomToken('fmr_'); const t = now(); d.prepare('DELETE FROM api_access_tokens WHERE expires_at < ?').run([t]); d.prepare('INSERT INTO api_access_tokens (token_hash, grant_id, expires_at) VALUES (?, ?, ?)') .run([sha256Hex(accessToken), grantId, t + ACCESS_TOKEN_TTL_MS]); const g = d.prepare('SELECT refresh_hash FROM api_grants WHERE id = ?').get([grantId]); d.prepare('UPDATE api_grants SET prev_refresh_hash = ?, refresh_hash = ?, refresh_expires_at = ? WHERE id = ?') .run([g ? g.refresh_hash : null, sha256Hex(refreshToken), t + REFRESH_TOKEN_TTL_MS, grantId]); return { accessToken, refreshToken, expiresIn: Math.floor(ACCESS_TOKEN_TTL_MS / 1000) }; } function createOAuthGrant ({ username, clientId, name, scopes }) { const id = 'g_' + crypto.randomBytes(12).toString('base64url'); getDb().prepare('INSERT INTO api_grants (id, username, kind, client_id, name, scopes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)') .run([id, username, 'oauth', clientId, name, scopes.join(' '), now()]); return id; } function createPersonalToken ({ username, name, scopes, expiresAt }) { const id = 'g_' + crypto.randomBytes(12).toString('base64url'); const token = randomToken('fmp_'); getDb().prepare('INSERT INTO api_grants (id, username, kind, client_id, name, scopes, created_at, expires_at, secret_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)') .run([id, username, 'personal', null, name, scopes.join(' '), now(), expiresAt || null, sha256Hex(token)]); return { id, token }; } function getGrant (id) { return getDb().prepare('SELECT * FROM api_grants WHERE id = ?').get([String(id || '')]) || null; } /** * Refresh token rotation with reuse detection: presenting an already rotated * refresh token revokes the whole grant (it was probably stolen). */ function refreshGrant (clientId, refreshToken) { const d = getDb(); const hash = sha256Hex(refreshToken || ''); const g = d.prepare('SELECT * FROM api_grants WHERE refresh_hash = ?').get([hash]); if (!g) { const reused = d.prepare('SELECT id FROM api_grants WHERE prev_refresh_hash = ?').get([hash]); if (reused) revokeGrant(reused.id); return { error: 'invalid_grant' }; } if (g.revoked_at || g.client_id !== clientId || !g.refresh_expires_at || g.refresh_expires_at < now()) { return { error: 'invalid_grant' }; } const client = getClient(g.client_id); if (!client || client.disabled) return { error: 'invalid_grant' }; if (!userExists(g.username)) return { error: 'invalid_grant' }; return { grant: g, tokens: issueTokensForGrant(g.id) }; } function revokeGrant (id) { const d = getDb(); 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') .run([now(), id]); d.prepare('DELETE FROM api_access_tokens WHERE grant_id = ?').run([id]); d.prepare('DELETE FROM api_uploads WHERE grant_id = ?').run([id]); } function revokeAllForUser (username) { const rows = getDb().prepare('SELECT id FROM api_grants WHERE username = ? AND revoked_at IS NULL').all([username]); for (const r of rows) revokeGrant(r.id); } /** Revoke by presenting either the access or the refresh token (RFC 7009). */ function revokeByToken (token) { const d = getDb(); const hash = sha256Hex(token || ''); const at = d.prepare('SELECT grant_id FROM api_access_tokens WHERE token_hash = ?').get([hash]); if (at) { revokeGrant(at.grant_id); return true; } const g = d.prepare('SELECT id FROM api_grants WHERE refresh_hash = ? OR secret_hash = ?').get([hash, hash]); if (g) { revokeGrant(g.id); return true; } return false; } function userExists (username) { return !!getDb().prepare('SELECT 1 AS ok FROM users WHERE username = ?').get([username]); } /** * Resolve a bearer token to { grant, scopes }. Returns null when the token is * unknown, expired or revoked. */ function resolveBearer (token) { const t = String(token || ''); if (!t) return null; const d = getDb(); const hash = sha256Hex(t); let grant = null; if (t.startsWith('fma_')) { const row = d.prepare('SELECT grant_id, expires_at FROM api_access_tokens WHERE token_hash = ?').get([hash]); if (!row || row.expires_at < now()) return null; grant = getGrant(row.grant_id); } else if (t.startsWith('fmp_')) { grant = d.prepare('SELECT * FROM api_grants WHERE secret_hash = ?').get([hash]) || null; if (grant && grant.expires_at && grant.expires_at < now()) return null; } if (!grant || grant.revoked_at) return null; if (grant.kind === 'oauth') { const client = getClient(grant.client_id); if (!client || client.disabled) return null; } return { grant, scopes: String(grant.scopes || '').split(' ').filter(Boolean) }; } function touchGrant (id, ip) { const g = getGrant(id); if (!g) return; const t = now(); if (!g.last_used_at || t - g.last_used_at > 60 * 1000 || g.last_used_ip !== ip) { getDb().prepare('UPDATE api_grants SET last_used_at = ?, last_used_ip = ? WHERE id = ?').run([t, ip, id]); } } function listGrantsForUser (username) { 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 WHERE g.username = ? AND g.revoked_at IS NULL ORDER BY g.created_at DESC`) .all([username]) .map((g) => ({ id: g.id, kind: g.kind, name: g.name, clientId: g.client_id, clientName: g.client_name || null, scopes: String(g.scopes || '').split(' ').filter(Boolean), createdAt: g.created_at, lastUsedAt: g.last_used_at, lastUsedIp: g.last_used_ip, expiresAt: g.expires_at || (g.kind === 'oauth' ? g.refresh_expires_at : null), })); } module.exports = { SCOPES, SCOPE_DESCRIPTIONS, ACCESS_TOKEN_TTL_MS, REFRESH_TOKEN_TTL_MS, initApiSchema, sha256Hex, normalizeScopes, validateRedirectUri, createClient, getClient, listClients, deleteClient, redirectUriAllowed, createAuthCode, consumeAuthCode, pkceS256, createOAuthGrant, createPersonalToken, issueTokensForGrant, refreshGrant, revokeGrant, revokeAllForUser, revokeByToken, resolveBearer, touchGrant, getGrant, listGrantsForUser, userExists, };