Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(home-satellite): serve health and mint a token while still unpaired
nirholas9e9a2f42f779
diff --git a/services/home-satellite/src/bridge.js b/services/home-satellite/src/bridge.jsindex f3ad44eaa..7d0e18626 100644--- a/services/home-satellite/src/bridge.js+++ b/services/home-satellite/src/bridge.js@@ -184,10 +184,14 @@ export function attachViewer(satellite, socket, { identity, onLog = () => {} } =* @param {object} options.identity* @param {(entry: object) => void} [options.onLog]*/-export function createViewerServer({ satellite, satelliteId, secret, identity, onLog = () => {} }) {+export function createViewerServer({ satellite, satelliteId = null, secret = null, identity, health = null, pairingError = null, onLog = () => {} }) {const http = createServer((req, res) => {if (req.url === '/healthz' || req.url === '/') {- const body = JSON.stringify({ ok: true, satellite_id: satelliteId, ...satellite.snapshot(), viewers: viewers.size });+ const body = JSON.stringify(+ health+ ? health()+ : { ok: !!secret, satellite_id: satelliteId, ...satellite.snapshot(), viewers: viewers.size },+ );res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });res.end(body);return;@@ -211,6 +215,15 @@ export function createViewerServer({ satellite, satelliteId, secret, identity, osocket.destroy();return;}+ // An unpaired satellite serves health and refuses everything else. There+ // is no room to join and no secret to check a token against, so the only+ // honest answer is the reason, closed cleanly enough for a browser to+ // read it rather than report a generic network failure.+ if (!secret) {+ onLog({ level: 'warn', event: 'viewer.rejected', reason: 'unpaired' });+ wss.handleUpgrade(req, socket, head, (ws) => ws.close(CLOSE.UNAUTHORIZED, pairingError || 'this satellite is not paired'));+ return;+ }const check = verifyToken(url.searchParams.get('token') || '', secret);if (!check.ok || check.claims.role !== ROLE.VIEWER || check.claims.sid !== satelliteId) {onLog({ level: 'warn', event: 'viewer.rejected', reason: check.ok ? 'wrong_room' : check.reason });diff --git a/services/home-satellite/src/index.js b/services/home-satellite/src/index.jsindex 90fd9ab2e..72120c656 100755--- a/services/home-satellite/src/index.js+++ b/services/home-satellite/src/index.js@@ -11,6 +11,8 @@*/import { createSatelliteService, createHubService, SERVICE_VERSION } from './server.js';+import { loadIdentity } from './pairing.js';+import { signToken, ROLE } from './token.js';const argv = process.argv.slice(2);const role = argv.find((a) => !a.startsWith('-')) || process.env.SATELLITE_ROLE || 'satellite';@@ -40,13 +42,27 @@ if (argv.includes('--help') || argv.includes('-h')) {process.exit(0);}+const log = (entry) => process.stdout.write(`${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\n`);+// `token` prints one credential to stdout and nothing else, because the-// documented way to use it is `--token "$(node src/index.js token)"`. Logging a-// startup line to stdout in that role puts JSON in front of the token and hands-// the caller something that cannot authenticate. Every other role logs to-// stdout, where a container runtime collects it.-const logStream = role === 'token' ? process.stderr : process.stdout;-const log = (entry) => logStream.write(`${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\n`);+// documented way to use it is `--token "$(node src/index.js token)"`: a startup+// line on stdout would put JSON in front of the token and hand the caller+// something that cannot authenticate. It reads the identity off disk and signs,+// and deliberately does NOT build the service. The documented place to run it is+// the machine already running the satellite, so constructing the service here+// binds 10700 and 10701 a second time and the role died with EADDRINUSE in+// exactly the situation it exists for. Signing needs the satellite id and the+// secret and nothing else, so there is no server to start and no hub to dial.+if (role === 'token') {+ const identity = await loadIdentity(flag('state-dir', process.env.SATELLITE_STATE_DIR || './.satellite'));+ if (!identity) {+ console.error('this satellite has not been paired, so it has no room to hand out tokens for');+ process.exit(1);+ }+ const ttl = Number(flag('ttl', process.env.VIEWER_TOKEN_TTL || 3600));+ process.stdout.write(`${signToken({ sid: identity.satellite_id, role: ROLE.VIEWER }, identity.secret, ttl)}\n`);+ process.exit(0);+}if (role === 'hub') {const service = await createHubService({ port: Number(flag('port', process.env.PORT || 8080)), log });@@ -69,17 +85,6 @@ if (role === 'hub') {log,});- if (role === 'token') {- const token = service.viewerToken(3600);- await service.close();- if (!token) {- console.error('this satellite has not been paired, so it has no room to hand out tokens for');- process.exit(1);- }- process.stdout.write(`${token}\n`);- process.exit(0);- }-const health = service.health();log({ level: 'info', event: 'satellite.ready', ...health });if (!health.paired) {diff --git a/services/home-satellite/src/server.js b/services/home-satellite/src/server.jsindex 5d8229abe..13f84d8d6 100644--- a/services/home-satellite/src/server.js+++ b/services/home-satellite/src/server.js@@ -131,49 +131,68 @@ export async function createSatelliteService({version: SERVICE_VERSION,};- if (paired) {- viewerServer = createViewerServer({+ const health = () => ({+ ok: paired,+ service: 'home-satellite',+ version: SERVICE_VERSION,+ wyoming: WYOMING_VERSION,+ paired,+ pairing_error: pairingError,+ satellite_id: identity?.satellite_id || null,+ agent: identity?.agent || null,+ hub_connected: !!hubLink?.connected,+ viewers: viewerCount(),+ ...satellite.snapshot(),+ });++ // The viewer server runs whether or not the satellite is paired. An unpaired+ // one serves its health (and so says WHY it is unpaired) and closes every+ // viewer upgrade with that reason, which is the state an operator is most+ // likely to be debugging. Refusing to open the port at all leaves them+ // nothing to read but a container that looks alive.+ viewerServer = createViewerServer({+ satellite,+ satelliteId: identity?.satellite_id || null,+ secret: identity?.secret || null,+ identity: identityForViewer,+ health,+ pairingError,+ onLog: log,+ });+ viewerAddress = await viewerServer.listen(viewerPort, host);+ log({ level: 'info', event: 'viewer.listening', port: viewerAddress.port, paired });++ if (paired && hub && identity.hub_url) {+ // The token is read fresh on every dial, so a reconnect after a long+ // outage picks up whatever the refresh loop last stored rather than+ // replaying an expired one.+ hubLink = createHubLink({satellite,- satelliteId: identity.satellite_id,- secret: identity.secret,+ url: identity.hub_url,+ token: () => identity.hub_token,identity: identityForViewer,onLog: log,});- viewerAddress = await viewerServer.listen(viewerPort, host);- log({ level: 'info', event: 'viewer.listening', port: viewerAddress.port });-- if (hub && identity.hub_url) {- // The token is read fresh on every dial, so a reconnect after a long- // outage picks up whatever the refresh loop last stored rather than- // replaying an expired one.- hubLink = createHubLink({- satellite,- url: identity.hub_url,- token: () => identity.hub_token,- identity: identityForViewer,- onLog: log,- });-- const refresh = async () => {- try {- const next = await refreshHubToken({ identity, fetchImpl });- identity = { ...identity, ...next };- await saveIdentity(stateDir, identity);- log({ level: 'info', event: 'hub.token_refreshed', expires: identity.hub_token_exp });- } catch (err) {- log({ level: 'warn', event: 'hub.token_refresh_failed', message: err.message });- }- };- const schedule = () => {- const seconds = Math.max(60, (identity.hub_token_exp || 0) - Math.floor(Date.now() / 1000) - HUB_TOKEN_LEAD_SECONDS);- hubRefresh = setTimeout(async () => {- await refresh();- schedule();- }, seconds * 1000);- hubRefresh.unref?.();- };- schedule();- }++ const refresh = async () => {+ try {+ const next = await refreshHubToken({ identity, fetchImpl });+ identity = { ...identity, ...next };+ await saveIdentity(stateDir, identity);+ log({ level: 'info', event: 'hub.token_refreshed', expires: identity.hub_token_exp });+ } catch (err) {+ log({ level: 'warn', event: 'hub.token_refresh_failed', message: err.message });+ }+ };+ const schedule = () => {+ const seconds = Math.max(60, (identity.hub_token_exp || 0) - Math.floor(Date.now() / 1000) - HUB_TOKEN_LEAD_SECONDS);+ hubRefresh = setTimeout(async () => {+ await refresh();+ schedule();+ }, seconds * 1000);+ hubRefresh.unref?.();+ };+ schedule();}return {@@ -190,21 +209,7 @@ export async function createSatelliteService({if (!identity) return null;return signToken({ sid: identity.satellite_id, role: ROLE.VIEWER }, identity.secret, ttlSeconds);},- health() {- return {- ok: paired,- service: 'home-satellite',- version: SERVICE_VERSION,- wyoming: WYOMING_VERSION,- paired,- pairing_error: pairingError,- satellite_id: identity?.satellite_id || null,- agent: identity?.agent || null,- hub_connected: !!hubLink?.connected,- viewers: viewerCount(),- ...satellite.snapshot(),- };- },+ health,async close() {if (hubRefresh) clearTimeout(hubRefresh);hubLink?.close();diff --git a/tests/home-satellite-pairing.test.js b/tests/home-satellite-pairing.test.jsindex 4d225ea69..2fc8539e5 100644--- a/tests/home-satellite-pairing.test.js+++ b/tests/home-satellite-pairing.test.js@@ -7,7 +7,16 @@import { describe, expect, it } from 'vitest';+import { spawn } from 'node:child_process';+import { createServer } from 'node:net';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { generateCode, normalizeCode, CODE_TTL_MINUTES } from '../api/_lib/home/satellites.js';+import { saveIdentity } from '../services/home-satellite/src/pairing.js';+import { newSecret, verifyToken, ROLE } from '../services/home-satellite/src/token.js';import { PcmDownsampler, floatTo16kPcm } from '../src/voice/mic-capture.js';describe('pairing codes', () => {@@ -109,3 +118,69 @@ describe('the streaming resampler', () => {expect(Math.abs(streamed - oneShot.length)).toBeLessThan(4);});});++// The `token` role exists to be run on the machine that is already running the+// satellite, because that is where the identity file is. It used to build the+// whole service to reach the signing key, which bound the Wyoming and viewer+// ports a second time and died with EADDRINUSE in exactly that situation. So+// the test that matters is that it mints while those ports are occupied.+describe('the token role', () => {+ it('mints a viewer token while the satellite it belongs to is running', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'satellite-token-'));+ const identity = {+ satellite_id: '00000000-0000-4000-8000-00000000beef',+ secret: newSecret(),+ name: 'Kitchen display',+ agent: { id: 'a', name: 'Ada', avatarUrl: null },+ };+ await saveIdentity(dir, identity);++ // Hold two ports and then tell the child to use exactly those, which is+ // what a running satellite does to the machine the token is minted on.+ const held = [createServer(), createServer()];+ const ports = await Promise.all(held.map((s) => new Promise((resolve, reject) => {+ s.once('error', reject);+ s.listen(0, '127.0.0.1', () => resolve(s.address().port));+ })));++ try {+ const token = await new Promise((resolve, reject) => {+ const child = spawn(process.execPath, ['src/index.js', 'token', '--state-dir', dir], {+ cwd: fileURLToPath(new URL('../services/home-satellite', import.meta.url)),+ env: { ...process.env, WYOMING_PORT: String(ports[0]), VIEWER_PORT: String(ports[1]) },+ });+ let out = '';+ let err = '';+ child.stdout.on('data', (b) => { out += b; });+ child.stderr.on('data', (b) => { err += b; });+ child.on('close', (code) => (code === 0 ? resolve(out.trim()) : reject(new Error(`exit ${code}: ${err}`))));+ });++ // Nothing but the token: the documented use is `--token "$(… token)"`.+ expect(token.split('\n')).toHaveLength(1);+ const check = verifyToken(token, identity.secret);+ expect(check.ok).toBe(true);+ expect(check.claims.sid).toBe(identity.satellite_id);+ expect(check.claims.role).toBe(ROLE.VIEWER);+ } finally {+ await Promise.all(held.map((s) => new Promise((r) => s.close(r))));+ await rm(dir, { recursive: true, force: true });+ }+ });++ it('exits non-zero when the satellite has never been paired', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'satellite-token-'));+ try {+ const code = await new Promise((resolve) => {+ const child = spawn(process.execPath, ['src/index.js', 'token', '--state-dir', dir], {+ cwd: fileURLToPath(new URL('../services/home-satellite', import.meta.url)),+ stdio: 'ignore',+ });+ child.on('close', resolve);+ });+ expect(code).toBe(1);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });+});diff --git a/tests/home-satellite-server.test.js b/tests/home-satellite-server.test.jsindex 0efc21dc5..206cfdf8a 100644--- a/tests/home-satellite-server.test.js+++ b/tests/home-satellite-server.test.js@@ -299,6 +299,44 @@ describe('an unpaired satellite', () => {expect(error.data.code).toBe('unpaired');expect(error.data.text).toMatch(/has not been paired/);});++ // The state an operator is most likely to be debugging is the one where+ // nothing works yet, so the health endpoint has to answer in it. It used to+ // be created only for a paired satellite, which meant the documented+ // `curl localhost:10701/healthz` answered nothing at all on a fresh install.+ it('still serves its health, and says why it is unpaired', async () => {+ const { satellite } = await startSatellite({ paired: false });+ const server = createViewerServer({+ satellite,+ secret: null,+ identity: { name: 'three.ws agent', agent: null, version: '1.0.0' },+ pairingError: 'no pairing code was supplied and no identity has been claimed',+ });+ const address = await server.listen(0, '127.0.0.1');+ cleanup(() => server.close());++ const health = await fetch(`http://127.0.0.1:${address.port}/healthz`).then((r) => r.json());+ expect(health.ok).toBe(false);+ expect(health.paired).toBe(false);+ expect(health.state).toBe('unpaired');+ });++ it('closes a viewer with the reason it cannot be watched', async () => {+ const { satellite } = await startSatellite({ paired: false });+ const server = createViewerServer({+ satellite,+ secret: null,+ identity: { name: 'three.ws agent', agent: null, version: '1.0.0' },+ pairingError: 'no pairing code was supplied and no identity has been claimed',+ });+ const address = await server.listen(0, '127.0.0.1');+ cleanup(() => server.close());++ const ws = new WebSocket(`ws://127.0.0.1:${address.port}/viewer?token=anything`);+ const [code, reason] = await once(ws, 'close');+ expect(code).toBe(4401);+ expect(String(reason)).toMatch(/no pairing code/);+ });});describe('viewer tokens', () => {