arco-workbench 0.1.8 → 0.1.9
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/CONTRIBUTING.md +11 -0
- package/README.md +7 -5
- package/client/dist/assets/{PhosphorBackdrop-D7jdAV_G.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-DrDm60h8.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
- package/client/dist/assets/{XtermView-BGFujb1e.js → XtermView-Xk7_9JaH.js} +1 -1
- package/client/dist/assets/{galleryEditor-D951A2sE.js → galleryEditor-CI8ClzBa.js} +1 -1
- package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
- package/client/dist/assets/{index-CsVy3eZm.js → index-C7WzZfsr.js} +246 -244
- package/client/dist/index.html +2 -2
- package/client/src/App.tsx +2 -0
- package/client/src/components/ChatMessage.tsx +33 -8
- package/client/src/components/ChatModeView.tsx +2 -0
- package/client/src/components/ClusterRightPanel/SkillsControl.tsx +25 -8
- package/client/src/components/CodexLateCommand.tsx +34 -0
- package/client/src/components/DialogShell.tsx +2 -0
- package/client/src/components/MemberCard.tsx +4 -1
- package/client/src/components/MemberPane.tsx +3 -1
- package/client/src/components/PhoneUpload.tsx +288 -0
- package/client/src/components/PrimaryStatus.tsx +14 -6
- package/client/src/components/RuntimeStateBanner.tsx +5 -0
- package/client/src/components/SkillEditorDialog.tsx +2 -2
- package/client/src/components/SkillsSettings.tsx +17 -5
- package/client/src/components/TerminalInput.tsx +3 -1
- package/client/src/components/WorkflowView.tsx +2 -0
- package/client/src/explorer/ArtifactsLens.tsx +37 -28
- package/client/src/explorer/ExplorerApp.tsx +5 -4
- package/client/src/explorer/types.ts +8 -3
- package/client/src/help/content/cluster.tsx +11 -1
- package/client/src/help/content/composer.tsx +18 -1
- package/client/src/help/content/header.tsx +2 -1
- package/client/src/help/content/misc.tsx +1 -1
- package/client/src/help/content/settings.tsx +1 -1
- package/client/src/help/manualSections/clusters.tsx +3 -0
- package/client/src/help/manualSections/configuration.tsx +3 -1
- package/client/src/help/manualSections/gettingStarted.tsx +4 -4
- package/client/src/help/manualSections/maintenance.tsx +7 -6
- package/client/src/help/manualSections/powerFeatures.tsx +3 -2
- package/client/src/help/manualSections/workspace.tsx +30 -0
- package/client/src/stores/appStore.ts +7 -0
- package/client/src/stores/appStore.types.ts +4 -0
- package/client/src/styles/global.css +109 -0
- package/client/src/utils/phoneTheme.ts +38 -0
- package/client/src/utils/phoneUploadApi.ts +10 -0
- package/client/src/ws/handleServerMessage.ts +23 -6
- package/docs/CLIENT.md +7 -1
- package/docs/FEATURES.md +6 -3
- package/docs/GETTING_STARTED.md +8 -3
- package/docs/INDEX.md +1 -1
- package/docs/OPERATIONS.md +199 -48
- package/docs/PROTOCOL_CLUSTER.md +9 -1
- package/docs/PROVIDERS.md +34 -0
- package/docs/SETTINGS.md +5 -3
- package/native/darwin-arm64/manifest.json +1 -1
- package/native/linux-x64/manifest.json +1 -1
- package/native/win32-x64/manifest.json +1 -1
- package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -0
- package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +11 -0
- package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/server/dist/clusterDirector.js +1 -0
- package/server/dist/clusterPeerOps.js +4 -1
- package/server/dist/clusterRehydrate.js +2 -0
- package/server/dist/explorerDocs.d.ts +10 -6
- package/server/dist/explorerDocs.js +75 -34
- package/server/dist/http/attachmentUpload.d.ts +13 -0
- package/server/dist/http/attachmentUpload.js +38 -0
- package/server/dist/http/browserWorktrees.d.ts +23 -0
- package/server/dist/http/browserWorktrees.js +120 -0
- package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
- package/server/dist/http/phoneUploadDrafts.js +125 -0
- package/server/dist/http/phoneUploadListener.d.ts +17 -0
- package/server/dist/http/phoneUploadListener.js +81 -0
- package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
- package/server/dist/http/phoneUploadNetwork.js +106 -0
- package/server/dist/http/phoneUploadPage.d.ts +2 -0
- package/server/dist/http/phoneUploadPage.js +136 -0
- package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
- package/server/dist/http/phoneUploadRouteHistory.js +72 -0
- package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
- package/server/dist/http/phoneUploadRoutes.js +419 -0
- package/server/dist/http/phoneUploadTheme.d.ts +17 -0
- package/server/dist/http/phoneUploadTheme.js +96 -0
- package/server/dist/http/projectBinding.d.ts +1 -0
- package/server/dist/http/projectBinding.js +3 -2
- package/server/dist/http/readConfinement.js +5 -1
- package/server/dist/http/router.js +13 -24
- package/server/dist/http/writeConfinement.js +19 -2
- package/server/dist/primitives/seedWorker.d.ts +1 -0
- package/server/dist/primitives/seedWorker.js +2 -1
- package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
- package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
- package/server/dist/providers/codex-appserver/index.d.ts +52 -2
- package/server/dist/providers/codex-appserver/index.js +239 -21
- package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
- package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
- package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
- package/server/dist/providers/codex-appserver/worker.js +89 -20
- package/server/dist/providers/codex.js +2 -2
- package/server/dist/providers/codexCodeMode.d.ts +2 -1
- package/server/dist/providers/codexCodeMode.js +7 -3
- package/server/dist/workers/WorkerManager.d.ts +1 -0
- package/server/dist/workers/WorkerManager.js +1 -0
- package/server/dist/workers/processKill.d.ts +9 -1
- package/server/dist/workers/processKill.js +26 -10
- package/server/dist/ws/handoffHandlers.js +2 -0
- package/server/dist/ws/turnEngine.js +17 -0
- package/server/package.json +1 -1
- package/server/src/clusterDirector.ts +1 -0
- package/server/src/clusterPeerOps.ts +4 -1
- package/server/src/clusterRehydrate.ts +2 -0
- package/server/src/explorerDocs.ts +75 -34
- package/server/src/http/attachmentUpload.ts +49 -0
- package/server/src/http/browserWorktrees.ts +124 -0
- package/server/src/http/phoneUploadDrafts.ts +118 -0
- package/server/src/http/phoneUploadListener.ts +96 -0
- package/server/src/http/phoneUploadNetwork.ts +117 -0
- package/server/src/http/phoneUploadPage.ts +137 -0
- package/server/src/http/phoneUploadRouteHistory.ts +73 -0
- package/server/src/http/phoneUploadRoutes.ts +398 -0
- package/server/src/http/phoneUploadTheme.ts +97 -0
- package/server/src/http/projectBinding.ts +3 -2
- package/server/src/http/readConfinement.ts +5 -1
- package/server/src/http/router.ts +11 -25
- package/server/src/http/writeConfinement.ts +13 -2
- package/server/src/primitives/seedWorker.ts +3 -1
- package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
- package/server/src/providers/codex-appserver/index.ts +222 -20
- package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
- package/server/src/providers/codex-appserver/worker.ts +85 -21
- package/server/src/providers/codex.ts +2 -2
- package/server/src/providers/codexCodeMode.ts +8 -3
- package/server/src/workers/WorkerManager.ts +2 -0
- package/server/src/workers/processKill.ts +35 -7
- package/server/src/ws/handoffHandlers.ts +2 -0
- package/server/src/ws/turnEngine.ts +15 -0
- package/shared/dist/protocol/chat.d.ts +1 -0
- package/shared/dist/protocol/clusters.d.ts +2 -0
- package/shared/dist/protocol/serverMessages.d.ts +11 -0
- package/shared/dist/protocol/workflows.d.ts +1 -0
- package/shared/src/protocol/chat.ts +1 -0
- package/shared/src/protocol/clusters.ts +4 -5
- package/shared/src/protocol/serverMessages.ts +11 -0
- package/shared/src/protocol/workflows.ts +4 -0
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { extname } from 'node:path';
|
|
3
|
+
import { unzipSync } from 'fflate';
|
|
4
|
+
import * as clusterStore from '../clusterStore.js';
|
|
5
|
+
import { fileHeaderKind } from '../fileContent/detect.js';
|
|
6
|
+
import { awaitModelImage } from '../providers/attachments.js';
|
|
7
|
+
import { PORT, UUID_PATTERN } from '../server/constants.js';
|
|
8
|
+
import { workflows } from '../server/state.js';
|
|
9
|
+
import { managedUploadPath } from '../uploadImages.js';
|
|
10
|
+
import { readAttachmentBody, storeAttachment, UploadTooLarge } from './attachmentUpload.js';
|
|
11
|
+
import { readFileForExplorer } from './fileRead.js';
|
|
12
|
+
import { discardPhoneDraft, phoneDraftForOwner, phoneFilename, rememberPhoneDraft, PHONE_DRAFT_TTL_MS } from './phoneUploadDrafts.js';
|
|
13
|
+
import { phoneListenerAddresses, phoneUploadOrigins, privatePhoneOrigin } from './phoneUploadNetwork.js';
|
|
14
|
+
import { startPhoneListener } from './phoneUploadListener.js';
|
|
15
|
+
import { recordRouteSuccess, routeSuccesses } from './phoneUploadRouteHistory.js';
|
|
16
|
+
import { checkRequestOrigin } from './originGuard.js';
|
|
17
|
+
import { PHONE_PAGE, PHONE_PAGE_CSP } from './phoneUploadPage.js';
|
|
18
|
+
import { bundledPhoneFont, checkedPhoneTheme } from './phoneUploadTheme.js';
|
|
19
|
+
import { readCookie, SESSION_COOKIE, verifyToken } from './wsAuth.js';
|
|
20
|
+
const PHONE_PATH = '/phone-upload';
|
|
21
|
+
const API_PATH = '/api/phone-upload';
|
|
22
|
+
const UNAVAILABLE = 'Phone upload is unavailable. Open Arco on your private network first.';
|
|
23
|
+
const NO_PRIVATE_ADDRESS = 'Phone upload is unavailable. This computer has no private network or tailnet address a phone can reach. Connect it to Wi-Fi, a wired network or Tailscale, then try again.';
|
|
24
|
+
const NOT_LISTENING = 'Phone upload is unavailable. Arco could not accept connections on this computer\'s private network address. Try again; if it keeps failing, the Arco log has a line with the error code.';
|
|
25
|
+
const CLOSED = 'This link is closed or expired. Open a new code in Arco.';
|
|
26
|
+
const MIB = 1024 * 1024;
|
|
27
|
+
const FILE_LIMIT = 20 * MIB;
|
|
28
|
+
const LINK_LIMIT = 100 * MIB;
|
|
29
|
+
const COUNT_LIMIT = 10;
|
|
30
|
+
const LINK_TTL_MS = 5 * 60_000;
|
|
31
|
+
const MAX_OPEN_LINKS = 8;
|
|
32
|
+
const MAX_TRANSFERS = 2;
|
|
33
|
+
// The temporary phone listener stays open this long after the last request
|
|
34
|
+
// for a code, so a choice between several addresses finds it still there.
|
|
35
|
+
const LISTENER_GRACE_MS = 60_000;
|
|
36
|
+
const links = new Map();
|
|
37
|
+
const tokens = new Map();
|
|
38
|
+
let transfers = 0;
|
|
39
|
+
let phoneListener = null;
|
|
40
|
+
let openingCodes = 0;
|
|
41
|
+
let listenerGraceUntil = 0;
|
|
42
|
+
const digest = (s) => createHash('sha256').update(s).digest('hex');
|
|
43
|
+
function json(res, status, body) {
|
|
44
|
+
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
45
|
+
res.end(JSON.stringify(body));
|
|
46
|
+
}
|
|
47
|
+
function error(res, status, message) {
|
|
48
|
+
json(res, status, { error: message });
|
|
49
|
+
}
|
|
50
|
+
function targetAvailable(id, wf) {
|
|
51
|
+
if (!wf?.config.workingDirectory || wf.config.incognito)
|
|
52
|
+
return false;
|
|
53
|
+
const cluster = clusterStore.getClusterIdForWorkflow(id);
|
|
54
|
+
return !cluster || clusterStore.getMemberAccessMode(cluster, id) !== 'isolated';
|
|
55
|
+
}
|
|
56
|
+
function closeLink(link) {
|
|
57
|
+
link.closed = true;
|
|
58
|
+
tokens.delete(link.key);
|
|
59
|
+
}
|
|
60
|
+
function active(link) {
|
|
61
|
+
const wf = workflows.get(link.workflowId);
|
|
62
|
+
if (link.closed || link.expiresAt <= Date.now() || wf !== link.workflow
|
|
63
|
+
|| !targetAvailable(link.workflowId, wf) || wf.config.workingDirectory !== link.cwd) {
|
|
64
|
+
closeLink(link);
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
function purgeLinks() {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
for (const [id, link] of links) {
|
|
72
|
+
active(link);
|
|
73
|
+
if (!link.transferring && link.expiresAt + 60_000 <= now)
|
|
74
|
+
links.delete(id);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// The temporary listener closes only when no code is being opened, no upload
|
|
78
|
+
// is in progress, no link is still open and the grace time has passed.
|
|
79
|
+
function releasePhoneListener() {
|
|
80
|
+
if (!phoneListener || openingCodes > 0 || transfers > 0 || Date.now() < listenerGraceUntil)
|
|
81
|
+
return;
|
|
82
|
+
if ([...tokens.values()].some(link => active(link)))
|
|
83
|
+
return;
|
|
84
|
+
const closing = phoneListener;
|
|
85
|
+
phoneListener = null;
|
|
86
|
+
void closing.then(listener => listener.close());
|
|
87
|
+
}
|
|
88
|
+
setInterval(() => { purgeLinks(); releasePhoneListener(); }, 30_000).unref();
|
|
89
|
+
export async function _closePhoneListenerForTest() {
|
|
90
|
+
const closing = phoneListener;
|
|
91
|
+
phoneListener = null;
|
|
92
|
+
(await closing)?.close();
|
|
93
|
+
}
|
|
94
|
+
// The temporary listener's only route: the same Host and Origin precheck as
|
|
95
|
+
// the main router, then the phone page and its upload endpoint.
|
|
96
|
+
async function phoneOnly(req, res) {
|
|
97
|
+
if (!checkRequestOrigin(req).ok)
|
|
98
|
+
return error(res, 403, 'Forbidden origin');
|
|
99
|
+
await tryHandlePhonePage(req, res);
|
|
100
|
+
}
|
|
101
|
+
// When the main server serves no private address (the default loopback
|
|
102
|
+
// bind), open the temporary phone listener on this machine's private network
|
|
103
|
+
// and tailnet addresses, or reuse the one already open.
|
|
104
|
+
async function temporaryOrigins(port) {
|
|
105
|
+
listenerGraceUntil = Date.now() + LISTENER_GRACE_MS;
|
|
106
|
+
if (!phoneListener) {
|
|
107
|
+
const addresses = phoneListenerAddresses();
|
|
108
|
+
if (!addresses.length)
|
|
109
|
+
return { origins: [], error: NO_PRIVATE_ADDRESS };
|
|
110
|
+
phoneListener = startPhoneListener(addresses, port, phoneOnly);
|
|
111
|
+
}
|
|
112
|
+
const current = phoneListener;
|
|
113
|
+
const { origins } = await current;
|
|
114
|
+
if (origins.length)
|
|
115
|
+
return { origins };
|
|
116
|
+
if (phoneListener === current)
|
|
117
|
+
phoneListener = null;
|
|
118
|
+
return { origins, error: NOT_LISTENING };
|
|
119
|
+
}
|
|
120
|
+
const imageExtensions = {
|
|
121
|
+
'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp',
|
|
122
|
+
'image/avif': '.avif', 'image/heic': '.heic', 'image/tiff': '.tiff', 'image/bmp': '.bmp', 'image/x-icon': '.ico',
|
|
123
|
+
};
|
|
124
|
+
function officeDocument(ext, bytes) {
|
|
125
|
+
const required = {
|
|
126
|
+
'.docx': 'word/document.xml', '.xlsx': 'xl/workbook.xml', '.pptx': 'ppt/presentation.xml',
|
|
127
|
+
'.odt': 'content.xml', '.ods': 'content.xml', '.odp': 'content.xml',
|
|
128
|
+
};
|
|
129
|
+
if (!required[ext])
|
|
130
|
+
return false;
|
|
131
|
+
let containsDocument = false;
|
|
132
|
+
let containsActivePart = false;
|
|
133
|
+
try {
|
|
134
|
+
const parts = unzipSync(bytes, { filter: (file) => {
|
|
135
|
+
if (file.name === required[ext])
|
|
136
|
+
containsDocument = true;
|
|
137
|
+
if (/vbaProject|^Scripts\/|^Basic\//i.test(file.name))
|
|
138
|
+
containsActivePart = true;
|
|
139
|
+
return file.name === 'mimetype' && file.originalSize <= 128 && /^\.od/.test(ext);
|
|
140
|
+
} });
|
|
141
|
+
if (!containsDocument || containsActivePart)
|
|
142
|
+
return false;
|
|
143
|
+
if (!/^\.od/.test(ext))
|
|
144
|
+
return true;
|
|
145
|
+
const kind = { '.odt': 'text', '.ods': 'spreadsheet', '.odp': 'presentation' };
|
|
146
|
+
return !!parts.mimetype && Buffer.from(parts.mimetype).toString() === 'application/vnd.oasis.opendocument.' + kind[ext];
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function checkedFilename(req, bytes) {
|
|
153
|
+
const supplied = req.headers['x-filename'];
|
|
154
|
+
if (typeof supplied !== 'string' || supplied.length > 1024)
|
|
155
|
+
return null;
|
|
156
|
+
let filename;
|
|
157
|
+
try {
|
|
158
|
+
filename = phoneFilename(decodeURIComponent(supplied));
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
if (!filename)
|
|
164
|
+
return null;
|
|
165
|
+
const ext = extname(filename).toLowerCase();
|
|
166
|
+
const content = fileHeaderKind(bytes);
|
|
167
|
+
const detectedExtension = imageExtensions[content];
|
|
168
|
+
if (detectedExtension) {
|
|
169
|
+
const alternates = detectedExtension === '.jpg' ? ['.jpeg'] : detectedExtension === '.heic' ? ['.heif']
|
|
170
|
+
: detectedExtension === '.tiff' ? ['.tif'] : [];
|
|
171
|
+
if (!ext)
|
|
172
|
+
filename += detectedExtension;
|
|
173
|
+
else if (ext !== detectedExtension && !alternates.includes(ext))
|
|
174
|
+
return null;
|
|
175
|
+
return phoneFilename(filename) || null;
|
|
176
|
+
}
|
|
177
|
+
if ((ext === '.pdf' && content === 'application/pdf') || (ext === '.rtf' && content === 'application/rtf')
|
|
178
|
+
|| (['.txt', '.md', '.csv'].includes(ext) && content === 'text/plain')
|
|
179
|
+
|| (content === 'application/zip' && officeDocument(ext, bytes))) {
|
|
180
|
+
return filename;
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
async function uploadFromPhone(req, res, origin) {
|
|
185
|
+
const token = req.headers['x-arco-phone-upload'];
|
|
186
|
+
if (req.headers.origin !== origin || typeof token !== 'string' || !/^[\w-]{43}$/.test(token)) {
|
|
187
|
+
return error(res, 403, 'Open the upload page from the QR code.');
|
|
188
|
+
}
|
|
189
|
+
const link = tokens.get(digest(token));
|
|
190
|
+
if (!link || !active(link))
|
|
191
|
+
return error(res, 410, CLOSED);
|
|
192
|
+
if (link.origin !== origin)
|
|
193
|
+
return error(res, 403, UNAVAILABLE);
|
|
194
|
+
if (link.transferring || transfers >= MAX_TRANSFERS)
|
|
195
|
+
return error(res, 429, 'Another upload is in progress. Try again shortly.');
|
|
196
|
+
if (link.files.length >= COUNT_LIMIT || link.receivedBytes >= LINK_LIMIT) {
|
|
197
|
+
return error(res, 413, 'This link has reached its file limit. Open a new code for more files.');
|
|
198
|
+
}
|
|
199
|
+
const limit = Math.min(FILE_LIMIT, LINK_LIMIT - link.receivedBytes);
|
|
200
|
+
const remaining = link.expiresAt - Date.now();
|
|
201
|
+
const timer = setTimeout(() => req.destroy(), remaining);
|
|
202
|
+
timer.unref();
|
|
203
|
+
link.transferring = true;
|
|
204
|
+
transfers++;
|
|
205
|
+
let draft;
|
|
206
|
+
try {
|
|
207
|
+
if (Number(req.headers['content-length']) > limit)
|
|
208
|
+
throw new UploadTooLarge();
|
|
209
|
+
const body = await readAttachmentBody(req, limit);
|
|
210
|
+
if (!active(link))
|
|
211
|
+
return error(res, 410, CLOSED);
|
|
212
|
+
if (!body.length)
|
|
213
|
+
return error(res, 400, 'The file is empty.');
|
|
214
|
+
link.receivedBytes += body.length;
|
|
215
|
+
const checked = checkedFilename(req, body);
|
|
216
|
+
if (!checked)
|
|
217
|
+
return error(res, 415, 'Choose a supported photo, PDF, text or office document.');
|
|
218
|
+
const fileId = randomUUID();
|
|
219
|
+
await storeAttachment(body, checked, '', {
|
|
220
|
+
fileId,
|
|
221
|
+
beforeWrite: async (file) => {
|
|
222
|
+
draft = { ...file, workflowId: link.workflowId, owner: link.owner, expiresAt: Date.now() + PHONE_DRAFT_TTL_MS };
|
|
223
|
+
await rememberPhoneDraft(draft);
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
if (!draft)
|
|
227
|
+
throw new Error('Missing draft receipt');
|
|
228
|
+
if (!active(link)) {
|
|
229
|
+
await discardPhoneDraft(draft);
|
|
230
|
+
return error(res, 410, CLOSED);
|
|
231
|
+
}
|
|
232
|
+
link.files.push(draft);
|
|
233
|
+
// The route worked: remember it. Saving happens in the background and a
|
|
234
|
+
// failure there never turns this successful upload into an error.
|
|
235
|
+
void recordRouteSuccess(link.origin);
|
|
236
|
+
json(res, 201, { ok: true });
|
|
237
|
+
}
|
|
238
|
+
catch (e) {
|
|
239
|
+
if (draft)
|
|
240
|
+
await discardPhoneDraft(draft).catch(() => { });
|
|
241
|
+
if (res.destroyed)
|
|
242
|
+
return;
|
|
243
|
+
if (e instanceof UploadTooLarge) {
|
|
244
|
+
res.setHeader('Connection', 'close');
|
|
245
|
+
error(res, 413, 'This file is too large for the remaining upload allowance.');
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
error(res, 500, 'Upload failed. Try again from the phone.');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
link.transferring = false;
|
|
254
|
+
transfers--;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// Opens one upload link on a chosen address, or lists the addresses to
|
|
258
|
+
// choose from when there are several. Synchronous, so a temporary listener
|
|
259
|
+
// cannot close between its origins being read and the link being recorded.
|
|
260
|
+
function createLink(res, body, workflow, owner, origins) {
|
|
261
|
+
const origin = body.origin ?? (origins.length === 1 ? origins[0] : undefined);
|
|
262
|
+
if (!origin) {
|
|
263
|
+
json(res, 200, { origins, verified: routeSuccesses(origins) });
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
if (!origins.includes(origin)) {
|
|
267
|
+
error(res, 403, UNAVAILABLE);
|
|
268
|
+
return true;
|
|
269
|
+
}
|
|
270
|
+
if (tokens.size >= MAX_OPEN_LINKS || links.size >= 4 * MAX_OPEN_LINKS) {
|
|
271
|
+
error(res, 429, 'Too many phone upload links. Wait for one to expire.');
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
const token = randomBytes(32).toString('base64url');
|
|
275
|
+
const link = {
|
|
276
|
+
id: randomUUID(), key: digest(token), owner, workflowId: body.workflowId, workflow,
|
|
277
|
+
cwd: workflow.config.workingDirectory, origin, expiresAt: Date.now() + LINK_TTL_MS,
|
|
278
|
+
files: [], receivedBytes: 0, closed: false, transferring: false, theme: checkedPhoneTheme(body.theme),
|
|
279
|
+
};
|
|
280
|
+
links.set(link.id, link);
|
|
281
|
+
tokens.set(link.key, link);
|
|
282
|
+
json(res, 201, {
|
|
283
|
+
id: link.id, url: origin + PHONE_PATH + '#' + token, expiresAt: link.expiresAt,
|
|
284
|
+
verifiedAt: routeSuccesses([origin])[origin],
|
|
285
|
+
});
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
// What the phone page reads with its token: the theme snapshot taken when
|
|
289
|
+
// the code was opened, or one bundled font that theme names. Nothing else.
|
|
290
|
+
async function phoneResource(req, res, origin) {
|
|
291
|
+
const token = req.headers['x-arco-phone-upload'];
|
|
292
|
+
if (typeof token !== 'string' || !/^[\w-]{43}$/.test(token))
|
|
293
|
+
return error(res, 403, 'Open the upload page from the QR code.');
|
|
294
|
+
const link = tokens.get(digest(token));
|
|
295
|
+
if (!link || !active(link))
|
|
296
|
+
return error(res, 410, CLOSED);
|
|
297
|
+
if (link.origin !== origin)
|
|
298
|
+
return error(res, 403, UNAVAILABLE);
|
|
299
|
+
const fontId = req.headers['x-arco-phone-font'];
|
|
300
|
+
if (fontId === undefined)
|
|
301
|
+
return json(res, 200, { theme: link.theme ?? null });
|
|
302
|
+
const font = typeof fontId === 'string' ? await bundledPhoneFont(link.theme, fontId) : null;
|
|
303
|
+
if (!font)
|
|
304
|
+
return error(res, 404, 'Not found.');
|
|
305
|
+
res.writeHead(200, { 'Content-Type': font.type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
306
|
+
res.end(font.bytes);
|
|
307
|
+
}
|
|
308
|
+
// This exact path has upload authority only. It is deliberately handled
|
|
309
|
+
// before operator session auth, with the same router Host/Origin precheck.
|
|
310
|
+
export async function tryHandlePhonePage(req, res) {
|
|
311
|
+
if (req.url !== PHONE_PATH)
|
|
312
|
+
return false;
|
|
313
|
+
const origin = privatePhoneOrigin(req);
|
|
314
|
+
if (!origin)
|
|
315
|
+
error(res, 403, UNAVAILABLE);
|
|
316
|
+
else if (req.method === 'POST')
|
|
317
|
+
await uploadFromPhone(req, res, origin);
|
|
318
|
+
else if (req.method === 'GET' && req.headers['x-arco-phone-upload'] !== undefined)
|
|
319
|
+
await phoneResource(req, res, origin);
|
|
320
|
+
else if (req.method === 'GET') {
|
|
321
|
+
res.writeHead(200, {
|
|
322
|
+
'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': PHONE_PAGE_CSP,
|
|
323
|
+
'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
|
|
324
|
+
});
|
|
325
|
+
res.end(PHONE_PAGE);
|
|
326
|
+
}
|
|
327
|
+
else
|
|
328
|
+
error(res, 405, 'Method not allowed.');
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
export async function tryHandlePhoneOperator(req, res) {
|
|
332
|
+
const path = req.url ?? '';
|
|
333
|
+
if (path !== API_PATH && !path.startsWith(API_PATH + '/'))
|
|
334
|
+
return false;
|
|
335
|
+
const cookie = readCookie(req, SESSION_COOKIE);
|
|
336
|
+
if (!cookie || !verifyToken(cookie)) {
|
|
337
|
+
error(res, 401, 'Session required.');
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
const ownerKey = req.headers['x-arco-phone-owner'];
|
|
341
|
+
if (typeof ownerKey !== 'string' || !/^[0-9a-f]{64}$/.test(ownerKey)) {
|
|
342
|
+
error(res, 403, 'Phone upload must be opened from the message box.');
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
const owner = digest(ownerKey);
|
|
346
|
+
try {
|
|
347
|
+
if (path === API_PATH && req.method === 'POST') {
|
|
348
|
+
purgeLinks();
|
|
349
|
+
const body = JSON.parse((await readAttachmentBody(req, 8192)).toString());
|
|
350
|
+
const workflow = typeof body?.workflowId === 'string' ? workflows.get(body.workflowId) : undefined;
|
|
351
|
+
if (!body?.workflowId || !targetAvailable(body.workflowId, workflow)) {
|
|
352
|
+
error(res, 409, 'This conversation does not accept attachments.');
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
let origins = phoneUploadOrigins(req);
|
|
356
|
+
if (!origins.length) {
|
|
357
|
+
openingCodes++;
|
|
358
|
+
try {
|
|
359
|
+
const opened = await temporaryOrigins(req.socket.localPort || PORT);
|
|
360
|
+
if (opened.error) {
|
|
361
|
+
error(res, 503, opened.error);
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
origins = opened.origins;
|
|
365
|
+
return createLink(res, { workflowId: body.workflowId, origin: body.origin, theme: body.theme }, workflow, owner, origins);
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
openingCodes--;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return createLink(res, { workflowId: body.workflowId, origin: body.origin, theme: body.theme }, workflow, owner, origins);
|
|
372
|
+
}
|
|
373
|
+
const id = path.slice(path.lastIndexOf('/') + 1);
|
|
374
|
+
if (!UUID_PATTERN.test(id)) {
|
|
375
|
+
error(res, 404, 'Phone upload not found.');
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
if (path === API_PATH + '/draft/' + id) {
|
|
379
|
+
const draft = phoneDraftForOwner(id, owner);
|
|
380
|
+
if (!draft)
|
|
381
|
+
error(res, 404, 'Phone attachment has expired.');
|
|
382
|
+
else if (req.method === 'DELETE') {
|
|
383
|
+
await discardPhoneDraft(draft);
|
|
384
|
+
json(res, 200, { ok: true });
|
|
385
|
+
}
|
|
386
|
+
else if (req.method === 'GET') {
|
|
387
|
+
const image = managedUploadPath(await awaitModelImage(draft.path));
|
|
388
|
+
const preview = image ? await readFileForExplorer(image) : null;
|
|
389
|
+
json(res, 200, { preview: preview?.type === 'image' ? preview.dataUrl : undefined });
|
|
390
|
+
}
|
|
391
|
+
else
|
|
392
|
+
error(res, 405, 'Method not allowed.');
|
|
393
|
+
return true;
|
|
394
|
+
}
|
|
395
|
+
const link = path === API_PATH + '/' + id ? links.get(id) : undefined;
|
|
396
|
+
if (!link || link.owner !== owner)
|
|
397
|
+
error(res, 404, 'Phone upload link not found.');
|
|
398
|
+
else if (req.method === 'GET' || req.method === 'DELETE') {
|
|
399
|
+
if (req.method === 'DELETE')
|
|
400
|
+
closeLink(link);
|
|
401
|
+
const closed = !active(link);
|
|
402
|
+
const files = link.files.filter(file => phoneDraftForOwner(file.fileId, owner))
|
|
403
|
+
.map(({ fileId, filename, path, expiresAt }) => ({ fileId, filename, path, expiresAt }));
|
|
404
|
+
if (req.method === 'DELETE')
|
|
405
|
+
links.delete(id);
|
|
406
|
+
json(res, 200, { files, closed, verifiedAt: routeSuccesses([link.origin])[link.origin] });
|
|
407
|
+
}
|
|
408
|
+
else
|
|
409
|
+
error(res, 405, 'Method not allowed.');
|
|
410
|
+
}
|
|
411
|
+
catch (e) {
|
|
412
|
+
if (e instanceof UploadTooLarge || e instanceof SyntaxError)
|
|
413
|
+
error(res, 400, 'Invalid phone upload request.');
|
|
414
|
+
else
|
|
415
|
+
error(res, 500, 'Phone upload failed.');
|
|
416
|
+
}
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
//# sourceMappingURL=phoneUploadRoutes.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const PHONE_THEME_COLORS: readonly ["color-bg", "color-bg-dialog", "color-fg", "color-fg-muted", "color-border", "color-accent-primary", "color-control-fg", "color-success", "color-error"];
|
|
2
|
+
export interface PhoneTheme {
|
|
3
|
+
vars: Record<string, string>;
|
|
4
|
+
scheme?: 'light' | 'dark';
|
|
5
|
+
fonts: {
|
|
6
|
+
id: string;
|
|
7
|
+
family: string;
|
|
8
|
+
weight: string;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
/** Keep only the values that pass their checks; undefined when none do. */
|
|
12
|
+
export declare function checkedPhoneTheme(input: unknown): PhoneTheme | undefined;
|
|
13
|
+
/** The bytes of one bundled font that the theme names, or null. */
|
|
14
|
+
export declare function bundledPhoneFont(theme: PhoneTheme | undefined, id: string): Promise<{
|
|
15
|
+
type: string;
|
|
16
|
+
bytes: Buffer;
|
|
17
|
+
} | null>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { PROJECT_ROOT } from '../server/constants.js';
|
|
4
|
+
// The look of the phone upload page: a snapshot of the Arco theme that was
|
|
5
|
+
// active on the computer when the code was opened. Only these fixed values
|
|
6
|
+
// are accepted, each checked against a strict form, so the phone page never
|
|
7
|
+
// receives CSS, HTML or a URL from the browser that sent them. A value that
|
|
8
|
+
// fails its check is dropped and the page keeps its plain default for it.
|
|
9
|
+
export const PHONE_THEME_COLORS = [
|
|
10
|
+
'color-bg', 'color-bg-dialog', 'color-fg', 'color-fg-muted', 'color-border',
|
|
11
|
+
'color-accent-primary', 'color-control-fg', 'color-success', 'color-error',
|
|
12
|
+
];
|
|
13
|
+
const LENGTHS = ['border-width', 'radius-sm'];
|
|
14
|
+
const FONTS = ['font-display', 'font-body'];
|
|
15
|
+
const GENERIC_FONTS = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-monospace', 'ui-sans-serif', 'ui-serif']);
|
|
16
|
+
// Fonts that ship inside Arco itself. The phone page may fetch these, and
|
|
17
|
+
// only these, through its own token-checked path. A theme font that the
|
|
18
|
+
// computer loads from the internet falls back to the phone's own fonts.
|
|
19
|
+
const BUNDLED_FONTS = {
|
|
20
|
+
'victor-mono-400': { family: 'Victor Mono', weight: '400', type: 'font/otf', file: 'themes/victor-mono/VictorMono-Regular.otf' },
|
|
21
|
+
'victor-mono-700': { family: 'Victor Mono', weight: '700', type: 'font/otf', file: 'themes/victor-mono/VictorMono-Bold.otf' },
|
|
22
|
+
'excalifont-400': { family: 'Excalifont', weight: '400', type: 'font/woff2', file: 'themes/excalifont/Excalifont-Regular.woff2' },
|
|
23
|
+
};
|
|
24
|
+
function color(value) {
|
|
25
|
+
if (typeof value !== 'string')
|
|
26
|
+
return undefined;
|
|
27
|
+
const m = /^rgba?\((\d{1,3}), (\d{1,3}), (\d{1,3})(?:, (0|1|0?\.\d{1,6}))?\)$/.exec(value);
|
|
28
|
+
return m && [m[1], m[2], m[3]].every(n => Number(n) <= 255) ? value : undefined;
|
|
29
|
+
}
|
|
30
|
+
function length(value) {
|
|
31
|
+
if (typeof value !== 'string')
|
|
32
|
+
return undefined;
|
|
33
|
+
const m = /^(\d{1,2}(?:\.\d{1,3})?)px$/.exec(value);
|
|
34
|
+
return m && Number(m[1]) <= 24 ? value : undefined;
|
|
35
|
+
}
|
|
36
|
+
function families(value) {
|
|
37
|
+
if (typeof value !== 'string' || value.length > 240)
|
|
38
|
+
return undefined;
|
|
39
|
+
const names = [];
|
|
40
|
+
for (const part of value.split(',').slice(0, 6)) {
|
|
41
|
+
const name = part.trim().replace(/^(['"])(.*)\1$/, '$2');
|
|
42
|
+
if (GENERIC_FONTS.has(name) || /^[A-Za-z0-9][A-Za-z0-9 _-]{0,47}$/.test(name))
|
|
43
|
+
names.push(name);
|
|
44
|
+
else
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
return names.length ? names : undefined;
|
|
48
|
+
}
|
|
49
|
+
const stack = (names) => names.map(n => GENERIC_FONTS.has(n) ? n : `"${n}"`).join(', ');
|
|
50
|
+
/** Keep only the values that pass their checks; undefined when none do. */
|
|
51
|
+
export function checkedPhoneTheme(input) {
|
|
52
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
53
|
+
return undefined;
|
|
54
|
+
const raw = input;
|
|
55
|
+
const vars = {};
|
|
56
|
+
for (const key of PHONE_THEME_COLORS) {
|
|
57
|
+
const value = color(raw[key]);
|
|
58
|
+
if (value)
|
|
59
|
+
vars[key] = value;
|
|
60
|
+
}
|
|
61
|
+
for (const key of LENGTHS) {
|
|
62
|
+
const value = length(raw[key]);
|
|
63
|
+
if (value)
|
|
64
|
+
vars[key] = value;
|
|
65
|
+
}
|
|
66
|
+
const fonts = new Map();
|
|
67
|
+
for (const key of FONTS) {
|
|
68
|
+
const names = families(raw[key]);
|
|
69
|
+
if (!names)
|
|
70
|
+
continue;
|
|
71
|
+
vars[key] = stack(names);
|
|
72
|
+
// The first family is the one the theme shows; bring it along when it
|
|
73
|
+
// is bundled with Arco.
|
|
74
|
+
for (const [id, font] of Object.entries(BUNDLED_FONTS)) {
|
|
75
|
+
if (font.family === names[0])
|
|
76
|
+
fonts.set(id, { id, family: font.family, weight: font.weight });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const scheme = raw.scheme === 'light' || raw.scheme === 'dark' ? raw.scheme : undefined;
|
|
80
|
+
if (!Object.keys(vars).length && !scheme)
|
|
81
|
+
return undefined;
|
|
82
|
+
return { vars, ...(scheme ? { scheme } : {}), fonts: [...fonts.values()] };
|
|
83
|
+
}
|
|
84
|
+
/** The bytes of one bundled font that the theme names, or null. */
|
|
85
|
+
export async function bundledPhoneFont(theme, id) {
|
|
86
|
+
const font = Object.hasOwn(BUNDLED_FONTS, id) ? BUNDLED_FONTS[id] : undefined;
|
|
87
|
+
if (!font || !theme?.fonts.some(f => f.id === id))
|
|
88
|
+
return null;
|
|
89
|
+
try {
|
|
90
|
+
return { type: font.type, bytes: await readFile(join(PROJECT_ROOT, 'client', 'dist', font.file)) };
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=phoneUploadTheme.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare function gitOutput(cwd: string, args: string[], signal?: AbortSignal): Promise<string>;
|
|
1
2
|
export declare function requireProjectBinding(cwd?: string | null, workflowId?: string | null): Promise<string>;
|
|
2
3
|
/** Search may narrow a project or admitted worktree to an ordinary folder. */
|
|
3
4
|
export declare function requireProjectFolder(cwd?: string | null, workflowId?: string | null): Promise<string>;
|
|
@@ -4,6 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
5
|
import { confinedPath, isPathWithin, FileAccessError, safeDirectory } from '../fileAccessPolicy.js';
|
|
6
6
|
import { worktreesRoot } from '../project/taskWorktree.js';
|
|
7
|
+
import { projectGitEnv } from '../publicProject.js';
|
|
7
8
|
import { resolveBoundCwd } from './writeConfinement.js';
|
|
8
9
|
const execFileAsync = promisify(execFile);
|
|
9
10
|
const samePath = (a, b) => path.relative(a, b) === '';
|
|
@@ -11,8 +12,8 @@ class SelectedWorktreeError extends Error {
|
|
|
11
12
|
code = 'EACCES';
|
|
12
13
|
constructor() { super('The selected worktree is unavailable or is not registered with this tab\'s project. Select a worktree again.'); }
|
|
13
14
|
}
|
|
14
|
-
async function gitOutput(cwd, args) {
|
|
15
|
-
const { stdout } = await execFileAsync('git', args, { cwd, encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024 });
|
|
15
|
+
export async function gitOutput(cwd, args, signal) {
|
|
16
|
+
const { stdout } = await execFileAsync('git', args, { cwd, encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024, env: projectGitEnv(), signal });
|
|
16
17
|
return stdout;
|
|
17
18
|
}
|
|
18
19
|
export async function requireProjectBinding(cwd, workflowId) {
|
|
@@ -2,11 +2,12 @@ import { readListingSettings } from '../settings.js';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { explorerRoot } from './explorerRoot.js';
|
|
4
4
|
import { readdir } from 'node:fs/promises';
|
|
5
|
-
import { FileAccessError, assertSafePath, confinedPath, createReadAccessContext } from '../fileAccessPolicy.js';
|
|
5
|
+
import { FileAccessError, assertSafePath, confinedPath, createReadAccessContext, isPathWithin } from '../fileAccessPolicy.js';
|
|
6
6
|
import { knownRoots, resolveBoundCwd } from './writeConfinement.js';
|
|
7
7
|
import { UPLOADS_DIR } from '../server/constants.js';
|
|
8
8
|
import { SCRATCH_ROOT } from '../media/scratch.js';
|
|
9
9
|
import { artifactsDir } from '../workers/limits.js';
|
|
10
|
+
import { resolveWorktreeFile } from './browserWorktrees.js';
|
|
10
11
|
export async function readRoots(cwd, workflowId) {
|
|
11
12
|
const bound = await resolveBoundCwd(cwd, workflowId);
|
|
12
13
|
if (!bound.ok && bound.reason !== 'none')
|
|
@@ -37,6 +38,9 @@ export async function resolveBrowserRead(p, cwd, workflowId, kind = 'file') {
|
|
|
37
38
|
return confinedPath(target, roots, kind);
|
|
38
39
|
}
|
|
39
40
|
catch (err) {
|
|
41
|
+
if (kind === 'file' && bound.ok && !roots.some(root => isPathWithin(root, target))) {
|
|
42
|
+
return resolveWorktreeFile(target, bound.cwd, await createReadAccessContext());
|
|
43
|
+
}
|
|
40
44
|
// Only a missing bare filename can fall back to this bound workflow's
|
|
41
45
|
// artifacts. Traversal, denied paths and unknown bindings never fall back.
|
|
42
46
|
if (err.code !== 'ENOENT' || kind !== 'file' || !bound.ok || !workflowId
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { localRuntimeStatusService } from '../localRuntimeStatus.js';
|
|
2
2
|
import { tryHandleHandoffHistoryRoute } from './handoffHistoryRoutes.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { UnsafeStorageRootError } from '../storageRoot.js';
|
|
4
|
+
import { readAttachmentBody, storeAttachment } from './attachmentUpload.js';
|
|
5
|
+
import { tryHandlePhoneOperator, tryHandlePhonePage } from './phoneUploadRoutes.js';
|
|
5
6
|
import { requireProjectBinding } from './projectBinding.js';
|
|
6
7
|
import { tryHandleStorageRoutes } from './storageRoutes.js';
|
|
7
8
|
import { tryHandleArchitectureReviewRoutes } from './architectureReviewRoutes.js';
|
|
@@ -24,9 +25,9 @@ import { tryHandleDeepSeekRoutes } from './deepseekRoutes.js';
|
|
|
24
25
|
import { tryHandleVoiceRoutes } from './voiceRoutes.js';
|
|
25
26
|
import { spawn } from 'child_process';
|
|
26
27
|
import { chmodSync, writeFileSync } from 'fs';
|
|
27
|
-
import { mkdir, readdir, readFile
|
|
28
|
+
import { mkdir, readdir, readFile } from 'fs/promises';
|
|
28
29
|
import { homedir, tmpdir } from 'os';
|
|
29
|
-
import {
|
|
30
|
+
import { extname, join, resolve, sep } from 'path';
|
|
30
31
|
import { unloadLocalModels } from '../localModels.js';
|
|
31
32
|
import { getAuthStatus, triggerAuthLogin } from '../auth.js';
|
|
32
33
|
import { cliSnapshotDir, runCliUpdate, refreshRuntimeVersions } from '../capabilities.js';
|
|
@@ -56,8 +57,7 @@ import { probeOllamaLive, aggregateOllamaPs, unloadOllamaModel } from '../provid
|
|
|
56
57
|
import { computeVramReport, computeOllamaFit } from '../providers/ollamaVram.js';
|
|
57
58
|
import { markAvailable as quotaMarkAvailable, markThrottled as quotaMarkThrottled, wireSnapshot as quotaWireSnapshot } from '../quota.js';
|
|
58
59
|
import { broadcastWorkflow, send } from '../server/broadcast.js';
|
|
59
|
-
import { compareDirectoryNames, PORT, PROJECT_ROOT
|
|
60
|
-
import { queueModelImage } from '../providers/attachments.js';
|
|
60
|
+
import { compareDirectoryNames, PORT, PROJECT_ROOT } from '../server/constants.js';
|
|
61
61
|
import { sessions, workflows } from '../server/state.js';
|
|
62
62
|
import { patchSettings, readSettings, readListingSettings } from '../settings.js';
|
|
63
63
|
import { deleteSkill, isValidSlug, listSkills, readSkillBody, readBuiltinSkill, copyBuiltinSkill, writeSkill } from '../skills.js';
|
|
@@ -155,6 +155,8 @@ export async function handleHttpRequest(req, res, deps) {
|
|
|
155
155
|
res.end(JSON.stringify({ error: 'Forbidden origin' }));
|
|
156
156
|
return;
|
|
157
157
|
}
|
|
158
|
+
if (await tryHandlePhonePage(req, res))
|
|
159
|
+
return;
|
|
158
160
|
if (guard.origin) {
|
|
159
161
|
res.setHeader('Access-Control-Allow-Origin', guard.origin);
|
|
160
162
|
res.setHeader('Vary', 'Origin');
|
|
@@ -230,6 +232,8 @@ export async function handleHttpRequest(req, res, deps) {
|
|
|
230
232
|
}
|
|
231
233
|
// Operator routes in their own modules: behind the session gate like every
|
|
232
234
|
// other /api route (they read or change settings and can call providers).
|
|
235
|
+
if (await tryHandlePhoneOperator(req, res))
|
|
236
|
+
return;
|
|
233
237
|
if (await tryHandleProviderThrottleRoutes(req, res))
|
|
234
238
|
return;
|
|
235
239
|
if (await tryHandleSmartPickupRoutes(req, res))
|
|
@@ -323,10 +327,7 @@ export async function handleHttpRequest(req, res, deps) {
|
|
|
323
327
|
}
|
|
324
328
|
if (req.url === '/upload' && req.method === 'POST') {
|
|
325
329
|
try {
|
|
326
|
-
const
|
|
327
|
-
for await (const chunk of req)
|
|
328
|
-
chunks.push(chunk);
|
|
329
|
-
const body = Buffer.concat(chunks);
|
|
330
|
+
const body = await readAttachmentBody(req);
|
|
330
331
|
// Reject empty uploads so they cannot produce invalid image blocks in
|
|
331
332
|
// a worker's persistent history.
|
|
332
333
|
if (body.length === 0) {
|
|
@@ -338,21 +339,9 @@ export async function handleHttpRequest(req, res, deps) {
|
|
|
338
339
|
? req.headers['x-filename'].trim()
|
|
339
340
|
: `upload-${Date.now()}`;
|
|
340
341
|
const contentType = typeof req.headers['content-type'] === 'string' ? req.headers['content-type'].split(';')[0].trim().toLowerCase() : '';
|
|
341
|
-
const
|
|
342
|
-
const inferredExt = !ext && contentType ? UPLOAD_IMAGE_EXT[contentType] : undefined;
|
|
343
|
-
const filename = basename(rawFilename) + (inferredExt ?? '');
|
|
344
|
-
const fileId = crypto.randomUUID().slice(0, 8);
|
|
345
|
-
const uploadRoot = await ensureStorageRoot(UPLOADS_DIR);
|
|
346
|
-
const savePath = join(uploadRoot, `${fileId}-${filename}`);
|
|
347
|
-
await writeFile(savePath, body, { flag: 'wx' });
|
|
348
|
-
console.log(`[arco] File uploaded: ${filename} -> ${savePath}`);
|
|
349
|
-
// Finish upload-only replacement before publishing the stable path.
|
|
350
|
-
// Failure retains the original; project files never enter this path.
|
|
351
|
-
await shrinkUploadedImage(savePath);
|
|
352
|
-
// Other formats still use a separate model-compatible copy.
|
|
353
|
-
queueModelImage(savePath);
|
|
342
|
+
const stored = await storeAttachment(body, rawFilename, contentType);
|
|
354
343
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
355
|
-
res.end(JSON.stringify(
|
|
344
|
+
res.end(JSON.stringify(stored));
|
|
356
345
|
}
|
|
357
346
|
catch (error) {
|
|
358
347
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|