import { test, describe } from 'node:test'; import assert from 'node:assert/strict'; import http from 'node:http'; import crypto from 'node:crypto'; import { DbService } from '../src/relay/db-service.js'; import { AuthService } from '../src/relay/auth-service.js'; import { createRelayHttpHandler } from '../src/relay/http-handler.js'; function createInMemoryPool() { const users = new Map(); const stations = new Map(); // key: `${userId}::${pin}` return { users, stations, async query(sql, params = []) { const normalized = sql.replace(/\s+/g, ' ').trim(); if (normalized.startsWith('CREATE TABLE IF NOT EXISTS')) { return { rows: [], rowCount: 0 }; } if (normalized.startsWith('INSERT INTO users')) { const [id, email, name, picture] = params; const now = new Date().toISOString(); const existing = users.get(id); const record = { id, email: email ?? existing?.email ?? null, name: name ?? existing?.name ?? null, picture: picture ?? existing?.picture ?? null, created_at: existing?.created_at || now, updated_at: now }; users.set(id, record); return { rows: [record], rowCount: 1 }; } if (normalized.startsWith('SELECT pin, name, machine_name, created_at, updated_at FROM user_stations')) { const [userId] = params; const rows = Array.from(stations.values()) .filter(s => s.user_id === userId) .sort((a, b) => b.updated_at.localeCompare(a.updated_at)); return { rows, rowCount: rows.length }; } if (normalized.startsWith('INSERT INTO user_stations')) { const [userId, pin, name, machineName] = params; const key = `${userId}::${pin}`; const now = new Date().toISOString(); const existing = stations.get(key); const record = { user_id: userId, pin, name, machine_name: machineName ?? existing?.machine_name ?? null, created_at: existing?.created_at || now, updated_at: now }; stations.set(key, record); return { rows: [record], rowCount: 1 }; } if (normalized.startsWith('UPDATE user_stations SET name =')) { const [name, userId, pin] = params; const key = `${userId}::${pin}`; const existing = stations.get(key); if (!existing) return { rows: [], rowCount: 0 }; existing.name = name; existing.updated_at = new Date().toISOString(); return { rows: [existing], rowCount: 1 }; } if (normalized.startsWith('DELETE FROM user_stations')) { const [userId, pin] = params; const key = `${userId}::${pin}`; const existed = stations.delete(key); return { rows: [], rowCount: existed ? 1 : 0 }; } throw new Error(`Query não suportada no mock: ${normalized}`); } }; } function buildFakeIdToken({ iss, aud, sub, nonce, email, name, picture }) { const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url'); const payload = Buffer.from(JSON.stringify({ iss, aud, sub, nonce, email, name, picture, exp: Math.floor(Date.now() / 1000) + 300 })).toString('base64url'); return `${header}.${payload}.fakesig`; } async function makeHttpRequest(server, method, path, { headers = {}, body } = {}) { const addr = server.address(); return new Promise((resolve, reject) => { const req = http.request({ hostname: '127.0.0.1', port: addr.port, path, method, headers: { Host: `127.0.0.1:${addr.port}`, ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers } }, (res) => { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => { let json = null; try { json = JSON.parse(data); } catch {} resolve({ status: res.statusCode, headers: res.headers, text: data, json }); }); }); req.on('error', reject); if (body) req.write(typeof body === 'string' ? body : JSON.stringify(body)); req.end(); }); } describe('Auth OIDC PKCE & User Stations Persistence', () => { test('DbService isola estações por user_id e executa CRUD completo', async () => { const pool = createInMemoryPool(); const db = new DbService({ pool }); await db.ensureSchema(); await db.upsertUser({ id: 'user-a', email: 'a@example.com', name: 'Alice', picture: 'https://img/a' }); await db.upsertUser({ id: 'user-b', email: 'b@example.com', name: 'Bob', picture: 'https://img/b' }); const created = await db.upsertStation('user-a', { pin: '123456', name: 'Nitro', machineName: 'NITRO-PC' }); assert.equal(created.station.pin, '123456'); assert.equal(created.station.name, 'Nitro'); assert.equal(created.stations.length, 1); // User B não vê nem altera estação de User A const listB = await db.listStations('user-b'); assert.equal(listB.length, 0); const renameByB = await db.renameStation('user-b', '123456', 'Hack'); assert.equal(renameByB, null); const deleteByB = await db.deleteStation('user-b', '123456'); assert.equal(deleteByB.deleted, false); // User A renomeia e remove normalmente const renamedA = await db.renameStation('user-a', '123456', 'Nitro-Casa'); assert.equal(renamedA.station.name, 'Nitro-Casa'); const deletedA = await db.deleteStation('user-a', '123456'); assert.equal(deletedA.deleted, true); assert.equal(deletedA.stations.length, 0); }); test('AuthService executa fluxo PKCE start -> callback -> poll (uso único) e valida JWT', async () => { const pool = createInMemoryPool(); const db = new DbService({ pool }); const issuer = 'https://auth.winicomw.ddnsfree.com/realms/maestri'; const clientId = 'maestri-remote'; let capturedTokenBody = null; const mockFetch = async (url, opts) => { if (url === `${issuer}/protocol/openid-connect/token`) { capturedTokenBody = new URLSearchParams(opts.body); const nonceMatch = authNonce; return { ok: true, status: 200, json: async () => ({ access_token: 'kc-access-123', id_token: buildFakeIdToken({ iss: issuer, aud: clientId, sub: 'google-sub-001', nonce: nonceMatch, email: 'dev@example.com', name: 'Dev User', picture: 'https://img/dev.png' }) }) }; } if (url === `${issuer}/protocol/openid-connect/userinfo`) { return { ok: true, status: 200, json: async () => ({ sub: 'google-sub-001', email: 'dev@example.com', name: 'Dev User', picture: 'https://img/dev.png' }) }; } throw new Error(`Fetch inesperado: ${url}`); }; const auth = new AuthService({ issuer, clientId, clientSecret: 'super-secret', redirectUri: 'https://remote.winicomw.ddnsfree.com/api/auth/callback', jwtSecret: 'test-jwt-secret-32-bytes-minimum!', dbService: db, fetchFn: mockFetch }); const { flowId, authUrl } = auth.startFlow(); assert.ok(flowId); const parsedUrl = new URL(authUrl); assert.equal(parsedUrl.searchParams.get('kc_idp_hint'), 'google'); assert.equal(parsedUrl.searchParams.get('code_challenge_method'), 'S256'); const state = parsedUrl.searchParams.get('state'); const authNonce = parsedUrl.searchParams.get('nonce'); assert.ok(state); assert.ok(authNonce); // Poll antes do callback deve retornar pending assert.deepEqual(auth.pollFlow(flowId), { status: 'pending' }); // Callback troca code + code_verifier const cbResult = await auth.handleCallback({ code: 'auth-code-999', state }); assert.ok(cbResult.token); assert.equal(cbResult.user.id, 'google-sub-001'); assert.equal(cbResult.user.email, 'dev@example.com'); assert.ok(capturedTokenBody.get('code_verifier')); // Verifica code_challenge S256 bate com code_verifier enviado const expectedChallenge = crypto .createHash('sha256') .update(capturedTokenBody.get('code_verifier')) .digest('base64url'); assert.equal(parsedUrl.searchParams.get('code_challenge'), expectedChallenge); // Primeiro poll retorna completed; segundo poll retorna expired (uso único) const poll1 = auth.pollFlow(flowId); assert.equal(poll1.status, 'completed'); assert.equal(poll1.token, cbResult.token); assert.equal(poll1.user.id, 'google-sub-001'); const poll2 = auth.pollFlow(flowId); assert.equal(poll2.status, 'expired'); // Validação do Session JWT const verified = auth.verifyJwt(cbResult.token); assert.equal(verified.sub, 'google-sub-001'); assert.equal(auth.verifyJwt(cbResult.token + 'tamper'), null); }); test('Rotas HTTP /api/auth/* e /api/stations* exigem JWT e isolam usuários', async () => { const pool = createInMemoryPool(); const db = new DbService({ pool }); const issuer = 'https://auth.winicomw.ddnsfree.com/realms/maestri'; const clientId = 'maestri-remote'; let currentNonce = null; const auth = new AuthService({ issuer, clientId, clientSecret: 'secret', redirectUri: 'https://remote.winicomw.ddnsfree.com/api/auth/callback', jwtSecret: 'http-test-jwt-secret-key-123456', dbService: db, fetchFn: async (url) => { if (url.endsWith('/token')) { return { ok: true, status: 200, json: async () => ({ access_token: 'tok', id_token: buildFakeIdToken({ iss: issuer, aud: clientId, sub: 'user-http-1', nonce: currentNonce, email: 'http1@example.com', name: 'HTTP User 1', picture: '' }) }) }; } return { ok: true, status: 200, json: async () => ({ sub: 'user-http-1', email: 'http1@example.com', name: 'HTTP User 1', picture: '' }) }; } }); const handler = createRelayHttpHandler({ authService: auth, dbService: db, publicDir: new URL('../public', import.meta.url).pathname }); const server = http.createServer(handler); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); try { // Sem token -> 401 const unauthMe = await makeHttpRequest(server, 'GET', '/api/auth/me'); assert.equal(unauthMe.status, 401); const unauthStations = await makeHttpRequest(server, 'GET', '/api/stations'); assert.equal(unauthStations.status, 401); // Fluxo completo via HTTP const startRes = await makeHttpRequest(server, 'POST', '/api/auth/start'); assert.equal(startRes.status, 200); assert.ok(startRes.json.flowId); const authUrl = new URL(startRes.json.authUrl); const state = authUrl.searchParams.get('state'); currentNonce = authUrl.searchParams.get('nonce'); const cbRes = await makeHttpRequest(server, 'GET', `/api/auth/callback?code=c1&state=${encodeURIComponent(state)}`); assert.equal(cbRes.status, 200); assert.match(cbRes.text, /MAESTRI_AUTH_SUCCESS/); const pollRes = await makeHttpRequest(server, 'GET', `/api/auth/poll?flowId=${encodeURIComponent(startRes.json.flowId)}`); assert.equal(pollRes.status, 200); assert.equal(pollRes.json.status, 'completed'); const tokenA = pollRes.json.token; // /api/auth/me autenticado const meRes = await makeHttpRequest(server, 'GET', '/api/auth/me', { headers: { Authorization: `Bearer ${tokenA}` } }); assert.equal(meRes.status, 200); assert.equal(meRes.json.user.id, 'user-http-1'); // CRUD estações para User A const postRes = await makeHttpRequest(server, 'POST', '/api/stations', { headers: { Authorization: `Bearer ${tokenA}` }, body: { pin: '654321', name: 'Workstation A', machineName: 'WS-A' } }); assert.equal(postRes.status, 200); assert.equal(postRes.json.stations.length, 1); const patchRes = await makeHttpRequest(server, 'PATCH', '/api/stations/654321', { headers: { Authorization: `Bearer ${tokenA}` }, body: { name: 'WS-A-Editado' } }); assert.equal(patchRes.status, 200); assert.equal(patchRes.json.station.name, 'WS-A-Editado'); // User B com outro JWT válido não vê nem remove estação de User A await db.upsertUser({ id: 'user-http-2', email: 'http2@example.com', name: 'HTTP User 2', picture: '' }); const tokenB = auth.signJwt({ sub: 'user-http-2', email: 'http2@example.com', name: 'HTTP User 2', picture: '' }); const listB = await makeHttpRequest(server, 'GET', '/api/stations', { headers: { Authorization: `Bearer ${tokenB}` } }); assert.equal(listB.status, 200); assert.equal(listB.json.stations.length, 0); const delByB = await makeHttpRequest(server, 'DELETE', '/api/stations/654321', { headers: { Authorization: `Bearer ${tokenB}` } }); assert.equal(delByB.status, 404); const delByA = await makeHttpRequest(server, 'DELETE', '/api/stations/654321', { headers: { Authorization: `Bearer ${tokenA}` } }); assert.equal(delByA.status, 200); assert.equal(delByA.json.ok, true); assert.equal(delByA.json.stations.length, 0); } finally { await new Promise(resolve => server.close(resolve)); } }); });