A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(desktop): retire node:test suite for local app and network
Hampus887dc46fdc1a
diff --git a/fluxer_desktop/src/common/NativeGatewayTransportEvent.test.mjs b/fluxer_desktop/src/common/NativeGatewayTransportEvent.test.mjsdeleted file mode 100644index 226f8327c..000000000--- a/fluxer_desktop/src/common/NativeGatewayTransportEvent.test.mjs+++ /dev/null@@ -1,184 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import '../main/LocalAppTestSupport.test.mjs';--const {NATIVE_GATEWAY_TRANSPORT_CLOSE_REASON_MAX_BYTES, NativeGatewayTransportEventKind} = await import(- '../../../packages/desktop_ipc/src/GatewayTransportContract.ts'-);-const {parseNativeGatewayTransportEvent} = await import('./NativeGatewayTransportEvent.ts');--const CONNECTION_ID = 'gateway-renderer-3f2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d:9a8b7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d';--function frame(overrides) {- return {- connectionId: CONNECTION_ID,- kind: NativeGatewayTransportEventKind.OPEN,- data: null,- binary: null,- code: null,- reason: null,- wasClean: null,- message: null,- ...overrides,- };-}--function closeFrame(reason) {- return frame({kind: NativeGatewayTransportEventKind.CLOSE, code: 1000, reason, wasClean: true});-}--function rejects(value, fragment) {- assert.throws(- () => parseNativeGatewayTransportEvent(value),- (error) => error.name === 'InvalidNativeGatewayTransportEventError' && error.message.includes(fragment),- `the preload must refuse this event with ${fragment}`,- );-}--describe('reconstructing a native gateway transport event in the preload', () => {- test('each event kind keeps its own payload and nulls the rest', () => {- const opened = parseNativeGatewayTransportEvent(frame({}));- assert.deepEqual(opened, {- connectionId: CONNECTION_ID,- kind: 'open',- data: null,- binary: null,- code: null,- reason: null,- wasClean: null,- message: null,- });-- const message = parseNativeGatewayTransportEvent(- frame({kind: NativeGatewayTransportEventKind.MESSAGE, data: '{"op":11}'}),- );- assert.equal(message.data, '{"op":11}');- assert.equal(message.binary, null);-- const closed = parseNativeGatewayTransportEvent(closeFrame('going away'));- assert.equal(closed.code, 1000);- assert.equal(closed.reason, 'going away');- assert.equal(closed.wasClean, true);-- const errored = parseNativeGatewayTransportEvent(- frame({kind: NativeGatewayTransportEventKind.ERROR, message: 'socket died'}),- );- assert.equal(errored.message, 'socket died');- });-- test('a binary frame is copied out of a view so the sender cannot mutate it afterwards', () => {- const source = new Uint8Array([9, 1, 2, 3, 4, 9]);- const view = source.subarray(1, 5);- const event = parseNativeGatewayTransportEvent(frame({kind: NativeGatewayTransportEventKind.BINARY, binary: view}));- view[0] = 99;- assert.ok(event.binary instanceof ArrayBuffer);- assert.deepEqual(Array.from(new Uint8Array(event.binary)), [1, 2, 3, 4]);- });-- test('a payload that is not exactly the declared shape is refused', () => {- rejects(null, 'plain object');- rejects([], 'plain object');- rejects({...frame({}), extra: 1}, 'plain object');- const missing = frame({});- delete missing.message;- rejects(missing, 'plain object');- rejects(frame({kind: 'sneak'}), 'event kind is unknown');- rejects(frame({connectionId: 'gateway-renderer-nope'}), 'connection id has an invalid format');- rejects(frame({connectionId: 42}), 'connection id must be a string');- });-- test('a field that belongs to another kind must still be null', () => {- rejects(frame({data: 'stowaway'}), 'data must be null');- rejects(- frame({kind: NativeGatewayTransportEventKind.MESSAGE, data: 'hi', message: 'stowaway'}),- 'message must be null',- );- rejects({...closeFrame('bye'), binary: new ArrayBuffer(1)}, 'binary must be null');- });-- test('a close frame validates its code and disposition', () => {- rejects(- frame({kind: NativeGatewayTransportEventKind.CLOSE, code: 1000.5, reason: 'x', wasClean: true}),- 'close code',- );- rejects(frame({kind: NativeGatewayTransportEventKind.CLOSE, code: -1, reason: 'x', wasClean: true}), 'close code');- rejects(- frame({kind: NativeGatewayTransportEventKind.CLOSE, code: 65_536, reason: 'x', wasClean: true}),- 'close code',- );- rejects(- frame({kind: NativeGatewayTransportEventKind.CLOSE, code: 1000, reason: 'x', wasClean: 'yes'}),- 'disposition',- );- });-- test('the size cap counts utf-8 bytes, not utf-16 units', () => {- const cap = NATIVE_GATEWAY_TRANSPORT_CLOSE_REASON_MAX_BYTES;- assert.equal(cap, 123);-- const asciiAtCap = 'a'.repeat(cap);- assert.equal(parseNativeGatewayTransportEvent(closeFrame(asciiAtCap)).reason, asciiAtCap);- rejects(closeFrame('a'.repeat(cap + 1)), 'close reason is too large');-- const threeByteAtCap = '€'.repeat(cap / 3);- assert.equal(parseNativeGatewayTransportEvent(closeFrame(threeByteAtCap)).reason, threeByteAtCap);- rejects(closeFrame('€'.repeat(cap / 3 + 1)), 'close reason is too large');-- const astral = '\u{1f600}'.repeat(30);- assert.equal(new TextEncoder().encode(astral).length, 120);- assert.equal(astral.length, 60);- assert.equal(parseNativeGatewayTransportEvent(closeFrame(astral)).reason, astral);- rejects(closeFrame('\u{1f600}'.repeat(31)), 'close reason is too large');- });-});--function nativeEvent(overrides) {- return {- kind: 'open',- data: null,- binary: null,- code: null,- reason: null,- wasClean: null,- message: null,- ...overrides,- };-}--describe('NativeGatewayTransportEventParser', () => {- test('accepts the addon exact seven field shape and normalises binary to ArrayBuffer', () => {- const parsed = parseNativeGatewayTransportEvent(- nativeEvent({kind: 'binary', binary: Buffer.from([1, 2, 3])}),- 'id',- );- assert.equal(parsed.kind, 'binary');- assert.deepEqual([...new Uint8Array(parsed.binary)], [1, 2, 3]);- assert.equal(parsed.data, null);- });-- test('rejects an inapplicable field that is not null', () => {- assert.throws(- () => parseNativeGatewayTransportEvent(nativeEvent({kind: 'open', message: ''}), 'id'),- /message must be null/u,- );- assert.throws(- () => parseNativeGatewayTransportEvent(nativeEvent({kind: 'open', data: undefined}), 'id'),- /must be a plain object with exactly the declared keys|data must be null/u,- );- });-- test('rejects a close event with an out of range code', () => {- assert.throws(- () =>- parseNativeGatewayTransportEvent(nativeEvent({kind: 'close', code: 70_000, reason: '', wasClean: true}), 'id'),- /unsigned 16-bit integer/u,- );- });-- test('rejects a prototype-polluted record', () => {- const hostile = Object.create({kind: 'open'});- assert.throws(() => parseNativeGatewayTransportEvent(hostile, 'id'), /plain object/u);- });-});diff --git a/fluxer_desktop/src/main/DesktopDebugInfo.test.mjs b/fluxer_desktop/src/main/DesktopDebugInfo.test.mjsdeleted file mode 100644index 798281f5c..000000000--- a/fluxer_desktop/src/main/DesktopDebugInfo.test.mjs+++ /dev/null@@ -1,152 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import vm from 'node:vm';-import {loadTsModule} from './fixtures/TsModuleLoader.mjs';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const sourcePath = fileURLToPath(new URL('./DesktopDebugInfo.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadDesktopDebugInfo(options = {}) {- function requireStub(specifier) {- if (specifier === 'electron') {- return {- app: {commandLine: {hasSwitch: () => false}, getPath: () => '', getLocale: () => 'en-US', isReady: () => true},- };- }- if (specifier === 'electron-log') {- return {info() {}, transports: {file: {getFile: () => null}}};- }- if (specifier === '@electron/common/Constants') {- return {DESKTOP_APP_URL: 'fluxer-app://app/'};- }- if (specifier === '@electron/common/DesktopConfig') {- return {- getDesktopTroubleshootingSettings: () => options.troubleshooting ?? {disableHardwareAcceleration: false},- getDesktopWindowBehaviorSettings: () => ({}),- };- }- if (specifier === '@electron/common/UserDataPath') {- return {isPortableMode: () => false};- }- if (specifier === '@electron/main/ChromiumRuntime') {- return {hasEnabledBlinkFeature: () => false, MIDDLE_CLICK_AUTOSCROLL_BLINK_FEATURE: 'feature'};- }- if (specifier === '@electron/main/DesktopAccountStoreTelemetry') {- return {formatDesktopAccountStoreTelemetry: () => '', readDesktopAccountStoreTelemetry: () => ({})};- }- if (specifier === '@electron/main/DesktopAppStoreHealth') {- return {readDesktopAppStoreState: () => null};- }- if (specifier === '@electron/main/PlatformInfo') {- return {getDesktopInfo: async () => ({})};- }- if (specifier === '@electron/main/LaunchOptions' || specifier === '@fluxer/desktop_ipc/src/DesktopLabels') {- return loadTsModule(specifier);- }- return require(specifier);- }-- const module = {exports: {}};- const context = vm.createContext({- require: requireStub,- module,- exports: module.exports,- process: {- ...process,- env: {},- argv: options.argv ?? [],- platform: options.platform ?? process.platform,- },- console,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--describe('DesktopDebugInfo effective troubleshooting settings', () => {- test('reports hardware acceleration disabled when a launch flag disabled it', () => {- const {resolveEffectiveDesktopTroubleshootingSettings} = loadDesktopDebugInfo();-- for (const flag of ['--fluxer-disable-gpu', '--fluxer-disable-hardware-acceleration', '--fluxer-safe-mode']) {- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings({disableHardwareAcceleration: false}, [flag], 'win32')- .disableHardwareAcceleration,- true,- flag,- );- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings({disableHardwareAcceleration: false}, [flag], 'linux')- .disableHardwareAcceleration,- true,- flag,- );- }- });-- test('honours the persisted setting when no launch flag disabled it', () => {- const {resolveEffectiveDesktopTroubleshootingSettings} = loadDesktopDebugInfo();-- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings({disableHardwareAcceleration: true}, [], 'win32')- .disableHardwareAcceleration,- true,- );- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings(- {disableHardwareAcceleration: false},- ['--fluxer-devtools'],- 'linux',- ).disableHardwareAcceleration,- false,- );- });-- test('reports hardware acceleration enabled on macOS', () => {- const {resolveEffectiveDesktopTroubleshootingSettings} = loadDesktopDebugInfo();-- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings(- {disableHardwareAcceleration: true},- ['--fluxer-safe-mode'],- 'darwin',- ).disableHardwareAcceleration,- false,- );- });-- test('keeps the launch answer when the persisted setting changes without a restart', () => {- const troubleshooting = {disableHardwareAcceleration: true};- const {getLaunchDesktopTroubleshootingSettings} = loadDesktopDebugInfo({- troubleshooting,- argv: [],- platform: 'win32',- });-- assert.equal(getLaunchDesktopTroubleshootingSettings().disableHardwareAcceleration, true);- troubleshooting.disableHardwareAcceleration = false;- assert.equal(getLaunchDesktopTroubleshootingSettings().disableHardwareAcceleration, true);- });-- test('answers the launch flag when nothing is persisted', () => {- const {getLaunchDesktopTroubleshootingSettings} = loadDesktopDebugInfo({- argv: ['--fluxer-disable-hardware-acceleration'],- platform: 'linux',- });-- assert.equal(getLaunchDesktopTroubleshootingSettings().disableHardwareAcceleration, true);- });-});diff --git a/fluxer_desktop/src/main/DesktopHappyEyeballs.test.mjs b/fluxer_desktop/src/main/DesktopHappyEyeballs.test.mjsdeleted file mode 100644index 7ec4a16ec..000000000--- a/fluxer_desktop/src/main/DesktopHappyEyeballs.test.mjs+++ /dev/null@@ -1,55 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import net from 'node:net';-import {describe, test} from 'node:test';--const {connectToFirstAnsweringAddress} = await import('./DesktopHappyEyeballs.ts');--function race(addresses, port, options) {- return new Promise((resolve) => {- connectToFirstAnsweringAddress(addresses, port, options, (error, socket) => resolve({error, socket}));- });-}--describe('DesktopHappyEyeballs', () => {- test('a slow first address keeps racing after the next one fails fast', async () => {- const server = net.createServer((socket) => socket.end());- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- const {port} = server.address();- const dial = (options) => {- if (options.host !== '127.0.0.1') {- return net.connect(options);- }- const socket = new net.Socket();- setTimeout(() => socket.connect(options), 150);- return socket;- };- try {- const {error, socket} = await race(- [- {address: '127.0.0.1', family: 4},- {address: '::1', family: 6},- ],- port,- {attemptDelayMs: 20, dial},- );- assert.equal(error, null, 'a connect slower than the attempt delay must not be abandoned');- assert.equal(socket.remoteAddress, '127.0.0.1');- socket.destroy();- } finally {- server.close();- }- });-- test('when every address fails the error names each attempt', async () => {- const server = net.createServer();- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- const {port} = server.address();- await new Promise((resolve) => server.close(resolve));- const {error, socket} = await race([{address: '127.0.0.1', family: 4}], port, {});- assert.equal(socket, null);- assert.equal(error.code, 'ECONNREFUSED');- assert.match(error.message, /ECONNREFUSED 127\.0\.0\.1/);- });-});diff --git a/fluxer_desktop/src/main/DesktopOutboundHTTP.test.mjs b/fluxer_desktop/src/main/DesktopOutboundHTTP.test.mjsdeleted file mode 100644index 65b7a02f2..000000000--- a/fluxer_desktop/src/main/DesktopOutboundHTTP.test.mjs+++ /dev/null@@ -1,1056 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import http from 'node:http';-import {Readable} from 'node:stream';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopOriginTrust, DesktopOutboundHTTP, createPinnedHostLookup, readBoundedMessage} = await import(- './DesktopOutboundHTTP.ts'-);-const {DesktopSelectedInstanceClient} = await import('./SelectedInstanceFetch.ts');-const {getLaunchInstanceEndpointOverride} = await import('../common/DesktopConfig.ts');--const PNG_BYTES = Buffer.from('89504e470d0a1a0a', 'hex');--function stubResolver(table) {- return async (hostname) => {- const key = hostname.endsWith('.') ? hostname.slice(0, -1) : hostname;- const addresses = table[key];- if (addresses == null) {- throw new Error(`no stubbed address for ${hostname}`);- }- return addresses;- };-}--async function startServer(routes) {- const requested = [];- const server = http.createServer((request, response) => {- const url = new URL(request.url, 'http://127.0.0.1');- requested.push(url.pathname);- const route = routes[url.pathname];- if (route == null) {- response.writeHead(404);- response.end();- return;- }- route(request, response);- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- return {port: server.address().port, requested, server};-}--function sendImage(response, contentType, body, headers = {}) {- response.writeHead(200, {'content-type': contentType, ...headers});- response.end(body);-}--describe('DesktopOutboundHTTP origin anchoring', () => {- test('a publicly reachable anchor refuses an advertised origin that resolves privately', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'media.internal': ['10.0.0.1'], 'public.example': ['93.184.216.34']}),- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://public.example',- origins: ['https://media.internal'],- });- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: 'https://media.internal',- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 500,- url: 'https://media.internal/avatars/1.webp',- }),- /cannot authorize the privately resolving origin/,- );- outboundHTTP.cleanup();- });-- test('an anchor that cannot resolve registers under the remembered requirement', async () => {- let online = false;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async (hostname) => {- if (!online) {- throw Object.assign(new Error(`getaddrinfo EAI_AGAIN ${hostname}`), {- code: 'EAI_AGAIN',- syscall: 'getaddrinfo',- });- }- return hostname.startsWith('media.internal') ? ['10.0.0.1'] : ['93.184.216.34'];- },- });- const registration = {anchorOrigin: 'https://public.example', origins: ['https://media.internal']};- await assert.rejects(outboundHTTP.registerAnchoredOrigins(registration), {code: 'EAI_AGAIN'});- assert.equal(outboundHTTP.isRegisteredOrigin('https://public.example'), false);- assert.equal(- await outboundHTTP.registerAnchoredOrigins({...registration, unresolvedAnchorRequirement: 'public'}),- 'public',- );- assert.equal(outboundHTTP.isRegisteredOrigin('https://media.internal'), true);- online = true;- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: 'https://media.internal',- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 500,- url: 'https://media.internal/avatars/1.webp',- }),- /cannot authorize the privately resolving origin/,- );- assert.equal(await outboundHTTP.registerAnchoredOrigins(registration), 'public');- outboundHTTP.cleanup();- });-- test('an anchor that resolves to no usable address never falls back to the remembered requirement', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'unusable.example': ['not-an-address']}),- });- await assert.rejects(- outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://unusable.example',- origins: [],- unresolvedAnchorRequirement: 'any',- }),- {name: 'DesktopOutboundHTTPEmptyResolutionError'},- );- assert.equal(outboundHTTP.isRegisteredOrigin('https://unusable.example'), false);- outboundHTTP.cleanup();- });-- test('a split-horizon anchor resolving to private and public addresses is anchored on its private address', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'chat.home.example': ['2606:4700:4700::1111', '192.168.1.20']}),- });- assert.equal(- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: 'http://chat.home.example', origins: []}),- 'any',- );- assert.equal(await outboundHTTP.requireCleartextTransportAddress('http://chat.home.example'), '192.168.1.20');- outboundHTTP.cleanup();- });-- test('a publicly reachable anchor refuses an advertised origin that also resolves privately', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({- 'public.example': ['93.184.216.34'],- 'media.mixed.example': ['93.184.216.35', '10.0.0.1'],- }),- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://public.example',- origins: ['https://media.mixed.example'],- });- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: 'https://media.mixed.example',- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 500,- url: 'https://media.mixed.example/avatars/1.webp',- }),- /cannot authorize the privately resolving origin/,- );- outboundHTTP.cleanup();- });-- test('only cleartext origins anchored on a private address are offered to the page policy', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({- 'lan.example': ['192.168.1.20'],- 'public.example': ['93.184.216.34'],- }),- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'http://lan.example:48090',- origins: ['http://lan.example:48091', 'https://lan.example'],- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://public.example',- origins: ['http://public.example'],- });- assert.deepEqual(outboundHTTP.registeredCleartextOrigins(), [- 'http://lan.example:48090',- 'http://lan.example:48091',- ]);- outboundHTTP.cleanup();- });-- test('a request whose signal already aborted is refused instead of sent', async () => {- const seen = [];- const {port, server} = await startServer({- '/ok': (request, response) => {- seen.push(request.url);- sendImage(response, 'image/png', PNG_BYTES);- },- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'lan.example': ['127.0.0.1']}),- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: `http://lan.example:${port}`,- origins: [`http://lan.example:${port}`],- });- const controller = new AbortController();- controller.abort();-- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: `http://lan.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: controller.signal,- timeoutMs: 2000,- url: `http://lan.example:${port}/ok`,- }),- );-- assert.deepEqual(seen, []);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a LAN self-hosted instance whose anchor resolves privately is allowed', async () => {- const {port, server} = await startServer({- '/media/ok': (_request, response) => sendImage(response, 'image/png', PNG_BYTES),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'lan.example': ['127.0.0.1'], 'media.lan.example': ['127.0.0.1']}),- });- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: `http://lan.example:${port}`,- origins: [`http://media.lan.example:${port}`],- });- const message = await outboundHTTP.request({- body: null,- expectedOrigin: `http://media.lan.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 2000,- url: `http://media.lan.example:${port}/media/ok`,- });- assert.equal(message.status, 200);- message.message.resume();- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a streamed request body reaches the server for every method that carries one', async () => {- const received = [];- const {port, server} = await startServer({- '/api/v1/oauth2/applications/1': (request, response) => {- let body = '';- request.setEncoding('utf8');- request.on('data', (chunk) => {- body += chunk;- });- request.on('end', () => {- received.push({body, method: request.method, sudo: request.headers['x-fluxer-sudo-mode-jwt'] ?? null});- response.writeHead(204, {'x-fluxer-sudo-mode-jwt': 'granted'});- response.end();- });- },- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'lan.example': ['127.0.0.1']}),- });- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: `http://lan.example:${port}`, origins: []});- const payload = JSON.stringify({mfa_method: 'totp', mfa_code: '123456'});- for (const method of ['DELETE', 'POST', 'PATCH', 'PUT']) {- const message = await outboundHTTP.request({- body: Readable.toWeb(Readable.from([Buffer.from(payload)])),- expectedOrigin: `http://lan.example:${port}`,- headers: {'content-type': 'application/json', 'x-fluxer-sudo-mode-jwt': 'previous'},- method,- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 2000,- url: `http://lan.example:${port}/api/v1/oauth2/applications/1`,- });- assert.equal(message.status, 204);- assert.equal(message.headers['x-fluxer-sudo-mode-jwt'], 'granted');- message.message.resume();- }- assert.deepEqual(- received.map((entry) => entry.method),- ['DELETE', 'POST', 'PATCH', 'PUT'],- );- for (const entry of received) {- assert.equal(entry.body, payload);- assert.equal(entry.sudo, 'previous');- }- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a private literal anchor binds and registers without a public requirement', async () => {- const outboundHTTP = new DesktopOutboundHTTP({resolveHostAddresses: stubResolver({})});- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: 'http://192.168.1.10', origins: []});- assert.equal(outboundHTTP.isRegisteredOrigin('http://192.168.1.10'), true);- outboundHTTP.cleanup();- });-- test('http is refused for a publicly resolving origin and accepted for a loopback one', async () => {- const {port, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'example.com': ['93.184.216.34'], localhost: ['127.0.0.1']}),- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- await assert.rejects(- client.fetch({expectedOrigin: 'http://example.com', timeoutMs: 500, url: 'http://example.com/ping'}),- /requires https for the publicly routable origin/,- );- const loopback = await client.fetch({- expectedOrigin: `http://localhost:${port}`,- timeoutMs: 2000,- url: `http://localhost:${port}/ping`,- });- assert.equal(loopback.status, 200);- const literal = await client.fetch({- expectedOrigin: `http://127.0.0.1:${port}`,- timeoutMs: 2000,- url: `http://127.0.0.1:${port}/ping`,- });- assert.equal(literal.status, 200);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('cleartext transport addresses are pinned for loopback and LAN origins and refused for public ones', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({- 'gateway.example.com': ['93.184.216.34'],- 'nas.lan': ['192.168.1.20'],- localhost: ['::1', '127.0.0.1'],- }),- });- assert.equal(await outboundHTTP.requireCleartextTransportAddress('http://localhost:8088'), '127.0.0.1');- assert.equal(await outboundHTTP.requireCleartextTransportAddress('http://nas.lan'), '192.168.1.20');- assert.equal(await outboundHTTP.requireCleartextTransportAddress('http://10.0.0.5:8080'), '10.0.0.5');- await assert.rejects(- outboundHTTP.requireCleartextTransportAddress('http://gateway.example.com'),- /requires https for the publicly routable origin/,- );- await assert.rejects(- outboundHTTP.requireCleartextTransportAddress('http://93.184.216.34'),- /requires https for the publicly routable origin/,- );- outboundHTTP.cleanup();- });-- test('a loopback host resolving to IPv6 first still reaches an IPv4 only server', async () => {- const {port, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => ['::1', '127.0.0.1'],- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- const response = await client.fetch({- expectedOrigin: `http://localdev.example:${port}`,- timeoutMs: 2000,- url: `http://localdev.example:${port}/ping`,- });- assert.equal(- response.status,- 200,- 'macOS returns ::1 first for a loopback name and dev servers commonly bind IPv4 only, so pinning the first record makes every request fail with ECONNREFUSED',- );- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('the pinned address survives a resolver that rebinds after the allow-list check', async () => {- const {port, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- let rebound = false;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => {- if (rebound) {- return ['203.0.113.7'];- }- return ['127.0.0.1'];- },- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- const first = await client.fetch({- expectedOrigin: `http://rebind.example:${port}`,- timeoutMs: 2000,- url: `http://rebind.example:${port}/ping`,- });- assert.equal(first.status, 200);- rebound = true;- const second = await client.fetch({- expectedOrigin: `http://rebind.example:${port}`,- timeoutMs: 2000,- url: `http://rebind.example:${port}/ping`,- });- assert.equal(second.status, 200);- assert.equal(second.body.toString('utf8'), 'ok');- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a pinned address that stops answering is resolved again instead of staying pinned for the process lifetime', async () => {- const {port, server} = await startServer({});- await new Promise((resolve) => server.close(resolve));- let resolutions = 0;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => {- resolutions += 1;- return ['127.0.0.1'];- },- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- const request = {- expectedOrigin: `http://moved.example:${port}`,- timeoutMs: 2000,- url: `http://moved.example:${port}/ping`,- };- await assert.rejects(client.fetch(request), /ECONNREFUSED/);- assert.equal(resolutions, 1);- const revived = http.createServer((_request, response) => sendImage(response, 'text/plain', 'ok'));- await new Promise((resolve) => revived.listen(port, '127.0.0.1', resolve));- try {- const response = await client.fetch(request);- assert.equal(response.status, 200);- assert.equal(- resolutions,- 2,- 'an address that stopped answering leaves the origin unreachable until the app restarts unless the failed binding is released',- );- outboundHTTP.cleanup();- } finally {- revived.close();- }- });-- test('a released cleartext binding that re-resolves to a public address never sends cleartext there', async () => {- const {port, server} = await startServer({});- await new Promise((resolve) => server.close(resolve));- let rebound = false;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => {- if (rebound) {- return ['93.184.216.34'];- }- return ['127.0.0.1'];- },- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- const request = {- expectedOrigin: `http://scope.example:${port}`,- timeoutMs: 2000,- url: `http://scope.example:${port}/ping`,- };- await assert.rejects(client.fetch(request), /ECONNREFUSED/);- rebound = true;- await assert.rejects(client.fetch(request), /requires https for the publicly routable origin/);- outboundHTTP.cleanup();- });-- test('a split-horizon origin that moves from its LAN address to a public one is resolved again instead of failing until restart', async () => {- const {port, server} = await startServer({});- await new Promise((resolve) => server.close(resolve));- let rebound = false;- let resolutions = 0;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => {- resolutions += 1;- return rebound ? ['93.184.216.34'] : ['127.0.0.1'];- },- });- const request = (signal) => ({- body: null,- expectedOrigin: `https://home.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.BOUND,- signal,- timeoutMs: 2000,- url: `https://home.example:${port}/ping`,- });- await assert.rejects(outboundHTTP.request(request(null)), /ECONNREFUSED/);- rebound = true;- const left = new AbortController();- left.abort();- await assert.rejects(outboundHTTP.request(request(left.signal)), /was aborted by its caller/);- assert.equal(resolutions, 2);- outboundHTTP.cleanup();- });-- test('an address that swallows connections is released when the request gives up before connecting', async () => {- let resolutions = 0;- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => {- resolutions += 1;- return ['10.255.255.1'];- },- });- const request = {- body: null,- expectedOrigin: 'http://blackhole.example:9',- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.BOUND,- signal: null,- timeoutMs: 200,- url: 'http://blackhole.example:9/ping',- };- await assert.rejects(outboundHTTP.request(request));- await assert.rejects(outboundHTTP.request(request));- assert.equal(- resolutions,- 2,- 'a binding whose address never answers stays pinned for the process lifetime when a timeout does not release it',- );- outboundHTTP.cleanup();- });-- test('a chosen origin resolving to both public and non-public addresses is reached on its non-public address', async () => {- const {port, requested, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'mixed.example': ['93.184.216.34', '127.0.0.1']}),- });- const response = await outboundHTTP.request({- body: null,- expectedOrigin: `http://mixed.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.BOUND,- signal: null,- timeoutMs: 2000,- url: `http://mixed.example:${port}/ping`,- });- response.message.resume();- assert.equal(response.status, 200);- assert.deepEqual(requested, ['/ping']);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a target on a different port than its declared origin is refused before any connection', async () => {- const declared = await startServer({'/ping': (_request, response) => sendImage(response, 'text/plain', 'ok')});- const other = await startServer({'/steal': (_request, response) => sendImage(response, 'text/plain', 'stolen')});- try {- const outboundHTTP = new DesktopOutboundHTTP({resolveHostAddresses: stubResolver({})});- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: `http://127.0.0.1:${declared.port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.BOUND,- signal: null,- timeoutMs: 2000,- url: `http://127.0.0.1:${other.port}/steal`,- }),- /not a canonical URL under its declared origin/,- );- assert.deepEqual(other.requested, [], 'a target outside the declared origin must never be contacted');- assert.deepEqual(declared.requested, []);- outboundHTTP.cleanup();- } finally {- declared.server.close();- other.server.close();- }- });-- test('a keepalive socket the peer closed between requests is retried exactly once', async () => {- let seen = 0;- const server = http.createServer((request, response) => {- seen += 1;- if (seen === 2) {- request.socket.destroy();- return;- }- response.writeHead(200, {'content-type': 'text/plain'});- response.end(`attempt-${seen}`);- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- const {port} = server.address();- try {- const outboundHTTP = new DesktopOutboundHTTP({resolveHostAddresses: stubResolver({})});- const send = () =>- outboundHTTP.request({- body: null,- expectedOrigin: `http://127.0.0.1:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.BOUND,- signal: null,- timeoutMs: 5000,- url: `http://127.0.0.1:${port}/ping`,- });- const readBody = async (message) =>- (- await readBoundedMessage({- declaredBytes: null,- description: 'test body',- maxBytes: 1024,- maxChunks: 16,- message: message.message,- })- ).toString('utf8');-- assert.equal(await readBody(await send()), 'attempt-1');- assert.equal(await readBody(await send()), 'attempt-3');- assert.equal(seen, 3);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a stale reused socket is not replayed for a request whose body cannot be replayed', async () => {- let seen = 0;- const server = http.createServer((request, response) => {- seen += 1;- if (seen === 2) {- request.socket.destroy();- return;- }- request.resume();- request.on('end', () => {- response.writeHead(200, {'content-type': 'text/plain'});- response.end(`attempt-${seen}`);- });- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- const {port} = server.address();- try {- const outboundHTTP = new DesktopOutboundHTTP({resolveHostAddresses: stubResolver({})});- const send = (body) =>- outboundHTTP.request({- body,- expectedOrigin: `http://127.0.0.1:${port}`,- headers: {'content-type': 'text/plain'},- method: 'PUT',- originTrust: DesktopOriginTrust.BOUND,- signal: null,- timeoutMs: 5000,- url: `http://127.0.0.1:${port}/upload`,- });- const streamBody = () => Readable.toWeb(Readable.from([Buffer.from('payload')]));-- const first = await send(streamBody());- await readBoundedMessage({- declaredBytes: null,- description: 'test body',- maxBytes: 1024,- maxChunks: 16,- message: first.message,- });- await assert.rejects(send(streamBody()), (error) => error.code === 'ECONNRESET');- assert.equal(seen, 2, 'a streamed body must never be replayed onto a fresh socket');- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('the pinned lookup answers after its caller returns', async () => {- const lookup = createPinnedHostLookup('pinned.example', {address: '127.0.0.1', family: 4});- const order = [];- const answered = new Promise((resolve) =>- lookup('pinned.example', {all: true}, (error, addresses) => {- order.push('answered');- resolve({addresses, error});- }),- );- order.push('returned');- const {addresses, error} = await answered;- assert.deepEqual(order, ['returned', 'answered']);- assert.equal(error, null);- assert.deepEqual(addresses, [{address: '127.0.0.1', family: 4}]);- });-- test('a pinned address with no route fails the request instead of the process', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'unrouted.example': ['255.255.255.255']}),- });- const uncaught = [];- const onUncaught = (error) => uncaught.push(error);- process.on('uncaughtException', onUncaught);- try {- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: 'https://unrouted.example', origins: []});- await assert.rejects(- outboundHTTP.request({- body: null,- expectedOrigin: 'https://unrouted.example',- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 2000,- url: 'https://unrouted.example/',- }),- (error) => typeof error.code === 'string' && error.syscall === 'connect',- );- await new Promise((resolve) => setImmediate(resolve));- assert.deepEqual(uncaught, []);- } finally {- process.off('uncaughtException', onUncaught);- outboundHTTP.cleanup();- }- });-- test('the pinned lookup offers every validated address for happy eyeballs', async () => {- const lookup = createPinnedHostLookup('dual.example', [- {address: '2606:4700:4700::1111', family: 6},- {address: '93.184.216.34', family: 4},- ]);- const all = await new Promise((resolve) =>- lookup('dual.example', {all: true}, (error, addresses) => resolve({addresses, error})),- );- assert.equal(all.error, null);- assert.deepEqual(all.addresses, [- {address: '2606:4700:4700::1111', family: 6},- {address: '93.184.216.34', family: 4},- ]);- const single = await new Promise((resolve) =>- lookup('dual.example', {}, (error, address, family) => resolve({address, error, family})),- );- assert.equal(single.address, '2606:4700:4700::1111');- assert.equal(single.family, 6);- });-- test('a registered origin whose IPv6 address refuses connects over IPv4 without waiting', async () => {- const {port, requested, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'dual.example': ['::1', '127.0.0.1']}),- });- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: `http://dual.example:${port}`, origins: []});- const startedAt = Date.now();- const response = await outboundHTTP.request({- body: null,- expectedOrigin: `http://dual.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 2000,- url: `http://dual.example:${port}/ping`,- });- response.message.resume();- assert.equal(response.status, 200, 'the refused IPv6 address must fall back to the IPv4 one like Chromium does');- assert.ok(Date.now() - startedAt < 1000);- assert.deepEqual(requested, ['/ping']);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a registered origin whose first address never answers is reached on the next one', async () => {- const {port, requested, server} = await startServer({- '/ping': (_request, response) => sendImage(response, 'text/plain', 'ok'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'multi.example': ['127.0.0.2', '127.0.0.1']}),- });- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: `http://multi.example:${port}`, origins: []});- const startedAt = Date.now();- const response = await outboundHTTP.request({- body: null,- expectedOrigin: `http://multi.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 3000,- url: `http://multi.example:${port}/ping`,- });- response.message.resume();- assert.equal(response.status, 200, 'a dead first address must not stop the connection from trying the others');- assert.ok(Date.now() - startedAt < 1500);- assert.deepEqual(requested, ['/ping']);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a public requirement still refuses an answer that includes a private address', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'mixed.example': ['2606:4700:4700::1111', '127.0.0.1']}),- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- await assert.rejects(- client.fetch({expectedOrigin: 'https://mixed.example', timeoutMs: 2000, url: 'https://mixed.example/ping'}),- );- outboundHTTP.cleanup();- });-- test('the pinned lookup refuses a hostname it was not created for', async () => {- const lookup = createPinnedHostLookup('pinned.example', {address: '127.0.0.1', family: 4});- const mismatch = await new Promise((resolve) => lookup('rebound.example', {}, resolve));- assert.equal(mismatch.name, 'PinnedLookupHostnameMismatchError');- const match = await new Promise((resolve) =>- lookup('PINNED.example.', {}, (error, address) => resolve({address, error})),- );- assert.equal(match.error, null);- assert.equal(match.address, '127.0.0.1');- });-});--describe('DesktopSelectedInstanceClient', () => {- test('a redirect on the instance path is refused instead of followed', async () => {- const {port, requested, server} = await startServer({- '/api/v1/auth/login': (_request, response) => {- response.writeHead(302, {location: '/api/v1/elsewhere'});- response.end();- },- '/api/v1/elsewhere': (_request, response) => sendImage(response, 'text/plain', 'followed'),- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'self.example': ['127.0.0.1']}),- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- await assert.rejects(- client.fetch({- expectedOrigin: `http://self.example:${port}`,- method: 'POST',- timeoutMs: 2000,- url: `http://self.example:${port}/api/v1/auth/login`,- }),- /was answered with an HTTP 302 redirect, which is never followed/,- );- assert.deepEqual(requested, ['/api/v1/auth/login']);- outboundHTTP.cleanup();- } finally {- server.close();- }- });-- test('a foreign-origin URL throws', async () => {- const outboundHTTP = new DesktopOutboundHTTP({resolveHostAddresses: stubResolver({'self.example': ['127.0.0.1']})});- const client = new DesktopSelectedInstanceClient(outboundHTTP);- await assert.rejects(- client.fetch({- expectedOrigin: 'http://self.example',- timeoutMs: 500,- url: 'http://other.example/api/v1/users/@me',- }),- /is not a canonical URL under its declared origin/,- );- outboundHTTP.cleanup();- });-- test('a response beyond the one mebibyte bound aborts', async () => {- const {port, server} = await startServer({- '/big': (_request, response) => {- response.writeHead(200, {'content-type': 'application/json'});- const chunk = Buffer.alloc(256 * 1024, 0x61);- for (let index = 0; index < 8; index += 1) {- response.write(chunk);- }- response.end();- },- });- try {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: stubResolver({'self.example': ['127.0.0.1']}),- });- const client = new DesktopSelectedInstanceClient(outboundHTTP);- await assert.rejects(- client.fetch({- expectedOrigin: `http://self.example:${port}`,- timeoutMs: 5000,- url: `http://self.example:${port}/big`,- }),- /Instance response exceeds 1048576 bytes/,- );- outboundHTTP.cleanup();- } finally {- server.close();- }- });-});--describe('DesktopOutboundHTTP system proxy routes', () => {- function proxiedOutboundHTTP() {- const sent = [];- const resolved = [];- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async (hostname) => {- resolved.push(hostname);- throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), {syscall: 'getaddrinfo'});- },- resolveProxy: async (url) =>- url.startsWith('https://direct.example') ? 'DIRECT' : 'PROXY 127.0.0.1:7890; DIRECT',- sendThroughSession: async (request) => {- sent.push({method: request.method, url: request.url.href, headers: request.headers});- return {- headers: {'content-type': 'image/png'},- message: Readable.from([PNG_BYTES]),- status: 200,- statusText: 'OK',- };- },- });- return {outboundHTTP, resolved, sent};- }-- test('an instance behind the system proxy is anchored and fetched without a local lookup', async () => {- const {outboundHTTP, resolved, sent} = proxiedOutboundHTTP();- const requirement = await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://api.blocked.example',- origins: ['https://media.blocked.example'],- });- assert.equal(requirement, 'public');- const message = await outboundHTTP.request({- body: null,- expectedOrigin: 'https://media.blocked.example',- headers: {Accept: 'image/png'},- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 500,- url: 'https://media.blocked.example/avatar.png',- });- assert.deepEqual(- await readBoundedMessage({- declaredBytes: null,- description: 'proxied',- maxBytes: 64,- maxChunks: 4,- message: message.message,- }),- PNG_BYTES,- );- assert.deepEqual(resolved, []);- assert.deepEqual(sent, [- {method: 'GET', url: 'https://media.blocked.example/avatar.png', headers: {Accept: 'image/png'}},- ]);- outboundHTTP.cleanup();- });-- test('a proxied download goes through the session and a direct one keeps the pinned lookup', async () => {- const {outboundHTTP, resolved, sent} = proxiedOutboundHTTP();- const message = await outboundHTTP.get({- context: 'test',- timeoutMs: 500,- url: new URL('https://cdn.blocked.example/icon.png'),- });- message.message.resume();- await assert.rejects(- outboundHTTP.get({context: 'test', timeoutMs: 500, url: new URL('https://direct.example/icon.png')}),- /could not be reached/,- );- assert.deepEqual(- sent.map((entry) => entry.url),- ['https://cdn.blocked.example/icon.png'],- );- assert.deepEqual(resolved, ['direct.example']);- outboundHTTP.cleanup();- });-- test('a proxied route keeps the cleartext and private address rules', async () => {- const {outboundHTTP, sent} = proxiedOutboundHTTP();- await outboundHTTP.registerAnchoredOrigins({- anchorOrigin: 'https://api.blocked.example',- origins: ['http://10.0.0.1'],- });- const request = (url, originTrust = DesktopOriginTrust.BOUND) => ({- body: null,- expectedOrigin: new URL(url).origin,- headers: null,- method: 'GET',- originTrust,- signal: null,- timeoutMs: 500,- url,- });- await assert.rejects(outboundHTTP.request(request('http://plain.blocked.example/x')), /requires https/);- await assert.rejects(- outboundHTTP.request(request('http://10.0.0.1/x', DesktopOriginTrust.REGISTERED)),- /cannot authorize the privately resolving origin/,- );- await assert.rejects(- outboundHTTP.get({context: 'test', timeoutMs: 500, url: new URL('https://10.0.0.1/x')}),- /could not be reached/,- );- assert.deepEqual(sent, []);- outboundHTTP.cleanup();- });-});--describe('desktop instance launch surfaces', () => {- test('--fluxer-instance is a development-only API endpoint flag', () => {- const originalDefaultApp = process.defaultApp;- try {- process.defaultApp = undefined;- assert.equal(getLaunchInstanceEndpointOverride(['electron', '.']), null);- assert.throws(- () => getLaunchInstanceEndpointOverride(['--fluxer-instance', 'https://self.example/api']),- /only accepted in a development build/,- );- process.defaultApp = true;- assert.equal(- getLaunchInstanceEndpointOverride(['--fluxer-instance', 'https://self.example/api/']),- 'https://self.example/api',- );- assert.equal(- getLaunchInstanceEndpointOverride(['--fluxer-instance=https://self.example:8443/api']),- 'https://self.example:8443/api',- );- assert.throws(- () => getLaunchInstanceEndpointOverride(['--fluxer-instance', '/api']),- /absolute http\(s\) API endpoint/,- );- assert.throws(() => getLaunchInstanceEndpointOverride(['--fluxer-instance']), /absolute http\(s\) API endpoint/);- } finally {- process.defaultApp = originalDefaultApp;- }- });-});diff --git a/fluxer_desktop/src/main/DesktopRuntimeDiscovery.test.mjs b/fluxer_desktop/src/main/DesktopRuntimeDiscovery.test.mjsdeleted file mode 100644index 774fe95c5..000000000--- a/fluxer_desktop/src/main/DesktopRuntimeDiscovery.test.mjs+++ /dev/null@@ -1,50 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {runtimePlanFromServedDiscovery} = await import('@electron/main/DesktopRuntimeDiscovery');-const {DEPLOYED_OFFICIAL_DOCUMENT} = await import('@fluxer/instance_bootstrap/src/__tests__/DiscoveryFixtures');--describe('runtime plans from a served discovery document', () => {- test('a document served by its own API origin builds a plan keyed on that origin', () => {- const built = runtimePlanFromServedDiscovery(- 'https://api.fluxer.app/.well-known/fluxer',- DEPLOYED_OFFICIAL_DOCUMENT,- );- assert.equal(built.instanceKey, 'https://api.fluxer.app');- assert.equal(built.document, DEPLOYED_OFFICIAL_DOCUMENT);- });-- test('a document that claims another instance API is refused before a plan exists', () => {- const spoofed = {- ...DEPLOYED_OFFICIAL_DOCUMENT,- endpoints: {- ...DEPLOYED_OFFICIAL_DOCUMENT.endpoints,- gateway: 'wss://gw.evil.example',- media: 'https://evil.example',- webapp: 'https://evil.example',- upload_relay: 'https://evil.example/upload',- },- };- assert.throws(() => runtimePlanFromServedDiscovery('https://evil.example/.well-known/fluxer', spoofed), {- name: 'InstanceDiscoveryOriginMismatchError',- });- });-- test('an api_client on another origin is refused even when api matches', () => {- const spoofed = {- ...DEPLOYED_OFFICIAL_DOCUMENT,- endpoints: {- ...DEPLOYED_OFFICIAL_DOCUMENT.endpoints,- api: 'https://evil.example',- api_client: 'https://api.fluxer.app',- },- };- assert.throws(() => runtimePlanFromServedDiscovery('https://evil.example/.well-known/fluxer', spoofed), {- name: 'InstanceDiscoveryOriginMismatchError',- });- });-});diff --git a/fluxer_desktop/src/main/DesktopRuntimeDiscoveryOfficialAlias.test.mjs b/fluxer_desktop/src/main/DesktopRuntimeDiscoveryOfficialAlias.test.mjsdeleted file mode 100644index 6ac49a780..000000000--- a/fluxer_desktop/src/main/DesktopRuntimeDiscoveryOfficialAlias.test.mjs+++ /dev/null@@ -1,147 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {beforeEach, describe, test} from 'node:test';-import {installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--const NETWORK_KEY = '__fluxerDesktopDiscoveryAliasTestNetwork__';-const network = {served: new Map(), fetched: [], anchored: []};-globalThis[NETWORK_KEY] = network;--installElectronStub();-installTestModuleStub(- '@electron/main/SelectedInstanceFetch',- `const network = globalThis[${JSON.stringify(NETWORK_KEY)}];- export function getDesktopSelectedInstanceClient() {- return {- async fetch({url, expectedOrigin}) {- network.fetched.push({url, expectedOrigin});- const document = network.served.get(new URL(url).origin);- if (document === undefined || !url.endsWith('/.well-known/fluxer')) {- return {ok: false, status: 404, headers: {}, body: null};- }- return {- ok: true,- status: 200,- headers: {'content-type': 'application/json'},- body: Buffer.from(JSON.stringify(document), 'utf8'),- };- },- };- }`,-);-installTestModuleStub(- '@electron/main/DesktopOutboundHTTP',- `const network = globalThis[${JSON.stringify(NETWORK_KEY)}];- export const DesktopAddressRequirement = Object.freeze({ANY: 'any', PUBLIC: 'public'});- export const requireDesktopHTTPOrigin = (value) => new URL(value).origin;- export const isDesktopHostResolutionFailure = () => false;- export function getDesktopOutboundHTTP() {- return {- async registerAnchoredOrigins(request) {- network.anchored.push(request);- return 'public';- },- };- }`,-);--const {resolveDesktopRuntimePlan} = await import('@electron/main/DesktopRuntimeDiscovery');-const {DEPLOYED_OFFICIAL_DOCUMENT} = await import('@fluxer/instance_bootstrap/src/__tests__/DiscoveryFixtures');--function officialDocument(clientOrigin) {- return {- ...DEPLOYED_OFFICIAL_DOCUMENT,- endpoints: {- ...DEPLOYED_OFFICIAL_DOCUMENT.endpoints,- api: `${clientOrigin}/api`,- api_client: `${clientOrigin}/api`,- webapp: clientOrigin,- },- };-}--const CHANNELS = Object.freeze([- {migrated: 'https://fluxer.com', official: 'https://web.fluxer.app'},- {migrated: 'https://canary.fluxer.com', official: 'https://web.canary.fluxer.app'},-]);--describe('desktop discovery for an account stored on the migrated official domain', () => {- beforeEach(() => {- network.served.clear();- network.fetched.length = 0;- network.anchored.length = 0;- for (const {migrated, official} of CHANNELS) {- network.served.set(migrated, officialDocument(official));- network.served.set(official, officialDocument(official));- }- });-- for (const {migrated, official} of CHANNELS) {- test(`${migrated}/api resolves the official instance at ${official}/api`, async () => {- const plan = await resolveDesktopRuntimePlan({input: `${migrated}/api`, signal: null});-- assert.equal(plan.instanceKey, `${official}/api`);- assert.equal(plan.endpoints.apiEndpoint, `${official}/api`);- assert.deepEqual(- network.fetched.map((request) => new URL(request.url).origin),- [official],- );- assert.equal(network.fetched[0].expectedOrigin, official);- assert.equal(network.anchored.length, 1);- assert.equal(network.anchored[0].anchorOrigin, official);- });-- test(`${official}/api keeps resolving as itself`, async () => {- const plan = await resolveDesktopRuntimePlan({input: `${official}/api`, signal: null});-- assert.equal(plan.instanceKey, `${official}/api`);- assert.deepEqual(- network.fetched.map((request) => new URL(request.url).origin),- [official],- );- });- }-- test('an alias domain that declares another API resolves the instance it declares', async () => {- network.served.set('https://domain2.example.test', officialDocument('https://domain1.example.test'));- network.served.set('https://domain1.example.test', officialDocument('https://domain1.example.test'));-- const plan = await resolveDesktopRuntimePlan({input: 'https://domain2.example.test/api', signal: null});-- assert.equal(plan.instanceKey, 'https://domain1.example.test/api');- assert.equal(plan.endpoints.apiEndpoint, 'https://domain1.example.test/api');- assert.equal(network.anchored.length, 1);- assert.equal(network.anchored[0].anchorOrigin, 'https://domain1.example.test');- assert.deepEqual(- network.fetched- .filter((request) => new URL(request.url).origin === 'https://domain1.example.test')- .map((request) => request.expectedOrigin),- ['https://domain1.example.test'],- );- });-- test('the declared instance must declare itself, so a chain stops after one hop', async () => {- network.served.set('https://a.example.test', officialDocument('https://b.example.test'));- network.served.set('https://b.example.test', officialDocument('https://c.example.test'));- network.served.set('https://c.example.test', officialDocument('https://c.example.test'));-- await assert.rejects(resolveDesktopRuntimePlan({input: 'https://a.example.test/api', signal: null}), {- name: 'DesktopRuntimeDiscoveryFailedError',- });- assert.equal(- network.fetched.some((request) => new URL(request.url).origin === 'https://c.example.test'),- false,- );- assert.equal(network.anchored.length, 0);- });-- test('a declared instance that serves no discovery is refused', async () => {- network.served.set('https://chat.example.test', officialDocument('https://gone.example.test'));-- await assert.rejects(resolveDesktopRuntimePlan({input: 'https://chat.example.test/api', signal: null}), {- name: /DesktopRuntimeDiscovery/,- });- assert.equal(network.anchored.length, 0);- });-});diff --git a/fluxer_desktop/src/main/DesktopRuntimeDiscoveryUnreachable.test.mjs b/fluxer_desktop/src/main/DesktopRuntimeDiscoveryUnreachable.test.mjsdeleted file mode 100644index 350321c29..000000000--- a/fluxer_desktop/src/main/DesktopRuntimeDiscoveryUnreachable.test.mjs+++ /dev/null@@ -1,217 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {beforeEach, describe, test} from 'node:test';-import {installDesktopAppStorageStub, installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--const NETWORK_KEY = '__fluxerDesktopDiscoveryUnreachableTestNetwork__';-const network = {respond: null, fetched: [], resolvable: true, registrations: []};-globalThis[NETWORK_KEY] = network;--const markers = new Map();-const storage = {- refuseWrites: false,- getMarker: async (key) => markers.get(key) ?? null,- setMarker: async (key, value) => {- if (storage.refuseWrites) throw new Error('the store is read-only');- markers.set(key, value);- },-};--installElectronStub();-installDesktopAppStorageStub(storage);-installTestModuleStub(- '@electron/main/SelectedInstanceFetch',- `const network = globalThis[${JSON.stringify(NETWORK_KEY)}];- export function getDesktopSelectedInstanceClient() {- return {- async fetch({url}) {- network.fetched.push(url);- return network.respond(url);- },- };- }`,-);-installTestModuleStub(- '@electron/main/DesktopOutboundHTTP',- `const network = globalThis[${JSON.stringify(NETWORK_KEY)}];- export const DesktopAddressRequirement = Object.freeze({ANY: 'any', PUBLIC: 'public'});- export const requireDesktopHTTPOrigin = (value) => new URL(value).origin;- export const isDesktopHostResolutionFailure = (error) => error?.syscall === 'getaddrinfo';- export function getDesktopOutboundHTTP() {- return {- async registerAnchoredOrigins(registration) {- network.registrations.push(registration);- if (network.resolvable) return 'public';- if (registration.unresolvedAnchorRequirement != null) return registration.unresolvedAnchorRequirement;- throw Object.assign(new Error('getaddrinfo EAI_AGAIN api.fluxer.app'), {- code: 'EAI_AGAIN',- syscall: 'getaddrinfo',- });- },- };- }`,-);--const {resolveDesktopRuntimePlan, restoreRememberedRuntimePlan} = await import(- '@electron/main/DesktopRuntimeDiscovery'-);-const {DEPLOYED_OFFICIAL_DOCUMENT} = await import('@fluxer/instance_bootstrap/src/__tests__/DiscoveryFixtures');-const {DESKTOP_RUNTIME_DISCOVERY_UNREACHABLE_ERROR_NAME} = await import(- '@fluxer/desktop_ipc/src/LocalAppRuntimeContract'-);--const API_ENDPOINT = 'https://api.fluxer.app';-const MARKER_KEY = `runtime_discovery.v1:${API_ENDPOINT}`;--function served(document) {- return () => ({- ok: true,- status: 200,- headers: {'content-type': 'application/json'},- body: Buffer.from(JSON.stringify(document), 'utf8'),- });-}--function refused() {- return () => {- throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:9'), {code: 'ECONNREFUSED'});- };-}--function status(code) {- return () => ({ok: false, status: code, headers: {}, body: null});-}--function resolve(signal = null) {- return resolveDesktopRuntimePlan({input: API_ENDPOINT, signal});-}--describe('desktop discovery while the instance is unreachable', () => {- beforeEach(() => {- markers.clear();- storage.refuseWrites = false;- network.fetched.length = 0;- network.resolvable = true;- network.registrations.length = 0;- network.respond = served(DEPLOYED_OFFICIAL_DOCUMENT);- });-- test('a served document is remembered for its API endpoint', async () => {- const plan = await resolve();- const remembered = JSON.parse(markers.get(MARKER_KEY));- assert.deepEqual(remembered.document, DEPLOYED_OFFICIAL_DOCUMENT);- assert.equal(new URL(remembered.url).origin, API_ENDPOINT);- assert.equal(plan.instanceKey, API_ENDPOINT);- });-- test('a refused connection resolves the plan from the last served document', async () => {- const online = await resolve();- network.respond = refused();- const offline = await resolve();- assert.equal(offline.instanceKey, online.instanceKey);- assert.deepEqual(offline.endpoints, online.endpoints);- assert.deepEqual(offline.document, DEPLOYED_OFFICIAL_DOCUMENT);- });-- test('a name that cannot resolve still resolves the plan from the last served document', async () => {- const online = await resolve();- assert.equal(JSON.parse(markers.get(MARKER_KEY)).anchorRequirement, 'public');- network.respond = refused();- network.resolvable = false;- const offline = await resolve();- assert.equal(offline.instanceKey, online.instanceKey);- assert.equal(network.registrations.at(-1).unresolvedAnchorRequirement, 'public');- });-- test('a remembered document without an anchor requirement fails as unreachable when the name cannot resolve', async () => {- await resolve();- const remembered = JSON.parse(markers.get(MARKER_KEY));- markers.set(MARKER_KEY, JSON.stringify({url: remembered.url, document: remembered.document}));- network.respond = refused();- network.resolvable = false;- await assert.rejects(resolve(), {name: DESKTOP_RUNTIME_DISCOVERY_UNREACHABLE_ERROR_NAME});- });-- test('a gateway error from the instance resolves the plan from the last served document', async () => {- await resolve();- network.respond = status(503);- assert.equal((await resolve()).instanceKey, API_ENDPOINT);- });-- test('an unreachable instance that was never served fails as unreachable', async () => {- network.respond = refused();- await assert.rejects(resolve(), (error) => {- assert.equal(error.name, DESKTOP_RUNTIME_DISCOVERY_UNREACHABLE_ERROR_NAME);- assert.match(error.message, /ECONNREFUSED/u);- return true;- });- });-- test('an instance that answers without a discovery document never falls back', async () => {- await resolve();- network.respond = status(404);- await assert.rejects(resolve(), {name: 'DesktopRuntimeDiscoveryFailedError'});- });-- test('an instance that now serves a foreign API never falls back', async () => {- await resolve();- network.respond = served({- ...DEPLOYED_OFFICIAL_DOCUMENT,- endpoints: {...DEPLOYED_OFFICIAL_DOCUMENT.endpoints, api: 'https://evil.example/api'},- });- await assert.rejects(resolve(), {name: 'DesktopRuntimeDiscoveryFailedError'});- });-- test('a cancelled resolution never falls back', async () => {- await resolve();- const controller = new AbortController();- network.respond = () => {- controller.abort();- throw new Error('aborted by its caller');- };- await assert.rejects(resolve(controller.signal), {name: 'DesktopRuntimeDiscoveryFailedError'});- });-- test('a remembered document that no longer validates is ignored', async () => {- markers.set(MARKER_KEY, JSON.stringify({url: 'https://evil.example/.well-known/fluxer', document: {}}));- network.respond = refused();- await assert.rejects(resolve(), {name: DESKTOP_RUNTIME_DISCOVERY_UNREACHABLE_ERROR_NAME});- });-- test('a store that refuses the write still resolves the served plan', async () => {- storage.refuseWrites = true;- assert.equal((await resolve()).instanceKey, API_ENDPOINT);- assert.equal(markers.size, 0);- });-});--describe('a media or API route for a saved instance after a cold start', () => {- beforeEach(() => {- markers.clear();- storage.refuseWrites = false;- network.fetched.length = 0;- network.resolvable = true;- network.registrations.length = 0;- network.respond = served(DEPLOYED_OFFICIAL_DOCUMENT);- });-- test('restores the plan of an instance this app was served before without fetching discovery', async () => {- const online = await resolve();- network.fetched.length = 0;- network.registrations.length = 0;- const restored = await restoreRememberedRuntimePlan(online.instanceKey);- assert.equal(restored?.instanceKey, online.instanceKey);- assert.deepEqual(restored?.endpoints, online.endpoints);- assert.deepEqual(network.fetched, []);- assert.equal(network.registrations.length, 1);- assert.equal(network.registrations[0].unresolvedAnchorRequirement, 'public');- });-- test('never invents a plan for an instance this app was not served', async () => {- assert.equal(await restoreRememberedRuntimePlan('https://unknown.example'), null);- assert.equal(await restoreRememberedRuntimePlan('not a url'), null);- assert.deepEqual(network.fetched, []);- assert.deepEqual(network.registrations, []);- });-});diff --git a/fluxer_desktop/src/main/DesktopRuntimeSecurity.test.mjs b/fluxer_desktop/src/main/DesktopRuntimeSecurity.test.mjsdeleted file mode 100644index f99df1b6a..000000000--- a/fluxer_desktop/src/main/DesktopRuntimeSecurity.test.mjs+++ /dev/null@@ -1,163 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {DesktopRuntimeSecurity} = await import('@electron/main/DesktopRuntimeSecurity');--function createLogger() {- const errors = [];- return {- errors,- error: (...args) => errors.push(args),- };-}--function createSession() {- const session = {- requestFilter: null,- requestListener: null,- webRequest: {- onBeforeSendHeaders: (...args) => {- session.requestFilter = args.length > 1 ? args[0] : null;- session.requestListener = args.at(-1);- },- },- };- return session;-}--function createInstalled() {- const logger = createLogger();- const session = createSession();- const security = new DesktopRuntimeSecurity({logger});- security.install(session);- return {security, session, logger};-}--function settleRequest(session, details) {- let settlement = null;- let calls = 0;- session.requestListener(details, (value) => {- calls += 1;- settlement = value;- });- assert.equal(calls, 1, 'the request callback must be invoked exactly once');- return settlement;-}--describe('DesktopRuntimeSecurity', () => {- test('gives the YouTube embed frame the canonical app origin YouTube authorizes', () => {- const {session} = createInstalled();-- const settlement = settleRequest(session, {- resourceType: 'subFrame',- url: 'https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1',- requestHeaders: {Accept: '*/*'},- });-- assert.deepEqual({...settlement.requestHeaders}, {Accept: '*/*', Referer: 'https://web.fluxer.app/'});- });-- test('never invents a referrer for anything but the YouTube embed frame', () => {- const {session} = createInstalled();-- for (const details of [- {resourceType: 'subFrame', url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'},- {resourceType: 'subFrame', url: 'https://youtube.com/embed/dQw4w9WgXcQ'},- {resourceType: 'subFrame', url: 'https://www.youtube.com.example.test/embed/dQw4w9WgXcQ'},- {resourceType: 'subFrame', url: 'http://www.youtube.com/embed/dQw4w9WgXcQ'},- {resourceType: 'subFrame', url: 'https://challenges.cloudflare.com/embed/widget'},- {resourceType: 'xhr', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ'},- {resourceType: 'script', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ'},- {resourceType: 'mainFrame', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ'},- ]) {- assert.deepEqual(settleRequest(session, {...details, requestHeaders: {Accept: '*/*'}}), {}, details.url);- }- });-- test('replaces the local shell origin the renderer sends with the canonical app origin', () => {- const {session} = createInstalled();-- const settlement = settleRequest(session, {- resourceType: 'subFrame',- url: 'https://www.youtube.com/embed/dQw4w9WgXcQ',- requestHeaders: {Accept: '*/*', referer: 'fluxer-app://app/'},- });-- assert.deepEqual({...settlement.requestHeaders}, {Accept: '*/*', Referer: 'https://web.fluxer.app/'});- });-- test('emits request header values Electron will actually send rather than response-shaped arrays', () => {- const {session} = createInstalled();-- const settlement = settleRequest(session, {- resourceType: 'subFrame',- url: 'https://www.youtube.com/embed/dQw4w9WgXcQ',- requestHeaders: {Accept: '*/*', 'User-Agent': 'agent'},- });-- for (const [name, value] of Object.entries(settlement.requestHeaders)) {- assert.equal(typeof value, 'string', `${name} must be a string, Electron drops array-valued request headers`);- }- });-- test('the embed referrer cannot smuggle the local app authorization secret out with it', () => {- const session = createSession();- const security = new DesktopRuntimeSecurity({- logger: createLogger(),- localAppAuthorization: {- applyRequestHeaders: (_details, headers) => {- const next = {};- for (const [name, value] of Object.entries(headers)) {- if (name.toLowerCase() !== 'x-fluxer-desktop-protocol-authorization') {- next[name] = value;- }- }- return next;- },- },- });- security.install(session);-- const settlement = settleRequest(session, {- resourceType: 'subFrame',- url: 'https://www.youtube.com/embed/dQw4w9WgXcQ',- requestHeaders: {Accept: '*/*', 'X-Fluxer-Desktop-Protocol-Authorization': 'secret'},- });-- assert.deepEqual({...settlement.requestHeaders}, {Accept: '*/*', Referer: 'https://web.fluxer.app/'});- });-- test('leaves a request it has no reason to touch alone', () => {- const {session} = createInstalled();-- assert.deepEqual(- settleRequest(session, {- resourceType: 'mainFrame',- url: 'https://web.fluxer.app/channels/@me',- requestHeaders: {Accept: '*/*'},- }),- {},- );- });-- test('only intercepts local app requests and the YouTube embed frame', () => {- const {session} = createInstalled();-- assert.deepEqual(session.requestFilter, {urls: ['fluxer-app://*/*', 'https://www.youtube.com/embed/*']});- });-- test('installs once per session and stops listening after cleanup', () => {- const {security, session} = createInstalled();- const firstRequestListener = session.requestListener;-- security.install(session);- assert.equal(session.requestListener, firstRequestListener);-- security.cleanup();- assert.equal(session.requestListener, null);- assert.throws(() => security.install(session), /closed/);- });-});diff --git a/fluxer_desktop/src/main/DesktopRuntimeTransactionRegistry.test.mjs b/fluxer_desktop/src/main/DesktopRuntimeTransactionRegistry.test.mjsdeleted file mode 100644index 68f11f536..000000000--- a/fluxer_desktop/src/main/DesktopRuntimeTransactionRegistry.test.mjs+++ /dev/null@@ -1,346 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {beforeEach, describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import {installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const PROTOCOL_KEY = '__fluxerDesktopRuntimeTransactionTestProtocol__';-const DISCOVERY_KEY = '__fluxerDesktopRuntimeTransactionTestDiscovery__';--installTestModuleStub(- '@electron/main/LocalAppProtocol',- `export const getDesktopLocalAppProtocol = () => globalThis[${JSON.stringify(PROTOCOL_KEY)}];`,-);-installTestModuleStub(- '@electron/main/DesktopRuntimeDiscovery',- `export const resolveDesktopRuntimePlan = async (request) => await globalThis[${JSON.stringify(DISCOVERY_KEY)}](request);`,-);--const REGISTRY_SOURCE_PATH = fileURLToPath(new URL('./DesktopRuntimeTransactionRegistry.ts', import.meta.url));--const {DesktopRuntimeTransactionRegistry} = await import(- `data:text/javascript,${encodeURIComponent(- esbuild.transformSync(readFileSync(REGISTRY_SOURCE_PATH, 'utf8'), {- loader: 'ts',- format: 'esm',- platform: 'node',- target: 'node22',- }).code,- )}`-);--const MAX_RUNTIME_PREPARATIONS = 8;--const ONE = 'https://one.test/api';-const TWO = 'https://two.test/api';-const BASE = 'https://base.test/api';--function createPlan(instanceKey) {- return {- instanceKey,- document: {instance: instanceKey},- endpoints: {- apiEndpoint: instanceKey,- apiPublicEndpoint: null,- webAppEndpoint: null,- mediaEndpoint: null,- staticCdnEndpoint: null,- uploadRelayEndpoint: null,- gatewayEndpoint: null,- inviteEndpoint: null,- giftEndpoint: null,- },- selfHosted: true,- };-}--function createProtocol(activePlan = null) {- const shutdown = new AbortController();- let active = activePlan;- return {- activations: [],- getActivePlan: () => active,- findPlanForRoute: () => null,- getShutdownSignal: () => shutdown.signal,- activateRuntimePlan(plan) {- active = plan;- this.activations.push(plan.instanceKey);- },- deactivateRuntimePlan() {- active = null;- this.activations.push(null);- },- };-}--function createRendererDocument(name) {- const watchers = new Set();- const owner = {- sender: name,- frame: name,- isCurrent: () => true,- matchesEvent: (event) => event.document === owner,- requireCurrent: () => undefined,- watchInvalidation(onInvalidated) {- const watcher = {onInvalidated, dispose: () => watchers.delete(watcher)};- watchers.add(watcher);- return watcher;- },- };- return {owner, event: {document: owner}, liveWatchers: () => watchers.size};-}--const rendererDocuments = {capture: (event) => event.document};--function transactionRequest(preparation) {- return {- preparationId: preparation.preparationId,- instanceKey: preparation.instanceKey,- baseRevision: preparation.baseRevision,- };-}--function committedRequest(preparation, committedRevision) {- return {...transactionRequest(preparation), committedRevision};-}--function named(name) {- return (error) => {- assert.equal(error.name, name, `expected ${name}, got ${error.name}: ${error.message}`);- return true;- };-}--let protocol;-let discovered;-let document;-let registry;--beforeEach(() => {- protocol = createProtocol();- discovered = new Map([- [ONE, createPlan(ONE)],- [TWO, createPlan(TWO)],- ]);- globalThis[PROTOCOL_KEY] = protocol;- globalThis[DISCOVERY_KEY] = async ({input}) => {- const plan = discovered.get(input);- if (plan == null) {- throw new Error(`no discovery fixture for ${input}`);- }- return plan;- };- document = createRendererDocument('document-one');- registry = new DesktopRuntimeTransactionRegistry(rendererDocuments);-});--describe('DesktopRuntimeTransactionRegistry.commit', () => {- test('a preparation cannot commit at a revision an earlier rollback already moved past', async () => {- const basePlan = createPlan(BASE);- protocol = createProtocol(basePlan);- globalThis[PROTOCOL_KEY] = protocol;- registry = new DesktopRuntimeTransactionRegistry(rendererDocuments);- registry.initialize();- const first = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const second = await registry.prepare(document.event, {preparationId: 'second', instanceKey: ONE});- assert.equal(second.baseRevision, first.baseRevision);- assert.equal(second.baseActiveInstanceKey, BASE);- registry.commit(document.event, transactionRequest(first));- registry.abort(document.event, {preparationId: 'first'});- assert.equal(protocol.getActivePlan(), basePlan);-- assert.throws(- () => registry.commit(document.event, transactionRequest(second)),- named('DesktopRuntimePreparationSupersededError'),- );- assert.equal(protocol.getActivePlan(), basePlan);- assert.deepEqual(protocol.activations, [ONE, BASE]);- });-- test('a preparation left behind by another commit is refused as superseded', async () => {- registry.initialize();- const first = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const second = await registry.prepare(document.event, {preparationId: 'second', instanceKey: TWO});- assert.equal(first.baseRevision, 0);- assert.equal(second.baseRevision, 0);-- const commit = registry.commit(document.event, transactionRequest(first));- assert.deepEqual(commit, {preparationId: 'first', instanceKey: ONE, baseRevision: 0, revision: 1});- registry.finalize(document.event, committedRequest(first, 1));-- assert.throws(- () => registry.commit(document.event, transactionRequest(second)),- named('DesktopRuntimePreparationSupersededError'),- );- assert.equal(protocol.getActivePlan().instanceKey, ONE);- assert.deepEqual(protocol.activations, [ONE]);- });-- test('a commit whose base activation moved underneath it is refused on identity', async () => {- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- assert.equal(prepared.baseActiveInstanceKey, null);-- protocol.activateRuntimePlan(createPlan(BASE));-- assert.throws(- () => registry.commit(document.event, transactionRequest(prepared)),- named('DesktopRuntimePreparationIdentityError'),- );- assert.equal(protocol.getActivePlan().instanceKey, BASE);- assert.deepEqual(protocol.activations, [BASE]);- });-- test('a second provisional commit is refused while the first is still open', async () => {- registry.initialize();- const first = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const second = await registry.prepare(document.event, {preparationId: 'second', instanceKey: TWO});- registry.commit(document.event, transactionRequest(first));-- assert.throws(- () => registry.commit(document.event, transactionRequest(second)),- named('DesktopRuntimeCommitInProgressError'),- );- assert.equal(protocol.getActivePlan().instanceKey, ONE);- });-});--describe('DesktopRuntimeTransactionRegistry.abort', () => {- test('aborting a committed preparation restores the exact plan it replaced', async () => {- const basePlan = createPlan(BASE);- protocol = createProtocol(basePlan);- globalThis[PROTOCOL_KEY] = protocol;- registry = new DesktopRuntimeTransactionRegistry(rendererDocuments);- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- assert.equal(prepared.baseRevision, 1);- assert.equal(prepared.baseActiveInstanceKey, BASE);- registry.commit(document.event, transactionRequest(prepared));- assert.equal(protocol.getActivePlan().instanceKey, ONE);-- const aborted = registry.abort(document.event, {preparationId: 'first'});-- assert.deepEqual(aborted, {disposition: 'rolled-back', revision: 3, activeInstanceKey: BASE});- assert.equal(protocol.getActivePlan(), basePlan);- assert.deepEqual(protocol.activations, [ONE, BASE]);- assert.equal(document.liveWatchers(), 0);- });-- test('aborting a committed preparation that replaced nothing deactivates the runtime again', async () => {- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- registry.commit(document.event, transactionRequest(prepared));-- const aborted = registry.abort(document.event, {preparationId: 'first'});-- assert.deepEqual(aborted, {disposition: 'rolled-back', revision: 2, activeInstanceKey: null});- assert.equal(protocol.getActivePlan(), null);- assert.deepEqual(protocol.activations, [ONE, null]);- });-- test('aborting a prepared-but-uncommitted preparation leaves the runtime alone', async () => {- registry.initialize();- await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});-- const aborted = registry.abort(document.event, {preparationId: 'first'});-- assert.deepEqual(aborted, {disposition: 'aborted', revision: 0, activeInstanceKey: null});- assert.deepEqual(protocol.activations, []);- assert.deepEqual(registry.abort(document.event, {preparationId: 'first'}), {- disposition: 'absent',- revision: 0,- activeInstanceKey: null,- });- });-});--describe('DesktopRuntimeTransactionRegistry.rollback', () => {- test('rolling back a committed preparation restores the exact plan it replaced', async () => {- const basePlan = createPlan(BASE);- protocol = createProtocol(basePlan);- globalThis[PROTOCOL_KEY] = protocol;- registry = new DesktopRuntimeTransactionRegistry(rendererDocuments);- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const commit = registry.commit(document.event, transactionRequest(prepared));-- const rollback = registry.rollback(document.event, committedRequest(prepared, commit.revision));-- assert.deepEqual(rollback, {revision: commit.revision + 1, activeInstanceKey: BASE});- assert.equal(protocol.getActivePlan(), basePlan);- assert.throws(- () => registry.rollback(document.event, committedRequest(prepared, commit.revision)),- named('DesktopRuntimePreparationNotFoundError'),- );- });-- test('a finalized preparation can no longer be rolled back', async () => {- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const commit = registry.commit(document.event, transactionRequest(prepared));- registry.finalize(document.event, committedRequest(prepared, commit.revision));-- assert.throws(- () => registry.rollback(document.event, committedRequest(prepared, commit.revision)),- named('DesktopRuntimePreparationNotFoundError'),- );- assert.equal(protocol.getActivePlan().instanceKey, ONE);- assert.deepEqual(protocol.activations, [ONE]);- });-});--describe('DesktopRuntimeTransactionRegistry.prepare', () => {- test('a renderer cannot hold more preparations than the registry admits', async () => {- registry.initialize();- for (let index = 0; index < MAX_RUNTIME_PREPARATIONS; index += 1) {- discovered.set(`https://instance-${index}.test/api`, createPlan(`https://instance-${index}.test/api`));- const prepared = await registry.prepare(document.event, {- preparationId: `preparation-${index}`,- instanceKey: `https://instance-${index}.test/api`,- });- assert.equal(prepared.instanceKey, `https://instance-${index}.test/api`);- }-- await assert.rejects(- registry.prepare(document.event, {preparationId: 'overflow', instanceKey: ONE}),- named('DesktopRuntimePreparationCapacityError'),- );- assert.equal(document.liveWatchers(), MAX_RUNTIME_PREPARATIONS);- assert.deepEqual(registry.abort(document.event, {preparationId: 'overflow'}), {- disposition: 'absent',- revision: 0,- activeInstanceKey: null,- });- });-- test('a duplicate preparation id is refused before it can shadow the live one', async () => {- registry.initialize();- await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});-- await assert.rejects(- registry.prepare(document.event, {preparationId: 'first', instanceKey: TWO}),- named('DesktopRuntimePreparationAlreadyExistsError'),- );- assert.equal(document.liveWatchers(), 1);- });-- test('a preparation belongs to the renderer document that opened it', async () => {- registry.initialize();- const prepared = await registry.prepare(document.event, {preparationId: 'first', instanceKey: ONE});- const other = createRendererDocument('document-two');-- assert.throws(- () => registry.commit(other.event, transactionRequest(prepared)),- named('DesktopRuntimePreparationOwnershipError'),- );- assert.deepEqual(protocol.activations, []);- });-});diff --git a/fluxer_desktop/src/main/DesktopSystemTrustVerifier.test.mjs b/fluxer_desktop/src/main/DesktopSystemTrustVerifier.test.mjsdeleted file mode 100644index 9674e0d11..000000000--- a/fluxer_desktop/src/main/DesktopSystemTrustVerifier.test.mjs+++ /dev/null@@ -1,102 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {X509Certificate} from 'node:crypto';-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import {describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {buildDesktopTrustAnchors, verifyAgainstDesktopSystemTrust} = await import('./DesktopSystemTrustVerifier.ts');-const {resolveDesktopLocallyAddedCertificates} = await import('./DesktopTrustedCertificates.ts');--const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures', 'desktop-trust');-const read = (name) => fs.readFileSync(path.join(FIXTURES, `${name}.pem`), 'utf8');-const AUTHORITY_INVALID = -202;-const DEFER = -3;-const ACCEPT = 0;--function chain(names) {- let certificate;- for (const name of [...names].reverse()) certificate = {data: read(name), issuerCert: certificate};- return certificate;-}--function verify(names, {hostname = 'host.example', errorCode = AUTHORITY_INVALID, anchors = ['root']} = {}) {- const store = buildDesktopTrustAnchors(anchors.map(read));- return verifyAgainstDesktopSystemTrust({hostname, certificate: chain(names), errorCode}, () => store);-}--describe('desktop system trust verifier', () => {- test('accepts a chain that ends at a locally added CA', () => {- assert.equal(verify(['leaf', 'int']), ACCEPT);- assert.equal(verify(['leaf', 'int'], {hostname: 'HOST.example.'}), ACCEPT);- assert.equal(verify(['leaf', 'int'], {hostname: '127.0.0.1'}), ACCEPT);- assert.equal(verify(['leaf', 'int'], {hostname: '[::1]'}), ACCEPT);- assert.equal(verify(['ec_leaf']), ACCEPT);- assert.equal(verify(['wc_leaf'], {hostname: 'a.lan.home.example'}), ACCEPT);- });-- test('defers to Chromium for other errors, anchors and hosts', () => {- assert.equal(verify(['leaf', 'int'], {errorCode: -201}), DEFER);- assert.equal(verify(['leaf', 'int'], {anchors: ['pl_int']}), DEFER);- assert.equal(verify(['leaf', 'int'], {hostname: 'other.example'}), DEFER);- assert.equal(verify(['wc_leaf'], {hostname: 'a.b.lan.home.example'}), DEFER);- assert.equal(verify(['wc_leaf'], {hostname: 'a.home.example'}), DEFER);- assert.equal(verify(['wc_leaf'], {hostname: 'victim.co.uk'}), DEFER);- });-- test('defers on constrained, weak or unknown certificates in the path', () => {- assert.equal(verify(['nc_leaf', 'nc_int']), DEFER);- assert.equal(verify(['nc_leaf'], {anchors: ['nc_int']}), DEFER);- assert.equal(verify(['eku_leaf', 'eku_int']), DEFER);- assert.equal(verify(['pl_leaf', 'pl_int2', 'pl_int']), DEFER);- assert.equal(verify(['crit_leaf']), DEFER);- assert.equal(verify(['sha1_leaf']), DEFER);- assert.equal(verify(['weak_leaf']), DEFER);- });-- test('rejects non-DER booleans and Chromium blocklisted keys', () => {- assert.equal(verify(['bool_ff_leaf']), ACCEPT);- assert.equal(verify(['bool_01_leaf']), DEFER);- assert.equal(buildDesktopTrustAnchors([read('kz_root')]).size, 0);- });-- test('anchors on DER roots read from the Windows intermediate store', () => {- const der = (name) => new X509Certificate(read(name)).raw;- const store = buildDesktopTrustAnchors([der('root')]);- const request = {hostname: 'host.example', certificate: chain(['leaf', 'int']), errorCode: AUTHORITY_INVALID};- assert.equal(- verifyAgainstDesktopSystemTrust(request, () => store),- ACCEPT,- );- assert.equal(buildDesktopTrustAnchors([der('kz_root'), Buffer.from('not a certificate')]).size, 0);- });-- test('anchors only on admin added CAs that the distro bundle still trusts', () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-trust-'));- const write = (file, content) => {- fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});- fs.writeFileSync(path.join(root, file), content);- };- const der = (name) => new X509Certificate(read(name)).raw;- try {- assert.deepEqual(resolveDesktopLocallyAddedCertificates(root), []);- write('etc/ssl/certs/ca-certificates.crt', [read('root'), read('int'), read('kz_root')].join('\n'));- write('usr/local/share/ca-certificates/site/root.crt', read('root'));- write('usr/local/share/ca-certificates/int.der', der('int'));- write('usr/local/share/ca-certificates/deselected.crt', read('pl_int'));- write('cert.pem', read('pl_int'));- process.env.SSL_CERT_FILE = path.join(root, 'cert.pem');- const added = resolveDesktopLocallyAddedCertificates(root).map((pem) => new X509Certificate(pem).subject);- assert.deepEqual(added.sort(), ['CN=Trust Test Int', 'CN=Trust Test Root']);- } finally {- delete process.env.SSL_CERT_FILE;- fs.rmSync(root, {recursive: true, force: true});- }- });-});diff --git a/fluxer_desktop/src/main/DesktopTrustedCertificates.test.mjs b/fluxer_desktop/src/main/DesktopTrustedCertificates.test.mjsdeleted file mode 100644index 051b87bc2..000000000--- a/fluxer_desktop/src/main/DesktopTrustedCertificates.test.mjs+++ /dev/null@@ -1,93 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import https from 'node:https';-import path from 'node:path';-import {describe, test} from 'node:test';-import tls from 'node:tls';-import {fileURLToPath} from 'node:url';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {resolveDesktopTrustedCertificates} = await import('./DesktopTrustedCertificates.ts');-const {DesktopOriginTrust, DesktopOutboundHTTP} = await import('./DesktopOutboundHTTP.ts');--const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures', 'desktop-tls');-const read = (name) => fs.readFileSync(path.join(FIXTURES, name), 'utf8');-const TRUSTED_CA = read('trusted-ca.pem');-const UNTRUSTED_CA = read('untrusted-ca.pem');--async function startTLSServer() {- const server = https.createServer({cert: read('leaf.pem'), key: read('leaf.key')}, (_request, response) => {- response.writeHead(200, {'content-type': 'text/plain'});- response.end('ok');- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- return {port: server.address().port, server};-}--async function fetchThrough(certificates, port) {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => ['127.0.0.1'],- trustedCertificates: certificates,- });- try {- await outboundHTTP.registerAnchoredOrigins({anchorOrigin: `https://ca.example:${port}`, origins: []});- const response = await outboundHTTP.request({- body: null,- expectedOrigin: `https://ca.example:${port}`,- headers: null,- method: 'GET',- originTrust: DesktopOriginTrust.REGISTERED,- signal: null,- timeoutMs: 3000,- url: `https://ca.example:${port}/`,- });- response.message.resume();- return response.status;- } finally {- outboundHTTP.cleanup();- }-}--describe('desktop trusted certificates', () => {- test('merges the bundled roots with the system store without duplicates', () => {- const merged = resolveDesktopTrustedCertificates((store) => (store === 'default' ? ['a', 'b'] : ['b', 'c']));- assert.deepEqual(merged, ['a', 'b', 'c']);- });-- test('keeps the bundled roots when the system store cannot be read', () => {- const merged = resolveDesktopTrustedCertificates((store) => {- if (store === 'system') throw new Error('no system store');- return ['a'];- });- assert.deepEqual(merged, ['a']);- });-- test('reaches an instance whose CA is only trusted by the system store', async () => {- const {port, server} = await startTLSServer();- try {- const certificates = resolveDesktopTrustedCertificates((store) =>- store === 'system' ? [TRUSTED_CA] : tls.getCACertificates('default'),- );- assert.equal(await fetchThrough(certificates, port), 200);- } finally {- server.close();- }- });-- test('still refuses an instance signed by a CA nobody trusts', async () => {- const {port, server} = await startTLSServer();- try {- const certificates = resolveDesktopTrustedCertificates((store) =>- store === 'system' ? [UNTRUSTED_CA] : tls.getCACertificates('default'),- );- await assert.rejects(fetchThrough(certificates, port));- await assert.rejects(fetchThrough(tls.getCACertificates('default'), port));- } finally {- server.close();- }- });-});diff --git a/fluxer_desktop/src/main/FileDownloads.test.mjs b/fluxer_desktop/src/main/FileDownloads.test.mjsdeleted file mode 100644index d71383e80..000000000--- a/fluxer_desktop/src/main/FileDownloads.test.mjs+++ /dev/null@@ -1,239 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createHash} from 'node:crypto';-import {existsSync, mkdtempSync, readFileSync, writeFileSync} from 'node:fs';-import {createServer} from 'node:http';-import {createRequire} from 'node:module';-import {tmpdir} from 'node:os';-import {join} from 'node:path';-import {after, before, describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import vm from 'node:vm';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--function transform(name) {- const url = new URL(`./${name}`, import.meta.url);- const path = fileURLToPath(url);- return {- path,- code: esbuild.transformSync(readFileSync(path, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',- define: {'import.meta.url': JSON.stringify(url.href)},- }).code,- };-}--const happyEyeballsSource = transform('DesktopHappyEyeballs.ts');-const ipAddressSource = transform('../../../packages/ip_utils/src/IpAddress.ts');-const outboundSource = transform('DesktopOutboundHTTP.ts');-const fileDownloadsSource = transform('FileDownloads.ts');--const PAYLOAD = Buffer.alloc(300_000, 9);-const PAYLOAD_SHA256 = createHash('sha256').update(PAYLOAD).digest('hex');-const CORRUPT = Buffer.concat([Buffer.from([0]), PAYLOAD.subarray(1)]);-const CORRUPT_SHA256 = createHash('sha256').update(CORRUPT).digest('hex');-const EMPTY_SHA256 = createHash('sha256').digest('hex');--let server;-let baseUrl;-let requests = 0;--before(async () => {- server = createServer((request, response) => {- requests += 1;- if (request.url === '/payload' || request.url === '/redirected') {- response.writeHead(200, {'content-type': 'application/octet-stream', 'content-length': PAYLOAD.length});- response.end(PAYLOAD);- return;- }- if (request.url === '/corrupt') {- response.writeHead(200, {'content-type': 'application/octet-stream', 'content-length': CORRUPT.length});- response.end(CORRUPT);- return;- }- if (request.url === '/redirect') {- response.writeHead(302, {location: '/redirected'});- response.end();- return;- }- if (request.url === '/empty') {- response.writeHead(204);- response.end();- return;- }- response.writeHead(404);- response.end('missing');- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- baseUrl = `http://127.0.0.1:${server.address().port}`;-});--after(async () => {- await new Promise((resolve) => server.close(resolve));-});--async function loadFileDownloads({registerOrigin = true} = {}) {- const stubs = {- '@electron/common/Logger': {- createChildLogger: () => ({debug() {}, info() {}, warn() {}, error() {}}),- },- '@fluxer/instance_bootstrap/src/NetworkOrigin': {normalizeHTTPNetworkOrigin: (value) => new URL(value).origin},- '@electron/main/DesktopSessionHTTP': {- isDirectProxyRoute: (route) => route === 'DIRECT',- resolveDesktopSessionProxy: async () => 'DIRECT',- sendThroughDesktopSession: async () => {- throw new Error('a direct route never reaches the session');- },- },- '@electron/main/DesktopTrustedCertificates': {resolveDesktopTrustedCertificates: () => []},- };- const sandbox = {- console,- Buffer,- URL,- process,- setTimeout,- clearTimeout,- require: (specifier) => stubs[specifier] ?? require(specifier),- };- const context = vm.createContext(sandbox);-- const happyEyeballsModule = {exports: {}};- const happyEyeballsContext = vm.createContext({- ...sandbox,- exports: happyEyeballsModule.exports,- module: happyEyeballsModule,- });- vm.runInContext(happyEyeballsSource.code, happyEyeballsContext, {filename: happyEyeballsSource.path});- stubs['@electron/main/DesktopHappyEyeballs'] = happyEyeballsModule.exports;-- const ipAddressModule = {exports: {}};- const ipAddressContext = vm.createContext({...sandbox, exports: ipAddressModule.exports, module: ipAddressModule});- vm.runInContext(ipAddressSource.code, ipAddressContext, {filename: ipAddressSource.path});- stubs['@fluxer/ip_utils/src/IpAddress'] = ipAddressModule.exports;-- const outboundModule = {exports: {}};- sandbox.module = outboundModule;- sandbox.exports = outboundModule.exports;- vm.runInContext(outboundSource.code, context, {filename: outboundSource.path});- stubs['@electron/main/DesktopOutboundHTTP'] = outboundModule.exports;- if (registerOrigin) {- await outboundModule.exports.getDesktopOutboundHTTP().registerAnchoredOrigins({anchorOrigin: baseUrl, origins: []});- }-- const fileDownloadsModule = {exports: {}};- sandbox.module = fileDownloadsModule;- sandbox.exports = fileDownloadsModule.exports;- vm.runInContext(fileDownloadsSource.code, context, {filename: fileDownloadsSource.path});- return fileDownloadsModule.exports;-}--function destination() {- return join(mkdtempSync(join(tmpdir(), 'fluxer-download-test-')), 'Fluxer-linux-amd64.deb');-}--describe('downloadFile checksum verification', () => {- test('keeps the file when the bytes match the published sha256', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await downloadFile(`${baseUrl}/payload`, destPath, {sha256: PAYLOAD_SHA256});-- assert.equal(readFileSync(destPath).equals(PAYLOAD), true);- });-- test('accepts an uppercase published sha256', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await downloadFile(`${baseUrl}/payload`, destPath, {sha256: PAYLOAD_SHA256.toUpperCase()});-- assert.equal(readFileSync(destPath).equals(PAYLOAD), true);- });-- test('verifies the bytes that survive a redirect', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await downloadFile(`${baseUrl}/redirect`, destPath, {sha256: PAYLOAD_SHA256});-- assert.equal(readFileSync(destPath).equals(PAYLOAD), true);- });-- test('deletes the download and reports both digests when the bytes do not match', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await assert.rejects(downloadFile(`${baseUrl}/corrupt`, destPath, {sha256: PAYLOAD_SHA256}), (error) => {- assert.equal(error.name, 'DownloadChecksumError');- assert.match(error.message, new RegExp(PAYLOAD_SHA256));- assert.match(error.message, new RegExp(CORRUPT_SHA256));- return true;- });-- assert.equal(existsSync(destPath), false);- });-- test('leaves nothing behind when an earlier file sits at the destination', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();- writeFileSync(destPath, Buffer.from('an older download'), {mode: 0o755});-- await assert.rejects(downloadFile(`${baseUrl}/corrupt`, destPath, {sha256: PAYLOAD_SHA256}));-- assert.equal(existsSync(destPath), false);- });-- test('refuses an empty body when a checksum was published', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await assert.rejects(downloadFile(`${baseUrl}/empty`, destPath, {sha256: PAYLOAD_SHA256}), (error) => {- assert.equal(error.name, 'DownloadChecksumError');- assert.match(error.message, new RegExp(EMPTY_SHA256));- return true;- });-- assert.equal(existsSync(destPath), false);- });-- test('refuses a malformed checksum before asking for any bytes', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();- const requestsBefore = requests;-- await assert.rejects(downloadFile(`${baseUrl}/payload`, destPath, {sha256: 'deb-2026.909.202036'}), (error) => {- assert.equal(error.message, 'Download checksum is malformed');- return true;- });-- assert.equal(requests, requestsBefore);- assert.equal(existsSync(destPath), false);- });-- test('downloads without verifying when the feed published no checksum', async () => {- const {downloadFile} = await loadFileDownloads();- const destPath = destination();-- await downloadFile(`${baseUrl}/corrupt`, destPath, {sha256: null});-- assert.equal(readFileSync(destPath).equals(CORRUPT), true);- });-- test('refuses a non-public address that no registered instance vouches for', async () => {- const {downloadFile} = await loadFileDownloads({registerOrigin: false});- const destPath = destination();- const requestsBefore = requests;-- await assert.rejects(downloadFile(`${baseUrl}/payload`, destPath, {sha256: PAYLOAD_SHA256}));-- assert.equal(requests, requestsBefore);- assert.equal(existsSync(destPath), false);- });-});diff --git a/fluxer_desktop/src/main/LocalAppCsp.test.mjs b/fluxer_desktop/src/main/LocalAppCsp.test.mjsdeleted file mode 100644index 513eeab3a..000000000--- a/fluxer_desktop/src/main/LocalAppCsp.test.mjs+++ /dev/null@@ -1,129 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import path from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub, REPOSITORY_ROOT} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {buildLocalAppCSP} = await import('@electron/main/LocalAppCSP');-const {randomLocalAppCSPNonce, rewriteLocalAppIndexHTML} = await import('@electron/main/LocalAppIndexHTML');--const DESKTOP_GOLDEN = [- "default-src 'self'",- "script-src 'self' 'nonce-NONCE' 'wasm-unsafe-eval' blob: https://*.fluxer.app",- "style-src 'self' 'unsafe-inline' https://*.fluxer.app https://fonts.googleapis.com https://api.fonts.coollabs.io",- "img-src 'self' blob: data: https://*.fluxer.app https://i.ytimg.com https://*.youtube.com https://*.fluxer.media https://fluxer.media https: http://localhost:* http://*.localhost:* http://127.0.0.1:*",- "media-src 'self' blob: https://*.fluxer.app https://*.youtube.com https://*.fluxer.media https://fluxer.media https: data: http://localhost:* http://*.localhost:* http://127.0.0.1:*",- "font-src 'self' data: https://*.fluxer.app https://fonts.gstatic.com https://api.fonts.coollabs.io",- "connect-src 'self' blob: data: https://*.fluxer.app wss://*.fluxer.app https://*.fluxer.media wss://*.fluxer.media https://fluxer-uploads.ewr1.vultrobjects.com https://fluxerstatus.com https://fluxer.media https: wss: http://localhost:* http://*.localhost:* http://127.0.0.1:*",- "frame-src 'self' https://www.youtube.com/embed/ https://www.youtube.com/s/player/",- "worker-src 'self' blob: https://*.fluxer.app",- "manifest-src 'self' https://*.fluxer.app",- "object-src 'none'",- "base-uri 'self'",- "frame-ancestors 'none'",-].join('; ');--function desktopPolicy() {- return buildLocalAppCSP({nonce: 'NONCE'});-}--function directive(policy, name) {- const found = policy.split('; ').find((entry) => entry.startsWith(`${name} `));- assert.ok(found != null, `missing directive ${name}`);- return found.slice(name.length + 1).split(' ');-}--describe('the local desktop CSP', () => {- test('the policy matches the desktop builder byte for byte', () => {- assert.equal(desktopPolicy(), DESKTOP_GOLDEN);- });-});--describe('the desktop ceiling widens without displacing self', () => {- test("'self' survives the ceiling in img-src, media-src and connect-src", () => {- for (const name of ['img-src', 'media-src', 'connect-src']) {- assert.equal(directive(desktopPolicy(), name)[0], "'self'", `${name} lost 'self'`);- }- });-- test('connect-src carries https:, wss: and blob:', () => {- const connect = directive(desktopPolicy(), 'connect-src');- for (const source of ['https:', 'wss:', 'blob:', 'data:']) {- assert.ok(connect.includes(source), `connect-src missing ${source}`);- }- });-- test('img-src and media-src carry data: and blob: for theme files and audio worklets', () => {- for (const name of ['img-src', 'media-src']) {- const sources = directive(desktopPolicy(), name);- assert.ok(sources.includes('data:'), `${name} missing data:`);- assert.ok(sources.includes('blob:'), `${name} missing blob:`);- }- });-- test('worker-src carries blob: for the LiveKit E2EE worker', () => {- assert.ok(directive(desktopPolicy(), 'worker-src').includes('blob:'));- });-- test('no directive allows a third-party captcha host', () => {- const policy = desktopPolicy();- assert.ok(!policy.includes('hcaptcha'), policy);- assert.ok(!policy.includes('challenges.cloudflare.com'), policy);- });-});--describe('cleartext self-hosted instances', () => {- test('loopback http instances load images and media on a cold start', () => {- for (const name of ['img-src', 'media-src', 'connect-src']) {- const sources = directive(desktopPolicy(), name);- assert.ok(sources.includes('http://localhost:*'), `${name} missing loopback`);- assert.ok(sources.includes('http://127.0.0.1:*'), `${name} missing loopback`);- }- });-- test('registered private http instance origins are granted, and nothing else is', () => {- const policy = buildLocalAppCSP({- nonce: 'NONCE',- cleartextInstanceOrigins: [- 'http://192.168.1.20:48090',- 'https://web.example',- 'http://[fd00::1]:8080',- 'http://nas.lan/path',- "http://evil'; script-src *",- ],- });- for (const name of ['img-src', 'media-src', 'connect-src']) {- const sources = directive(policy, name);- assert.ok(sources.includes('http://192.168.1.20:48090'), `${name} missing the instance`);- assert.ok(!sources.includes('https://web.example'));- assert.ok(!sources.some((source) => source.includes('fd00') || source.includes('nas.lan')));- }- assert.ok(!policy.includes('evil'), policy);- assert.ok(!directive(policy, 'script-src').some((source) => source.startsWith('http:')));- });-});--describe('the shipped index.html runs under the local CSP', () => {- const sourceIndex = readFileSync(path.join(REPOSITORY_ROOT, 'fluxer_app', 'index.html'), 'utf8');-- test('every inline script carries the nonce the policy grants', () => {- const nonce = randomLocalAppCSPNonce();- const html = rewriteLocalAppIndexHTML({html: sourceIndex, nonce, prebootTheme: null});- const policy = buildLocalAppCSP({nonce});- const grantedNonce = directive(policy, 'script-src')[1];- const inlineScriptTags = [...html.matchAll(/<script\b([^>]*)>/giu)]- .map((match) => match[1])- .filter((attributes) => !/\ssrc\s*=/iu.test(attributes));- assert.ok(inlineScriptTags.length > 0);- for (const attributes of inlineScriptTags) {- assert.equal(grantedNonce, `'nonce-${nonce}'`);- assert.ok(- attributes.includes(`nonce="${nonce}"`),- `inline script without the granted nonce: <script${attributes}>`,- );- }- });-});diff --git a/fluxer_desktop/src/main/LocalAppFileResolver.test.mjs b/fluxer_desktop/src/main/LocalAppFileResolver.test.mjsdeleted file mode 100644index d8f2c4c4a..000000000--- a/fluxer_desktop/src/main/LocalAppFileResolver.test.mjs+++ /dev/null@@ -1,538 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {mkdirSync, mkdtempSync, symlinkSync, writeFileSync} from 'node:fs';-import fsPromises, {rm} from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopLocalAppFiles, LocalAppResourceBudget} = await import('./LocalAppFileResolver.ts');--const REACTION_BURST_SIZE = 300;-const REWRITTEN_FILE_MAX_BYTES = 4 * 1024 * 1024;-const OPEN_SHELL_RESPONSES = 16;-const WAIT_GIVE_UP_MS = 250;-const LARGE_ASSET_BODY = 'x'.repeat(512 * 1024);--const temporaryRoots = [];--function createRoot(prefix) {- const root = mkdtempSync(path.join(os.tmpdir(), prefix));- temporaryRoots.push(root);- return root;-}--function createRendererRoot() {- const root = createRoot('local-app-renderer-');- mkdirSync(path.join(root, 'assets'));- mkdirSync(path.join(root, 'web'));- writeFileSync(path.join(root, 'index.html'), '<html lang="en"><head></head><body></body></html>');- writeFileSync(path.join(root, 'assets', 'deadbeefdeadbeef.js'), 'console.log(1)');- writeFileSync(path.join(root, 'assets', 'cafed00dcafed00d.css'), '');- writeFileSync(path.join(root, 'assets', 'f00dfacef00dface.js'), LARGE_ASSET_BODY);- writeFileSync(path.join(root, 'web', 'favicon-32x32.png'), 'png-bytes');- writeFileSync(path.join(root, 'manifest.json'), '{}');- return root;-}--const rendererRoot = createRendererRoot();-const outsideRoot = createRoot('local-app-outside-');-writeFileSync(path.join(outsideRoot, 'secret.txt'), 'secret');-symlinkSync(path.join(outsideRoot, 'secret.txt'), path.join(rendererRoot, 'escape.txt'));--const files = new DesktopLocalAppFiles({rendererRoot});--function resolvePath(pathname) {- return files.resolve(`fluxer-app://app${pathname}`);-}--function neverAborted() {- return new AbortController().signal;-}--async function drain(stream) {- let text = '';- for await (const chunk of stream) {- text += Buffer.from(chunk).toString('utf8');- }- return text;-}--function tick() {- return new Promise((resolve) => {- setImmediate(resolve);- });-}--const STILL_WAITING = Symbol('still-waiting');--async function settleOrGiveUp(promise) {- let timer;- const gaveUp = new Promise((resolve) => {- timer = setTimeout(() => resolve(STILL_WAITING), WAIT_GIVE_UP_MS);- });- promise.catch(() => {});- try {- return await Promise.race([promise, gaveUp]);- } finally {- clearTimeout(timer);- }-}--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--describe('renderer file resolution', () => {- test('extensionless routes fall back to index.html', async () => {- for (const pathname of ['/', '/channels/@me', '/login', '/settings/user']) {- const resolved = await resolvePath(pathname);- assert.equal(resolved.filePath, path.join(rendererRoot, 'index.html'), pathname);- }- });-- test('a dotted route segment still falls back to index.html, not 404', async () => {- for (const pathname of ['/invite/abc.def', '/users/1.2.3', '/theme/my.custom.theme']) {- const resolved = await resolvePath(pathname);- assert.equal(resolved.filePath, path.join(rendererRoot, 'index.html'), pathname);- }- });-- test('a present asset resolves to itself with the right metadata', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- assert.equal(resolved.type, 'file');- assert.equal(resolved.filePath, path.join(rendererRoot, 'assets', 'deadbeefdeadbeef.js'));- assert.equal(resolved.size, 14);- assert.equal(resolved.contentType, 'application/javascript; charset=utf-8');- assert.equal(resolved.cacheControl, 'public, max-age=31536000, immutable');- });-- test('a missing asset is 404, never the SPA shell', async () => {- const resolved = await resolvePath('/assets/missing.js');- assert.equal(resolved.type, 'not-found');- });-});--describe('renderer file resolution refuses to leave the bundle', () => {- test('path escapes in every encoding are blocked', async () => {- const escapes = [- '/..%2f..%2fetc%2fpasswd',- '/%2e%2e%2f%2e%2e%2fx',- '/..\\..\\x',- '/assets/..%5c..%5cx',- '/x%00.js',- '/C:\\x',- '/%ZZ',- ];- for (const pathname of escapes) {- const resolved = await resolvePath(pathname);- assert.equal(resolved.type, 'blocked', `${pathname} -> ${JSON.stringify(resolved)}`);- }- });-- test('a dot-segment path is normalised by the URL parser before it can escape', async () => {- const resolved = await resolvePath('/../etc/passwd');- assert.equal(resolved.filePath, path.join(rendererRoot, 'index.html'));- });-- test('a symlink pointing outside the bundle is not served', async () => {- const resolved = await resolvePath('/escape.txt');- assert.equal(resolved.type, 'not-found');- });-- test('a request that is not on the local app origin is blocked', async () => {- assert.equal((await files.resolve('https://web.fluxer.app/')).reason, 'invalid-origin');- assert.equal((await files.resolve('data:text/html,x')).reason, 'invalid-origin');- assert.equal((await files.resolve('fluxer-app://evil/')).reason, 'invalid-origin');- assert.equal((await files.resolve('fluxer-app://app:8080/')).reason, 'invalid-origin');- });-});--describe('renderer file reads', () => {- test('a served asset comes back byte for byte', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- const stream = await files.openStream(resolved.filePath, resolved.size, neverAborted());- assert.equal(await drain(stream), 'console.log(1)');- });-- test('an asset too large to buffer is streamed and still comes back whole', async () => {- const resolved = await resolvePath('/assets/f00dfacef00dface.js');- assert.equal(resolved.size, LARGE_ASSET_BODY.length);- const stream = await files.openStream(resolved.filePath, resolved.size, neverAborted());- assert.equal(await drain(stream), LARGE_ASSET_BODY);- });-- test('an empty asset is an empty body, not a failure', async () => {- const resolved = await resolvePath('/assets/cafed00dcafed00d.css');- assert.equal(resolved.size, 0);- const stream = await files.openStream(resolved.filePath, resolved.size, neverAborted());- assert.equal(await drain(stream), '');- });-- test('readForResponse hands back the bytes and enforces the size ceiling', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- const file = await files.readForResponse(resolved.filePath, 1024, neverAborted());- try {- assert.equal(file.contents.toString('utf8'), 'console.log(1)');- } finally {- file.release();- }- await assert.rejects(() => files.readForResponse(resolved.filePath, 4, neverAborted()), /exceeds 4 bytes/u);- });-- test('openStream streams the file and refuses a size that changed under it', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- const controller = new AbortController();- const stream = await files.openStream(resolved.filePath, resolved.size, controller.signal);- assert.equal(await drain(stream), 'console.log(1)');- await assert.rejects(- () => files.openStream(resolved.filePath, resolved.size + 1, controller.signal),- (error) => error.name === 'LocalRendererFileChangedDuringOpenError',- );- controller.abort();- await assert.rejects(() => files.openStream(resolved.filePath, resolved.size, controller.signal));- });-- test('a buffered body the renderer never reads is torn down when the request aborts', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- const controller = new AbortController();- const stream = await files.openStream(resolved.filePath, resolved.size, controller.signal);- controller.abort(new Error('renderer went away'));- await assert.rejects(() => drain(stream), /renderer went away/u);- });-- test('isIndexFile only matches the shell document', async () => {- assert.equal(files.isIndexFile(path.join(rendererRoot, 'index.html')), true);- assert.equal(files.isIndexFile(path.join(rendererRoot, 'manifest.json')), false);- });-- test('a symlinked path handed straight to a read never yields what it points at', async () => {- const symlinkPath = path.join(rendererRoot, 'escape.txt');- await assert.rejects(- () => files.readForResponse(symlinkPath, 1024, neverAborted()),- (error) => error.code === 'ELOOP',- 'readForResponse followed a symlink out of the bundle',- );- await assert.rejects(- () => files.openStream(symlinkPath, 'secret'.length, neverAborted()),- (error) => error.code === 'ELOOP',- 'openStream followed a symlink out of the bundle',- );- });-});--describe('a reaction burst is served rather than refused', () => {- test('every request of a burst far past the old in-flight ceiling gets its bytes', async () => {- const resolved = await resolvePath('/assets/deadbeefdeadbeef.js');- const signal = neverAborted();- const streams = await Promise.all(- Array.from({length: REACTION_BURST_SIZE}, () => files.openStream(resolved.filePath, resolved.size, signal)),- );- const bodies = await Promise.all(streams.map((stream) => drain(stream)));- assert.deepEqual(bodies, new Array(REACTION_BURST_SIZE).fill('console.log(1)'));- });-- test('a burst of shell rewrites is served one after another instead of being turned away', async () => {- const resolved = await resolvePath('/index.html');- const signal = neverAborted();- const bodies = await Promise.all(- Array.from({length: 32}, async () => {- const file = await files.readForResponse(resolved.filePath, REWRITTEN_FILE_MAX_BYTES, signal);- try {- return file.contents.toString('utf8');- } finally {- file.release();- }- }),- );- assert.deepEqual(bodies, new Array(32).fill('<html lang="en"><head></head><body></body></html>'));- });-- test('a shell rewrite never waits on shell responses that are still open', async () => {- const resolved = await resolvePath('/index.html');- const signal = neverAborted();- const open = [];- try {- for (let index = 0; index < OPEN_SHELL_RESPONSES; index += 1) {- const file = await settleOrGiveUp(files.readForResponse(resolved.filePath, REWRITTEN_FILE_MAX_BYTES, signal));- assert.notEqual(file, STILL_WAITING, `shell response ${index} was made to wait on the ones before it`);- open.push(file);- }- } finally {- for (const file of open) {- file.release();- }- }- assert.equal(open.length, OPEN_SHELL_RESPONSES);- });-- test('a shell document past the rewrite ceiling still fails loudly', async () => {- const resolved = await resolvePath('/index.html');- await assert.rejects(- () => files.readForResponse(resolved.filePath, 4, neverAborted()),- (error) => error.name === 'LocalRendererFileTooLargeError',- );- });-});--describe('the resource budget queues instead of refusing', () => {- test('a burst is admitted in order and never exceeds the limit', async () => {- const budget = new LocalAppResourceBudget(2);- const signal = neverAborted();- const admitted = [];- let peak = 0;- await Promise.all(- Array.from({length: 10}, (_unused, index) =>- budget.acquire(1, signal).then(async (permit) => {- admitted.push(index);- peak = Math.max(peak, budget.inUse);- await tick();- permit.release();- }),- ),- );- assert.deepEqual(admitted, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);- assert.equal(peak, 2);- assert.equal(budget.inUse, 0);- assert.equal(budget.waitingCount, 0);- });-- test('a reservation larger than the whole budget still runs once the budget frees up', async () => {- const budget = new LocalAppResourceBudget(4);- const signal = neverAborted();- const held = await budget.acquire(4, signal);- const oversized = budget.acquire(16, signal);- held.release();- const permit = await oversized;- assert.equal(budget.inUse, 4);- permit.release();- assert.equal(budget.inUse, 0);- });-- test('a waiter that aborts leaves the queue and reserves nothing', async () => {- const budget = new LocalAppResourceBudget(1);- const held = await budget.acquire(1, neverAborted());- const controller = new AbortController();- const queued = budget.acquire(1, controller.signal);- assert.equal(budget.waitingCount, 1);- controller.abort(new Error('renderer went away'));- await assert.rejects(() => queued, /renderer went away/u);- assert.equal(budget.waitingCount, 0);- assert.equal(budget.inUse, 1);- held.release();- assert.equal(budget.inUse, 0);- });-- test('a waiter aborted in the same turn it is admitted hands its permit straight back', async () => {- const budget = new LocalAppResourceBudget(1);- const held = await budget.acquire(1, neverAborted());- const controller = new AbortController();- controller.signal.addEventListener('abort', () => held.release());- const queued = budget.acquire(1, controller.signal);- controller.abort(new Error('renderer went away'));- await assert.rejects(() => queued, /renderer went away/u);- assert.equal(budget.inUse, 0);- assert.equal(budget.waitingCount, 0);- const permit = await budget.acquire(1, neverAborted());- assert.equal(budget.inUse, 1);- permit.release();- });-- test('an acquire that is already aborted never joins the queue', async () => {- const budget = new LocalAppResourceBudget(1);- const controller = new AbortController();- controller.abort(new Error('gone'));- await assert.rejects(() => budget.acquire(1, controller.signal), /gone/u);- assert.equal(budget.inUse, 0);- assert.equal(budget.waitingCount, 0);- });-- test('a waiter that aborts wakes the waiter queued behind it', async () => {- const budget = new LocalAppResourceBudget(10);- const kept = await budget.acquire(5, neverAborted());- const released = await budget.acquire(5, neverAborted());- const controller = new AbortController();- const blocked = budget.acquire(8, controller.signal);- const successor = budget.acquire(4, neverAborted());- released.release();- assert.equal(budget.waitingCount, 2);- controller.abort(new Error('renderer went away'));- await assert.rejects(() => blocked, /renderer went away/u);- const permit = await settleOrGiveUp(successor);- assert.notEqual(permit, STILL_WAITING, 'the successor was never woken after the aborted waiter left');- assert.equal(budget.inUse, 9);- permit.release();- kept.release();- assert.equal(budget.inUse, 0);- assert.equal(budget.waitingCount, 0);- });-- test('a nonsensical reservation is a real error, not a capacity refusal', async () => {- const budget = new LocalAppResourceBudget(4);- await assert.rejects(() => budget.acquire(0, neverAborted()), /not a positive integer/u);- await assert.rejects(() => budget.acquire(1.5, neverAborted()), /not a positive integer/u);- });-});--describe('a renderer root with no index.html', () => {- test('rejects with MissingLocalRendererIndexError, and the rejection is memoised', async () => {- const emptyRoot = createRoot('local-app-empty-');- const emptyFiles = new DesktopLocalAppFiles({rendererRoot: emptyRoot});- const isMissingIndex = (error) => error.name === 'MissingLocalRendererIndexError';- await assert.rejects(() => emptyFiles.resolve('fluxer-app://app/'), isMissingIndex);- writeFileSync(path.join(emptyRoot, 'index.html'), '<html lang="en"></html>');- await assert.rejects(() => emptyFiles.resolve('fluxer-app://app/'), isMissingIndex);- });-});--describe('a renderer root probe that fails', () => {- test('is retried on the next request instead of poisoning every later one', async () => {- const root = createRendererRoot();- const indexPath = path.join(root, 'index.html');- const probed = new DesktopLocalAppFiles({rendererRoot: root});- const lstat = fsPromises.lstat;- let failed = false;- fsPromises.lstat = async (target, ...rest) => {- if (target === indexPath && !failed) {- failed = true;- throw Object.assign(new Error('too many open files'), {code: 'EMFILE'});- }- return await lstat(target, ...rest);- };- try {- await assert.rejects(- () => probed.resolve('fluxer-app://app/channels/@me'),- (error) => error.code === 'EMFILE',- );- const resolved = await probed.resolve('fluxer-app://app/channels/@me');- assert.equal(resolved.filePath, indexPath);- } finally {- fsPromises.lstat = lstat;- }- });-});--const moduleStoreRoot = createRoot('local-app-modules-');-const moduleDirectory = path.join(moduleStoreRoot, 'store', 'fluxer_renderer', 'b'.repeat(64));-mkdirSync(path.join(moduleDirectory, 'assets'), {recursive: true});-writeFileSync(path.join(moduleDirectory, 'assets', 'cafebabecafebabe.wasm'), 'wasm-bytes');-writeFileSync(path.join(moduleDirectory, 'assets', 'deadbeefdeadbeef.js'), 'console.log(2)');-writeFileSync(path.join(moduleDirectory, 'index.html'), '<html lang="en"><body>module</body></html>');-symlinkSync(path.join(outsideRoot, 'secret.txt'), path.join(moduleDirectory, 'assets', 'aaaaaaaabbbbbbbb.css'));--const siblingStoreRoot = `${moduleStoreRoot}-sibling`;-temporaryRoots.push(siblingStoreRoot);-mkdirSync(siblingStoreRoot);-writeFileSync(path.join(siblingStoreRoot, 'secret.txt'), 'sibling-secret');--function moduleIndexEntries() {- return [- ['assets/cafebabecafebabe.wasm', path.join(moduleDirectory, 'assets', 'cafebabecafebabe.wasm')],- ['assets/deadbeefdeadbeef.js', path.join(moduleDirectory, 'assets', 'deadbeefdeadbeef.js')],- ['assets/aaaaaaaabbbbbbbb.css', path.join(moduleDirectory, 'assets', 'aaaaaaaabbbbbbbb.css')],- ['index.html', path.join(moduleDirectory, 'index.html')],- ];-}--function createModuleFiles(entries = moduleIndexEntries()) {- const moduleFiles = new DesktopLocalAppFiles({rendererRoot: createRendererRoot()});- moduleFiles.setModuleIndex({root: moduleStoreRoot, files: new Map(entries)});- return moduleFiles;-}--describe('the module root chain', () => {- test('a committed module file wins over the asar copy', async () => {- const moduleFiles = createModuleFiles();- const resolved = await moduleFiles.resolve('fluxer-app://app/assets/deadbeefdeadbeef.js');- assert.equal(resolved.type, 'file');- assert.equal(resolved.filePath, path.join(moduleDirectory, 'assets', 'deadbeefdeadbeef.js'));- assert.equal(resolved.size, 14);- assert.equal(resolved.contentType, 'application/javascript; charset=utf-8');- const stream = await moduleFiles.openStream(resolved.filePath, resolved.size, neverAborted());- assert.equal(await drain(stream), 'console.log(2)');- });-- test('a store asset is cached from its resolved path, not its request path', async () => {- const moduleFiles = createModuleFiles();- const resolved = await moduleFiles.resolve('fluxer-app://app/assets/cafebabecafebabe.wasm');- assert.equal(resolved.filePath, path.join(moduleDirectory, 'assets', 'cafebabecafebabe.wasm'));- assert.equal(resolved.cacheControl, 'public, max-age=31536000, immutable');- assert.equal(resolved.contentType, 'application/wasm');- assert.equal(resolved.size, 10);- });-- test('a missing module asset is 404, never the SPA shell', async () => {- const moduleFiles = createModuleFiles();- for (const pathname of ['/assets/missing.wasm', '/assets/missing.js', '/assets/missing.woff2']) {- const resolved = await moduleFiles.resolve(`fluxer-app://app${pathname}`);- assert.equal(resolved.type, 'not-found', pathname);- assert.equal(resolved.filePath, undefined, pathname);- }- });-- test('a module entry whose file is gone falls back to the asar copy', async () => {- const rendererRoot = createRendererRoot();- const moduleFiles = new DesktopLocalAppFiles({rendererRoot});- moduleFiles.setModuleIndex({- root: moduleStoreRoot,- files: new Map([['assets/deadbeefdeadbeef.js', path.join(moduleDirectory, 'assets', 'ghost.js')]]),- });- const resolved = await moduleFiles.resolve('fluxer-app://app/assets/deadbeefdeadbeef.js');- assert.equal(resolved.filePath, path.join(rendererRoot, 'assets', 'deadbeefdeadbeef.js'));- assert.equal(resolved.size, 14);- });-- test('a module entry pointing outside the store root is blocked', async () => {- const moduleFiles = createModuleFiles([['evil.txt', path.join(outsideRoot, 'secret.txt')]]);- const resolved = await moduleFiles.resolve('fluxer-app://app/evil.txt');- assert.equal(resolved.type, 'blocked');- assert.equal(resolved.reason, 'path-escape');- });-- test('a module entry in a sibling directory that only shares the store root name prefix is blocked', async () => {- const moduleFiles = createModuleFiles([['evil.txt', path.join(siblingStoreRoot, 'secret.txt')]]);- const resolved = await moduleFiles.resolve('fluxer-app://app/evil.txt');- assert.equal(resolved.type, 'blocked');- assert.equal(resolved.reason, 'path-escape');- });-- test('a symlinked module file is not served and does not become the SPA shell', async () => {- const moduleFiles = createModuleFiles();- const resolved = await moduleFiles.resolve('fluxer-app://app/assets/aaaaaaaabbbbbbbb.css');- assert.equal(resolved.type, 'not-found');- });-- test('request path hardening still runs when an index is installed', async () => {- const moduleFiles = createModuleFiles();- for (const pathname of ['/x%00.js', '/..%2f..%2fetc%2fpasswd', '/assets/..%5c..%5cx']) {- const resolved = await moduleFiles.resolve(`fluxer-app://app${pathname}`);- assert.equal(resolved.type, 'blocked', pathname);- }- });-- test('the committed module supplies index.html for the shell and for SPA routes', async () => {- const moduleFiles = createModuleFiles();- for (const pathname of ['/', '/index.html', '/channels/@me', '/invite/abc.def']) {- const resolved = await moduleFiles.resolve(`fluxer-app://app${pathname}`);- assert.equal(resolved.filePath, path.join(moduleDirectory, 'index.html'), pathname);- }- });-- test('clearing the module index restores the asar chain', async () => {- const rendererRoot = createRendererRoot();- const moduleFiles = new DesktopLocalAppFiles({rendererRoot});- moduleFiles.setModuleIndex({root: moduleStoreRoot, files: new Map(moduleIndexEntries())});- moduleFiles.setModuleIndex(null);- const resolved = await moduleFiles.resolve('fluxer-app://app/assets/deadbeefdeadbeef.js');- assert.equal(resolved.filePath, path.join(rendererRoot, 'assets', 'deadbeefdeadbeef.js'));- const route = await moduleFiles.resolve('fluxer-app://app/channels/@me');- assert.equal(route.filePath, path.join(rendererRoot, 'index.html'));- });-});diff --git a/fluxer_desktop/src/main/LocalAppIndexHtml.test.mjs b/fluxer_desktop/src/main/LocalAppIndexHtml.test.mjsdeleted file mode 100644index adb8872b7..000000000--- a/fluxer_desktop/src/main/LocalAppIndexHtml.test.mjs+++ /dev/null@@ -1,105 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {existsSync, readFileSync} from 'node:fs';-import path from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub, REPOSITORY_ROOT} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {randomLocalAppCSPNonce, rewriteLocalAppIndexHTML} = await import('@electron/main/LocalAppIndexHTML');--const SOURCE_INDEX_PATH = path.join(REPOSITORY_ROOT, 'fluxer_app', 'index.html');-const BUILT_INDEX_PATH = path.join(REPOSITORY_ROOT, 'fluxer_app', 'dist', 'index.html');-const SOURCE_INDEX = readFileSync(SOURCE_INDEX_PATH, 'utf8');-const MINIFIED_INDEX = SOURCE_INDEX.replaceAll(/<!--[\s\S]*?-->/gu, '');--const BASE_INPUT = {- nonce: 'aabbccddeeff00112233445566778899',- prebootTheme: null,-};--function inject(overrides = {}) {- return rewriteLocalAppIndexHTML({html: SOURCE_INDEX, ...BASE_INPUT, ...overrides});-}--describe('local app rewriting of the shipped index.html', () => {- test('every CSP nonce placeholder is substituted', () => {- const html = inject();- const placeholderCount = SOURCE_INDEX.split('nonce="{{CSP_NONCE_PLACEHOLDER}}"').length - 1;- assert.ok(!html.includes('{{CSP_NONCE_PLACEHOLDER}}'));- assert.ok(placeholderCount > 0);- assert.equal(html.split(`nonce="${BASE_INPUT.nonce}"`).length - 1, placeholderCount);- });-- test('the static CDN placeholder becomes a root-relative path', () => {- const html = inject();- assert.ok(!html.includes('{{STATIC_CDN_ENDPOINT}}'));- assert.ok(html.includes('href="/web/favicon-32x32.png"'));- assert.ok(html.includes('href="/web/apple-touch-icon.png"'));- });-- test('does not inject scripts', () => {- const html = inject();- assert.equal(html.split('<script').length, SOURCE_INDEX.split('<script').length);- });-});--describe('local app rewriting of production-shaped documents', () => {- test('a minified document remains injection-free', () => {- const html = rewriteLocalAppIndexHTML({html: MINIFIED_INDEX, ...BASE_INPUT});- assert.ok(!html.includes('{{CSP_NONCE_PLACEHOLDER}}'));- assert.ok(!html.includes('{{STATIC_CDN_ENDPOINT}}'));- assert.equal(html.split('<script').length, MINIFIED_INDEX.split('<script').length);- assert.ok(html.includes('<head>'), 'the opening head tag must survive');- });-- test('a document with no head does not receive an injected script', () => {- const html = rewriteLocalAppIndexHTML({html: '<html lang="en"><body></body></html>', ...BASE_INPUT});- assert.equal(html, '<html lang="en"><body></body></html>');- });-- test('the real built dist/index.html remains injection-free', {- skip: existsSync(BUILT_INDEX_PATH) ? false : 'fluxer_app/dist is not built in this working tree',- }, () => {- const built = readFileSync(BUILT_INDEX_PATH, 'utf8');- const html = rewriteLocalAppIndexHTML({html: built, ...BASE_INPUT});- assert.ok(!html.includes('{{CSP_NONCE_PLACEHOLDER}}'));- assert.ok(!html.includes('{{STATIC_CDN_ENDPOINT}}'));- assert.equal(html.split('<script').length, built.split('<script').length);- });-});--describe('the preboot theme stamp', () => {- test('a safe theme token is stamped onto the html element', () => {- assert.ok(inject({prebootTheme: 'dark'}).includes('<html lang="en" class="theme-dark">'));- });-- test('no theme means no class attribute is added', () => {- assert.ok(!inject({prebootTheme: null}).includes('class="theme-'));- });-- test('a hostile theme token is refused rather than escaped', () => {- const html = inject({prebootTheme: 'dark"><script>alert(1)</script>'});- assert.ok(!html.includes('alert(1)'));- assert.ok(!html.includes('class="theme-'));- });-- test('an existing class attribute is never overwritten', () => {- const html = rewriteLocalAppIndexHTML({- html: '<html lang="en" class="preset"><head></head></html>',- ...BASE_INPUT,- prebootTheme: 'light',- });- assert.ok(html.includes('class="preset"'));- assert.ok(!html.includes('theme-light'));- });-});--describe('the CSP nonce generator', () => {- test('is 16 random bytes hex, matching generate_nonce in csp.rs', () => {- const nonce = randomLocalAppCSPNonce();- assert.match(nonce, /^[0-9a-f]{32}$/u);- assert.notEqual(nonce, randomLocalAppCSPNonce());- });-});diff --git a/fluxer_desktop/src/main/LocalAppInstanceKeyAgreement.test.mjs b/fluxer_desktop/src/main/LocalAppInstanceKeyAgreement.test.mjsdeleted file mode 100644index f004e3544..000000000--- a/fluxer_desktop/src/main/LocalAppInstanceKeyAgreement.test.mjs+++ /dev/null@@ -1,76 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-installTestModuleStub(- '@app/features/app/config/Config',- `const unavailable = () => { throw new Error('Renderer build configuration is outside the instance-key test boundary'); };- export default Object.freeze({- get PUBLIC_BUILD_VERSION() { return unavailable(); },- get PUBLIC_RELEASE_CHANNEL() { return unavailable(); },- });`,-);-installTestModuleStub(- '@app/features/platform/state/PrebootNetworkHandoff',- 'export function takePrebootDiscoveryResponse() { return null; }',-);--const {localAppRuntimeInstanceKey} = await import('./LocalAppRuntimePlans.ts');-const {runtimeInstanceKey} = await import('../../../fluxer_app/src/features/app/state/InstanceSnapshotStore.ts');--const AGREED_KEYS = Object.freeze([- ['https://web.fluxer.app/api', 'https://web.fluxer.app/api'],- ['https://web.fluxer.app/api/', 'https://web.fluxer.app/api'],- ['https://web.fluxer.app/api//', 'https://web.fluxer.app/api'],- ['HTTPS://WEB.FLUXER.APP/api', 'https://web.fluxer.app/api'],- ['https://web.fluxer.app', 'https://web.fluxer.app'],- ['https://web.fluxer.app/', 'https://web.fluxer.app'],- [' https://web.fluxer.app/api ', 'https://web.fluxer.app/api'],- ['https://web.fluxer.app/API', 'https://web.fluxer.app/API'],- ['http://localhost:3000/api', 'http://localhost:3000/api'],- ['http://127.0.0.1:3000/api/', 'http://127.0.0.1:3000/api'],- ['https://user:[email protected]/api', null],- ['https://:[email protected]/api', null],- ['https://web.fluxer.app/api?x=1', null],- ['https://web.fluxer.app/api#f', null],- ['ftp://x/api', null],- ['fluxer-app://app/api', null],- ['', null],- [' ', null],- ['not a url', null],-]);--const ACCOUNT_STORAGE_KEY_SEPARATOR = '::';--describe('the instance key derivation agrees between the main process and the renderer', () => {- for (const [apiEndpoint, expected] of AGREED_KEYS) {- test(`${JSON.stringify(apiEndpoint)} keys as ${JSON.stringify(expected)} on both sides`, () => {- const main = localAppRuntimeInstanceKey(apiEndpoint);- const renderer = runtimeInstanceKey({apiEndpoint});-- assert.equal(main, expected, 'the main-process derivation drifted');- assert.equal(renderer, expected, 'the renderer derivation drifted');- assert.equal(main, renderer, 'the /api/<key> route and the renderer would disagree');- });- }-- test('every agreed key survives the account storage key it is concatenated into', () => {- const userId = '1234567890';- for (const [apiEndpoint] of AGREED_KEYS) {- const main = localAppRuntimeInstanceKey(apiEndpoint);- const renderer = runtimeInstanceKey({apiEndpoint});- if (main === null) {- assert.equal(renderer, null, apiEndpoint);- continue;- }- assert.equal(- `${main}${ACCOUNT_STORAGE_KEY_SEPARATOR}${userId}`,- `${renderer}${ACCOUNT_STORAGE_KEY_SEPARATOR}${userId}`,- apiEndpoint,- );- }- });-});diff --git a/fluxer_desktop/src/main/LocalAppMime.test.mjs b/fluxer_desktop/src/main/LocalAppMime.test.mjsdeleted file mode 100644index a1c24d836..000000000--- a/fluxer_desktop/src/main/LocalAppMime.test.mjs+++ /dev/null@@ -1,52 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {localAppCacheControl} = await import('./LocalAppMime.ts');-const {shouldRewriteLocalAppStaticMetadata} = await import('./LocalAppStaticMetadata.ts');--const IMMUTABLE = 'public, max-age=31536000, immutable';-const REVALIDATED = 'public, max-age=3600, must-revalidate';--describe('local app cache control', () => {- test('content-hashed assets are immutable', () => {- assert.equal(localAppCacheControl('/assets/deadbeefdeadbeef.js'), IMMUTABLE);- assert.equal(localAppCacheControl('/assets/c4fd91dc82f7db6f.css'), IMMUTABLE);- assert.equal(localAppCacheControl('/assets/main-c4fd91dc82f7db6f.js'), IMMUTABLE);- });-- test('the rewritten documents are never cached', () => {- assert.equal(localAppCacheControl('/index.html'), 'no-store');- assert.equal(localAppCacheControl('/manifest.json'), 'no-store');- assert.equal(localAppCacheControl('/browserconfig.xml'), 'no-store');- });-- test('icons under /web are revalidated, never immutable (stale icon after upgrade)', () => {- assert.equal(localAppCacheControl('/web/favicon-32x32.png'), REVALIDATED);- assert.equal(localAppCacheControl('/web/mstile-150x150.png'), REVALIDATED);- assert.equal(localAppCacheControl('/robots.txt'), REVALIDATED);- });-- test('an unhashed file inside /assets is not immutable', () => {- assert.equal(localAppCacheControl('/assets/fonts-NOTICE.txt'), REVALIDATED);- });-});--describe('the rewritten-file lists in LocalAppMime and LocalAppStaticMetadata agree', () => {- test('every rewritten static metadata file is served no-store', () => {- for (const fileName of ['manifest.json', 'browserconfig.xml']) {- assert.equal(shouldRewriteLocalAppStaticMetadata(fileName), true, fileName);- assert.equal(localAppCacheControl(`/${fileName}`), 'no-store', fileName);- assert.equal(localAppCacheControl(`/nested/${fileName}`), 'no-store', fileName);- }- });-- test('index.html is rewritten by the index path, not by the static metadata rewriter', () => {- assert.equal(shouldRewriteLocalAppStaticMetadata('index.html'), false);- assert.equal(localAppCacheControl('/index.html'), 'no-store');- });-});diff --git a/fluxer_desktop/src/main/LocalAppModuleServing.test.mjs b/fluxer_desktop/src/main/LocalAppModuleServing.test.mjsdeleted file mode 100644index a1570fec9..000000000--- a/fluxer_desktop/src/main/LocalAppModuleServing.test.mjs+++ /dev/null@@ -1,318 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {createHash} from 'node:crypto';-import {existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import zlib from 'node:zlib';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const BLOCK = 512;-const SHELL_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const SOURCE_SHA = 'a'.repeat(40);-const LOCAL_APP_SCHEME = 'fluxer-app';-const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable';-const MODULE_ONLY_ASSET = 'assets/deadbeefcafebabe.js';-const MODULE_ONLY_BODY = 'module-store renderer chunk';-const ASAR_ONLY_ASSET = 'assets/00000000feedface.js';-const ASAR_ONLY_BODY = 'asar renderer chunk';-const GRAMMAR_ONLY_ASSET = 'assets/grammars/rust.wasm';-const GRAMMAR_ONLY_BODY = 'on-demand rust grammar';--const temporaryRoots = [];--function createRoot(prefix) {- const root = mkdtempSync(path.join(os.tmpdir(), prefix));- temporaryRoots.push(root);- return root;-}--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--const appDataRoot = createRoot('local-app-module-appdata-');-const appPathRoot = createRoot('local-app-module-asar-');-const rendererRoot = path.join(appPathRoot, 'dist', 'renderer');-mkdirSync(path.join(rendererRoot, 'assets'), {recursive: true});-writeFileSync(path.join(rendererRoot, 'index.html'), '<html lang="en"><head></head><body>asar</body></html>');-writeFileSync(path.join(rendererRoot, ASAR_ONLY_ASSET), ASAR_ONLY_BODY);--const protocolHandlers = new Map();-const electronPaths = new Map([['appData', appDataRoot]]);--const registry = installElectronStub({- app: {- isReady: () => true,- getAppPath: () => appPathRoot,- getPath: (name) => electronPaths.get(name) ?? path.join(appDataRoot, name),- setPath: (name, value) => electronPaths.set(name, value),- getVersion: () => SHELL_VERSION,- },- protocol: {- registerSchemesAsPrivileged: () => undefined,- handle: (scheme, handler) => {- protocolHandlers.set(scheme, handler);- },- unhandle: (scheme) => {- protocolHandlers.delete(scheme);- },- isProtocolHandled: (scheme) => protocolHandlers.has(scheme),- },-});--const {configureUserDataPath} = await import('@electron/common/UserDataPath');-const {getModuleStoreRoot, ModuleStore} = await import('@electron/main/ModuleStore');-const {setCommittedModuleFiles} = await import('@electron/main/ModuleBootHandoff');-const {createOnDemandModuleInstaller} = await import('@electron/main/ModuleOnDemand');-const {getDesktopLocalAppAuthorization} = await import('@electron/main/LocalAppProtocolAuthorization');-const LOCAL_APP_PROTOCOL_MODULE_URL = new URL('./LocalAppProtocol.ts', import.meta.url).href;-const mainAppProtocol = await import(LOCAL_APP_PROTOCOL_MODULE_URL);-const bundledOnlyProtocol = await import(`${LOCAL_APP_PROTOCOL_MODULE_URL}?instance=bundled-only`);--function sha256(data) {- return createHash('sha256').update(data).digest('hex');-}--function octal(value, width) {- return `${value.toString(8).padStart(width - 1, '0')}\0`;-}--function ustarHeader(name, size) {- const header = Buffer.alloc(BLOCK);- header.write(name, 0, 100, 'utf8');- header.write(octal(0o644, 8), 100, 8, 'ascii');- header.write(octal(0, 8), 108, 8, 'ascii');- header.write(octal(0, 8), 116, 8, 'ascii');- header.write(octal(size, 12), 124, 12, 'ascii');- header.write(octal(0, 12), 136, 12, 'ascii');- header.write('0', 156, 1, 'ascii');- header.write('ustar\0', 257, 6, 'ascii');- header.write('00', 263, 2, 'ascii');- header.fill(0x20, 148, 156);- let sum = 0;- for (const byte of header) {- sum += byte;- }- header.write(octal(sum, 8), 148, 8, 'ascii');- return header;-}--function pad(size) {- const remainder = size % BLOCK;- return remainder === 0 ? Buffer.alloc(0) : Buffer.alloc(BLOCK - remainder);-}--function packModule(moduleName, entries) {- const files = entries.map(([relative, body]) => ({- path: relative,- sha256: sha256(Buffer.from(body, 'utf8')),- bytes: Buffer.byteLength(body, 'utf8'),- }));- const manifest = Buffer.from(- `${JSON.stringify(- {- module: moduleName,- build_version: SHELL_VERSION,- release_channel: RELEASE_CHANNEL,- source_sha: SOURCE_SHA,- files,- },- null,- '\t',- )}\n`,- 'utf8',- );- const chunks = [ustarHeader('module.json', manifest.length), manifest, pad(manifest.length)];- for (const [relative, body] of entries) {- const payload = Buffer.from(body, 'utf8');- chunks.push(ustarHeader(`files/${relative}`, payload.length), payload, pad(payload.length));- }- chunks.push(Buffer.alloc(BLOCK * 2));- const tar = Buffer.concat(chunks);- const packed = zlib.brotliCompressSync(tar, {- params: {[zlib.constants.BROTLI_PARAM_QUALITY]: 5, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: tar.length},- });- return {module: moduleName, packed, sha256: sha256(packed)};-}--function streamOf(buffer) {- return {- offset: 0,- chunks: (async function* stream() {- for (let offset = 0; offset < buffer.length; offset += 4096) {- yield buffer.subarray(offset, Math.min(offset + 4096, buffer.length));- }- })(),- };-}--const userData = configureUserDataPath();-const authorization = getDesktopLocalAppAuthorization();--const rendererWebContents = {id: 1, isDestroyed: () => false, once: () => undefined};-const rendererFrame = {- processId: 1,- routingId: 1,- url: `${LOCAL_APP_SCHEME}://app/`,- origin: `${LOCAL_APP_SCHEME}://app`,- detached: false,- parent: null,- isDestroyed: () => false,- owner: rendererWebContents,-};-rendererFrame.top = rendererFrame;-rendererWebContents.mainFrame = rendererFrame;-registry.contents.set(rendererWebContents.id, rendererWebContents);-registry.frames.set(`${rendererFrame.processId}:${rendererFrame.routingId}`, rendererFrame);-authorization.authorize(rendererWebContents);--function requestAsset(pathname) {- const url = `${LOCAL_APP_SCHEME}://app/${pathname}`;- const headers = authorization.applyRequestHeaders(- {url, resourceType: 'script', frame: rendererFrame, webContentsId: rendererWebContents.id},- {},- );- const handler = protocolHandlers.get(LOCAL_APP_SCHEME);- assert.ok(handler != null, 'no protocol handler is registered');- return handler(new Request(url, {headers}));-}--async function commitRendererModule() {- const store = await ModuleStore.open({- root: getModuleStoreRoot(userData.base),- shellVersion: SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- });- const packaged = packModule('fluxer_renderer', [- [MODULE_ONLY_ASSET, MODULE_ONLY_BODY],- ['index.html', '<html lang="en"><head></head><body>module</body></html>'],- ]);- await store.installModule({- module: packaged.module,- sha256: packaged.sha256,- download: () => streamOf(packaged.packed),- });- await store.commit({fluxer_renderer: packaged.sha256});- return {store, sha256: packaged.sha256};-}--describe('the committed module index reaches the renderer through the real protocol handler', () => {- test('with nothing committed the protocol serves the offline renderer untouched, the only path an offline build takes', async () => {- const bundledOnly = bundledOnlyProtocol.getDesktopLocalAppProtocol();- bundledOnly.register();- const response = await requestAsset(ASAR_ONLY_ASSET);- assert.equal(response.status, 200);- assert.equal(await response.text(), ASAR_ONLY_BODY);- const missing = await requestAsset(MODULE_ONLY_ASSET);- assert.equal(missing.status, 404);- await bundledOnlyProtocol.cleanupDesktopLocalAppProtocol();- assert.equal(protocolHandlers.has(LOCAL_APP_SCHEME), false);- });-- test('a committed module asset is served from the store with an immutable cache policy', async () => {- const {store, sha256: digest} = await commitRendererModule();- assert.equal(store.storeRoot, path.join(getModuleStoreRoot(userData.base), 'store'));-- setCommittedModuleFiles(store.storeRoot, await store.buildModuleIndex());-- mainAppProtocol.getDesktopLocalAppProtocol().register();-- const storePath = path.join(store.storeRoot, 'fluxer_renderer', digest, MODULE_ONLY_ASSET);- assert.equal(readFileSync(storePath, 'utf8'), MODULE_ONLY_BODY);- assert.equal(existsSync(path.join(rendererRoot, MODULE_ONLY_ASSET)), false);-- const response = await requestAsset(MODULE_ONLY_ASSET);- assert.equal(response.status, 200);- assert.equal(response.headers.get('Cache-Control'), IMMUTABLE_CACHE_CONTROL);- assert.equal(response.headers.get('Content-Type'), 'application/javascript; charset=utf-8');- assert.equal(response.headers.get('Content-Length'), String(Buffer.byteLength(MODULE_ONLY_BODY)));- assert.equal(await response.text(), MODULE_ONLY_BODY);- });-- test('an asset the module does not carry falls through to the offline renderer, which a modules build does not have', async () => {- const response = await requestAsset(ASAR_ONLY_ASSET);- assert.equal(response.status, 200);- assert.equal(await response.text(), ASAR_ONLY_BODY);- });-- test('a module committed after the handler registered is served on the very next request', async () => {- const missing = await requestAsset(GRAMMAR_ONLY_ASSET);- assert.equal(missing.status, 404);-- const store = await ModuleStore.open({- root: getModuleStoreRoot(userData.base),- shellVersion: SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- });- const packaged = packModule('fluxer_grammars', [[GRAMMAR_ONLY_ASSET, GRAMMAR_ONLY_BODY]]);- const install = createOnDemandModuleInstaller({- ensure: async (moduleName) => {- await store.installModule({- module: moduleName,- sha256: packaged.sha256,- download: () => streamOf(packaged.packed),- });- await store.commit({...store.getCommitted(), [moduleName]: packaged.sha256});- return {module: moduleName, status: 'installed'};- },- refresh: async () => {- setCommittedModuleFiles(store.storeRoot, await store.buildModuleIndex());- },- });-- assert.deepEqual(await install('fluxer_grammars'), {module: 'fluxer_grammars', status: 'installed'});- assert.equal(existsSync(path.join(rendererRoot, GRAMMAR_ONLY_ASSET)), false);-- const response = await requestAsset(GRAMMAR_ONLY_ASSET);- assert.equal(response.status, 200);- assert.equal(response.headers.get('Content-Type'), 'application/wasm');- assert.equal(await response.text(), GRAMMAR_ONLY_BODY);-- const renderer = await requestAsset(MODULE_ONLY_ASSET);- assert.equal(renderer.status, 200);- assert.equal(await renderer.text(), MODULE_ONLY_BODY);- });-- test('a background activation keeps serving the running build until the renderer reloads into the new one', async () => {- const store = await ModuleStore.open({- root: getModuleStoreRoot(userData.base),- shellVersion: SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- });- const live = {...store.getCommitted()};- const nextAsset = 'assets/next-renderer.js';- const packaged = packModule('fluxer_renderer', [- [nextAsset, 'next renderer'],- ['index.html', '<html lang="en"><head></head><body>next</body></html>'],- ]);- await store.installModule({- module: packaged.module,- sha256: packaged.sha256,- download: () => streamOf(packaged.packed),- });-- const activated = await store.activateMergedForRendererReload({fluxer_renderer: packaged.sha256});- assert.notEqual(activated, null);- assert.equal(store.getCommitted().fluxer_renderer, packaged.sha256);-- setCommittedModuleFiles(store.storeRoot, await store.buildModuleIndex(live));- const running = await requestAsset(MODULE_ONLY_ASSET);- assert.equal(running.status, 200);- assert.equal(await running.text(), MODULE_ONLY_BODY);- assert.equal((await requestAsset(nextAsset)).status, 404);-- setCommittedModuleFiles(store.storeRoot, await store.buildModuleIndex(activated.committed));- const reloaded = await requestAsset(nextAsset);- assert.equal(reloaded.status, 200);- assert.equal(await reloaded.text(), 'next renderer');- assert.equal((await requestAsset(MODULE_ONLY_ASSET)).status, 404);- });-});diff --git a/fluxer_desktop/src/main/LocalAppProtocol.test.mjs b/fluxer_desktop/src/main/LocalAppProtocol.test.mjsdeleted file mode 100644index 8dc3f52e8..000000000--- a/fluxer_desktop/src/main/LocalAppProtocol.test.mjs+++ /dev/null@@ -1,136 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import path from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub, REPOSITORY_ROOT} from './LocalAppTestSupport.test.mjs';--const DESKTOP_DIRECTORY = path.join(REPOSITORY_ROOT, 'fluxer_desktop');-const MODULE_URL = new URL('./LocalAppProtocol.ts', import.meta.url).href;--let appReady = true;-const registeredSchemes = [];-const handledSchemes = new Set();-let handleCalls = 0;--installElectronStub({- app: {- isReady: () => appReady,- getAppPath: () => DESKTOP_DIRECTORY,- getPath: () => path.join(DESKTOP_DIRECTORY, '.test-userdata'),- },- protocol: {- registerSchemesAsPrivileged: (schemes) => {- registeredSchemes.push(...schemes);- },- handle: (scheme) => {- handleCalls += 1;- handledSchemes.add(scheme);- },- unhandle: (scheme) => {- handledSchemes.delete(scheme);- },- isProtocolHandled: (scheme) => handledSchemes.has(scheme),- },-});--const bootstrapModule = await import(MODULE_URL);-const mainAppModule = await import(`${MODULE_URL}?instance=main-app`);-const {getDesktopOutboundHTTP} = await import('@electron/main/DesktopOutboundHTTP');--const REGISTERED_ORIGIN = 'http://127.0.0.1:7431';-const UNREGISTERED_ORIGIN = 'http://127.0.0.2:7432';--function runtimePlan(origin) {- return {- instanceKey: `${origin}/api`,- document: {},- selfHosted: true,- endpoints: {- apiEndpoint: `${origin}/api`,- apiPublicEndpoint: null,- webAppEndpoint: null,- mediaEndpoint: null,- staticCdnEndpoint: null,- uploadRelayEndpoint: null,- gatewayEndpoint: null,- inviteEndpoint: null,- giftEndpoint: null,- },- };-}--describe('registerSchemes', () => {- test('throws when the app is ready and the privileged scheme was never registered', () => {- appReady = true;- assert.throws(() => bootstrapModule.getDesktopLocalAppProtocol().registerSchemes(), {- name: 'LocalAppProtocolSchemeRegistrationOrderError',- });- assert.equal(registeredSchemes.length, 0);- });-- test('registers the privileged scheme once across repeated calls', () => {- appReady = false;- const protocolOwner = bootstrapModule.getDesktopLocalAppProtocol();- protocolOwner.registerSchemes();- protocolOwner.registerSchemes();- assert.equal(registeredSchemes.length, 1);- assert.equal(registeredSchemes[0].scheme, 'fluxer-app');- assert.equal(registeredSchemes[0].privileges.standard, true);- assert.equal(registeredSchemes[0].privileges.secure, true);- });-- test('is a no-op once the app is ready', () => {- appReady = true;- bootstrapModule.getDesktopLocalAppProtocol().registerSchemes();- assert.equal(registeredSchemes.length, 1);- });-- test('is a no-op for a separate module instance that loaded after the app was ready', () => {- appReady = true;- mainAppModule.getDesktopLocalAppProtocol().registerSchemes();- assert.equal(registeredSchemes.length, 1);- });-});--describe('register', () => {- test('takes ownership once and rejects a second owner', () => {- appReady = true;- const protocolOwner = bootstrapModule.getDesktopLocalAppProtocol();- protocolOwner.register();- assert.ok(handledSchemes.has('fluxer-app'));- protocolOwner.register();- assert.equal(handleCalls, 1);- assert.throws(() => mainAppModule.getDesktopLocalAppProtocol().register(), {- name: 'LocalAppProtocolHandlerOwnershipError',- });- });-});--describe('runtime plan admission', () => {- test('a plan naming an origin instance discovery never registered cannot be activated or cached', () => {- const protocolOwner = mainAppModule.getDesktopLocalAppProtocol();- const plan = runtimePlan(UNREGISTERED_ORIGIN);- const isUnregistered = {name: 'DesktopOutboundHTTPOriginNotRegisteredError'};-- assert.throws(() => protocolOwner.activateRuntimePlan(plan), isUnregistered);- assert.equal(protocolOwner.getActivePlan(), null);- assert.equal(protocolOwner.findPlanForRoute(plan.instanceKey), null);-- assert.throws(() => protocolOwner.cacheRuntimePlan(plan), isUnregistered);- assert.equal(protocolOwner.findPlanForRoute(plan.instanceKey), null);- });-- test('a plan whose origins were registered through discovery activates', async () => {- await getDesktopOutboundHTTP().registerAnchoredOrigins({anchorOrigin: REGISTERED_ORIGIN, origins: []});- const protocolOwner = mainAppModule.getDesktopLocalAppProtocol();- const plan = runtimePlan(REGISTERED_ORIGIN);-- protocolOwner.activateRuntimePlan(plan);- assert.equal(protocolOwner.getActivePlan(), plan);- assert.equal(protocolOwner.findPlanForRoute(plan.instanceKey), plan);-- protocolOwner.deactivateRuntimePlan();- assert.equal(protocolOwner.getActivePlan(), null);- });-});diff --git a/fluxer_desktop/src/main/LocalAppProtocolAuthorization.test.mjs b/fluxer_desktop/src/main/LocalAppProtocolAuthorization.test.mjsdeleted file mode 100644index a7e108ad3..000000000--- a/fluxer_desktop/src/main/LocalAppProtocolAuthorization.test.mjs+++ /dev/null@@ -1,308 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {beforeEach, describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const registry = installElectronStub();-const {DESKTOP_PROTOCOL_AUTHORIZATION_HEADER, DesktopLocalAppAuthorization, getDesktopLocalAppAuthorization} =- await import('@electron/main/LocalAppProtocolAuthorization');--const LOCAL_APP_ORIGIN = 'fluxer-app://app';--let nextWebContentsId = 1;-let nextRoutingId = 1;--function createWebContents() {- const id = nextWebContentsId;- nextWebContentsId += 1;- const contents = {- id,- destroyed: false,- mainFrame: null,- destroyedListeners: [],- isDestroyed() {- return this.destroyed;- },- once(event, listener) {- if (event === 'destroyed') {- this.destroyedListeners.push(listener);- }- return this;- },- destroy() {- this.destroyed = true;- for (const listener of this.destroyedListeners.splice(0)) {- listener();- }- },- };- registry.contents.set(id, contents);- return contents;-}--function createFrame(owner, {url, origin, parent = null}) {- const routingId = nextRoutingId;- nextRoutingId += 1;- const frame = {- processId: 1,- routingId,- url,- origin,- parent,- detached: false,- owner,- isDestroyed: () => false,- };- frame.top = parent == null ? frame : parent.top;- registry.frames.set(`1:${routingId}`, frame);- return frame;-}--function createMainFrame(owner, options) {- const frame = createFrame(owner, options);- owner.mainFrame = frame;- return frame;-}--function stampedValue(headers) {- return headers[DESKTOP_PROTOCOL_AUTHORIZATION_HEADER] ?? null;-}--let authorization;-let owner;-let mainFrame;--beforeEach(() => {- authorization = new DesktopLocalAppAuthorization();- owner = createWebContents();- mainFrame = createMainFrame(owner, {url: '', origin: 'null'});-});--describe('the boot navigation must be authorized, or the app 404s and never starts', () => {- test('the very first main-frame navigation is stamped even though the frame URL is still empty', () => {- authorization.authorize(owner);- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {Accept: '*/*'},- );- assert.notEqual(stampedValue(headers), null, 'the bootstrap navigation was not stamped');- assert.equal(headers.Accept, '*/*', 'other request headers must survive the stamp');- });-- test('an about:blank main frame is also a valid bootstrap frame', () => {- authorization.authorize(owner);- mainFrame.url = 'about:blank';- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/channels/@me', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- assert.notEqual(stampedValue(headers), null);- });-- test('the stamped value is exactly what the request handler accepts', async () => {- authorization.authorize(owner);- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- const request = new Request('fluxer-app://app/', {headers: {...headers}});- assert.equal(authorization.hasValidRequestAuthorization(request), true);- });-- test('a main-frame navigation to a reserved proxy path is never stamped', () => {- authorization.authorize(owner);- for (const url of ['fluxer-app://app/api/k/v1/users/@me', 'fluxer-app://app/proxy/k?url=https://evil.example']) {- const headers = authorization.applyRequestHeaders(- {url, resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- assert.equal(stampedValue(headers), null, url);- }- });-- test('a main-frame navigation from an unregistered WebContents is never stamped', () => {- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- assert.equal(stampedValue(headers), null);- });-- test('a sub-frame cannot claim the bootstrap branch', () => {- authorization.authorize(owner);- const child = createFrame(owner, {url: '', origin: 'null', parent: mainFrame});- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: child, webContentsId: owner.id},- {},- );- assert.equal(stampedValue(headers), null);- });-});--describe('subresource requests from a live app document', () => {- beforeEach(() => {- authorization.authorize(owner);- mainFrame.url = 'fluxer-app://app/channels/@me';- mainFrame.origin = LOCAL_APP_ORIGIN;- });-- test('XHR at the API route and asset loads are both stamped', () => {- for (const [url, resourceType] of [- ['fluxer-app://app/api/k/v1/users/@me', 'xhr'],- ['fluxer-app://app/proxy/k?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png', 'image'],- ['fluxer-app://app/assets/main.js', 'script'],- ]) {- const headers = authorization.applyRequestHeaders(- {url, resourceType, frame: mainFrame, webContentsId: owner.id},- {},- );- assert.notEqual(stampedValue(headers), null, url);- }- });-- test('an about:blank popout frame that inherited the app origin is stamped', () => {- const popout = createFrame(owner, {url: 'about:blank', origin: LOCAL_APP_ORIGIN});- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/api/k/v1/x', resourceType: 'xhr', frame: popout, webContentsId: owner.id},- {},- );- assert.notEqual(stampedValue(headers), null);- });-- test('an about:blank frame with a foreign origin is not stamped', () => {- const popout = createFrame(owner, {url: 'about:blank', origin: 'https://web.fluxer.app'});- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/api/k/v1/x', resourceType: 'xhr', frame: popout, webContentsId: owner.id},- {},- );- assert.equal(stampedValue(headers), null);- });-});--describe('the data: URL voice-debug window is a confused deputy and must be refused', () => {- test('a data: document carrying the privileged preload is never stamped', () => {- const sink = createWebContents();- const sinkFrame = createMainFrame(sink, {url: 'data:text/html,x', origin: 'null'});- authorization.authorize(owner);- authorization.authorize(sink);- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/api/k/v1/users/@me', resourceType: 'xhr', frame: sinkFrame, webContentsId: sink.id},- {},- );- assert.equal(stampedValue(headers), null);- });-});--describe('a renderer can never forge or exfiltrate the secret', () => {- test('a caller-supplied header is stripped before the decision, in any casing', () => {- authorization.authorize(owner);- mainFrame.url = 'data:text/html,x';- for (const name of [- DESKTOP_PROTOCOL_AUTHORIZATION_HEADER,- DESKTOP_PROTOCOL_AUTHORIZATION_HEADER.toLowerCase(),- DESKTOP_PROTOCOL_AUTHORIZATION_HEADER.toUpperCase(),- ]) {- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/api/k/v1/x', resourceType: 'xhr', frame: mainFrame, webContentsId: owner.id},- {[name]: 'forged'},- );- assert.deepEqual(Object.values(headers), [], `${name} survived`);- }- });-- test('a forged header on an outbound https request is stripped, so the secret cannot be smuggled', () => {- authorization.authorize(owner);- mainFrame.url = 'fluxer-app://app/channels/@me';- mainFrame.origin = LOCAL_APP_ORIGIN;- const headers = authorization.applyRequestHeaders(- {- url: 'https://evil.example/collect',- resourceType: 'xhr',- frame: mainFrame,- webContentsId: owner.id,- },- {'x-fluxer-desktop-protocol-authorization': 'forged', Accept: '*/*'},- );- assert.equal(stampedValue(headers), null);- assert.equal(headers['x-fluxer-desktop-protocol-authorization'], undefined);- assert.equal(headers.Accept, '*/*');- });-- test('a wrong or missing header value fails the handler check', () => {- assert.equal(- authorization.hasValidRequestAuthorization(- new Request('fluxer-app://app/', {headers: {[DESKTOP_PROTOCOL_AUTHORIZATION_HEADER]: 'wrong'}}),- ),- false,- );- assert.equal(authorization.hasValidRequestAuthorization(new Request('fluxer-app://app/')), false);- });-- test('two authorization instances never share a secret', () => {- const other = new DesktopLocalAppAuthorization();- other.authorize(owner);- authorization.authorize(owner);- const details = {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id};- const first = stampedValue(authorization.applyRequestHeaders(details, {}));- const second = stampedValue(other.applyRequestHeaders(details, {}));- assert.notEqual(first, null);- assert.notEqual(second, null);- assert.notEqual(first, second);- });-});--describe('registration hygiene', () => {- test('authorizing something that is not a live WebContents throws', () => {- const isInvalid = (error) => error.name === 'InvalidLocalAppWebContentsError';- assert.throws(() => authorization.authorize(null), isInvalid);- assert.throws(() => authorization.authorize({id: 999}), isInvalid);- const destroyed = createWebContents();- destroyed.destroyed = true;- assert.throws(() => authorization.authorize(destroyed), isInvalid);- });-- test('authorizing the same WebContents twice is idempotent', () => {- authorization.authorize(owner);- authorization.authorize(owner);- assert.equal(owner.destroyedListeners.length, 1, 'the second authorize registered a second destroyed listener');- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- assert.notEqual(stampedValue(headers), null);- });-- test('a recycled WebContents id never takes over the registration it collides with', () => {- authorization.authorize(owner);- const recycled = createWebContents();- registry.contents.delete(recycled.id);- recycled.id = owner.id;- registry.contents.set(owner.id, recycled);- assert.throws(- () => authorization.authorize(recycled),- (error) => error.name === 'InvalidLocalAppWebContentsError',- );- });-- test('a destroyed WebContents stops being authorized', () => {- authorization.authorize(owner);- owner.destroy();- const headers = authorization.applyRequestHeaders(- {url: 'fluxer-app://app/', resourceType: 'mainFrame', frame: mainFrame, webContentsId: owner.id},- {},- );- assert.equal(stampedValue(headers), null);- });-- test('malformed details never throw and never stamp', () => {- authorization.authorize(owner);- for (const details of [null, undefined, 'fluxer-app://app/', {}, {url: 42}, {url: 'fluxer-app://app/'}]) {- assert.deepEqual(Object.values(authorization.applyRequestHeaders(details, {})), []);- }- });-- test('the module singleton is stable', () => {- assert.equal(getDesktopLocalAppAuthorization(), getDesktopLocalAppAuthorization());- });-});diff --git a/fluxer_desktop/src/main/LocalAppProxyConcurrency.test.mjs b/fluxer_desktop/src/main/LocalAppProxyConcurrency.test.mjsdeleted file mode 100644index d7e97094d..000000000--- a/fluxer_desktop/src/main/LocalAppProxyConcurrency.test.mjs+++ /dev/null@@ -1,126 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {PassThrough, Readable} from 'node:stream';-import {describe, mock, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopLocalAppProxyClient, LocalAppProxyTraffic} = await import('./LocalAppProxyClient.ts');--const RENDERED_AVATAR_COUNT = 120;-const PARKED_MEDIA_BODY_COUNT = 200;-const RESOURCE_HEADERS_DEADLINE_MS = 30_000;--function tick() {- return new Promise((resolve) => {- setImmediate(resolve);- });-}--function avatarRequest(index, signal) {- return {- targetURL: `https://media.fluxer.app/avatars/${index}.webp`,- method: 'GET',- headers: new Headers(),- body: null,- signal,- acceptEncoding: null,- uploadId: null,- uploadTotalBytes: null,- };-}--function createUpstream({streamBodies}) {- const state = {started: [], aborted: 0};- const outboundHTTP = {- request: (request) =>- new Promise((resolve, reject) => {- const entry = {- url: request.url,- answer: () =>- resolve({- headers: {'content-type': 'image/webp'},- message: streamBodies ? new PassThrough() : Readable.from([Buffer.from('avatar-bytes')]),- status: 200,- statusText: 'OK',- url: new URL(request.url),- }),- };- state.started.push(entry);- request.signal.addEventListener(- 'abort',- () => {- state.aborted += 1;- reject(request.signal.reason);- },- {once: true},- );- }),- };- return {outboundHTTP, state};-}--describe('the local app proxy never queues a request behind another', () => {- test('every avatar of a fully rendered chat starts at once', async () => {- const {outboundHTTP, state} = createUpstream({streamBodies: false});- const client = new DesktopLocalAppProxyClient({outboundHTTP, traffic: LocalAppProxyTraffic.REMOTE_RESOURCE});- const renderer = new AbortController();-- const fetches = [];- for (let index = 0; index < RENDERED_AVATAR_COUNT; index += 1) {- fetches.push(client.fetch(avatarRequest(index, renderer.signal)));- }- await tick();- assert.equal(state.started.length, RENDERED_AVATAR_COUNT);-- for (const entry of state.started) {- entry.answer();- }- const texts = await Promise.all(fetches.map(async (fetch) => await (await fetch).text()));- assert.deepEqual(texts, new Array(RENDERED_AVATAR_COUNT).fill('avatar-bytes'));- });-- test('a media request starts at once while earlier response bodies sit unread', async () => {- const {outboundHTTP, state} = createUpstream({streamBodies: true});- const client = new DesktopLocalAppProxyClient({outboundHTTP, traffic: LocalAppProxyTraffic.REMOTE_RESOURCE});- const renderer = new AbortController();-- for (let index = 0; index < PARKED_MEDIA_BODY_COUNT; index += 1) {- const fetch = client.fetch(avatarRequest(index, renderer.signal));- await tick();- state.started.at(-1).answer();- assert.equal((await fetch).status, 200);- }-- const next = client.fetch(avatarRequest(PARKED_MEDIA_BODY_COUNT, renderer.signal));- await tick();- assert.equal(state.started.length, PARKED_MEDIA_BODY_COUNT + 1);- state.started.at(-1).answer();- assert.equal((await next).status, 200);- renderer.abort();- });-});--describe('media that a slow or silent self-host never answers is cut off', () => {- test('a silent upstream is aborted at the headers deadline', async () => {- mock.timers.enable({apis: ['setTimeout']});- try {- const {outboundHTTP, state} = createUpstream({streamBodies: false});- const client = new DesktopLocalAppProxyClient({outboundHTTP, traffic: LocalAppProxyTraffic.REMOTE_RESOURCE});- const renderer = new AbortController();- const silent = client.fetch(avatarRequest(0, renderer.signal));- silent.catch(() => {});- await tick();-- mock.timers.tick(RESOURCE_HEADERS_DEADLINE_MS);-- await assert.rejects(silent, (error) => error.name === 'LocalAppProxyResponseHeadersDeadlineError');- assert.equal(state.aborted, 1);- } finally {- mock.timers.reset();- }- });-});diff --git a/fluxer_desktop/src/main/LocalAppProxyHttpPolicy.test.mjs b/fluxer_desktop/src/main/LocalAppProxyHttpPolicy.test.mjsdeleted file mode 100644index 344fc1747..000000000--- a/fluxer_desktop/src/main/LocalAppProxyHttpPolicy.test.mjs+++ /dev/null@@ -1,416 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {- buildAPIRequestHeaders,- buildAPITargetURL,- buildProxyResponseHeaders,- LocalAppProxyCacheDefault,- buildRemoteResourceRequestHeaders,- isAllowedRemoteProxyTarget,- isSupportedRemoteResourceMethod,- localAppProxyNotFoundResponse,- readLocalAppUploadId,- readRequestContentLength,- remoteProxyTargetURL,- requestHasBody,-} = await import('@electron/main/LocalAppProxyHTTPPolicy');-const {DESKTOP_PROTOCOL_AUTHORIZATION_HEADER} = await import('@electron/main/LocalAppProtocolAuthorization');-const {LOCAL_APP_UPLOAD_ID_HEADER} = await import('@fluxer/desktop_ipc/src/LocalAppRouteContract');--function plan(overrides = {}) {- return {- instanceKey: 'https://api.fluxer.app',- document: {},- selfHosted: false,- degraded: false,- endpoints: {- apiEndpoint: 'https://api.fluxer.app',- apiPublicEndpoint: 'https://api.fluxer.app',- webAppEndpoint: 'https://web.fluxer.app',- mediaEndpoint: 'https://media.fluxer.app',- staticCdnEndpoint: 'https://cdn.fluxer.app',- uploadRelayEndpoint: 'https://media.fluxer.app/upload',- gatewayEndpoint: 'wss://gateway.fluxer.app',- inviteEndpoint: null,- giftEndpoint: null,- ...overrides,- },- };-}--function allowsRemoteResource(targetURL, runtimePlan = plan()) {- return isAllowedRemoteProxyTarget({method: 'GET', targetURL, plan: runtimePlan});-}--function allowsUploadRelay(targetURL, runtimePlan = plan()) {- return isAllowedRemoteProxyTarget({method: 'PUT', targetURL, plan: runtimePlan});-}--function headerNames(headers) {- return [...headers.keys()].sort();-}--describe('rewriting the local API path onto the instance API endpoint', () => {- const cases = [- ['https://api.fluxer.app', '/api/k/v1/users/@me?x=1', '/api/k', 'https://api.fluxer.app/v1/users/@me?x=1'],- ['https://h.example/base/', '/api/k/v1/x', '/api/k', 'https://h.example/base/v1/x'],- ['https://h.example/base', '/api/k/v1/x', '/api/k', 'https://h.example/base/v1/x'],- ['https://h.example/base', '/api/k', '/api/k', 'https://h.example/base/'],- ['https://h.example', '/api/k', '/api/k', 'https://h.example/'],- ['https://h.example/base//', '/api/k/v1/x', '/api/k', 'https://h.example/base/v1/x'],- ];-- for (const [apiEndpoint, requestPath, localPathPrefix, expected] of cases) {- test(`${apiEndpoint} + ${requestPath}`, () => {- const requestURL = `fluxer-app://app${requestPath}`;- assert.equal(buildAPITargetURL({apiEndpoint, requestURL, localPathPrefix}), expected);- });- }-- test('the renderer contributes only path and query, never the host', () => {- const target = buildAPITargetURL({- apiEndpoint: 'https://api.fluxer.app',- requestURL: 'fluxer-app://app/api/k/..%2F..%2Fv1/x?y=1',- localPathPrefix: '/api/k',- });- assert.equal(new URL(target).origin, 'https://api.fluxer.app');- });-});--describe('outbound API request headers', () => {- test('a non-GET carries the instance own web app origin, which MiddlewarePipeline requires', () => {- const headers = buildAPIRequestHeaders({- headers: new Headers({Origin: 'fluxer-app://app', Authorization: 'token'}),- method: 'POST',- origin: 'https://web.fluxer.app',- });- assert.equal(headers.get('Origin'), 'https://web.fluxer.app');- assert.equal(headers.get('Authorization'), 'token');- });-- test('a GET carries no Origin at all', () => {- const headers = buildAPIRequestHeaders({- headers: new Headers({Origin: 'fluxer-app://app'}),- method: 'GET',- origin: 'https://web.fluxer.app',- });- assert.equal(headers.get('Origin'), null);- });-- test('a renderer-supplied Origin can never survive, even when the plan has none', () => {- for (const method of ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']) {- const headers = buildAPIRequestHeaders({- headers: new Headers({Origin: 'https://web.fluxer.app'}),- method,- origin: null,- });- assert.equal(headers.get('Origin'), null, method);- }- });-- test('requestHasBody decides which methods get an Origin', () => {- assert.equal(requestHasBody('GET'), false);- assert.equal(requestHasBody('HEAD'), false);- assert.equal(requestHasBody('POST'), true);- assert.equal(requestHasBody('PUT'), true);- assert.equal(requestHasBody('PATCH'), true);- assert.equal(requestHasBody('DELETE'), true);- });-- test('the protocol authorization secret and the upload id never leave the machine', () => {- const headers = buildAPIRequestHeaders({- headers: new Headers({- [DESKTOP_PROTOCOL_AUTHORIZATION_HEADER]: 'secret',- [LOCAL_APP_UPLOAD_ID_HEADER]: 'abc',- Accept: 'application/json',- }),- method: 'POST',- origin: 'https://web.fluxer.app',- });- assert.equal(headers.get(DESKTOP_PROTOCOL_AUTHORIZATION_HEADER), null);- assert.equal(headers.get(LOCAL_APP_UPLOAD_ID_HEADER), null);- assert.equal(headers.get('Accept'), 'application/json');- });-- test('hop-by-hop, cookie, host, referer and content-length are dropped', () => {- const headers = buildAPIRequestHeaders({- headers: new Headers({- Connection: 'keep-alive',- 'Keep-Alive': 'timeout=5',- TE: 'trailers',- Upgrade: 'websocket',- Cookie: 'a=b',- Host: 'app',- Referer: 'fluxer-app://app/channels/@me',- 'Content-Length': '10',- 'Accept-Encoding': 'gzip',- Expect: '100-continue',- 'Proxy-Connection': 'keep-alive',- 'X-Fluxer-Client-Installation-Id': 'install',- }),- method: 'POST',- origin: null,- });- assert.deepEqual(headerNames(headers), ['x-fluxer-client-installation-id']);- });-});--describe('outbound remote-resource request headers', () => {- test('credentials are stripped on the /proxy route but survive on /api', () => {- const source = new Headers({Authorization: 'token', 'X-Fluxer-Sudo-Mode-Jwt': 'jwt', Range: 'bytes=0-10'});- const proxied = buildRemoteResourceRequestHeaders(source);- assert.equal(proxied.get('Authorization'), null);- assert.equal(proxied.get('X-Fluxer-Sudo-Mode-Jwt'), null);- assert.equal(proxied.get('Range'), 'bytes=0-10');- const api = buildAPIRequestHeaders({headers: source, method: 'GET', origin: null});- assert.equal(api.get('Authorization'), 'token');- assert.equal(api.get('X-Fluxer-Sudo-Mode-Jwt'), 'jwt');- });-});--describe('proxied response headers', () => {- test('CORS, cookies, encodings and lengths are stripped', () => {- const headers = buildProxyResponseHeaders({- cacheDefault: LocalAppProxyCacheDefault.NO_STORE,- headers: new Headers({- 'Access-Control-Allow-Origin': '*',- 'Access-Control-Allow-Credentials': 'true',- 'Access-Control-Expose-Headers': 'X-Fluxer-Version',- 'Access-Control-Max-Age': '86400',- 'Set-Cookie': 'a=b',- 'Content-Encoding': 'gzip',- 'Content-Length': '10',- 'Content-Security-Policy': "default-src 'self'",- 'Transfer-Encoding': 'chunked',- 'Content-Type': 'application/json',- }),- });- assert.equal(headers.get('Content-Type'), 'application/json');- for (const name of [- 'Access-Control-Allow-Origin',- 'Access-Control-Allow-Credentials',- 'Access-Control-Expose-Headers',- 'Access-Control-Max-Age',- 'Set-Cookie',- 'Content-Encoding',- 'Content-Length',- 'Transfer-Encoding',- ]) {- assert.equal(headers.get(name), null, name);- }- });-- test('the response is forced into a non-document, non-framable posture', () => {- const headers = buildProxyResponseHeaders({- cacheDefault: LocalAppProxyCacheDefault.NO_STORE,- headers: new Headers({'Content-Type': 'text/html'}),- });- assert.equal(headers.get('Content-Security-Policy'), "sandbox; default-src 'none'; frame-ancestors 'none'");- assert.equal(headers.get('X-Content-Type-Options'), 'nosniff');- });-- test('headers the renderer actually reads through XHR survive', () => {- const headers = buildProxyResponseHeaders({- cacheDefault: LocalAppProxyCacheDefault.NO_STORE,- headers: new Headers({- 'X-Fluxer-Version': '1',- 'Retry-After': '5',- 'X-RateLimit-Reset-After': '2.5',- 'X-Fluxer-Sudo-Mode-Jwt': 'rotated',- }),- });- assert.equal(headers.get('X-Fluxer-Version'), '1');- assert.equal(headers.get('Retry-After'), '5');- assert.equal(headers.get('X-RateLimit-Reset-After'), '2.5');- assert.equal(headers.get('X-Fluxer-Sudo-Mode-Jwt'), 'rotated');- });-- test('an upstream Cache-Control always wins', () => {- for (const cacheDefault of [LocalAppProxyCacheDefault.NO_STORE, LocalAppProxyCacheDefault.UPSTREAM]) {- assert.equal(- buildProxyResponseHeaders({- cacheDefault,- headers: new Headers({'Cache-Control': 'public, max-age=60'}),- }).get('Cache-Control'),- 'public, max-age=60',- cacheDefault,- );- }- });-- test('an API response that declares no caching is held to no-store', () => {- assert.equal(- buildProxyResponseHeaders({- cacheDefault: LocalAppProxyCacheDefault.NO_STORE,- headers: new Headers(),- }).get('Cache-Control'),- 'no-store',- );- });-- test('a remote resource that declares no caching keeps its upstream validators and stays cacheable', () => {- const headers = buildProxyResponseHeaders({- cacheDefault: LocalAppProxyCacheDefault.UPSTREAM,- headers: new Headers({ETag: '"abc"', 'Last-Modified': 'Wed, 21 Oct 2015 07:28:00 GMT'}),- });- assert.equal(headers.get('Cache-Control'), null);- assert.equal(headers.get('ETag'), '"abc"');- assert.equal(headers.get('Last-Modified'), 'Wed, 21 Oct 2015 07:28:00 GMT');- });-});--describe('resolving the remote resource target', () => {- test('an absolute http target is accepted', () => {- assert.equal(- remoteProxyTargetURL('fluxer-app://app/proxy/k?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png'),- 'https://media.fluxer.app/x.png',- );- });-- test('a missing, relative, credentialed or non-http target is refused', () => {- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k'), null);- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k?url='), null);- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k?url=%2Fetc%2Fpasswd'), null);- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k?url=file%3A%2F%2F%2Fetc%2Fpasswd'), null);- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k?url=javascript%3Aalert(1)'), null);- assert.equal(remoteProxyTargetURL('fluxer-app://app/proxy/k?url=https%3A%2F%2Fu%3Ap%40evil.example%2F'), null);- });-- test('only GET, HEAD and PUT reach the remote resource route', () => {- assert.equal(isSupportedRemoteResourceMethod('GET'), true);- assert.equal(isSupportedRemoteResourceMethod('HEAD'), true);- assert.equal(isSupportedRemoteResourceMethod('PUT'), true);- assert.equal(isSupportedRemoteResourceMethod('POST'), false);- assert.equal(isSupportedRemoteResourceMethod('DELETE'), false);- assert.equal(isSupportedRemoteResourceMethod('get'), false);- });-});--describe('the remote resource origin allowlist', () => {- test('only origins named by the active plan are reachable', () => {- for (const target of [- 'https://api.fluxer.app/v1/x',- 'https://web.fluxer.app/x',- 'https://media.fluxer.app/attachments/x.png',- 'https://cdn.fluxer.app/libs/x.wasm',- ]) {- assert.equal(allowsRemoteResource(target), true, target);- }- });-- test('an origin outside the plan is refused, including a lookalike host', () => {- for (const target of [- 'https://evil.example/x',- 'https://media.fluxer.app.evil.example/x',- 'http://media.fluxer.app/x',- 'https://media.fluxer.app:8443/x',- 'fluxer-app://app/x',- ]) {- assert.equal(allowsRemoteResource(target), false, target);- }- });-- test('the gateway origin is not a remote-resource target', () => {- assert.equal(allowsRemoteResource('https://gateway.fluxer.app/x'), false);- });-- test('GET and PUT take different admission paths', () => {- const relay = 'https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png?t=TOKEN';- assert.equal(isAllowedRemoteProxyTarget({method: 'GET', targetURL: relay, plan: plan()}), true);- assert.equal(- isAllowedRemoteProxyTarget({method: 'PUT', targetURL: 'https://media.fluxer.app/x.png', plan: plan()}),- false,- );- });-});--describe('the upload relay admission rule matches fluxer_api UploadRelay.ts', () => {- test('a single-part relay PUT is admitted', () => {- assert.equal(allowsUploadRelay('https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png?t=TOKEN'), true);- });-- test('a multipart part upload carrying uploadId and partNumber is admitted', () => {- assert.equal(- allowsUploadRelay(- 'https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png?t=TOKEN&uploadId=U1&partNumber=2',- ),- true,- );- });-- test('a relay endpoint advertised with its own /v1/relay suffix normalises the same way the API does', () => {- const relayPlan = plan({uploadRelayEndpoint: 'https://media.fluxer.app/upload/v1/relay'});- assert.equal(- allowsUploadRelay('https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png?t=TOKEN', relayPlan),- true,- 'KNOWN BUG (WP-I): isAllowedUploadRelayEndpoint rejects any endpoint whose pathname contains a relay ' +- 'segment before uploadRelayBasePath gets to strip the /v1/relay suffix, so UPLOAD_RELAY_BASE_SUFFIX_PATTERN ' +- 'is dead code. fluxer_api relayEndpointBase (UploadRelay.ts:74) and the renderer parseUploadRelayBase ' +- '(DesktopResourceUrl.ts:139) both strip the suffix first, so an operator who sets ' +- 'FLUXER_MEDIA_PROXY_UPLOAD_RELAY_ENDPOINT to a URL ending in /v1/relay gets renderer-wrapped uploads that ' +- 'main 403s. Fix: strip the suffix before the relay-segment guard, exactly as the renderer does.',- );- });-- test('a root relay endpoint admits /v1/relay/<key>', () => {- const relayPlan = plan({uploadRelayEndpoint: 'https://media.fluxer.app'});- assert.equal(allowsUploadRelay('https://media.fluxer.app/v1/relay/attachments%2Fa.png?t=TOKEN', relayPlan), true);- });-- test('a missing token, an empty token or a duplicated token is refused', () => {- const base = 'https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png';- assert.equal(allowsUploadRelay(base), false);- assert.equal(allowsUploadRelay(`${base}?t=`), false);- assert.equal(allowsUploadRelay(`${base}?t=A&t=B`), false);- });-- test('an unknown query parameter is refused', () => {- const base = 'https://media.fluxer.app/upload/v1/relay/attachments%2Fa.png';- assert.equal(allowsUploadRelay(`${base}?t=TOKEN&redirect=https://evil.example`), false);- });-- test('a hash, a wrong origin, an empty key or a path outside the relay prefix is refused', () => {- assert.equal(allowsUploadRelay('https://media.fluxer.app/upload/v1/relay/a.png?t=T#frag'), false);- assert.equal(allowsUploadRelay('https://evil.example/upload/v1/relay/a.png?t=T'), false);- assert.equal(allowsUploadRelay('https://media.fluxer.app/upload/v1/relay/?t=T'), false);- assert.equal(allowsUploadRelay('https://media.fluxer.app/upload/v1/x/a.png?t=T'), false);- assert.equal(allowsUploadRelay('https://media.fluxer.app/v1/relay/a.png?t=T'), false);- });-- test('no advertised relay endpoint means no relay PUT is ever admitted', () => {- const relayPlan = plan({uploadRelayEndpoint: null});- assert.equal(allowsUploadRelay('https://media.fluxer.app/upload/v1/relay/a.png?t=T', relayPlan), false);- });-});--describe('upload correlation and content length', () => {- test('only a safe correlation token is accepted', () => {- assert.equal(readLocalAppUploadId(new Headers({[LOCAL_APP_UPLOAD_ID_HEADER]: 'abc-DEF_123'})), 'abc-DEF_123');- assert.equal(readLocalAppUploadId(new Headers({[LOCAL_APP_UPLOAD_ID_HEADER]: 'a b'})), null);- assert.equal(readLocalAppUploadId(new Headers({[LOCAL_APP_UPLOAD_ID_HEADER]: ''})), null);- assert.equal(readLocalAppUploadId(new Headers({[LOCAL_APP_UPLOAD_ID_HEADER]: 'x'.repeat(129)})), null);- assert.equal(readLocalAppUploadId(new Headers()), null);- });-- test('content length is parsed strictly', () => {- assert.equal(readRequestContentLength(new Headers({'Content-Length': '1024'})), 1024);- assert.equal(readRequestContentLength(new Headers({'Content-Length': ' 1024 '})), 1024);- assert.equal(readRequestContentLength(new Headers({'Content-Length': '-1'})), null);- assert.equal(readRequestContentLength(new Headers({'Content-Length': '1e3'})), null);- assert.equal(readRequestContentLength(new Headers()), null);- });-});--describe('the not-found response is an oracle-free 404', () => {- test('it never reveals why', async () => {- const response = localAppProxyNotFoundResponse('Not found');- assert.equal(response.status, 404);- assert.equal(await response.text(), 'Not found');- assert.equal(response.headers.get('Content-Type'), 'text/plain; charset=utf-8');- });-});diff --git a/fluxer_desktop/src/main/LocalAppRequestHandler.test.mjs b/fluxer_desktop/src/main/LocalAppRequestHandler.test.mjsdeleted file mode 100644index b9fcc0911..000000000--- a/fluxer_desktop/src/main/LocalAppRequestHandler.test.mjs+++ /dev/null@@ -1,303 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {mkdirSync, mkdtempSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import {after, beforeEach, describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {DesktopLocalAppRequestHandler} = await import('@electron/main/LocalAppRequestHandler');-const {DesktopLocalAppFiles} = await import('@electron/main/LocalAppFileResolver');--const rendererRoot = mkdtempSync(path.join(os.tmpdir(), 'local-app-handler-'));-mkdirSync(path.join(rendererRoot, 'assets'));-writeFileSync(- path.join(rendererRoot, 'index.html'),- '<html lang="en"><head><script nonce="{{CSP_NONCE_PLACEHOLDER}}"></script></head><body></body></html>',-);-writeFileSync(path.join(rendererRoot, 'assets', 'deadbeefdeadbeef.js'), 'console.log(1)');--const INSTANCE_KEY = 'https://api.fluxer.app';-const ENCODED_KEY = encodeURIComponent(INSTANCE_KEY);-const SECRET = 'test-secret';-const REACTION_BURST_SIZE = 300;--const PLAN = {- instanceKey: INSTANCE_KEY,- document: {},- selfHosted: false,- endpoints: {- apiEndpoint: 'https://api.fluxer.app',- apiPublicEndpoint: 'https://api.fluxer.app',- webAppEndpoint: 'https://web.fluxer.app',- mediaEndpoint: 'https://media.fluxer.app',- staticCdnEndpoint: null,- uploadRelayEndpoint: null,- gatewayEndpoint: null,- inviteEndpoint: null,- giftEndpoint: null,- },-};--let proxyCalls;--function createProxyClient() {- return {- fetch(request) {- proxyCalls.push(request);- return Promise.resolve(new Response('upstream', {status: 200, headers: {'Content-Type': 'text/plain'}}));- },- responseBodyForMethod({method, response}) {- return Promise.resolve(method === 'HEAD' ? null : response.body);- },- settleFailure({failure}) {- return Promise.resolve({bodyCancellationFailed: false, error: failure});- },- };-}--function createHandler(options = {}) {- return new DesktopLocalAppRequestHandler({- authorization: {- hasValidRequestAuthorization: (request) =>- request.headers.get('X-Fluxer-Desktop-Protocol-Authorization') === SECRET,- },- files: new DesktopLocalAppFiles({rendererRoot}),- indexContext: () => ({prebootTheme: null}),- apiProxyClient: createProxyClient(),- resourceProxyClient: createProxyClient(),- runtimePlans: {planForRoute: async (key) => (key === INSTANCE_KEY ? PLAN : null)},- shutdownSignal: new AbortController().signal,- ...options,- });-}--function authorized(url, init = {}) {- const headers = new Headers(init.headers ?? {});- headers.set('X-Fluxer-Desktop-Protocol-Authorization', SECRET);- return new Request(url, {...init, headers});-}--beforeEach(() => {- proxyCalls = [];-});--after(async () => {- await rm(rendererRoot, {recursive: true, force: true});-});--describe('an unauthorized request is indistinguishable from nothing being there', () => {- test('no header at all yields a bare 404', async () => {- const response = await createHandler().handle(new Request('fluxer-app://app/'));- assert.equal(response.status, 404);- assert.equal(await response.text(), 'Not found');- });-- test('a wrong header value yields the same 404 on every privileged route', async () => {- const handler = createHandler();- for (const url of [- 'fluxer-app://app/',- 'fluxer-app://app/channels/@me',- `fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`,- `fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png`,- ]) {- const response = await handler.handle(- new Request(url, {headers: {'X-Fluxer-Desktop-Protocol-Authorization': 'wrong'}}),- );- assert.equal(response.status, 404, url);- assert.equal(await response.text(), 'Not found', url);- }- assert.deepEqual(proxyCalls, [], 'an unauthorized request must never reach the network');- });-- test('static asset reads are exempt because Electron cannot stamp browser-initiated loads', async () => {- const handler = createHandler();- const response = await handler.handle(- new Request('fluxer-app://app/assets/deadbeefdeadbeef.js', {- headers: {'X-Fluxer-Desktop-Protocol-Authorization': 'wrong'},- }),- );- assert.equal(response.status, 200);- assert.deepEqual(proxyCalls, [], 'an asset read must never reach the network');- });-- test('the asset exemption is confined to GET/HEAD reads of served asset paths', async () => {- const handler = createHandler();- const cases = [- new Request('fluxer-app://app/assets/deadbeefdeadbeef.js', {- method: 'POST',- headers: {'X-Fluxer-Desktop-Protocol-Authorization': 'wrong'},- }),- new Request('fluxer-app://app/not-assets/deadbeefdeadbeef.js', {- headers: {'X-Fluxer-Desktop-Protocol-Authorization': 'wrong'},- }),- new Request('fluxer-app://app/assets/index.html', {- headers: {'X-Fluxer-Desktop-Protocol-Authorization': 'wrong'},- }),- ];- for (const request of cases) {- const response = await handler.handle(request);- assert.equal(response.status, 404, request.url);- }- });-});--describe('the document gate keeps a hostile instance out of the privileged origin', () => {- test('a framed /api request is 404ed before any outbound fetch is attempted', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`, {- headers: {'Upgrade-Insecure-Requests': '1'},- }),- );- assert.equal(response.status, 404);- assert.deepEqual(proxyCalls, [], 'the proxy client must not be called for a document-class request');- });-- test('a framed /proxy request is 404ed before any outbound fetch is attempted', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png`, {- headers: {'Upgrade-Insecure-Requests': '1'},- }),- );- assert.equal(response.status, 404);- assert.deepEqual(proxyCalls, []);- });-- test('a Sec-Fetch-Dest document load is 404ed even without a navigation preference header', async () => {- const handler = createHandler();- for (const url of [- `fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`,- `fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png`,- ]) {- const response = await handler.handle(authorized(url, {headers: {'Sec-Fetch-Dest': 'document'}}));- assert.equal(response.status, 404, url);- }- assert.deepEqual(proxyCalls, [], 'the proxy client must not be called for a document-class request');- });-- test('every document-class destination is refused, not just a top-level document', async () => {- const handler = createHandler();- for (const destination of ['document', 'embed', 'frame', 'iframe', 'object']) {- const response = await handler.handle(- authorized(`fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`, {- headers: {'Sec-Fetch-Dest': destination},- }),- );- assert.equal(response.status, 404, destination);- }- assert.deepEqual(proxyCalls, [], 'the proxy client must not be called for a document-class request');- });-- test('a data-class destination on the same route is still served', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`, {headers: {'Sec-Fetch-Dest': 'empty'}}),- );- assert.equal(response.status, 200);- assert.equal(proxyCalls.length, 1);- });-- test('the same URL fetched as data still works', async () => {- const response = await createHandler().handle(authorized(`fluxer-app://app/api/${ENCODED_KEY}/v1/users/@me`));- assert.equal(response.status, 200);- assert.equal(proxyCalls.length, 1);- assert.equal(proxyCalls[0].targetURL, 'https://api.fluxer.app/v1/users/@me');- });-});--describe('runtime key routing', () => {- test('an unknown runtime key is 404ed and never reaches the network', async () => {- const handler = createHandler();- for (const url of [- 'fluxer-app://app/api/https%3A%2F%2Fevil.example/v1/users/@me',- 'fluxer-app://app/proxy/https%3A%2F%2Fevil.example?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png',- ]) {- const response = await handler.handle(authorized(url));- assert.equal(response.status, 404, url);- }- assert.deepEqual(proxyCalls, []);- });-- test('a remote target outside the active plan is refused with 403', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fevil.example%2Fx.png`),- );- assert.equal(response.status, 403);- assert.deepEqual(proxyCalls, []);- });-- test('a remote target inside the active plan is proxied', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png`),- );- assert.equal(response.status, 200);- assert.equal(proxyCalls[0].targetURL, 'https://media.fluxer.app/x.png');- });-- test('a POST on the remote resource route is refused', async () => {- const response = await createHandler().handle(- authorized(`fluxer-app://app/proxy/${ENCODED_KEY}?url=https%3A%2F%2Fmedia.fluxer.app%2Fx.png`, {- method: 'POST',- }),- );- assert.equal(response.status, 405);- assert.equal(response.headers.get('Allow'), 'GET, HEAD, PUT');- assert.deepEqual(proxyCalls, []);- });-});--describe('everything that is not a runtime route falls through to the bundle', () => {- test('a bare /api or /proxy with no key renders the SPA shell', async () => {- const handler = createHandler();- for (const url of ['fluxer-app://app/api', 'fluxer-app://app/api/', 'fluxer-app://app/proxy']) {- const response = await handler.handle(authorized(url));- assert.equal(response.status, 200, url);- assert.equal(response.headers.get('Content-Type'), 'text/html; charset=utf-8', url);- }- assert.deepEqual(proxyCalls, []);- });-- test('the index response carries a CSP whose nonce is the one in the document', async () => {- const response = await createHandler().handle(authorized('fluxer-app://app/channels/@me'));- assert.equal(response.status, 200);- assert.equal(response.headers.get('Cache-Control'), 'no-store');- const body = await response.text();- const nonce = /nonce="([0-9a-f]{32})"/u.exec(body)?.[1];- assert.ok(nonce != null, 'no nonce in the served document');- assert.ok(- response.headers.get('Content-Security-Policy').includes(`'nonce-${nonce}'`),- 'the nonce must round-trip',- );- });-- test('the index Content-Length describes the rewritten body, not the file on disk', async () => {- const handler = createHandler();- const body = await (await handler.handle(authorized('fluxer-app://app/'))).text();- const head = await handler.handle(authorized('fluxer-app://app/', {method: 'HEAD'}));- assert.equal(await head.text(), '');- assert.ok(Number(head.headers.get('Content-Length')) > 35, 'HEAD advertised the pre-rewrite length');- assert.ok(body.length > 35);- });-- test('a missing asset is 404 and a bad method is 405', async () => {- const handler = createHandler();- assert.equal((await handler.handle(authorized('fluxer-app://app/assets/nope.js'))).status, 404);- const badMethod = await handler.handle(authorized('fluxer-app://app/', {method: 'POST'}));- assert.equal(badMethod.status, 405);- assert.equal(badMethod.headers.get('Allow'), 'GET, HEAD');- });-- test('a message full of reaction emoji is served in full, never turned away for capacity', async () => {- const handler = createHandler();- const responses = await Promise.all(- Array.from({length: REACTION_BURST_SIZE}, () =>- handler.handle(authorized('fluxer-app://app/assets/deadbeefdeadbeef.js')),- ),- );- assert.deepEqual(new Set(responses.map((response) => response.status)), new Set([200]));- const bodies = await Promise.all(responses.map((response) => response.text()));- assert.deepEqual(bodies, new Array(REACTION_BURST_SIZE).fill('console.log(1)'));- });-});diff --git a/fluxer_desktop/src/main/LocalAppRuntimePlans.test.mjs b/fluxer_desktop/src/main/LocalAppRuntimePlans.test.mjsdeleted file mode 100644index 95f4313ee..000000000--- a/fluxer_desktop/src/main/LocalAppRuntimePlans.test.mjs+++ /dev/null@@ -1,206 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-const {- DesktopLocalAppRuntimePlans,- buildLocalAppRuntimeURL,- httpOriginSource,- localAppRuntimeInstanceKey,- localAppRuntimePlanFromDiscovery,- parseLocalAppRuntimeRoute,- runtimePlanTrustedHTTPOrigins,-} = await import('@electron/main/LocalAppRuntimePlans');-const {DEPLOYED_OFFICIAL_DOCUMENT, SELF_HOSTED_API_TOPOLOGY_DOCUMENT, UPGRADED_DOCUMENT} = await import(- '@fluxer/instance_bootstrap/src/__tests__/DiscoveryFixtures'-);--const OFFICIAL_KEY = 'https://api.fluxer.app';--function plan(overrides = {}) {- return {- instanceKey: OFFICIAL_KEY,- document: {},- selfHosted: false,- endpoints: {- apiEndpoint: 'https://api.fluxer.app',- apiPublicEndpoint: 'https://api.fluxer.app',- webAppEndpoint: 'https://web.fluxer.app',- mediaEndpoint: 'https://media.fluxer.app',- staticCdnEndpoint: 'https://cdn.fluxer.app',- uploadRelayEndpoint: null,- gatewayEndpoint: 'wss://gateway.fluxer.app',- inviteEndpoint: null,- giftEndpoint: null,- ...overrides,- },- };-}--describe('instance keys', () => {- test('the key is the lowercased origin plus the path, without trailing slashes', () => {- assert.equal(localAppRuntimeInstanceKey('https://API.Fluxer.App'), 'https://api.fluxer.app');- assert.equal(localAppRuntimeInstanceKey('https://web.fluxer.app/api'), 'https://web.fluxer.app/api');- assert.equal(localAppRuntimeInstanceKey('https://web.fluxer.app/api/'), 'https://web.fluxer.app/api');- assert.equal(localAppRuntimeInstanceKey(' https://api.fluxer.app '), 'https://api.fluxer.app');- assert.equal(localAppRuntimeInstanceKey('http://127.0.0.1:3000/api'), 'http://127.0.0.1:3000/api');- });-- test('a credentialed, query-bearing or non-http endpoint has no key', () => {- assert.equal(localAppRuntimeInstanceKey('https://u:[email protected]'), null);- assert.equal(localAppRuntimeInstanceKey('https://api.fluxer.app?x=1'), null);- assert.equal(localAppRuntimeInstanceKey('https://api.fluxer.app#x'), null);- assert.equal(localAppRuntimeInstanceKey('fluxer-app://app/api'), null);- assert.equal(localAppRuntimeInstanceKey('not a url'), null);- });-- test('httpOriginSource only accepts http and https', () => {- assert.equal(httpOriginSource('https://web.fluxer.app/api'), 'https://web.fluxer.app');- assert.equal(httpOriginSource('http://127.0.0.1:3000/x'), 'http://127.0.0.1:3000');- assert.equal(httpOriginSource('fluxer-app://app/'), null);- assert.equal(httpOriginSource('wss://gateway.fluxer.app'), null);- assert.equal(httpOriginSource(null), null);- assert.equal(httpOriginSource(''), null);- });-});--describe('runtime route URLs', () => {- test('the instance key becomes exactly one encoded path segment', () => {- const url = buildLocalAppRuntimeURL('/api', 'https://web.fluxer.app/api');- assert.equal(url, 'fluxer-app://app/api/https%3A%2F%2Fweb.fluxer.app%2Fapi');- assert.equal(new URL(url).pathname.split('/').length, 3);- });-- test('a leading or trailing slash on the base path does not double up', () => {- assert.equal(buildLocalAppRuntimeURL('api/', 'k'), 'fluxer-app://app/api/k');- assert.equal(buildLocalAppRuntimeURL('/proxy', 'k'), 'fluxer-app://app/proxy/k');- });-});--describe('parsing a runtime route', () => {- const cases = [- ['fluxer-app://app/api/k', '/api', {runtimeKey: 'k', localPathPrefix: '/api/k'}],- ['fluxer-app://app/api/k/', '/api', {runtimeKey: 'k', localPathPrefix: '/api/k'}],- ['fluxer-app://app/api/k/v1/users/@me', '/api', {runtimeKey: 'k', localPathPrefix: '/api/k'}],- [- 'fluxer-app://app/api/https%3A%2F%2Fweb.fluxer.app%2Fapi/v1/x?y=1',- '/api',- {runtimeKey: 'https://web.fluxer.app/api', localPathPrefix: '/api/https%3A%2F%2Fweb.fluxer.app%2Fapi'},- ],- [- 'fluxer-app://app/proxy/k?url=https://media.fluxer.app/x',- '/proxy',- {runtimeKey: 'k', localPathPrefix: '/proxy/k'},- ],- ];-- for (const [url, basePath, expected] of cases) {- test(`${url} under ${basePath}`, () => {- assert.deepEqual(parseLocalAppRuntimeRoute(url, basePath), expected);- });- }-- test('a bare prefix with no key does not parse', () => {- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/api', '/api'), null);- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/api/', '/api'), null);- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/api//v1/x', '/api'), null);- });-- test('a whitespace-only or undecodable key does not parse', () => {- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/api/%20', '/api'), null);- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/api/%ZZ', '/api'), null);- });-- test('a different prefix does not parse', () => {- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/proxy/k', '/api'), null);- assert.equal(parseLocalAppRuntimeRoute('fluxer-app://app/apix/k', '/api'), null);- assert.equal(parseLocalAppRuntimeRoute('not a url', '/api'), null);- });-});--describe('building a plan from a discovery document', () => {- test('the official document keys on its API endpoint and keeps the document verbatim', () => {- const built = localAppRuntimePlanFromDiscovery(DEPLOYED_OFFICIAL_DOCUMENT);- assert.equal(built.instanceKey, OFFICIAL_KEY);- assert.equal(built.selfHosted, false);- assert.equal(built.document, DEPLOYED_OFFICIAL_DOCUMENT);- assert.equal(built.endpoints.webAppEndpoint, 'https://web.fluxer.app');- assert.equal(built.endpoints.mediaEndpoint, 'https://media.fluxer.app');- assert.equal(built.endpoints.gatewayEndpoint, 'wss://gateway.fluxer.app');- });-- test('a self-hosted document is flagged self hosted', () => {- const built = localAppRuntimePlanFromDiscovery(SELF_HOSTED_API_TOPOLOGY_DOCUMENT);- assert.equal(built.selfHosted, true);- });-- test('the upload relay endpoint is carried through when advertised', () => {- assert.equal(- localAppRuntimePlanFromDiscovery(UPGRADED_DOCUMENT).endpoints.uploadRelayEndpoint,- 'https://media.fluxer.app/upload',- );- });-- test('a document with an unusable API endpoint is refused', () => {- const broken = {...DEPLOYED_OFFICIAL_DOCUMENT, endpoints: {...DEPLOYED_OFFICIAL_DOCUMENT.endpoints}};- assert.throws(() => localAppRuntimePlanFromDiscovery({...broken, endpoints: null}));- });-});--describe('the trusted origin set of a plan', () => {- test('every http endpoint plus the gateway as an http origin is trusted', () => {- assert.deepEqual(runtimePlanTrustedHTTPOrigins(plan()), [- 'https://api.fluxer.app',- 'https://cdn.fluxer.app',- 'https://gateway.fluxer.app',- 'https://media.fluxer.app',- 'https://web.fluxer.app',- ]);- });-- test('an origin outside the plan is not trusted', () => {- const origins = runtimePlanTrustedHTTPOrigins(plan());- assert.equal(origins.includes('https://evil.example'), false);- assert.equal(origins.includes('https://media.fluxer.app'), true);- });-- test('a non-http endpoint contributes nothing', () => {- const origins = runtimePlanTrustedHTTPOrigins(plan({staticCdnEndpoint: 'fluxer-app://app', gatewayEndpoint: null}));- assert.ok(!origins.some((origin) => origin.startsWith('fluxer-app:')));- });-});--describe('the runtime plan cache', () => {- test('the active plan is found by its own key without a cache lookup', () => {- const plans = new DesktopLocalAppRuntimePlans();- const active = plan();- plans.activate(active);- assert.equal(plans.getActivePlan(), active);- assert.equal(plans.findPlanForRoute(OFFICIAL_KEY), active);- });-- test('an unknown key resolves to null rather than to the active plan', () => {- const plans = new DesktopLocalAppRuntimePlans();- plans.activate(plan());- assert.equal(plans.findPlanForRoute('https://evil.example'), null);- assert.equal(plans.findPlanForRoute(''), null);- });-- test('a cached plan is reachable, and eviction at 256 keys never drops the active plan', () => {- const plans = new DesktopLocalAppRuntimePlans();- const active = plan();- plans.activate(active);- const survivor = {...plan(), instanceKey: 'https://survivor.example'};- plans.cache(survivor);- for (let index = 0; index < 300; index += 1) {- plans.cache({...plan(), instanceKey: `https://filler-${index}.example`});- assert.equal(plans.findPlanForRoute(survivor.instanceKey)?.instanceKey, survivor.instanceKey);- }- assert.equal(plans.findPlanForRoute(OFFICIAL_KEY), active);- assert.equal(plans.findPlanForRoute('https://filler-0.example'), null);- assert.equal(plans.findPlanForRoute('https://filler-299.example')?.instanceKey, 'https://filler-299.example');- });-});diff --git a/fluxer_desktop/src/main/LocalAppTestSupport.test.mjs b/fluxer_desktop/src/main/LocalAppTestSupport.test.mjsdeleted file mode 100644index b9c7365a4..000000000--- a/fluxer_desktop/src/main/LocalAppTestSupport.test.mjs+++ /dev/null@@ -1,173 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {registerHooks} from 'node:module';-import path from 'node:path';-import {fileURLToPath} from 'node:url';--const DESKTOP_SRC = new URL('../', import.meta.url);-const PACKAGES = new URL('../../../packages/', import.meta.url);-const APP_SRC = new URL('../../../fluxer_app/src/', import.meta.url);--export const REPOSITORY_ROOT = fileURLToPath(new URL('../../../', import.meta.url));--const DESKTOP_DIRECTORY = fileURLToPath(new URL('../../', import.meta.url));--const ELECTRON_EXPORT_NAMES = Object.freeze([- 'app',- 'autoUpdater',- 'BaseWindow',- 'BrowserWindow',- 'clipboard',- 'contextBridge',- 'crashReporter',- 'desktopCapturer',- 'dialog',- 'globalShortcut',- 'inAppPurchase',- 'ipcMain',- 'ipcRenderer',- 'Menu',- 'MenuItem',- 'nativeImage',- 'nativeTheme',- 'net',- 'netLog',- 'Notification',- 'powerMonitor',- 'powerSaveBlocker',- 'protocol',- 'safeStorage',- 'screen',- 'session',- 'shell',- 'systemPreferences',- 'Tray',- 'utilityProcess',- 'webContents',- 'webFrame',- 'webFrameMain',-]);--const LIVE_STATE_KEY = '__fluxerDesktopLocalAppTestState__';--const state = {electron: {}, desktopAppStorage: null};--globalThis[LIVE_STATE_KEY] = state;--function dataModule(source) {- return `data:text/javascript,${encodeURIComponent(source)}`;-}--const ELECTRON_STUB = dataModule(`const state = globalThis[${JSON.stringify(LIVE_STATE_KEY)}];-const live = (name) =>- new Proxy(function electronStub() {}, {- get: (_target, property) => Reflect.get(state.electron[name], property),- set: (_target, property, value) => Reflect.set(state.electron[name], property, value),- apply: (_target, thisArgument, args) => Reflect.apply(state.electron[name], thisArgument, args),- construct: (_target, args) => Reflect.construct(state.electron[name], args),- });-export default new Proxy({}, {get: (_target, property) => state.electron[property]});-${ELECTRON_EXPORT_NAMES.map((name) => `export const ${name} = live(${JSON.stringify(name)});`).join('\n')}`);--const ELECTRON_LOG_STUB = dataModule(`const noop = () => undefined;-const log = {debug: noop, info: noop, warn: noop, error: noop, transports: {file: {}, console: {}}};-export default log;-export const {debug, info, warn, error, transports} = log;`);--const DESKTOP_APP_STORAGE_STUB = dataModule(`const state = globalThis[${JSON.stringify(LIVE_STATE_KEY)}];-export const getDesktopAppStorage = () => state.desktopAppStorage;`);--const WINDOW_STUB = dataModule(`const state = globalThis[${JSON.stringify(LIVE_STATE_KEY)}];-export const isAppDocumentWindowContents = (contents) => state.mainWindow?.webContents === contents;-export const isTrustedOrigin = () => true;`);--const APP_LOGGER_STUB = dataModule(`const noop = () => undefined;-export class Logger {- debug = noop;- info = noop;- warn = noop;- error = noop;- log = noop;-}`);--const APP_REST_TRANSPORT_STUB = dataModule(`const unavailable = () => {- throw new Error('The renderer REST transport is not available in a main-process test');-};-export const http = new Proxy({}, {get: () => unavailable});`);--const APP_NATIVE_UTILS_STUB = dataModule('export const getElectronAPI = () => null;');--const STUB_MODULES = new Map([- ['electron', ELECTRON_STUB],- ['electron-log', ELECTRON_LOG_STUB],- ['@app/features/platform/transport/RestTransport', APP_REST_TRANSPORT_STUB],- ['@app/features/platform/utils/AppLogger', APP_LOGGER_STUB],- ['@app/features/ui/utils/NativeUtils', APP_NATIVE_UTILS_STUB],-]);--registerHooks({- resolve(specifier, context, nextResolve) {- const stub = STUB_MODULES.get(specifier);- if (stub != null) {- return {shortCircuit: true, url: stub};- }- if (specifier.startsWith('@app/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@app/'.length)}.ts`, APP_SRC).href};- }- if (specifier.startsWith('@fluxer/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@fluxer/'.length)}.ts`, PACKAGES).href};- }- if (specifier.startsWith('@electron/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@electron/'.length)}.ts`, DESKTOP_SRC).href};- }- try {- return nextResolve(specifier, context);- } catch (error) {- if (error?.code !== 'ERR_MODULE_NOT_FOUND' || /\.[a-z]+$/u.test(specifier)) {- throw error;- }- return nextResolve(`${specifier}.ts`, context);- }- },-});--const APP_STUB_DEFAULTS = {- isReady: () => true,- getAppPath: () => DESKTOP_DIRECTORY,- getPath: () => path.join(DESKTOP_DIRECTORY, '.test-userdata'),-};--export function installElectronStub(extra = {}) {- const registry = {contents: new Map(), frames: new Map()};- const webContents = {- fromId: (id) => registry.contents.get(id) ?? null,- fromFrame: (frame) => (frame == null ? null : (frame.owner ?? null)),- };- const webFrameMain = {- fromId: (processId, routingId) => registry.frames.get(`${processId}:${routingId}`) ?? null,- };- const app = extra.app ?? {};- for (const [key, value] of Object.entries(APP_STUB_DEFAULTS)) {- if (!(key in app)) {- app[key] = value;- }- }- const nativeTheme = {themeSource: 'system'};- const session = {defaultSession: {resolveProxy: async () => 'DIRECT'}};- state.electron = {nativeTheme, session, webContents, webFrameMain, ...extra, app};- return registry;-}--export function installTestModuleStub(specifier, source) {- STUB_MODULES.set(specifier, dataModule(source));-}--export function installDesktopAppStorageStub(storage) {- STUB_MODULES.set('@electron/main/DesktopAppStorage', DESKTOP_APP_STORAGE_STUB);- state.desktopAppStorage = storage;-}--export function installWindowStub(mainWindow) {- STUB_MODULES.set('@electron/main/Window', WINDOW_STUB);- state.mainWindow = mainWindow;-}diff --git a/fluxer_desktop/src/main/LocalAppUrl.test.mjs b/fluxer_desktop/src/main/LocalAppUrl.test.mjsdeleted file mode 100644index d4d3e55c9..000000000--- a/fluxer_desktop/src/main/LocalAppUrl.test.mjs+++ /dev/null@@ -1,76 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {isLocalAppRendererDocumentURL, isLocalAppURL, isReservedLocalAppProxyPath} = await import('./LocalAppURL.ts');--describe('local app URL recognition', () => {- test('accepts the local app origin and its routes', () => {- assert.equal(isLocalAppURL('fluxer-app://app/'), true);- assert.equal(isLocalAppURL('fluxer-app://app'), true);- assert.equal(isLocalAppURL('fluxer-app://app/channels/@me'), true);- assert.equal(isLocalAppURL('fluxer-app://app/assets/deadbeefdeadbeef.js?v=1#x'), true);- });-- test('rejects the credential, port and host bypasses', () => {- assert.equal(isLocalAppURL('fluxer-app://evil@app:1234/x'), false);- assert.equal(isLocalAppURL('fluxer-app://u:p@app/'), false);- assert.equal(isLocalAppURL('fluxer-app://app:8080/'), false);- assert.equal(isLocalAppURL('fluxer-app://evil/'), false);- assert.equal(isLocalAppURL('fluxer-app://app.evil.example/'), false);- });-- test('rejects every non-local scheme, including the opaque ones', () => {- assert.equal(isLocalAppURL('data:text/html,x'), false);- assert.equal(isLocalAppURL('about:blank'), false);- assert.equal(isLocalAppURL('blob:fluxer-app://app/1234'), false);- assert.equal(isLocalAppURL('file:///etc/passwd'), false);- assert.equal(isLocalAppURL('https://web.fluxer.app/'), false);- assert.equal(isLocalAppURL('fluxer://guild/channel'), false);- assert.equal(isLocalAppURL('not a url'), false);- assert.equal(isLocalAppURL(''), false);- assert.equal(isLocalAppURL(null), false);- });-- test('the recogniser does not lean on URL.origin, which is "null" for this scheme in Node', () => {- assert.equal(new URL('fluxer-app://app').origin, 'null');- assert.equal(new URL('data:text/html,x').origin, 'null');- assert.equal(isLocalAppURL('data:text/html,x'), false);- });-});--describe('reserved proxy paths', () => {- test('claims the API and remote-resource prefixes', () => {- for (const pathname of ['/api', '/api/', '/api/x', '/api/x/v1/users/@me', '/proxy', '/proxy/', '/proxy/x']) {- assert.equal(isReservedLocalAppProxyPath(pathname), true, pathname);- }- });-- test('does not claim prefixes that merely start with the same letters', () => {- for (const pathname of ['/apix', '/api-docs', '/proxying', '/', '/channels/@me', '/x/api']) {- assert.equal(isReservedLocalAppProxyPath(pathname), false, pathname);- }- });-});--describe('renderer document URLs', () => {- test('a reserved proxy path is never a renderer document', () => {- assert.equal(isLocalAppRendererDocumentURL('fluxer-app://app/api/x'), false);- assert.equal(isLocalAppRendererDocumentURL('fluxer-app://app/proxy/x?url=https://evil.example'), false);- });-- test('ordinary app routes are renderer documents', () => {- assert.equal(isLocalAppRendererDocumentURL('fluxer-app://app/'), true);- assert.equal(isLocalAppRendererDocumentURL('fluxer-app://app/channels/@me'), true);- });-- test('an untrusted origin is never a renderer document', () => {- assert.equal(isLocalAppRendererDocumentURL('https://web.fluxer.app/channels/@me'), false);- assert.equal(isLocalAppRendererDocumentURL('data:text/html,x'), false);- assert.equal(isLocalAppRendererDocumentURL('about:blank'), false);- });-});diff --git a/fluxer_desktop/src/main/NativeGatewayTransport.test.mjs b/fluxer_desktop/src/main/NativeGatewayTransport.test.mjsdeleted file mode 100644index 4027bcfaf..000000000--- a/fluxer_desktop/src/main/NativeGatewayTransport.test.mjs+++ /dev/null@@ -1,961 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopNativeGatewayTransport} = await import('./NativeGatewayTransport.ts');-const {GatewayOriginRegistry} = await import('./GatewayOriginRegistry.ts');-const {DesktopOutboundHTTP} = await import('./DesktopOutboundHTTP.ts');-const {RendererDocumentOwnerFactory} = await import('./RendererDocumentOwner.ts');-const {getNativeGatewayDisableReason} = await import('./LaunchOptions.ts');-const {createNativeGatewayPreloadAPI} = await import('../preload/NativeGatewayPreload.ts');-const {- NATIVE_GATEWAY_TRANSPORT_AVAILABLE_RENDERER_ARG,- NATIVE_GATEWAY_TRANSPORT_CHANNELS,- NATIVE_GATEWAY_TRANSPORT_EVENT_CHANNEL,-} = await import('../../../packages/desktop_ipc/src/GatewayTransportContract.ts');--const APP_ORIGIN = 'https://web.fluxer.app';-const GATEWAY_URL = 'wss://gateway.fluxer.app/?v=9&encoding=json&compress=zstd-stream&stream=1';-const GATEWAY_WS_ORIGIN = 'wss://gateway.fluxer.app';--let connectionCounter = 0;--function nextConnectionId() {- connectionCounter += 1;- const suffix = String(connectionCounter).padStart(12, '0');- return `gateway-renderer-11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-${suffix}`;-}--function createDocument({url = `${APP_ORIGIN}/channels/@me`, privileged = true} = {}) {- const listeners = new Map();- const sent = [];- const frame = {- url,- detached: false,- parent: null,- send: (channel, payload) => sent.push({channel, payload}),- };- const sender = {- privileged,- destroyed: false,- isDestroyed: () => sender.destroyed,- isLoadingMainFrame: () => false,- mainFrame: frame,- on: (event, listener) => {- const list = listeners.get(event) ?? [];- list.push(listener);- listeners.set(event, list);- },- once: (event, listener) => sender.on(event, listener),- removeListener: (event, listener) => {- const list = listeners.get(event) ?? [];- const index = list.indexOf(listener);- if (index >= 0) list.splice(index, 1);- listeners.set(event, list);- },- emit: (event, ...args) => {- for (const listener of [...(listeners.get(event) ?? [])]) listener(...args);- },- listenerCount: (event) => (listeners.get(event) ?? []).length,- };- frame.top = frame;- frame.owner = sender;- return {frame, sender, sent, event: {sender, senderFrame: frame}};-}--function createSubframeEvent(document) {- const subframe = {- url: document.frame.url,- detached: false,- parent: document.frame,- send: () => {},- owner: document.sender,- };- subframe.top = document.frame;- return {sender: document.sender, senderFrame: subframe};-}--function createBoundary() {- const connections = [];- return {- connections,- boundary: {- connect: ({url, address, onEvent, onTerminalEvent}) => {- const connection = {- url,- address,- onEvent,- onTerminalEvent,- disposed: false,- text: [],- binary: [],- closes: [],- sendText: (value) => connection.text.push(value),- sendBinary: (value) => connection.binary.push(value),- close: (code, reason) => connection.closes.push({code, reason}),- dispose: () => {- connection.disposed = true;- },- };- connections.push(connection);- return connection;- },- },- };-}--function createRegistry({gatewayEndpoint = 'wss://gateway.fluxer.app/', anchors = []} = {}) {- const resolved = [];- const registry = new GatewayOriginRegistry({- additionalAnchorOrigins: async () => anchors,- resolveAnchorGatewayOrigin: async (anchorOrigin) => {- resolved.push(anchorOrigin);- return anchorOrigin === APP_ORIGIN ? gatewayEndpoint : null;- },- });- registry.seedAnchorOrigin(APP_ORIGIN);- return {registry, resolved};-}--function refuseCleartextGatewayAddress(httpOrigin) {- return Promise.reject(new Error(`unexpected cleartext lookup for ${httpOrigin}`));-}--function createTransport({- privileged = true,- registry,- boundary,- requireCleartextGatewayAddress = refuseCleartextGatewayAddress,- resolveProxy = async () => 'DIRECT',-} = {}) {- const origins = registry ?? createRegistry();- const native = boundary ?? createBoundary();- const mainDocument = createDocument({privileged});- const transport = new DesktopNativeGatewayTransport({- boundary: native.boundary,- logger: {info: () => {}, warn: () => {}, error: () => {}},- originRegistry: origins.registry,- requireCleartextGatewayAddress,- resolveProxy,- rendererDocumentOwners: new RendererDocumentOwnerFactory({- policy: {- isPrivilegedRendererDocument: ({sender, url}) => sender.privileged === true && url.startsWith(APP_ORIGIN),- },- onWatcherFailure: () => {},- }),- });- return {transport, routes: transport.ipcRoutes(), native, origins, mainDocument};-}--function nativeEvent(overrides) {- return {- kind: 'open',- data: null,- binary: null,- code: null,- reason: null,- wasClean: null,- message: null,- ...overrides,- };-}--async function rejects(promise, matcher) {- await assert.rejects(promise, matcher);-}--describe('NativeGatewayTransportRequestBoundary', () => {- test('refuses an http, file, credentialed or fragmented target', async () => {- const {routes, mainDocument} = createTransport();- for (const url of [- 'http://gateway.fluxer.app/',- 'file:///etc/passwd',- 'wss://user:[email protected]/',- 'wss://gateway.fluxer.app/#fragment',- 'not-a-url',- ]) {- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url,- mode: 'gateway',- }),- /Native gateway transport request is invalid/u,- );- }- });-- test('refuses a malformed connection id and an unexpected request key', async () => {- const {routes, mainDocument} = createTransport();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: 'voice-renderer-1',- url: GATEWAY_URL,- mode: 'gateway',- }),- /connection id has an invalid format/u,- );- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- compression: 'none',- }),- /plain object with exactly its own keys/u,- );- });-- test('refuses the voice transport mode at the TS boundary', async () => {- const {routes, mainDocument} = createTransport();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'voice',- }),- /transport mode must be gateway/u,- );- });-- test('refuses an origin that no reachable instance advertises as its gateway', async () => {- const {routes, mainDocument} = createTransport();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: 'wss://attacker.example/',- mode: 'gateway',- }),- /no reachable instance advertises it as its gateway/u,- );- });-- test('refuses a close code outside 1000 and the application range', async () => {- const {routes, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.close](mainDocument.event, {connectionId, code: 1006, reason: ''}),- /close code is not permitted/u,- );- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.close](mainDocument.event, {- connectionId,- code: 4000,- reason: 'Client disconnecting',- });- });-});--describe('RendererDocumentOwner', () => {- test('rejects a capture from a subframe', async () => {- const {routes, mainDocument} = createTransport();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](createSubframeEvent(mainDocument), {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /requires the current privileged main-frame renderer document/u,- );- });-- test('rejects a capture from a data: URL popout document sharing the preload', async () => {- const {routes} = createTransport();- const popout = createDocument({url: 'data:text/html;charset=utf-8,%3Chtml%3E'});- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](popout.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /requires the current privileged main-frame renderer document/u,- );- });-- test('rejects a capture from a second privileged-origin window that is not the app window', async () => {- const {routes} = createTransport();- const popout = createDocument({url: `${APP_ORIGIN}/popout`, privileged: false});- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](popout.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /requires the current privileged main-frame renderer document/u,- );- });-- test('rejects a capture with no sender frame', async () => {- const {routes, mainDocument} = createTransport();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](- {sender: mainDocument.sender, senderFrame: null},- {connectionId: nextConnectionId(), url: GATEWAY_URL, mode: 'gateway'},- ),- /requires the current privileged main-frame renderer document/u,- );- });-});--describe('DesktopNativeGatewayTransport', () => {- test('forwards compressed frames byte-for-byte in both directions without inspecting them', async () => {- const {routes, native, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- const connection = native.connections[0];- const compressed = new Uint8Array([0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x58, 0x21, 0x00, 0x00]);- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.sendBinary](mainDocument.event, {- connectionId,- payload: compressed.buffer,- });- assert.deepEqual([...connection.binary[0]], [...compressed]);- connection.onEvent(nativeEvent({kind: 'binary', binary: Buffer.from(compressed)}));- const delivered = mainDocument.sent.at(-1);- assert.equal(delivered.channel, NATIVE_GATEWAY_TRANSPORT_EVENT_CHANNEL);- assert.deepEqual([...new Uint8Array(delivered.payload.binary)], [...compressed]);- assert.equal(delivered.payload.data, null);- });-- test('passes the admitted URL through verbatim, including stream=1', async () => {- const {routes, native, mainDocument} = createTransport();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- assert.equal(native.connections[0].url, GATEWAY_URL);- assert.ok(native.connections[0].url.includes('stream=1'));- assert.ok(native.connections[0].url.includes('compress=zstd-stream'));- });-- test('connects wss without a pinned address', async () => {- const {routes, native, mainDocument} = createTransport();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- assert.equal(native.connections[0].address, null);- });-- test('pins a cleartext ws gateway to the non-public address it resolved', async () => {- const looked = [];- const {routes, native, mainDocument} = createTransport({- registry: createRegistry({gatewayEndpoint: 'ws://localhost:8088/gateway'}),- requireCleartextGatewayAddress: async (httpOrigin) => {- looked.push(httpOrigin);- return '127.0.0.1';- },- });- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: 'ws://localhost:8088/gateway?v=9',- mode: 'gateway',- });- assert.deepEqual(looked, ['http://localhost:8088']);- assert.equal(native.connections[0].address, '127.0.0.1');- });-- test('refuses a cleartext ws gateway on a publicly routable host', async () => {- const outboundHTTP = new DesktopOutboundHTTP({- resolveHostAddresses: async () => ['93.184.216.34'],- });- const {routes, native, mainDocument} = createTransport({- registry: createRegistry({gatewayEndpoint: 'ws://gateway.example.com/'}),- requireCleartextGatewayAddress: (httpOrigin) => outboundHTTP.requireCleartextTransportAddress(httpOrigin),- });- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: 'ws://gateway.example.com/?v=9',- mode: 'gateway',- }),- /requires https for the publicly routable origin http:\/\/gateway\.example\.com/u,- );- assert.equal(native.connections.length, 0);- outboundHTTP.cleanup();- });-- test('refuses a second document acting on another document that owns the connection', async () => {- const {routes, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- const intruder = createDocument();- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.sendText](intruder.event, {connectionId, payload: '{"op":1}'}),- /owned by another renderer document/u,- );- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.dispose](intruder.event, connectionId),- /owned by another renderer document/u,- );- });-- test('a did-start-navigation disposes exactly that document connections', async () => {- const shared = createTransport();- const second = createDocument();- const firstId = nextConnectionId();- const secondId = nextConnectionId();- await shared.routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](shared.mainDocument.event, {- connectionId: firstId,- url: GATEWAY_URL,- mode: 'gateway',- });- await shared.routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](second.event, {- connectionId: secondId,- url: GATEWAY_URL,- mode: 'gateway',- });- assert.equal(shared.native.connections.length, 2);- shared.mainDocument.sender.emit('did-start-navigation', {isMainFrame: true, isSameDocument: false});- assert.equal(shared.native.connections[0].disposed, true);- assert.equal(shared.native.connections[1].disposed, false);- await rejects(- shared.routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.sendText](shared.mainDocument.event, {- connectionId: firstId,- payload: '{}',- }),- /does not exist/u,- );- await shared.routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.sendText](second.event, {- connectionId: secondId,- payload: '{}',- });- });-- test('ignores a same-document navigation and a subframe navigation', async () => {- const {routes, native, mainDocument} = createTransport();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- mainDocument.sender.emit('did-start-navigation', {isMainFrame: true, isSameDocument: true});- mainDocument.sender.emit('did-start-navigation', {isMainFrame: false, isSameDocument: false});- assert.equal(native.connections[0].disposed, false);- });-- test('a render-process-gone disposes the document connections', async () => {- const {routes, native, mainDocument} = createTransport();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- mainDocument.sender.emit('render-process-gone');- assert.equal(native.connections[0].disposed, true);- });-- test('removes every renderer listener once the last connection is gone', async () => {- const {routes, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- assert.equal(mainDocument.sender.listenerCount('did-start-navigation'), 1);- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.dispose](mainDocument.event, connectionId);- assert.equal(mainDocument.sender.listenerCount('did-start-navigation'), 0);- assert.equal(mainDocument.sender.listenerCount('render-process-gone'), 0);- assert.equal(mainDocument.sender.listenerCount('destroyed'), 0);- });-- test('refuses the ninth live connection for one document', async () => {- const {routes, native, mainDocument} = createTransport();- for (let index = 0; index < 8; index += 1) {- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- }- assert.equal(native.connections.length, 8);- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /connection limit reached/u,- );- });-- test('refuses a duplicate connection id', async () => {- const {routes, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- }),- /already exists/u,- );- });-- test('a malformed native event produces a synthetic error, close 1006 and destroys the connection', async () => {- for (const malformed of [- nativeEvent({kind: 'message', data: 'payload', extra: 1}),- {kind: 'open', data: null, binary: null, code: null, reason: null, wasClean: null},- nativeEvent({kind: 'message', data: 'payload', code: 4000}),- nativeEvent({kind: 'unknown'}),- ]) {- const {routes, native, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- mainDocument.sent.length = 0;- native.connections[0].onEvent(malformed);- assert.equal(mainDocument.sent.length, 2);- assert.equal(mainDocument.sent[0].payload.kind, 'error');- assert.equal(mainDocument.sent[1].payload.kind, 'close');- assert.equal(mainDocument.sent[1].payload.code, 1006);- assert.equal(mainDocument.sent[1].payload.wasClean, false);- assert.equal(native.connections[0].disposed, true);- }- });-- test('a native close event retires the connection', async () => {- const {routes, native, mainDocument} = createTransport();- const connectionId = nextConnectionId();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId,- url: GATEWAY_URL,- mode: 'gateway',- });- native.connections[0].onTerminalEvent(- nativeEvent({kind: 'close', code: 1006, reason: 'delivery failed', wasClean: false}),- );- assert.equal(native.connections[0].disposed, true);- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.sendText](mainDocument.event, {connectionId, payload: '{}'}),- /does not exist/u,- );- });-- test('refuses every verb once the transport is shut down and disposes live connections', async () => {- const {transport, routes, native, mainDocument} = createTransport();- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- transport.cleanup();- assert.equal(native.connections[0].disposed, true);- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /shutting down/u,- );- });-- test('refuses a gateway the session routes through a proxy and opens no native socket', async () => {- const lookups = [];- const {routes, mainDocument, native} = createTransport({- resolveProxy: async (event, url) => {- lookups.push({sender: event.sender, url});- return 'PROXY proxy.corp.example:8080; DIRECT';- },- });- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /resolves through a proxy/u,- );- assert.deepEqual(lookups, [{sender: mainDocument.sender, url: GATEWAY_URL.replace(/^wss/u, 'https')}]);- assert.equal(native.connections.length, 0);- });-- test('opens a native socket when the session resolves the gateway as DIRECT', async () => {- const {routes, mainDocument, native} = createTransport({resolveProxy: async () => ' DIRECT '});- await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- assert.equal(native.connections.length, 1);- });-- test('resolves the proxy route while the origin admission is still in flight', async () => {- let releaseAdmission;- const admissionGate = new Promise((resolve) => {- releaseAdmission = resolve;- });- const registry = new GatewayOriginRegistry({- resolveAnchorGatewayOrigin: async (anchor) => {- await admissionGate;- return anchor === APP_ORIGIN ? 'wss://gateway.fluxer.app/' : null;- },- });- registry.seedAnchorOrigin(APP_ORIGIN);- let proxyLookups = 0;- const {routes, mainDocument, native} = createTransport({- registry: {registry},- resolveProxy: async () => {- proxyLookups += 1;- return 'DIRECT';- },- });- const created = routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](mainDocument.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(proxyLookups, 1);- assert.equal(native.connections.length, 0);- releaseAdmission();- await created;- assert.equal(native.connections.length, 1);- });-- test('reports availability from the boundary the shell actually loaded', async () => {- const withAddon = createTransport();- assert.equal(- await withAddon.routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.isAvailable](withAddon.mainDocument.event),- true,- );- const origins = createRegistry();- const withoutAddon = new DesktopNativeGatewayTransport({- boundary: null,- logger: {info: () => {}, warn: () => {}, error: () => {}},- originRegistry: origins.registry,- requireCleartextGatewayAddress: refuseCleartextGatewayAddress,- resolveProxy: async () => 'DIRECT',- rendererDocumentOwners: new RendererDocumentOwnerFactory({- policy: {isPrivilegedRendererDocument: () => true},- onWatcherFailure: () => {},- }),- });- const routes = withoutAddon.ipcRoutes();- const document = createDocument();- assert.equal(await routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.isAvailable](document.event), false);- await rejects(- routes[NATIVE_GATEWAY_TRANSPORT_CHANNELS.create](document.event, {- connectionId: nextConnectionId(),- url: GATEWAY_URL,- mode: 'gateway',- }),- /addon is unavailable/u,- );- });-});--describe('GatewayOriginRegistry', () => {- test('admits an origin an anchor instance advertises and caches it for the document', async () => {- const {registry, resolved} = createRegistry();- const document = {};- assert.equal(await registry.admit({documentKey: document, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- assert.deepEqual(resolved, [APP_ORIGIN]);- assert.equal(await registry.admit({documentKey: document, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- assert.deepEqual(resolved, [APP_ORIGIN]);- });-- test('keys admission per renderer document', async () => {- const {registry} = createRegistry();- await registry.admit({documentKey: {}, url: GATEWAY_URL});- const second = {};- assert.equal(await registry.admit({documentKey: second, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- });-- test('admits the gateway a runtime plan advertises without fetching discovery again', async () => {- const resolved = [];- let anchorReads = 0;- const registry = new GatewayOriginRegistry({- additionalAnchorOrigins: async () => {- anchorReads += 1;- return ['other.example'];- },- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return null;- },- });- registry.recordAnchorGateway(`${APP_ORIGIN}/api`, 'wss://gateway.fluxer.app');- assert.equal(await registry.admit({documentKey: {}, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- assert.deepEqual(resolved, []);- assert.equal(anchorReads, 0);- });-- test('still fetches discovery for a gateway no recorded runtime plan advertises', async () => {- const resolved = [];- const registry = new GatewayOriginRegistry({- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === 'https://gateway.fluxer.app' ? 'wss://gateway.fluxer.app' : null;- },- });- registry.recordAnchorGateway(`${APP_ORIGIN}/api`, 'wss://gateway.other.example');- assert.equal(await registry.admit({documentKey: {}, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- assert.deepEqual(resolved, ['https://gateway.fluxer.app']);- });-- test('fetches discovery for a recorded runtime plan that advertises no gateway', async () => {- const resolved = [];- const registry = new GatewayOriginRegistry({- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === APP_ORIGIN ? 'wss://gateway.fluxer.app' : null;- },- });- registry.recordAnchorGateway(`${APP_ORIGIN}/api`, null);- assert.equal(await registry.admit({documentKey: {}, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- assert.deepEqual(resolved, [APP_ORIGIN]);- });-- test('fetches discovery again once a recorded runtime plan gateway expires', async () => {- let now = 1_000_000;- const resolved = [];- const registry = new GatewayOriginRegistry({- now: () => now,- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === APP_ORIGIN ? 'wss://gateway.fluxer.app' : null;- },- });- registry.recordAnchorGateway(`${APP_ORIGIN}/api`, 'wss://gateway.fluxer.app');- await registry.admit({documentKey: {}, url: GATEWAY_URL});- assert.deepEqual(resolved, []);- now += 6 * 60 * 60 * 1000 + 1;- await registry.admit({documentKey: {}, url: GATEWAY_URL});- assert.deepEqual(resolved, [APP_ORIGIN]);- });-- test('tries the target own HTTP origin as a last anchor for single-host self-hosters', async () => {- const resolved = [];- const registry = new GatewayOriginRegistry({- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === 'https://self.example' ? 'wss://self.example/gateway' : null;- },- });- assert.equal(await registry.admit({documentKey: {}, url: 'wss://self.example/gateway'}), 'wss://self.example');- assert.deepEqual(resolved, ['https://self.example']);- });-- test('tries a known instance origin so a split-host self-hoster still connects', async () => {- const registry = new GatewayOriginRegistry({- additionalAnchorOrigins: async () => ['self.example'],- resolveAnchorGatewayOrigin: async (anchor) =>- anchor === 'https://self.example' ? 'wss://gateway.self.example' : null,- });- assert.equal(- await registry.admit({documentKey: {}, url: 'wss://gateway.self.example/'}),- 'wss://gateway.self.example',- );- });-- test('shares one in-flight admission so concurrent sockets on the same origin all connect', async () => {- const now = 1_000_000;- const resolved = [];- const registry = new GatewayOriginRegistry({- now: () => now,- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === APP_ORIGIN ? 'wss://gateway.fluxer.app/' : null;- },- });- registry.seedAnchorOrigin(APP_ORIGIN);- const document = {};- const admitted = await Promise.all([- registry.admit({documentKey: document, url: GATEWAY_URL}),- registry.admit({documentKey: document, url: GATEWAY_URL}),- registry.admit({documentKey: document, url: GATEWAY_URL}),- ]);- assert.deepEqual(admitted, [GATEWAY_WS_ORIGIN, GATEWAY_WS_ORIGIN, GATEWAY_WS_ORIGIN]);- assert.deepEqual(resolved, [APP_ORIGIN]);- });-- test('refuses a second attempt on the same origin within a second', async () => {- let now = 1_000_000;- const registry = new GatewayOriginRegistry({now: () => now, resolveAnchorGatewayOrigin: async () => null});- const document = {};- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /no reachable instance/u);- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /attempted too recently/u);- now += 1000;- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /no reachable instance/u);- });-- test('refuses more than eight distinct origins in a minute and sixty-four per document', async () => {- let now = 1_000_000;- const registry = new GatewayOriginRegistry({now: () => now, resolveAnchorGatewayOrigin: async () => null});- const document = {};- for (let index = 0; index < 8; index += 1) {- now += 1;- await rejects(registry.admit({documentKey: document, url: `wss://host-${index}.example/`}), /no reachable/u);- }- now += 1;- await rejects(registry.admit({documentKey: document, url: 'wss://host-8.example/'}), /too many origins/u);- now += 60_000;- let attempts = 8;- while (attempts < 64) {- now += 60_000;- await rejects(registry.admit({documentKey: document, url: `wss://host-${attempts}.example/`}), /no reachable/u);- attempts += 1;- }- now += 60_000;- await rejects(- registry.admit({documentKey: document, url: 'wss://host-100.example/'}),- /exhausted its origin registration budget/u,- );- });-- test('re-verifies an admitted origin after the six hour TTL', async () => {- let now = 1_000_000;- const resolved = [];- const registry = new GatewayOriginRegistry({- now: () => now,- resolveAnchorGatewayOrigin: async (anchor) => {- resolved.push(anchor);- return anchor === APP_ORIGIN ? 'wss://gateway.fluxer.app/' : null;- },- });- registry.seedAnchorOrigin(APP_ORIGIN);- const document = {};- await registry.admit({documentKey: document, url: GATEWAY_URL});- now += 6 * 60 * 60 * 1000 + 1;- await registry.admit({documentKey: document, url: GATEWAY_URL});- assert.equal(resolved.length, 2);- });-- test('does not cache a discovery failure for six hours', async () => {- let now = 1_000_000;- let advertised = null;- const registry = new GatewayOriginRegistry({now: () => now, resolveAnchorGatewayOrigin: async () => advertised});- registry.seedAnchorOrigin(APP_ORIGIN);- const document = {};- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /no reachable instance/u);- advertised = 'wss://gateway.fluxer.app/';- now += 60 * 1000 + 1;- assert.equal(await registry.admit({documentKey: document, url: GATEWAY_URL}), GATEWAY_WS_ORIGIN);- });-- test('releases a document state so a reload starts from a clean budget', async () => {- const now = 1_000_000;- const registry = new GatewayOriginRegistry({now: () => now, resolveAnchorGatewayOrigin: async () => null});- const document = {};- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /no reachable/u);- registry.releaseDocument(document);- await rejects(registry.admit({documentKey: document, url: GATEWAY_URL}), /no reachable/u);- });-});--describe('native gateway kill switches', () => {- test('names the launch flag, the environment variable and safe mode as disable reasons', () => {- assert.equal(getNativeGatewayDisableReason([]), null);- assert.equal(getNativeGatewayDisableReason(['--fluxer-disable-native-gateway']), '--fluxer-disable-native-gateway');- assert.equal(getNativeGatewayDisableReason(['--fluxer-safe-mode']), '--fluxer-safe-mode');- process.env.FLUXER_DISABLE_NATIVE_GATEWAY = '1';- try {- assert.equal(getNativeGatewayDisableReason([]), 'FLUXER_DISABLE_NATIVE_GATEWAY');- } finally {- delete process.env.FLUXER_DISABLE_NATIVE_GATEWAY;- }- });-- test('the renderer reports isAvailable false when the shell passes no availability argument', async () => {- const invoked = [];- const renderer = {- invoke: async (channel, ...args) => {- invoked.push({channel, args});- return channel === NATIVE_GATEWAY_TRANSPORT_CHANNELS.isAvailable ? false : undefined;- },- on: () => {},- removeListener: () => {},- };- const disabled = createNativeGatewayPreloadAPI(renderer, ['electron']).nativeGatewayTransport;- assert.equal(disabled.isAvailable, false);- await rejects(- disabled.create({connectionId: nextConnectionId(), url: GATEWAY_URL, mode: 'gateway'}),- /unavailable in this desktop shell/u,- );- const enabled = createNativeGatewayPreloadAPI(renderer, [- 'electron',- NATIVE_GATEWAY_TRANSPORT_AVAILABLE_RENDERER_ARG,- ]).nativeGatewayTransport;- assert.equal(enabled.isAvailable, true);- });-- test('the preload create awaits the main availability gate exactly once', async () => {- let probes = 0;- const renderer = {- invoke: async (channel) => {- if (channel === NATIVE_GATEWAY_TRANSPORT_CHANNELS.isAvailable) {- probes += 1;- return true;- }- return {connectionId: 'ok'};- },- on: () => {},- removeListener: () => {},- };- const api = createNativeGatewayPreloadAPI(renderer, [- 'electron',- NATIVE_GATEWAY_TRANSPORT_AVAILABLE_RENDERER_ARG,- ]).nativeGatewayTransport;- await api.create({connectionId: nextConnectionId(), url: GATEWAY_URL, mode: 'gateway'});- await api.create({connectionId: nextConnectionId(), url: GATEWAY_URL, mode: 'gateway'});- assert.equal(probes, 1);- });-- test('the preload drops an event that fails its own validation and detaches on unsubscribe', () => {- const listeners = [];- const renderer = {- invoke: async () => undefined,- on: (_channel, listener) => listeners.push(listener),- removeListener: (_channel, listener) => {- const index = listeners.indexOf(listener);- if (index >= 0) listeners.splice(index, 1);- },- };- const api = createNativeGatewayPreloadAPI(renderer, ['electron']).nativeGatewayTransport;- const received = [];- const unsubscribe = api.onEvent((event) => received.push(event));- listeners[0](null, {kind: 'open'});- assert.equal(received.length, 0);- listeners[0](null, {- connectionId: nextConnectionId(),- kind: 'open',- data: null,- binary: null,- code: null,- reason: null,- wasClean: null,- message: null,- });- assert.equal(received.length, 1);- unsubscribe();- assert.equal(listeners.length, 0);- });-});diff --git a/fluxer_desktop/src/main/OfficialInstanceAlias.test.mjs b/fluxer_desktop/src/main/OfficialInstanceAlias.test.mjsdeleted file mode 100644index 8225e8ce8..000000000--- a/fluxer_desktop/src/main/OfficialInstanceAlias.test.mjs+++ /dev/null@@ -1,69 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {OFFICIAL_CLIENT_API_ENDPOINTS, officialClientApiEndpointForAlias} = await import(- '@fluxer/instance_bootstrap/src/OfficialInstance'-);-const {localAppRuntimeInstanceKey} = await import('./LocalAppRuntimePlans.ts');--describe('resolving an official client API alias', () => {- test('the migrated domain same-origin API is the official instance of its channel', () => {- assert.equal(officialClientApiEndpointForAlias('https://fluxer.com/api'), OFFICIAL_CLIENT_API_ENDPOINTS.stable);- assert.equal(- officialClientApiEndpointForAlias('https://canary.fluxer.com/api'),- OFFICIAL_CLIENT_API_ENDPOINTS.canary,- );- });-- test('the legacy web origins already are the official instance of their channel', () => {- assert.equal(officialClientApiEndpointForAlias('https://web.fluxer.app/api'), OFFICIAL_CLIENT_API_ENDPOINTS.stable);- assert.equal(- officialClientApiEndpointForAlias('https://web.canary.fluxer.app/api'),- OFFICIAL_CLIENT_API_ENDPOINTS.canary,- );- });-- test('the official endpoint is its own instance key in the main process', () => {- for (const endpoint of Object.values(OFFICIAL_CLIENT_API_ENDPOINTS)) {- assert.equal(localAppRuntimeInstanceKey(endpoint), endpoint);- }- });-- test('spelling differences do not create a second identity', () => {- for (const spelling of [- 'https://canary.fluxer.com/api/',- 'https://canary.fluxer.com/api//',- 'HTTPS://CANARY.FLUXER.COM/api',- 'https://canary.fluxer.com:443/api',- ' https://canary.fluxer.com/api ',- ]) {- assert.equal(officialClientApiEndpointForAlias(spelling), OFFICIAL_CLIENT_API_ENDPOINTS.canary, spelling);- }- });-- test('anything that is not an official same-origin client API is left alone', () => {- for (const other of [- 'https://canary.fluxer.com',- 'https://canary.fluxer.com/',- 'https://canary.fluxer.com/api/v1',- 'https://canary.fluxer.com/API',- 'http://canary.fluxer.com/api',- 'https://canary.fluxer.com:8443/api',- 'https://user:[email protected]/api',- 'https://canary.fluxer.com/api?x=1',- 'https://canary.fluxer.com/api#f',- 'https://api.fluxer.app/api',- 'https://fluxer.app/api',- 'https://evil.fluxer.com.example.test/api',- 'https://chat.example.test/api',- '/api',- '',- 'not a url',- ]) {- assert.equal(officialClientApiEndpointForAlias(other), null, other);- }- });-});diff --git a/fluxer_desktop/src/main/fixtures/TsModuleLoader.mjs b/fluxer_desktop/src/main/fixtures/TsModuleLoader.mjsdeleted file mode 100644index 9c2249d54..000000000--- a/fluxer_desktop/src/main/fixtures/TsModuleLoader.mjs+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {readFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {fileURLToPath} from 'node:url';-import vm from 'node:vm';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const sourceRoots = {- '@electron/main/': new URL('../', import.meta.url),- '@electron/common/': new URL('../../common/', import.meta.url),- '@fluxer/': new URL('../../../../packages/', import.meta.url),-};--function resolveSourcePath(specifier) {- for (const [prefix, root] of Object.entries(sourceRoots)) {- if (specifier.startsWith(prefix)) {- return fileURLToPath(new URL(`${specifier.slice(prefix.length)}.ts`, root));- }- }- return null;-}--export function loadTsModule(specifier, {stubs = {}} = {}) {- const cache = new Map();- const load = (moduleSpecifier) => {- if (Object.hasOwn(stubs, moduleSpecifier)) return stubs[moduleSpecifier];- const sourcePath = resolveSourcePath(moduleSpecifier);- if (sourcePath === null) throw new Error(`Unexpected import: ${moduleSpecifier}`);- const cached = cache.get(sourcePath);- if (cached) return cached.exports;- const transformed = esbuild.transformSync(readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',- }).code;- const module = {exports: {}};- cache.set(sourcePath, module);- const factory = vm.runInThisContext(`(function (require, module, exports) {${transformed}\n})`, {- filename: sourcePath,- });- factory(load, module, module.exports);- return module.exports;- };- return load(specifier);-}diff --git a/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.key b/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.keydeleted file mode 100644index 446dc8d4f..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.key+++ /dev/null@@ -1,5 +0,0 @@------BEGIN PRIVATE KEY------MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgjRw9RoOHDfdSs087-7vd6ZmYW1AJE4+6LGqJW4RJfvs+hRANCAAQvRk8uN0d9x8o01QFpd75RxviSJhaZ-nr4iEQRdEGEs+OKic0Cm9nHwBSainqm0kO8YKlT9cq2RI1jK9rqM9hIt------END PRIVATE KEY-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.pemdeleted file mode 100644index afeeb27dd..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-tls/leaf.pem+++ /dev/null@@ -1,12 +0,0 @@------BEGIN CERTIFICATE------MIIBzDCCAXGgAwIBAgIUFo38/sRgT50k5RgWhjrjAqkyUxwwCgYIKoZIzj0EAwIw-ITEfMB0GA1UEAwwWRmx1eGVyIFRlc3QgdHJ1c3RlZCBDQTAgFw0yNjEwMDgxMTAw-NDVaGA8yMTI2MDkxNDExMDA0NVowFTETMBEGA1UEAwwKY2EuZXhhbXBsZTBZMBMG-ByqGSM49AgEGCCqGSM49AwEHA0IABC9GTy43R33HyjTVAWl3vlHG+JImFpmeviIR-BF0QYSz44qJzQKb2cfAFJqKeqbSQ7xgqVP1yrZEjWMr2uoz2Ei2jgZAwgY0wGwYD-VR0RBBQwEoIKY2EuZXhhbXBsZYcEfwAAATAJBgNVHRMEAjAAMA4GA1UdDwEB/wQE-AwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATAdBgNVHQ4EFgQUrTpUZ2NXWO1wgiIJ-5SXBE3OlT+MwHwYDVR0jBBgwFoAUekfvEi5SI/1J8dOCNgGBW+TJQGUwCgYIKoZI-zj0EAwIDSQAwRgIhALqUP9Hm71LmvrbIuP9IIrG2efo70QPNL0n3caoCmVO8AiEA-p7IbBwavgmqy6QhAkIgH5BPAQ4n37fP0UyeZVetYFII=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-tls/trusted-ca.pem b/fluxer_desktop/src/main/fixtures/desktop-tls/trusted-ca.pemdeleted file mode 100644index e7d284ba5..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-tls/trusted-ca.pem+++ /dev/null@@ -1,11 +0,0 @@------BEGIN CERTIFICATE------MIIBqTCCAU+gAwIBAgIUM6OwmZlGxvxbg2ReQWwRMOy5H0swCgYIKoZIzj0EAwIw-ITEfMB0GA1UEAwwWRmx1eGVyIFRlc3QgdHJ1c3RlZCBDQTAgFw0yNjEwMDgxMTAw-NDVaGA8yMTI2MDkxNDExMDA0NVowITEfMB0GA1UEAwwWRmx1eGVyIFRlc3QgdHJ1-c3RlZCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABH+hGFbBocy+br8Lt+lE-9usokqgUdcJEEE8F1DSwzKqtTXYqaNQ1IbnjnYOnMzMP3C8SH+Z+W7h4CCgbeCHo-3FCjYzBhMB0GA1UdDgQWBBR6R+8SLlIj/Unx04I2AYFb5MlAZTAfBgNVHSMEGDAW-gBR6R+8SLlIj/Unx04I2AYFb5MlAZTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB-/wQEAwIBBjAKBggqhkjOPQQDAgNIADBFAiEA9ZiceuAgmWNbt1iGI8pIEKJnEBOK-B2EbyL9bNslsOwcCICmZwV2NHSnLTVtNiPqQDkRskugRL5ywBhddeqApBdk6------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-tls/untrusted-ca.pem b/fluxer_desktop/src/main/fixtures/desktop-tls/untrusted-ca.pemdeleted file mode 100644index 6b9c4206e..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-tls/untrusted-ca.pem+++ /dev/null@@ -1,12 +0,0 @@------BEGIN CERTIFICATE------MIIBrTCCAVOgAwIBAgIUXHirlkuWFHOEJ+x5lRwAyIeQH0AwCgYIKoZIzj0EAwIw-IzEhMB8GA1UEAwwYRmx1eGVyIFRlc3QgdW50cnVzdGVkIENBMCAXDTI2MTAwODEx-MDA0NVoYDzIxMjYwOTE0MTEwMDQ1WjAjMSEwHwYDVQQDDBhGbHV4ZXIgVGVzdCB1-bnRydXN0ZWQgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASYetrmC6ot/0o0-jxSFQRVFuZBzfdGYnOZ41+N2Jao9/6CoxuD+pqjOJ+NAjLP5QSMBuoaYaDKRzq+r-jDlVf+JJo2MwYTAdBgNVHQ4EFgQUi/e+X9VSTPlOrhbO2BAqjCl28OAwHwYDVR0j-BBgwFoAUi/e+X9VSTPlOrhbO2BAqjCl28OAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV-HQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwIDSAAwRQIhAN9+gjPnixgQHJqspIqJG2x7-jPmFxBGV9fQiEUM14NzAAiAt4pdRQ+sHc1VHsfEeUUHS2W0+UKoc/XHTjDZtppEH-Xw==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/bool_01_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/bool_01_leaf.pemdeleted file mode 100644index 0c82d303f..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/bool_01_leaf.pem+++ /dev/null@@ -1,18 +0,0 @@------BEGIN CERTIFICATE------MIIC5TCCAc2gAwIBAgIBTjANBgkqhkiG9w0BAQsFADAaMRgwFgYDVQQDDA9UcnVz-dCBUZXN0IFJvb3QwIhgPMjAyNTAxMDEwMDAwMDBaGA8yMTI1MDEwMTAwMDAwMFow-DDEKMAgGA1UEAwwBeDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALdv-Oze1slSycxDpCnpZYKClaHOXTRWnzAI8mHMhoiEpgjmXrbN1T75+aruMCQAr2VSB-1YOkxzf8Ntsb0ACfaSEJj2AwcCR6NfXoYbbSIE+V//1HkD/BbrOCUb81wubNFxjd-RZpJjhr6x6wb7DDM5rh8ly2t92N6r9Kh6il7Nssf27v2UZbb8XsjPgKxz2YmCtT8-Ry5ZiwGes9e4qEzV650Fl4xVjOiKKTJMy7ByNnm7guqL8ALhyHoIeRZUmTF85D4I-Pp90AkkMv9qjYllv5pBDHMjj68VldwhTYRTGAvhZjy8eIXA0OQXbpySPL5i8TZVM-O4jLoJFm3Kn5WIvdWO8CAwEAAaNAMD4wDgYDVR0PAQEBBAQDAgWgMBMGA1UdJQQM-MAoGCCsGAQUFBwMBMBcGA1UdEQQQMA6CDGhvc3QuZXhhbXBsZTANBgkqhkiG9w0B-AQsFAAOCAQEAftI9a2g+PexV+mSm/HHLxeGuWdK0IB5Dts/WhisGgAnxjabbZHJI-UZ6GoD5iQqX8RpZMqF2Cilq1oDfBUoWIujHG4JEzTj3WA0vQOE5wgcsmO4QcypNJ-cEn2KezBgDqzWbJ1hTRA3wwlzzOqJIHStt+4QjwetFvhM36R2o/6WzDlfyKmPSIi-1+eQYA7vl2DWr/j13+Oo3e4X/Uqr9KIVJPNYCdg73oRmi98gTi4aNvBcCb2Pz7ty-8lVgQ3iCysa2LYqk14pfGLm2Rs4QeYC0rRI0z3/Jbu5W81Y09FhW+5yyp9pJXmjO-ZxT7ZtgZsmmqp8iW7vpyQjQMhBA+HKtTBg==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/bool_ff_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/bool_ff_leaf.pemdeleted file mode 100644index 30db29594..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/bool_ff_leaf.pem+++ /dev/null@@ -1,18 +0,0 @@------BEGIN CERTIFICATE------MIIC5TCCAc2gAwIBAgIBTTANBgkqhkiG9w0BAQsFADAaMRgwFgYDVQQDDA9UcnVz-dCBUZXN0IFJvb3QwIhgPMjAyNTAxMDEwMDAwMDBaGA8yMTI1MDEwMTAwMDAwMFow-DDEKMAgGA1UEAwwBeDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALdv-Oze1slSycxDpCnpZYKClaHOXTRWnzAI8mHMhoiEpgjmXrbN1T75+aruMCQAr2VSB-1YOkxzf8Ntsb0ACfaSEJj2AwcCR6NfXoYbbSIE+V//1HkD/BbrOCUb81wubNFxjd-RZpJjhr6x6wb7DDM5rh8ly2t92N6r9Kh6il7Nssf27v2UZbb8XsjPgKxz2YmCtT8-Ry5ZiwGes9e4qEzV650Fl4xVjOiKKTJMy7ByNnm7guqL8ALhyHoIeRZUmTF85D4I-Pp90AkkMv9qjYllv5pBDHMjj68VldwhTYRTGAvhZjy8eIXA0OQXbpySPL5i8TZVM-O4jLoJFm3Kn5WIvdWO8CAwEAAaNAMD4wDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQM-MAoGCCsGAQUFBwMBMBcGA1UdEQQQMA6CDGhvc3QuZXhhbXBsZTANBgkqhkiG9w0B-AQsFAAOCAQEAddtLsvQf8S/uuGyOMUgV8NKw4Ki1kX+BTr5xzsq1A01WgCfdYG5u-HL32V6uATwDzO3cH3piDoGLoXAF0sstnciBnfeibCgeBcOrj/8PTXGrRch5kkHnw-kK3OBZQSutT4BafIKoVIpiH95+3t/5sy2dWSkt1NGQN7noPBgddqSTmDiq4nxx+i-LQ+NhT5sX+AkWB6GZNyxnvEC1UtUJiY7k8DQIvV5vLPj4+oCa7XRiY/8rFzVoyBo-5Yq5FP5WgyGXKlWLhtwIeaD+7pAYjrUSnrTR9gWJsJ0l6/vCWhH3aT2vbPf9JUwS-3aHt4faDpfGbcvhlkXWyKHS7T3XYgnFf4A==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/crit_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/crit_leaf.pemdeleted file mode 100644index d10165a88..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/crit_leaf.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDWjCCAkKgAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaewwDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NVoY-DzIxMjYwOTE0MTcxOTQ1WjAMMQowCAYDVQQDDAF4MIIBIjANBgkqhkiG9w0BAQEF-AAOCAQ8AMIIBCgKCAQEAvD4+ud9Fp9RwYMtvhL366FKGNhEL6Y6oTouFjU97eQ4a-jTBIgizBsc2CwOoFyNAIK5UDRw68Kvs3m417L07BiDoTh4Y8J/62CKAGsJ5S2KAw-xgZh3BIyvs0gLGa5CAy0FqZ5tzCe546XHZdeGg4ETW3zEQmkB1Zq1ZwtCPX86pr4-N2MrKthotsaRug7ZQ5I8KC0XI819zdA2Bi6LvXIUCilDaWfZb9oeRUsrNCBzTvX4-/uL2sMJDwuiP1Dfk7heqnjsvP2s9N+0k6uw3thIBisTy4F2yhCpfCi9WT+OJZoEH-UjLgOAR0H2fhAVPBR9YTPtVwy7di0PMWsYdfYGvB4QIDAQABo4GjMIGgMAwGA1Ud-EwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB8G-A1UdIwQYMBaAFDl9W8k1XKQCubIn46G/oYwjeDkqMBcGA1UdEQQQMA6CDGhvc3Qu-ZXhhbXBsZTASBgkrBgEEAYaNHwEBAf8EAgUAMB0GA1UdDgQWBBQmoqL8NAcX6wuB-1XmVPq0bFnxPKDANBgkqhkiG9w0BAQsFAAOCAQEAYZQW4q0zeprbMilnHRk6C6Td-sXOaOHhB5DiRZW1wjhe3LO1zPLe/nckzqFG+g+jTFa7nLuC6APRlj1yk0pCoyWiD-zkHtdPDy1VdkkIOMEcPdMVPOgEPcIZYFZY77sMz4Ac8d6qRlAcqhJDKwapaQYGZV-ddy1pwPNZxk3EL0DcXYRThD/VOk3FuxZRZseuFNUkdyQ8a14bv+2mrHCFHcYxH26-Q73GvjMsyuL2oncG/ZhFza2kXoOUzi+ZHWh/KIDtWGruXLeFYDvEssaUUVykP2mV-0hy/XEGdOZmUP88GJ4N4CYu1SSn1shGiho42KLrXwpnDqOp43+bAUIOJAYnV1A==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/ec_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/ec_leaf.pemdeleted file mode 100644index 0d2542d8b..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/ec_leaf.pem+++ /dev/null@@ -1,16 +0,0 @@------BEGIN CERTIFICATE------MIICezCCAWOgAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaecwDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NFoY-DzIxMjYwOTE0MTcxOTQ0WjAMMQowCAYDVQQDDAF4MFkwEwYHKoZIzj0CAQYIKoZI-zj0DAQcDQgAEHHjSNNp5dsZfAnkKCGhzX70d/Ulaz8UFm9caIp6vOi2y1EXi10dZ-VAEgXal5HYc27/wbIFqLztnfofpu+0SlEqOBjzCBjDAMBgNVHRMBAf8EAjAAMA4G-A1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAfBgNVHSMEGDAWgBQ5-fVvJNVykArmyJ+Ohv6GMI3g5KjAXBgNVHREEEDAOggxob3N0LmV4YW1wbGUwHQYD-VR0OBBYEFNjhzyL6G+did2jKx0TJnTj2NhWHMA0GCSqGSIb3DQEBCwUAA4IBAQCs-ITZEqDiKXMtJvSrnfJ6ZGwuQBy/AU3tbw/DlCvTr/UMfcZk8qJ92otWf3MRgKOU7-XBgvCdruxCcG0ST3GqLq9PmGVt+fMwsx5FGF/qzWlDK8ZkFi0Adzsptw732v3/0H-BR8rh+59/NUmyLnag6Xw+nOY0boCVJ87CtNgBNsVmUL65YmVgCHEopen7Fv1q5ms-uGgi+HtWxfGnSiz+4Upw6RdcNmedH+F5M8wzZ4q4Iv4Wmupz3iaLdwGcucpuuC1R-6HIrDOEk+TOBofytCEd+iDorjjIXxNsgBDQf/gjKCvtHh7OVX0MFgQysgPNyIDC6-9mhFYM4YwMfhsMauBm5x------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/eku_int.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/eku_int.pemdeleted file mode 100644index d9e392c50..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/eku_int.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDNDCCAhygAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaeowDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NFoY-DzIxMjYwOTE0MTcxOTQ0WjASMRAwDgYDVQQDDAdFS1UgSW50MIIBIjANBgkqhkiG-9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4v27QD9YFXG8+oPhwytCyErQCaV2PYeHGVm/-l0D0zc+9EHQfI6UbKC/1KjRXgMjmsFNGpGEAj2xVwXMsN04QmsxBhSrrOqrH36Fw-adSj5ewBaKf5/jaFOkJ8O1t4NOl4Ki0Fle4Op6r6IJZwzGpy4qNqlYbgRoPj8H7J-R9BufEtoC18jXcQNlwQP/4go7sq4YwtbFjOJ9mK/mlaAeD9zCb3LApLcYyQyqQaQ-bFEOMifJhCNE6WxbrTXH/+nTEM7nmPaGFqzovAf+0PBNjTkYSd+NqZJDD/fvU3XF-VMiqlAWj8R/UP03KKoTemqey9rXxbocxLTh0wJr/gPjOt7/+VQIDAQABo3gwdjAP-BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUMG5Sf79f-OgByO3UsgJsjlV8lvfEwHwYDVR0jBBgwFoAUOX1byTVcpAK5sifjob+hjCN4OSow-EwYDVR0lBAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAFprsUH/ZoMC-QgPZUnW33Tc5tnsEMBgREiqU5LDKdXAy9Qko1b/C2JaDIefYntBcu7eIlLVAfhSs-cBk+XhgditEjAG5yYjV/NPZRh/+L4OjVcVmFRtCtQ+z+DGwVWGn3PzbUL228izFK-djJOitXUPFGu8U1sbA/zv6Z+DpngnLkRWFwJz8cl84beyCnaExXh2MIg3AleDNdf-FoVU0lylC47nx9FHqEthOtGqRn7BHi49htqcCXd4E4OE3c8CLKU0WTRP8ofjK0FW-IdwXVsxWSheDVWRa1Gs3OOsv2TPWRyaRhEQ9mcCws7nVMbhZ94HIC3Rixy3YcLPY-vQXMYpMWrgo=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/eku_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/eku_leaf.pemdeleted file mode 100644index aff345371..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/eku_leaf.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDPjCCAiagAwIBAgIUOuSVRC3VFKpaTRwNlFx7hNY+hPUwDQYJKoZIhvcNAQEL-BQAwEjEQMA4GA1UEAwwHRUtVIEludDAgFw0yNjEwMDgxNzE5NDRaGA8yMTI2MDkx-NDE3MTk0NFowDDEKMAgGA1UEAwwBeDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC-AQoCggEBAMYnHmYegqC2h4F4iCFCMo/jGGtOLPmVj4QoX676VEq7Ilw1qMoLfKwe-neNYPt0odizU1wWGf0SuEZ3QrWT5kgh14yzu0AQPboYUpMeYwkIjSxclrMbKqN63-bVT8BVYYuAnOV+4wGKLtSjZS2c3QcJKUijp+C50jyYdJ3DHYuiOviiaCSsCL7jo5-W6I4q5GfyifGA+T089YnLtlQYljhsqz2CWRNsxObD0RcjiAls23ZUAARKVU5cZ/V-PO2H/zF7tSuRSA8nE3/HepSO5pOcAS0/Gz0AEqmr9FdGztixhJ55RLfMIAGDDM3G-DC1wzg/Q0iG53vuJpmIEVpfx3ED5i/sCAwEAAaOBjzCBjDAMBgNVHRMBAf8EAjAA-MA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAfBgNVHSMEGDAW-gBQwblJ/v186AHI7dSyAmyOVXyW98TAXBgNVHREEEDAOggxob3N0LmV4YW1wbGUw-HQYDVR0OBBYEFNtHkj6LRNuSCFCEDvWcb/vaxmOKMA0GCSqGSIb3DQEBCwUAA4IB-AQCymlwRyp0JOXJltxNG5qHLpes+juIN9p5COTs9FhvAkpC58W+w1ynkN23J1UVk-WA5G1t5BOO/eyU7lZkdabDA/Mb0hvxdWIG4a028EUkd8vgkJEeDjPbjSZDPaIdL8-RAq9lq88LcetWP9g8NOZRFBhDbigphqYmwGNzk/J1ZIYhOfsNr0SU5BU/xe4ogT1-WmcBkaPw9g+7yPsevNXNmaMPlcKRiEL9AJA4rMZSU8aLnZ4+WXRleQnhSzHdBWPx-Li2jb41I39ECmY7gXPCJqRAORcaov4AO8WZCNVKqRLd/uFmOddpBABlPN9RyiyIn-pivGrcARZfTLYxHrOpQu74gz------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/int.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/int.pemdeleted file mode 100644index cd2349dbd..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/int.pem+++ /dev/null@@ -1,19 +0,0 @@------BEGIN CERTIFICATE------MIIDJjCCAg6gAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaeYwDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0M1oY-DzIxMjYwOTE0MTcxOTQzWjAZMRcwFQYDVQQDDA5UcnVzdCBUZXN0IEludDCCASIw-DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKTTaf/jUVe80O44xs2+jRQSnv7w-zKiGMUnDMTwLheS3NlOuXUJAPfggtOUmp8fWdLUi9tmvwO/jSjOZZLnQ2fz9bGiV-Oovs9y9TgywdxOH1nnCMQ+hKLw0cMdk8X2Pm8wGZdGEblEcPJBXFF09JX1t6y3h6-cHlV5tpxdAUjNNdxjREnXclixWUPBDF4IziRrg4fOi+aB5FFREhhKLGlvJJ0NNq5-t9N3quFHoQCAGvwrnQQXsey58zRF58yK1AS6VrNMvkYRhcs/N+5W8Cxb6hVhthhz-0n96GgJ1BcGwpSGPC/69WpZHQot9VrT6qUoKJHUg3fnTHyzodJcRkHyAsKUCAwEA-AaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE-FGa9d7RPsqY3+fnUCK3+sbIHKdCZMB8GA1UdIwQYMBaAFDl9W8k1XKQCubIn46G/-oYwjeDkqMA0GCSqGSIb3DQEBCwUAA4IBAQDJsifCCoydUHayqGMitWtCnAhts+hz-bOtYafchsnsmgn+LyetPC5ghdocn7QBHFZqmwoSfmZG2xrS5YfwSNJH5a65meFF1-Ca0eqxo0KZcNt3YSMH5bEOf1aphw9ame/UqNB89ZjJjSoIF2/Us/Yr2uLO0LLBmK-01HF1JqWFIXUOZ7g0VPhR1ulV7apYFvgXUtj0A9PUWOcJb+lxrepU4uWbV4TN0BM-EveNKX91kIzujemL0L1LDKpqU76lUG9sPAVrareKBDsDP9h4xGOJLzsybK0tpFHS-5rXCepsRIh2h9liL4ofxyIrD3bMKlSd/mo5hC6EaaHCLh4XtRuw8Iw93------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/kz_root.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/kz_root.pemdeleted file mode 100644index 8001e0de2..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/kz_root.pem+++ /dev/null@@ -1,35 +0,0 @@------BEGIN CERTIFICATE------MIIGFDCCA/ygAwIBAgIUKH3ODOPG96qjP/ll526pjIJKWdswDQYJKoZIhvcNAQEL-BQAwVjE4MDYGA1UEAxMvSW5mb3JtYXRpb24gU2VjdXJpdHkgQ2VydGlmaWNhdGlv-biBBdXRob3JpdHkgQ0ExDTALBgNVBAoTBElTQ0ExCzAJBgNVBAYTAktaMB4XDTIw-MDIyODA0MDgwM1oXDTQwMDIyODA0MDgwM1owVjE4MDYGA1UEAxMvSW5mb3JtYXRp-b24gU2VjdXJpdHkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgQ0ExDTALBgNVBAoT-BElTQ0ExCzAJBgNVBAYTAktaMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKC-AgEA2Q8hjYT89iYfD+gdxiaKw5NNRq0sfKDj1xAXbtmhQh+tA5DhnVPehqFybVFH-ZBsyMwmL9SA4Bp/2ytE7CmnDefqg9xfRuNX2p6RzUgrsarYaZgXgaPW+g/TZ+nXU-uGgYb1I01XOg5xhFr65cjIM5DX5L9tr90tzRE1afjeUyvT0AYkSodQzJmweQG1nz-WQ9INEf//smQf6Dvguwe6pCZye8RcwbdH8P+1U5uHtmIKGSWVRzX347M2TGREtOe-arAblsfmB75t/eIracWIP0+goQSf8O942GrhBpqlMHYhPYn1ALYpgJVTp/mlIYtl-GtDDEeu8LHbF5z0orEBLp+x5aAbqbwIUXdvIejehFS669Mxb2p5K9XDbFWJJ5osn-6pAKFdTx7oo0HvGQP6vVEdsHkzZMenhj8U76jDlJKLAZi2Rww3Usfy0obssPT1Iu-R8JLjqpVgwXwKMaeLsGf4GUkqBLNsj72fNK5NGCJWeRged0G+jqaP2/Lf2UCbMxV-pAmoAciNdVexY9ytH+wPXLLKbGPIKAKPqepF3vhX4yHoL2Q+gR9Hx194r6hRdfHV-AKknDoG6/MWWzaqEieec28oXCNZwXdkPWJyssa1E6W1fojL/xhdvmiHUFUeR3rgs-xiMOdxvhFusKbuHjYpGwb9/D6+D7hUQGlSZ/8UMW3hfWiJcCAwEAAaOB2TCB1jAP-BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUqH3ODOPG-96qjP/ll526pjIJKWdswgZMGA1UdIwSBizCBiIAUqH3ODOPG96qjP/ll526pjIJK-WduhWqRYMFYxODA2BgNVBAMTL0luZm9ybWF0aW9uIFNlY3VyaXR5IENlcnRpZmlj-YXRpb24gQXV0aG9yaXR5IENBMQ0wCwYDVQQKEwRJU0NBMQswCQYDVQQGEwJLWoIU-KH3ODOPG96qjP/ll526pjIJKWdswDQYJKoZIhvcNAQELBQADggIBAD3Qw2GXqOJ8-BUqdN382O6KwdDljJzVhgxkOzcC6avfisoZ+Vhj74dy7qoMmQ84M+yXnA7BCCzHr-wBYsDKUwLT/WiHKcjToFtsejMteofiU/M0/ljigoI4Fbcl5w0tl8C47wAm5R2qAJ-sU4re9npst1z+AX4Ll7BurgsBKtTvA3PtZtRlsPm3zd7xS2xCGRaybXdMkLYWDRZ-J6R+A/iK1NM7UzAeEYpCyhDZo/OCrFgNWDpqwVTiOe3CPqM3aEBPPbohTbjMV9Gj-L0g7m1j2BI+X3ByHvTEYqZia36HOgmy4jrOuMsWeSqXw/RjTINBWtOzQDnm7Enrq-RpjR1kpugkAzNvGFSEUvkj7moKo++ixH46iOjSNGexPx21ktQijUXAvQ9ETO9EsJ-jmUNOiTd+iRjUEnACaGn+od99CsgEXBDq9EtP65KedzXIy5MTu6fMULSSLaQdzLh-Vd827PEzgMvNCj45pqVisVJ6l+N73J7yLrtq6Ad6BQ1N+jC0MMiiYn2r7E5Gt54j-+GzQMZgHgdoHbk6tiUw3UXrM8CGzaHJhSu/g/oUkGU0EDKlduHigTNCuHLX9uuvw-gNglHhejbQE8ai7ApOwoEmZMXBH9B+oFkwU5CSN1AoNDiQIUlzqS2mv41GU7q2iX-k3zu7DCQingYbxGab/J8R/e9aTMNhD8W------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/leaf.pemdeleted file mode 100644index 870b3623d..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/leaf.pem+++ /dev/null@@ -1,21 +0,0 @@------BEGIN CERTIFICATE------MIIDXTCCAkWgAwIBAgIUEPlNJxZrwg60AMmYq4fl4iKEp6MwDQYJKoZIhvcNAQEL-BQAwGTEXMBUGA1UEAwwOVHJ1c3QgVGVzdCBJbnQwIBcNMjYxMDA4MTcxOTQ0WhgP-MjEyNjA5MTQxNzE5NDRaMAwxCjAIBgNVBAMMAXgwggEiMA0GCSqGSIb3DQEBAQUA-A4IBDwAwggEKAoIBAQDh/WlixnDuMipvbyvaXShC9Oa6b8fG7focttANGZtwwCpX-+TkEO6NTRvlwOBCdj1zGZEPuEQDZtbVgyz0DIxCuDK8sdlY7UgZjUY9ifThKhAmA-ux7CC2UcDLnr7P16ixVd3z1ev14zWqkyl0wZPG6udBoIyLUo/DzLj8j/YQQC0+Zt-JxGrtY2mwYbwyj0OFafkVrWGLe8EJZV8IrV7N0+OGGUi9ZHuvzbtgP4fc8xJj7Md-zQtxa2vA+Uq02PHfR+iYyAFow1taltelKV+mbfVJypy6RgQEnyIlEPpACMXD4HoU-QLG4dZAca0KFzdgI1IsxTSeC5SJxKk0RYp3ElyfJAgMBAAGjgacwgaQwDAYDVR0T-AQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHwYD-VR0jBBgwFoAUZr13tE+ypjf5+dQIrf6xsgcp0JkwLwYDVR0RBCgwJoIMaG9zdC5l-eGFtcGxlhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBRgGEvI6VZt-KCBl88e6Icmez0rXPjANBgkqhkiG9w0BAQsFAAOCAQEABG/ol4K9If/YAfPGGqfn-7FVzGQOjgviCaWpQEQueBAmSLDSjgCyN4pRoZuFwIjzc0m0UkL8fQdS2ypF9dtHq-dIFCZRlBugqpTwzLvuPwJk6pPcPkwqpBB3jIJo25PFo6LokH/sA9sNnndprLmlwA-6iBC8wh3Nn81ge9Go2tM/yueOHAlFkSIMUXlq2/qPkRPSk/I9S9K94ESML4mLVY3-SQ/ysv6G3Djjucey2Nasm5JJukzjgcUd047Yrnw88SDpO/jcmpoGwuCfmqMTr5gS-pBo8L1D4yJaG1CQM/OLlOBnDQrAyCUZ696nVQH/U5zJhjTR3wdzt9UeyE9kQEOJr-RA==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/nc_int.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/nc_int.pemdeleted file mode 100644index 2f7d2cf41..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/nc_int.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDQzCCAiugAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaekwDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NFoY-DzIxMjYwOTE0MTcxOTQ0WjARMQ8wDQYDVQQDDAZOQyBJbnQwggEiMA0GCSqGSIb3-DQEBAQUAA4IBDwAwggEKAoIBAQDBpGTjp6pklNYbUn+TAOFFojcQOry16ECScxx7-VGZKHMYxBa1/9LCoAeS/z81CaiPIK6dv6kHOvKh3OA4VJinfoT03MPFo77tBtgie-Fgyt7GgROHMQHjjnSHCeMrv4UgF7qRgUMDpBOa+mXHx+gw1hLGSajnHMByQYjPSn-FUdn99c3GfA435sInwsneK3Z6K6w9dnaGfa5/cNcGs/LdFRARuBzutVFm0ZFz44E-nVoMeHppw3OBb4ZEA18Gn8cERW06+yA4/De98dzo8gPVt3IMwjx4Y5TPX5xm8JeI-vofKiHPofvTHnBlqCzvUeOxUafQUUKaexyygooiiB4NEymwfAgMBAAGjgYcwgYQw-DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHWJVS3H-Wh0c4hnE52bOWg2s/aGvMB8GA1UdIwQYMBaAFDl9W8k1XKQCubIn46G/oYwjeDkq-MCEGA1UdHgEB/wQXMBWgEzARgg9hbGxvd2VkLmV4YW1wbGUwDQYJKoZIhvcNAQEL-BQADggEBAKkFGxFm6cibc6Y853pNWoDN30fvkbt1e8YGf/Ws+E7e18wf9JM+HxfU-cCF5NFI9rZAScaLPifcoewxRnO0lqMtkNYk52/iJYE8WHkcn0/sCxluuHpD5HOVI-7YEbniFcPGBhTM/62An1FGtsCFd02vjP6dZ1m79fxgONYVKsMpJoiGZsYeScFixE-J0qpqXsJ8cfvhH0FkxQeSX28PHRKV9cay2ElmP8yAelpA9DGeowcE67KeIa2GH0E-75DIZlqa8+HTYSXGZOBKlEdPtLWtluGS/ewhDNN8jTmWu4rxPLvUU4VcnoOxHWri-WUK2t8zRGPlReSvQhSwZC54hBJx4e+c=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/nc_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/nc_leaf.pemdeleted file mode 100644index 5c4c32ed0..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/nc_leaf.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDPTCCAiWgAwIBAgIUetjuFkPGZNknh/9qYSrAMnZYVfAwDQYJKoZIhvcNAQEL-BQAwETEPMA0GA1UEAwwGTkMgSW50MCAXDTI2MTAwODE3MTk0NFoYDzIxMjYwOTE0-MTcxOTQ0WjAMMQowCAYDVQQDDAF4MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB-CgKCAQEAyhDyS5OTWf9yoZbBFCY69Em5fa2AVKSXnjQsLn/LRSfPrMyXp0doKdmI-gmhNsaFcEFMxyavyD8V2uMfpgg7QMEoEvRXZXdQkNPpT1k2WRPtkkQReig9vOtsc-sKL4oK3uU099jFaVOC5CmDUDElHTdTK83/WP2x2cLoPi2cfj7vwrmc2y9x2LGkzC-pOoKsDYEFMRZ2cyffSiudC1uT8kYKI8c32AO9hDwJF1sEyaqIzTVBh4P3zOw/g6O-dsWSSxFIHd+pbFjMXQSIePIpMSMuYVs5Pgz8mMuEJSNnWsfr6a5phEiezyM4rcMs-MZ6NCUqK9XThsxLXGw1QVPatbyTXLQIDAQABo4GPMIGMMAwGA1UdEwEB/wQCMAAw-DgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB8GA1UdIwQYMBaA-FHWJVS3HWh0c4hnE52bOWg2s/aGvMBcGA1UdEQQQMA6CDGhvc3QuZXhhbXBsZTAd-BgNVHQ4EFgQUqEPPZG734QvkFZT6gtaRMTCcK2owDQYJKoZIhvcNAQELBQADggEB-AEy+iqqtgRXNk2CCClBLi2HrU2dBjr6FdbYNWPyWZ2FrvQigiAsbkzxql4bKlE6Q-jRGhf57nELD3W5jVbkh57X6Km5cGQcyBhPvpZzYjbMk9dDOWeyd8zyxnrZsOaXoo-Q0djdYu+uyqcBMvz4OfZn+GDybXRdwzY5PgeSSjRMbDhR7XIIMOiBmOv1A6sJoGC-6qqoo4nQPKrCGHBBNVv8sy78ZUTgDs2vGX9+Sx0VUyrAlrXLDF/6vxgjhTCEED6p-FX3agZtNVgkbj/B3I3sML4DzDZ+SMtlyyeOhuJgdWkI5YnptfDfhtPG1G1SHTBvL-u03WVlBWeiYY6to1/OD7SGc=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int.pemdeleted file mode 100644index 5f9047c5f..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int.pem+++ /dev/null@@ -1,19 +0,0 @@------BEGIN CERTIFICATE------MIIDITCCAgmgAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpaeswDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NFoY-DzIxMjYwOTE0MTcxOTQ0WjARMQ8wDQYDVQQDDAZQTCBJbnQwggEiMA0GCSqGSIb3-DQEBAQUAA4IBDwAwggEKAoIBAQCvpCVepJ8mvuB1zxlU2n9jMSDCDEDydVkBvcKW-fQQr2e8OWKcQ6y86DQ8ZCyLNWe+L4pZTMyV1Wq/T0jIo7vEJ3PfJjzcjaiT6yW+k-ZhxuaA4bWtnt8OArTNXRThTavkw1Ef7euhYL1degRZUxDJEpm86zNnwfv6YBRwoF-y6F1oh4Z7nTJyPs9xc63MrgATOltJ3t2gHjAOXdRyWglUBYRae2IWofgQScSk7jT-0T1KwD2ce5Q6RvCNpuhyXlzvZ6y9YcnijY1EjV5I0rnFwIV3u1PQQJt5v6RxL4rL-g2uJrnAhnKGBGonhl4QcpUw0nazcGa5jMHh8iZv9p18qf23fAgMBAAGjZjBkMBIG-A1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQ2CJRo-uL2JbMe/bo3463fl8YjK/zAfBgNVHSMEGDAWgBQ5fVvJNVykArmyJ+Ohv6GMI3g5-KjANBgkqhkiG9w0BAQsFAAOCAQEAhyqPUkysJw0CV07uTU39sdYnYS6LyDqFKEwE-1ToZ+1u4pL5QZRo8yJ65psR0+9w8NTsSnmKS3bgkTqxq08VsC/P5x/wZFeL02JAg-4mzfDn8Xb/FxACQDs5QafRyU6MXHhHI0m6ndS5EhLnWu/IPKcoUAxPWstlLe6ixR-VXY7FXjiraiU1smT97tHxbd2woVwaoJxPlaK1NupLMYY8KGNTOHBn6gLMWspdl/J-bi/3JkNc5E9TCILFBAtWH9sWw3/PY8Mb7ir7k88DWHq3HJIDSYTDt0tOpdUfAke4-M/QdhHDS2pFQYCZxtSwK3RZ3OQHTfcZY7L2ospNTIsjsujGLZw==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int2.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int2.pemdeleted file mode 100644index 84724d151..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_int2.pem+++ /dev/null@@ -1,19 +0,0 @@------BEGIN CERTIFICATE------MIIDFjCCAf6gAwIBAgIUI9bf0eiAxYZ4G3OLjOVETtL3aOQwDQYJKoZIhvcNAQEL-BQAwETEPMA0GA1UEAwwGUEwgSW50MCAXDTI2MTAwODE3MTk0NVoYDzIxMjYwOTE0-MTcxOTQ1WjASMRAwDgYDVQQDDAdQTCBJbnQyMIIBIjANBgkqhkiG9w0BAQEFAAOC-AQ8AMIIBCgKCAQEAzeWnMybz8DmgEmziIs39MNQsnWvmqnhh7q10kDdOZDwV0v7C-rdDCQ6vPf3jaLt79jMvWURAQz1zJU4bpNsYw53+yqrraNw999jPyKI8k6ZJw1QPs-Na3VBxnulZb4sc8HQYD1RMXDrGeJwE07+AVFw1ej8FrWRsERLd5O4/gY2+eW1Sxi-aXkjzgA/iYpZW3p4+KKHGT93sseU7N7Alm54DgcHiksRGoQPwBSempty0p17f/R5-PlvQX4/MmmLcpreEcOAiVtJDTf6qq8zXaogaCGvyEjYb/m4wfdRkuPBp03T9JA1I-VWugtXPqp+2oR/XDF9O2ZD9VlysagJNctoY5OQIDAQABo2MwYTAPBgNVHRMBAf8E-BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUkR09mkxkUjE/r7WNfrt1-T3fICNIwHwYDVR0jBBgwFoAUNgiUaLi9iWzHv26N+Ot35fGIyv8wDQYJKoZIhvcN-AQELBQADggEBAJXeXPehboZGaAV85eEfasMW9cd17zNXFh7/WWE+9b7Rwz+5q6RY-G4yMizRFlSqorBiCidN9lKBqmCEETEkMjD1UI8iXQWXcMBHSUI9xvfdJiZ+I7xrV-Cjq4A5KJeKhayjlMTb27GlUV1g+irdh7g/rCDtN84LRGOMhpKZTcd6DerQCx6zrA-QxCP3vMexoyYh9Rv/90K7CO7mSXuplPGUX2zV6TUhwTR09M4+J+quvA32aamc7Wc-mtqoRTnG8HPh5ey2hjKJAjrbAA2edGDWaQb+0uOQyFhtJAHRpoGu6Mv7bt4Kk5Jb-A/WlHsdIlt1q1lS0iOCSLOZVaiaJB9y2Ce4=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/pl_leaf.pemdeleted file mode 100644index 9807869a5..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/pl_leaf.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDPjCCAiagAwIBAgIUTTXPR16Bluu+wyeTi8GeJHAm+4QwDQYJKoZIhvcNAQEL-BQAwEjEQMA4GA1UEAwwHUEwgSW50MjAgFw0yNjEwMDgxNzE5NDVaGA8yMTI2MDkx-NDE3MTk0NVowDDEKMAgGA1UEAwwBeDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC-AQoCggEBALXpnV/pQz+nAooMhg52ANUSOZup3lVVRoSoqGiEZRoBUqEM9tVRbd9W-u2ZlWGqdquvxmR1IZtqvgW3cjp1+Fr4eoi/GCbGPXgdiNMVnmjP54M+qY93hMriR-TYA3KHVXhYR/XUnVuXsgHRnIeYC2yPx/W+pn5A58tQqODvPp/AFMCi/nWlitCOI+-/UpMzuYVBm+vzAxBBCY8t/7MnTp7IyccxIShrDf9AHcGG2FPm9ZHZMSUeL7Dqnx+-OXxZcGGSZfOdJRfIqUoOkO6KJqnha34SMSke3pj35IeTS9FLGecGY1UaWnN44SlO-IJgKze7MNXNNxxCKONjsnGsYzSJg01kCAwEAAaOBjzCBjDAMBgNVHRMBAf8EAjAA-MA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAfBgNVHSMEGDAW-gBSRHT2aTGRSMT+vtY1+u3VPd8gI0jAXBgNVHREEEDAOggxob3N0LmV4YW1wbGUw-HQYDVR0OBBYEFEJ84ALu2SsxcnbD5p7C4pLStNcVMA0GCSqGSIb3DQEBCwUAA4IB-AQC4O6dQxcm6Grf4Q//XMo4zMBI/HcosD7Pqt8ToMfOMlmcpV5y9iuWD04K4yrrJ-KqhNdzqtuIPw/tPwDXfFX/vw2n3wvUXx2W4AP2951FnC5dWuE+CxgQA9kXjiqOiw-pZIUAqO+hjXfIswOtocMxmwCKvCbibh6DS4p+GMhDXFYPiBx60155DenUtfdfxps-0xgs42n/+UzesZhF+cUqvEtF8VrfkP2SpHrJXwxaII/0Yc0yqxCfd5xMAUw+ccP2-FWoBMm4QSPI62OmXSXk3lGjn8zZAABilPONqo2nsSv2HcOH82OqvleloRVXnVIMK-58Dib6o7IcPlgsnoH/tKoy7J------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/root.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/root.pemdeleted file mode 100644index cb16e6b68..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/root.pem+++ /dev/null@@ -1,19 +0,0 @@------BEGIN CERTIFICATE------MIIDBjCCAe6gAwIBAgIUU93kzExCdrzi3lnMnhSZgjnowIswDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0M1oY-DzIxMjYwOTE0MTcxOTQzWjAaMRgwFgYDVQQDDA9UcnVzdCBUZXN0IFJvb3QwggEi-MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDc4SkwOK60qqk09EjIPTRGvSnH-sOPJu0A1+IfRKsdfdMk6pTXL1Xm01nOLLqbsW4oz3rRfFQJyZPOSpPzzkCAdjKfp-y8KtKUZjzlnz8ADOoaeGLCnCyELw09anO/JsbnDv0snPMInYS5R2Onq5+M6qlEdH-iSe9uG0qiWx0OGXBkoDs+zF+Buc5ilYEKVNHZBho3V3qUoFjKKEE2O9DyKJ1qL+v-KgvTg0Z6KPjiyvlkkMRdn2UCHsJl5XTxU2dLLbs99F3/GSGbVjk+UXcUcJp4ZpA/-/oQd99g4MYqKGDJIItFYQ0WQDTk1s2rEzqaOKS9DA83eXCwgvDBfOGaY+HCjAgMB-AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQW-BBQ5fVvJNVykArmyJ+Ohv6GMI3g5KjANBgkqhkiG9w0BAQsFAAOCAQEAZKD6bPnD-8l6xoyaai0AhqEx03MK1rBLiji2iK65FznWOFlRJCJX6MH5fJbGyafCHiM7fkTOw-BX2hY/hXC8Yg4AtsOvf6hRNYHEy0Z0Nj7qfCY9BpJXHzMvPLkJqqJB0UJisr5EDk-FKNiBiXftwbAUeUXuzncfviKbXroHlT5oLHBvApb6jhxIPhb7dBrbpN2urRfMzZu-ezbK+jWUB89h79xupK4ph7B8zFY5swiIZ3bjXDFqlNDzyksgzqqWOoZqyI3FoCJY-msORGKupBklLJgm78AjDJdu1/lhGfLflM9pspYi7A8Kct6fQerw2SJ+5xoFw9WKz-CUKllHzH9kJnew==------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/sha1_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/sha1_leaf.pemdeleted file mode 100644index 53f726c45..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/sha1_leaf.pem+++ /dev/null@@ -1,20 +0,0 @@------BEGIN CERTIFICATE------MIIDRjCCAi6gAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpae0wDQYJKoZIhvcNAQEF-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NVoY-DzIxMjYwOTE0MTcxOTQ1WjAMMQowCAYDVQQDDAF4MIIBIjANBgkqhkiG9w0BAQEF-AAOCAQ8AMIIBCgKCAQEAj3JW39sTg/nPYlrrd1wcXpP4Ya2WmjizYVfXIujTj+ud-mOYFUM373ZCPo+VgyT4HP4DM6sq4p3vO6EuuVzyJ8soeFEnrDeikeQAnQbKw/2Zt-3S87iFMurZ34pMAWDauxUxVcONnwuf7meNME4aQoBWjPHbcGWke/Ri3xPNHKOODQ-3nt3HHr6wIBALOJXnUMWWRjovn4GcUxO0O1OGghr6taoI2MCsrBGbvv2BZ4TXtVd-anz5sQx1l9cAi9HlvnqpcIl07mkpvJ4nXf8wlmESZPpgrlKmI17R3CFhtoI0lhNW-WCx5KetPhgKYQmqHYCF5REdV0gjNbQqyyIv2KEnGTQIDAQABo4GPMIGMMAwGA1Ud-EwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB8G-A1UdIwQYMBaAFDl9W8k1XKQCubIn46G/oYwjeDkqMBcGA1UdEQQQMA6CDGhvc3Qu-ZXhhbXBsZTAdBgNVHQ4EFgQU0IoQbg1eN6pJMBqiJndYE2R3Z4gwDQYJKoZIhvcN-AQEFBQADggEBACgpJLT7wIynXT7UIO9ysQZZHICrTW92oopBh6CxnwzJuLsTjG4g-bQEnGO6NHQIBC3SCilyaEC9tDfDIpjJwfzyX4DuH/7UfAA6+xnJWxbaUFfAssiAG-DGTChKZlmZvRhf7V415QKKbEWeQz9I+j+X47at6aki/64BAmMw7ErDPHQukg74kB-zQvNFvkpSVcO6dgbYKP/+F/x3drAierIvJkfhcox/HoZSwcgKGDp2VFcfEKxUK91-PkyDw78ONQANiM53PNSAjfSRVzRzW3PsPjNiF+OHGg+FNp6Cp8VbS6fSyhN6qf2q-RXlF1J0mj226t9l9v7JkWfjTkiktRBnJoXU=------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/wc_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/wc_leaf.pemdeleted file mode 100644index 04723df0f..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/wc_leaf.pem+++ /dev/null@@ -1,21 +0,0 @@------BEGIN CERTIFICATE------MIIDZTCCAk2gAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpae8wDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MjAyNFoY-DzIxMjYwOTE0MTcyMDI0WjAMMQowCAYDVQQDDAF4MIIBIjANBgkqhkiG9w0BAQEF-AAOCAQ8AMIIBCgKCAQEApbYcbze7NDc8K8nCy4yoCy++oUFvoppPJpPaPb7SpRRD-0AHISMpE09/yXr2+NNVf80yzhmsSfuej7cq4TMYN2m6cZUVe9r+lCZC7QztfpZdO-9UZLWv/S53rWcLA/rtH2yg5Q1DRgt2uoY/FlCmMJt3cgrr3H7R9vCtQUrhSayGyY-PfPwyrwkL6Rja3ztkKPlco83CgqRnWMOwG6gpxcqTAcyzH1WAcyDkTWmhkr+1G50-oL852GdVV+kO0rLNAI4+bPdsbPOKk4HikaTHHE0SQV78eb0Z5X/D0wFGu1iGopJ/-BBGSym2LYibMbNLvkaWrnAT2vdVP1n/6afcJxAjj+wIDAQABo4GuMIGrMAwGA1Ud-EwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB8G-A1UdIwQYMBaAFDl9W8k1XKQCubIn46G/oYwjeDkqMDYGA1UdEQQvMC2CEioubGFu-LmhvbWUuZXhhbXBsZYIOKi5ob21lLmV4YW1wbGWCByouY28udWswHQYDVR0OBBYE-FNDwHsBO73UfLTCvRi/q/XHb0o6dMA0GCSqGSIb3DQEBCwUAA4IBAQDLXwJYrYI+-efdLGjymEXT0CR/M67x6BIQKB8w0onIGyz26WedaTX+LKuji+WGgenY/AkIEC6AL-T4rv6dBVjxHv4+x8TgnzU+aWNOEEdDWNeaXc8sb+3ZZzm5mkPooVWfVdnej9i/G1-WHjAFo/p0RHs613UuGRoZ6ZCmMomNYs9nwFoz6EmHUseARwj4dCAkdih+Z64j3NR-610hnoRsirKk/Ihjcn8RxUTVrBA+N6RkbIJByCeNzyhNzSmfNi8XvyvCqjjiUNon-b83rGCcF+V0px7NaZU8QwUJPDDekcUo/k8mQ+LjjLEAHByTJ9+Ap+3lhRuv21DWg-kJIAoFUaST7C------END CERTIFICATE-----diff --git a/fluxer_desktop/src/main/fixtures/desktop-trust/weak_leaf.pem b/fluxer_desktop/src/main/fixtures/desktop-trust/weak_leaf.pemdeleted file mode 100644index d1c206f99..000000000--- a/fluxer_desktop/src/main/fixtures/desktop-trust/weak_leaf.pem+++ /dev/null@@ -1,17 +0,0 @@------BEGIN CERTIFICATE------MIICwjCCAaqgAwIBAgIUA+GJ9S/l9MoO3gPga8JwUYNpae4wDQYJKoZIhvcNAQEL-BQAwGjEYMBYGA1UEAwwPVHJ1c3QgVGVzdCBSb290MCAXDTI2MTAwODE3MTk0NVoY-DzIxMjYwOTE0MTcxOTQ1WjAMMQowCAYDVQQDDAF4MIGfMA0GCSqGSIb3DQEBAQUA-A4GNADCBiQKBgQDWzciJ+1PQ5RoweAE4xbNqaEnbwIyOR0+NwdUt02tcjezWlQfy-A9hWb/DkETcfw6LQx3u458vmBXM1YVmnYAhnd2P8OIwlQ0Se2xQ17iKJdpoa7IQ/-aTkF1yjBvFxD8DoDRojpVupPI+mh5wg+wCCvgznX+fpZYkXEPorTFeDe2QIDAQAB-o4GPMIGMMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoG-CCsGAQUFBwMBMB8GA1UdIwQYMBaAFDl9W8k1XKQCubIn46G/oYwjeDkqMBcGA1Ud-EQQQMA6CDGhvc3QuZXhhbXBsZTAdBgNVHQ4EFgQU/l8az3OuVEjRNlmpfraqM0+p-NT8wDQYJKoZIhvcNAQELBQADggEBANJhIs3MqR/U3CZshOZSduYdDz3xXUbqg5K6-/z6EynXzF+DW26LiwZcWa3bJxfi15NbQ3urMu9UueyX2JJ1tffRNRnwWEPRG6qZ5-oD4y7hyrPvbPSVMCGTZJPX1mBi1Fo0ijPNtrziujNw9xEuFL/3Exan3xelJJpg8J-jLdVYzvzgzqT/m0Q1gy9ceRb6VJhtUN1ingYLyUvRwiih64pLLslBwvluEGrHqZ8-f6JmpvxKX5kjaWXH8M6ZjgJofmD2vaCDjnb3Y7dZAMNlxMpDXhW0hxQEjycnh3dZ-cpLB7DwofmR/ov/wE/tVmjA+lqR6Fp8fpyy5vtvGCeVMnJv32/I=------END CERTIFICATE-----