@pi-chamber/web 1.0.8-rc.2 → 1.0.8-rc.4
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/{AgentsSurface-CcWBqAWV.js → AgentsSurface-DbCBygRD.js} +1 -1
- package/dist/assets/{ChoicesArtifact-Kk-qvrSB.js → ChoicesArtifact-DUqhCvXh.js} +1 -1
- package/dist/assets/{DiagramView-DZUBo1uP.js → DiagramView-CnVOyJd2.js} +1 -1
- package/dist/assets/{DiffView-CiZy4jFA.js → DiffView-Db8JXsvA.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-DZ9NDwOO.js → FileSaveConflictDialog-D6xyf709.js} +1 -1
- package/dist/assets/{FilesView-DqiZ9kw9.js → FilesView-Cir0Wl9F.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-DM2DH7o8.js → GitHubDetailScaffold-US37Di_K.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-ChB8NZ1h.js → GitHubLinkPicker-k_D-sk-e.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-CibDiJGq.js → GitHubListPrimitives-DuUXrJGk.js} +1 -1
- package/dist/assets/{GitView--EaZQrBr.js → GitView-BdX_3XRr.js} +3 -3
- package/dist/assets/{IssuesSurface-CySTpaD1.js → IssuesSurface-Cw93HC0G.js} +2 -2
- package/dist/assets/{JsonTreeView-_yMHKKQZ.js → JsonTreeView-Bze4htWt.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-D_-2fQw0.js → MarkdownRendererImpl-Ch7NDkF9.js} +1 -1
- package/dist/assets/{PatchDiff-bHObDlhD.js → PatchDiff-l68Yz45X.js} +1 -1
- package/dist/assets/{PierreDiffViewer-UY7Cse-s.js → PierreDiffViewer-BHBySiXQ.js} +1 -1
- package/dist/assets/{PullRequestsSurface-iXy6chwc.js → PullRequestsSurface-CGD4_ljc.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-DJGCa_wN.js → SessionSwitcherContent-DqP8OWzB.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CDOX-5Y2.js → SessionSwitcherDropdown-BkTg-cVd.js} +2 -2
- package/dist/assets/{SessionUnreadDot-Dwc3MdvA.js → SessionUnreadDot-CgvC3F5e.js} +1 -1
- package/dist/assets/SettingsView-CkIxCYhs.js +11 -0
- package/dist/assets/{SettingsWindow-CUg49Mfh.js → SettingsWindow-DSdhzapT.js} +1 -1
- package/dist/assets/{SubagentsArtifact-DUZX9tDe.js → SubagentsArtifact-BN3aX_8M.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BuZZaRw4.js → ToolOutputDialog-CLwm4TjA.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CKncG6i2.js → ToolPartDiffPreview-ERAStEKA.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BGZiLPe_.js → VirtualizedFileDiff-DwR2fZHv.js} +1 -1
- package/dist/assets/VisualFrame-Dwp7B_st.js +22 -0
- package/dist/assets/{VisualsArtifact-Bq0vMO-i.js → VisualsArtifact-DlOxifHd.js} +1 -1
- package/dist/assets/{collapsible-Bro9KrfM.js → collapsible-CW-_qd6v.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DJQqK49u.js → computeVirtualFileMetrics-SlBfr8LB.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-ByWK3Sru.js → contextFileOpenGuard-CHoFT50j.js} +1 -1
- package/dist/assets/{fileTreeStatus-CyJ3TOYD.js → fileTreeStatus-D0uiC1D0.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BsXrwngT.js → gitStatusPredicates-Bj3pkh2e.js} +1 -1
- package/dist/assets/{githubLink-g2bmC0qi.js → githubLink-CheLNuP0.js} +1 -1
- package/dist/assets/index-BFkW-BPM.js +11 -0
- package/dist/assets/index-C5JgjS20.css +1 -0
- package/dist/assets/{index-C9rUUQ_Y.js → index-C8zaLvup.js} +1 -1
- package/dist/assets/{main-DT-4_fhe.js → main-CUEqZRu1.js} +2 -2
- package/dist/assets/{main-DsLMU9CT.js → main-V66ie29o.js} +4 -4
- package/dist/assets/{markdownCore-QmM_aOnZ.js → markdownCore-BRedKgCo.js} +1 -1
- package/dist/assets/{miniChat-BqGslD2z.js → miniChat-BXwuEQhz.js} +2 -2
- package/dist/assets/{mobile-C5JOcDIC.js → mobile-7s-xLDG3.js} +2 -2
- package/dist/assets/{nativeFileSave-DSMsJqXM.js → nativeFileSave-Bj-V_9ae.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-Cc_S4zi1.js → pi-session-focus-preference-clbekCjz.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-BXhnIAHg.js → renderDiffWithHighlighter-g9eKWi78.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CiSkecEE.js → renderElectronMiniChatApp-B6BN8YgC.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-CK29YZtC.js → renderFileWithHighlighter-DKl6vubK.js} +1 -1
- package/dist/assets/{renderMobileApp-C4JuoxsZ.js → renderMobileApp-Bp735rW7.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-Dwj-jCDS.js → runtimeEndpointReset-CtHv_OMT.js} +7 -7
- package/dist/assets/{runtimeSurface-0K7vuUpd.js → runtimeSurface-DD4Vn4HC.js} +1 -1
- package/dist/assets/{selection-CnYkEsu_.js → selection-DDT954wY.js} +1 -1
- package/dist/assets/useAppFontEffects-DJCrUN2D.js +226 -0
- package/dist/assets/{useGitHubRemoteSearch-CgP-zEBj.js → useGitHubRemoteSearch-B77fMiwQ.js} +1 -1
- package/dist/assets/{useSwitcherItems-C8G5F0hs.js → useSwitcherItems-CFY3mP06.js} +1 -1
- package/dist/assets/{web-components-BpncHjnV.js → web-components-XIP_3VZv.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -1
- package/pichamber.d.ts +139 -0
- package/plugins/subagents/extension.js +5 -5
- package/plugins/subagents/package.json +3 -2
- package/plugins/visuals/choices.js +8 -7
- package/plugins/visuals/extension.js +6 -6
- package/plugins/visuals/package.json +1 -1
- package/server/index.js +4 -0
- package/server/lib/marketplace/DOCUMENTATION.md +2 -2
- package/server/lib/marketplace/npm-registry.js +1 -1
- package/server/lib/marketplace/npm-registry.test.js +1 -1
- package/server/lib/marketplace/service.test.js +4 -4
- package/server/lib/open-url/DOCUMENTATION.md +1 -1
- package/server/lib/pi/extension-card.js +48 -0
- package/server/lib/pi/extension-card.test.js +35 -0
- package/server/lib/pi/extension-commands.js +49 -0
- package/server/lib/pi/extension-commands.test.js +38 -0
- package/server/lib/pi/extension-protocol.js +1 -2
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +52 -223
- package/server/lib/pi/routes-extension-events.test.js +35 -48
- package/server/lib/pi/routes.js +44 -54
- package/server/lib/pi/routes.test.js +32 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +7 -7
- package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +0 -54
- package/server/lib/pi/session-daemon/extension-bridge.js +39 -162
- package/server/lib/pi/session-daemon/extension-controls.js +12 -57
- package/server/lib/pi/session-daemon/extension-controls.test.js +4 -34
- package/server/lib/pi/session-daemon/pichamber-api.js +38 -0
- package/server/lib/pi/session-daemon/pichamber-api.test.js +24 -0
- package/server/lib/pi/session-daemon/plugin-host.js +5 -7
- package/server/lib/pi/session-daemon/plugin-host.test.js +2 -3
- package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +53 -7
- package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +5 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +9 -4
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +28 -71
- package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +1 -1
- package/server/lib/pi/session-daemon/session-daemon.js +138 -78
- package/server/lib/pi/session-daemon/session-daemon.test.js +68 -0
- package/server/lib/pi/ui-settings-store.js +2 -1
- package/server/lib/plugins/DOCUMENTATION.md +3 -3
- package/server/lib/plugins/impact.js +2 -4
- package/server/lib/plugins/impact.test.js +0 -1
- package/server/lib/plugins/manifest.js +9 -5
- package/server/lib/plugins/manifest.test.js +5 -4
- package/server/lib/plugins/store.test.js +1 -1
- package/server/lib/plugins/visuals-extension.test.js +16 -14
- package/server/lib/wallpaper/DOCUMENTATION.md +25 -0
- package/server/lib/wallpaper/routes.js +63 -0
- package/server/lib/wallpaper/routes.test.js +109 -0
- package/server/lib/wallpaper/store.js +87 -0
- package/dist/assets/SettingsView-DA-U9lsj.js +0 -11
- package/dist/assets/VisualFrame-DBZkHFnG.js +0 -22
- package/dist/assets/index-B_L9GVYw.css +0 -1
- package/dist/assets/index-CKKWVoND.js +0 -11
- package/dist/assets/useAppFontEffects-CV5UyTRw.js +0 -226
- package/server/lib/pi/session-daemon/pichamber-ui.js +0 -44
|
@@ -20,7 +20,7 @@ const MAX_TOGGLES = 4;
|
|
|
20
20
|
const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
21
21
|
// Discovery keywords every Pi package or PiChamber plugin carries; they say
|
|
22
22
|
// nothing about what one plugin does, so they are left out of its keywords.
|
|
23
|
-
const DISCOVERY_KEYWORDS = new Set(['pi-package', 'pichamber
|
|
23
|
+
const DISCOVERY_KEYWORDS = new Set(['pi-package', 'pichamber']);
|
|
24
24
|
const MAX_KEYWORDS = 16;
|
|
25
25
|
const MAX_KEYWORD_LENGTH = 40;
|
|
26
26
|
|
|
@@ -99,12 +99,16 @@ const parseState = (value) => {
|
|
|
99
99
|
const parseContributes = (value, stateSchema) => {
|
|
100
100
|
if (value === undefined) return { composerToggles: [], settings: [] };
|
|
101
101
|
if (!isRecord(value)) fail('contributes is invalid');
|
|
102
|
-
|
|
103
|
-
|
|
102
|
+
// `contributes.controls` are composer controls whose value PiChamber
|
|
103
|
+
// stores (`state`), where `pichamber.control()` declares ones the
|
|
104
|
+
// extension stores (`command`). Only toggles can be stored today.
|
|
105
|
+
const toggles = value.controls ?? [];
|
|
106
|
+
if (!Array.isArray(toggles) || toggles.length > MAX_TOGGLES) fail('contributes.controls is invalid');
|
|
104
107
|
const toggleIds = new Set();
|
|
105
108
|
const composerToggles = toggles.map((toggle, index) => {
|
|
106
|
-
const field = `contributes.
|
|
109
|
+
const field = `contributes.controls[${index}]`;
|
|
107
110
|
if (!isRecord(toggle)) fail(`${field} is invalid`);
|
|
111
|
+
if (toggle.kind !== 'toggle') fail(`${field}.kind must be toggle`);
|
|
108
112
|
const id = pluginId(toggle.id, `${field}.id`);
|
|
109
113
|
if (toggleIds.has(id)) fail(`${field}.id repeats`);
|
|
110
114
|
toggleIds.add(id);
|
|
@@ -128,7 +132,7 @@ const parseContributes = (value, stateSchema) => {
|
|
|
128
132
|
if (settings.includes(key)) fail(`contributes.settings repeats ${key}`);
|
|
129
133
|
// A composer switch's default is the plugin's own switch in Settings; a
|
|
130
134
|
// second Settings control for it would be a confusing duplicate.
|
|
131
|
-
if (composerToggles.some((toggle) => toggle.state === key)) fail(`contributes.settings lists ${key}, which a composer
|
|
135
|
+
if (composerToggles.some((toggle) => toggle.state === key)) fail(`contributes.settings lists ${key}, which a composer control sets`);
|
|
132
136
|
settings.push(key);
|
|
133
137
|
}
|
|
134
138
|
const contributes = { composerToggles, settings };
|
|
@@ -29,7 +29,7 @@ const validPackage = (pichamber = {}, extra = {}) => ({
|
|
|
29
29
|
},
|
|
30
30
|
},
|
|
31
31
|
contributes: {
|
|
32
|
-
|
|
32
|
+
controls: [{ id: 'demo', kind: 'toggle', state: 'on', label: 'Demo', icon: 'artboard', description: 'Toggle it' }],
|
|
33
33
|
settings: ['mode'],
|
|
34
34
|
ui: 'demo',
|
|
35
35
|
},
|
|
@@ -82,7 +82,7 @@ describe('parsePluginPackage', () => {
|
|
|
82
82
|
|
|
83
83
|
it('keeps package keywords that say what it does', () => {
|
|
84
84
|
const manifest = parsePluginPackage(validPackage({}, {
|
|
85
|
-
keywords: ['pi-package', 'PiChamber
|
|
85
|
+
keywords: ['pi-package', 'PiChamber', 'Chart', 'chart', '', 7, 'x'.repeat(41), 'diagram'],
|
|
86
86
|
}), { packageDir });
|
|
87
87
|
expect(manifest.packageName).toBe('demo');
|
|
88
88
|
expect(manifest.keywords).toEqual(['chart', 'diagram']);
|
|
@@ -100,10 +100,11 @@ describe('parsePluginPackage', () => {
|
|
|
100
100
|
expect(reason(validPackage({ state: { on: { type: 'boolean', scope: 'global', default: 'yes', label: 'x' } } }))).toMatch(/default/);
|
|
101
101
|
expect(reason(validPackage({ state: { m: { type: 'enum', scope: 'global', default: 'z', label: 'x', options: [{ value: 'a', label: 'A' }] } } }))).toMatch(/default/);
|
|
102
102
|
expect(reason(validPackage({ state: { constructor: { type: 'boolean', scope: 'global', default: true, label: 'x' } } }))).toMatch(/constructor/);
|
|
103
|
-
expect(reason(validPackage({ contributes: {
|
|
103
|
+
expect(reason(validPackage({ contributes: { controls: [{ id: 'demo', kind: 'toggle', state: 'mode', label: 'x', icon: 'artboard' }] } }))).toMatch(/boolean/);
|
|
104
|
+
expect(reason(validPackage({ contributes: { controls: [{ id: 'demo', state: 'on', label: 'x', icon: 'artboard' }] } }))).toMatch(/kind/);
|
|
104
105
|
expect(reason(validPackage({ contributes: { settings: ['missing'] } }))).toMatch(/unknown/);
|
|
105
106
|
expect(reason(validPackage({ contributes: { settings: ['mode', 'mode'] } }))).toMatch(/repeats/);
|
|
106
|
-
expect(reason(validPackage({ contributes: {
|
|
107
|
+
expect(reason(validPackage({ contributes: { controls: [{ id: 'demo', kind: 'toggle', state: 'on', label: 'Demo', icon: 'artboard' }], settings: ['on'] } }))).toMatch(/composer control/);
|
|
107
108
|
expect(reason({ ...validPackage(), version: 'latest' })).toMatch(/version/);
|
|
108
109
|
expect(reason(validPackage({}, {}), { packageDir: 'relative' })).toMatch(/folder/);
|
|
109
110
|
});
|
|
@@ -32,7 +32,7 @@ const manifest = parsePluginPackage({
|
|
|
32
32
|
options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }],
|
|
33
33
|
},
|
|
34
34
|
},
|
|
35
|
-
contributes: {
|
|
35
|
+
contributes: { controls: [{ id: 'demo', kind: 'toggle', state: 'on', label: 'Demo', icon: 'artboard' }] },
|
|
36
36
|
},
|
|
37
37
|
}, { packageDir: '/plugins/demo', bundled: true });
|
|
38
38
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
2
|
import { mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
@@ -37,6 +37,9 @@ const fakePi = (activeTools = ['read', 'bash']) => {
|
|
|
37
37
|
return pi;
|
|
38
38
|
};
|
|
39
39
|
|
|
40
|
+
// The tests that need PiChamber install their own `globalThis.pichamber`.
|
|
41
|
+
afterEach(() => { delete globalThis.pichamber; });
|
|
42
|
+
|
|
40
43
|
describe('Visuals render_html', () => {
|
|
41
44
|
it('returns a short line and the page in details', async () => {
|
|
42
45
|
await expect(renderHtml({ title: ' Sales ', html: '<p>x</p>', height: 300 })).resolves.toEqual({
|
|
@@ -105,21 +108,19 @@ describe('Visuals extension', () => {
|
|
|
105
108
|
expect(pi.active).toEqual(['read', 'bash', TOOL_NAME, CHOICES_TOOL_NAME]);
|
|
106
109
|
});
|
|
107
110
|
|
|
108
|
-
it('shows the options, then asks through pichamber.
|
|
111
|
+
it('shows the options, then asks through pichamber.choose with its own tool call id', async () => {
|
|
109
112
|
const pi = fakePi();
|
|
110
113
|
const order = [];
|
|
111
114
|
const asked = [];
|
|
112
115
|
const ctx = { cwd: '/p', ui: {} };
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return { id: 'b', note: 'darker header' };
|
|
119
|
-
},
|
|
116
|
+
globalThis.pichamber = {
|
|
117
|
+
choose: async (askedCtx, title, choices, opts) => {
|
|
118
|
+
order.push('asked');
|
|
119
|
+
asked.push({ ctx: askedCtx, title, choices, opts });
|
|
120
|
+
return { id: 'b', note: 'darker header' };
|
|
120
121
|
},
|
|
121
122
|
};
|
|
122
|
-
visuals(pi
|
|
123
|
+
visuals(pi);
|
|
123
124
|
const tool = pi.tools.find((entry) => entry.name === CHOICES_TOOL_NAME);
|
|
124
125
|
const signal = new AbortController().signal;
|
|
125
126
|
const result = await tool.execute('call-9', {
|
|
@@ -213,12 +214,13 @@ describe('Visuals render_choices', () => {
|
|
|
213
214
|
const choices = await renderChoices({ title: 'Which?', options: two });
|
|
214
215
|
const listed = [];
|
|
215
216
|
const withSelect = { hasUI: true, ui: { select: async (title, names) => { listed.push({ title, names }); return 'B: Two'; } } };
|
|
216
|
-
await expect(askChoice(
|
|
217
|
+
await expect(askChoice(withSelect, 'call-1', choices)).resolves.toEqual({ asked: true, id: 'b' });
|
|
217
218
|
expect(listed).toEqual([{ title: 'Which?', names: ['A: One', 'B: Two'] }]);
|
|
218
|
-
await expect(askChoice(
|
|
219
|
-
await expect(askChoice(
|
|
219
|
+
await expect(askChoice({ hasUI: true, ui: { select: async () => undefined } }, 'call-1', choices)).resolves.toEqual({ asked: true });
|
|
220
|
+
await expect(askChoice({ hasUI: false, ui: {} }, 'call-1', choices)).resolves.toEqual({ asked: false });
|
|
220
221
|
// An id the question never offered counts as no answer.
|
|
221
|
-
|
|
222
|
+
globalThis.pichamber = { choose: async () => ({ id: 'z' }) };
|
|
223
|
+
await expect(askChoice({}, 'call-1', choices)).resolves.toEqual({ asked: true });
|
|
222
224
|
});
|
|
223
225
|
|
|
224
226
|
it('tells the agent what happened and keeps the answer in details', async () => {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Wallpaper picture
|
|
2
|
+
|
|
3
|
+
Holds the one picture a server shows behind the new-session screen. Whether
|
|
4
|
+
it shows (`draftWallpaperPicture`, under whichever `draftWallpaper` pattern is
|
|
5
|
+
chosen, which then takes its colours) and which picture the clients expect
|
|
6
|
+
(`draftWallpaperImageVersion`) are UI settings; this module only stores bytes.
|
|
7
|
+
|
|
8
|
+
## Files
|
|
9
|
+
|
|
10
|
+
- `store.js`: `<dataDir>/wallpaper/image` and `image.json` (`{ version, type }`).
|
|
11
|
+
- `routes.js`: `GET`, `PUT` and `DELETE /api/wallpaper-image`, behind the
|
|
12
|
+
global `/api` auth gate.
|
|
13
|
+
|
|
14
|
+
## Invariants
|
|
15
|
+
|
|
16
|
+
- The type comes from the file's first bytes. Only PNG, JPEG and WebP are
|
|
17
|
+
accepted (no SVG: it can carry script). Responses send `nosniff`.
|
|
18
|
+
- `version` is the first 16 hex characters of the bytes' SHA-256. A record
|
|
19
|
+
whose version does not match the stored picture reads as no picture, so a
|
|
20
|
+
crash between the two writes never serves a picture under the wrong name.
|
|
21
|
+
- A refused upload (too large, unknown type) leaves the previous picture.
|
|
22
|
+
- The size cap (8 MB) only stops abuse: the UI scales pictures to at most
|
|
23
|
+
2560 px on the long side and re-encodes them before sending.
|
|
24
|
+
- `GET` answers `private, no-cache` with an ETag; clients key their copy by
|
|
25
|
+
version and fetch again only when the setting names a new one.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { MAX_WALLPAPER_IMAGE_BYTES } from './store.js';
|
|
2
|
+
|
|
3
|
+
// Authenticated routes (the global `/api` auth gate applies) for the
|
|
4
|
+
// new-session wallpaper picture. Which wallpaper shows, and how, is the
|
|
5
|
+
// `draftWallpaper*` UI settings; these only hold the picture.
|
|
6
|
+
|
|
7
|
+
const STATUS_BY_CODE = {
|
|
8
|
+
WALLPAPER_IMAGE_TOO_LARGE: 413,
|
|
9
|
+
WALLPAPER_IMAGE_UNSUPPORTED: 415,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const sendError = (res, error) => {
|
|
13
|
+
const status = STATUS_BY_CODE[error?.code];
|
|
14
|
+
if (status) return res.status(status).json({ error: { code: error.code } });
|
|
15
|
+
console.warn('[wallpaper] image request failed', error?.code ?? error);
|
|
16
|
+
return res.status(500).json({ error: { code: 'WALLPAPER_IMAGE_UNAVAILABLE' } });
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const registerWallpaperRoutes = (app, { express, store }) => {
|
|
20
|
+
app.get('/api/wallpaper-image', async (_req, res) => {
|
|
21
|
+
try {
|
|
22
|
+
const image = await store.read();
|
|
23
|
+
if (!image) return res.status(404).json({ error: { code: 'WALLPAPER_IMAGE_NOT_FOUND' } });
|
|
24
|
+
res.set({
|
|
25
|
+
'Content-Type': image.type,
|
|
26
|
+
'Cache-Control': 'private, no-cache',
|
|
27
|
+
ETag: `"${image.version}"`,
|
|
28
|
+
'X-Content-Type-Options': 'nosniff',
|
|
29
|
+
'X-Wallpaper-Version': image.version,
|
|
30
|
+
});
|
|
31
|
+
return res.send(image.buffer);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
return sendError(res, error);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
app.put(
|
|
38
|
+
'/api/wallpaper-image',
|
|
39
|
+
express.raw({ type: () => true, limit: MAX_WALLPAPER_IMAGE_BYTES }),
|
|
40
|
+
async (req, res) => {
|
|
41
|
+
try {
|
|
42
|
+
return res.json(await store.write(Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0)));
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return sendError(res, error);
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
app.delete('/api/wallpaper-image', async (_req, res) => {
|
|
50
|
+
try {
|
|
51
|
+
await store.remove();
|
|
52
|
+
return res.status(204).end();
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return sendError(res, error);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// express.raw reports an oversized body before the handler runs.
|
|
59
|
+
app.use('/api/wallpaper-image', (error, _req, res, next) => {
|
|
60
|
+
if (error?.type === 'entity.too.large') return res.status(413).json({ error: { code: 'WALLPAPER_IMAGE_TOO_LARGE' } });
|
|
61
|
+
return next(error);
|
|
62
|
+
});
|
|
63
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import express from 'express';
|
|
6
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { registerWallpaperRoutes } from './routes.js';
|
|
9
|
+
import { MAX_WALLPAPER_IMAGE_BYTES, createWallpaperImageStore, sniffImageType } from './store.js';
|
|
10
|
+
|
|
11
|
+
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from('rest of a png')]);
|
|
12
|
+
const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from('jpeg body')]);
|
|
13
|
+
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0, 0, 0, 0]), Buffer.from('WEBPVP8 ')]);
|
|
14
|
+
|
|
15
|
+
const listen = (app) => new Promise((resolve, reject) => {
|
|
16
|
+
const server = app.listen(0, '127.0.0.1', () => resolve(server));
|
|
17
|
+
server.once('error', reject);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
describe('wallpaper image', () => {
|
|
21
|
+
let server;
|
|
22
|
+
let dataDir;
|
|
23
|
+
|
|
24
|
+
afterEach(async () => {
|
|
25
|
+
await new Promise((resolve) => (server ? server.close(resolve) : resolve()));
|
|
26
|
+
server = undefined;
|
|
27
|
+
if (dataDir) await rm(dataDir, { recursive: true, force: true });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const setup = async () => {
|
|
31
|
+
dataDir = await mkdtemp(join(tmpdir(), 'pc-wallpaper-'));
|
|
32
|
+
const app = express();
|
|
33
|
+
// The server parses JSON bodies for every route; an image must pass through.
|
|
34
|
+
app.use(express.json());
|
|
35
|
+
const store = createWallpaperImageStore({ dataDir });
|
|
36
|
+
registerWallpaperRoutes(app, { express, store });
|
|
37
|
+
server = await listen(app);
|
|
38
|
+
const base = `http://127.0.0.1:${server.address().port}/api/wallpaper-image`;
|
|
39
|
+
return { base, store };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
it('knows PNG, JPEG and WebP by their bytes only', () => {
|
|
43
|
+
expect(sniffImageType(PNG)).toBe('image/png');
|
|
44
|
+
expect(sniffImageType(JPEG)).toBe('image/jpeg');
|
|
45
|
+
expect(sniffImageType(WEBP)).toBe('image/webp');
|
|
46
|
+
expect(sniffImageType(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>'))).toBeNull();
|
|
47
|
+
expect(sniffImageType(Buffer.from('GIF89a'))).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('has no picture until one is saved, then serves it with its version', async () => {
|
|
51
|
+
const { base } = await setup();
|
|
52
|
+
expect((await fetch(base)).status).toBe(404);
|
|
53
|
+
|
|
54
|
+
const put = await fetch(base, { method: 'PUT', headers: { 'content-type': 'image/webp' }, body: WEBP });
|
|
55
|
+
expect(put.status).toBe(200);
|
|
56
|
+
const saved = await put.json();
|
|
57
|
+
expect(saved.type).toBe('image/webp');
|
|
58
|
+
expect(saved.version).toMatch(/^[0-9a-f]{16}$/);
|
|
59
|
+
|
|
60
|
+
const get = await fetch(base);
|
|
61
|
+
expect(get.status).toBe(200);
|
|
62
|
+
expect(get.headers.get('content-type')).toBe('image/webp');
|
|
63
|
+
expect(get.headers.get('x-wallpaper-version')).toBe(saved.version);
|
|
64
|
+
expect(get.headers.get('x-content-type-options')).toBe('nosniff');
|
|
65
|
+
expect(Buffer.from(await get.arrayBuffer()).equals(WEBP)).toBe(true);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('types the picture by its bytes, not the request header', async () => {
|
|
69
|
+
const { base } = await setup();
|
|
70
|
+
const put = await fetch(base, { method: 'PUT', headers: { 'content-type': 'text/html' }, body: PNG });
|
|
71
|
+
expect((await put.json()).type).toBe('image/png');
|
|
72
|
+
expect((await fetch(base)).headers.get('content-type')).toBe('image/png');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('refuses other files and keeps the picture it had', async () => {
|
|
76
|
+
const { base } = await setup();
|
|
77
|
+
await fetch(base, { method: 'PUT', body: JPEG });
|
|
78
|
+
const svg = await fetch(base, { method: 'PUT', headers: { 'content-type': 'image/svg+xml' }, body: '<svg onload="alert(1)"/>' });
|
|
79
|
+
expect(svg.status).toBe(415);
|
|
80
|
+
const empty = await fetch(base, { method: 'PUT', headers: { 'content-type': 'image/png' }, body: '' });
|
|
81
|
+
expect(empty.status).toBe(415);
|
|
82
|
+
expect((await fetch(base)).headers.get('content-type')).toBe('image/jpeg');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('refuses pictures over the size limit', async () => {
|
|
86
|
+
const { base } = await setup();
|
|
87
|
+
const big = Buffer.concat([PNG, Buffer.alloc(MAX_WALLPAPER_IMAGE_BYTES)]);
|
|
88
|
+
const put = await fetch(base, { method: 'PUT', headers: { 'content-type': 'image/png' }, body: big });
|
|
89
|
+
expect(put.status).toBe(413);
|
|
90
|
+
expect((await fetch(base)).status).toBe(404);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('removes the picture', async () => {
|
|
94
|
+
const { base } = await setup();
|
|
95
|
+
await fetch(base, { method: 'PUT', body: PNG });
|
|
96
|
+
expect((await fetch(base, { method: 'DELETE' })).status).toBe(204);
|
|
97
|
+
expect((await fetch(base)).status).toBe(404);
|
|
98
|
+
expect((await fetch(base, { method: 'DELETE' })).status).toBe(204);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('reads a damaged or mismatched record as no picture', async () => {
|
|
102
|
+
const { base, store } = await setup();
|
|
103
|
+
await store.write(PNG);
|
|
104
|
+
await writeFile(join(dataDir, 'wallpaper', 'image'), JPEG);
|
|
105
|
+
expect((await fetch(base)).status).toBe(404);
|
|
106
|
+
await writeFile(join(dataDir, 'wallpaper', 'image.json'), '{not json');
|
|
107
|
+
expect(await store.read()).toBeNull();
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rm } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { writeFileAtomic } from '../fs/atomic-write.js';
|
|
6
|
+
|
|
7
|
+
/** The UI scales pictures down before sending, so this only stops abuse. */
|
|
8
|
+
export const MAX_WALLPAPER_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
|
|
10
|
+
const IMAGE_FILE = 'image';
|
|
11
|
+
const META_FILE = 'image.json';
|
|
12
|
+
|
|
13
|
+
const wallpaperError = (code, message) => Object.assign(new Error(message), { code });
|
|
14
|
+
|
|
15
|
+
/** Image type from the file's first bytes; the client's Content-Type is not trusted. */
|
|
16
|
+
export const sniffImageType = (buffer) => {
|
|
17
|
+
if (buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';
|
|
18
|
+
if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return 'image/jpeg';
|
|
19
|
+
if (buffer.length >= 12 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
|
|
20
|
+
return null;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const isMeta = (value) => value !== null
|
|
24
|
+
&& typeof value === 'object'
|
|
25
|
+
&& typeof value.version === 'string'
|
|
26
|
+
&& /^[0-9a-f]{16}$/.test(value.version)
|
|
27
|
+
&& ['image/png', 'image/jpeg', 'image/webp'].includes(value.type);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The server's one wallpaper picture, in `<dataDir>/wallpaper/`. Every
|
|
31
|
+
* client of the server shows the same one. `version` is a hash of the bytes,
|
|
32
|
+
* so clients can tell a new picture from a cached one.
|
|
33
|
+
*/
|
|
34
|
+
export const createWallpaperImageStore = ({ dataDir }) => {
|
|
35
|
+
const dir = join(dataDir, 'wallpaper');
|
|
36
|
+
const imagePath = join(dir, IMAGE_FILE);
|
|
37
|
+
const metaPath = join(dir, META_FILE);
|
|
38
|
+
|
|
39
|
+
const readMeta = async () => {
|
|
40
|
+
try {
|
|
41
|
+
const meta = JSON.parse(await readFile(metaPath, 'utf8'));
|
|
42
|
+
return isMeta(meta) ? { version: meta.version, type: meta.type } : null;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error?.code === 'ENOENT') return null;
|
|
45
|
+
// A torn or hand-edited file reads as no picture rather than failing every request.
|
|
46
|
+
if (error instanceof SyntaxError) return null;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
/** `{ version, type, buffer }`, or null when there is no picture. */
|
|
53
|
+
async read() {
|
|
54
|
+
const meta = await readMeta();
|
|
55
|
+
if (!meta) return null;
|
|
56
|
+
try {
|
|
57
|
+
const buffer = await readFile(imagePath);
|
|
58
|
+
// The picture was replaced between the two reads; the newer write wins next time.
|
|
59
|
+
if (createHash('sha256').update(buffer).digest('hex').slice(0, 16) !== meta.version) return null;
|
|
60
|
+
return { ...meta, buffer };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error?.code === 'ENOENT') return null;
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
/** Saves `buffer` as the picture and returns its `{ version, type }`. */
|
|
68
|
+
async write(buffer) {
|
|
69
|
+
if (!Buffer.isBuffer(buffer) || buffer.length === 0) throw wallpaperError('WALLPAPER_IMAGE_UNSUPPORTED', 'Empty image');
|
|
70
|
+
if (buffer.length > MAX_WALLPAPER_IMAGE_BYTES) throw wallpaperError('WALLPAPER_IMAGE_TOO_LARGE', 'Image is too large');
|
|
71
|
+
const type = sniffImageType(buffer);
|
|
72
|
+
if (!type) throw wallpaperError('WALLPAPER_IMAGE_UNSUPPORTED', 'Only PNG, JPEG and WebP images are accepted');
|
|
73
|
+
const version = createHash('sha256').update(buffer).digest('hex').slice(0, 16);
|
|
74
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
75
|
+
// Picture first, then the record naming it: a crash between the two
|
|
76
|
+
// leaves the old record, which no longer matches and reads as none.
|
|
77
|
+
await writeFileAtomic(imagePath, buffer);
|
|
78
|
+
await writeFileAtomic(metaPath, `${JSON.stringify({ version, type })}\n`);
|
|
79
|
+
return { version, type };
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
async remove() {
|
|
83
|
+
await rm(metaPath, { force: true });
|
|
84
|
+
await rm(imagePath, { force: true });
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
};
|