Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

10.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router';
import useEidoverseFrame from './useEidoverseFrame';
import { safeRemoveStorage, safeWriteStorage } from '../lib/safeStorage';
import { mockFrameWindows } from '../test/mockFrameWindows.js';

const hostUrl = 'https://world.example.com/';
const objects = [{ id: 'portos-design-v2-signal-app-example', route: '/apps' }];
function Harness({ projected = objects, onTravel, onIdentityRename, capture } = {}) {
  const frame = useEidoverseFrame(hostUrl, projected, onTravel, onIdentityRename);
  capture?.(frame);
  const location = useLocation();
  return <>
    <iframe title="Test renderer" ref={frame.frameRef} onLoad={frame.onFrameLoad} />
    <output aria-label="Route">{location.pathname}</output>
    <output aria-label="Bridge status">{frame.connection.status}</output>
    <button onClick={() => frame.changeLabelVisibility('off')}>Hide labels</button>
  </>;
}
// The inert iframe dispatches its initial load asynchronously. Settle that
// mount before a test starts the explicit load/handshake it controls.
const renderFrame = async (element) => {
  let view;
  await act(async () => { view = render(element); });
  return view;
};
const mount = () => renderFrame(<MemoryRouter initialEntries={['/eidoverse']}><Harness /></MemoryRouter>);
const send = (source, data, extra = {}) => act(() => {
  window.dispatchEvent(new MessageEvent('message', { source, origin: new URL(hostUrl).origin, data, ...extra }));
});

afterEach(() => {
  vi.useRealTimers();
  vi.restoreAllMocks();
  safeRemoveStorage('portos-eidoverse-label-visibility');
});

