VNOX-Web/tests/api.test.js

43 lines
2.8 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { request, isSession, safeAvatar, ApiError } from '../src/api.js';
import { messages, detectLanguage } from '../src/i18n.js';
test('catalogs match and never silently fall back to a missing translation',()=>{
assert.deepEqual(Object.keys(messages.ru).sort(),Object.keys(messages.en).sort());
for (const catalog of Object.values(messages)) for (const value of Object.values(catalog)) assert.ok(typeof value==='string' && value.length>0);
});
test('language preference is bounded and follows the OS without storage',()=>{
assert.equal(detectLanguage('en',['ru-RU']),'en');
assert.equal(detectLanguage('bad',['ru-RU']),'ru');
assert.equal(detectLanguage(undefined,['pl-PL']),'en');
assert.equal(detectLanguage('RU',['en-US']),'en');
});
test('API keeps authentication on the same origin and sends CSRF only in header',async()=>{
let observed;
const result=await request('/v1/auth/logout',{method:'POST',csrf:'fixture-csrf',fetcher:async(path,options)=>{
observed={path,options};return {ok:true,status:204};
}});
assert.equal(result,null);
assert.equal(observed.path,'/v1/auth/logout');
assert.equal(observed.options.credentials,'same-origin');
assert.equal(observed.options.cache,'no-store');
assert.equal(observed.options.headers['X-CSRF-Token'],'fixture-csrf');
assert.equal(observed.options.method,'POST');
await assert.rejects(request('https://evil.example/v1/auth/session'),TypeError);
await assert.rejects(request('//evil.example/v1/auth/session'),TypeError);
});
test('API failures expose a generic code and preserve status for expired sessions',async()=>{
await assert.rejects(request('/v1/auth/session',{fetcher:async()=>({ok:false,status:401})}),error=>error instanceof ApiError && error.status===401 && error.message==='request_failed');
});
test('session validation rejects malformed authenticated payloads',()=>{
assert.ok(isSession({authenticated:false}));
assert.ok(isSession({authenticated:true,csrf_token:'fixture',user:{user_id:'fixture',handle:'test',display_name:'Test'}}));
assert.equal(isSession({authenticated:true,user:{}}),false);
assert.equal(isSession({authenticated:'true'}),false);
assert.equal(isSession({authenticated:true,csrf_token:'',user:{user_id:'fixture',handle:'test',display_name:'Test'}}),false);
});
test('avatars allow only uncredentialed HTTPS GitHub image origin',()=>{
assert.equal(safeAvatar('https://avatars.githubusercontent.com/u/1?v=4'),'https://avatars.githubusercontent.com/u/1?v=4');
for (const url of ['javascript:alert(1)','data:image/svg+xml,<svg/>','http://avatars.githubusercontent.com/u/1','https://avatars.githubusercontent.com.evil.example/u/1','https://evil@avatars.githubusercontent.com/u/1','https://avatars.githubusercontent.com:8443/u/1','https://evil.example/u/1',null]) assert.equal(safeAvatar(url),null);
});