Skip to content

@ogygia/federation

Non-ogygia hosts

The federation wire is plain HTTP and JSON, so a PHP page or a bare Node server can show an ogygia app's pages and widgets, with their islands awake. This page lists every endpoint, header and answer, and how to sign a call by hand.

On this page

A fragment carries the URL of the runtime that wakes its islands, so a host that isn’t an ogygia app at all can show one: anything that can make an HTTP request and print HTML. It needs two things: a request the producer accepts, which means signing it as a peer, and the producer’s runtime script on the page.

signHeaders() is in sign.ts below. A refused call answers { error, status } with no document, so check res.ok first. A redirect’s location is in the producer’s address space (/cms/…); map it to your own URL for that page. Answer with the document’s status, so the peer’s 404 page stays a 404. The title is plain text, so escape it; the rest is HTML. examples/mfe/foreign-hosts in the repository has complete hosts in plain Node and in PHP, with form posts and redirects. The producer’s built files must be served with CORS from an origin the browser can reach, and the producer lists the host as a peer with its public key.

import { signHeaders } from './sign';

type FragmentDocument = {
  status: number;
  location?: string;
  title: string;
  css: string[];
  head?: string;
  body: string;
  runtime?: string;
};

const escapeHtml = (s: string) =>
  s.replaceAll('&', '&amp;').replaceAll('<', '&lt;');

export async function renderSolar(): Promise<Response> {
  const url = new URL(
    '/og/fragment/page',
    'https://cms.example.com'
  );
  url.searchParams.set('path', '/solar');

  const res = await fetch(url, {
    headers: signHeaders(
      process.env.LEGACY_SIGNING_KEY!,
      'GET',
      url
    )
  });
 if (!res.ok)
    return new Response('The section is unavailable.', {
      status: 502
    });// a 400, 401, 404 or 413: { error, status }
  const doc = (await res.json()) as FragmentDocument;
   if (doc.location)
    return new Response(null, {
      status: 303,
      headers: { location: doc.location }
    }); 

  const html = `<!doctype html>
<html><head>
  <meta charset="utf-8">
  <title>${escapeHtml(doc.title)}</title>
  ${doc.css.join('')}${doc.head ?? ''}
  ${doc.runtime ? `<script type="module" src="${doc.runtime}"></script>` : ''}
</head><body>${doc.body}</body></html>`;
  return new Response(html, {
    status: doc.status,
    headers: { 'content-type': 'text/html; charset=utf-8' }
  });
}

Endpoints

Every endpoint answers JSON, except /og/frag.

Pages