describe('hosted Eidoverse frame navigation', () => {
  beforeEach(mockFrameWindows);
  it('waits for the current renderer departure acknowledgement before retiring its frame', async () => {
    let frame;
    await renderFrame(<MemoryRouter><Harness capture={(value) => { frame = value; }} /></MemoryRouter>);
    const iframe = screen.getByTitle('Test renderer');
    const source = iframe.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    const { nonce } = post.mock.calls.at(-1)[0];
    send(source, { type: 'eidoverse:ready', version: 1, nonce, capabilities: { worldDeparture: 1 } });
    const done = vi.fn();
    const leaving = frame.leaveWorld().then(done);
    expect(post.mock.calls.at(-1)[0]).toEqual({ type: 'portos:depart', version: 1, nonce });
    send(source, { type: 'eidoverse:departed', version: 1, nonce: 'stale', ok: true });
    expect(done).not.toHaveBeenCalled();
    send(source, { type: 'eidoverse:departed', version: 1, nonce, ok: true });
    await act(async () => { await Promise.resolve(); });
    fireEvent.load(iframe);
    await act(async () => leaving);
    expect(done).toHaveBeenCalledOnce();
    expect(iframe.getAttribute('src')).toBe('about:blank');
  });

  it('refuses travel when the current renderer cannot confirm departure', async () => {
    vi.useFakeTimers();
    let frame;
    await renderFrame(<MemoryRouter><Harness capture={(value) => { frame = value; }} /></MemoryRouter>);
    const iframe = screen.getByTitle('Test renderer');
    const source = iframe.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    const { nonce } = post.mock.calls.at(-1)[0];
    send(source, { type: 'eidoverse:ready', version: 1, nonce, capabilities: { worldDeparture: 1 } });
    const result = frame.leaveWorld().catch(error => error.message);
    await act(async () => { vi.advanceTimersByTime(5000); });
    expect(await result).toMatch(/Could not leave/);
    expect(iframe.getAttribute('src')).not.toBe('about:blank');
  });
  it('resolves a pod through the local legend rather than a destination claimed by the frame', async () => {
    const onTravel = vi.fn();
    const pod = { id: 'example-pod', route: '/eidoverse', travelPeerId: 'peer-example' };
    await renderFrame(<MemoryRouter><Harness projected={[pod]} onTravel={onTravel} /></MemoryRouter>);
    const iframe = screen.getByTitle('Test renderer');
    const source = iframe.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    const { nonce } = post.mock.calls.at(-1)[0];
    send(source, { type: 'eidoverse:ready', version: 1, nonce, capabilities: { portosNavigation: 1 } });
    const action = { type: 'eidoverse:navigate', version: 1, nonce, entityId: pod.id, route: pod.route, travelPeerId: 'untrusted-peer' };
    send(source, { ...action, entityId: 'foreign-pod' });
    expect(onTravel).not.toHaveBeenCalled();
    send(source, action);
    expect(onTravel).toHaveBeenCalledExactlyOnceWith('peer-example');
  });

  it('accepts a bounded identity draft only from the negotiated current frame session', async () => {
    const onIdentityRename = vi.fn();
    await renderFrame(<MemoryRouter><Harness onIdentityRename={onIdentityRename} /></MemoryRouter>);
    const iframe = screen.getByTitle('Test renderer');
    const source = iframe.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    const [hello] = post.mock.calls.at(-1);
    expect(hello.capabilities.identityRenameRequest).toBe(1);
    const ready = { type: 'eidoverse:ready', version: 1, nonce: hello.nonce,
      capabilities: { identityRenameRequest: 1 } };
    const request = { type: 'eidoverse:identity-rename', version: 1, nonce: hello.nonce,
      name: '  Example Visitor  ' };
    send(source, request);
    send(source, ready);
    for (const [data, extra] of [
      [request, { origin: 'https://attacker.example.com' }],
      [request, { source: window }],
      [{ ...request, nonce: 'stale' }, {}],
      [{ ...request, name: 'x'.repeat(65) }, {}],
      [{ ...request, name: 'line\nbreak' }, {}],
    ]) send(source, data, extra);
    expect(onIdentityRename).not.toHaveBeenCalled();
    send(source, request);
    expect(onIdentityRename).toHaveBeenCalledExactlyOnceWith('Example Visitor');
  });

  it('refuses identity drafts from a renderer without the negotiated capability', async () => {
    const onIdentityRename = vi.fn();
    await renderFrame(<MemoryRouter><Harness onIdentityRename={onIdentityRename} /></MemoryRouter>);
    const iframe = screen.getByTitle('Test renderer');
    const source = iframe.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    const [hello] = post.mock.calls.at(-1);
    send(source, { type: 'eidoverse:ready', version: 1, nonce: hello.nonce, capabilities: {} });
    send(source, { type: 'eidoverse:identity-rename', version: 1, nonce: hello.nonce, name: 'Example Visitor' });
    expect(onIdentityRename).not.toHaveBeenCalled();
  });

  it('requires the hosted window, exact origin, current handshake and projected section route', async () => {
    await mount();
    const frame = screen.getByTitle('Test renderer');
    const source = frame.contentWindow;
    const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});
    fireEvent.load(frame);
    const [hello, origin] = post.mock.calls.at(-1);
    expect(origin).toBe('https://world.example.com');
    expect(hello).toMatchObject({ type: 'portos:connect', version: 1, labelVisibility: 'off' });
    expect(hello.capabilities.identityRenameRequest).toBeUndefined();
    expect(Object.keys(hello).sort()).toEqual(['capabilities', 'labelVisibility', 'nonce', 'type', 'version']);
    const navigation = { type: 'eidoverse:navigate', version: 1, nonce: hello.nonce, entityId: objects[0].id, route: '/apps' };
    send(source, navigation); // No handshake yet.
    expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');
    const ready = { type: 'eidoverse:ready', version: 1, nonce: hello.nonce, capabilities: { objectLabels: 1, portosNavigation: 1, labelPreferences: 1 } };
    send(source, { ...ready, version: 0 });
    send(source, navigation);
    expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');
    send(source, ready);
    for (const [data, extra] of [
      [navigation, { origin: 'https://attacker.example.com' }],
      [navigation, { source: window }],
      [{ ...navigation, nonce: 'old-session' }, {}],
      [{ ...navigation, version: 99 }, {}],
      [{ ...navigation, route: 'https://attacker.example.com/' }, {}],
      [{ ...navigation, route: '//attacker.example.com/' }, {}],
      [{ ...navigation, route: '/apps?redirect=https://attacker.example.com' }, {}],
      [{ ...navigation, route: '/apps/../settings' }, {}],
      [{ ...navigation, route: '/settings/database' }, {}],
      [{ ...navigation, entityId: 'foreign-object' }, {}],
    ]) {
      send(source, data, extra);
      expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');
    }
    fireEvent.click(screen.getByRole('button', { name: 'Hide labels' }));
    expect(post.mock.calls.at(-1)).toEqual([{
      type: 'portos:label-preference', version: 1, nonce: hello.nonce, labelVisibility: 'off',
    }, origin]);
    fireEvent.load(frame);
    const [nextHello] = post.mock.calls.at(-1);
    expect(nextHello.nonce).not.toBe(hello.nonce);
    expect(nextHello.labelVisibility).toBe('off');
    send(source, ready);
    send(source, navigation);
    expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');
    send(source, { ...ready, nonce: nextHello.nonce });
    send(source, { ...navigation, nonce: nextHello.nonce });
    expect(screen.getByLabelText('Route')).toHaveTextContent('/apps');
  });

  it('starts hidden even if an older visit saved always-on labels', async () => {
    safeWriteStorage('portos-eidoverse-label-visibility', 'all-nearby');
    await mount();
    const iframe = screen.getByTitle('Test renderer');
    const post = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    expect(post.mock.calls.at(-1)[0]).toMatchObject({ type: 'portos:connect', labelVisibility: 'off' });
  });

  it('marks an unresponsive older renderer unsupported without waiting in production time', async () => {
    vi.useFakeTimers();
    const view = await mount();
    const iframe = screen.getByTitle('Test renderer');
    vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
    fireEvent.load(iframe);
    act(() => vi.advanceTimersByTime(5000));
    expect(screen.getByLabelText('Bridge status')).toHaveTextContent('unsupported');
    view.unmount();
    expect(vi.getTimerCount()).toBe(0);
  });
});