@causyne/agent 1.20.124 → 1.20.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/causyne.js +1 -1
- package/docs/THIRD_PARTY_NOTICES.md +36 -2
- package/package.json +6 -4
- package/src/acp/protocol.ts +19 -1
- package/src/acp/server.js +282 -8
- package/src/acp/server.ts +284 -8
- package/src/agent/abortableDelay.js +2 -2
- package/src/agent/abortableDelay.ts +2 -2
- package/src/agent/errorClassifier.js +9 -1
- package/src/agent/errorClassifier.ts +8 -1
- package/src/agentLoop.js +142 -53
- package/src/agentLoop.ts +151 -50
- package/src/approvalPolicy.js +34 -10
- package/src/approvalPolicy.ts +42 -11
- package/src/browser/causyneBrowser.js +61 -3
- package/src/browser/causyneBrowser.ts +65 -3
- package/src/browser/urlPolicy.js +14 -1
- package/src/browser/urlPolicy.ts +12 -1
- package/src/cliMode.js +21 -9
- package/src/cliMode.ts +20 -8
- package/src/commands.js +365 -45
- package/src/commands.ts +403 -45
- package/src/config.js +19 -4
- package/src/config.ts +18 -4
- package/src/core/contextCompactor.js +54 -7
- package/src/core/contextCompactor.ts +63 -7
- package/src/core/goalLoop.js +257 -0
- package/src/core/goalLoop.ts +310 -0
- package/src/entrypoint.js +135 -3
- package/src/entrypoint.ts +136 -3
- package/src/game/causyneCoreBridge.js +686 -0
- package/src/game/causyneCoreBridge.ts +702 -0
- package/src/game/gameLauncher.js +287 -0
- package/src/game/gameLauncher.ts +352 -0
- package/src/game/gameProvisioner.js +425 -0
- package/src/game/gameProvisioner.ts +488 -0
- package/src/headlessCli.js +19 -12
- package/src/headlessCli.ts +22 -8
- package/src/infra/atomicWriter.js +40 -4
- package/src/infra/atomicWriter.ts +36 -4
- package/src/launchIntent.js +73 -3
- package/src/launchIntent.ts +76 -3
- package/src/lsp/lspClient.js +83 -12
- package/src/lsp/lspClient.ts +75 -12
- package/src/mcp/mcpRegistry.js +75 -8
- package/src/mcp/mcpRegistry.ts +70 -7
- package/src/memory/contextBudget.js +2 -0
- package/src/memory/contextBudget.ts +1 -0
- package/src/memory/episodicStore.js +40 -0
- package/src/memory/episodicStore.ts +46 -0
- package/src/memory.js +67 -0
- package/src/memory.ts +65 -0
- package/src/modelVariants.js +45 -0
- package/src/modelVariants.ts +54 -0
- package/src/outputRecovery.js +3 -2
- package/src/outputRecovery.ts +4 -2
- package/src/permissionPresets.js +327 -0
- package/src/permissionPresets.ts +361 -0
- package/src/personalization.js +365 -0
- package/src/personalization.ts +471 -0
- package/src/projectInstructions.js +30 -10
- package/src/projectInstructions.ts +31 -12
- package/src/providers/acp.js +3 -2
- package/src/providers/acp.ts +3 -2
- package/src/providers/antigravity.js +64 -9
- package/src/providers/antigravity.ts +75 -9
- package/src/providers/byokHttp.js +7 -1
- package/src/providers/byokHttp.ts +6 -1
- package/src/providers/byokStream.js +21 -8
- package/src/providers/byokStream.ts +17 -7
- package/src/providers/dashscope-byok.js +21 -5
- package/src/providers/dashscope-byok.ts +29 -11
- package/src/providers/moonshot.js +26 -7
- package/src/providers/moonshot.ts +34 -13
- package/src/providers/muse.js +6 -0
- package/src/providers/muse.ts +8 -0
- package/src/providers/ollama.js +39 -7
- package/src/providers/ollama.ts +36 -7
- package/src/providers/openai-compatible.js +16 -3
- package/src/providers/openai-compatible.ts +13 -3
- package/src/providers/openai.js +62 -4
- package/src/providers/openai.ts +50 -4
- package/src/providers/openrouter.js +19 -4
- package/src/providers/openrouter.ts +21 -4
- package/src/providers/qwen-byok.js +21 -5
- package/src/providers/qwen-byok.ts +29 -11
- package/src/providers/xai.js +26 -10
- package/src/providers/xai.ts +34 -16
- package/src/reporting.js +4 -2
- package/src/reporting.ts +4 -2
- package/src/sandbox.js +34 -0
- package/src/sandbox.ts +43 -0
- package/src/scheduler/scheduler.js +372 -0
- package/src/scheduler/scheduler.ts +433 -0
- package/src/sessionSearchIndex.js +267 -0
- package/src/sessionSearchIndex.ts +311 -0
- package/src/skillsManager.js +2 -3
- package/src/skillsManager.ts +2 -3
- package/src/toolPacks.js +6 -0
- package/src/toolPacks.ts +6 -0
- package/src/tools/applyPatch.js +1 -1
- package/src/tools/applyPatch.ts +1 -1
- package/src/tools/generateMediaViaApi.js +4 -3
- package/src/tools/generateMediaViaApi.ts +4 -3
- package/src/tools/memoryWrite.js +15 -1
- package/src/tools/memoryWrite.ts +16 -1
- package/src/tools/nativeEngine.js +2 -2
- package/src/tools/nativeEngine.ts +2 -2
- package/src/tools/openSourceToolProvisioner.js +2 -2
- package/src/tools/openSourceToolProvisioner.ts +2 -2
- package/src/tools/osSandbox.js +1 -1
- package/src/tools/osSandbox.ts +1 -1
- package/src/tools/payloadSanitizer.js +0 -1
- package/src/tools/payloadSanitizer.ts +0 -1
- package/src/tools/pdfReader.js +122 -20
- package/src/tools/pdfReader.ts +111 -20
- package/src/tools/presentDeliverable.js +103 -0
- package/src/tools/presentDeliverable.ts +127 -0
- package/src/tools/ptcRuntime.js +444 -0
- package/src/tools/ptcRuntime.ts +490 -0
- package/src/tools/ptyTerminal.js +1108 -0
- package/src/tools/ptyTerminal.ts +1245 -0
- package/src/tools/registry.js +21 -12
- package/src/tools/registry.ts +21 -12
- package/src/tools/toolOutputStore.js +26 -4
- package/src/tools/toolOutputStore.ts +22 -4
- package/src/tools/webFetch.js +158 -11
- package/src/tools/webFetch.ts +145 -11
- package/src/tools/webSearch.js +123 -36
- package/src/tools/webSearch.ts +124 -33
- package/src/tui/banner.js +5 -1
- package/src/tui/banner.ts +6 -1
- package/src/tui/chatRenderer.js +1 -2
- package/src/tui/chatRenderer.ts +1 -2
- package/src/tui/completion.js +1 -0
- package/src/tui/completion.ts +1 -0
- package/src/tui/composerControls.js +111 -27
- package/src/tui/composerControls.ts +124 -28
- package/src/tui/dialogs.js +3 -16
- package/src/tui/dialogs.ts +3 -16
- package/src/tui/home.js +1 -0
- package/src/tui/home.ts +1 -0
- package/src/tui/invocation.js +1 -2
- package/src/tui/invocation.ts +1 -2
- package/src/tui/modelPicker.js +22 -12
- package/src/tui/modelPicker.ts +22 -12
- package/src/tui/overlay.js +2 -5
- package/src/tui/overlay.ts +2 -5
- package/src/tui/prompt.js +6 -4
- package/src/tui/prompt.ts +6 -4
- package/src/tui/selectList.js +4 -12
- package/src/tui/selectList.ts +4 -12
- package/src/tui/setup.js +22 -9
- package/src/tui/setup.ts +26 -9
- package/src/tui/statusLine.ts +2 -0
- package/src/web/client/browserPanel.js +905 -0
- package/src/web/client/browserPanel.ts +872 -0
- package/src/web/client/chatStream.js +321 -0
- package/src/web/client/chatStream.ts +297 -0
- package/src/web/client/cliPanel.js +165 -0
- package/src/web/client/cliPanel.ts +171 -0
- package/src/web/client/composer.js +204 -0
- package/src/web/client/composer.ts +209 -0
- package/src/web/client/diffPanel.js +176 -0
- package/src/web/client/diffPanel.ts +203 -0
- package/src/web/client/dom.js +271 -0
- package/src/web/client/dom.ts +272 -0
- package/src/web/client/filesAndCanvas.js +233 -0
- package/src/web/client/filesAndCanvas.ts +240 -0
- package/src/web/client/gameLauncherUi.js +78 -0
- package/src/web/client/gameLauncherUi.ts +78 -0
- package/src/web/client/main.js +316 -0
- package/src/web/client/main.ts +391 -0
- package/src/web/client/markdown.js +364 -0
- package/src/web/client/markdown.ts +373 -0
- package/src/web/client/modelPicker.js +455 -0
- package/src/web/client/modelPicker.ts +451 -0
- package/src/web/client/permissionPresetsUi.js +307 -0
- package/src/web/client/permissionPresetsUi.ts +333 -0
- package/src/web/client/sessions.js +353 -0
- package/src/web/client/sessions.ts +372 -0
- package/src/web/client/settingsModal.js +824 -0
- package/src/web/client/settingsModal.ts +959 -0
- package/src/web/client/state.js +280 -0
- package/src/web/client/state.ts +259 -0
- package/src/web/client/streamSmoother.js +127 -0
- package/src/web/client/streamSmoother.ts +119 -0
- package/src/web/client/studioLayout.js +89 -0
- package/src/web/client/studioLayout.ts +103 -0
- package/src/web/client/studioShell.js +660 -0
- package/src/web/client/studioShell.ts +672 -0
- package/src/web/client/studioStart.js +77 -0
- package/src/web/client/studioStart.ts +89 -0
- package/src/web/client/terminalPanel.js +606 -0
- package/src/web/client/terminalPanel.ts +632 -0
- package/src/web/client/terminalTheme.js +249 -0
- package/src/web/client/terminalTheme.ts +258 -0
- package/src/web/client/turnView.js +934 -0
- package/src/web/client/turnView.ts +981 -0
- package/src/web/client/types.js +1 -0
- package/src/web/client/types.ts +322 -0
- package/src/web/client/validators.js +147 -0
- package/src/web/client/validators.ts +140 -0
- package/src/web/server/activeRuns.js +152 -0
- package/src/web/server/activeRuns.ts +171 -0
- package/src/web/server/routesBrowser.js +409 -0
- package/src/web/server/routesBrowser.ts +435 -0
- package/src/web/server/routesChat.js +304 -0
- package/src/web/server/routesChat.ts +347 -0
- package/src/web/server/routesCore.js +472 -0
- package/src/web/server/routesCore.ts +522 -0
- package/src/web/server/routesSettings.js +344 -0
- package/src/web/server/routesSettings.ts +397 -0
- package/src/web/server/routesTerminal.js +162 -0
- package/src/web/server/routesTerminal.ts +182 -0
- package/src/web/server/routesWorkspace.js +510 -0
- package/src/web/server/routesWorkspace.ts +546 -0
- package/src/web/server/security.js +98 -0
- package/src/web/server/security.ts +108 -0
- package/src/web/server/sessionTranscript.js +586 -0
- package/src/web/server/sessionTranscript.ts +566 -0
- package/src/web/server/staticAssets.js +104 -0
- package/src/web/server/staticAssets.ts +116 -0
- package/src/web/server/types.js +1 -0
- package/src/web/server/types.ts +135 -0
- package/src/web/server/workspaceFiles.js +368 -0
- package/src/web/server/workspaceFiles.ts +363 -0
- package/src/web/skybridgeServer.js +78 -2448
- package/src/web/skybridgeServer.ts +120 -2600
- package/src/web/skybridgeUi.js +20 -450
- package/src/web/skybridgeUi.ts +24 -455
- package/src/web/styles/agent.css +380 -0
- package/src/web/styles/composer.css +193 -0
- package/src/web/styles/overlays.css +935 -0
- package/src/web/styles/shell.css +387 -0
- package/src/web/styles/studio.css +951 -0
- package/src/web/styles/thread.css +221 -0
- package/src/web/styles/tokens.css +94 -0
- package/src/web/ui/brandMark.js +73 -0
- package/src/web/ui/brandMark.ts +82 -0
- package/src/web/ui/modalsTemplate.js +388 -0
- package/src/web/ui/modalsTemplate.ts +388 -0
- package/src/web/ui/sidebarTemplate.js +63 -0
- package/src/web/ui/sidebarTemplate.ts +64 -0
- package/src/web/ui/studioTemplate.js +256 -0
- package/src/web/ui/studioTemplate.ts +256 -0
- package/src/web/ui/workspaceTemplate.js +72 -0
- package/src/web/ui/workspaceTemplate.ts +73 -0
- package/src/worktreeManager.js +16 -1
- package/src/worktreeManager.ts +22 -1
- package/src/web/skybridgeClientScript.js +0 -3951
- package/src/web/skybridgeClientScript.ts +0 -3952
- package/src/web/skybridgeStyles.js +0 -827
- package/src/web/skybridgeStyles.ts +0 -828
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import type http from 'node:http';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { atomicWriteFileSync } from '../../infra/atomicWriter.js';
|
|
5
|
+
import {
|
|
6
|
+
createSession,
|
|
7
|
+
deleteSession,
|
|
8
|
+
getSession,
|
|
9
|
+
listSessions,
|
|
10
|
+
renameSession
|
|
11
|
+
} from '../../sessionJournal.js';
|
|
12
|
+
import { collectWorkingTreeDiff } from '../../diffReview.js';
|
|
13
|
+
import { auditLog } from '../../auditLog.js';
|
|
14
|
+
import { redactProviderSecrets } from '../../providers/byokHttp.js';
|
|
15
|
+
import { isIgnoredByCausyneIgnore } from '../../ignoreRules.js';
|
|
16
|
+
import { listCommands, parseCommand, runCommand } from '../../commands.js';
|
|
17
|
+
import { listGroups } from '../../checkpoints.js';
|
|
18
|
+
import { listCompiledSkills } from '../../skillsManager.js';
|
|
19
|
+
import { serverStatus } from '../../mcp/mcpRegistry.js';
|
|
20
|
+
import { listAllPeers } from '../../acp/peerProfiles.js';
|
|
21
|
+
import { listWorktrees } from '../../worktreeManager.js';
|
|
22
|
+
import { backgroundTaskManager } from '../../backgroundTasks.js';
|
|
23
|
+
import { causyneBrowser } from '../../browser/causyneBrowser.js';
|
|
24
|
+
import { SAFE_SESSION_ID_RE, readJsonBody, sendJson } from './security.js';
|
|
25
|
+
import {
|
|
26
|
+
MAX_FILE_READ_BYTES,
|
|
27
|
+
MAX_FILE_WRITE_BYTES,
|
|
28
|
+
buildSynthesizedWriteHunk,
|
|
29
|
+
formatByteSize,
|
|
30
|
+
listWorkspaceEntries,
|
|
31
|
+
packLocalHtmlPreview,
|
|
32
|
+
readLastGitCommitDiffForFile,
|
|
33
|
+
resolveWorkspaceRelativePath,
|
|
34
|
+
workspaceMatchesSession
|
|
35
|
+
} from './workspaceFiles.js';
|
|
36
|
+
import {
|
|
37
|
+
extractSessionDisplayMessages,
|
|
38
|
+
extractSessionFileEvidence,
|
|
39
|
+
extractSessionTouchedFiles,
|
|
40
|
+
parseSessionIdRoute,
|
|
41
|
+
parseSessionStreamRoute
|
|
42
|
+
} from './sessionTranscript.js';
|
|
43
|
+
import type { SessionFileEvidence, SkybridgeContext } from './types.js';
|
|
44
|
+
|
|
45
|
+
export async function handleWorkspaceRoutes(
|
|
46
|
+
req: http.IncomingMessage,
|
|
47
|
+
res: http.ServerResponse,
|
|
48
|
+
parsedUrl: URL,
|
|
49
|
+
ctx: SkybridgeContext
|
|
50
|
+
): Promise<boolean> {
|
|
51
|
+
const pathname = parsedUrl.pathname;
|
|
52
|
+
const { workspaceRoot } = ctx;
|
|
53
|
+
|
|
54
|
+
if (req.method === 'GET' && pathname === '/api/sessions') {
|
|
55
|
+
const all = listSessions();
|
|
56
|
+
const scoped = all.filter((row) => workspaceMatchesSession(row.workspace, workspaceRoot));
|
|
57
|
+
sendJson(res, 200, {
|
|
58
|
+
ok: true,
|
|
59
|
+
sessions: scoped.slice(0, 50).map((row) => {
|
|
60
|
+
const run = ctx.activeRuns.get(row.id);
|
|
61
|
+
const isRunning = Boolean(run && (run.status === 'running' || run.status === 'awaiting_client'));
|
|
62
|
+
return {
|
|
63
|
+
id: row.id,
|
|
64
|
+
title: row.title,
|
|
65
|
+
createdAt: row.createdAt,
|
|
66
|
+
updatedAt: row.updatedAt,
|
|
67
|
+
messageCount: row.messageCount,
|
|
68
|
+
running: isRunning,
|
|
69
|
+
awaitingClient: Boolean(run && run.status === 'awaiting_client')
|
|
70
|
+
};
|
|
71
|
+
})
|
|
72
|
+
});
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const sessionStreamId = parseSessionStreamRoute(pathname);
|
|
77
|
+
if (req.method === 'GET' && sessionStreamId) {
|
|
78
|
+
const run = ctx.activeRuns.get(sessionStreamId);
|
|
79
|
+
if (!run || (run.status !== 'running' && run.status !== 'awaiting_client')) {
|
|
80
|
+
res.statusCode = 200;
|
|
81
|
+
res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
|
|
82
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
83
|
+
res.end(`${JSON.stringify({ type: 'idle', sessionId: sessionStreamId })}\n`);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
ctx.attachRunStream(req, res, run, true);
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (req.method === 'POST' && pathname === '/api/sessions') {
|
|
91
|
+
const body = await readJsonBody(req);
|
|
92
|
+
const rawTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
|
|
93
|
+
const created = createSession(workspaceRoot, rawTitle || 'Untitled', false);
|
|
94
|
+
sendJson(res, 201, {
|
|
95
|
+
ok: true,
|
|
96
|
+
session: {
|
|
97
|
+
id: created.id,
|
|
98
|
+
title: created.title,
|
|
99
|
+
createdAt: created.createdAt,
|
|
100
|
+
updatedAt: created.updatedAt,
|
|
101
|
+
messageCount: 0,
|
|
102
|
+
messages: []
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const sessionIdParam = parseSessionIdRoute(pathname);
|
|
109
|
+
if (sessionIdParam) {
|
|
110
|
+
const existing = getSession(sessionIdParam);
|
|
111
|
+
if (!existing || !workspaceMatchesSession(existing.workspace, workspaceRoot)) {
|
|
112
|
+
sendJson(res, 404, { error: 'Session not found in this workspace.' });
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
if (req.method === 'GET') {
|
|
116
|
+
const persistedTouched = extractSessionTouchedFiles(existing.messages, workspaceRoot);
|
|
117
|
+
const liveTouched = [...(ctx.sessionTouchedFilesMap.get(existing.id) ?? [])];
|
|
118
|
+
const touchedFiles = [...new Set([...persistedTouched, ...liveTouched])].sort();
|
|
119
|
+
const activeRun = ctx.activeRuns.get(existing.id);
|
|
120
|
+
const isRunning = Boolean(activeRun && (activeRun.status === 'running' || activeRun.status === 'awaiting_client'));
|
|
121
|
+
sendJson(res, 200, {
|
|
122
|
+
ok: true,
|
|
123
|
+
session: {
|
|
124
|
+
id: existing.id,
|
|
125
|
+
title: existing.title,
|
|
126
|
+
createdAt: existing.createdAt,
|
|
127
|
+
updatedAt: existing.updatedAt,
|
|
128
|
+
messageCount: existing.messages.length,
|
|
129
|
+
messages: extractSessionDisplayMessages(existing.messages),
|
|
130
|
+
touchedFiles,
|
|
131
|
+
running: isRunning,
|
|
132
|
+
awaitingClient: Boolean(activeRun && activeRun.status === 'awaiting_client'),
|
|
133
|
+
activeRun: isRunning && activeRun ? {
|
|
134
|
+
taskId: activeRun.taskId,
|
|
135
|
+
status: activeRun.status,
|
|
136
|
+
prompt: activeRun.prompt,
|
|
137
|
+
startedAt: activeRun.startedAt
|
|
138
|
+
} : null
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
if (req.method === 'PATCH') {
|
|
144
|
+
const body = await readJsonBody(req);
|
|
145
|
+
const nextTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
|
|
146
|
+
if (!nextTitle) {
|
|
147
|
+
sendJson(res, 400, { error: 'A non-empty session title is required.' });
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
const updated = renameSession(existing.id, nextTitle);
|
|
151
|
+
if (!updated) {
|
|
152
|
+
sendJson(res, 400, { error: 'Could not rename session.' });
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
sendJson(res, 200, { ok: true, id: existing.id, title: nextTitle });
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
if (req.method === 'DELETE') {
|
|
159
|
+
const removed = deleteSession(existing.id);
|
|
160
|
+
sendJson(res, removed ? 200 : 404, { ok: removed, id: existing.id });
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (req.method === 'GET' && pathname === '/api/files') {
|
|
166
|
+
const dir = parsedUrl.searchParams.get('dir') || '';
|
|
167
|
+
const q = parsedUrl.searchParams.get('q') || '';
|
|
168
|
+
const entries = listWorkspaceEntries(workspaceRoot, dir, q);
|
|
169
|
+
const parentDir = dir ? path.posix.dirname(dir.replace(/\\/g, '/')) : '';
|
|
170
|
+
sendJson(res, 200, {
|
|
171
|
+
ok: true,
|
|
172
|
+
dir,
|
|
173
|
+
parentDir: parentDir === '.' ? '' : parentDir,
|
|
174
|
+
entries
|
|
175
|
+
});
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (req.method === 'GET' && pathname === '/api/file') {
|
|
180
|
+
const rel = parsedUrl.searchParams.get('path') || '';
|
|
181
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
182
|
+
if (!abs) {
|
|
183
|
+
sendJson(res, 403, { error: 'Path is outside the locked workspace boundary.' });
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
const stat = fs.lstatSync(abs);
|
|
187
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
188
|
+
sendJson(res, 403, { error: 'Only regular workspace files can be read.' });
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
if (stat.size > MAX_FILE_READ_BYTES) {
|
|
192
|
+
sendJson(res, 413, { error: `File exceeds ${MAX_FILE_READ_BYTES} byte preview limit.` });
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
const content = fs.readFileSync(abs, 'utf8');
|
|
196
|
+
sendJson(res, 200, {
|
|
197
|
+
ok: true,
|
|
198
|
+
path: path.relative(workspaceRoot, abs).split(path.sep).join('/'),
|
|
199
|
+
size: stat.size,
|
|
200
|
+
content
|
|
201
|
+
});
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (req.method === 'GET' && pathname === '/api/file/pack-html') {
|
|
206
|
+
const rel = parsedUrl.searchParams.get('path') || '';
|
|
207
|
+
const packed = packLocalHtmlPreview(workspaceRoot, rel);
|
|
208
|
+
sendJson(res, 200, {
|
|
209
|
+
ok: true,
|
|
210
|
+
path: rel,
|
|
211
|
+
packedAssets: packed.packedAssets,
|
|
212
|
+
totalBytes: packed.totalBytes,
|
|
213
|
+
html: packed.html
|
|
214
|
+
});
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (req.method === 'POST' && pathname === '/api/file') {
|
|
219
|
+
const body = await readJsonBody(req, MAX_FILE_WRITE_BYTES);
|
|
220
|
+
const rel = typeof body.path === 'string' ? body.path : '';
|
|
221
|
+
const content = typeof body.content === 'string' ? body.content : null;
|
|
222
|
+
if (!rel || content === null) {
|
|
223
|
+
sendJson(res, 400, { error: 'Both `path` and string `content` are required.' });
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
227
|
+
if (!abs) {
|
|
228
|
+
sendJson(res, 403, { error: 'Refusing write outside locked workspace boundary.' });
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
const relNormalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
|
|
232
|
+
if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) {
|
|
233
|
+
sendJson(res, 403, { error: 'File path is blocked by .causyneignore.' });
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
const byteCount = Buffer.byteLength(content, 'utf8');
|
|
237
|
+
if (byteCount > MAX_FILE_WRITE_BYTES) {
|
|
238
|
+
sendJson(res, 413, { error: 'File content exceeds maximum write limit.' });
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
atomicWriteFileSync(abs, content);
|
|
242
|
+
if (typeof body.sessionId === 'string') {
|
|
243
|
+
ctx.recordSessionTouchedFile(body.sessionId.trim(), relNormalized);
|
|
244
|
+
}
|
|
245
|
+
auditLog.log({ event: 'skybridge_file_write', path: relNormalized, bytes: byteCount });
|
|
246
|
+
sendJson(res, 200, { ok: true, path: relNormalized, bytes: byteCount });
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (req.method === 'GET' && pathname === '/api/diff') {
|
|
251
|
+
handleDiffRequest(res, parsedUrl, ctx);
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (req.method === 'GET' && pathname === '/api/commands') {
|
|
256
|
+
const commands = listCommands('terminal').map((cmd) => ({
|
|
257
|
+
name: cmd.name,
|
|
258
|
+
aliases: cmd.aliases ?? [],
|
|
259
|
+
usage: cmd.usage,
|
|
260
|
+
description: cmd.description
|
|
261
|
+
}));
|
|
262
|
+
sendJson(res, 200, { ok: true, commands });
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (req.method === 'POST' && pathname === '/api/command') {
|
|
267
|
+
const body = await readJsonBody(req);
|
|
268
|
+
let cmdName = '';
|
|
269
|
+
let cmdArgv: string[] = [];
|
|
270
|
+
if (typeof body.input === 'string' && body.input.trim()) {
|
|
271
|
+
const rawLine = body.input.trim().startsWith('/') ? body.input.trim() : `/${body.input.trim()}`;
|
|
272
|
+
const parsed = parseCommand(rawLine);
|
|
273
|
+
if (!parsed) {
|
|
274
|
+
sendJson(res, 400, { error: 'Invalid CLI slash command syntax.' });
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
cmdName = parsed.name;
|
|
278
|
+
cmdArgv = parsed.argv;
|
|
279
|
+
} else if (typeof body.name === 'string' && body.name.trim()) {
|
|
280
|
+
cmdName = body.name.trim().toLowerCase();
|
|
281
|
+
cmdArgv = Array.isArray(body.argv) ? body.argv.map((x: unknown) => String(x ?? '')) : [];
|
|
282
|
+
} else {
|
|
283
|
+
sendJson(res, 400, { error: 'Command input or name is required.' });
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
if (cmdName === 'exit' || cmdName === 'quit') {
|
|
287
|
+
sendJson(res, 200, {
|
|
288
|
+
ok: true,
|
|
289
|
+
command: cmdName,
|
|
290
|
+
title: 'Exit',
|
|
291
|
+
output: 'Press Ctrl+C in the terminal running `causyne web` to stop the local Skybridge server cleanly.'
|
|
292
|
+
});
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
const prevCwd = process.cwd();
|
|
296
|
+
let result: Awaited<ReturnType<typeof runCommand>>;
|
|
297
|
+
try {
|
|
298
|
+
if (prevCwd !== workspaceRoot) process.chdir(workspaceRoot);
|
|
299
|
+
result = await runCommand(cmdName, cmdArgv, {
|
|
300
|
+
surface: 'terminal',
|
|
301
|
+
workspaceRoot,
|
|
302
|
+
cwd: workspaceRoot
|
|
303
|
+
});
|
|
304
|
+
} finally {
|
|
305
|
+
try { if (process.cwd() !== prevCwd) process.chdir(prevCwd); } catch { /* ignore */ }
|
|
306
|
+
}
|
|
307
|
+
auditLog.log({ event: 'skybridge_cli_command', command: cmdName, ok: Boolean(result.ok) });
|
|
308
|
+
sendJson(res, 200, {
|
|
309
|
+
ok: Boolean(result.ok),
|
|
310
|
+
command: cmdName,
|
|
311
|
+
title: typeof result.title === 'string' ? result.title : `/${cmdName}`,
|
|
312
|
+
effect: typeof result.effect === 'string' ? result.effect : null,
|
|
313
|
+
output: redactProviderSecrets(String(result.output || ''))
|
|
314
|
+
});
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (req.method === 'GET' && pathname === '/api/cli/overview') {
|
|
319
|
+
const checkpoints = listGroups(12).map((g) => ({
|
|
320
|
+
id: g.taskId,
|
|
321
|
+
createdAt: g.ts,
|
|
322
|
+
label: g.prompt || g.taskId,
|
|
323
|
+
fileCount: Array.isArray(g.fileEntries) ? g.fileEntries.length : 0
|
|
324
|
+
}));
|
|
325
|
+
const skills = listCompiledSkills();
|
|
326
|
+
const mcpServers = serverStatus().map((s) => ({
|
|
327
|
+
name: s.name,
|
|
328
|
+
connected: Boolean((s as any).connected),
|
|
329
|
+
granted: Boolean((s as any).granted),
|
|
330
|
+
toolsCount: typeof (s as any).toolsCount === 'number' ? (s as any).toolsCount : 0
|
|
331
|
+
}));
|
|
332
|
+
const peers = listAllPeers().map((p) => ({
|
|
333
|
+
name: p.id,
|
|
334
|
+
label: p.label,
|
|
335
|
+
command: p.command
|
|
336
|
+
}));
|
|
337
|
+
const tasks = backgroundTaskManager.list().slice(0, 20).map((t) => ({
|
|
338
|
+
id: t.taskId,
|
|
339
|
+
label: t.label,
|
|
340
|
+
command: t.command,
|
|
341
|
+
status: t.status,
|
|
342
|
+
startedAt: t.startedAt
|
|
343
|
+
}));
|
|
344
|
+
let worktrees: Array<{ path: string; branch: string; managed: boolean }> = [];
|
|
345
|
+
try {
|
|
346
|
+
worktrees = listWorktrees(workspaceRoot).map((w) => ({
|
|
347
|
+
path: w.path,
|
|
348
|
+
branch: w.branch || 'detached',
|
|
349
|
+
managed: Boolean(w.managed)
|
|
350
|
+
}));
|
|
351
|
+
} catch {
|
|
352
|
+
worktrees = [];
|
|
353
|
+
}
|
|
354
|
+
sendJson(res, 200, {
|
|
355
|
+
ok: true,
|
|
356
|
+
commandsCount: listCommands('terminal').length,
|
|
357
|
+
skillsCount: skills.length,
|
|
358
|
+
checkpoints,
|
|
359
|
+
mcpServers,
|
|
360
|
+
peers,
|
|
361
|
+
tasks,
|
|
362
|
+
worktrees,
|
|
363
|
+
browserActive: causyneBrowser({ workspace: workspaceRoot }).isActive(),
|
|
364
|
+
browserControlOwner: ctx.getBrowserControlOwner()
|
|
365
|
+
});
|
|
366
|
+
return true;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function handleDiffRequest(
|
|
373
|
+
res: http.ServerResponse,
|
|
374
|
+
parsedUrl: URL,
|
|
375
|
+
ctx: SkybridgeContext
|
|
376
|
+
): void {
|
|
377
|
+
const { workspaceRoot } = ctx;
|
|
378
|
+
const staged = parsedUrl.searchParams.get('staged') === '1';
|
|
379
|
+
const rawSessionId = (parsedUrl.searchParams.get('sessionId') || '').trim();
|
|
380
|
+
const sessionId = SAFE_SESSION_ID_RE.test(rawSessionId) ? rawSessionId : '';
|
|
381
|
+
const rawScope = (parsedUrl.searchParams.get('scope') || '').trim().toLowerCase();
|
|
382
|
+
const scope: 'session' | 'workspace' = rawScope === 'session' && sessionId ? 'session' : 'workspace';
|
|
383
|
+
|
|
384
|
+
const sessionEvidenceMap = new Map<string, SessionFileEvidence>();
|
|
385
|
+
if (sessionId) {
|
|
386
|
+
const sess = getSession(sessionId);
|
|
387
|
+
if (sess && workspaceMatchesSession(sess.workspace, workspaceRoot)) {
|
|
388
|
+
for (const [p, ev] of extractSessionFileEvidence(sess.messages, workspaceRoot)) {
|
|
389
|
+
sessionEvidenceMap.set(p, ev);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
for (const p of ctx.sessionTouchedFilesMap.get(sessionId) ?? []) {
|
|
393
|
+
if (!sessionEvidenceMap.has(p)) {
|
|
394
|
+
sessionEvidenceMap.set(p, {
|
|
395
|
+
path: p,
|
|
396
|
+
status: 'modified',
|
|
397
|
+
additions: 0,
|
|
398
|
+
deletions: 0,
|
|
399
|
+
hunks: []
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const buildNonGitSessionEntry = (rel: string, ev: SessionFileEvidence | undefined, isGit: boolean) => {
|
|
406
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
407
|
+
let existsOnDisk = false;
|
|
408
|
+
let diskSize = 0;
|
|
409
|
+
let diskHunks: Array<{ header: string; lines: string[] }> = [];
|
|
410
|
+
let diskAdditions = 0;
|
|
411
|
+
let diskDeletions = 0;
|
|
412
|
+
let fromLastCommit = false;
|
|
413
|
+
if (abs) {
|
|
414
|
+
try {
|
|
415
|
+
const st = fs.lstatSync(abs);
|
|
416
|
+
if (!st.isSymbolicLink() && st.isFile()) {
|
|
417
|
+
existsOnDisk = true;
|
|
418
|
+
diskSize = st.size;
|
|
419
|
+
if (isGit && (!ev || ev.hunks.length === 0)) {
|
|
420
|
+
const commitDiff = readLastGitCommitDiffForFile(workspaceRoot, rel);
|
|
421
|
+
if (commitDiff) {
|
|
422
|
+
diskHunks = commitDiff.hunks;
|
|
423
|
+
diskAdditions = commitDiff.additions;
|
|
424
|
+
diskDeletions = commitDiff.deletions;
|
|
425
|
+
fromLastCommit = true;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (diskHunks.length === 0 && st.size > 0 && st.size <= 48 * 1024 && (!ev || ev.hunks.length === 0)) {
|
|
429
|
+
const buf = fs.readFileSync(abs);
|
|
430
|
+
if (!buf.includes(0)) {
|
|
431
|
+
const synth = buildSynthesizedWriteHunk(buf.toString('utf8'));
|
|
432
|
+
diskHunks = synth.hunks;
|
|
433
|
+
diskAdditions = synth.additions;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
} catch {
|
|
438
|
+
existsOnDisk = false;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const hunks = ev && ev.hunks.length > 0 ? ev.hunks : diskHunks;
|
|
442
|
+
const additions = ev && ev.additions > 0 ? ev.additions : diskAdditions;
|
|
443
|
+
const deletions = ev && ev.deletions > 0 ? ev.deletions : diskDeletions;
|
|
444
|
+
const status = fromLastCommit && diskDeletions > 0
|
|
445
|
+
? 'modified'
|
|
446
|
+
: (ev?.status ?? (existsOnDisk ? 'modified' : 'added'));
|
|
447
|
+
let note: string | undefined;
|
|
448
|
+
if (existsOnDisk) {
|
|
449
|
+
if (fromLastCommit) {
|
|
450
|
+
note = 'Latest committed diff on disk';
|
|
451
|
+
} else if (hunks.length === 0) {
|
|
452
|
+
note = diskSize > 0
|
|
453
|
+
? `On disk (${formatByteSize(diskSize)}) · ${isGit ? 'committed or binary asset' : 'workspace file'}`
|
|
454
|
+
: (isGit ? 'Clean on disk' : 'Touched in this conversation');
|
|
455
|
+
}
|
|
456
|
+
} else {
|
|
457
|
+
const sizeLabel = ev?.bytesWritten ? ` (${formatByteSize(ev.bytesWritten)})` : '';
|
|
458
|
+
note = `Written in this chat${sizeLabel} · no longer on disk`;
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
path: rel,
|
|
462
|
+
status,
|
|
463
|
+
additions,
|
|
464
|
+
deletions,
|
|
465
|
+
inGitDiff: false,
|
|
466
|
+
existsOnDisk,
|
|
467
|
+
note,
|
|
468
|
+
hunks
|
|
469
|
+
};
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
try {
|
|
473
|
+
const report = collectWorkingTreeDiff(workspaceRoot, { staged });
|
|
474
|
+
const mappedWorkspaceFiles = report.files.slice(0, 60).map((f) => {
|
|
475
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, f.displayPath);
|
|
476
|
+
let existsOnDisk = f.status !== 'deleted';
|
|
477
|
+
let note: string | undefined;
|
|
478
|
+
if (abs && f.hunks.length === 0 && f.status !== 'deleted') {
|
|
479
|
+
try {
|
|
480
|
+
const st = fs.lstatSync(abs);
|
|
481
|
+
existsOnDisk = st.isFile();
|
|
482
|
+
if (existsOnDisk) note = `Binary or large asset (${formatByteSize(st.size)})`;
|
|
483
|
+
} catch {
|
|
484
|
+
existsOnDisk = false;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
path: f.displayPath,
|
|
489
|
+
status: f.status,
|
|
490
|
+
additions: f.additions,
|
|
491
|
+
deletions: f.deletions,
|
|
492
|
+
inGitDiff: true,
|
|
493
|
+
existsOnDisk,
|
|
494
|
+
note,
|
|
495
|
+
hunks: f.hunks.slice(0, 20).map((h) => ({
|
|
496
|
+
header: h.header,
|
|
497
|
+
lines: h.lines.slice(0, 200)
|
|
498
|
+
}))
|
|
499
|
+
};
|
|
500
|
+
});
|
|
501
|
+
const matchedSessionGitFiles = mappedWorkspaceFiles.filter((f) => sessionEvidenceMap.has(f.path));
|
|
502
|
+
const matchedPaths = new Set(matchedSessionGitFiles.map((f) => f.path));
|
|
503
|
+
const extraSessionFiles = [...sessionEvidenceMap.keys()]
|
|
504
|
+
.sort()
|
|
505
|
+
.filter((rel) => !matchedPaths.has(rel))
|
|
506
|
+
.map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), true));
|
|
507
|
+
const sessionFiles = [...matchedSessionGitFiles, ...extraSessionFiles];
|
|
508
|
+
const returnedFiles = scope === 'session' ? sessionFiles : mappedWorkspaceFiles;
|
|
509
|
+
const totalAdditions = scope === 'session'
|
|
510
|
+
? returnedFiles.reduce((sum, f) => sum + f.additions, 0)
|
|
511
|
+
: report.totalAdditions;
|
|
512
|
+
const totalDeletions = scope === 'session'
|
|
513
|
+
? returnedFiles.reduce((sum, f) => sum + f.deletions, 0)
|
|
514
|
+
: report.totalDeletions;
|
|
515
|
+
sendJson(res, 200, {
|
|
516
|
+
ok: true,
|
|
517
|
+
isGitRepo: true,
|
|
518
|
+
scope,
|
|
519
|
+
sessionId: sessionId || null,
|
|
520
|
+
staged: report.staged,
|
|
521
|
+
workspaceFileCount: mappedWorkspaceFiles.length,
|
|
522
|
+
sessionFileCount: sessionFiles.length,
|
|
523
|
+
totalAdditions,
|
|
524
|
+
totalDeletions,
|
|
525
|
+
truncated: report.truncated,
|
|
526
|
+
files: returnedFiles
|
|
527
|
+
});
|
|
528
|
+
} catch {
|
|
529
|
+
const fallbackSessionFiles = [...sessionEvidenceMap.keys()]
|
|
530
|
+
.sort()
|
|
531
|
+
.map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), false));
|
|
532
|
+
sendJson(res, 200, {
|
|
533
|
+
ok: true,
|
|
534
|
+
isGitRepo: false,
|
|
535
|
+
scope,
|
|
536
|
+
sessionId: sessionId || null,
|
|
537
|
+
staged,
|
|
538
|
+
workspaceFileCount: 0,
|
|
539
|
+
sessionFileCount: fallbackSessionFiles.length,
|
|
540
|
+
totalAdditions: fallbackSessionFiles.reduce((sum, f) => sum + f.additions, 0),
|
|
541
|
+
totalDeletions: fallbackSessionFiles.reduce((sum, f) => sum + f.deletions, 0),
|
|
542
|
+
truncated: false,
|
|
543
|
+
files: scope === 'session' ? fallbackSessionFiles : []
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
export const MAX_JSON_BODY_BYTES = 1024 * 1024;
|
|
3
|
+
export const SAFE_SESSION_ID_RE = /^s_[a-zA-Z0-9_-]{3,80}$/;
|
|
4
|
+
export const SAFE_PROVIDER_RE = /^[a-zA-Z0-9._/-]{1,64}$/;
|
|
5
|
+
export const SAFE_MODEL_RE = /^[a-zA-Z0-9._/:()+ -]{1,128}$/;
|
|
6
|
+
const ALLOWED_REMOTE_ORIGINS = new Set(['https://causyne.com', 'https://www.causyne.com']);
|
|
7
|
+
export function isAllowedSkybridgeHost(hostHeader, port) {
|
|
8
|
+
if (!hostHeader || typeof hostHeader !== 'string')
|
|
9
|
+
return false;
|
|
10
|
+
const normalized = hostHeader.trim().toLowerCase();
|
|
11
|
+
return normalized === `127.0.0.1:${port}`
|
|
12
|
+
|| normalized === `localhost:${port}`
|
|
13
|
+
|| normalized === `[::1]:${port}`;
|
|
14
|
+
}
|
|
15
|
+
export function isAllowedSkybridgeOrigin(originHeader, port, extraOrigins = []) {
|
|
16
|
+
if (!originHeader || typeof originHeader !== 'string')
|
|
17
|
+
return true;
|
|
18
|
+
const trimmed = originHeader.trim();
|
|
19
|
+
if (!trimmed || trimmed === 'null')
|
|
20
|
+
return false;
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = new URL(trimmed);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
const canonical = parsed.origin.toLowerCase();
|
|
29
|
+
if (canonical === `http://127.0.0.1:${port}` || canonical === `http://localhost:${port}`) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (ALLOWED_REMOTE_ORIGINS.has(canonical))
|
|
33
|
+
return true;
|
|
34
|
+
for (const extra of extraOrigins) {
|
|
35
|
+
try {
|
|
36
|
+
const parsedExtra = new URL(extra);
|
|
37
|
+
if (parsedExtra.protocol === 'https:' && parsedExtra.origin.toLowerCase() === canonical) {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// ignore invalid extra origin
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
export function timingSafeBearerMatch(authHeader, expectedToken) {
|
|
48
|
+
if (!authHeader || typeof authHeader !== 'string')
|
|
49
|
+
return false;
|
|
50
|
+
const prefix = 'Bearer ';
|
|
51
|
+
if (!authHeader.startsWith(prefix))
|
|
52
|
+
return false;
|
|
53
|
+
const supplied = authHeader.slice(prefix.length).trim();
|
|
54
|
+
const a = Buffer.from(supplied, 'utf8');
|
|
55
|
+
const b = Buffer.from(expectedToken, 'utf8');
|
|
56
|
+
if (a.length !== b.length || a.length === 0)
|
|
57
|
+
return false;
|
|
58
|
+
return crypto.timingSafeEqual(a, b);
|
|
59
|
+
}
|
|
60
|
+
export function applySecurityHeaders(res, originHeader, originAllowed) {
|
|
61
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
62
|
+
res.setHeader('X-Frame-Options', 'DENY');
|
|
63
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
64
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
65
|
+
if (originHeader && originAllowed) {
|
|
66
|
+
res.setHeader('Access-Control-Allow-Origin', originHeader);
|
|
67
|
+
res.setHeader('Access-Control-Allow-Private-Network', 'true');
|
|
68
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
|
|
69
|
+
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
|
|
70
|
+
res.setHeader('Vary', 'Origin, Access-Control-Request-Private-Network');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function sendJson(res, status, payload) {
|
|
74
|
+
const body = JSON.stringify(payload);
|
|
75
|
+
res.statusCode = status;
|
|
76
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
77
|
+
res.end(body);
|
|
78
|
+
}
|
|
79
|
+
export async function readJsonBody(req, maxBytes = MAX_JSON_BODY_BYTES) {
|
|
80
|
+
const chunks = [];
|
|
81
|
+
let total = 0;
|
|
82
|
+
for await (const chunk of req) {
|
|
83
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
84
|
+
total += buf.length;
|
|
85
|
+
if (total > maxBytes) {
|
|
86
|
+
throw new Error('Request body exceeded maximum allowed size.');
|
|
87
|
+
}
|
|
88
|
+
chunks.push(buf);
|
|
89
|
+
}
|
|
90
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
91
|
+
if (!text)
|
|
92
|
+
return {};
|
|
93
|
+
const parsed = JSON.parse(text);
|
|
94
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
95
|
+
throw new Error('JSON request body must be an object.');
|
|
96
|
+
}
|
|
97
|
+
return parsed;
|
|
98
|
+
}
|