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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add scoped local managed-app visitor broker
[._.]/ Adam Eivyc24d9927c433
diff --git a/data.reference/managed-visitor-credentials.json b/data.reference/managed-visitor-credentials.jsonnew file mode 100644index 0000000000..4614a96a42--- /dev/null+++ b/data.reference/managed-visitor-credentials.json@@ -0,0 +1 @@+{"schemaVersion":1,"credentials":[]}diff --git a/docs/README.md b/docs/README.mdindex deab2928b6..343f68145c 100644--- a/docs/README.md+++ b/docs/README.md@@ -64,3 +64,5 @@ Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./feat- **[examples/](./examples/README.md)** — copy-ready config examples (e.g. Claude Code → Ollama settings).- **[`.changelog/README.md`](../.changelog/README.md)** — how `/do:release` synthesizes release notes from the commit log, and the versioned-file format.- **media/** — screenshots and logo used by the root README.++- [Local managed-app visitor broker](features/managed-visitors.md) — opt-in credential provisioning, versioned nonhumanoid scope and host negotiation.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex b9d08f0031..4d627b0c25 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -466,3 +466,7 @@ scheduled-task defaults remain unchanged. `mind.choose-name` uses `manageMind`,normal semantic validation, call budgets, idempotency and trajectory outcomes.Without that grant the existing automatic core-identity memory path can retainan initial conversational choice; it does not grant semantic write authority.++### Managed-app visitor credentials++`data/managed-visitor-credentials.json` is `file-primary`, intentionally machine-local and never federated: bounded app credential digests, exact individual/world allowlists and expiries configure this install's loopback visitor broker. There are no cross-record queries, sync cursors or tombstones. No plaintext credential or neural/private history is stored. The empty schema-1 seed initializes new installs; this new standalone document changes no existing record format. Backups retain the credential configuration with other local data. Ephemeral visitor admissions are memory-only, expire independently at the host, and never resume on startup. Adapter: `server/services/managedVisitorBroker.js`; protocol: [managed visitors](features/managed-visitors.md).diff --git a/docs/features/managed-visitors.md b/docs/features/managed-visitors.mdnew file mode 100644index 0000000000..3b71c83b0a--- /dev/null+++ b/docs/features/managed-visitors.md@@ -0,0 +1,61 @@+# Local managed-app visitor broker++The version-1 broker provides an explicit, app-scoped route to a separately configured nonhumanoid Eidoverse host. It never reuses peer/Mind travel, humanoid guest tickets, the owner identity or ordinary PortOS session credentials as app authority. It makes no boot traffic and starts no host. Without a configured host credential and exact negotiated capabilities it returns unavailable.++## Owner setup and credential lifecycle++Use the ordinary PortOS owner API:++- `GET /api/managed-visitor-admin` lists credential metadata and allowed scopes, never hashes or plaintext credentials.+- `POST /api/managed-visitor-admin/:appId/credential` provisions or rotates a credential for an existing, unarchived managed-app record. Body: `{individualIds:["individual-a"],worldIds:["quiet-garden"],ttlMs:86400000}`. IDs start with a letter or digit and contain 1–128 letters, digits, dots, underscores, colons or hyphens. Allow 1–64 individual IDs and 1–32 worlds. Credential lifetime is 1 minute to 7 days. The response contains `credential` **once**, plus scope and expiry metadata; do not log or publish it. Rotation revokes existing sessions.+- `DELETE /api/managed-visitor-admin/:appId/credential` revokes its credential and current sessions.++When an instance password is set, management requires a verified owner session; a peer Basic credential is insufficient. When the password is unset, management retains PortOS's existing private-install owner API posture: no authenticated human identity can be inferred. Cross-origin requests and app bearer credentials are rejected by management in either posture. A local process with unrestricted access to the passwordless owner API is not sandboxed by this feature.++`data/managed-visitor-credentials.json` contains only SHA-256 credential digests, app IDs, exact scope allowlists and timestamps. It is bounded to 64 credentials and 64 KiB, machine-local and never federated. Admission/session authority is memory-only and is forgotten on restart. A restart does not resume any visit.++The host administrator separately configures matching **64 lowercase hexadecimal characters** in `PORTOS_EIDOVERSE_VISITOR_TOKEN` for PortOS and Eidoverse. This host credential is distinct from every app credential. The Eidoverse host also requires its explicit world allowlist. No command in this document configures, starts or restarts a live host; setup is a deliberate operator action after both source implementations are reviewed.++## App-facing protocol++Every `/api/managed-visitors/v1/*` request requires `Authorization: Bearer <credential>` and a direct loopback socket. The broker accepts neither forwarded-IP claims nor ordinary owner sessions as substitutes. The same credential verification runs whether the instance password is set or unset. A credential never grants access to other password-protected PortOS APIs. Observer/browser UI should not receive these backend credentials.++`GET /capabilities` returns `{version:1,available,appId,worldIds,individualIds,contract,reason}`. Availability requires the host's explicit `managedVisitors` contract; old `guestEntry` support alone is insufficient.++`POST /admissions` accepts exactly:++```json+{"individualId":"individual-a","individualSessionId":"runtime-a","worldId":"quiet-garden","body":"fly-v1","ttlMs":30000}+```++TTL is 1–300 seconds and cannot outlive the app credential. Each app/individual has at most one live or pending admission, across all worlds and runtime sessions. The global admission bound is 64. A successful response contains `version`, the authenticated `appId`, the three requested scope IDs, opaque broker `sessionId`, `epoch`, `expiresAt`, `status:"paused"` and `pose:{x,z,yaw}`. Admission never starts movement. Every subsequent request must carry that exact scope and epoch. Restore/replacement must leave and explicitly admit the new individual runtime session.++`POST /sessions/:sessionId/observations` body is exactly `{individualId,individualSessionId,worldId,epoch}`. The response adds `version`, `appId`, the same broker `sessionId`, `frameId`, `capturedAtMs`, `camera:"controller"`, `width:8`, `height:4`, `rgb` (96 integer bytes), `pose`, and `sensorySource:"engineered-gentle-patch-spatial-proxy-v1"`. This host source is an engineered spatial proxy from its declared gentle patch, **not rendered retinal imagery or validated fly vision**. Responses must advance frame IDs and be at most 250 ms old. Unknown/private fields are rejected rather than forwarded.++`POST /sessions/:sessionId/actions` takes the same scope plus `sequence` (starting at zero, increasing by exactly one) and one action:++```json+{"type":"start"}+{"type":"pause"}+{"type":"rest"}+{"type":"leave"}+{"type":"move","forward":0.05,"yaw":0.1,"intervalMs":5}+```++Movement is bounded to forward speed 0–0.12 and yaw speed −0.8–0.8 per second over exactly 5 ms. Pose is bounded to x/z ±2 and yaw ±π. Host actions return the same scope plus `sequence`, `status`, `pose` and the unchanged expiry. These are engineered controls; arbitrary verbs, scripts, messages, neural state, weights, private history and tool calls are never accepted.++One operation per session can be pending. Malformed, mismatched or uncertain host responses revoke local authority and attempt scoped host cleanup; no uncertain action is retried. Credential rotation during a pending admission/action cannot publish new authority for the old credential. A backward broker clock revokes active authority. Expired, revoked, wrong-app, wrong-world, wrong-individual/session/epoch and replayed requests are refused.++## Host-facing contract++Requests go only to fixed loopback port 8940 under `/api/managed-visitors/v1`, with the separate host bearer, a three-second deadline, redirects disabled and response buffering capped at 16 KiB. `/version` must negotiate:++```json+{"capabilities":{"managedVisitors":{"version":1,"bodies":["fly-v1"],"controllerRaster":{"width":8,"height":4,"channels":3},"actions":["start","pause","rest","move","leave"],"expiryEnforced":true}}}+```++Host admissions add `version:1` and the authenticated `appId` to the app request. Later host operations add `appId` to the scoped body and use the private host session ID, which PortOS never exposes as app authority. Host admission/action responses include `expiresAt`; the broker checks it and clamps the outward deadline to its own earlier limit. Both layers independently enforce scope and expiry.++A dedicated unsequenced `POST /sessions/:hostId/leave` takes `{appId,individualId,individualSessionId,worldId,epoch}` for idempotent revocation. It must invalidate a pending action even when its sequence is uncertain. This is how credential revocation avoids racing the normal action sequence. If the host cannot be reached, broker authority is still revoked immediately and independently enforced host expiry bounds the remaining ephemeral presence.++This foundation does not implement connectome execution, retained learning, travel consent inference, arbitrary world authority or client-side embodiment. Fly Garden remains paused at home unless its own explicit visitor adapter is subsequently enabled. Source changes do not enable a production visitor.diff --git a/server/index.js b/server/index.jsindex 279665f8d3..652add72a8 100644--- a/server/index.js+++ b/server/index.js@@ -90,6 +90,7 @@ import backupRoutes from './routes/backup.js';import legacyExportRoutes from './routes/legacyExport.js';import eidoverseWorldRoutes from './routes/eidoverseWorldRoutes.js';import eidoverseTravelRoutes from './routes/eidoverseTravelRoutes.js';+import { createManagedVisitorRoutes, createManagedVisitorAdminRoutes } from './routes/managedVisitors.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';import codeReviewRoutes from './routes/codeReview.js';@@ -318,6 +319,8 @@ app.use('/api/backup', backupRoutes);app.use('/api/legacy-export', legacyExportRoutes);app.use('/api/eidoverse/world', eidoverseWorldRoutes);app.use('/api/eidoverse/travel', eidoverseTravelRoutes);+app.use('/api/managed-visitors/v1', createManagedVisitorRoutes());+app.use('/api/managed-visitor-admin', createManagedVisitorAdminRoutes());app.use('/api/database', databaseRoutes);app.use('/api/uploads', uploadsRoutes);app.use('/api/image-clean', imageCleanRoutes);diff --git a/server/lib/managedVisitorValidation.js b/server/lib/managedVisitorValidation.jsnew file mode 100644index 0000000000..6e440be4b2--- /dev/null+++ b/server/lib/managedVisitorValidation.js@@ -0,0 +1,24 @@+import { z } from 'zod';+const id = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/);+export const visitorScopeSchema = z.object({ individualId: id, individualSessionId: id, worldId: id, epoch: id }).strict();+export const visitorCredentialSchema = z.object({ individualIds: z.array(id).min(1).max(64), worldIds: z.array(id).min(1).max(32),+ ttlMs: z.number().int().min(60000).max(7 * 86400000) }).strict();+export const visitorAdmissionSchema = z.object({ individualId: id, individualSessionId: id, worldId: id,+ body: z.literal('fly-v1'), ttlMs: z.number().int().min(1000).max(300000) }).strict();+export const visitorActionSchema = visitorScopeSchema.extend({ sequence: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),+ action: z.discriminatedUnion('type', [z.object({ type: z.enum(['start', 'pause', 'rest', 'leave']) }).strict(),+ z.object({ type: z.literal('move'), forward: z.number().min(0).max(0.12), yaw: z.number().min(-0.8).max(0.8), intervalMs: z.literal(5) }).strict()]) }).strict();+export const visitorIdSchema = id;+export const visitorPoseSchema = z.object({ x: z.number().finite().min(-2).max(2), z: z.number().finite().min(-2).max(2),+ yaw: z.number().finite().min(-Math.PI).max(Math.PI) }).strict();+const hostScope = visitorScopeSchema.extend({ version: z.literal(1), appId: id, sessionId: id });+export const visitorHostAdmissionSchema = hostScope.extend({ expiresAt: z.number().int().positive(), status: z.literal('paused'), pose: visitorPoseSchema }).strict();+export const visitorHostObservationSchema = hostScope.extend({ frameId: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),+ capturedAtMs: z.number().int().positive(), sensorySource: z.literal('engineered-gentle-patch-spatial-proxy-v1'), camera: z.literal('controller'), width: z.literal(8), height: z.literal(4),+ rgb: z.array(z.number().int().min(0).max(255)).length(96), pose: visitorPoseSchema }).strict();+export const visitorHostActionSchema = hostScope.extend({ expiresAt: z.number().int().positive(), sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),+ status: z.enum(['running', 'paused', 'resting', 'left']), pose: visitorPoseSchema }).strict();+export const visitorCredentialDocumentSchema = z.object({ schemaVersion: z.literal(1), credentials: z.array(z.object({+ appId: id, digest: z.string().regex(/^[a-f0-9]{64}$/), individualIds: z.array(id).min(1).max(64), worldIds: z.array(id).min(1).max(32),+ createdAt: z.number().int().positive(), expiresAt: z.number().int().positive(),+}).strict()).max(64) }).strict();diff --git a/server/routes/managedVisitors.js b/server/routes/managedVisitors.jsnew file mode 100644index 0000000000..1133890698--- /dev/null+++ b/server/routes/managedVisitors.js@@ -0,0 +1,51 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { visitorCredentialSchema, visitorAdmissionSchema, visitorScopeSchema, visitorActionSchema, visitorIdSchema } from '../lib/managedVisitorValidation.js';+import { getManagedVisitorBroker } from '../services/managedVisitors.js';+import { isCrossOrigin } from '../../lib/portosAuthCore.js';++// Keep the large shared validation barrel off the broker's import-only path.+const validateRequest = async (schema, value) => (await import('../lib/validation.js')).validateRequest(schema, value);++export function createManagedVisitorRoutes(getBroker = getManagedVisitorBroker) {+ const router = Router();+ router.use((req, _res, next) => {+ if (!req.managedVisitorAuth) return next(new ServerError('Managed app credential required.', { status: 401 }));+ next();+ });+ router.get('/capabilities', asyncHandler(async (req, res) => res.json(await getBroker().capabilities(req.managedVisitorAuth))));+ router.post('/admissions', asyncHandler(async (req, res) => {+ const body = await validateRequest(visitorAdmissionSchema, req.body); res.json(await getBroker().admit(req.managedVisitorAuth, body));+ }));+ router.post('/sessions/:id/observations', asyncHandler(async (req, res) => {+ const id = await validateRequest(visitorIdSchema, req.params.id), body = await validateRequest(visitorScopeSchema, req.body);+ res.json(await getBroker().observe(req.managedVisitorAuth, id, body));+ }));+ router.post('/sessions/:id/actions', asyncHandler(async (req, res) => {+ const id = await validateRequest(visitorIdSchema, req.params.id), body = await validateRequest(visitorActionSchema, req.body);+ res.json(await getBroker().action(req.managedVisitorAuth, id, body));+ }));+ return router;+}++export function createManagedVisitorAdminRoutes(getBroker = getManagedVisitorBroker) {+ const router = Router();+ router.use((req, _res, next) => {+ // No app/peer credential acquires owner provisioning authority. Auth-off retains+ // PortOS's documented private-install owner API posture, with explicit CSRF protection.+ if (isCrossOrigin(req) || /^Bearer mv1_/i.test(req.headers.authorization ?? '')+ || req.portosAuthContext?.enabled && req.portosAuthContext.method !== 'session') {+ return next(new ServerError('Visitor credential management requires the owner interface.', { status: 403 }));+ }+ next();+ });+ router.get('/', asyncHandler(async (_req, res) => res.json({ credentials: await getBroker().listCredentials() })));+ router.post('/:appId/credential', asyncHandler(async (req, res) => {+ const id = await validateRequest(visitorIdSchema, req.params.appId), body = await validateRequest(visitorCredentialSchema, req.body);+ res.set('Cache-Control', 'no-store'); res.json(await getBroker().provision(id, body));+ }));+ router.delete('/:appId/credential', asyncHandler(async (req, res) => {+ res.json(await getBroker().revoke(await validateRequest(visitorIdSchema, req.params.appId)));+ }));+ return router;+}diff --git a/server/routes/managedVisitors.test.js b/server/routes/managedVisitors.test.jsnew file mode 100644index 0000000000..ec9562f22e--- /dev/null+++ b/server/routes/managedVisitors.test.js@@ -0,0 +1,150 @@+import { beforeEach, afterEach, expect, it, vi } from 'vitest';+import express from 'express';+import { mkdtemp, rm, readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { EventEmitter } from 'node:events';+import { createManagedVisitorBroker, managedVisitorContract } from '../services/managedVisitorBroker.js';+import { request } from '../lib/testHelper.js';+const shared = vi.hoisted(() => ({ enabled: false, broker: null }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => shared.enabled, extractToken: req => req.headers.authorization?.slice(7),+ verifySession: async token => token === 'owner-session', verifyPassword: async () => false }));+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}), settingsEvents: new EventEmitter() }));+vi.mock('../services/managedVisitors.js', async () => {+ const actual = await vi.importActual('../services/managedVisitors.js');+ return { ...actual, getManagedVisitorBroker: () => shared.broker,+ authenticateManagedVisitorRequest: req => actual.authenticateManagedVisitorRequest(req, shared.broker) };+});+import { authGate } from '../services/authGate.js';+import { createManagedVisitorRoutes, createManagedVisitorAdminRoutes } from './managedVisitors.js';+let directory, app, clock, host, credentials, count, delayed;+const appId = 'managed-app', individualId = 'individual-a', individualSessionId = 'runtime-a', worldId = 'quiet-garden';+const admission = { individualId, individualSessionId, worldId, body: 'fly-v1', ttlMs: 30000 };+const credentialInput = { individualIds: [individualId], worldIds: [worldId], ttlMs: 60000 };+const scope = visit => ({ individualId, individualSessionId, worldId, epoch: visit.epoch });+const authHeader = () => `Bearer ${credentials.credential}`;+beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'portos-managed-visitor-')); clock = Date.now(); shared.enabled = false; delayed = null; count = 0;+ host = {+ capabilities: vi.fn(async () => ({ managedVisitors: managedVisitorContract })),+ admit: vi.fn(async body => {+ if (delayed) await delayed;+ return { version: 1, appId: body.appId, individualId: body.individualId, individualSessionId: body.individualSessionId,+ worldId: body.worldId, epoch: 'host-epoch', sessionId: `host-${count++}`, expiresAt: clock + body.ttlMs, status: 'paused', pose: { x: 0, z: 0, yaw: 0 } };+ }),+ observe: vi.fn(async (id, body) => ({ version: 1, ...body, sessionId: id, frameId: 0, capturedAtMs: clock,+ camera: 'controller', sensorySource: 'engineered-gentle-patch-spatial-proxy-v1', width: 8, height: 4, rgb: Array(96).fill(0), pose: { x: 0, z: 0, yaw: 0 } })),+ action: vi.fn(async (id, { sequence, action, ...body }) => ({ version: 1, ...body, sessionId: id, sequence, expiresAt: clock + admission.ttlMs,+ status: { start: 'running', pause: 'paused', rest: 'resting', move: 'running', leave: 'left' }[action.type], pose: { x: 0, z: 0, yaw: 0 } })),+ leave: vi.fn(async () => ({ status: 'left' })),+ };+ shared.broker = createManagedVisitorBroker({ path: join(directory, 'credentials.json'), getApp: async id => id === appId ? { id } : null, host, now: () => clock });+ app = express(); app.use(express.json()); app.use(authGate);+ app.use('/api/managed-visitors/v1', createManagedVisitorRoutes(() => shared.broker));+ app.use('/api/managed-visitor-admin', createManagedVisitorAdminRoutes(() => shared.broker));+ app.get('/api/private', (_req, res) => res.json({ private: true }));+ app.use((err, _req, res, _next) => res.status(err.status || 500).json({ error: err.code || 'error' }));+ const response = await request(app).post(`/api/managed-visitor-admin/${appId}/credential`).send(credentialInput);+ expect(response.status).toBe(200); credentials = response.body;+});+afterEach(async () => { await rm(directory, { recursive: true, force: true }); });+it('requires separate app credentials with optional password off/on and grants no owner or protected ordinary API authority', async () => {+ for (const enabled of [false, true]) {+ shared.enabled = enabled;+ expect((await request(app).get('/api/managed-visitors/v1/capabilities')).status).toBe(401);+ expect((await request(app).get('/api/managed-visitors/v1/capabilities').set('Authorization', 'Bearer owner-session')).status).toBe(401);+ expect((await request(app).get('/api/managed-visitors/v1/capabilities').set('Authorization', authHeader())).body.available).toBe(true);+ expect((await request(app).get('/api/managed-visitor-admin').set('Authorization', authHeader())).status).not.toBe(200);+ }+ expect((await request(app).get('/api/private').set('Authorization', authHeader())).status).toBe(401);+ expect((await request(app).get('/api/private').set('Authorization', 'Bearer owner-session')).status).toBe(200);+ expect(await readFile(join(directory, 'credentials.json'), 'utf8')).not.toContain(credentials.credential);+ expect(JSON.stringify(await shared.broker.listCredentials())).not.toMatch(/digest|mv1_/);+});+it('denies unsupported hosts and out-of-scope/private admission fields before any world mutation', async () => {+ host.capabilities.mockResolvedValue({ guestEntry: 1 });+ expect((await request(app).post('/api/managed-visitors/v1/admissions').set('Authorization', authHeader()).send(admission)).status).toBe(409);+ expect(host.admit).not.toHaveBeenCalled(); host.capabilities.mockResolvedValue({ managedVisitors: managedVisitorContract });+ for (const body of [{ ...admission, worldId: 'other-world' }, { ...admission, individualId: 'other-person' }, { ...admission, neuralState: [1] }]) {+ expect((await request(app).post('/api/managed-visitors/v1/admissions').set('Authorization', authHeader()).send(body)).status).toBeGreaterThanOrEqual(400);+ }+ expect(host.admit).not.toHaveBeenCalled();+});+it('starts paused and enforces observed scope, action sequence, epoch and expiration', async () => {+ const result = await request(app).post('/api/managed-visitors/v1/admissions').set('Authorization', authHeader()).send(admission);+ expect(result.status).toBe(200); const visit = result.body; expect(visit.status).toBe('paused'); expect(visit.sessionId).not.toBe('host-0');+ const path = `/api/managed-visitors/v1/sessions/${visit.sessionId}`;+ const observed = await request(app).post(`${path}/observations`).set('Authorization', authHeader()).send(scope(visit));+ expect(observed.body.rgb).toHaveLength(96); expect(observed.body.sessionId).toBe(visit.sessionId);+ const command = { ...scope(visit), sequence: 0, action: { type: 'start' } };+ expect((await request(app).post(`${path}/actions`).set('Authorization', authHeader()).send(command)).body.status).toBe('running');+ expect((await request(app).post(`${path}/actions`).set('Authorization', authHeader()).send(command)).status).toBe(409);+ expect((await request(app).post(`${path}/actions`).set('Authorization', authHeader()).send({ ...command, sequence: 1, epoch: 'other' })).status).toBe(403);+ expect(host.action).toHaveBeenCalledTimes(1); clock += 30001;+ expect((await request(app).post(`${path}/observations`).set('Authorization', authHeader()).send(scope(visit))).status).toBe(403);+});+it('rotation closes visits and rejects late admission authority issued for a revoked credential', async () => {+ const auth = await shared.broker.authenticate(credentials.credential), visit = await shared.broker.admit(auth, admission);+ await shared.broker.provision(appId, credentialInput);+ await expect(shared.broker.observe(auth, visit.sessionId, scope(visit))).rejects.toThrow(/revoked/); expect(host.leave).toHaveBeenCalledTimes(1);+ credentials = await shared.broker.provision(appId, credentialInput);+ const newAuth = await shared.broker.authenticate(credentials.credential); let release;+ delayed = new Promise(resolve => { release = resolve; }); const pending = shared.broker.admit(newAuth, admission);+ await vi.waitFor(() => expect(host.admit).toHaveBeenCalledTimes(2));+ await shared.broker.revoke(appId); release();+ await expect(pending).rejects.toThrow(/changed/); expect(host.leave).toHaveBeenCalledTimes(2);+});+it('denies cross-origin provisioning and nonloopback broker callers even without password auth', async () => {+ expect((await request(app).post(`/api/managed-visitor-admin/${appId}/credential`).set('Origin', 'https://unrelated.invalid').send(credentialInput)).status).toBe(403);+ const { authenticateManagedVisitorRequest } = await vi.importActual('../services/managedVisitors.js');+ await expect(authenticateManagedVisitorRequest({ socket: { remoteAddress: '192.0.2.1' }, headers: { authorization: authHeader() } }, shared.broker)).rejects.toThrow(/local/);+});+it('revokes malformed/private host outputs instead of forwarding or retrying uncertain operations', async () => {+ const auth = await shared.broker.authenticate(credentials.credential), visit = await shared.broker.admit(auth, admission);+ host.observe.mockImplementationOnce(async (id, body) => ({ version: 1, ...body, sessionId: id, neuralState: ['private'] }));+ await expect(shared.broker.observe(auth, visit.sessionId, scope(visit))).rejects.toThrow(/revoked/); expect(host.leave).toHaveBeenCalled();+ await expect(shared.broker.action(auth, visit.sessionId, { ...scope(visit), sequence: 0, action: { type: 'start' } })).rejects.toThrow(/scope/);+ expect(host.action).not.toHaveBeenCalled();+});++it('rejects duplicate host observation frames and invalidates the visitor rather than delivering a replay', async () => {+ const auth = await shared.broker.authenticate(credentials.credential), visit = await shared.broker.admit(auth, admission);+ await shared.broker.observe(auth, visit.sessionId, scope(visit));+ await expect(shared.broker.observe(auth, visit.sessionId, scope(visit))).rejects.toThrow(/revoked/);+ expect(host.leave).toHaveBeenCalledTimes(1);+});++it('rejects malformed negotiation shapes and cleans up malformed admission acknowledgements with original scope only', async () => {+ const auth = await shared.broker.authenticate(credentials.credential);+ for (const invalid of [{ ...managedVisitorContract, bodies: 'fly-v1' }, { ...managedVisitorContract, actions: 'start pause rest move leave' },+ { ...managedVisitorContract, bodies: {} }]) {+ host.capabilities.mockResolvedValue({ managedVisitors: invalid });+ expect((await shared.broker.capabilities(auth)).available).toBe(false);+ await expect(shared.broker.admit(auth, admission)).rejects.toThrow(/capability/);+ }+ expect(host.admit).not.toHaveBeenCalled(); host.capabilities.mockResolvedValue({ managedVisitors: managedVisitorContract });+ const normal = host.admit.getMockImplementation();+ host.admit.mockImplementationOnce(async body => ({ ...await normal(body), privateHistory: ['not forwarded'], individualId: 'other-person' }));+ await expect(shared.broker.admit(auth, admission)).rejects.toThrow(/invalid/);+ expect(host.leave).toHaveBeenCalledWith('host-0', { appId, individualId, individualSessionId, worldId, epoch: 'host-epoch' });+});++it('a backward broker clock revokes active authority even if wall time later recovers', async () => {+ const auth = await shared.broker.authenticate(credentials.credential), visit = await shared.broker.admit(auth, admission);+ clock -= 1; await expect(shared.broker.observe(auth, visit.sessionId, scope(visit))).rejects.toThrow(/clock/);+ clock += 1; await expect(shared.broker.observe(auth, visit.sessionId, scope(visit))).rejects.toThrow(/scope/);+ expect(host.leave).toHaveBeenCalledTimes(1);+});+it('revocation during a pending action discards its late response and admission latency cannot extend the broker deadline', async () => {+ const auth = await shared.broker.authenticate(credentials.credential), visit = await shared.broker.admit(auth, admission);+ let release; const normal = host.action.getMockImplementation();+ host.action.mockImplementationOnce(async (...args) => { await new Promise(resolve => { release = resolve; }); return normal(...args); });+ const action = shared.broker.action(auth, visit.sessionId, { ...scope(visit), sequence: 0, action: { type: 'start' } });+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ await shared.broker.revoke(appId); release(); await expect(action).rejects.toThrow(/revoked/);+ expect(host.leave).toHaveBeenCalled();+ credentials = await shared.broker.provision(appId, credentialInput);+ const current = await shared.broker.authenticate(credentials.credential), admitNormally = host.admit.getMockImplementation();+ host.admit.mockImplementationOnce(async body => { clock += 1001; return admitNormally(body); });+ await expect(shared.broker.admit(current, { ...admission, ttlMs: 1000 })).rejects.toThrow(/expired/);+});diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 17eb64167b..d28b9b2dd3 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -62,6 +62,13 @@ export const authGate = async (req, res, next) => {// one authoritative verifier, so leave a request-local, non-secret marker// instead of re-running password verification in each provider route.req.portosAuthContext = { enabled, authenticated: false, method: null };+ // App credentials authorize only this exact local broker namespace, whether+ // or not the optional instance password is configured. Never exempt its admin API.+ if (/^\/api\/managed-visitors\/v1(?:\/|$)/i.test(req.path)) {+ const { authenticateManagedVisitorRequest } = await import('./managedVisitors.js');+ req.managedVisitorAuth = await authenticateManagedVisitorRequest(req);+ return next();+ }if (!enabled) return next();// CSRF guard runs FIRST, before isPublicPath — public endpoints like// /api/auth/logout still mutate state (clear the cookie + revoke thediff --git a/server/services/managedVisitorBroker.js b/server/services/managedVisitorBroker.jsnew file mode 100644index 0000000000..8107180838--- /dev/null+++ b/server/services/managedVisitorBroker.js@@ -0,0 +1,169 @@+import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';+import { readFile, stat } from 'node:fs/promises';+import { dirname } from 'node:path';+import { atomicWrite, ensureDir } from '../lib/fileCore.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { ServerError } from '../lib/errorHandler.js';+import { visitorCredentialSchema, visitorAdmissionSchema, visitorScopeSchema, visitorActionSchema, visitorCredentialDocumentSchema,+ visitorHostAdmissionSchema, visitorHostObservationSchema, visitorHostActionSchema, visitorIdSchema } from '../lib/managedVisitorValidation.js';++const hash = token => createHash('sha256').update(token).digest('hex');+const fail = (message, status = 409) => new ServerError(message, { status, code: 'MANAGED_VISITOR_UNAVAILABLE' });+const scopeKeys = ['appId', 'individualId', 'individualSessionId', 'worldId', 'epoch'];+const publicCredential = ({ digest, ...record }) => record;+export const managedVisitorContract = Object.freeze({ version: 1, bodies: ['fly-v1'], controllerRaster: { width: 8, height: 4, channels: 3 },+ actions: ['start', 'pause', 'rest', 'move', 'leave'], expiryEnforced: true });+export function supportsManagedVisitors(capabilities) {+ const value = capabilities?.managedVisitors;+ return value?.version === 1 && value.expiryEnforced === true && Array.isArray(value.bodies) && value.bodies.every(v => typeof v === 'string')+ && value.bodies.includes('fly-v1') && Array.isArray(value.actions) && value.actions.every(v => typeof v === 'string')+ && value.controllerRaster?.width === 8 && value.controllerRaster?.height === 4 && value.controllerRaster?.channels === 3+ && managedVisitorContract.actions.every(action => value.actions?.includes(action));+}++/** Local credentials persist; ephemeral admissions do not survive broker restart.+ * No peer sync, AI provider, arbitrary host URL or private runtime payload is accepted. */+export function createManagedVisitorBroker({ path, getApp, host, now = Date.now }) {+ const queue = createFileWriteQueue(), sessions = new Map(), pendingAdmissions = new Set();+ const wallNow = now;+ let lastTime = wallNow();+ function time() {+ const current = wallNow();+ if (!Number.isSafeInteger(current) || current < lastTime) {+ for (const session of [...sessions.values()]) close(session).catch(() => null);+ sessions.clear();+ throw fail('Broker clock changed; visitor authority revoked.');+ }+ lastTime = current; return current;+ }+ const read = async () => {+ const metadata = await stat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (!metadata) return { schemaVersion: 1, credentials: [] };+ if (metadata.size > 65536) throw fail('Managed visitor credential store exceeds its bound.');+ const document = await readFile(path, 'utf8').then(JSON.parse).catch(() => { throw fail('Managed visitor credential store is unreadable.'); });+ const result = visitorCredentialDocumentSchema.safeParse(document);+ if (!result.success || new Set(result.data.credentials.map(c => c.appId)).size !== result.data.credentials.length) throw fail('Managed visitor credential store is incompatible.');+ return result.data;+ };+ async function write(document) {+ const text = JSON.stringify(visitorCredentialDocumentSchema.parse(document));+ if (Buffer.byteLength(text) > 65536) throw fail('Managed visitor credential capacity reached.');+ await ensureDir(dirname(path)); await atomicWrite(path, text);+ }+ async function app(id) { const value = await getApp(id); if (!value || value.archived) throw fail('Managed app is unavailable.', 403); }+ async function credential(auth) {+ await app(auth.appId);+ const current = (await read()).credentials.find(record => record.appId === auth.appId);+ if (!current || current.digest !== auth.digest || current.expiresAt <= time()) throw fail('Managed app credential expired or revoked.', 401);+ return current;+ }+ async function authenticate(token) {+ if (typeof token !== 'string' || !/^mv1_[a-f0-9]{64}$/.test(token)) throw fail('Managed app credential required.', 401);+ const digest = hash(token), record = (await read()).credentials.find(record => timingSafeEqual(Buffer.from(record.digest, 'hex'), Buffer.from(digest, 'hex')));+ if (!record) throw fail('Managed app credential required.', 401);+ const auth = { appId: record.appId, digest }; await credential(auth); return auth;+ }+ async function close(session) {+ sessions.delete(session.id);+ // Local authority is gone even if the host is disconnected; negotiated host expiry is the backstop.+ await host.leave(session.hostId, session.scope).catch(() => null);+ }+ async function revokeSessions(appId) { await Promise.all([...sessions.values()].filter(s => s.scope.appId === appId).map(close)); }+ async function provision(appId, input) {+ const value = visitorCredentialSchema.parse(input); await app(appId);+ return queue(async () => {+ const document = await read(), token = `mv1_${randomBytes(32).toString('hex')}`;+ const record = { appId, digest: hash(token), individualIds: [...new Set(value.individualIds)], worldIds: [...new Set(value.worldIds)], createdAt: time(), expiresAt: time() + value.ttlMs };+ document.credentials = document.credentials.filter(record => record.appId !== appId);+ if (document.credentials.length >= 64) throw fail('Managed credential capacity reached.');+ document.credentials.push(record); await write(document);+ await revokeSessions(appId); return { ...publicCredential(record), credential: token };+ });+ }+ async function revoke(appId) {+ return queue(async () => {+ const document = await read(); document.credentials = document.credentials.filter(record => record.appId !== appId);+ await write(document); await revokeSessions(appId); return { revoked: true };+ });+ }+ async function capabilities(auth) {+ const c = await credential(auth), capability = await host.capabilities();+ return { version: 1, available: supportsManagedVisitors(capability), appId: auth.appId, worldIds: c.worldIds, individualIds: c.individualIds,+ contract: managedVisitorContract, reason: supportsManagedVisitors(capability) ? null : 'Managed host has not negotiated the nonhumanoid visitor contract.' };+ }+ function validateResult(schema, result, expected) {+ const parsed = schema.safeParse(result);+ if (!parsed.success || scopeKeys.some(key => parsed.data[key] !== expected[key])) throw fail('Host response does not match the scoped visitor contract.');+ return parsed.data;+ }+ async function admit(auth, input) {+ const value = visitorAdmissionSchema.parse(input), c = await credential(auth);+ if (!c.individualIds.includes(value.individualId) || !c.worldIds.includes(value.worldId)) throw fail('Visitor is outside the owner-approved app scope.', 403);+ if (!supportsManagedVisitors(await host.capabilities())) throw fail('Managed host lacks the required nonhumanoid capability.');+ const key = JSON.stringify([auth.appId, value.individualId]);+ for (const session of [...sessions.values()]) if (session.expiresAt <= time()) await close(session);+ if (sessions.size + pendingAdmissions.size >= 64 || pendingAdmissions.has(key) || [...sessions.values()].some(s => s.key === key)) throw fail('Individual already visiting or admission capacity reached.');+ pendingAdmissions.add(key);+ let candidate = null;+ return (async () => {+ const begin = time(), ttlMs = Math.min(value.ttlMs, c.expiresAt - begin);+ if (ttlMs < 1000) throw fail('Credential expires too soon for admission.');+ const response = await host.admit({ version: 1, appId: auth.appId, ...value, ttlMs });+ const parsed = visitorHostAdmissionSchema.safeParse(response);+ const scope = { appId: auth.appId, individualId: value.individualId, individualSessionId: value.individualSessionId, worldId: value.worldId, epoch: response?.epoch };+ if (!parsed.success || scopeKeys.some(key => parsed.data[key] !== scope[key])) {+ // A malformed acknowledgement may still represent a live admission. Clean up+ // only using the request's original identity/world and syntactically valid lease keys.+ if (visitorIdSchema.safeParse(response?.sessionId).success && visitorIdSchema.safeParse(response?.epoch).success) {+ await host.leave(response.sessionId, scope).catch(() => null);+ }+ throw fail('Host returned an invalid scoped admission.');+ }+ const result = parsed.data;+ const session = { id: randomUUID(), hostId: result.sessionId, scope, key, digest: auth.digest, expiresAt: result.expiresAt, hostExpiresAt: result.expiresAt, sequence: -1, frameId: -1, pending: false };+ candidate = session;+ session.expiresAt = Math.min(result.expiresAt, begin + ttlMs);+ const valid = session.expiresAt > time() && result.expiresAt <= time() + ttlMs;+ // Rotation while an admission is pending must not publish fresh authority from the old credential.+ const current = await credential(auth).then(() => true, () => false);+ if (!valid || !current) throw fail('Admission expired or credential changed during negotiation.');+ sessions.set(session.id, session);+ return { ...result, sessionId: session.id, expiresAt: session.expiresAt };+ })().catch(async error => { if (candidate) await close(candidate); throw error; })+ .finally(() => pendingAdmissions.delete(key));+ }+ async function sessionFor(auth, id, input) {+ await credential(auth);+ const session = sessions.get(id);+ if (!session || session.digest !== auth.digest || session.expiresAt <= time() || scopeKeys.some(key => (key === 'appId' ? auth.appId : input[key]) !== session.scope[key])) throw fail('Visitor session scope, epoch or expiry mismatch.', 403);+ if (session.pending) throw fail('A visitor operation is already pending.');+ return session;+ }+ async function operate(auth, id, input, observation) {+ const request = (observation ? visitorScopeSchema : visitorActionSchema).parse(input), session = await sessionFor(auth, id, request);+ if (!observation && request.sequence !== session.sequence + 1) throw fail('Visitor action sequence is stale or out of order.');+ session.pending = true;+ return (async () => {+ const reply = await (observation ? host.observe(session.hostId, session.scope) : host.action(session.hostId, { ...session.scope, sequence: request.sequence, action: request.action }));+ const stillValid = await credential(auth).then(() => true, () => false);+ if (!stillValid || sessions.get(id) !== session || session.expiresAt <= time()) throw fail('Visitor authority changed while the host operation was pending.');+ const result = validateResult(observation ? visitorHostObservationSchema : visitorHostActionSchema, reply, session.scope);+ if (result.sessionId !== session.hostId) throw fail('Host session mismatch.');+ if (observation) {+ if (result.frameId <= session.frameId || result.capturedAtMs > time() || time() - result.capturedAtMs > 250) throw fail('Host observation is stale or future-dated.');+ session.frameId = result.frameId;+ } else {+ const expected = { start: 'running', pause: 'paused', rest: 'resting', move: 'running', leave: 'left' }[request.action.type];+ if (result.sequence !== request.sequence || result.status !== expected || result.expiresAt !== session.hostExpiresAt) throw fail('Host action sequence/status mismatch.');+ session.sequence = result.sequence;+ if (request.action.type === 'leave') sessions.delete(id);+ }+ return { ...result, sessionId: id, ...(observation ? {} : { expiresAt: session.expiresAt }) };+ })().catch(async () => { await close(session); throw fail('Host operation unavailable or inconsistent; visitor authority revoked.'); })+ .finally(() => { session.pending = false; });+ }++ return { authenticate, provision, revoke, capabilities, admit,+ listCredentials: async () => (await read()).credentials.map(publicCredential),+ observe: (auth, id, input) => operate(auth, id, input, true), action: (auth, id, input) => operate(auth, id, input, false) };+}diff --git a/server/services/managedVisitorHost.js b/server/services/managedVisitorHost.jsnew file mode 100644index 0000000000..adfdd744bd--- /dev/null+++ b/server/services/managedVisitorHost.js@@ -0,0 +1,33 @@+import { ServerError } from '../lib/errorHandler.js';++/** Explicitly configured local host only; construction and disabled capability reads make no requests. */+export function createManagedVisitorHost({ token = process.env.PORTOS_EIDOVERSE_VISITOR_TOKEN, fetchImpl = fetch, port = 8940 } = {}) {+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new ServerError('Invalid managed visitor host port.', { status: 400 });+ const enabled = typeof token === 'string' && /^[a-f0-9]{64}$/.test(token);+ async function request(path, body) {+ if (!enabled) throw new ServerError('Managed visitor host credential is not configured.', { status: 409 });+ const response = await fetchImpl(`http://127.0.0.1:${port}/api/managed-visitors/v1${path}`, {+ method: body === undefined ? 'GET' : 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: 'error', signal: AbortSignal.timeout(3000),+ });+ if (!response.ok) throw new ServerError('Managed visitor host refused the operation.', { status: 409 });+ const reader = response.body?.getReader();+ if (!reader) throw new ServerError('Managed visitor host response is unavailable.', { status: 409 });+ const chunks = []; let bytes = 0;+ for (;;) {+ const part = await reader.read(); if (part.done) break;+ bytes += part.value.byteLength;+ if (bytes > 16384) { await reader.cancel(); throw new ServerError('Managed visitor host response exceeds its bound.', { status: 409 }); }+ chunks.push(Buffer.from(part.value));+ }+ return Promise.resolve(Buffer.concat(chunks).toString('utf8')).then(JSON.parse)+ .catch(() => { throw new ServerError('Managed visitor host returned invalid JSON.', { status: 409 }); });+ }+ return {+ capabilities: () => enabled ? request('/version').then(value => value.capabilities, () => null) : Promise.resolve(null),+ admit: body => request('/admissions', body),+ observe: (id, body) => request(`/sessions/${encodeURIComponent(id)}/observations`, body),+ leave: (id, body) => request(`/sessions/${encodeURIComponent(id)}/leave`, body),+ action: (id, body) => request(`/sessions/${encodeURIComponent(id)}/actions`, body),+ };+}diff --git a/server/services/managedVisitorHost.test.js b/server/services/managedVisitorHost.test.jsnew file mode 100644index 0000000000..0ac417fd42--- /dev/null+++ b/server/services/managedVisitorHost.test.js@@ -0,0 +1,20 @@+import { expect, it, vi } from 'vitest';+import { createManagedVisitorHost } from './managedVisitorHost.js';+it('disabled transport makes no requests and explicit configuration keeps host credentials on the fixed loopback namespace', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ capabilities: { managedVisitors: null } })));+ const disabled = createManagedVisitorHost({ token: '', fetchImpl });+ expect(await disabled.capabilities()).toBe(null); await expect(disabled.admit({})).rejects.toThrow(/not configured/);+ expect(fetchImpl).not.toHaveBeenCalled();+ const token = 'a'.repeat(64), host = createManagedVisitorHost({ token, fetchImpl }); await host.capabilities();+ const [url, options] = fetchImpl.mock.calls[0];+ expect(url).toBe('http://127.0.0.1:8940/api/managed-visitors/v1/version');+ expect(options.headers.Authorization).toBe(`Bearer ${token}`); expect(options.redirect).toBe('error'); expect(options.signal).toBeInstanceOf(AbortSignal);+});+it('host response buffering is bounded and malformed/non-success replies do not become capabilities', async () => {+ let canceled = false;+ const fetchImpl = vi.fn(async () => new Response(new ReadableStream({ pull(controller) { controller.enqueue(new Uint8Array(17000)); }, cancel() { canceled = true; } })));+ const host = createManagedVisitorHost({ token: 'a'.repeat(64), fetchImpl });+ await expect(host.observe('session', {})).rejects.toThrow(/bound/); expect(canceled).toBe(true);+ fetchImpl.mockResolvedValueOnce(new Response('not json')); expect(await host.capabilities()).toBe(null);+ fetchImpl.mockResolvedValueOnce(new Response('{}', { status: 401 })); await expect(host.admit({})).rejects.toThrow(/refused/);+});diff --git a/server/services/managedVisitors.js b/server/services/managedVisitors.jsnew file mode 100644index 0000000000..7289ae9772--- /dev/null+++ b/server/services/managedVisitors.js@@ -0,0 +1,19 @@+import { dataPath } from '../lib/paths.js';+import { createManagedVisitorBroker } from './managedVisitorBroker.js';+import { createManagedVisitorHost } from './managedVisitorHost.js';+import { ServerError } from '../lib/errorHandler.js';+import { isCrossOrigin } from '../../lib/portosAuthCore.js';++let broker;+export function getManagedVisitorBroker() {+ broker ??= createManagedVisitorBroker({ path: dataPath('managed-visitor-credentials.json'),+ getApp: async id => (await import('./apps.js')).getAppById(id), host: createManagedVisitorHost() });+ return broker;+}+export async function authenticateManagedVisitorRequest(req, broker = getManagedVisitorBroker()) {+ if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket?.remoteAddress) || isCrossOrigin(req)) {+ throw new ServerError('Managed visitor API requires a local same-origin caller.', { status: 403 });+ }+ const match = /^Bearer (mv1_[a-f0-9]{64})$/i.exec(req.headers.authorization ?? '');+ return broker.authenticate(match?.[1]);+}