GET /og/fragment/page?path=<route>&search=<query> returns a page of the exposed table. path is the route without the producer’s base, / when left out; search is optional. Send path with its leading /: one without it is served, but filed under the wrong thaw tag (#2311, item 12). A form post is the same URL with POST, the form body and its content-type. The answer is the fragment document, always with a 200 when the call is accepted, the page’s own status inside it:

StatusWhen
200The document: status, title, css, head, body, runtime, path, location for a redirect, sources, build, trace, server_ms.
400path would leave the producer’s origin (//host, /\host, \host), or the body didn’t arrive whole. The message says “path must start with exactly one /“.
401No signature, a bad one, a key the producer doesn’t list, the wrong audience, too old, or a replay.
404The app exposes no table.
413The body is over maxBodyBytes.

Errors are { "error": "<message>", "status": <code> }.

Widgets

GET /og/fragment/<name>?<props> returns { html, origin, sources, build, trace, server_ms }, with html the widget’s markup, its assets absolute to origin. A 401 is a signature problem, a 404 a widget the app doesn’t have, and a 500 a widget that returned no HTML. GET /og/fragment/__catalog is unsigned and returns the catalog.

Thaw notices

POST /og/thaw takes { "id": "<uuid>", "hop": 0, "tags": ["p:/cms/posts/1"] }, or "tags": "all", signed like any call. An ogygia sender also adds "from", its own federate({ name }), which receivers ignore: they name the sender by the key that checks. It answers { "ok": true, "thawed": <n> }, { "ok": true, "deduped": true } for an id it applied in the last 10 minutes, 400 for a body of another shape, 401, 413, or 503 when its store couldn’t apply it, so send it again. Cross-app thaw says what each tag clears.

Holes

GET /og/frag?peer=…&kind=…&target=…&search=…&exp=…&sig=…&k=… is the URL a shell writes for a deferred remote region. It’s signed with the shell’s own OGYGIA_SECRET, not with a key, and only the shell that wrote it can answer it. It returns HTML with cache-control: no-store:

StatusWhen
200The fragment’s HTML.
204A nested server island of the peer’s answered “keep the fallback”.
403A URL it didn’t sign, or an expired one, which the runtime renews.
404A peer it doesn’t list.
429The visitor spent their region budget, with Retry-After, as for any server island.
502A nested server island the peer didn’t answer as a region, or a peer answer it couldn’t use.
503, 504The peer’s own 503 or 504, or no answer in time (504).
Other 4xx and 5xxThe page’s own status when it’s 400 or above (the peer’s not-found or error page, inside a good answer), with no body, so the placeholder stays. A 404 or a 503 can mean either this or its row above.

Signing

The producer checks every call against the public keys in its peers, so a host signs as a peer. Make a pair with npx ogygia keys legacy, list the public key on the producer (peers: { legacy: { origin: 'https://legacy.example.com', key: env.LEGACY_PUBLIC_KEY } }), and sign each request with the private key. The signature is Ed25519 over this string, the parts joined by .:

PartValue
tsThe current time in milliseconds. The producer accepts skewMs either way, 120 s by default.
METHODThe HTTP method, upper case.
path and queryThe pathname and search of the URL you call, as sent: /og/fragment/page?path=%2Fsolar.
body hashThe base64 SHA-256 of the body’s bytes, or of no bytes for a GET.
claimsBase64 of the visitor claims as JSON, or empty for an anonymous call.
audienceThe producer’s audience, or the host of its ORIGIN when it sets none, port included.
nonceA random string, new for every request.

The request carries x-og-ts (the ts), x-og-n (the nonce), x-og-sig (the base64 signature, standard alphabet with padding) and, when there are claims, x-og-user (the same base64 claims). The private key is base64 PKCS#8 DER and the public key base64 SPKI DER, as npx ogygia keys prints them. In Node, with no ogygia dependency:

It signs for url.host, so it assumes the producer’s audience includes the host you call (Audience). An ogygia peer also sends x-og-cap, one token over the same parts, written v1.<expiry ms>.<nonce>.<signature>. A producer checks a call that carries it by that token alone, and still accepts the headers above without it. Those headers alone get weaker replay protection: once about 50,000 other calls signed this way (100,000 in the token form) arrive inside one window, a captured call sent with only these headers can be accepted again (Replay and clocks, #2312).

<ts>.<METHOD>.<path and query>.<body hash>.<claims>.<audience>.<nonce>
import {
  createPrivateKey,
  createHash,
  randomBytes,
  sign
} from 'node:crypto';

export function signHeaders(
  privateKey: string,
  method: string,
  url: URL,
  body?: Uint8Array,
  claims?: Record<string, unknown>
): Record<string, string> {
  const key = createPrivateKey({
    key: Buffer.from(privateKey, 'base64'),
    format: 'der',
    type: 'pkcs8'
  });
  const ts = String(Date.now());
  const nonce = randomBytes(8).toString('hex');
  const bodyHash = createHash('sha256')
    .update(body ?? new Uint8Array(0))
    .digest('base64');
  const user = claims
    ? Buffer.from(JSON.stringify(claims)).toString('base64')
    : '';
  const payload = `${ts}.${method.toUpperCase()}.${url.pathname + url.search}.${bodyHash}.${user}.${url.host}.${nonce}`;
  return {
    'x-og-ts': ts,
    'x-og-n': nonce,
    'x-og-sig': sign(null, Buffer.from(payload), key).toString(
      'base64'
    ),
    ...(user ? { 'x-og-user': user } : {})
  };
}

Form posts

To forward a form, POST the body to the same /og/fragment/page URL, signed over those exact bytes, with the form’s content-type and an origin header equal to the origin the producer answers on: its ORIGIN, which isn’t always the address you call. A built Kit app refuses a form post whose Origin isn’t its own with a 403, before ogygia sees it.

When the document has a location, answer the browser with a redirect. The location is in the producer’s own address space (/cms/posts/1), so the host maps it to its own URL for that page.

import { signHeaders } from './sign';

// the address you call; signHeaders() signs for its host, so the producer lists both
// hosts in its audience: ['cms.example.com', 'cms.internal']
const producer = 'https://cms.internal';
const producerOrigin = 'https://cms.example.com'; // the producer's ORIGIN
const url = new URL('/og/fragment/page', producer);
url.searchParams.set('path', '/posts/1');
const body = new TextEncoder().encode('comment=hello');

const doc = await (
  await fetch(url, {
    method: 'POST',
    body,
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
      origin: producerOrigin,
      ...signHeaders(
        process.env.LEGACY_SIGNING_KEY!,
        'POST',
        url,
        body
      )
    }
  })
).json();
// doc.location: send the browser a 303 there

Signing helpers

Inside an ogygia app, the same two halves are exported from @ogygia/federation, for endpoints of your own:

  • sign_headers(privateKey, method, url, body?, claims?, audience?) returns the headers a peer sends, x-og-cap included. audience defaults to url.host.
  • verify_signed_request({ publicKeys, audience?, skewMs? }, request, url, body?) returns { user? } for a fresh, valid signature from one of publicKeys that hasn’t been seen before, or null. Without audience, it checks against the host of ORIGIN, and with neither it returns null.

A check records the signature in the replay memory, so check each request once: a second check of the same request returns null. The memory is the one federation’s own endpoints use, with the same limits (Replay and clocks). Import these in an ogygia app’s server code; a server that isn’t one signs with code like signHeaders() above.

import type { RequestHandler } from './$types';
import { verify_signed_request } from '@ogygia/federation';
import { env } from '$env/dynamic/private';

export const POST: RequestHandler = async ({
  request,
  url
}) => {
  const body = new Uint8Array(await request.arrayBuffer());
  const publicKeys = [env.SHELL_PUBLIC_KEY].filter(
    (k) => k !== undefined
  );
  const ok =  verify_signed_request(
    { publicKeys, audience: 'cms.internal' },
    request,
    url,
    body
  ); 
  if (!ok) return new Response('unauthorized', { status: 401 });
  // ok.user holds the signed claims, if any
  return new Response(null, { status: 204 });
};