import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { DesktopConfigStore, deriveBackendWsUrl } from '../src/main/config' import { resolveExternalTargetUrl } from '../src/main/external-links' import { createEarthProtocolHandler, createStaticFileResponse, isProxiedBackendPath, parseByteRange, resolveEarthStaticPath, } from '../src/main/protocol-core' let tempRoot = '' let bundleRoot = '' beforeAll(() => { tempRoot = mkdtempSync(path.join(os.tmpdir(), 'planet-client-test-')) bundleRoot = path.join(tempRoot, 'earth') const dataDir = path.join(bundleRoot, 'data') const fs = require('node:fs') fs.mkdirSync(dataDir, { recursive: true }) writeFileSync(path.join(bundleRoot, 'index.html'), 'Earth', 'utf8') writeFileSync(path.join(dataDir, 'sample.pmtiles'), '0123456789ABCDEF', 'utf8') }) afterAll(() => { if (tempRoot) { rmSync(tempRoot, { recursive: true, force: true }) } }) describe('protocol-core static and range handling', () => { test('resolves earth entry and blocks directory traversal', () => { expect(resolveEarthStaticPath(bundleRoot, '/')).toBe(path.join(bundleRoot, 'index.html')) expect(resolveEarthStaticPath(bundleRoot, '/earth/')).toBe(path.join(bundleRoot, 'index.html')) expect(resolveEarthStaticPath(bundleRoot, '/earth/data/sample.pmtiles')).toBe( path.join(bundleRoot, 'data/sample.pmtiles'), ) expect(resolveEarthStaticPath(bundleRoot, '/earth/../../etc/passwd')).toBeNull() expect(resolveEarthStaticPath(bundleRoot, '/..%2f..%2fsecret')).toBeNull() }) test('parses byte ranges and serves 206 Partial Content for PMTiles', async () => { expect(parseByteRange('bytes=0-3', 16)).toEqual({ kind: 'range', start: 0, end: 3 }) expect(parseByteRange('bytes=10-', 16)).toEqual({ kind: 'range', start: 10, end: 15 }) expect(parseByteRange('bytes=-4', 16)).toEqual({ kind: 'range', start: 12, end: 15 }) expect(parseByteRange('bytes=30-40', 16)).toEqual({ kind: 'unsatisfiable' }) const pmtilesPath = path.join(bundleRoot, 'data/sample.pmtiles') const partial = createStaticFileResponse(pmtilesPath, new Headers({ Range: 'bytes=2-5' })) expect(partial.status).toBe(206) expect(partial.headers.get('Content-Range')).toBe('bytes 2-5/16') expect(partial.headers.get('Accept-Ranges')).toBe('bytes') expect(await partial.text()).toBe('2345') const invalid = createStaticFileResponse(pmtilesPath, new Headers({ Range: 'bytes=99-120' })) expect(invalid.status).toBe(416) }) test('proxies /api/*, /health, and /earth-brand-assets/* to backendUrl', async () => { expect(isProxiedBackendPath('/api/v1/earth/brand')).toBe(true) expect(isProxiedBackendPath('/health')).toBe(true) expect(isProxiedBackendPath('/earth-brand-assets/logo.png')).toBe(true) expect(isProxiedBackendPath('/earth/index.html')).toBe(false) const seen: string[] = [] const handler = createEarthProtocolHandler({ earthBundleRoot: bundleRoot, getBackendUrl: () => 'http://127.0.0.1:8000', fetchImpl: (async (input: RequestInfo | URL) => { seen.push(String(input)) return Response.json({ ok: true }) }) as typeof fetch, }) const apiResp = await handler(new Request('planet://earth/api/v1/earth/brand?lang=zh')) expect(apiResp.status).toBe(200) expect(await apiResp.json()).toEqual({ ok: true }) const brandResp = await handler(new Request('planet://earth/earth-brand-assets/custom.png')) expect(brandResp.status).toBe(200) expect(seen).toEqual([ 'http://127.0.0.1:8000/api/v1/earth/brand?lang=zh', 'http://127.0.0.1:8000/earth-brand-assets/custom.png', ]) const blocked = await handler(new Request('planet://other/earth/index.html')) expect(blocked.status).toBe(403) }) test('forwards Accept-Encoding, If-None-Match, and AbortSignal and preserves 304 null-body responses', async () => { const capturedHeaders: Array = [] let receivedSignal: AbortSignal | undefined const handler = createEarthProtocolHandler({ earthBundleRoot: bundleRoot, getBackendUrl: () => 'http://127.0.0.1:8000', fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { capturedHeaders.push(new Headers(init?.headers)) receivedSignal = init?.signal return new Response(null, { status: 304, headers: { ETag: '"sat-v1"', 'Content-Length': '0' }, }) }) as typeof fetch, }) const abortController = new AbortController() const response = await handler( new Request('planet://earth/api/v1/visualization/geo/satellites?format=compact', { headers: { 'If-None-Match': '"sat-v1"' }, signal: abortController.signal, }), ) expect(response.status).toBe(304) expect(response.headers.get('ETag')).toBe('"sat-v1"') expect(await response.text()).toBe('') expect(capturedHeaders[0].get('accept-encoding')).toBe('gzip, deflate, br') expect(capturedHeaders[0].get('if-none-match')).toBe('"sat-v1"') expect(receivedSignal?.aborted).toBe(false) const abortedController = new AbortController() abortedController.abort(new DOMException('Aborted', 'AbortError')) const abortHandler = createEarthProtocolHandler({ earthBundleRoot: bundleRoot, getBackendUrl: () => 'http://127.0.0.1:8000', fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { if (init?.signal?.aborted) { throw init.signal.reason ?? new DOMException('Aborted', 'AbortError') } return Response.json({ ok: true }) }) as typeof fetch, }) await expect( abortHandler( new Request('planet://earth/api/v1/visualization/geo/satellites', { signal: abortedController.signal, }), ), ).rejects.toThrow() }) test('caches boundary artifacts to disk, cleans stale versions, and serves local 206/HEAD', async () => { const fs = require('node:fs') const boundaryCacheDir = path.join(tempRoot, 'boundary-cache') fs.mkdirSync(boundaryCacheDir, { recursive: true }) const staleFile = path.join(boundaryCacheDir, 'earth-boundaries.oldver.pmtiles') writeFileSync(staleFile, 'stale-data', 'utf8') const payload = 'PMTiles-Mock-Archive-Payload-0123456789' const upstreamCalls: Array<{ url: string; range: string | null }> = [] const handler = createEarthProtocolHandler({ earthBundleRoot: bundleRoot, boundaryCacheDir, getBackendUrl: () => 'http://127.0.0.1:8000', fetchImpl: (async (input: RequestInfo | URL, init?: RequestInit) => { const headers = new Headers(init?.headers) const range = headers.get('range') upstreamCalls.push({ url: String(input), range }) if (range && /^bytes=(\d+)-(\d*)$/.test(range)) { const match = /^bytes=(\d+)-(\d*)$/.exec(range)! const start = Number(match[1]) const end = match[2] ? Math.min(Number(match[2]), payload.length - 1) : payload.length - 1 const slice = payload.slice(start, end + 1) return new Response(slice, { status: 206, headers: { 'Content-Range': `bytes ${start}-${end}/${payload.length}`, 'Content-Length': String(slice.length), Accept: 'bytes', }, }) } return new Response(payload, { status: 200, headers: { 'Content-Length': String(payload.length) }, }) }) as typeof fetch, }) // First Range request misses local disk cache -> proxies upstream AND caches full file in background. const url = 'planet://earth/api/v1/earth/boundaries/files/earth-boundaries.newver.pmtiles' const first = await handler(new Request(url, { headers: { Range: 'bytes=0-6' } })) expect(first.status).toBe(206) expect(await first.text()).toBe('PMTiles') const targetPath = path.join(boundaryCacheDir, 'earth-boundaries.newver.pmtiles') for (let i = 0; i < 40 && !fs.existsSync(targetPath); i += 1) { await new Promise((r) => setTimeout(r, 15)) } expect(fs.existsSync(targetPath)).toBe(true) expect(fs.existsSync(staleFile)).toBe(false) // Subsequent Range and HEAD requests hit local disk cache with zero upstream calls. const callsBeforeHit = upstreamCalls.length const hitRange = await handler(new Request(url, { headers: { Range: 'bytes=8-11' } })) expect(hitRange.status).toBe(206) expect(hitRange.headers.get('Content-Range')).toBe(`bytes 8-11/${payload.length}`) expect(hitRange.headers.get('Cache-Control')).toContain('immutable') expect(await hitRange.text()).toBe('Mock') const hitHead = await handler(new Request(url, { method: 'HEAD' })) expect(hitHead.status).toBe(200) expect(hitHead.headers.get('Content-Length')).toBe(String(payload.length)) expect(await hitHead.text()).toBe('') expect(upstreamCalls.length).toBe(callsBeforeHit) // Path traversal or unexpected extensions are never read/written from local boundary cache. const traversal = await handler( new Request('planet://earth/api/v1/earth/boundaries/files/..%2Fsecret.pmtiles'), ) expect(traversal.status).toBe(200) expect(upstreamCalls.length).toBe(callsBeforeHit + 1) }) }) describe('external links and runtime config', () => { test('routes admin and docs links externally while keeping earth links internal', () => { const opts = { earthOrigin: 'planet://earth', adminUrl: 'http://127.0.0.1:3000/' } expect(resolveExternalTargetUrl('planet://earth/admin/users?page=1', opts)).toBe( 'http://127.0.0.1:3000/admin/users?page=1', ) expect(resolveExternalTargetUrl('planet://earth/docs/manual', opts)).toBe( 'http://127.0.0.1:3000/docs/manual', ) expect(resolveExternalTargetUrl('planet://earth/earth/index.html', opts)).toBeNull() expect(resolveExternalTargetUrl('https://example.org/news', opts)).toBe('https://example.org/news') }) test('resolves config precedence and persists user endpoints', () => { const userDataDir = path.join(tempRoot, 'user-data') const exeDir = path.join(tempRoot, 'exe-dir') const fs = require('node:fs') fs.mkdirSync(exeDir, { recursive: true }) writeFileSync( path.join(exeDir, 'planet-earth.json'), JSON.stringify({ backendUrl: 'http://10.0.0.5:8000', adminUrl: 'http://10.0.0.5:3000' }), ) const store = new DesktopConfigStore({ userDataDir, exeDir, argv: ['--backend-url=https://planet.example.com', '--fullscreen', '--fps'], env: {}, }) const cfg = store.get() expect(cfg.backendUrl).toBe('https://planet.example.com') expect(cfg.wsUrl).toBe('wss://planet.example.com/ws') expect(cfg.adminUrl).toBe('http://10.0.0.5:3000') expect(cfg.fullscreen).toBe(true) expect(cfg.forceShowFps).toBe(true) expect(deriveBackendWsUrl('http://127.0.0.1:8000')).toBe('ws://127.0.0.1:8000/ws') }) })