import crypto from 'node:crypto' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { afterEach, describe, expect, test } from 'bun:test' import { createEarthDesktopAuth } from '../src/main/earth-auth' import { createEarthProtocolHandler } from '../src/main/protocol-core' const tempDirs: string[] = [] function makeBundleDir(): string { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'planet-earth-auth-test-')) tempDirs.push(dir) fs.writeFileSync(path.join(dir, 'index.html'), '') return dir } afterEach(() => { while (tempDirs.length > 0) { const dir = tempDirs.pop()! fs.rmSync(dir, { recursive: true, force: true }) } }) describe('createEarthDesktopAuth', () => { test('mints, caches, signs HMAC handshake, and clears on backend change', async () => { let backendUrl = 'https://rclaw.top' let now = 1_700_000_000_000 const calls: Array<{ url: string; headers: Headers; body: string }> = [] let counter = 0 const auth = createEarthDesktopAuth({ getBackendUrl: () => backendUrl, getAppVersion: () => '0.80.3', handshakeSecret: 'super-secret-handshake', nowMs: () => now, fetchImpl: async (input, init) => { counter += 1 calls.push({ url: String(input), headers: new Headers(init?.headers), body: String(init?.body || ''), }) return new Response( JSON.stringify({ token: `desktop-tok-${counter}`, expires_in: 1800 }), { status: 200, headers: { 'Content-Type': 'application/json' } }, ) }, }) const tok1 = await auth.getToken() const tok2 = await auth.getToken() expect(tok1).toBe('desktop-tok-1') expect(tok2).toBe('desktop-tok-1') expect(calls).toHaveLength(1) const first = calls[0]! expect(first.url).toBe('https://rclaw.top/api/v1/auth/earth-session') expect(JSON.parse(first.body)).toEqual({ client_type: 'desktop' }) expect(first.headers.get('x-planet-client')).toBe('planet-earth-desktop/0.80.3') const ts = first.headers.get('x-planet-client-timestamp')! const nonce = first.headers.get('x-planet-client-nonce')! const sig = first.headers.get('x-planet-client-signature')! const expectedSig = crypto .createHmac('sha256', 'super-secret-handshake') .update(`${ts}.${nonce}.planet-earth-desktop/0.80.3`) .digest('hex') expect(sig).toBe(expectedSig) // Near expiration triggers refresh now += 1700 * 1000 const tok3 = await auth.getToken() expect(tok3).toBe('desktop-tok-2') expect(calls).toHaveLength(2) // Backend URL switch clears cache backendUrl = 'https://other.rclaw.top' const tok4 = await auth.getToken() expect(tok4).toBe('desktop-tok-3') expect(calls[2]!.url).toBe('https://other.rclaw.top/api/v1/auth/earth-session') }) test('protocol handler injects X-Planet-Earth-Token and refreshes once on 401', async () => { const bundleRoot = makeBundleDir() let currentToken = 'tok-stale' let refreshCalls = 0 const upstreamTokens: Array = [] const handler = createEarthProtocolHandler({ earthBundleRoot: bundleRoot, getBackendUrl: () => 'https://rclaw.top', getEarthAuthToken: async (opts) => { if (opts?.forceRefresh) { refreshCalls += 1 currentToken = 'tok-fresh' } return currentToken }, fetchImpl: async (_input, init) => { const headers = new Headers(init?.headers) const tok = headers.get('x-planet-earth-token') upstreamTokens.push(tok) if (tok === 'tok-stale') { return new Response(JSON.stringify({ detail: 'expired' }), { status: 401 }) } return new Response(JSON.stringify({ ok: true }), { status: 200 }) }, }) const res = await handler(new Request('planet://earth/api/v1/visualization/geo/summary')) expect(res.status).toBe(200) expect(await res.json()).toEqual({ ok: true }) expect(refreshCalls).toBe(1) expect(upstreamTokens).toEqual(['tok-stale', 'tok-fresh']) }) })