@openchamber/web 1.23.2 → 1.24.0
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/dist/assets/{CodeMirrorCommentWidgets-DdNGwbBw.js → CodeMirrorCommentWidgets-C9kV-n7r.js} +1 -1
- package/dist/assets/DiffView-B7YkbY-u.js +4 -0
- package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +1 -0
- package/dist/assets/FilesView-vjJx7VaM.js +13 -0
- package/dist/assets/GitView-BLhlMYEY.js +6 -0
- package/dist/assets/GuestAttachDialog-B-fwE8r3.js +3 -0
- package/dist/assets/{JsonTreeView-Chzx5Y6N.js → JsonTreeView-D_4G5X6-.js} +1 -1
- package/dist/assets/LinearIssuesView-1uKhePfH.js +1 -0
- package/dist/assets/{MarkdownImageGallery-CugnrZ6f.js → MarkdownImageGallery-Ix7N_2wp.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-Deel_y5S.js +12 -0
- package/dist/assets/{OnboardingScreen-hH9xcTjA.js → OnboardingScreen-ToIakxb_.js} +1 -1
- package/dist/assets/{PatchDiff-DRgNYc9l.js → PatchDiff-BjMgezr1.js} +1 -1
- package/dist/assets/{PierreDiffViewer-ZT2CKuzJ.js → PierreDiffViewer-53Ghfnlr.js} +5 -5
- package/dist/assets/PlanView-BGAzxDwD.js +5 -0
- package/dist/assets/SettingsView-n2X-jfBB.js +29 -0
- package/dist/assets/SettingsWindow-Bi8LE9XI.js +1 -0
- package/dist/assets/SubmoduleDiffSummary--YFqK6Ih.js +1 -0
- package/dist/assets/ToolOutputDialog-DRWBvdaJ.js +15 -0
- package/dist/assets/{ToolPartDiffPreview-oWxWCu-4.js → ToolPartDiffPreview-BxZJCU28.js} +2 -2
- package/dist/assets/{VirtualizedFileDiff-CiyrAq_I.js → VirtualizedFileDiff-DCXjBGRf.js} +3 -3
- package/dist/assets/{WalkthroughView-CKTevaea.js → WalkthroughView-CfIPvWWa.js} +2 -2
- package/dist/assets/appThemeRegistry-DDROzcUO.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-SUWoTyPe.js → computeVirtualFileMetrics-DHgQIkUq.js} +1 -1
- package/dist/assets/de-CX_f-T5U.js +10 -0
- package/dist/assets/es-BERmWNn_.js +16 -0
- package/dist/assets/fr-BjYYE_-z.js +14 -0
- package/dist/assets/index-DpzTz2UH.css +1 -0
- package/dist/assets/index-Dy8xgawx.js +40 -0
- package/dist/assets/{index-C4jJ3Ur5.js → index-WjufPkIV.js} +1 -1
- package/dist/assets/{isDiffPlainText-DfG0cZxr.js → isDiffPlainText-D9faP70y.js} +1 -1
- package/dist/assets/{isFilePlainText-CyNivOCU.js → isFilePlainText-6qOcz5Ky.js} +1 -1
- package/dist/assets/ja-DxqeAk9N.js +16 -0
- package/dist/assets/ko-Dty1aUod.js +16 -0
- package/dist/assets/main-BOYSXfYn.js +896 -0
- package/dist/assets/{main-B8cGozKr.js → main-Bjcre_GE.js} +2 -2
- package/dist/assets/{markdown-shiki.worker-D5fBU-lw.js → markdown-shiki.worker-CahLvHIq.js} +5 -5
- package/dist/assets/{markdownCore-kyGrWGsn.js → markdownCore-DPrwM1rU.js} +5 -5
- package/dist/assets/{miniChat-Cay99IxR.js → miniChat-Dz_bPgMc.js} +2 -2
- package/dist/assets/{mobile-Zfhix7nz.js → mobile-BbZPBJrK.js} +2 -2
- package/dist/assets/{patchFileDiff-CJ5AN9Ql.js → patchFileDiff-BvU6KOQC.js} +3 -3
- package/dist/assets/pl-CX-_ROkr.js +16 -0
- package/dist/assets/{pt-BR-CLosVawq.js → pt-BR-DhRR1arx.js} +4 -4
- package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +2 -0
- package/dist/assets/renderMobileApp-BK1kFlcJ.js +25 -0
- package/dist/assets/runtimeEndpointReset-BULHvOwb.js +25 -0
- package/dist/assets/{scheduledTasksApi-CGFV4Pap.js → scheduledTasksApi-DW3xqMQ8.js} +1 -1
- package/dist/assets/shikiHighlight-DsxD9QEa.js +1 -0
- package/dist/assets/textMateThemeFromAppTheme-Da7ed8qM.js +1 -0
- package/dist/assets/tr-cIQtYBpg.js +7 -0
- package/dist/assets/uk-CD21CXFV.js +16 -0
- package/dist/assets/{useAppFontEffects-DgCHy6Mr.js → useAppFontEffects-hfv2s6mZ.js} +198 -147
- package/dist/assets/useInlineCommentController-BmtfVbo8.js +2 -0
- package/dist/assets/useRootScrollLock-Cwc4kSl2.js +1 -0
- package/dist/assets/{vendor-base-ui-BY_5qla_.js → vendor-base-ui-CsXYnR5c.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-ES33GhKK.js → vendor-codemirror-language-data-BPMJpOpT.js} +2 -2
- package/dist/assets/vendor-framer-motion-Bq3iTZ6r.js +1 -0
- package/dist/assets/{vendor-motion-dom-D_o3BTI3.js → vendor-motion-dom-DcCgeG69.js} +1 -1
- package/dist/assets/vendor-strip-json-comments-5dJlOkP1.js +4 -0
- package/dist/assets/{vendor-zod-B6551dwG.js → vendor-zod-fZppILAM.js} +4 -4
- package/dist/assets/{web-components-CJZwV5BE.js → web-components-U-hWbgJo.js} +2 -2
- package/dist/assets/zh-CN-BWvlPHY-.js +16 -0
- package/dist/assets/zh-TW-CRp5dJU2.js +16 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +7 -5
- package/server/built-in-extensions/registry.json +4 -0
- package/server/index.d.ts +2 -0
- package/server/index.js +15 -3
- package/server/lib/fs/DOCUMENTATION.md +8 -0
- package/server/lib/fs/git-process.test.js +77 -0
- package/server/lib/fs/routes.js +2 -1
- package/server/lib/fs/search.js +2 -1
- package/server/lib/git/DOCUMENTATION.md +3 -1
- package/server/lib/git/routes.js +16 -3
- package/server/lib/git/service.js +112 -8
- package/server/lib/git/service.test.js +127 -0
- package/server/lib/guests/DOCUMENTATION.md +66 -0
- package/server/lib/guests/auth-store.js +184 -0
- package/server/lib/guests/auth-store.test.js +112 -0
- package/server/lib/guests/builtins.js +34 -0
- package/server/lib/guests/builtins.test.js +174 -0
- package/server/lib/guests/catalog.js +466 -0
- package/server/lib/guests/catalog.test.js +390 -0
- package/server/lib/guests/clone.js +297 -0
- package/server/lib/guests/extract-zip.js +136 -0
- package/server/lib/guests/extract-zip.test.js +109 -0
- package/server/lib/guests/files.js +308 -0
- package/server/lib/guests/files.test.js +262 -0
- package/server/lib/guests/grant-scope.js +81 -0
- package/server/lib/guests/grant-scope.test.js +75 -0
- package/server/lib/guests/host-session.js +73 -0
- package/server/lib/guests/host-session.test.js +30 -0
- package/server/lib/guests/html-styles.js +6 -0
- package/server/lib/guests/html-styles.test.js +45 -0
- package/server/lib/guests/html-tokens.js +73 -0
- package/server/lib/guests/html-tokens.test.js +53 -0
- package/server/lib/guests/install.js +406 -0
- package/server/lib/guests/install.test.js +338 -0
- package/server/lib/guests/oauth.js +501 -0
- package/server/lib/guests/oauth.test.js +481 -0
- package/server/lib/guests/persist.js +336 -0
- package/server/lib/guests/persist.test.js +288 -0
- package/server/lib/guests/request.js +112 -0
- package/server/lib/guests/request.test.js +206 -0
- package/server/lib/guests/routes.js +838 -0
- package/server/lib/guests/service.js +538 -0
- package/server/lib/guests/service.test.js +277 -0
- package/server/lib/guests/sockets.js +129 -0
- package/server/lib/guests/sockets.test.js +110 -0
- package/server/lib/guests/ssh-install.test.js +188 -0
- package/server/lib/guests/storage.js +68 -0
- package/server/lib/guests/storage.test.js +59 -0
- package/server/lib/guests/updates.js +294 -0
- package/server/lib/guests/updates.test.js +334 -0
- package/server/lib/guests/upload.js +50 -0
- package/server/lib/guests/upload.test.js +131 -0
- package/server/lib/linear/DOCUMENTATION.md +1 -1
- package/server/lib/openchamber-control/DOCUMENTATION.md +6 -0
- package/server/lib/openchamber-sessions/routes.js +44 -11
- package/server/lib/openchamber-sessions/routes.test.js +47 -0
- package/server/lib/opencode/DOCUMENTATION.md +40 -0
- package/server/lib/opencode/core-routes.js +39 -1
- package/server/lib/opencode/feature-routes-runtime.js +10 -0
- package/server/lib/opencode/lifecycle-process.test.js +84 -0
- package/server/lib/opencode/lifecycle.js +54 -67
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/opencode/settings-normalization-runtime.test.js +13 -0
- package/server/lib/opencode/settings-registry.json +4 -0
- package/server/lib/opencode/shutdown-runtime.js +3 -0
- package/server/lib/opencode/shutdown-runtime.test.js +24 -0
- package/server/lib/opencode/theme-archive.js +53 -0
- package/server/lib/opencode/theme-catalog.js +171 -0
- package/server/lib/opencode/theme-catalog.test.js +125 -0
- package/server/lib/opencode/theme-import.test.js +144 -0
- package/server/lib/opencode/theme-runtime.js +100 -28
- package/server/lib/opencode/theme-runtime.test.js +15 -0
- package/server/lib/quota/DOCUMENTATION.md +0 -1
- package/server/lib/quota/providers/index.js +0 -7
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +17 -2
- package/server/lib/terminal/runtime.test.js +45 -0
- package/server/lib/ui-auth/ui-auth.js +43 -8
- package/server/lib/ui-auth/ui-auth.test.js +40 -0
- package/dist/assets/DiffView-GYriC0Wk.js +0 -4
- package/dist/assets/DirtyBranchSwitchDialog-Bv0C99hc.js +0 -1
- package/dist/assets/FilesView-2Lin13wx.js +0 -13
- package/dist/assets/GitView-9wKba3UO.js +0 -6
- package/dist/assets/LinearIssuesView-DXS9QJiR.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CaMyct2Q.js +0 -12
- package/dist/assets/PlanView-DiTBm2BD.js +0 -5
- package/dist/assets/SettingsView-CN8VeM99.js +0 -28
- package/dist/assets/SettingsWindow-DisOghhD.js +0 -1
- package/dist/assets/ToolOutputDialog-BqiKydxR.js +0 -15
- package/dist/assets/appThemeRegistry-BK0dHKa6.js +0 -1
- package/dist/assets/de-DQWC94VK.js +0 -10
- package/dist/assets/es-DixFUD3m.js +0 -16
- package/dist/assets/fr-D6u8tvfA.js +0 -14
- package/dist/assets/index-BvpFzhLs.js +0 -40
- package/dist/assets/index-n5p3SnES.css +0 -1
- package/dist/assets/ja-4u4pCorB.js +0 -16
- package/dist/assets/ko-C27-LW_b.js +0 -16
- package/dist/assets/main-tEA-fFPg.js +0 -930
- package/dist/assets/pl-FtCjsNdW.js +0 -16
- package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-CuHOGlF4.js +0 -2
- package/dist/assets/renderMobileApp-C4X_KUH8.js +0 -25
- package/dist/assets/runtimeEndpointReset-CMg-KUx3.js +0 -41
- package/dist/assets/shikiHighlight-DdKWYWrV.js +0 -1
- package/dist/assets/tr-D2j6wUez.js +0 -7
- package/dist/assets/uk-C6IzmwM_.js +0 -16
- package/dist/assets/useGitComparison-BIaI0WZI.js +0 -1
- package/dist/assets/useInlineCommentController-2wcCtpM3.js +0 -2
- package/dist/assets/useRootScrollLock-CbWA03xR.js +0 -1
- package/dist/assets/vendor-framer-motion-livSKyyV.js +0 -1
- package/dist/assets/zh-CN-Wl6tIDz1.js +0 -16
- package/dist/assets/zh-TW-hgphoWSN.js +0 -16
- package/server/lib/quota/providers/crof.js +0 -96
- package/server/lib/quota/providers/crof.test.js +0 -98
|
@@ -154,6 +154,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
|
|
|
154
154
|
: null;
|
|
155
155
|
const iconBackground = normalizeIconBackground(candidate.iconBackground);
|
|
156
156
|
const color = typeof candidate.color === 'string' ? candidate.color.trim() : '';
|
|
157
|
+
const defaultAgent = typeof candidate.defaultAgent === 'string' ? candidate.defaultAgent.trim() : '';
|
|
157
158
|
const defaultModel = typeof candidate.defaultModel === 'string' ? candidate.defaultModel.trim() : '';
|
|
158
159
|
const defaultVariant = typeof candidate.defaultVariant === 'string' ? candidate.defaultVariant.trim() : '';
|
|
159
160
|
const addedAt = Number.isFinite(candidate.addedAt) ? Number(candidate.addedAt) : null;
|
|
@@ -175,6 +176,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
|
|
|
175
176
|
...(icon ? { icon } : {}),
|
|
176
177
|
...(iconBackground ? { iconBackground } : {}),
|
|
177
178
|
...(color ? { color } : {}),
|
|
179
|
+
...(defaultAgent ? { defaultAgent } : {}),
|
|
178
180
|
...(defaultModel && defaultModel.includes('/') ? { defaultModel } : {}),
|
|
179
181
|
// A variant is meaningless without the model it belongs to.
|
|
180
182
|
...(defaultModel && defaultModel.includes('/') && defaultVariant ? { defaultVariant } : {}),
|
|
@@ -122,6 +122,19 @@ describe('settings normalization runtime - symlink resolution', () => {
|
|
|
122
122
|
expect(result[1].defaultVariant).toBe(undefined);
|
|
123
123
|
});
|
|
124
124
|
|
|
125
|
+
it('keeps a project default agent', () => {
|
|
126
|
+
const runtime = createTestRuntime({
|
|
127
|
+
realpathSync: (p) => p,
|
|
128
|
+
path: { resolve: (p) => p, sep: '/', dirname: (p) => p.split('/').slice(0, -1).join('/') || '/' },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const result = runtime.sanitizeProjects([
|
|
132
|
+
{ id: 'proj1', path: '/a', defaultAgent: 'plan' },
|
|
133
|
+
]);
|
|
134
|
+
|
|
135
|
+
expect(result[0].defaultAgent).toBe('plan');
|
|
136
|
+
});
|
|
137
|
+
|
|
125
138
|
it('deduplicates projects that resolve to the same realpath', () => {
|
|
126
139
|
const runtime = createTestRuntime({
|
|
127
140
|
realpathSync: (p) => p.startsWith('/symlink') ? '/real/project' : p,
|
|
@@ -108,6 +108,9 @@ export const createGracefulShutdownRuntime = (dependencies) => {
|
|
|
108
108
|
console.log('HTTP server closed');
|
|
109
109
|
resolve();
|
|
110
110
|
});
|
|
111
|
+
// The backend has stopped. Active SSE/HTTP clients must not keep
|
|
112
|
+
// Desktop waiting for the outer shutdown deadline.
|
|
113
|
+
server.closeAllConnections?.();
|
|
111
114
|
}),
|
|
112
115
|
new Promise((resolve) => {
|
|
113
116
|
closeTimeout = setTimeout(() => {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import http from 'node:http';
|
|
2
3
|
|
|
3
4
|
import { createGracefulShutdownRuntime } from './shutdown-runtime.js';
|
|
4
5
|
|
|
@@ -55,4 +56,27 @@ describe('graceful shutdown runtime', () => {
|
|
|
55
56
|
expect(warnSpy).not.toHaveBeenCalledWith('Server close timeout reached, forcing shutdown');
|
|
56
57
|
expect(vi.getTimerCount()).toBe(0);
|
|
57
58
|
});
|
|
59
|
+
|
|
60
|
+
it('closes an active HTTP stream instead of waiting for the shutdown deadline', async () => {
|
|
61
|
+
const server = http.createServer((_request, response) => {
|
|
62
|
+
response.writeHead(200, { 'content-type': 'text/event-stream' });
|
|
63
|
+
response.write('data: fixture\n\n');
|
|
64
|
+
});
|
|
65
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
66
|
+
const request = http.get(`http://127.0.0.1:${server.address().port}`);
|
|
67
|
+
request.on('error', () => {});
|
|
68
|
+
const response = await new Promise((resolve) => request.once('response', resolve));
|
|
69
|
+
response.resume();
|
|
70
|
+
const closed = new Promise((resolve) => response.once('close', resolve));
|
|
71
|
+
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
72
|
+
try {
|
|
73
|
+
await createRuntime(server).gracefulShutdown({ exitProcess: false });
|
|
74
|
+
expect(warning).not.toHaveBeenCalledWith('Server close timeout reached, forcing shutdown');
|
|
75
|
+
await closed;
|
|
76
|
+
} finally {
|
|
77
|
+
request.destroy();
|
|
78
|
+
server.closeAllConnections();
|
|
79
|
+
await new Promise((resolve) => server.close(resolve));
|
|
80
|
+
}
|
|
81
|
+
});
|
|
58
82
|
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { inflateRaw } from 'node:zlib';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
|
|
4
|
+
const inflate = promisify(inflateRaw);
|
|
5
|
+
const MAX_FILE_BYTES = 512 * 1024;
|
|
6
|
+
|
|
7
|
+
// Read only selected JSON entries in memory. Nothing from a VSIX is executed or
|
|
8
|
+
// extracted onto the host filesystem.
|
|
9
|
+
export function openThemeArchive(bytes) {
|
|
10
|
+
let end = bytes.length - 22;
|
|
11
|
+
const lower = Math.max(0, end - 65535);
|
|
12
|
+
while (end >= lower && (bytes.readUInt32LE(end) !== 0x06054b50 || end + 22 + bytes.readUInt16LE(end + 20) !== bytes.length)) end--;
|
|
13
|
+
if (end < lower) throw new Error('Invalid VSIX directory');
|
|
14
|
+
const count = bytes.readUInt16LE(end + 10);
|
|
15
|
+
const directorySize = bytes.readUInt32LE(end + 12);
|
|
16
|
+
let cursor = bytes.readUInt32LE(end + 16);
|
|
17
|
+
if (count > 5000 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6)
|
|
18
|
+
|| bytes.readUInt16LE(end + 8) !== count || cursor + directorySize !== end) throw new Error('Unsupported VSIX directory');
|
|
19
|
+
const entries = new Map();
|
|
20
|
+
let totalSize = 0;
|
|
21
|
+
for (let index = 0; index < count; index++) {
|
|
22
|
+
if (cursor + 46 > end || bytes.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid VSIX entry');
|
|
23
|
+
const flags = bytes.readUInt16LE(cursor + 8);
|
|
24
|
+
const method = bytes.readUInt16LE(cursor + 10);
|
|
25
|
+
const compressed = bytes.readUInt32LE(cursor + 20);
|
|
26
|
+
const size = bytes.readUInt32LE(cursor + 24);
|
|
27
|
+
const nameLength = bytes.readUInt16LE(cursor + 28);
|
|
28
|
+
const next = cursor + 46 + nameLength + bytes.readUInt16LE(cursor + 30) + bytes.readUInt16LE(cursor + 32);
|
|
29
|
+
const offset = bytes.readUInt32LE(cursor + 42);
|
|
30
|
+
if (next > end || nameLength > 1024 || flags & 1 || ![0, 8].includes(method)) throw new Error('Unsupported VSIX entry');
|
|
31
|
+
const name = bytes.toString('utf8', cursor + 46, cursor + 46 + nameLength);
|
|
32
|
+
const parts = name.replace(/\/$/, '').split('/');
|
|
33
|
+
if (parts.some((part) => !part || part === '.' || part === '..') || /[\\\0:]/.test(name) || entries.has(name)) throw new Error('Unsafe VSIX path');
|
|
34
|
+
totalSize += size;
|
|
35
|
+
if (totalSize > 100 * 1024 * 1024) throw new Error('VSIX contents too large');
|
|
36
|
+
entries.set(name, { offset, compressed, size, method });
|
|
37
|
+
cursor = next;
|
|
38
|
+
}
|
|
39
|
+
if (cursor !== end) throw new Error('Invalid VSIX directory size');
|
|
40
|
+
return async (name) => {
|
|
41
|
+
const entry = entries.get(name);
|
|
42
|
+
if (!entry || entry.size > MAX_FILE_BYTES) throw new Error('Theme file missing or too large');
|
|
43
|
+
const { offset, compressed, size, method } = entry;
|
|
44
|
+
if (offset + 30 > bytes.length || bytes.readUInt32LE(offset) !== 0x04034b50 || bytes.readUInt16LE(offset + 8) !== method) throw new Error('Invalid VSIX file');
|
|
45
|
+
const nameLength = bytes.readUInt16LE(offset + 26);
|
|
46
|
+
const start = offset + 30 + nameLength + bytes.readUInt16LE(offset + 28);
|
|
47
|
+
if (start + compressed > bytes.length || bytes.toString('utf8', offset + 30, offset + 30 + nameLength) !== name) throw new Error('Invalid VSIX file bounds');
|
|
48
|
+
const data = bytes.subarray(start, start + compressed);
|
|
49
|
+
const result = method === 0 ? data : await inflate(data, { maxOutputLength: MAX_FILE_BYTES });
|
|
50
|
+
if (result.length !== size) throw new Error('Invalid VSIX file size');
|
|
51
|
+
return result.toString('utf8');
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { parse } from 'jsonc-parser';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { openThemeArchive } from './theme-archive.js';
|
|
6
|
+
|
|
7
|
+
const identifier = z.string().min(1).max(160).regex(/^[\w-]+$/);
|
|
8
|
+
const version = z.string().min(1).max(80).regex(/^[\w.+-]+$/);
|
|
9
|
+
const settings = z.object({ foreground: z.string().optional() });
|
|
10
|
+
const tokenRules = z.array(z.object({ scope: z.union([z.string(), z.array(z.string())]).optional(), settings }));
|
|
11
|
+
const sourceSchema = z.object({
|
|
12
|
+
name: z.string().optional(), type: z.string().optional(), include: z.string().optional(),
|
|
13
|
+
colors: z.record(z.string(), z.string().nullable()).default({}),
|
|
14
|
+
tokenColors: z.union([z.string(), tokenRules]).optional(),
|
|
15
|
+
semanticHighlighting: z.boolean().optional(),
|
|
16
|
+
semanticTokenColors: z.record(z.string(), z.union([z.string(), settings])).optional(),
|
|
17
|
+
});
|
|
18
|
+
const extensionSchema = z.object({
|
|
19
|
+
namespace: identifier, name: identifier, version,
|
|
20
|
+
displayName: z.string().optional(), files: z.object({ icon: z.string().optional() }),
|
|
21
|
+
});
|
|
22
|
+
const detailSchema = extensionSchema.extend({ files: z.object({ download: z.string(), sha256: z.string() }) });
|
|
23
|
+
const manifestSchema = z.object({
|
|
24
|
+
publisher: identifier, name: identifier, version,
|
|
25
|
+
contributes: z.object({ themes: z.array(z.object({
|
|
26
|
+
label: z.string().min(1).max(160), path: z.string().min(1).max(1024),
|
|
27
|
+
uiTheme: z.enum(['vs', 'vs-dark', 'hc-black', 'hc-light']).optional(),
|
|
28
|
+
})).min(1).max(40) }),
|
|
29
|
+
});
|
|
30
|
+
const querySchema = z.object({ query: z.string().trim().min(1).max(160) });
|
|
31
|
+
const packageSchema = z.object({ namespace: identifier, name: identifier, version });
|
|
32
|
+
const hosts = new Set(['open-vsx.org', 'openvsx.eclipsecontent.org']);
|
|
33
|
+
|
|
34
|
+
function trustedUrl(value) {
|
|
35
|
+
const url = new URL(value);
|
|
36
|
+
if (url.protocol !== 'https:' || !hosts.has(url.hostname) || url.port || url.username || url.password) throw new Error('Unexpected catalog host');
|
|
37
|
+
return url;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function download(url, maxBytes, signal, fetchImpl) {
|
|
41
|
+
for (let redirects = 0; redirects < 4; redirects++) {
|
|
42
|
+
const response = await fetchImpl(trustedUrl(url), { signal, redirect: 'manual' });
|
|
43
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
44
|
+
await response.body?.cancel();
|
|
45
|
+
url = new URL(response.headers.get('location') ?? '', url).href;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (!response.ok || !response.body || Number(response.headers.get('content-length')) > maxBytes) {
|
|
49
|
+
await response.body?.cancel();
|
|
50
|
+
throw new Error('Catalog request failed');
|
|
51
|
+
}
|
|
52
|
+
const reader = response.body.getReader();
|
|
53
|
+
const chunks = [];
|
|
54
|
+
let length = 0;
|
|
55
|
+
try {
|
|
56
|
+
while (true) {
|
|
57
|
+
const { done, value } = await reader.read();
|
|
58
|
+
if (done) break;
|
|
59
|
+
length += value.byteLength;
|
|
60
|
+
if (length > maxBytes) throw new Error('Catalog response too large');
|
|
61
|
+
chunks.push(value);
|
|
62
|
+
}
|
|
63
|
+
} finally {
|
|
64
|
+
await reader.cancel();
|
|
65
|
+
reader.releaseLock();
|
|
66
|
+
}
|
|
67
|
+
return Buffer.concat(chunks, length);
|
|
68
|
+
}
|
|
69
|
+
throw new Error('Too many catalog redirects');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseJsonc(text, schema) {
|
|
73
|
+
const errors = [];
|
|
74
|
+
const value = parse(text, errors, { allowTrailingComma: true });
|
|
75
|
+
if (errors.length) throw new Error('Invalid theme JSON');
|
|
76
|
+
return schema.parse(value);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function themePath(from, reference) {
|
|
80
|
+
if (/[\\\0:]/.test(reference) || reference.startsWith('/')) throw new Error('Invalid theme reference');
|
|
81
|
+
const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(from), reference));
|
|
82
|
+
if (!resolved.startsWith('extension/')) throw new Error('Theme reference escapes package');
|
|
83
|
+
return resolved;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function createThemeCatalog({ fetchImpl = fetch } = {}) {
|
|
87
|
+
const search = async (input, signal = AbortSignal.timeout(15000)) => {
|
|
88
|
+
const { query } = querySchema.parse(input);
|
|
89
|
+
const url = new URL('https://open-vsx.org/api/-/search');
|
|
90
|
+
url.search = new URLSearchParams({ query, category: 'Themes', size: '24', sortBy: 'relevance' }).toString();
|
|
91
|
+
const bytes = await download(url.href, 1024 * 1024, signal, fetchImpl);
|
|
92
|
+
const result = z.object({ extensions: z.array(extensionSchema).max(24) }).parse(JSON.parse(bytes.toString('utf8')));
|
|
93
|
+
return result.extensions.map((extension) => ({
|
|
94
|
+
namespace: extension.namespace, name: extension.name, version: extension.version,
|
|
95
|
+
label: extension.displayName || extension.name,
|
|
96
|
+
icon: extension.files.icon && URL.canParse(extension.files.icon) && hosts.has(new URL(extension.files.icon).hostname)
|
|
97
|
+
? trustedUrl(extension.files.icon).href : null,
|
|
98
|
+
}));
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const readPackage = async (input, signal = AbortSignal.timeout(45000)) => {
|
|
102
|
+
const requested = packageSchema.parse(input);
|
|
103
|
+
const url = `https://open-vsx.org/api/${requested.namespace}/${requested.name}/${requested.version}`;
|
|
104
|
+
const detail = detailSchema.parse(JSON.parse((await download(url, 512 * 1024, signal, fetchImpl)).toString('utf8')));
|
|
105
|
+
const bytes = await download(detail.files.download, 20 * 1024 * 1024, signal, fetchImpl);
|
|
106
|
+
const checksum = (await download(detail.files.sha256, 256, signal, fetchImpl)).toString('utf8').trim().split(/\s+/)[0];
|
|
107
|
+
if (createHash('sha256').update(bytes).digest('hex') !== checksum?.toLowerCase()) throw new Error('VSIX checksum mismatch');
|
|
108
|
+
const read = openThemeArchive(bytes);
|
|
109
|
+
const manifest = parseJsonc(await read('extension/package.json'), manifestSchema);
|
|
110
|
+
if (manifest.publisher.toLowerCase() !== requested.namespace.toLowerCase() || manifest.name !== requested.name || manifest.version !== requested.version) throw new Error('VSIX identity mismatch');
|
|
111
|
+
let reads = 0;
|
|
112
|
+
const load = async (file, ancestors = []) => {
|
|
113
|
+
signal.throwIfAborted();
|
|
114
|
+
if (ancestors.includes(file) || ancestors.length >= 8 || ++reads > 320) throw new Error('Too many theme references');
|
|
115
|
+
const source = parseJsonc(await read(file), sourceSchema);
|
|
116
|
+
const parent = source.include ? await load(themePath(file, source.include), [...ancestors, file]) : null;
|
|
117
|
+
const reference = z.string().safeParse(source.tokenColors);
|
|
118
|
+
const rules = reference.success
|
|
119
|
+
? parseJsonc(await read(themePath(file, reference.data)), tokenRules) : tokenRules.parse(source.tokenColors ?? []);
|
|
120
|
+
const { include: _include, ...own } = source;
|
|
121
|
+
return {
|
|
122
|
+
...parent, ...own,
|
|
123
|
+
colors: { ...parent?.colors, ...source.colors },
|
|
124
|
+
tokenColors: [...(parent?.tokenColors ?? []), ...(rules ?? [])],
|
|
125
|
+
semanticTokenColors: { ...parent?.semanticTokenColors, ...source.semanticTokenColors },
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const themes = [];
|
|
129
|
+
let totalBytes = 0;
|
|
130
|
+
for (const contribution of manifest.contributes.themes) {
|
|
131
|
+
try {
|
|
132
|
+
const file = themePath('extension/package.json', contribution.path);
|
|
133
|
+
const source = await load(file);
|
|
134
|
+
source.name = contribution.label;
|
|
135
|
+
if (contribution.uiTheme) source.type = contribution.uiTheme === 'vs' ? 'light' : contribution.uiTheme === 'vs-dark' ? 'dark' : contribution.uiTheme;
|
|
136
|
+
const text = JSON.stringify(source);
|
|
137
|
+
totalBytes += Buffer.byteLength(text);
|
|
138
|
+
if (Buffer.byteLength(text) > 512 * 1024 || totalBytes > 10 * 1024 * 1024) throw new Error('Resolved themes too large');
|
|
139
|
+
themes.push({ path: contribution.path, name: contribution.label, text, error: false });
|
|
140
|
+
} catch {
|
|
141
|
+
signal.throwIfAborted();
|
|
142
|
+
themes.push({ path: contribution.path, name: contribution.label, text: '', error: true });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return themes;
|
|
146
|
+
};
|
|
147
|
+
return { search, readPackage };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function registerThemeCatalogRoutes(app, catalog = createThemeCatalog()) {
|
|
151
|
+
for (const [route, operation, schema] of [
|
|
152
|
+
['/api/config/themes/catalog/search', catalog.search, querySchema],
|
|
153
|
+
['/api/config/themes/catalog/package', catalog.readPackage, packageSchema],
|
|
154
|
+
]) {
|
|
155
|
+
app.post(route, async (req, res) => {
|
|
156
|
+
const input = schema.safeParse(req.body);
|
|
157
|
+
if (!input.success) return res.status(400).json({ error: 'invalid' });
|
|
158
|
+
const controller = new AbortController();
|
|
159
|
+
const cancel = () => controller.abort();
|
|
160
|
+
res.on('close', cancel);
|
|
161
|
+
try {
|
|
162
|
+
const items = await operation(input.data, AbortSignal.any([controller.signal, AbortSignal.timeout(45000)]));
|
|
163
|
+
res.json({ items });
|
|
164
|
+
} catch {
|
|
165
|
+
if (!res.destroyed) res.status(502).json({ error: 'catalog' });
|
|
166
|
+
} finally {
|
|
167
|
+
res.off('close', cancel);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { deflateRawSync } from 'node:zlib';
|
|
4
|
+
import { createThemeCatalog, registerThemeCatalogRoutes } from './theme-catalog.js';
|
|
5
|
+
import { registerCommonRequestMiddleware } from './core-routes.js';
|
|
6
|
+
import express from 'express';
|
|
7
|
+
import request from 'supertest';
|
|
8
|
+
import { openThemeArchive } from './theme-archive.js';
|
|
9
|
+
|
|
10
|
+
function archive(files) {
|
|
11
|
+
const locals = [];
|
|
12
|
+
const directory = [];
|
|
13
|
+
let offset = 0;
|
|
14
|
+
for (const [filename, content] of Object.entries(files)) {
|
|
15
|
+
const name = Buffer.from(filename);
|
|
16
|
+
const data = Buffer.from(content);
|
|
17
|
+
const compressed = deflateRawSync(data);
|
|
18
|
+
const header = Buffer.alloc(30);
|
|
19
|
+
header.writeUInt32LE(0x04034b50);
|
|
20
|
+
header.writeUInt16LE(8, 8);
|
|
21
|
+
header.writeUInt32LE(compressed.length, 18);
|
|
22
|
+
header.writeUInt32LE(data.length, 22);
|
|
23
|
+
header.writeUInt16LE(name.length, 26);
|
|
24
|
+
locals.push(header, name, compressed);
|
|
25
|
+
const central = Buffer.alloc(46);
|
|
26
|
+
central.writeUInt32LE(0x02014b50);
|
|
27
|
+
central.writeUInt16LE(8, 10);
|
|
28
|
+
central.writeUInt32LE(compressed.length, 20);
|
|
29
|
+
central.writeUInt32LE(data.length, 24);
|
|
30
|
+
central.writeUInt16LE(name.length, 28);
|
|
31
|
+
central.writeUInt32LE(offset, 42);
|
|
32
|
+
directory.push(central, name);
|
|
33
|
+
offset += header.length + name.length + compressed.length;
|
|
34
|
+
}
|
|
35
|
+
const end = Buffer.alloc(22);
|
|
36
|
+
end.writeUInt32LE(0x06054b50);
|
|
37
|
+
end.writeUInt16LE(directory.length / 2, 8);
|
|
38
|
+
end.writeUInt16LE(directory.length / 2, 10);
|
|
39
|
+
end.writeUInt32LE(Buffer.concat(directory).length, 12);
|
|
40
|
+
end.writeUInt32LE(offset, 16);
|
|
41
|
+
return Buffer.concat([...locals, ...directory, end]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const identity = { namespace: 'Author', name: 'fixture', version: '1.0.0' };
|
|
45
|
+
const manifest = { publisher: 'Author', name: 'fixture', version: '1.0.0', contributes: { themes: [
|
|
46
|
+
{ label: 'Readable Night', path: './themes/night.json', uiTheme: 'vs-dark' },
|
|
47
|
+
{ label: 'Broken sibling', path: '../../outside.json', uiTheme: 'vs' },
|
|
48
|
+
] } };
|
|
49
|
+
const packageFiles = {
|
|
50
|
+
'extension/package.json': JSON.stringify(manifest),
|
|
51
|
+
'extension/base.json': '{"colors":{"editor.background":"#111111","editor.foreground":"#eeeeee"},"tokenColors":[{"scope":"string","settings":{"foreground":"#aaaaaa"}}]}',
|
|
52
|
+
'extension/themes/night.json': '{ // JSONC\n"include":"../base.json", "colors":{"editor.foreground":"#ffffff"},"tokenColors":"./tokens.json",}',
|
|
53
|
+
'extension/themes/tokens.json': '[{"scope":"keyword","settings":{"foreground":"#aabbcc"}}]',
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function transport(bytes, overrides = {}) {
|
|
57
|
+
const responses = new Map([
|
|
58
|
+
['https://open-vsx.org/api/Author/fixture/1.0.0', JSON.stringify({ ...identity, files: { download: 'https://open-vsx.org/package.vsix', sha256: 'https://open-vsx.org/package.sha256' } })],
|
|
59
|
+
['https://open-vsx.org/package.vsix', bytes],
|
|
60
|
+
['https://open-vsx.org/package.sha256', createHash('sha256').update(bytes).digest('hex')],
|
|
61
|
+
...Object.entries(overrides),
|
|
62
|
+
]);
|
|
63
|
+
return async (url) => {
|
|
64
|
+
const body = responses.get(url.href);
|
|
65
|
+
if (body === undefined) throw new Error(`Unexpected request ${url}`);
|
|
66
|
+
return new Response(body);
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
describe('Open VSX theme catalog', () => {
|
|
71
|
+
test('catalog requests retain their bodies through the production middleware', async () => {
|
|
72
|
+
const app = express();
|
|
73
|
+
registerCommonRequestMiddleware(app, { express });
|
|
74
|
+
const catalog = createThemeCatalog({ fetchImpl: transport(archive(packageFiles)) });
|
|
75
|
+
registerThemeCatalogRoutes(app, {
|
|
76
|
+
search: async (input) => { expect(input).toEqual({ query: 'nord' }); return []; },
|
|
77
|
+
readPackage: catalog.readPackage,
|
|
78
|
+
});
|
|
79
|
+
await request(app).post('/api/config/themes/catalog/search').send({ query: 'nord' }).expect(200);
|
|
80
|
+
const response = await request(app).post('/api/config/themes/catalog/package').send(identity).expect(200);
|
|
81
|
+
expect(response.body.items[0].name).toBe('Readable Night');
|
|
82
|
+
});
|
|
83
|
+
test('resolves JSONC includes and external token files, preserving healthy siblings and manifest labels', async () => {
|
|
84
|
+
const catalog = createThemeCatalog({ fetchImpl: transport(archive(packageFiles)) });
|
|
85
|
+
const result = await catalog.readPackage(identity);
|
|
86
|
+
expect(result[0].error).toBe(false);
|
|
87
|
+
const source = JSON.parse(result[0].text);
|
|
88
|
+
expect(source.name).toBe('Readable Night');
|
|
89
|
+
expect(source.type).toBe('dark');
|
|
90
|
+
expect(source.colors).toEqual({ 'editor.background': '#111111', 'editor.foreground': '#ffffff' });
|
|
91
|
+
expect(source.tokenColors.map((rule) => rule.scope)).toEqual(['string', 'keyword']);
|
|
92
|
+
expect(source.include).toBeUndefined();
|
|
93
|
+
expect(result[1].error).toBe(true);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('rejects checksum and package identity mismatches', async () => {
|
|
97
|
+
const bytes = archive(packageFiles);
|
|
98
|
+
await expect(createThemeCatalog({ fetchImpl: transport(bytes, { 'https://open-vsx.org/package.sha256': '0'.repeat(64) }) }).readPackage(identity)).rejects.toThrow('checksum');
|
|
99
|
+
const wrong = archive({ ...packageFiles, 'extension/package.json': JSON.stringify({ ...manifest, publisher: 'Impostor' }) });
|
|
100
|
+
await expect(createThemeCatalog({ fetchImpl: transport(wrong) }).readPackage(identity)).rejects.toThrow('identity');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('limits decompression and rejects traversal and cyclic includes', async () => {
|
|
104
|
+
expect(() => openThemeArchive(archive({ '../outside.json': '{}' }))).toThrow('Unsafe');
|
|
105
|
+
const read = openThemeArchive(archive({ 'extension/huge.json': ' '.repeat(512 * 1024 + 1) }));
|
|
106
|
+
await expect(read('extension/huge.json')).rejects.toThrow('large');
|
|
107
|
+
const cyclic = archive({ ...packageFiles, 'extension/base.json': '{"include":"./themes/night.json"}' });
|
|
108
|
+
expect((await createThemeCatalog({ fetchImpl: transport(cyclic) }).readPackage(identity))[0].error).toBe(true);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('searches only the theme category and rejects redirects outside the catalog', async () => {
|
|
112
|
+
const catalog = createThemeCatalog({ fetchImpl: async (url, options) => {
|
|
113
|
+
expect(url.searchParams.get('category')).toBe('Themes');
|
|
114
|
+
expect(url.searchParams.get('query')).toBe('Dune');
|
|
115
|
+
expect(options.redirect).toBe('manual');
|
|
116
|
+
return Response.json({ extensions: [{ ...identity, displayName: 'Dune', files: {} }] });
|
|
117
|
+
} });
|
|
118
|
+
expect((await catalog.search({ query: 'Dune' }))[0].label).toBe('Dune');
|
|
119
|
+
let calls = 0;
|
|
120
|
+
const hostile = createThemeCatalog({ fetchImpl: async () => { calls++; return new Response(null, { status: 302, headers: { location: 'http://127.0.0.1/private' } }); } });
|
|
121
|
+
await expect(hostile.search({ query: 'Dune' })).rejects.toThrow('host');
|
|
122
|
+
expect(calls).toBe(1);
|
|
123
|
+
await expect(catalog.readPackage({ ...identity, name: '../secret' })).rejects.toThrow();
|
|
124
|
+
});
|
|
125
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import * as fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import express from 'express';
|
|
6
|
+
import request from 'supertest';
|
|
7
|
+
import { createThemeRuntime } from './theme-runtime.js';
|
|
8
|
+
import { registerSettingsUtilityRoutes, registerCommonRequestMiddleware } from './core-routes.js';
|
|
9
|
+
|
|
10
|
+
const directories = [];
|
|
11
|
+
afterEach(async () => {
|
|
12
|
+
await Promise.all(directories.splice(0).map((directory) => fs.rm(directory, { recursive: true, force: true })));
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
const definition = {
|
|
16
|
+
metadata: { id: '../../escape', name: 'Imported fixture', variant: 'dark' },
|
|
17
|
+
colors: {
|
|
18
|
+
primary: { base: '#ffcc66' },
|
|
19
|
+
surface: { background: '#111111', foreground: '#eeeeee', muted: '#181818', mutedForeground: '#999999', elevated: '#222222' },
|
|
20
|
+
interactive: { border: '#333333' },
|
|
21
|
+
status: { error: '#ff6666', warning: '#ffcc66', success: '#66cc66', info: '#66aaff' },
|
|
22
|
+
syntax: { base: { comment: '#888888', keyword: '#aa88ff', string: '#88cc66', number: '#ffcc66', function: '#66aaff', variable: '#eeeeee', type: '#66dddd', operator: '#ff6677' } },
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
async function setup(overrides = {}) {
|
|
27
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'oc-theme-import-'));
|
|
28
|
+
directories.push(root);
|
|
29
|
+
const themesDir = path.join(root, 'themes');
|
|
30
|
+
const runtime = createThemeRuntime({ fsPromises: { ...fs, ...overrides }, path, themesDir, maxThemeJsonBytes: 512 * 1024, logger: console });
|
|
31
|
+
const app = express();
|
|
32
|
+
registerCommonRequestMiddleware(app, { express });
|
|
33
|
+
registerSettingsUtilityRoutes(app, runtime);
|
|
34
|
+
return { root, themesDir, runtime, app };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
describe('theme import persistence', () => {
|
|
38
|
+
it('deletes only imported files, leaves siblings intact and allows an identical reimport', async () => {
|
|
39
|
+
const { app, runtime, themesDir } = await setup();
|
|
40
|
+
const theme = await runtime.saveImportedTheme(definition);
|
|
41
|
+
await fs.writeFile(path.join(themesDir, 'custom.json'), JSON.stringify(definition));
|
|
42
|
+
await request(app).delete('/api/config/themes/openchamber-dark').expect(200);
|
|
43
|
+
await request(app).delete(`/api/config/themes/${theme.metadata.id}`).expect(200);
|
|
44
|
+
expect(await fs.readdir(themesDir)).toEqual(['custom.json']);
|
|
45
|
+
await request(app).delete(`/api/config/themes/${theme.metadata.id}`).expect(200);
|
|
46
|
+
expect(await runtime.saveImportedTheme(definition)).toEqual(theme);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('does not follow a symlink during deletion or report deletion failure as success', async () => {
|
|
50
|
+
const { app, root, themesDir } = await setup();
|
|
51
|
+
await fs.mkdir(themesDir);
|
|
52
|
+
const outside = path.join(root, 'outside.json');
|
|
53
|
+
await fs.writeFile(outside, 'keep');
|
|
54
|
+
const id = `imported-vscode-${'a'.repeat(24)}`;
|
|
55
|
+
await fs.symlink(outside, path.join(themesDir, `${id}.json`));
|
|
56
|
+
await request(app).delete(`/api/config/themes/${id}`).expect(200);
|
|
57
|
+
expect(await fs.readFile(outside, 'utf8')).toBe('keep');
|
|
58
|
+
const denied = await setup({ unlink: async () => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); } });
|
|
59
|
+
await fs.mkdir(denied.themesDir);
|
|
60
|
+
await fs.writeFile(path.join(denied.themesDir, `${id}.json`), JSON.stringify({ ...definition, metadata: { ...definition.metadata, id } }));
|
|
61
|
+
await request(denied.app).delete(`/api/config/themes/${id}`).expect(500);
|
|
62
|
+
expect(await fs.readdir(denied.themesDir)).toEqual([`${id}.json`]);
|
|
63
|
+
});
|
|
64
|
+
it('deletes a hand-added theme by its metadata ID, not by an assumed filename', async () => {
|
|
65
|
+
const { app, themesDir } = await setup();
|
|
66
|
+
await fs.mkdir(themesDir);
|
|
67
|
+
const custom = { ...definition, metadata: { ...definition.metadata, id: 't3-code-dark', name: 'T3 Code' } };
|
|
68
|
+
await fs.writeFile(path.join(themesDir, 'my-custom-palette.json'), JSON.stringify(custom));
|
|
69
|
+
const loaded = await request(app).get('/api/config/themes').expect(200);
|
|
70
|
+
expect(loaded.body.themes[0].metadata.id).toBe('t3-code-dark');
|
|
71
|
+
await request(app).delete('/api/config/themes/t3-code-dark').expect(200);
|
|
72
|
+
expect(await fs.readdir(themesDir)).toEqual([]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('refuses ambiguous duplicate IDs and does not turn an ID into a filesystem path', async () => {
|
|
76
|
+
const { app, themesDir, root } = await setup();
|
|
77
|
+
await fs.mkdir(themesDir);
|
|
78
|
+
const custom = { ...definition, metadata: { ...definition.metadata, id: 'duplicate' } };
|
|
79
|
+
for (const name of ['one.json', 'two.json']) await fs.writeFile(path.join(themesDir, name), JSON.stringify(custom));
|
|
80
|
+
await request(app).delete('/api/config/themes/duplicate').expect(409);
|
|
81
|
+
expect((await fs.readdir(themesDir)).sort()).toEqual(['one.json', 'two.json']);
|
|
82
|
+
await fs.writeFile(path.join(root, 'outside.json'), JSON.stringify(custom));
|
|
83
|
+
await request(app).delete('/api/config/themes/..%2Foutside').expect(200);
|
|
84
|
+
expect(await fs.readFile(path.join(root, 'outside.json'), 'utf8')).toBe(JSON.stringify(custom));
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('allows deleting a readable theme beside an unreadable sibling, but does not treat failed reads as absence', async () => {
|
|
88
|
+
const { runtime, themesDir } = await setup({ readFile: async (file, ...args) => {
|
|
89
|
+
if (path.basename(file) === 'unreadable.json') throw Object.assign(new Error('denied'), { code: 'EACCES' });
|
|
90
|
+
return fs.readFile(file, ...args);
|
|
91
|
+
} });
|
|
92
|
+
const theme = await runtime.saveImportedTheme(definition);
|
|
93
|
+
await fs.writeFile(path.join(themesDir, 'unreadable.json'), JSON.stringify(definition));
|
|
94
|
+
await runtime.deleteImportedTheme(theme.metadata.id);
|
|
95
|
+
expect(await fs.readdir(themesDir)).toEqual(['unreadable.json']);
|
|
96
|
+
await expect(runtime.deleteImportedTheme('possibly-unreadable')).rejects.toMatchObject({ code: 'EACCES' });
|
|
97
|
+
});
|
|
98
|
+
it('saves through the API under a server-owned ID and returns it through reload', async () => {
|
|
99
|
+
const { app, themesDir, root } = await setup();
|
|
100
|
+
const response = await request(app).post('/api/config/themes').send({ theme: definition }).expect(201);
|
|
101
|
+
expect(response.body.theme.metadata.id).toMatch(/^imported-vscode-[a-f0-9]{24}$/);
|
|
102
|
+
expect(await fs.readdir(root)).toEqual(['themes']);
|
|
103
|
+
expect(await fs.readdir(themesDir)).toEqual([`${response.body.theme.metadata.id}.json`]);
|
|
104
|
+
const loaded = await request(app).get('/api/config/themes').expect(200);
|
|
105
|
+
expect(loaded.body.themes).toEqual([response.body.theme]);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('deduplicates simultaneous imports and never overwrites a subsequently edited theme', async () => {
|
|
109
|
+
const { runtime, themesDir } = await setup();
|
|
110
|
+
const [first, second] = await Promise.all([runtime.saveImportedTheme(definition), runtime.saveImportedTheme(definition)]);
|
|
111
|
+
expect(first).toEqual(second);
|
|
112
|
+
expect((await fs.readdir(themesDir)).length).toBe(1);
|
|
113
|
+
const filename = path.join(themesDir, `${first.metadata.id}.json`);
|
|
114
|
+
await fs.writeFile(filename, 'manually edited');
|
|
115
|
+
await expect(runtime.saveImportedTheme(definition)).rejects.toMatchObject({ code: 'conflict', status: 409 });
|
|
116
|
+
expect(await fs.readFile(filename, 'utf8')).toBe('manually edited');
|
|
117
|
+
expect(await fs.readdir(themesDir)).toEqual([`${first.metadata.id}.json`]);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('rejects malformed definitions and unsafe token names without creating files', async () => {
|
|
121
|
+
const { app, root } = await setup();
|
|
122
|
+
await request(app).post('/api/config/themes').send({ theme: { ...definition, colors: {} } }).expect(400);
|
|
123
|
+
await request(app).post('/api/config/themes').send({ theme: { ...definition, colors: { ...definition.colors, syntax: { ...definition.colors.syntax, tokens: { 'x;body': '#000000' } } } } }).expect(400);
|
|
124
|
+
expect(await fs.readdir(root)).toEqual([]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('cleans temporary files after a publication failure', async () => {
|
|
128
|
+
const { runtime, themesDir } = await setup({ link: async () => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); } });
|
|
129
|
+
await expect(runtime.saveImportedTheme(definition)).rejects.toMatchObject({ code: 'EACCES' });
|
|
130
|
+
expect(await fs.readdir(themesDir)).toEqual([]);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('does not report a directory read failure as an empty theme library', async () => {
|
|
134
|
+
const { runtime } = await setup({ readdir: async () => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); } });
|
|
135
|
+
await expect(runtime.readCustomThemesFromDisk()).rejects.toMatchObject({ code: 'EACCES' });
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('rejects oversized imports without touching the themes directory', async () => {
|
|
139
|
+
const { runtime, root } = await setup();
|
|
140
|
+
const tokens = Object.fromEntries(Array.from({ length: 30000 }, (_, index) => [`token${index}`, '#123456']));
|
|
141
|
+
await expect(runtime.saveImportedTheme({ ...definition, colors: { ...definition.colors, syntax: { ...definition.colors.syntax, tokens } } })).rejects.toMatchObject({ code: 'size', status: 413 });
|
|
142
|
+
expect(await fs.readdir(root)).toEqual([]);
|
|
143
|
+
});
|
|
144
|
+
});
|