dsh-jiuling-link 0.0.0-stage → 0.2.1-rc.11
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/LICENSE +21 -0
- package/README.md +15 -2
- package/bridge/index.mjs +201 -0
- package/bridge/vnext.mjs +177 -0
- package/bridge/workspace-preview.mjs +170 -0
- package/cordis.patch.yml +3 -0
- package/desktop/images.mjs +84 -0
- package/desktop/index.mjs +414 -0
- package/desktop/journal.mjs +94 -0
- package/desktop/protocol.mjs +69 -0
- package/desktop/questions.mjs +343 -0
- package/desktop/session-options.mjs +262 -0
- package/desktop/uploads.mjs +68 -0
- package/desktop/windows-drives.mjs +143 -0
- package/desktop/workspace-files.mjs +162 -0
- package/host/account.mjs +223 -0
- package/host/cache-vault.mjs +78 -0
- package/host/cache.mjs +231 -0
- package/host/device.mjs +563 -0
- package/host/index.mjs +49 -0
- package/host/wire.mjs +203 -0
- package/icon.svg +1 -0
- package/licenses/@peculiar__asn1-cms@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-csr@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-ecc@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-pfx@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-pkcs8@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-pkcs9@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-rsa@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-schema@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-x509-attr@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__asn1-x509@2.11.1/LICENSE +21 -0
- package/licenses/@peculiar__utils@2.0.3/LICENSE +21 -0
- package/licenses/@peculiar__x509@1.14.3/LICENSE +21 -0
- package/licenses/asn1js@3.1.0/LICENSE +30 -0
- package/licenses/pvtsutils@1.3.6/LICENSE +21 -0
- package/licenses/pvutils@1.2.0/LICENSE +24 -0
- package/licenses/reflect-metadata@0.2.2/CopyrightNotice.txt +15 -0
- package/licenses/reflect-metadata@0.2.2/LICENSE +55 -0
- package/licenses/selfsigned@5.5.0/LICENSE +22 -0
- package/licenses/tslib@1.14.1/CopyrightNotice.txt +15 -0
- package/licenses/tslib@1.14.1/LICENSE.txt +12 -0
- package/licenses/tslib@2.9.1/CopyrightNotice.txt +15 -0
- package/licenses/tslib@2.9.1/LICENSE.txt +12 -0
- package/licenses/tsyringe@4.10.0/LICENSE +21 -0
- package/licenses/ws@8.23.0/LICENSE +20 -0
- package/locale/en.json +1 -0
- package/locale/zh.json +1 -0
- package/package.json +96 -4
- package/protocol/frames.mjs +93 -0
- package/protocol/identity.mjs +68 -0
- package/protocol/index.mjs +190 -0
- package/ui/client.js +14450 -0
- package/ui/vendor/jsQR.LICENSE +202 -0
- package/ui/vendor/qrcode.LICENSE +20 -0
- package/vault/index.mjs +204 -0
- package/vault/windows-dpapi.ps1 +28 -0
- package/vendor/selfsigned.mjs +19736 -0
- package/vendor/ws.mjs +3789 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jiuling Remote Workspaces contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 啾灵互联
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
适用于 Windows DSH Desktop 和 Android DSH System,宿主版本 `0.2.2-rc.5`。两端使用同一份 `dsh-jiuling-link` 离线安装包。
|
|
4
|
+
|
|
5
|
+
1. 双端打开「插件 → 添加插件」。手机选择应用可读位置的 `.tgz`。Windows 可将 `.tgz` 解开,把其中的 `package` 目录作为本地包安装。安装后点击「立即启用」。
|
|
6
|
+
2. 在电脑打开「设置 → 啾灵互联」,使用官网账号登录并查看官方中继订阅。订阅有效后,开启「允许手机连接」并生成一次性邀请。手机从相同设置页扫码或粘贴完整邀请。邀请有效期五分钟,只交给自己的设备。
|
|
7
|
+
3. 在电脑核对申请手机的指纹,勾选允许访问的工作区并批准。手机从侧栏「远程工作区」打开已有会话,也可新建。电脑保持 DSH 运行并联网。
|
|
8
|
+
4. 要停止共享,在电脑设置页关闭连接开关。再次开启可恢复原授权。要收回授权,选择对应设备并确认撤销。手机离线时也可在其设置页清除旧配对。
|
|
9
|
+
|
|
10
|
+
电脑保存会话并执行模型与工具请求。共享范围决定手机可以操作的 DSH 工作区。模型和工具仍使用电脑当前会话的权限。可在电脑设置中撤销手机授权。
|
|
11
|
+
|
|
12
|
+
香港中继只转发数据。两台设备在 WSS 内另建双向认证的 TLS 1.3 通道,并固定对端公钥。中继可以看到连接地址、随机路由、时间和流量大小,也可以阻断连接。你在电脑配置的模型供应商按现有 DSH 配置接收模型输入。
|
|
13
|
+
|
|
14
|
+
Windows 使用当前用户的 DPAPI 密封端点身份。随本项目交付的增强 System APK 使用 Android Keystore 密封身份,旧版 System 使用 DSH 应用私有凭据。配对的私钥会在端点运行时进入内存,操作系统账户、两端宿主和已安装的插件属于信任范围。设备丢失或重装后,在电脑撤销旧手机并重新配对。
|
|
15
|
+
|
|
16
|
+
工作区授权约束手机可访问的会话。模型工具使用电脑当前会话的工作目录和权限模式,请先选择合适的目录与权限。撤销后,电脑已受理的生成或工具调用仍可继续。若提交过程中断开,先在会话历史核对结果。附件每个最多 8 MiB。
|
package/bridge/index.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { isRemoteAction } from '../host/wire.mjs';
|
|
2
|
+
|
|
3
|
+
const endpoint = 'jiuling-link/action';
|
|
4
|
+
const requestLimit = 512 * 1024;
|
|
5
|
+
const responseLimit = 5 * 1024 * 1024;
|
|
6
|
+
const deadlineMs = 75000;
|
|
7
|
+
const maxActive = 24;
|
|
8
|
+
|
|
9
|
+
// Only fixed, public explanations cross the boundary. Never return arbitrary
|
|
10
|
+
// exception messages, even when they accompany an otherwise recognized code.
|
|
11
|
+
const messages = new Map(Object.entries({
|
|
12
|
+
invalid: 'Invalid request.', invalid_request: 'Invalid request.',
|
|
13
|
+
'too-large': 'The payload exceeds the local bridge limit.',
|
|
14
|
+
'apk-required': 'Install the official Jiuling Interconnect Android app to use this plugin.',
|
|
15
|
+
'cache-unavailable': 'The encrypted local cache is temporarily unavailable.',
|
|
16
|
+
'unknown-action': 'Unknown action.', disabled: 'Remote access is disabled.',
|
|
17
|
+
unsupported: 'Unsupported platform.', paired: 'A device is already paired.',
|
|
18
|
+
identity: 'Device identity is unavailable or has changed.',
|
|
19
|
+
expired: 'The pairing request expired.', scope: 'Workspace access is unavailable.',
|
|
20
|
+
disposed: 'The plugin is stopped.', cancelled: 'Request cancelled.',
|
|
21
|
+
busy: 'Too many active requests.', offline: 'The computer is offline.',
|
|
22
|
+
unavailable: 'The connection is unavailable.',
|
|
23
|
+
account_invalid: 'Check the email and password.',
|
|
24
|
+
account_required: 'Sign in with a Jiuling Interconnect account to use the official relay.',
|
|
25
|
+
account_inactive: 'An active subscription is required to use the official relay.',
|
|
26
|
+
account_rate_limited: 'Please wait before signing in again.',
|
|
27
|
+
account_unavailable: 'The account service is temporarily unavailable.',
|
|
28
|
+
unconfirmed: 'The action outcome is unconfirmed.',
|
|
29
|
+
outcome_unknown: 'Check the existing session before trying again.',
|
|
30
|
+
forbidden: 'Access to this workspace or session was refused.',
|
|
31
|
+
machine_access_required: 'Machine access requires approval on this computer.',
|
|
32
|
+
directory_unavailable: 'The specified directory is unavailable.',
|
|
33
|
+
directory_exists: 'A directory with this name already exists.',
|
|
34
|
+
permission_unavailable: 'The selected permission preset is unavailable.',
|
|
35
|
+
session_setup_incomplete: 'Session setup was interrupted. Check the session on the computer before creating another.',
|
|
36
|
+
'agent-preset/not-found': 'The selected agent preset is unavailable.',
|
|
37
|
+
request_conflict: 'This request identifier was already used for another action.',
|
|
38
|
+
journal_unavailable: 'The desktop could not save the request record.',
|
|
39
|
+
journal_full: 'The desktop request journal is full.',
|
|
40
|
+
image_unavailable: 'This history image is unavailable.',
|
|
41
|
+
image_too_large: 'This history image exceeds the size limit.',
|
|
42
|
+
model_does_not_support_images: 'The selected model cannot receive images.',
|
|
43
|
+
file_not_staged: 'The file must be attached again before sending.',
|
|
44
|
+
file_unavailable: 'The file is unavailable.',
|
|
45
|
+
not_text: 'This file does not support text preview.',
|
|
46
|
+
file_preview_update_required: 'Update Jiuling Interconnect on the computer and phone to preview this file.',
|
|
47
|
+
file_preview_too_large: 'This file exceeds the remote preview size limit.',
|
|
48
|
+
file_preview_changed: 'The file changed during preview. Reload it and try again.',
|
|
49
|
+
file_preview_unsupported: 'This file format is not available in remote preview.',
|
|
50
|
+
file_preview_invalid: 'The file is damaged or does not match its extension.',
|
|
51
|
+
file_preview_dimensions: 'The image is too large to display safely.',
|
|
52
|
+
receipt_missing: 'The attachment receipt is unavailable.',
|
|
53
|
+
question_closed: 'This request was already answered, withdrawn, or is no longer available.',
|
|
54
|
+
upload_missing: 'The attachment upload is unavailable.',
|
|
55
|
+
offset_mismatch: 'The uploaded chunk does not match the expected offset.',
|
|
56
|
+
checksum_mismatch: 'The attachment failed integrity verification.',
|
|
57
|
+
'session/model-unavailable': 'The selected model is unavailable.',
|
|
58
|
+
'operation-failed': 'The action could not be completed.',
|
|
59
|
+
}));
|
|
60
|
+
|
|
61
|
+
function failure(code) {
|
|
62
|
+
return { ok: false, error: { code, message: messages.get(code), details: {} } };
|
|
63
|
+
}
|
|
64
|
+
function stop(code) { throw Object.assign(new Error(), { code }); }
|
|
65
|
+
function rejected(status) {
|
|
66
|
+
return new Response(null, { status, headers: { 'cache-control': 'no-store' } });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function readRequest(req, signal) {
|
|
70
|
+
if (Number(req.headers.get('content-length')) > requestLimit) stop('too-large');
|
|
71
|
+
if (!req.body) stop('invalid');
|
|
72
|
+
signal.throwIfAborted();
|
|
73
|
+
const reader = req.body.getReader();
|
|
74
|
+
const abort = () => { void reader.cancel().catch(() => {}); };
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let size = 0;
|
|
77
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
78
|
+
try {
|
|
79
|
+
while (true) {
|
|
80
|
+
const { done, value } = await reader.read();
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
if (done) break;
|
|
83
|
+
size += value.byteLength;
|
|
84
|
+
if (size > requestLimit) { abort(); stop('too-large'); }
|
|
85
|
+
chunks.push(value);
|
|
86
|
+
}
|
|
87
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
|
|
88
|
+
} finally {
|
|
89
|
+
signal.removeEventListener('abort', abort);
|
|
90
|
+
reader.releaseLock();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);
|
|
95
|
+
const isRecord = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
96
|
+
function checkParams(params) {
|
|
97
|
+
if (!isRecord(params)) stop('invalid');
|
|
98
|
+
let count = 0;
|
|
99
|
+
function visit(value, depth) {
|
|
100
|
+
if (depth > 32 || ++count > 32000) stop('too-large');
|
|
101
|
+
if (typeof value === 'number' && !Number.isFinite(value)) stop('invalid');
|
|
102
|
+
if (typeof value !== 'object' || value === null) return;
|
|
103
|
+
for (const key of Object.keys(value)) {
|
|
104
|
+
if (unsafeKeys.has(key)) stop('invalid');
|
|
105
|
+
visit(value[key], depth + 1);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
visit(params, 0);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function validateLocalRequest(action, params) {
|
|
112
|
+
const exact = (required, optional = []) => required.every(k => Object.hasOwn(params, k)) &&
|
|
113
|
+
Object.keys(params).every(k => required.includes(k) || optional.includes(k));
|
|
114
|
+
const pin = value => typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
|
|
115
|
+
const id = value => typeof value === 'string' && /^[A-Za-z0-9_:.@-]{1,180}$/.test(value);
|
|
116
|
+
switch (action) {
|
|
117
|
+
case 'account.status':
|
|
118
|
+
case 'account.logout':
|
|
119
|
+
if (!exact([])) stop('invalid');
|
|
120
|
+
break;
|
|
121
|
+
case 'account.login':
|
|
122
|
+
if (!exact(['email', 'password']) || typeof params.email !== 'string' || params.email.length > 254 ||
|
|
123
|
+
typeof params.password !== 'string' || params.password.length > 256) stop('invalid');
|
|
124
|
+
break;
|
|
125
|
+
case 'local.remoteRequest':
|
|
126
|
+
if (!exact(['peerId', 'action', 'params']) || !pin(params.peerId) || !isRemoteAction(params.action) || !isRecord(params.params)) stop('invalid');
|
|
127
|
+
break;
|
|
128
|
+
case 'cache.read':
|
|
129
|
+
if (!exact(['peerId','cacheScope','action','params']) || !pin(params.peerId) ||
|
|
130
|
+
typeof params.cacheScope !== 'string' || !/^v1-[a-f0-9]{64}$/.test(params.cacheScope) ||
|
|
131
|
+
!['workspace.list','workspace.drives','workspace.directories','session.list','session.options','model.list','session.history'].includes(params.action) ||
|
|
132
|
+
!isRecord(params.params)) stop('invalid');
|
|
133
|
+
break;
|
|
134
|
+
case 'cache.info':
|
|
135
|
+
case 'cache.clear':
|
|
136
|
+
if (!exact([])) stop('invalid');
|
|
137
|
+
break;
|
|
138
|
+
case 'local.machineAccess':
|
|
139
|
+
if (!exact(['id', 'enabled']) || !pin(params.id) || typeof params.enabled !== 'boolean') stop('invalid');
|
|
140
|
+
break;
|
|
141
|
+
case 'local.confirm':
|
|
142
|
+
if (!exact(['id', 'workspaceIds'], ['machineAccess']) || !id(params.id) ||
|
|
143
|
+
('machineAccess' in params && typeof params.machineAccess !== 'boolean') || !Array.isArray(params.workspaceIds) ||
|
|
144
|
+
params.workspaceIds.length > 256 || !params.workspaceIds.every(id) || (!params.workspaceIds.length && params.machineAccess !== true)) stop('invalid');
|
|
145
|
+
break;
|
|
146
|
+
case 'local.events':
|
|
147
|
+
if (!exact([], ['after', 'waitMs', 'peerId']) || ('peerId' in params && !pin(params.peerId)) ||
|
|
148
|
+
('after' in params && (!Number.isSafeInteger(params.after) || params.after < 0)) ||
|
|
149
|
+
('waitMs' in params && (!Number.isFinite(params.waitMs) || params.waitMs < 0))) stop('invalid');
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function response(rpcId, result) {
|
|
155
|
+
const body = JSON.stringify({ type: 'server-response', rpcId, result });
|
|
156
|
+
if (Buffer.byteLength(body) > responseLimit) return response(rpcId, failure('too-large'));
|
|
157
|
+
return new Response(body, { headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Register this plugin's single owner-only route on DSH's shared /api carrier. */
|
|
161
|
+
export function installActionBridge(ctx, handler) {
|
|
162
|
+
if (typeof handler !== 'function') throw new TypeError('Expected an action handler');
|
|
163
|
+
const lifetime = new AbortController();
|
|
164
|
+
let active = 0;
|
|
165
|
+
// Registration and cleanup belong to the consuming Host plugin's fiber.
|
|
166
|
+
const unregister = ctx.connection.fetch.register({
|
|
167
|
+
path: `/api/${endpoint}`, methods: ['POST'], requestBody: 'streaming',
|
|
168
|
+
// rc5 createSharedFetchHandler gates exact routes on the admitted owner's
|
|
169
|
+
// Peer before invoking this callback. Never mount this callback on a socket.
|
|
170
|
+
async fetch(req) {
|
|
171
|
+
if (req.method !== 'POST') return rejected(405);
|
|
172
|
+
if (req.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') return rejected(415);
|
|
173
|
+
if (active >= maxActive || lifetime.signal.aborted) return rejected(503);
|
|
174
|
+
const deadline = AbortSignal.timeout(deadlineMs);
|
|
175
|
+
const signal = AbortSignal.any([req.signal, lifetime.signal, deadline]);
|
|
176
|
+
active++;
|
|
177
|
+
let id;
|
|
178
|
+
try {
|
|
179
|
+
const message = await readRequest(req, signal);
|
|
180
|
+
if (!isRecord(message) || message.type !== 'client-request' || message.method !== endpoint ||
|
|
181
|
+
typeof message.rpcId !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/.test(message.rpcId)) return rejected(400);
|
|
182
|
+
id = message.rpcId;
|
|
183
|
+
const payload = message.payload;
|
|
184
|
+
if (!isRecord(payload) || Object.keys(payload).length !== 2 || typeof payload.action !== 'string' ||
|
|
185
|
+
!/^[A-Za-z][A-Za-z0-9._-]{0,79}$/.test(payload.action)) stop('invalid');
|
|
186
|
+
checkParams(payload.params);
|
|
187
|
+
validateLocalRequest(payload.action, payload.params);
|
|
188
|
+
signal.throwIfAborted();
|
|
189
|
+
const value = await handler(payload.action, payload.params, signal);
|
|
190
|
+
signal.throwIfAborted();
|
|
191
|
+
return response(id, { ok: true, value: value ?? null });
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (!id) return rejected(error?.code === 'too-large' ? 413 : 400);
|
|
194
|
+
const code = deadline.aborted ? 'unconfirmed' : signal.aborted ? 'cancelled' :
|
|
195
|
+
(messages.has(error?.code) ? error.code : 'operation-failed');
|
|
196
|
+
return response(id, failure(code));
|
|
197
|
+
} finally { active--; }
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
return ctx.effect(() => () => { lifetime.abort(); return unregister(); }, 'jiuling-link: local action bridge');
|
|
201
|
+
}
|
package/bridge/vnext.mjs
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import {filePreviewChunkBytes, filePreviewMaxBytes, previewMediaType} from './workspace-preview.mjs';
|
|
2
|
+
|
|
3
|
+
// New routes carry only the declared UI selectors and labels, never raw DSH objects.
|
|
4
|
+
const own = (object, key) => Object.hasOwn(object, key);
|
|
5
|
+
const fields = (object, required, optional = []) => object != null && typeof object === 'object' && !Array.isArray(object) &&
|
|
6
|
+
required.every(key => own(object, key)) && Object.keys(object).every(key => required.includes(key) || optional.includes(key));
|
|
7
|
+
const text = (value, max = 256) => typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value);
|
|
8
|
+
const key = value => text(value, 180) && /^[A-Za-z0-9_:.@-]+$/.test(value);
|
|
9
|
+
const uint = value => Number.isSafeInteger(value) && value >= 0;
|
|
10
|
+
const present = (object, name, valid) => !own(object, name) || valid(object[name]);
|
|
11
|
+
const list = (value, max, valid) => Array.isArray(value) && value.length <= max && value.every(item => valid(item));
|
|
12
|
+
const drive = value => typeof value === 'string' && /^[A-Z]$/.test(value);
|
|
13
|
+
const windowsName = value => text(value, 255) && !/[\\/:*?"<>|]/.test(value) && !/[. ]$/.test(value) &&
|
|
14
|
+
!/^(?:con|prn|aux|nul|conin\$|conout\$|(?:com|lpt)[1-9¹²³])(?:\.|$)/i.test(value);
|
|
15
|
+
const segments = value => list(value, 128, windowsName);
|
|
16
|
+
function relativeFilePath(value, allowRoot) {
|
|
17
|
+
if (value === '') return allowRoot;
|
|
18
|
+
return typeof value === 'string' && value.length <= 4096 && list(value.split('/'), 64, windowsName);
|
|
19
|
+
}
|
|
20
|
+
const modelRoute = value => fields(value, ['provider', 'model'], ['reasoningEffort']) &&
|
|
21
|
+
text(value.provider) && text(value.model) && present(value, 'reasoningEffort', text);
|
|
22
|
+
const option = item => fields(item, ['id','isDefault'], ['name','description']) && text(item.id) && present(item, 'name', v => text(v, 1024)) && present(item, 'description', v => typeof v === 'string' && v.length <= 4096 && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v)) && typeof item.isDefault === 'boolean';
|
|
23
|
+
const sessionCommands = new Set(['goal','plan','feedback','compact','permission','team-mode']);
|
|
24
|
+
const feedbackCategories = new Set(['task-result','instruction-following','product-interaction','service-stability','resource-cost','security-privacy-permission','other']);
|
|
25
|
+
const effort = item => fields(item, ['id','name']) && text(item.id) && text(item.name, 1024);
|
|
26
|
+
const reasoning = value => fields(value, ['efforts'], ['defaultEffort']) && list(value.efforts, 128, effort) && present(value, 'defaultEffort', text);
|
|
27
|
+
const model = item => fields(item, ['id','name'], ['reasoning']) && text(item.id) && text(item.name, 1024) && present(item, 'reasoning', reasoning);
|
|
28
|
+
const group = item => fields(item, ['id','name','models']) && text(item.id) && text(item.name, 1024) && list(item.models, 8192, model);
|
|
29
|
+
const catalog = value => fields(value, ['default','groups']) && modelRoute(value.default) && list(value.groups, 1024, group);
|
|
30
|
+
|
|
31
|
+
const planMarkdown = value => typeof value === 'string' && Buffer.byteLength(value) <= 65536 && /^#\s+\S/.test(value.trim()) && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/u.test(value);
|
|
32
|
+
const reviewFeedback = value => typeof value === 'string' && value.trim().length > 0 && Buffer.byteLength(value) <= 8192 && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/u.test(value);
|
|
33
|
+
const previewRevision = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
34
|
+
function fileBinaryWindow(p) {
|
|
35
|
+
return uint(p.offset) && p.offset < filePreviewMaxBytes && p.offset % filePreviewChunkBytes === 0 &&
|
|
36
|
+
(p.offset === 0 ? !own(p,'revision') : previewRevision(p.revision));
|
|
37
|
+
}
|
|
38
|
+
const interactionScope = ['workspaceId','sessionId'];
|
|
39
|
+
const bounded = (value,max) => typeof value === 'string' && Buffer.byteLength(value) <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/u.test(value);
|
|
40
|
+
const questionItem = row => fields(row,['id','question'],['detail','header','multiSelect','options']) && !!row.id && bounded(row.id,256) &&
|
|
41
|
+
bounded(row.question,8192) && present(row,'detail',v=>bounded(v,16384)) && present(row,'header',v=>bounded(v,1024)) &&
|
|
42
|
+
present(row,'multiSelect',v=>typeof v==='boolean') && present(row,'options',options=>list(options,50,o=>fields(o,['label'],['description']) &&
|
|
43
|
+
!!o.label && bounded(o.label,4096) && present(o,'description',v=>bounded(v,4096))) && new Set(options.map(o=>o.label)).size===options.length);
|
|
44
|
+
const questionAnswer = row => fields(row,['id','selected'],['custom']) && !!row.id && bounded(row.id,256) &&
|
|
45
|
+
list(row.selected,50,label=>!!label && bounded(label,4096)) && present(row,'custom',value=>bounded(value,8192));
|
|
46
|
+
const settledRow = row => fields(row,['callId','answers']) && key(row.callId) && list(row.answers,50,questionAnswer);
|
|
47
|
+
const questionRow = row => fields(row,['callId','questions','state'],['dismiss']) && key(row.callId) && ['open','continued'].includes(row.state) &&
|
|
48
|
+
present(row,'dismiss',v=>row.state==='open' && v==='cancel') && list(row.questions,50,questionItem) && row.questions.length>0 &&
|
|
49
|
+
new Set(row.questions.map(item=>item.id)).size===row.questions.length;
|
|
50
|
+
const approvalRow = row => fields(row,['approvalId','toolName'],['callId','reason']) && key(row.approvalId) &&
|
|
51
|
+
!!row.toolName && bounded(row.toolName,256) && present(row,'callId',key) && present(row,'reason',v=>bounded(v,16384));
|
|
52
|
+
const vnextMethods = new Set(['workspace.drives','workspace.directories','workspace.createDirectory','workspace.open','workspace.files.list','workspace.files.preview','session.options','session.create','session.command','question.list','question.answer','question.dismiss','approval.respond','plan.review.respond','plan.preview']);
|
|
53
|
+
const errorCodes = new Set(['invalid_request','busy','forbidden','unsupported','machine_access_required','directory_unavailable','directory_exists',
|
|
54
|
+
'file_unavailable','not_text','file_preview_too_large','file_preview_changed','file_preview_unsupported','file_preview_invalid','file_preview_dimensions',
|
|
55
|
+
'permission_unavailable','agent-preset/not-found','agent-preset/invalid','session/model-unavailable','session_setup_incomplete',
|
|
56
|
+
'journal_full','journal_unavailable','outcome_unknown','request_conflict','unconfirmed','offline','cancelled','command_unavailable','command_failed','plan_unavailable','question_closed']);
|
|
57
|
+
export function newActionFailure(action, error) {
|
|
58
|
+
if (!vnextMethods.has(action)) return undefined;
|
|
59
|
+
// Only declared codes cross this link. Provider/OS exceptions can contain credentials or paths.
|
|
60
|
+
return {code:errorCodes.has(error?.code) ? error.code : 'operation-failed', message:'The remote action could not be completed.'};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function validate(condition, code) {
|
|
64
|
+
if (!condition) throw Object.assign(new Error(code === 'invalid_request' ? 'Invalid request fields' : 'Invalid remote response fields'), {code});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function validateNewRequest(action, p) {
|
|
68
|
+
let valid;
|
|
69
|
+
switch (action) {
|
|
70
|
+
case 'workspace.drives': valid = fields(p, []); break;
|
|
71
|
+
case 'workspace.directories':
|
|
72
|
+
valid = fields(p, ['drive','segments'], ['offset','limit','showHidden']) && drive(p.drive) && segments(p.segments) &&
|
|
73
|
+
present(p, 'offset', uint) && present(p, 'limit', n => uint(n) && n > 0 && n <= 128) && present(p, 'showHidden', v => typeof v === 'boolean'); break;
|
|
74
|
+
case 'workspace.createDirectory':
|
|
75
|
+
valid = fields(p, ['drive','segments','name','requestId']) && drive(p.drive) && segments(p.segments) && p.segments.length < 128 && windowsName(p.name) && key(p.requestId); break;
|
|
76
|
+
case 'workspace.open': valid = fields(p, ['drive','segments','requestId']) && drive(p.drive) && segments(p.segments) && key(p.requestId); break;
|
|
77
|
+
case 'workspace.files.list':
|
|
78
|
+
valid = fields(p,['workspaceId','sessionId','path']) && key(p.workspaceId) && key(p.sessionId) && relativeFilePath(p.path, true); break;
|
|
79
|
+
case 'workspace.files.preview':
|
|
80
|
+
valid = fields(p,['workspaceId','sessionId','path'],['offset','revision']) && key(p.workspaceId) && key(p.sessionId) && relativeFilePath(p.path, false) &&
|
|
81
|
+
(own(p,'offset') ? fileBinaryWindow(p) : !own(p,'revision')); break;
|
|
82
|
+
case 'question.list': valid = fields(p,interactionScope) && interactionScope.every(field=>key(p[field])); break;
|
|
83
|
+
case 'question.answer':
|
|
84
|
+
valid = fields(p,[...interactionScope,'callId','requestId','answers']) && [...interactionScope,'callId','requestId'].every(field=>key(p[field])) &&
|
|
85
|
+
list(p.answers,50,questionAnswer) && p.answers.length>0; break;
|
|
86
|
+
case 'question.dismiss':
|
|
87
|
+
valid = fields(p,[...interactionScope,'callId','requestId']) && [...interactionScope,'callId','requestId'].every(field=>key(p[field])); break;
|
|
88
|
+
case 'approval.respond':
|
|
89
|
+
valid = fields(p,[...interactionScope,'approvalId','requestId','decision']) && [...interactionScope,'approvalId','requestId'].every(field=>key(p[field])) &&
|
|
90
|
+
['allowed-once','rejected'].includes(p.decision); break;
|
|
91
|
+
case 'plan.preview': valid = fields(p,['workspaceId','sessionId','callId']) && key(p.workspaceId) && key(p.sessionId) && key(p.callId); break;
|
|
92
|
+
case 'plan.review.respond':
|
|
93
|
+
valid = fields(p,['workspaceId','sessionId','reviewId','requestId','decision'],['feedback']) &&
|
|
94
|
+
key(p.workspaceId) && key(p.sessionId) && key(p.reviewId) && key(p.requestId) && ['approve','revise','dismiss'].includes(p.decision) &&
|
|
95
|
+
present(p,'feedback',v=>p.decision === 'revise' && reviewFeedback(v)); break;
|
|
96
|
+
case 'session.options': valid = fields(p, ['workspaceId']) && key(p.workspaceId); break;
|
|
97
|
+
case 'session.command':
|
|
98
|
+
valid = fields(p, ['workspaceId','sessionId','requestId','command','args'], ['category']) &&
|
|
99
|
+
key(p.workspaceId) && key(p.sessionId) && key(p.requestId) && sessionCommands.has(p.command) &&
|
|
100
|
+
typeof p.args === 'string' && Buffer.byteLength(p.args) <= 8192 && !p.args.includes('\u0000') &&
|
|
101
|
+
(!own(p, 'category') || p.command === 'feedback' && feedbackCategories.has(p.category)) &&
|
|
102
|
+
(p.command !== 'compact' || p.args === '') &&
|
|
103
|
+
(p.command !== 'permission' || text(p.args) && p.args === p.args.trim()) &&
|
|
104
|
+
(p.command !== 'team-mode' || p.args === 'on' || p.args === 'off'); break;
|
|
105
|
+
case 'session.create': {
|
|
106
|
+
const options = ['provider','model','reasoningEffort','agentPreset','permissionPreset'];
|
|
107
|
+
valid = fields(p, ['workspaceId','requestId'], [...options,'agentTeamEnabled']) && key(p.workspaceId) && key(p.requestId) &&
|
|
108
|
+
options.every(field => present(p, field, text)) && present(p,'agentTeamEnabled', value => typeof value === 'boolean') &&
|
|
109
|
+
own(p,'provider') === own(p,'model') && (!own(p,'reasoningEffort') || own(p,'model')); break;
|
|
110
|
+
}
|
|
111
|
+
default: return;
|
|
112
|
+
}
|
|
113
|
+
validate(valid, 'invalid_request');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function validateNewReply(action, p, v) {
|
|
117
|
+
let valid;
|
|
118
|
+
switch (action) {
|
|
119
|
+
case 'workspace.drives':
|
|
120
|
+
valid = fields(v,['items']) && list(v.items, 26, row => fields(row,['drive','path']) && drive(row.drive) && row.path === row.drive + ':\\') &&
|
|
121
|
+
new Set(v.items.map(row => row.drive)).size === v.items.length; break;
|
|
122
|
+
case 'workspace.directories': {
|
|
123
|
+
const offset = p.offset ?? 0;
|
|
124
|
+
valid = fields(v,['items','nextOffset']) && list(v.items,p.limit ?? 80, row => fields(row,['name','hidden']) && windowsName(row.name) && typeof row.hidden === 'boolean') &&
|
|
125
|
+
(v.nextOffset === null || (uint(v.nextOffset) && v.nextOffset > offset)); break;
|
|
126
|
+
}
|
|
127
|
+
case 'workspace.createDirectory': {
|
|
128
|
+
const expected = [...p.segments, p.name];
|
|
129
|
+
valid = fields(v,['drive','segments']) && v.drive === p.drive && segments(v.segments) && v.segments.length === expected.length && v.segments.every((part, i) => part === expected[i]); break;
|
|
130
|
+
}
|
|
131
|
+
case 'workspace.open': valid = fields(v,['workspaceId','title']) && key(v.workspaceId) && text(v.title, 1024); break;
|
|
132
|
+
case 'workspace.files.list':
|
|
133
|
+
valid = fields(v,['path','entries','truncated']) && v.path === p.path && typeof v.truncated === 'boolean' &&
|
|
134
|
+
list(v.entries,200, item => fields(item,['name','type']) && windowsName(item.name) && ['directory','file'].includes(item.type)); break;
|
|
135
|
+
case 'workspace.files.preview': {
|
|
136
|
+
if (!own(p,'offset')) {
|
|
137
|
+
valid = fields(v,['path','text','truncated']) && v.path === p.path && typeof v.truncated === 'boolean' &&
|
|
138
|
+
typeof v.text === 'string' && v.text.length <= 32768 && Buffer.byteLength(v.text) <= 32768 && !/[\x00-\x08\x0b\x0e-\x1f\x7f]/u.test(v.text);
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
const mediaType = previewMediaType(p.path);
|
|
142
|
+
valid = fields(v,['path','offset','totalBytes','revision','mediaType','data']) && v.path === p.path && v.offset === p.offset &&
|
|
143
|
+
uint(v.totalBytes) && v.totalBytes > p.offset && v.totalBytes <= filePreviewMaxBytes && previewRevision(v.revision) &&
|
|
144
|
+
(p.offset === 0 || p.revision === v.revision) && mediaType !== undefined && v.mediaType === mediaType;
|
|
145
|
+
if (valid) {
|
|
146
|
+
const count = Math.min(filePreviewChunkBytes,v.totalBytes-p.offset);
|
|
147
|
+
valid = typeof v.data === 'string' && v.data.length === 4*Math.ceil(count/3);
|
|
148
|
+
if (valid) {
|
|
149
|
+
const chunk = Buffer.from(v.data,'base64');
|
|
150
|
+
valid = chunk.length === count && chunk.toString('base64') === v.data;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case 'question.list':
|
|
156
|
+
valid = fields(v,['items'],['planReviews','pendingApprovals','settled']) && Buffer.byteLength(JSON.stringify(v)) <= 640 * 1024 && list(v.items,16,questionRow) &&
|
|
157
|
+
present(v,'settled',rows=>list(rows,128,settledRow) && new Set(rows.map(row=>row.callId)).size===rows.length) &&
|
|
158
|
+
new Set(v.items.map(row=>row.callId)).size === v.items.length && present(v,'planReviews',rows=>
|
|
159
|
+
list(rows,2,row=>fields(row,['reviewId','callId','markdown']) && key(row.reviewId) && key(row.callId) && planMarkdown(row.markdown)) &&
|
|
160
|
+
new Set(rows.map(row=>row.reviewId)).size === rows.length) && present(v,'pendingApprovals',rows=>
|
|
161
|
+
list(rows,4,approvalRow) && new Set(rows.map(row=>row.approvalId)).size===rows.length); break;
|
|
162
|
+
case 'plan.preview':
|
|
163
|
+
valid = fields(v,['callId','title','markdown']) && v.callId === p.callId && planMarkdown(v.markdown) &&
|
|
164
|
+
v.title === /^#\s+(\S[^\r\n]*)/.exec(v.markdown.trim())?.[1]; break;
|
|
165
|
+
case 'question.answer': case 'question.dismiss': case 'approval.respond': case 'plan.review.respond':
|
|
166
|
+
valid = fields(v,['accepted']) && v.accepted === true; break;
|
|
167
|
+
case 'session.options':
|
|
168
|
+
valid = fields(v,['agentPresets','models','permissionPresets'],['commands','agentTeamDefault']) && list(v.agentPresets,1024,option) &&
|
|
169
|
+
list(v.permissionPresets,1024,option) && catalog(v.models) && present(v,'agentTeamDefault', value => typeof value === 'boolean') &&
|
|
170
|
+
present(v,'commands', names => list(names,sessionCommands.size, name => sessionCommands.has(name)) && new Set(names).size === names.length); break;
|
|
171
|
+
case 'session.command': valid = fields(v,['kind'],['text']) && v.kind === 'success' && present(v,'text', value => typeof value === 'string' && Buffer.byteLength(value) <= 8192 && !value.includes('\u0000')); break;
|
|
172
|
+
case 'session.create': valid = fields(v,['sessionId']) && key(v.sessionId); break;
|
|
173
|
+
default: return v;
|
|
174
|
+
}
|
|
175
|
+
validate(valid, 'operation-failed');
|
|
176
|
+
return v;
|
|
177
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Shared by the desktop, wire, and embedded browser code. No Node/browser IO here.
|
|
2
|
+
export const filePreviewChunkBytes = 128 * 1024;
|
|
3
|
+
export const filePreviewMaxBytes = 8 * 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
export function previewMediaType(path) {
|
|
6
|
+
const suffix = /\.([a-z]+)$/i.exec(path)?.[1].toLowerCase();
|
|
7
|
+
switch (suffix) {
|
|
8
|
+
case 'jpeg': case 'jpg': return 'image/jpeg';
|
|
9
|
+
case 'png': return 'image/png';
|
|
10
|
+
case 'gif': return 'image/gif';
|
|
11
|
+
case 'webp': return 'image/webp';
|
|
12
|
+
case 'bmp': return 'image/bmp';
|
|
13
|
+
case 'ico': return 'image/x-icon';
|
|
14
|
+
case 'pdf': return 'application/pdf';
|
|
15
|
+
default: return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// This is a cheap prefix inspection, not a decoder. The stock body still
|
|
20
|
+
// validates the file. For rasters also bound the decoded canvas dimensions.
|
|
21
|
+
// Reject ambiguous headers instead of letting a browser MIME-sniff the bytes.
|
|
22
|
+
export function inspectPreviewHeader(data, mediaType) {
|
|
23
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
24
|
+
const size = data.byteLength;
|
|
25
|
+
const bytes = (offset, ...expected) => offset + expected.length <= size && expected.every((b,i) => data[offset+i] === b);
|
|
26
|
+
const ascii = (offset, text) => bytes(offset, ...Array.from(text, c => c.charCodeAt(0)));
|
|
27
|
+
const u24 = offset => data[offset] + data[offset+1]*256 + data[offset+2]*65536;
|
|
28
|
+
const image = (w,h) => w > 0 && h > 0 && w <= 8192 && h <= 8192 && w*h <= 16_777_216 ? 'ok' : 'file_preview_dimensions';
|
|
29
|
+
switch (mediaType) {
|
|
30
|
+
case 'application/pdf':
|
|
31
|
+
// Require a real PDF header at byte zero; not HTML or a sniffed MIME type.
|
|
32
|
+
if (size >= 9 && ascii(0,'%PDF-') && (data[5] === 49 || data[5] === 50) && data[6] === 46 && data[7] >= 48 && data[7] <= 57 && [10,13].includes(data[8])) return 'ok';
|
|
33
|
+
break;
|
|
34
|
+
case 'image/png': {
|
|
35
|
+
if (size < 33 || !bytes(0,137,80,78,71,13,10,26) || view.getUint32(8) !== 13 || !ascii(12,'IHDR')) break;
|
|
36
|
+
for (let offset=33; offset+8<=size;) {
|
|
37
|
+
if (ascii(offset+4,'acTL')) return 'file_preview_unsupported';
|
|
38
|
+
if (ascii(offset+4,'IDAT')) return image(view.getUint32(16),view.getUint32(20));
|
|
39
|
+
offset += 12 + view.getUint32(offset);
|
|
40
|
+
}
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
case 'image/jpeg':
|
|
44
|
+
if (!bytes(0,255,216,255)) break;
|
|
45
|
+
for (let offset=2; offset+4<size;) {
|
|
46
|
+
if (data[offset++] !== 255) break;
|
|
47
|
+
while (data[offset] === 255) offset++;
|
|
48
|
+
const marker = data[offset++];
|
|
49
|
+
if (marker === 0xda || marker === 0xd9 || offset + 2 > size) break;
|
|
50
|
+
const len = view.getUint16(offset);
|
|
51
|
+
if (len < 2 || offset + len > size) break;
|
|
52
|
+
if ([0xc0,0xc1,0xc2].includes(marker) && len >= 8) return image(view.getUint16(offset+5),view.getUint16(offset+3));
|
|
53
|
+
offset += len;
|
|
54
|
+
}
|
|
55
|
+
break;
|
|
56
|
+
case 'image/gif':
|
|
57
|
+
if (size >= 13 && (ascii(0,'GIF87a') || ascii(0,'GIF89a'))) return image(view.getUint16(6,true),view.getUint16(8,true));
|
|
58
|
+
break;
|
|
59
|
+
case 'image/webp':
|
|
60
|
+
if (size < 25 || !ascii(0,'RIFF') || !ascii(8,'WEBP')) break;
|
|
61
|
+
if (size >= 30 && ascii(12,'VP8X')) {
|
|
62
|
+
if (data[20] & 2) return 'file_preview_unsupported';
|
|
63
|
+
return image(1+u24(24),1+u24(27));
|
|
64
|
+
}
|
|
65
|
+
if (size >= 30 && ascii(12,'VP8 ') && bytes(23,0x9d,1,0x2a)) return image(view.getUint16(26,true)&0x3fff,view.getUint16(28,true)&0x3fff);
|
|
66
|
+
if (ascii(12,'VP8L') && data[20] === 0x2f) {
|
|
67
|
+
const bits = view.getUint32(21,true);
|
|
68
|
+
return image((bits&0x3fff)+1,((bits>>>14)&0x3fff)+1);
|
|
69
|
+
}
|
|
70
|
+
break;
|
|
71
|
+
case 'image/bmp':
|
|
72
|
+
if (size >= 26 && ascii(0,'BM')) {
|
|
73
|
+
const header = view.getUint32(14,true);
|
|
74
|
+
if (header === 12) return image(view.getUint16(18,true),view.getUint16(20,true));
|
|
75
|
+
if ([40,52,56,108,124].includes(header) && size >= 14+header && [0,1,2,3,6].includes(view.getUint32(30,true))) {
|
|
76
|
+
return image(view.getInt32(18,true),Math.abs(view.getInt32(22,true)));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
break;
|
|
80
|
+
case 'image/x-icon':
|
|
81
|
+
if (size >= 22 && bytes(0,0,0,1,0) && view.getUint16(4,true)>0 && view.getUint16(4,true)<=32 && size>=6+16*view.getUint16(4,true)) return 'ok';
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
return 'file_preview_invalid';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Check the complete image for animation and verify embedded frame dimensions
|
|
88
|
+
// before handing compressed bytes to the native image decoder.
|
|
89
|
+
export function inspectPreviewContent(data, mediaType) {
|
|
90
|
+
const prefix = inspectPreviewHeader(data,mediaType);
|
|
91
|
+
if (prefix !== 'ok') return prefix;
|
|
92
|
+
const view = new DataView(data.buffer,data.byteOffset,data.byteLength);
|
|
93
|
+
const size = data.byteLength;
|
|
94
|
+
if (mediaType === 'image/png') {
|
|
95
|
+
for(let offset=33;offset+12<=size;) {
|
|
96
|
+
const length=view.getUint32(offset);
|
|
97
|
+
if(offset+12+length>size)return 'file_preview_invalid';
|
|
98
|
+
const type=String.fromCharCode(...data.subarray(offset+4,offset+8));
|
|
99
|
+
if(['acTL','fcTL','fdAT'].includes(type))return 'file_preview_unsupported';
|
|
100
|
+
if(type==='IEND')return length===0&&offset+12===size?'ok':'file_preview_invalid';
|
|
101
|
+
offset+=12+length;
|
|
102
|
+
}
|
|
103
|
+
return 'file_preview_invalid';
|
|
104
|
+
}
|
|
105
|
+
if (mediaType === 'image/webp') {
|
|
106
|
+
if(view.getUint32(4,true)+8!==size)return 'file_preview_invalid';
|
|
107
|
+
let frame=false;
|
|
108
|
+
for(let offset=12;offset+8<=size;) {
|
|
109
|
+
const length=view.getUint32(offset+4,true);
|
|
110
|
+
const end=offset+8+length;
|
|
111
|
+
if(end+(length%2)>size)return 'file_preview_invalid';
|
|
112
|
+
const type=String.fromCharCode(...data.subarray(offset,offset+4));
|
|
113
|
+
if(type==='ANIM'||type==='ANMF')return 'file_preview_unsupported';
|
|
114
|
+
if(type==='VP8 '||type==='VP8L') {
|
|
115
|
+
if(frame)return 'file_preview_invalid';
|
|
116
|
+
frame=true;
|
|
117
|
+
const frameHeader=new Uint8Array(30);
|
|
118
|
+
frameHeader.set(data.subarray(0,12));
|
|
119
|
+
frameHeader.set(data.subarray(offset,Math.min(end,offset+18)),12);
|
|
120
|
+
const result=inspectPreviewHeader(frameHeader,'image/webp');
|
|
121
|
+
if(result!=='ok')return result;
|
|
122
|
+
if(String.fromCharCode(...data.subarray(12,16))==='VP8X') {
|
|
123
|
+
const dimension=(bytes,at)=>1+bytes[at]+256*bytes[at+1]+65536*bytes[at+2];
|
|
124
|
+
const bits=new DataView(frameHeader.buffer).getUint32(21,true);
|
|
125
|
+
const w=type==='VP8 '?new DataView(frameHeader.buffer).getUint16(26,true)&0x3fff:(bits&0x3fff)+1;
|
|
126
|
+
const h=type==='VP8 '?new DataView(frameHeader.buffer).getUint16(28,true)&0x3fff:((bits>>>14)&0x3fff)+1;
|
|
127
|
+
if(w!==dimension(data,24)||h!==dimension(data,27))return 'file_preview_invalid';
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
offset=end+(length%2);
|
|
131
|
+
}
|
|
132
|
+
return frame?'ok':'file_preview_invalid';
|
|
133
|
+
}
|
|
134
|
+
if (mediaType === 'image/gif') {
|
|
135
|
+
const table = bits => bits & 128 ? 3 * (2 << (bits & 7)) : 0;
|
|
136
|
+
let pos = 13 + table(data[10]), frames = 0, pixels=0;
|
|
137
|
+
const canvasWidth = view.getUint16(6,true), canvasHeight = view.getUint16(8,true);
|
|
138
|
+
while (pos < size) {
|
|
139
|
+
const marker = data[pos++];
|
|
140
|
+
if (marker === 0x3b) return frames > 0 ? 'ok' : 'file_preview_invalid';
|
|
141
|
+
if (marker === 0x2c && pos + 10 <= size) {
|
|
142
|
+
const x=view.getUint16(pos,true), y=view.getUint16(pos+2,true);
|
|
143
|
+
const w=view.getUint16(pos+4,true), h=view.getUint16(pos+6,true);
|
|
144
|
+
if (!w || !h || x+w > canvasWidth || y+h > canvasHeight || ++frames > 120 || (pixels+=canvasWidth*canvasHeight)>48_000_000) return 'file_preview_dimensions';
|
|
145
|
+
pos += 10 + table(data[pos+8]);
|
|
146
|
+
} else if (marker === 0x21 && pos < size) pos++;
|
|
147
|
+
else break;
|
|
148
|
+
while (pos < size && data[pos] !== 0) pos += data[pos]+1;
|
|
149
|
+
pos++;
|
|
150
|
+
}
|
|
151
|
+
return 'file_preview_invalid';
|
|
152
|
+
}
|
|
153
|
+
if (mediaType === 'image/x-icon') {
|
|
154
|
+
const count=view.getUint16(4,true), directoryEnd=6+16*count;
|
|
155
|
+
for (let i=6;i<directoryEnd;i+=16) {
|
|
156
|
+
const length=view.getUint32(i+8,true), offset=view.getUint32(i+12,true);
|
|
157
|
+
if (length<16 || offset<directoryEnd || offset+length>size) return 'file_preview_invalid';
|
|
158
|
+
const w=data[i]||256,h=data[i+1]||256;
|
|
159
|
+
if (data[offset]===137 && data[offset+1]===80) {
|
|
160
|
+
if (length<33 || view.getUint32(offset+16)!==w || view.getUint32(offset+20)!==h ||
|
|
161
|
+
inspectPreviewHeader(data.subarray(offset,offset+length),'image/png')!=='ok') return 'file_preview_invalid';
|
|
162
|
+
} else {
|
|
163
|
+
const header=view.getUint32(offset,true);
|
|
164
|
+
if (![40,52,56,108,124].includes(header) || length<header || view.getInt32(offset+4,true)!==w || view.getInt32(offset+8,true)!==h*2 ||
|
|
165
|
+
![0,1,2,3,6].includes(view.getUint32(offset+16,true))) return 'file_preview_invalid';
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return 'ok';
|
|
170
|
+
}
|
package/cordis.patch.yml
ADDED