mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless Channels, Task Queues, Interactions, and SSE event streams are exposed through `paperclipai/sdk` so scripts and tools can coordinate agents without full board ceremony. > - Developers who want to build a custom minimal web interface over Paperclip Channels have no standalone runnable example to inspect or copy. > - Putting experimental example viewers into `ui/` would add maintenance load to the permanent React board UI instead of proving that external callers can build on the public SDK. > - This pull request adds an experimental, zero-dependency Channels and Activity web viewer binary under `tools/experimental/channels-viewer/` built strictly on `paperclipai/sdk`. > - The benefit is a clean reference implementation that connects to local or authenticated Paperclip servers, streams live updates over SSE, and keeps the main `ui/` bundle untouched. ## Linked Issues or Issue Description Refs #23329 Refs #23330 **Problem or motivation** Developers can post to channels, claim tasks, and stream events from the CLI or `paperclipai/sdk`, but there is no minimal runnable example showing how to build a custom web UI over those headless APIs with standard Paperclip authentication. **Proposed solution** Add a standalone experimental viewer binary at `tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs` backed by `node:http`, `paperclipai/sdk`, and zero-bundler ES modules. The viewer defaults to Paperclip's dark control-plane surface (`data-theme="dark"` with an optional Light mode switch in Settings), pairing sans-serif prose with monospace machine values (`DEM-1`, `#channel`, `key=value`, relative timestamps) and CSP-safe agent capsule avatars across an `Activity` feed, per-channel thread views, a `Task Queue` inspector, and a right-hand `Thread` pane with `kv_labels` editing, `approve`/`reject` confirmations, live SSE updates, and `--as` profile switching. **Alternatives considered** Adding a minimal channels layout directly inside `ui/` was rejected because this viewer is an experimental SDK integration example rather than a permanent core UI surface. Adding a frontend bundler or framework dependency under `tools/` was also rejected so the example runs directly on Node with zero extra packages. **Roadmap alignment** Builds directly on the headless coordination and SDK surface introduced in #23329 and #23330 without overlapping or altering planned core `ui/` work. ## What Changed - Added `tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs` with `--port`, `--host`, `--allow-remote`, `--remote-token`, `--allow-host`, `--api-base`, `--company`, `--as`, `--open`, and `--help` flags plus a startup status banner. - Added `tools/experimental/channels-viewer/src/server.mjs`, `src/viewer-data.mjs`, `src/auth.mjs`, `src/security.mjs`, and `src/format.mjs` to resolve Paperclip context/credentials via `paperclipai/sdk` (preserving untrusted repo-local endpoint guards), expose `/viewer-api/*` JSON and SSE proxy endpoints, and enforce loopback/remote-token binding, Host/DNS-rebinding guards, Origin checks, strict CSP headers, and timing-safe CSRF token validation. - Added zero-dependency ES module frontend files (`src/public/index.html`, `styles.css`, `overlays.css`, `app.js`, `render.js`, `dom-helpers.js`) styled with Paperclip's dark control-plane tokens (`data-theme="dark"` default + Light mode toggle), sans/mono typography hierarchy, status dots, and CSP-safe capsule avatars using safe DOM construction (`textContent`). - Added `tools/experimental/channels-viewer/README.md` and a brief reference section in `doc/HEADLESS-TUTORIALS.md`. - Excluded `tools/experimental` in `.dockerignore` so production Docker build contexts remain slim. - Added `tools/experimental/channels-viewer/test/channels-viewer.test.mjs` (`node:test`) and `server/src/__tests__/experimental-channels-viewer.test.ts` (Vitest full-stack E2E with Express, embedded PostgreSQL, and live SSE). ## Verification - Ran `node --test tools/experimental/channels-viewer/test/channels-viewer.test.mjs` (4/4 tests passed). - Ran `pnpm --filter @paperclipai/server typecheck` (passed across all server and test layers). - Ran `pnpm --filter @paperclipai/server exec vitest run src/__tests__/experimental-channels-viewer.test.ts` (3/3 tests passed, covering loopback/remote-token/Host/CSRF/strict-CSP protections, dark-mode `data-theme="dark"` default with zero inline styles, cross-source profile isolation, live SSE `board_event` delivery + `Last-Event-ID` precedence, interleaved channel activity, `kv_labels`, queued tasks, `approve`/`reject` interactions, and instant SSE-aware `viewer.close()`). - Ran `node scripts/check-module-boundaries.mjs`, `node scripts/check-test-budget.mjs --base origin/master`, `node scripts/check-docker-deps-stage.mjs`, and `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` (all passed). ## Risks - Low risk to core Paperclip runtime and builds: no files under `ui/`, `server/src/routes/`, `packages/db/`, or `packages/shared/` were modified, and `tools/experimental` is excluded from Docker build contexts via `.dockerignore`. - Local browser-to-localhost security is hardened by default loopback binding (`127.0.0.1`), strict `Host` and `Origin` checks, immutable startup `apiBase`, zero bearer-token serialization to the browser, and timing-safe CSRF headers on all mutating `/viewer-api/*` endpoints. ## Model Used - Anthropic Claude Opus 4.6 (`claude-opus-4-6`) with extended thinking, code execution, and tool use in Antigravity. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
628 lines
23 KiB
JavaScript
628 lines
23 KiB
JavaScript
import { randomBytes } from "node:crypto";
|
|
import { readFile } from "node:fs/promises";
|
|
import { createServer } from "node:http";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import {
|
|
createPinnedPaperclipClient,
|
|
discoverLocalViewerAuth,
|
|
loadPaperclipSdk,
|
|
toSdkSafeProfileKey,
|
|
} from "./auth.mjs";
|
|
import {
|
|
formatIssueBody,
|
|
resolveSpeakerLabel,
|
|
stripRedundantSchemaFences,
|
|
} from "./format.mjs";
|
|
import {
|
|
CSP_HEADER,
|
|
isAllowedViewerHost,
|
|
isLoopbackHost,
|
|
MIN_REMOTE_TOKEN_LENGTH,
|
|
readJsonBody,
|
|
sendJson,
|
|
serializeError,
|
|
validateViewerRequestSecurity,
|
|
verifyRemoteAccessToken,
|
|
} from "./security.mjs";
|
|
import { createViewerDataStore, normalizeLabelMutationBody } from "./viewer-data.mjs";
|
|
|
|
export {
|
|
createPinnedPaperclipClient,
|
|
discoverLocalViewerAuth,
|
|
formatIssueBody,
|
|
isAllowedViewerHost,
|
|
isLoopbackHost,
|
|
loadPaperclipSdk,
|
|
normalizeLabelMutationBody,
|
|
resolveSpeakerLabel,
|
|
stripRedundantSchemaFences,
|
|
toSdkSafeProfileKey,
|
|
};
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const PUBLIC_DIR = path.join(__dirname, "public");
|
|
|
|
const STATIC_ASSETS = new Map([
|
|
["/", { file: "index.html", contentType: "text/html; charset=utf-8", isHtml: true }],
|
|
["/index.html", { file: "index.html", contentType: "text/html; charset=utf-8", isHtml: true }],
|
|
["/styles.css", { file: "styles.css", contentType: "text/css; charset=utf-8", isHtml: false }],
|
|
["/overlays.css", { file: "overlays.css", contentType: "text/css; charset=utf-8", isHtml: false }],
|
|
["/app.js", { file: "app.js", contentType: "text/javascript; charset=utf-8", isHtml: false }],
|
|
["/render.js", { file: "render.js", contentType: "text/javascript; charset=utf-8", isHtml: false }],
|
|
[
|
|
"/dom-helpers.js",
|
|
{ file: "dom-helpers.js", contentType: "text/javascript; charset=utf-8", isHtml: false },
|
|
],
|
|
]);
|
|
|
|
function buildApiRoutes(store) {
|
|
return [
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/session$/,
|
|
handler: async ({ reqUrl }) => ({ status: 200, body: await store.buildSessionPayload(reqUrl) }),
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/session$/,
|
|
handler: async ({ req, reqUrl }) => {
|
|
const body = await readJsonBody(req);
|
|
if ("apiBase" in body || "apiKey" in body) {
|
|
return {
|
|
status: 400,
|
|
body: {
|
|
code: "immutable_endpoint",
|
|
message:
|
|
"apiBase and credentials cannot be mutated over HTTP. Restart paperclip-channels-viewer with --api-base to change servers.",
|
|
},
|
|
};
|
|
}
|
|
store.updateSession({
|
|
...(Object.hasOwn(body, "profile") ? { profile: body.profile } : {}),
|
|
...(Object.hasOwn(body, "company") ? { company: body.company } : {}),
|
|
});
|
|
return { status: 200, body: await store.buildSessionPayload(reqUrl) };
|
|
},
|
|
},
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/channels$/,
|
|
handler: async ({ client, reqUrl }) => {
|
|
const prefix = reqUrl.searchParams.get("prefix")?.trim() || undefined;
|
|
return { status: 200, body: { items: await client.channels.list(prefix) } };
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/channels$/,
|
|
handler: async ({ req, client }) => {
|
|
const body = await readJsonBody(req);
|
|
const channelPath = typeof body.path === "string" ? body.path.trim() : "";
|
|
if (!channelPath) {
|
|
return { status: 400, body: { code: "validation_error", message: "Channel path is required." } };
|
|
}
|
|
const channel = await client.channels.ensure(channelPath, {
|
|
...(typeof body.description === "string" ? { description: body.description } : {}),
|
|
...(body.visibility === "open" || body.visibility === "private"
|
|
? { visibility: body.visibility }
|
|
: {}),
|
|
});
|
|
return { status: 200, body: { channel } };
|
|
},
|
|
},
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/activity$/,
|
|
handler: async ({ client, reqUrl, scopeKey }) => {
|
|
const labels = reqUrl.searchParams.getAll("label").map((s) => s.trim()).filter(Boolean);
|
|
const rawLimit = Number.parseInt(reqUrl.searchParams.get("limit") || "60", 10);
|
|
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 150) : 60;
|
|
return { status: 200, body: await store.buildActivityFeed(client, { labels, limit, scopeKey }) };
|
|
},
|
|
},
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/channels\/threads$/,
|
|
handler: async ({ client, reqUrl }) => {
|
|
const channel = reqUrl.searchParams.get("channel")?.trim() || "";
|
|
if (!channel) {
|
|
return {
|
|
status: 400,
|
|
body: { code: "validation_error", message: "Query parameter 'channel' is required." },
|
|
};
|
|
}
|
|
const labels = reqUrl.searchParams.getAll("label").map((s) => s.trim()).filter(Boolean);
|
|
const statuses = reqUrl.searchParams.getAll("status").map((s) => s.trim()).filter(Boolean);
|
|
const rawLimit = Number.parseInt(reqUrl.searchParams.get("limit") || "50", 10);
|
|
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 100) : 50;
|
|
const page = await client.read(channel, {
|
|
...(labels.length > 0 ? { label: labels } : {}),
|
|
...(statuses.length > 0 ? { status: statuses } : {}),
|
|
limit,
|
|
});
|
|
const items = Array.isArray(page.items)
|
|
? [...page.items]
|
|
.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))
|
|
.map((item) => ({
|
|
...item,
|
|
speaker: resolveSpeakerLabel(item.actorProfile, null, item.assigneeAgentId),
|
|
formattedBody: formatIssueBody(item),
|
|
}))
|
|
: [];
|
|
return {
|
|
status: 200,
|
|
body: { kind: "channel", channel: page.channel ?? channel, items, cursor: page.cursor },
|
|
};
|
|
},
|
|
},
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/threads\/([^/]+)$/,
|
|
handler: async ({ client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
const detail = await store.readScopedThread(client, rawId, scopeKey);
|
|
const issue = detail.issue;
|
|
const comments = (detail.comments ?? [])
|
|
.filter((c) => !c.internal)
|
|
.map((c) => ({
|
|
...c,
|
|
speaker: resolveSpeakerLabel(
|
|
c.actorProfile,
|
|
c.authorType,
|
|
c.authorAgentId,
|
|
c.authorUserId,
|
|
),
|
|
formattedBody: stripRedundantSchemaFences(c.body, c.blocks),
|
|
}));
|
|
return {
|
|
status: 200,
|
|
body: {
|
|
kind: "thread",
|
|
issue: {
|
|
...issue,
|
|
speaker: resolveSpeakerLabel(issue.actorProfile, null, issue.assigneeAgentId),
|
|
formattedBody: formatIssueBody(issue),
|
|
},
|
|
comments,
|
|
interactions: detail.interactions ?? [],
|
|
cursor: detail.cursor,
|
|
},
|
|
};
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/posts$/,
|
|
handler: async ({ req, client }) => {
|
|
const body = await readJsonBody(req);
|
|
const channel = typeof body.channel === "string" ? body.channel.trim() : "";
|
|
if (!channel) {
|
|
return { status: 400, body: { code: "validation_error", message: "Channel is required." } };
|
|
}
|
|
const issue = await client.post(channel, {
|
|
...(typeof body.text === "string" ? { text: body.text } : {}),
|
|
...(typeof body.title === "string" ? { title: body.title } : {}),
|
|
...(typeof body.description === "string" ? { description: body.description } : {}),
|
|
...(body.labels && typeof body.labels === "object" ? { labels: body.labels } : {}),
|
|
...(body.schema && typeof body.schema === "object" ? { schema: body.schema } : {}),
|
|
...(Array.isArray(body.blocks) ? { blocks: body.blocks } : {}),
|
|
});
|
|
store.invalidateThreadCache(issue.id);
|
|
return { status: 201, body: { issue } };
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/threads\/([^/]+)\/replies$/,
|
|
handler: async ({ req, client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
await store.readScopedThread(client, rawId, scopeKey);
|
|
const body = await readJsonBody(req);
|
|
const comment = await client.reply(rawId, {
|
|
body:
|
|
typeof body.body === "string"
|
|
? body.body
|
|
: typeof body.text === "string"
|
|
? body.text
|
|
: "",
|
|
...(body.labels && typeof body.labels === "object" ? { labels: body.labels } : {}),
|
|
...(body.schema && typeof body.schema === "object" ? { schema: body.schema } : {}),
|
|
...(Array.isArray(body.blocks) ? { blocks: body.blocks } : {}),
|
|
...(typeof body.after === "string" && body.after.trim() ? { after: body.after.trim() } : {}),
|
|
});
|
|
store.invalidateThreadCache(rawId);
|
|
return { status: 201, body: { comment } };
|
|
},
|
|
},
|
|
{
|
|
method: "PATCH",
|
|
pattern: /^\/viewer-api\/threads\/([^/]+)\/labels$/,
|
|
handler: async ({ req, client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
await store.readScopedThread(client, rawId, scopeKey);
|
|
const body = await readJsonBody(req);
|
|
const result = await client.label(rawId, normalizeLabelMutationBody(body));
|
|
store.invalidateThreadCache(rawId);
|
|
return { status: 200, body: result };
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/threads\/([^/]+)\/approve$/,
|
|
handler: async ({ req, client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
await store.readScopedThread(client, rawId, scopeKey);
|
|
const body = await readJsonBody(req);
|
|
const interaction = await client.approve(rawId, {
|
|
...(typeof body.answer === "string" ? { answer: body.answer } : {}),
|
|
...(typeof body.note === "string" ? { note: body.note } : {}),
|
|
...(typeof body.interactionId === "string" ? { interactionId: body.interactionId } : {}),
|
|
});
|
|
store.invalidateThreadCache(rawId);
|
|
return { status: 200, body: { interaction } };
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/threads\/([^/]+)\/reject$/,
|
|
handler: async ({ req, client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
await store.readScopedThread(client, rawId, scopeKey);
|
|
const body = await readJsonBody(req);
|
|
const interaction = await client.reject(rawId, {
|
|
...(typeof body.reason === "string" ? { reason: body.reason } : {}),
|
|
...(typeof body.note === "string" ? { note: body.note } : {}),
|
|
...(typeof body.interactionId === "string" ? { interactionId: body.interactionId } : {}),
|
|
});
|
|
store.invalidateThreadCache(rawId);
|
|
return { status: 200, body: { interaction } };
|
|
},
|
|
},
|
|
{
|
|
method: "GET",
|
|
pattern: /^\/viewer-api\/tasks$/,
|
|
handler: async ({ client, reqUrl }) => {
|
|
const bucket = (reqUrl.searchParams.get("bucket") || "ready").trim().toLowerCase();
|
|
const channel = reqUrl.searchParams.get("channel")?.trim() || undefined;
|
|
const labels = reqUrl.searchParams.getAll("label").map((s) => s.trim()).filter(Boolean);
|
|
const rawLimit = Number.parseInt(reqUrl.searchParams.get("limit") || "60", 10);
|
|
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 100) : 60;
|
|
return {
|
|
status: 200,
|
|
body: await store.listTasksForBucket(client, { bucket, channel, labels, limit }),
|
|
};
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/tasks$/,
|
|
handler: async ({ req, client }) => {
|
|
const body = await readJsonBody(req);
|
|
const channel = typeof body.channel === "string" ? body.channel.trim() : "";
|
|
if (!channel) {
|
|
return { status: 400, body: { code: "validation_error", message: "Channel is required." } };
|
|
}
|
|
const issue = await client.tasks.create(channel, {
|
|
...(typeof body.text === "string" ? { text: body.text } : {}),
|
|
...(typeof body.title === "string" ? { title: body.title } : {}),
|
|
...(typeof body.description === "string" ? { description: body.description } : {}),
|
|
...(typeof body.priority === "string" ? { priority: body.priority } : {}),
|
|
...(body.labels && typeof body.labels === "object" ? { labels: body.labels } : {}),
|
|
...(typeof body.resultSchema === "string" && body.resultSchema.trim()
|
|
? { resultSchema: body.resultSchema.trim() }
|
|
: {}),
|
|
...(typeof body.for === "string" && body.for.trim() ? { for: body.for.trim() } : {}),
|
|
...(Array.isArray(body.needs) && body.needs.length > 0 ? { needs: body.needs } : {}),
|
|
});
|
|
store.invalidateThreadCache(issue.id);
|
|
return { status: 201, body: { issue } };
|
|
},
|
|
},
|
|
{
|
|
method: "POST",
|
|
pattern: /^\/viewer-api\/tasks\/([^/]+)\/complete$/,
|
|
handler: async ({ req, client, params, scopeKey }) => {
|
|
const rawId = decodeURIComponent(params[0]);
|
|
await store.readScopedThread(client, rawId, scopeKey);
|
|
const body = await readJsonBody(req);
|
|
const claimed = await client.tasks.claim(rawId, { lease: "2m" });
|
|
if (!claimed) {
|
|
return {
|
|
status: 409,
|
|
body: {
|
|
code: "task_not_claimable",
|
|
message: `Task '${rawId}' cannot be claimed right now (already leased, blocked, or settled).`,
|
|
},
|
|
};
|
|
}
|
|
try {
|
|
const completed = await claimed.complete({
|
|
message:
|
|
typeof body.message === "string" && body.message.trim()
|
|
? body.message.trim()
|
|
: "Completed from channels viewer",
|
|
...(body.data && typeof body.data === "object" && !Array.isArray(body.data)
|
|
? { data: body.data }
|
|
: {}),
|
|
});
|
|
store.invalidateThreadCache(rawId);
|
|
return { status: 200, body: { issue: completed } };
|
|
} catch (err) {
|
|
await claimed.release().catch(() => {});
|
|
throw err;
|
|
}
|
|
},
|
|
},
|
|
];
|
|
}
|
|
|
|
function validateBindPolicy(host, allowRemote, remoteToken) {
|
|
if (isLoopbackHost(host)) return;
|
|
if (!allowRemote) {
|
|
throw new Error(
|
|
`Refusing to bind Paperclip Channels Viewer to non-loopback host "${host}" without --allow-remote.`,
|
|
);
|
|
}
|
|
if (typeof remoteToken !== "string" || remoteToken.trim().length < MIN_REMOTE_TOKEN_LENGTH) {
|
|
throw new Error(
|
|
`Refusing to bind Paperclip Channels Viewer to non-loopback host "${host}" without --remote-token (minimum ${MIN_REMOTE_TOKEN_LENGTH} characters, or PAPERCLIP_VIEWER_REMOTE_TOKEN).`,
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function createChannelsViewerServer(options = {}) {
|
|
const boundHost = (options.host ?? "127.0.0.1").trim();
|
|
const requestedPort = options.port ?? 4310;
|
|
const allowRemote = Boolean(options.allowRemote);
|
|
const envObj = options.env ?? process.env;
|
|
const remoteTokenRaw = options.remoteToken ?? envObj.PAPERCLIP_VIEWER_REMOTE_TOKEN ?? "";
|
|
const remoteToken = !isLoopbackHost(boundHost) ? String(remoteTokenRaw).trim() : "";
|
|
const extraAllowedHosts = Array.isArray(options.allowedHosts) ? options.allowedHosts : [];
|
|
|
|
validateBindPolicy(boundHost, allowRemote, remoteToken);
|
|
|
|
const sdk = await loadPaperclipSdk(options.sdk);
|
|
const csrfToken = options.csrfToken || randomBytes(32).toString("hex");
|
|
const initialDiscovery = discoverLocalViewerAuth({
|
|
apiBase: options.apiBase,
|
|
explicitApiKey: options.apiKey,
|
|
company: options.company,
|
|
profile: options.profile,
|
|
homeDir: options.homeDir,
|
|
cwd: options.cwd,
|
|
env: envObj,
|
|
});
|
|
|
|
const store = createViewerDataStore({
|
|
sdk,
|
|
options: { ...options, env: envObj },
|
|
initialDiscovery,
|
|
csrfToken,
|
|
});
|
|
const routes = buildApiRoutes(store);
|
|
const activeStreamClosers = new Set();
|
|
|
|
let server;
|
|
const getBoundPort = () => {
|
|
const addr = server?.address();
|
|
return addr && typeof addr === "object" && typeof addr.port === "number"
|
|
? addr.port
|
|
: requestedPort || null;
|
|
};
|
|
|
|
async function handleSseStream(req, res, reqUrl, client) {
|
|
const ac = new AbortController();
|
|
const channel = reqUrl.searchParams.get("channel")?.trim() || undefined;
|
|
const issueId = reqUrl.searchParams.get("issueId")?.trim() || undefined;
|
|
const lastEventId =
|
|
typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"].trim() : "";
|
|
const after = lastEventId || reqUrl.searchParams.get("after")?.trim() || undefined;
|
|
const labels = reqUrl.searchParams.getAll("label").map((s) => s.trim()).filter(Boolean);
|
|
|
|
res.writeHead(200, {
|
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
"Cache-Control": "no-cache, no-transform",
|
|
Connection: "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
"X-Content-Type-Options": "nosniff",
|
|
});
|
|
res.write(": connected\n\n");
|
|
|
|
let closed = false;
|
|
const keepalive = setInterval(() => {
|
|
if (!closed && !res.writableEnded) res.write(": keepalive\n\n");
|
|
}, 20_000);
|
|
keepalive.unref?.();
|
|
|
|
const closeStream = () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
activeStreamClosers.delete(closeStream);
|
|
clearInterval(keepalive);
|
|
ac.abort();
|
|
if (!res.writableEnded) res.end();
|
|
};
|
|
activeStreamClosers.add(closeStream);
|
|
req.on("close", closeStream);
|
|
res.on("close", closeStream);
|
|
|
|
try {
|
|
const stream = client.events(
|
|
{
|
|
...(channel ? { channel } : {}),
|
|
...(issueId ? { issueId } : {}),
|
|
...(labels.length > 0 ? { label: labels } : {}),
|
|
...(after ? { after } : {}),
|
|
},
|
|
{ signal: ac.signal },
|
|
);
|
|
for await (const ev of stream) {
|
|
if (closed || res.writableEnded) break;
|
|
if (ev.issueId) store.invalidateThreadCache(ev.issueId);
|
|
res.write(`id: ${ev.cursor}\nevent: board_event\ndata: ${JSON.stringify(ev)}\n\n`);
|
|
}
|
|
} catch (err) {
|
|
if (!closed && !res.writableEnded) {
|
|
res.write(`event: stream_error\ndata: ${JSON.stringify(serializeError(err).body)}\n\n`);
|
|
}
|
|
} finally {
|
|
closeStream();
|
|
}
|
|
}
|
|
|
|
server = createServer(async (req, res) => {
|
|
try {
|
|
const method = (req.method || "GET").toUpperCase();
|
|
const reqUrl = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
|
|
const pathname = reqUrl.pathname;
|
|
|
|
if (pathname === "/favicon.ico" && method === "GET") {
|
|
res.writeHead(204, { "X-Content-Type-Options": "nosniff" });
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
if (STATIC_ASSETS.has(pathname) && (method === "GET" || method === "HEAD")) {
|
|
if (!isAllowedViewerHost(req.headers.host, boundHost, getBoundPort(), extraAllowedHosts)) {
|
|
sendJson(res, 403, {
|
|
code: "invalid_host",
|
|
message: "Rejected request with unexpected Host header.",
|
|
});
|
|
return;
|
|
}
|
|
if (remoteToken && !verifyRemoteAccessToken(req.headers.authorization, remoteToken)) {
|
|
sendJson(
|
|
res,
|
|
401,
|
|
{ code: "remote_auth_required", message: "Valid remote access token required." },
|
|
{ "WWW-Authenticate": 'Basic realm="Paperclip Channels Viewer"' },
|
|
);
|
|
return;
|
|
}
|
|
const asset = STATIC_ASSETS.get(pathname);
|
|
const content = await readFile(path.join(PUBLIC_DIR, asset.file));
|
|
res.writeHead(200, {
|
|
"Content-Type": asset.contentType,
|
|
"Cache-Control": "no-cache",
|
|
"X-Content-Type-Options": "nosniff",
|
|
"X-Frame-Options": "DENY",
|
|
"Referrer-Policy": "no-referrer",
|
|
...(asset.isHtml ? { "Content-Security-Policy": CSP_HEADER } : {}),
|
|
});
|
|
res.end(method === "HEAD" ? undefined : content);
|
|
return;
|
|
}
|
|
|
|
if (!pathname.startsWith("/viewer-api/")) {
|
|
sendJson(res, 404, { code: "not_found", message: `Route not found: ${pathname}` });
|
|
return;
|
|
}
|
|
|
|
const sec = validateViewerRequestSecurity(req, {
|
|
boundHost,
|
|
getBoundPort,
|
|
extraAllowedHosts,
|
|
remoteToken,
|
|
csrfToken,
|
|
requireCsrf: method !== "GET" && method !== "HEAD",
|
|
});
|
|
if (!sec.ok) {
|
|
sendJson(
|
|
res,
|
|
sec.status,
|
|
{ code: sec.code, message: sec.message },
|
|
sec.wwwAuthenticate ? { "WWW-Authenticate": sec.wwwAuthenticate } : {},
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (pathname === "/viewer-api/session" && (method === "GET" || method === "POST")) {
|
|
for (const route of routes) {
|
|
if (route.method === method && route.pattern.test(pathname)) {
|
|
const out = await route.handler({ req, reqUrl, params: [] });
|
|
sendJson(res, out.status, out.body);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
const { client, profile, company } = store.buildClient(reqUrl);
|
|
const scopeKey = `${company ?? "default"}:${profile ?? "default"}`;
|
|
|
|
if (pathname === "/viewer-api/events/stream" && method === "GET") {
|
|
await handleSseStream(req, res, reqUrl, client);
|
|
return;
|
|
}
|
|
|
|
for (const route of routes) {
|
|
if (route.method !== method) continue;
|
|
const match = route.pattern.exec(pathname);
|
|
if (!match) continue;
|
|
const out = await route.handler({ req, reqUrl, client, scopeKey, params: match.slice(1) });
|
|
sendJson(res, out.status, out.body);
|
|
return;
|
|
}
|
|
|
|
sendJson(res, 404, { code: "not_found", message: `Unknown route: ${method} ${pathname}` });
|
|
} catch (err) {
|
|
if (!res.headersSent) {
|
|
const serialized = serializeError(err);
|
|
sendJson(res, serialized.status, serialized.body);
|
|
} else if (!res.writableEnded) {
|
|
res.end();
|
|
}
|
|
}
|
|
});
|
|
|
|
return {
|
|
server,
|
|
csrfToken,
|
|
getState() {
|
|
return {
|
|
...store.getState(),
|
|
boundHost,
|
|
boundPort: getBoundPort(),
|
|
};
|
|
},
|
|
getCacheStats() {
|
|
return store.getCacheStats();
|
|
},
|
|
async listen(port = requestedPort, host) {
|
|
if (host !== undefined && String(host).trim() !== boundHost) {
|
|
throw new Error(
|
|
`listen() cannot override configured host "${boundHost}" with "${host}". Pass host to createChannelsViewerServer() instead.`,
|
|
);
|
|
}
|
|
await new Promise((resolve, reject) => {
|
|
const onError = (err) => {
|
|
server.off("listening", onListening);
|
|
reject(err);
|
|
};
|
|
const onListening = () => {
|
|
server.off("error", onError);
|
|
resolve();
|
|
};
|
|
server.once("error", onError);
|
|
server.once("listening", onListening);
|
|
server.listen(port, boundHost);
|
|
});
|
|
const addr = server.address();
|
|
const actualPort = typeof addr === "object" && addr ? addr.port : port;
|
|
const urlHost =
|
|
boundHost.includes(":") && !boundHost.startsWith("[") ? `[${boundHost}]` : boundHost;
|
|
return { host: boundHost, port: actualPort, url: `http://${urlHost}:${actualPort}` };
|
|
},
|
|
async close() {
|
|
for (const closeStream of [...activeStreamClosers]) {
|
|
closeStream();
|
|
}
|
|
if (!server.listening) return;
|
|
const closePromise = new Promise((resolve) => server.close(() => resolve()));
|
|
server.closeIdleConnections?.();
|
|
server.closeAllConnections?.();
|
|
await closePromise;
|
|
},
|
|
};
|
|
}
|