wishforge-ide/apps/ide/collaboration/test/isolated-oct.test.mjs
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

282 lines
11 KiB
JavaScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { randomUUID, webcrypto } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
import { createGateway } from '../../gateway/server.mjs';
import factory from '../client-factory.cjs';
const require = createRequire(new URL('../../package.json', import.meta.url));
const protocol = await import(pathToFileURL(require.resolve('open-collaboration-protocol')).href);
const { io } = await import(pathToFileURL(require.resolve('socket.io-client')).href);
const { OpenCollaborationYjsProvider } = await import(pathToFileURL(require.resolve('open-collaboration-yjs')).href);
const Y = await import('../../node_modules/yjs/dist/yjs.mjs');
const { Awareness } = await import('../../node_modules/y-protocols/awareness.js');
protocol.initializeProtocol({ cryptoModule: webcrypto });
const execute = promisify(execFile);
const docker = (...args) =>
execute('docker', ['--context', process.env.WF_TEST_DOCKER_CONTEXT ?? 'colima', ...args], { timeout: 30_000 });
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(check, message) {
const end = Date.now() + 10_000;
do {
if (await check()) return;
await sleep(25);
} while (Date.now() < end);
throw new Error(message);
}
async function listen(server) {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return `http://127.0.0.1:${server.address().port}`;
}
test(
'two isolated OCT instances support scoped Socket.IO/Yjs collaboration and reject invite/token reuse across workspaces',
{ skip: process.env.WF_OCT_INTEGRATION !== '1', timeout: 60_000 },
async () => {
const names = [],
connections = [],
docs = [],
awareness = [],
sockets = [];
let api, gateway;
const revoked = new Set();
const members = {
alice: { workspace: 'workspace-a', role: 'developer' },
bob: { workspace: 'workspace-a', role: 'developer' },
charlie: { workspace: 'workspace-b', role: 'developer' },
viewer: { workspace: 'workspace-a', role: 'viewer' },
};
try {
const origins = {};
for (const workspace of ['workspace-a', 'workspace-b']) {
const name = `wishforge-oct-test-${randomUUID().slice(0, 8)}`;
names.push(name);
await docker(
'run',
'-d',
'--rm',
'--name',
name,
'--read-only',
'--cap-drop',
'ALL',
'--security-opt',
'no-new-privileges',
'--tmpfs',
'/tmp:rw,noexec,nosuid,size=16m',
'-p',
'127.0.0.1::8100',
'-e',
`WF_WORKSPACE_ID=${workspace}`,
'-e',
'WF_TENANT_ID=fixture-tenant',
'-e',
'WISHFORGE_GATEWAY_ENFORCED=true',
'wishforge/oct-workspace:0.3.1-wf1',
);
const port = (await docker('port', name, '8100/tcp')).stdout.trim().split(':').at(-1);
origins[workspace] = `http://127.0.0.1:${port}`;
await until(async () => {
try {
return (await fetch(`${origins[workspace]}/api/meta`)).ok;
} catch {
return false;
}
}, 'OCT did not start');
}
api = http.createServer(async (req, res) => {
let text = '';
for await (const bytes of req) text += bytes;
const request = JSON.parse(text),
who = members[request.userToken],
workspace = req.url.split('/')[3];
if (!who || revoked.has(request.userToken) || who.workspace !== workspace) {
res.writeHead(403);
res.end();
return;
}
assert.equal(request.operation, 'edit');
res.setHeader('content-type', 'application/json');
res.end(
JSON.stringify({
data: {
tenantId: 'fixture-tenant',
projectId: `project-${workspace}`,
workspaceId: workspace,
role: who.role,
upstreamUrl: origins[workspace],
collaborationUpstreamUrl: origins[workspace],
},
}),
);
});
const apiOrigin = await listen(api);
// Reserve a local port before gateway construction, which requires its public origin.
const reserve = http.createServer();
const publicUrl = await listen(reserve);
await new Promise(resolve => reserve.close(resolve));
gateway = createGateway({
publicUrl,
tenantId: 'fixture-tenant',
serviceToken: 'gateway-fixture-token',
apiOrigin,
allowedUpstreamOrigins: Object.values(origins),
allowedCollaborationOrigins: Object.values(origins),
reauthorizeMs: 50,
});
await new Promise(resolve => gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1', resolve));
async function session(user) {
const workspace = members[user].workspace;
const launch = await fetch(`${publicUrl}/launch`, {
method: 'POST',
headers: { authorization: `Bearer ${user}`, 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId: workspace }),
});
if (!launch.ok) return { status: launch.status };
const { launchUrl } = await launch.json();
const response = await fetch(launchUrl, { redirect: 'manual' });
return { status: response.status, cookie: response.headers.get('set-cookie').split(';')[0], workspace };
}
const alice = await session('alice'),
bob = await session('bob'),
charlie = await session('charlie');
assert.equal((await session('viewer')).status, 403);
function client(user, displayName) {
const url = `${publicUrl}/workspaces/${user.workspace}/collaboration/`;
const localFetch = (target, init = {}) =>
fetch(target, { ...init, headers: { ...init.headers, cookie: user.cookie, origin: publicUrl } });
return factory.createPrefixConnectionProvider(
{
...protocol,
io: (origin, options) => {
const socket = io(origin, {
...options,
withCredentials: false,
extraHeaders: { ...options.extraHeaders, Cookie: user.cookie, Origin: publicUrl },
});
sockets.push(socket);
socket.on('connect_error', error =>
console.error(
'OCT socket connection error:',
error.message,
error.description,
error.context?.status,
error.context?.responseText?.slice(0, 300),
),
);
return socket;
},
},
{
url,
browserLocation: `${publicUrl}/workspaces/${user.workspace}/`,
client: 'WishForge integration',
fetch: localFetch,
authenticationHandler: async (token, metadata) => {
assert.equal(metadata.providers[0].endpoint, 'api/login/simple');
return (
await localFetch(new URL(metadata.providers[0].endpoint, url), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token, user: displayName }),
})
).ok;
},
},
);
}
const hostProvider = client(alice, 'Host display name'),
guestProvider = client(bob, 'Guest display name');
const claim = await hostProvider.createRoom({ abortSignal: AbortSignal.timeout(10_000) });
const host = await hostProvider.connect(claim.roomToken);
connections.push(host);
let hostIdentity;
host.peer.onInfo((_origin, peer) => {
hostIdentity = peer;
});
host.peer.onJoinRequest(async () => ({ workspace: { name: 'fixture', folders: ['source'] } }));
host.room.onJoin((_origin, peer) =>
host.peer.init(peer.id, {
protocol: protocol.VERSION,
host: hostIdentity,
guests: [peer],
permissions: { readonly: false },
capabilities: {},
workspace: { name: 'fixture', folders: ['source'] },
}),
);
await until(() => !!hostIdentity, 'Host peer did not connect');
const guestClaim = await guestProvider.joinRoom({
roomId: claim.roomId,
abortSignal: AbortSignal.timeout(10_000),
});
const guest = await guestProvider.connect(guestClaim.roomToken, guestClaim.host);
connections.push(guest);
guest.peer.onInfo(() => {});
let initialized = false;
guest.peer.onInit(() => {
initialized = true;
});
await until(() => initialized, 'Guest did not receive encrypted initialization');
for (const connection of [host, guest]) {
const doc = new Y.Doc();
const state = new Awareness(doc);
docs.push(doc);
awareness.push(state);
const provider = new OpenCollaborationYjsProvider(connection, doc, state);
provider.connect();
}
docs[0].getText('source/example.ts').insert(0, 'const greeting = "hello";');
await until(
() => docs[1].getText('source/example.ts').toString().includes('hello'),
'Host edit did not reach guest',
);
docs[1].getText('source/example.ts').insert(docs[1].getText('source/example.ts').length, '\n// guest edit');
await until(
() => docs[0].getText('source/example.ts').toString().includes('guest edit'),
'Guest edit did not reach host',
);
assert.equal(docs[0].getText('source/example.ts').toString(), docs[1].getText('source/example.ts').toString());
assert.equal(
(
await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, {
headers: { cookie: charlie.cookie },
})
).status,
401,
);
const outsider = client(charlie, 'Allowed in other workspace');
await assert.rejects(
() => outsider.joinRoom({ roomId: claim.roomId, abortSignal: AbortSignal.timeout(5_000) }),
/Room not found/,
);
const tokenCheck = await fetch(`${origins['workspace-b']}/api/login/validate`, {
method: 'POST',
headers: { 'x-oct-jwt': hostProvider.authToken },
});
assert.equal((await tokenCheck.json()).valid, false, 'Per-instance keys must reject another workspace OCT JWT');
revoked.add('bob');
await until(() => sockets[1].disconnected, 'Revoked member websocket was not closed');
assert.equal(
(await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, { headers: { cookie: bob.cookie } }))
.status,
403,
);
} catch (error) {
for (const name of names) console.error((await docker('logs', '--tail', '15', name)).stdout);
throw error;
} finally {
for (const state of awareness) state.destroy();
for (const doc of docs) doc.destroy();
for (const connection of connections) connection.dispose();
for (const socket of sockets) socket.disconnect();
if (gateway) await gateway.close();
if (api) await new Promise(resolve => api.close(resolve));
await Promise.all(names.map(name => docker('stop', '-t', '1', name).catch(() => undefined)));
}
},
);