synabun 2.4.2 → 2.4.3
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/CHANGELOG.md +20 -0
- package/README.md +1 -1
- package/docs/browser-extension-bridge.md +23 -3
- package/lib/release-npm-ci.mjs +23 -1
- package/mcp-server/dist/services/neural-interface.js +1 -1
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
- package/mcp-server/package-lock.json +5 -5
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/services/neural-interface.ts +1 -1
- package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
- package/neural-interface/i18n/en.json +50 -1
- package/neural-interface/i18n/pt-BR.json +57 -8
- package/neural-interface/lib/assistant-api.js +33 -0
- package/neural-interface/lib/assistant-brains/opencode.js +121 -7
- package/neural-interface/lib/assistant-dispatch.js +26 -2
- package/neural-interface/lib/assistant-envelope.js +40 -0
- package/neural-interface/lib/assistant-runtime.js +95 -10
- package/neural-interface/lib/browser-extension-adapter.js +1 -3
- package/neural-interface/lib/browser-extension-archive.js +149 -0
- package/neural-interface/lib/browser-extension-bridge.js +7 -4
- package/neural-interface/lib/browser-extension-folder.js +596 -76
- package/neural-interface/lib/browser-extension-package.js +200 -0
- package/neural-interface/lib/browser-extension-pin.js +84 -0
- package/neural-interface/lib/browser-extension-pin.json +33 -0
- package/neural-interface/lib/browser-extension-setup.js +105 -18
- package/neural-interface/lib/cli-install.js +23 -3
- package/neural-interface/lib/cli-update-planner.js +67 -4
- package/neural-interface/lib/native-loop-providers.js +10 -1
- package/neural-interface/lib/native-loop-runtime.js +20 -2
- package/neural-interface/lib/opencode-shell-read.js +107 -0
- package/neural-interface/lib/opencode-stop-failures.js +40 -0
- package/neural-interface/lib/opencode-turn-release.js +173 -0
- package/neural-interface/lib/opencode-v2-client.js +4 -1
- package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
- package/neural-interface/lib/opencode2-client.js +341 -6
- package/neural-interface/lib/opencode2-translate.js +161 -4
- package/neural-interface/lib/terminal-token-redaction.js +83 -0
- package/neural-interface/lib/whatsapp/bridge.js +52 -6
- package/neural-interface/package-lock.json +5 -5
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/extension-setup.html +5 -2
- package/neural-interface/public/shared/agy/agy-panel.js +38 -10
- package/neural-interface/public/shared/assistant/asst-api.js +25 -0
- package/neural-interface/public/shared/assistant/asst-panel.js +69 -1
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
- package/neural-interface/public/shared/assistant/asst-render.js +138 -6
- package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
- package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +1 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
- package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
- package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
- package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
- package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
- package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
- package/neural-interface/public/shared/shell-stop-view.js +83 -0
- package/neural-interface/public/shared/tour/tour-actor.js +14 -3
- package/neural-interface/public/shared/tray-auto-close.js +36 -6
- package/neural-interface/public/shared/ui-claude-panel.js +20 -0
- package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
- package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
- package/neural-interface/server.js +249 -35
- package/npm-shrinkwrap.json +5 -5
- package/package.json +1 -2
- package/browser-extension/content.js +0 -231
- package/browser-extension/engine.js +0 -658
- package/browser-extension/icons/icon-128.png +0 -0
- package/browser-extension/icons/icon-16.png +0 -0
- package/browser-extension/icons/icon-32.png +0 -0
- package/browser-extension/icons/icon-48.png +0 -0
- package/browser-extension/icons/status-off-16.png +0 -0
- package/browser-extension/icons/status-off-32.png +0 -0
- package/browser-extension/icons/status-off-48.png +0 -0
- package/browser-extension/icons/status-on-16.png +0 -0
- package/browser-extension/icons/status-on-32.png +0 -0
- package/browser-extension/icons/status-on-48.png +0 -0
- package/browser-extension/manifest.json +0 -58
- package/browser-extension/popup-strings.js +0 -250
- package/browser-extension/popup-view.js +0 -151
- package/browser-extension/popup.css +0 -166
- package/browser-extension/popup.html +0 -108
- package/browser-extension/popup.js +0 -359
- package/browser-extension/service-worker.js +0 -283
- package/browser-extension/setup-content.js +0 -36
- package/browser-extension/tokens.css +0 -326
- /package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +0 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Where the extension's files come from: the one package this app release pins (lib/browser-extension-pin.js),
|
|
2
|
+
// downloaded from synabun.ai (docs/browser-extension-bridge.md → Where the extension comes from). The extension has
|
|
3
|
+
// broad permissions in the owner's browser, so a download is hostile until it is proven to be that exact file:
|
|
4
|
+
//
|
|
5
|
+
// transfer HTTPS only, the one host only (a redirect anywhere else, or to plain http, is not followed), the body
|
|
6
|
+
// as sent (no Content-Encoding: the pinned size bounds the bytes on the wire), nothing larger than the
|
|
7
|
+
// pinned size, a wait for the first byte and between bytes (stallMs) and for the whole transfer
|
|
8
|
+
// (totalMs). It is the hardened transfer of lib/cli-install.js (downloadFile), which aborts the request
|
|
9
|
+
// of every answer it refuses.
|
|
10
|
+
// verify the size and the SHA-256 must be the pin's, checked over the bytes that are then read, before anything
|
|
11
|
+
// looks inside the file; then SynaBun's one zip form, the pinned version and key, and exactly the files
|
|
12
|
+
// the pin lists (lib/browser-extension-folder.js verifiedPackageFiles).
|
|
13
|
+
// place lib/browser-extension-folder.js prepareExtensionFolder: under the data home's lock, a staged folder,
|
|
14
|
+
// then two renames (the live folder aside, the new one into its place), recorded so that a stopped
|
|
15
|
+
// process is finished or taken back at the next start.
|
|
16
|
+
//
|
|
17
|
+
// The folder is held to the pin, never to its marker (inspectExtensionFolder): a folder that is not exactly the
|
|
18
|
+
// pinned extension for this port is repaired, from the verified package this data home keeps when it has one (no
|
|
19
|
+
// network), else by downloading it again. The port is set from the folder's own files only once they verified.
|
|
20
|
+
//
|
|
21
|
+
// When it downloads (createExtensionPackage): with no folder yet, only when the owner starts "Connect your browser"
|
|
22
|
+
// (`ensure`); with a folder that is not the pinned extension, by itself after start-up (`refreshInBackground`), keeping
|
|
23
|
+
// the old folder on any failure. One transfer at a time. Nothing is logged with a path, and the download's working
|
|
24
|
+
// file lives beside the folder, never in it.
|
|
25
|
+
import { readFileSync, rmSync } from 'node:fs';
|
|
26
|
+
import { join } from 'node:path';
|
|
27
|
+
import { downloadFile } from './cli-install.js';
|
|
28
|
+
import { cachedExtensionPackage, confirmExtensionReload, confirmExtensionRepairReload, downloadWorkName, extensionFolderState, extensionWorkDir, inspectExtensionFolder, prepareExtensionFolder, retargetExtensionFolder, verifiedPackageFiles } from './browser-extension-folder.js';
|
|
29
|
+
import { EXTENSION_PACKAGE_HOST, EXTENSION_PIN, pinProblems } from './browser-extension-pin.js';
|
|
30
|
+
|
|
31
|
+
/** What a failed download or check is called (the setup's error codes; lib/browser-extension-setup.js has the words). */
|
|
32
|
+
export const PACKAGE_ERROR_CODES = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED', 'EXTENSION_FOLDER_FAILED', 'EXTENSION_FOLDER_UNSAFE', 'EXTENSION_DOWNLOAD_CANCELLED']);
|
|
33
|
+
export const PACKAGE_STALL_MS = 20_000;
|
|
34
|
+
export const PACKAGE_TOTAL_MS = 120_000;
|
|
35
|
+
|
|
36
|
+
const packageError = (code, message, detail) => Object.assign(new Error(message), { code, ...(detail ? { detail } : {}) });
|
|
37
|
+
// The transfer's own failure kinds (lib/cli-install.js CLI_INSTALL_ERROR_CODES) as the setup's codes.
|
|
38
|
+
const TRANSFER_CODES = Object.freeze({
|
|
39
|
+
offline: 'EXTENSION_DOWNLOAD_OFFLINE', timeout: 'EXTENSION_DOWNLOAD_OFFLINE', interrupted: 'EXTENSION_DOWNLOAD_OFFLINE',
|
|
40
|
+
http: 'EXTENSION_DOWNLOAD_UNAVAILABLE', checksum: 'EXTENSION_VERIFY_FAILED', disk: 'EXTENSION_FOLDER_FAILED', cancelled: 'EXTENSION_DOWNLOAD_CANCELLED',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** Only the pinned host, on the default HTTPS port, with no credentials in the address. */
|
|
44
|
+
export function allowedPackageHost(url) {
|
|
45
|
+
return url.protocol === 'https:' && url.hostname === EXTENSION_PACKAGE_HOST && (url.port === '' || url.port === '443') && !url.username && !url.password;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The pinned package's bytes and verified files: { zip, files }. `workDir` holds the transfer's working file, removed
|
|
49
|
+
// whatever happens. Throws one of PACKAGE_ERROR_CODES; never writes anything else.
|
|
50
|
+
async function downloadPackage({ pin = EXTENSION_PIN, workDir, fetchImpl = fetch, signal, onProgress = () => {}, stallMs = PACKAGE_STALL_MS, totalMs = PACKAGE_TOTAL_MS }) {
|
|
51
|
+
if (pinProblems(pin).length) throw packageError('EXTENSION_VERIFY_FAILED', 'This SynaBun has no valid extension pin.');
|
|
52
|
+
const file = join(workDir, downloadWorkName());
|
|
53
|
+
const stop = new AbortController();
|
|
54
|
+
let timedOut = false;
|
|
55
|
+
const timer = setTimeout(() => { timedOut = true; stop.abort(); }, totalMs); timer.unref?.();
|
|
56
|
+
const onAbort = () => stop.abort();
|
|
57
|
+
if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
|
|
58
|
+
try {
|
|
59
|
+
let zip;
|
|
60
|
+
try {
|
|
61
|
+
await downloadFile({ url: pin.url, allow: allowedPackageHost, destination: file, maxBytes: pin.size, expectedSize: pin.size, sha256: pin.sha256, fetchImpl, signal: stop.signal, onProgress, stallMs,
|
|
62
|
+
accept: 'application/zip, application/octet-stream', identityOnly: true });
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (timedOut) throw packageError('EXTENSION_DOWNLOAD_OFFLINE', 'The download took too long.', 'timeout');
|
|
65
|
+
throw packageError(TRANSFER_CODES[error?.code] || 'EXTENSION_FOLDER_FAILED', error?.message || 'The download failed.', error?.code === 'http' ? error.detail : error?.code);
|
|
66
|
+
}
|
|
67
|
+
try { zip = readFileSync(file); } catch { throw packageError('EXTENSION_FOLDER_FAILED', 'The download could not be read back.'); }
|
|
68
|
+
// The bytes that are read are the bytes that were checked: size and SHA-256 once more, over what is in memory.
|
|
69
|
+
let files;
|
|
70
|
+
try { files = verifiedPackageFiles(zip, pin); } catch (error) { throw packageError('EXTENSION_VERIFY_FAILED', error?.message || 'The package cannot be read.'); }
|
|
71
|
+
return { zip, files };
|
|
72
|
+
} finally {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
signal?.removeEventListener('abort', onAbort);
|
|
75
|
+
rmSync(file, { force: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The verified files of the pinned package: [{ rel, bytes }]. `workDir` holds the transfer's working file, which is
|
|
81
|
+
* removed whatever happens. Throws one of PACKAGE_ERROR_CODES; never writes anything else.
|
|
82
|
+
*/
|
|
83
|
+
export async function fetchExtensionPackage(options) { return (await downloadPackage(options)).files; }
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The owner's extension folder and the package it comes from. `home`: the data home; `appPort`: () => this server's
|
|
87
|
+
* port; `pin`: the release's pin. Returns { status, needs, ensure, refreshInBackground, retarget, confirmReload, confirmRepairReload }.
|
|
88
|
+
*/
|
|
89
|
+
export function createExtensionPackage({ home, appPort, pin = EXTENSION_PIN, fetchImpl = fetch, now = Date.now, log = () => {}, stallMs = PACKAGE_STALL_MS, totalMs = PACKAGE_TOTAL_MS, io }) {
|
|
90
|
+
const port = () => Number(typeof appPort === 'function' ? appPort() : appPort);
|
|
91
|
+
let job = null; // the transfer under way: { promise, reason, received, total, stop }
|
|
92
|
+
let last = null; // how the last one ended: { ok, code, reason, at }
|
|
93
|
+
|
|
94
|
+
const look = () => inspectExtensionFolder({ home, appPort: port(), pin });
|
|
95
|
+
/**
|
|
96
|
+
* What the folder needs: 'install' (no folder), 'update' (a folder that is not exactly the pinned extension: another
|
|
97
|
+
* version, or a file changed, added or deleted), 'unsafe' (its root is a link, another user's or writable by others:
|
|
98
|
+
* nothing is done there), or null (the pinned extension; at most its port is set, with no download).
|
|
99
|
+
*/
|
|
100
|
+
function needs() {
|
|
101
|
+
const state = look().state;
|
|
102
|
+
return state === 'missing' ? 'install' : state === 'other' ? 'update' : state === 'unsafe' ? 'unsafe' : null;
|
|
103
|
+
}
|
|
104
|
+
function status() {
|
|
105
|
+
const state = extensionFolderState(home), need = needs(), shown = state.present ? state : null;
|
|
106
|
+
const failed = need === 'unsafe' ? { code: 'EXTENSION_FOLDER_UNSAFE', reason: 'check', at: null } : !job && last && !last.ok && need ? last : null;
|
|
107
|
+
return {
|
|
108
|
+
pinnedVersion: pin.version, folderVersion: shown ? shown.version : null, folder: shown ? shown.folder : null, needs: need,
|
|
109
|
+
phase: job ? 'downloading' : failed ? 'failed' : 'idle',
|
|
110
|
+
...(job ? { received: job.received, total: job.total, reason: job.reason } : {}),
|
|
111
|
+
...(!job && failed ? { code: failed.code, reason: failed.reason, at: failed.at } : {}),
|
|
112
|
+
// A Reload the folder's marker asks for (a port change, or a repair: lib/browser-extension-folder.js), until the
|
|
113
|
+
// setup page sees the extension running again (confirmReload), or for a repair until the owner confirms it in
|
|
114
|
+
// Settings (confirmRepairReload).
|
|
115
|
+
...(state.reloadPending ? { reloadPending: true, reloadReason: state.reloadReason } : {}),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const settle = () => retargetExtensionFolder({ home, appPort: port(), pin, now, io });
|
|
119
|
+
async function run(reason, stop) {
|
|
120
|
+
const workDir = extensionWorkDir(home);
|
|
121
|
+
// A folder this data home can repair or place by itself: the verified package it keeps, with no network.
|
|
122
|
+
const kept = cachedExtensionPackage({ home, pin });
|
|
123
|
+
if (kept) return prepareExtensionFolder({ files: kept, home, appPort: port(), pin, now, io });
|
|
124
|
+
const { zip, files } = await downloadPackage({ pin, workDir, fetchImpl, signal: stop.signal, stallMs, totalMs,
|
|
125
|
+
onProgress: ({ received, total }) => { if (job) { job.received = received; job.total = total || pin.size; } } });
|
|
126
|
+
// A setup the owner cancelled while the last bytes arrived installs nothing.
|
|
127
|
+
if (stop.signal.aborted) throw packageError('EXTENSION_DOWNLOAD_CANCELLED', 'The download was stopped.');
|
|
128
|
+
return prepareExtensionFolder({ files, zip, home, appPort: port(), pin, now, io });
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The folder, ready to load: when it is the pinned extension, as it is (its setup port set and verified, no network);
|
|
132
|
+
* else after the pinned package was verified and placed. Resolves what prepareExtensionFolder returns; rejects with
|
|
133
|
+
* one of PACKAGE_ERROR_CODES, leaving the folder that was there in place. `signal` stops the transfer.
|
|
134
|
+
*/
|
|
135
|
+
function ensure({ reason = 'setup', signal } = {}) {
|
|
136
|
+
// A transfer that was told to stop is over for whoever asks now (a setup started again): it gets its own, after it.
|
|
137
|
+
if (job?.stop.signal.aborted) {
|
|
138
|
+
const ending = job.promise;
|
|
139
|
+
return ending.then(() => {}, () => {}).then(() => ensure({ reason, signal }));
|
|
140
|
+
}
|
|
141
|
+
if (!job) {
|
|
142
|
+
const need = needs();
|
|
143
|
+
// Its message says why (no path): a link, another user's, others can write it, or a Linux group not proven private.
|
|
144
|
+
if (need === 'unsafe') { const why = look().reason; return Promise.reject(packageError('EXTENSION_FOLDER_UNSAFE', `The extension folder in the data folder is not safe to use${why ? `: ${why}` : ''}.`)); }
|
|
145
|
+
if (!need) {
|
|
146
|
+
// The pinned extension: its port set and the result verified (lib/browser-extension-folder.js), or a failure.
|
|
147
|
+
try {
|
|
148
|
+
const done = settle();
|
|
149
|
+
if (done.state !== 'current') throw packageError('EXTENSION_FOLDER_FAILED', 'The extension folder is not the pinned extension.');
|
|
150
|
+
return Promise.resolve({ folder: done.folder, version: done.version, changed: done.changed, previousVersion: done.version, appPort: port(), stale: false });
|
|
151
|
+
} catch (error) {
|
|
152
|
+
log({ event: 'package', outcome: 'failed', reason: 'port', code: error?.code || 'EXTENSION_FOLDER_FAILED' });
|
|
153
|
+
return Promise.reject(packageError(PACKAGE_ERROR_CODES.includes(error?.code) ? error.code : 'EXTENSION_FOLDER_FAILED', error?.message || 'The extension folder could not be set.'));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const stop = new AbortController();
|
|
157
|
+
const mine = { reason, received: 0, total: pin.size, stop, promise: null };
|
|
158
|
+
mine.promise = run(reason, stop).then(
|
|
159
|
+
result => { last = { ok: true, reason, at: now() }; log({ event: 'package', outcome: 'installed', reason, version: result.version, changed: result.changed }); return result; },
|
|
160
|
+
error => {
|
|
161
|
+
const code = PACKAGE_ERROR_CODES.includes(error?.code) ? error.code : 'EXTENSION_FOLDER_FAILED';
|
|
162
|
+
// The owner stopped it: nothing failed, and there is nothing to report. A folder that is still not the pinned
|
|
163
|
+
// extension is the exception: its update did not happen, nothing is running, and Settings has to offer Try again.
|
|
164
|
+
const cancelled = code === 'EXTENSION_DOWNLOAD_CANCELLED';
|
|
165
|
+
last = cancelled && needs() !== 'update' ? null : { ok: false, code, reason, at: now() };
|
|
166
|
+
log({ event: 'package', outcome: cancelled ? 'cancelled' : 'failed', reason, code, ...(typeof error?.detail === 'string' ? { detail: error.detail.slice(0, 40) } : {}) });
|
|
167
|
+
throw packageError(code, error?.message || code);
|
|
168
|
+
},
|
|
169
|
+
).finally(() => { if (job === mine) job = null; });
|
|
170
|
+
job = mine;
|
|
171
|
+
}
|
|
172
|
+
const current = job;
|
|
173
|
+
// A setup stops only a transfer made for a setup: one that joined the background update leaves it running.
|
|
174
|
+
if (signal && current.reason === 'setup') {
|
|
175
|
+
const onAbort = () => current.stop.abort();
|
|
176
|
+
if (signal.aborted) onAbort(); else { signal.addEventListener('abort', onAbort, { once: true }); current.promise.then(() => {}, () => {}).finally(() => signal.removeEventListener('abort', onAbort)); }
|
|
177
|
+
}
|
|
178
|
+
return current.promise;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
pin, needs, status, ensure,
|
|
182
|
+
/** After start-up: bring a folder that is not the pinned extension up to date. Never downloads for a folder that is not there. */
|
|
183
|
+
refreshInBackground() {
|
|
184
|
+
if (job || needs() !== 'update') return null;
|
|
185
|
+
const promise = ensure({ reason: 'update' });
|
|
186
|
+
promise.catch(() => {});
|
|
187
|
+
return promise;
|
|
188
|
+
},
|
|
189
|
+
/**
|
|
190
|
+
* At start-up (no network): a stopped replacement settled, leftovers removed, the pinned extension's setup port set
|
|
191
|
+
* to this server's, and a changed folder repaired from the verified package this data home keeps. Throws
|
|
192
|
+
* EXTENSION_FOLDER_FAILED / EXTENSION_FOLDER_UNSAFE.
|
|
193
|
+
*/
|
|
194
|
+
retarget: settle,
|
|
195
|
+
/** The setup page saw the extension on this port: a Reload a port change asked for is done (never a repair's). */
|
|
196
|
+
confirmReload: () => confirmExtensionReload({ home, appPort: port() }),
|
|
197
|
+
/** The owner confirmed in Settings that they reloaded the extension after a repair: that Reload is done. */
|
|
198
|
+
confirmRepairReload: () => confirmExtensionRepairReload({ home }),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Which SynaBun Browser Bridge this app release works with, and who the extension is.
|
|
2
|
+
//
|
|
3
|
+
// The extension is not inside the app (no npm file, no installer payload). The app knows it by two things kept here,
|
|
4
|
+
// in app-owned code, so the server starts and pairs with no extension folder and no network:
|
|
5
|
+
//
|
|
6
|
+
// identity the extension's public key (the manifest's `key`). The extension ID is derived from it (EXTENSION_ID)
|
|
7
|
+
// and is what the bridge accepts as an Origin. It never changes, so a paired browser stays paired.
|
|
8
|
+
// release one exact package per app release: its version, its address on synabun.ai, its size and SHA-256
|
|
9
|
+
// (browser-extension-pin.json). The wire contract rejects unknown fields, so app and extension move in
|
|
10
|
+
// lock-step: a download is installed only when it is exactly that file (lib/browser-extension-package.js).
|
|
11
|
+
// files the SHA-256 of every file of that package (the manifest's with its setup content script set to one
|
|
12
|
+
// fixed port, TEMPLATE_PORT of lib/browser-extension-folder.js). The folder the browser loads is current
|
|
13
|
+
// only when it holds exactly these files, byte for byte, and nothing else (inspectExtensionFolder).
|
|
14
|
+
//
|
|
15
|
+
// The pin file is written by scripts/extension/check-browser-extension-pin.mjs (Dev only) and checked by it before a
|
|
16
|
+
// release. Nothing here reads the network or the data home.
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { EXTENSION_MAX_FILES, extensionFileAllowed } from './browser-extension-archive.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The one host an extension package may come from, and the folder its versioned, immutable files live in. The website
|
|
23
|
+
* serves its `Public/` tree under that same name (its build copies a .zip there byte for byte, and its image copies
|
|
24
|
+
* no other top-level folder), so the file `Public/downloads/browser-extension/<name>` of the website is this address.
|
|
25
|
+
*/
|
|
26
|
+
export const EXTENSION_PACKAGE_HOST = 'synabun.ai';
|
|
27
|
+
export const EXTENSION_PACKAGE_PATH = '/Public/downloads/browser-extension/';
|
|
28
|
+
/** No package is ever larger than this, whatever a pin says (the real one is about 0.2 MB). */
|
|
29
|
+
export const EXTENSION_PACKAGE_MAX_BYTES = 8 * 1024 * 1024;
|
|
30
|
+
|
|
31
|
+
/** The file name of a version's package. */
|
|
32
|
+
export function extensionPackageName(version) { return `synabun-browser-bridge-${version}.zip`; }
|
|
33
|
+
/** The address of a version's package: https, the one host, a versioned path that is never reused. */
|
|
34
|
+
export function extensionPackageUrl(version) { return `https://${EXTENSION_PACKAGE_HOST}${EXTENSION_PACKAGE_PATH}${extensionPackageName(version)}`; }
|
|
35
|
+
/** The extension ID a browser gives the extension with this public key (base64 DER): SHA-256, 16 bytes, as a-p. */
|
|
36
|
+
export function extensionIdOf(key) {
|
|
37
|
+
return createHash('sha256').update(Buffer.from(String(key), 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)));
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The extension's ID since it was first published. It is derived from the key, and a browser keeps an extension's
|
|
41
|
+
* pairing under its ID: a pin whose key gives another ID would be another extension, and every owner would pair again.
|
|
42
|
+
* scripts/extension/check-browser-extension-pin.mjs refuses to write or pass such a pin.
|
|
43
|
+
*/
|
|
44
|
+
export const HISTORICAL_EXTENSION_ID = 'hnoncohimcacnnlngchbkgpflpoefnil';
|
|
45
|
+
/** What is wrong with a pin's file list (an empty list: nothing). */
|
|
46
|
+
export function inventoryProblems(files) {
|
|
47
|
+
if (!files || typeof files !== 'object' || Array.isArray(files)) return ['files is not an object'];
|
|
48
|
+
const names = Object.keys(files), problems = [], seen = new Set();
|
|
49
|
+
if (!names.length || names.length > EXTENSION_MAX_FILES) problems.push(`files lists no file, or more than ${EXTENSION_MAX_FILES}`);
|
|
50
|
+
if (!names.includes('manifest.json')) problems.push('files has no manifest.json');
|
|
51
|
+
for (const name of names) {
|
|
52
|
+
if (!extensionFileAllowed(name)) problems.push(`files names ${JSON.stringify(name.slice(0, 80))}, which no extension folder may hold`);
|
|
53
|
+
else if (seen.has(name.toLowerCase())) problems.push(`files names ${name} twice`);
|
|
54
|
+
seen.add(name.toLowerCase());
|
|
55
|
+
if (typeof files[name] !== 'string' || !/^[a-f0-9]{64}$/.test(files[name])) problems.push(`files.${name} is not 64 lowercase hex characters`);
|
|
56
|
+
}
|
|
57
|
+
return problems;
|
|
58
|
+
}
|
|
59
|
+
/** What is wrong with a pin (an empty list: nothing). */
|
|
60
|
+
export function pinProblems(pin) {
|
|
61
|
+
const problems = [];
|
|
62
|
+
if (!pin || typeof pin !== 'object') return ['the pin is not an object'];
|
|
63
|
+
if (typeof pin.name !== 'string' || !pin.name) problems.push('name is missing');
|
|
64
|
+
if (typeof pin.key !== 'string' || !/^[A-Za-z0-9+/]{300,}={0,2}$/.test(pin.key)) problems.push('key is not a base64 public key');
|
|
65
|
+
if (typeof pin.version !== 'string' || !/^\d+(\.\d+){1,3}$/.test(pin.version)) problems.push('version is not a dotted version');
|
|
66
|
+
if (typeof pin.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(pin.sha256)) problems.push('sha256 is not 64 lowercase hex characters');
|
|
67
|
+
if (!Number.isInteger(pin.size) || pin.size < 1 || pin.size > EXTENSION_PACKAGE_MAX_BYTES) problems.push(`size is not a whole number of bytes up to ${EXTENSION_PACKAGE_MAX_BYTES}`);
|
|
68
|
+
if (typeof pin.version === 'string' && pin.url !== extensionPackageUrl(pin.version)) problems.push(`url is not ${extensionPackageUrl(pin.version)}`);
|
|
69
|
+
problems.push(...inventoryProblems(pin.files));
|
|
70
|
+
return problems;
|
|
71
|
+
}
|
|
72
|
+
/** Reads and checks a pin file. Throws with every problem named. */
|
|
73
|
+
export function readExtensionPin(path) {
|
|
74
|
+
const { $comment: _comment, ...pin } = JSON.parse(readFileSync(path, 'utf8'));
|
|
75
|
+
const problems = pinProblems(pin);
|
|
76
|
+
if (problems.length) throw Object.assign(new Error(`The browser extension pin is not valid: ${problems.join('; ')}.`), { code: 'EXTENSION_PIN_INVALID' });
|
|
77
|
+
return Object.freeze({ ...pin, files: Object.freeze({ ...pin.files }) });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const EXTENSION_PIN_PATH = new URL('./browser-extension-pin.json', import.meta.url);
|
|
81
|
+
/** This release's pin: { name, key, version, url, sha256, size, files }. */
|
|
82
|
+
export const EXTENSION_PIN = readExtensionPin(EXTENSION_PIN_PATH);
|
|
83
|
+
/** The extension's ID in every Chromium browser, from every folder it is loaded from. */
|
|
84
|
+
export const EXTENSION_ID = extensionIdOf(EXTENSION_PIN.key);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$comment": "The one SynaBun Browser Bridge this app release works with (docs/browser-extension-bridge.md -> Where the extension comes from). The app downloads exactly this file when the owner presses \"Connect your browser\" and installs it only when its size and SHA-256 are these. files is the SHA-256 of every file in it (the manifest with its setup content script set to port 1): the folder the browser loads counts as this extension only when it holds exactly these files. version, url, sha256, size and files are written by `node scripts/extension/check-browser-extension-pin.mjs --write` from the zip built out of browser-extension/ (Dev only); never edit them by hand. key is the extension's public key (its manifest's `key`): the extension ID is derived from it and never changes.",
|
|
3
|
+
"name": "SynaBun Browser Bridge",
|
|
4
|
+
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDPDDuBTQq9nQgulmTSvzujxyOMZ7A7ttMSXtbIwup/X3kOlbkqoJEqQRGGJeb7+cNBSiiDBA5lhS0oYc9YeFcwNCucNMvGawDGblbQzDWEmn9dDK1krFVXWqNHVPIrEWlzCD2swXmIE2FCjMd5zw6dSRmmxu7VgE6bzvuOgB/W/oeOAyCsEDhDRDLBkjmb+yCsuexiXRWoempPsvAVhxhE8zEQJ1e8ChlFMtpOXSobU+YDgKYfcFy9Fbmk/o6M6B9y5zSlzs/HYIu7xvcCwjZI457idVMRxxAT6J/kXytmfKe/zbi5IO5/i0x9SCA1HRvt8K3nJqoH03h4TOvFwOwIDAQAB",
|
|
5
|
+
"version": "1.4.0",
|
|
6
|
+
"url": "https://synabun.ai/Public/downloads/browser-extension/synabun-browser-bridge-1.4.0.zip",
|
|
7
|
+
"sha256": "6c6fdd942c9b11173758701678571d3c60f1b56aa8712e3f754d6c7b8a7a96bb",
|
|
8
|
+
"size": 206907,
|
|
9
|
+
"files": {
|
|
10
|
+
"content.js": "5420e3bf96c4aea5c7d5f529264eedd49bae9431da3f52abb96de536a4f48944",
|
|
11
|
+
"engine.js": "653f06e353e99b7c417e61c1415925673455ffce075105ba794ae740e6a2c816",
|
|
12
|
+
"icons/icon-128.png": "0749c9c8b40090232e0a234443c634117275598630ec06f4834d20bcad2b6841",
|
|
13
|
+
"icons/icon-16.png": "e91f674029855c7ea4bc6ca045087fe867ddba706209707060379c4832c15422",
|
|
14
|
+
"icons/icon-32.png": "5cc0916b2557a8d13c479a7e3a0170584be4c2f58cf770899c1be1aea106fe53",
|
|
15
|
+
"icons/icon-48.png": "6076ff8376ddf79356adc53672524b893f35a007c1666c9b3873c15803a386d8",
|
|
16
|
+
"icons/status-off-16.png": "b860b60a99a5f89bb024fd8411c6645ca071fabc4eee807dad7d7e1a0eec6a26",
|
|
17
|
+
"icons/status-off-32.png": "9ecc6608dd8da21b3d35497aa94480bb4c8b542398d6d8b35b35d3912e72c7c1",
|
|
18
|
+
"icons/status-off-48.png": "9b1395d665df287e299b20b5ba7a0503eb880cd0797fa07c600572491e126c9a",
|
|
19
|
+
"icons/status-on-16.png": "c9cbb6e4211f918b2179a796908cf9ebcf7cb5723d9aaa38a93486c2e3b0cd3e",
|
|
20
|
+
"icons/status-on-32.png": "b67d8fb865e02754ca0d1f1f2e0ead08655340a4ad93511e52ff65db4d487ed7",
|
|
21
|
+
"icons/status-on-48.png": "c9f306fb5dcbd6a919e5169e3c87c618116bad54858b434b02245dcd1a40b269",
|
|
22
|
+
"manifest.json": "d027d047542b2affa0c2528ee1863de29767f4b2d9abdc79085022455b301735",
|
|
23
|
+
"popup-strings.js": "683063d9896a306b3abf5d19283ba38a8f0ed88a0c32db1f028262fa1d075107",
|
|
24
|
+
"popup-view.js": "c7c9bd582a893d11ca088544e64dd5661c75406920ef5f2b0609a44a58f183c4",
|
|
25
|
+
"popup.css": "d6a6c5442942bede66f315accef476c591ad71ea4ac09b51d689a622753208f1",
|
|
26
|
+
"popup.html": "b04a333f7c7db956fe30dfc760e2bb528984dcf874d5a8e5849776209b8529ec",
|
|
27
|
+
"popup.js": "62a83c93aa9657e16dbd81eb6e853cc772794b22042fca051ea8744c55602670",
|
|
28
|
+
"protocol.js": "7b29203855da05a6122565273b77094e2abfd91d2e820ac90797d6317bb8bea4",
|
|
29
|
+
"service-worker.js": "b8871ebe8b62b1e8d44c6b38757175cd8d519534ed04360597c8cc19cc956b88",
|
|
30
|
+
"setup-content.js": "9cb56f6f046af294328c03a080cefc58052ee405366eff5f3d70bb1ea02dbabe",
|
|
31
|
+
"tokens.css": "a27f691794d844cb81b98b45e12863b102e06e9f0a3c722ba96b69b84d3c5a3f"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
// shows the folder in Finder, Explorer or the file manager. The owner does the three steps no app may do for them
|
|
5
5
|
// (the extensions page, Developer mode, Load unpacked); the extension then pairs by itself with a one-time token.
|
|
6
6
|
//
|
|
7
|
+
// The folder's files are the one package this release pins, downloaded from synabun.ai and verified
|
|
8
|
+
// (lib/browser-extension-package.js). A folder that is already there is used as it is, in the same request as before.
|
|
9
|
+
// One that is not there yet, or is older than the pin, is fetched first: the setup is then `downloading` (with the
|
|
10
|
+
// bytes so far), and the browser and the folder are opened only once the verified files are in place. A download that
|
|
11
|
+
// fails ends the setup with its code (offline, unavailable, verification failed) and Start again tries once more;
|
|
12
|
+
// nothing is ever installed that did not verify.
|
|
13
|
+
//
|
|
7
14
|
// Every route that reaches this is the owner's (server.js mounts them behind the same guard as pairing and the mode:
|
|
8
15
|
// ownerRouteGuard, this boot's page secret, no automation caller). Nothing here starts a program by itself: `exec` is
|
|
9
16
|
// injected (server.js: execFile, no shell, detached) and gets a plan from lib/browser-default.js.
|
|
@@ -13,29 +20,60 @@
|
|
|
13
20
|
// bridge accepts it once, in its pairing handshake, and forgets it (lib/browser-extension-bridge.js
|
|
14
21
|
// beginSetupPairing). It is never logged, never in a status and never in a URL.
|
|
15
22
|
import { launchPlan, revealPlan, SUPPORTED_BROWSER_IDS } from './browser-default.js';
|
|
16
|
-
import { SETUP_PAGE_PATH } from './browser-extension-folder.js';
|
|
23
|
+
import { compareVersions, SETUP_PAGE_PATH } from './browser-extension-folder.js';
|
|
17
24
|
import { randomBytes } from 'node:crypto';
|
|
18
25
|
|
|
19
|
-
export const SETUP_STATES = Object.freeze(['idle', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
|
|
26
|
+
export const SETUP_STATES = Object.freeze(['idle', 'downloading', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
|
|
27
|
+
/** The codes a download of the extension package can end a setup with (lib/browser-extension-package.js). */
|
|
28
|
+
export const DOWNLOAD_ERRORS = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED']);
|
|
20
29
|
export const SETUP_WINDOW_MS = 15 * 60 * 1000;
|
|
21
30
|
export const TICKET_MS = 2 * 60 * 1000;
|
|
22
31
|
export const MAX_TICKETS = 5;
|
|
23
32
|
const fail = (code, message = code) => { throw Object.assign(new Error(message), { code }); };
|
|
24
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Whether the browser should be told to reload the extension: it is connected, the folder holds what this release
|
|
36
|
+
* wants (the pinned version, or a newer one a later release left there) and the browser runs something else. While
|
|
37
|
+
* the folder itself is older than the pin a Reload changes nothing: that is `updateNeeded`, which SynaBun settles by
|
|
38
|
+
* downloading the pinned package. `reloadPending`: the folder's marker asks for a Reload until the setup page saw the
|
|
39
|
+
* extension running again; `reloadReason` says why. 'port': the setup port changed while the version stayed, and the
|
|
40
|
+
* browser still runs the old manifest (asked only while the extension is connected). 'repair': files that were not
|
|
41
|
+
* the pinned extension were replaced, and the browser may still run them at the same version, connected or not (the
|
|
42
|
+
* changed code may not connect at all): asked until the owner confirms the Reload in Settings, and said in its own
|
|
43
|
+
* words (`reloadRepaired`).
|
|
44
|
+
*/
|
|
45
|
+
export function extensionVersions({ connected, extensionVersion, folderVersion, pinnedVersion, reloadPending = false, reloadReason = null }) {
|
|
46
|
+
const current = !!folderVersion && (!pinnedVersion || compareVersions(folderVersion, pinnedVersion) >= 0);
|
|
47
|
+
const repaired = current && reloadPending === true && reloadReason === 'repair';
|
|
48
|
+
const reloadNeeded = repaired || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
|
|
49
|
+
return {
|
|
50
|
+
reloadNeeded,
|
|
51
|
+
updateNeeded: !!(folderVersion && pinnedVersion && compareVersions(folderVersion, pinnedVersion) < 0),
|
|
52
|
+
...(repaired ? { reloadRepaired: true } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
25
56
|
/**
|
|
26
57
|
* `bridge` (createExtensionBridge), `detect()` → { browser, installedBrowsers } (browser-default.js detectBrowsers with
|
|
27
|
-
* the system's runners), `prepare()` → { folder, version, changed }
|
|
28
|
-
*
|
|
29
|
-
* `
|
|
58
|
+
* the system's runners), `prepare({ signal })` → { folder, version, changed } once the folder is ready to load
|
|
59
|
+
* (browser-extension-package.js ensure: it may download), `exec(cmd, args)` starts a program (never a shell),
|
|
60
|
+
* `appOrigin()` is this server's own origin on loopback (http://127.0.0.1:<port>), `platform` the OS,
|
|
61
|
+
* `folderVersion()` the version the folder holds, `packageStatus()` → { pinnedVersion, needs, phase, received, total,
|
|
62
|
+
* code, reloadPending } (browser-extension-package.js status; `needs` says that `prepare` will download),
|
|
63
|
+
* `confirmReload()` the setup page saw the extension's content script on this port (browser-extension-package.js; it
|
|
64
|
+
* never clears a repair's Reload).
|
|
30
65
|
*/
|
|
31
66
|
export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin, platform = process.platform, now = Date.now,
|
|
32
|
-
windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null } = {}) {
|
|
67
|
+
windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false } = {}) {
|
|
33
68
|
let setup = null;
|
|
69
|
+
// The latest start, from its first step: a cancel or a later start ends it before it prepares or opens anything.
|
|
70
|
+
let attempt = null;
|
|
34
71
|
const pageUrl = () => `${appOrigin()}${SETUP_PAGE_PATH}`;
|
|
35
72
|
const describe = browser => browser ? { id: browser.id, name: browser.name, supported: browser.supported === true, extensionsUrl: browser.extensionsUrl || null } : null;
|
|
36
73
|
function state() {
|
|
37
74
|
if (!setup) return 'idle';
|
|
38
75
|
if (setup.error) return 'error';
|
|
76
|
+
if (setup.preparing) return 'downloading';
|
|
39
77
|
const bridgeStatus = bridge.status();
|
|
40
78
|
// Paired by this setup: a pairing made after it began (its token, or the typed code as a fallback). Connected once
|
|
41
79
|
// the extension's first inventory arrived; "Pairing…" from the token's handshake until then.
|
|
@@ -59,16 +97,20 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
59
97
|
}
|
|
60
98
|
function view() {
|
|
61
99
|
const current = state(), bridgeStatus = bridge.status();
|
|
62
|
-
const version = folderVersion();
|
|
100
|
+
const version = folderVersion(), pkg = packageStatus() || {};
|
|
101
|
+
const pinnedVersion = typeof pkg.pinnedVersion === 'string' ? pkg.pinnedVersion : null;
|
|
63
102
|
return {
|
|
64
103
|
state: current,
|
|
65
104
|
...(setup ? { setupId: setup.id, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
|
|
66
105
|
folder: setup.folder, extensionsUrl: setup.browser?.extensionsUrl || null, opened: setup.opened, revealed: setup.revealed, expiresAt: setup.until } : {}),
|
|
67
106
|
...(setup?.error ? { code: setup.error.code } : {}),
|
|
68
107
|
connected: bridgeStatus.connected, paired: bridgeStatus.paired, bridgePort: bridgeStatus.port,
|
|
69
|
-
extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version,
|
|
70
|
-
// The
|
|
71
|
-
|
|
108
|
+
extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version, pinnedVersion,
|
|
109
|
+
// The bytes so far while the pinned package is on its way (the setup's own download, or an update's).
|
|
110
|
+
...(pkg.phase === 'downloading' ? { download: { received: Number(pkg.received) || 0, total: Number(pkg.total) || 0 } } : {}),
|
|
111
|
+
// The browser runs another copy than the folder holds (or an extension from before versions were reported);
|
|
112
|
+
// or the folder itself is older than this release's extension, which a download settles, never a Reload.
|
|
113
|
+
...extensionVersions({ connected: bridgeStatus.connected, extensionVersion: bridgeStatus.extensionVersion, folderVersion: version, pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
|
|
72
114
|
};
|
|
73
115
|
}
|
|
74
116
|
return {
|
|
@@ -79,9 +121,16 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
79
121
|
*/
|
|
80
122
|
async start({ browserId } = {}) {
|
|
81
123
|
if (browserId !== undefined && browserId !== null && !SUPPORTED_BROWSER_IDS.includes(browserId)) fail('INVALID_MESSAGE');
|
|
82
|
-
if (setup) bridge.endSetupPairing();
|
|
124
|
+
if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); }
|
|
125
|
+
// This start is the current one before its first wait: a cancel during the browser detection, or a later start
|
|
126
|
+
// whose detection ends first, leaves this one nothing to do when its own detection ends.
|
|
127
|
+
attempt?.stop.abort();
|
|
128
|
+
const own = { stop: new AbortController() };
|
|
129
|
+
attempt = own;
|
|
130
|
+
const superseded = () => attempt !== own || own.stop.signal.aborted;
|
|
83
131
|
let detected;
|
|
84
132
|
try { detected = await detect(); } catch { detected = { browser: null, installedBrowsers: [] }; }
|
|
133
|
+
if (superseded()) return view();
|
|
85
134
|
const installed = Array.isArray(detected?.installedBrowsers) ? detected.installedBrowsers.filter(b => b?.supported) : [];
|
|
86
135
|
const defaultBrowser = detected?.browser || { id: 'unknown', name: 'Unknown browser', supported: false, extensionsUrl: null };
|
|
87
136
|
let browser = defaultBrowser;
|
|
@@ -91,16 +140,47 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
91
140
|
}
|
|
92
141
|
setup = { id: randomBytes(12).toString('hex'), startedAt: now(), until: now() + windowMs, browser, defaultBrowser, installed,
|
|
93
142
|
folder: null, opened: false, revealed: false, tickets: 0, pairedBefore: bridge.status().pairedAt || 0, error: null };
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
143
|
+
const mine = setup;
|
|
144
|
+
mine.stop = own.stop;
|
|
145
|
+
// A browser that cannot run the extension gets no download: the page offers the installed ones, and choosing one
|
|
146
|
+
// starts the setup again.
|
|
147
|
+
if (!browser.supported && (packageStatus() || {}).needs) return view();
|
|
148
|
+
// Once the folder is ready: the page in the browser, the folder in the file manager (never for a start that was
|
|
149
|
+
// cancelled or replaced meanwhile).
|
|
150
|
+
const present = async () => {
|
|
151
|
+
if (!browser.supported || setup !== mine || superseded()) return;
|
|
152
|
+
mine.opened = await open(browser);
|
|
153
|
+
if (setup !== mine) return;
|
|
154
|
+
mine.revealed = (await reveal()).ok === true;
|
|
155
|
+
if (!mine.opened) mine.error = { code: 'OPEN_FAILED' };
|
|
156
|
+
};
|
|
157
|
+
// Started in this step, so the answer below already carries a download's progress.
|
|
158
|
+
let preparing;
|
|
159
|
+
try { preparing = Promise.resolve(prepare({ signal: mine.stop.signal })); } catch (error) { preparing = Promise.reject(error); }
|
|
160
|
+
const ready = preparing.then(
|
|
161
|
+
prepared => { mine.folder = prepared.folder; },
|
|
162
|
+
error => { mine.error = { code: DOWNLOAD_ERRORS.includes(error?.code) || error?.code === 'EXTENSION_FOLDER_UNSAFE' ? error.code : 'EXTENSION_FOLDER_FAILED' }; });
|
|
163
|
+
// A folder that needs no download answers in this request, as it always did. A download runs on: the setup is
|
|
164
|
+
// `downloading` until its files are verified and in place, and this request returns at once so its progress shows.
|
|
165
|
+
const needed = packageStatus() || {};
|
|
166
|
+
if (needed.needs || needed.phase === 'downloading') {
|
|
167
|
+
mine.preparing = true;
|
|
168
|
+
mine.settled = ready.then(async () => { mine.preparing = false; if (setup === mine && !mine.error) await present(); }).catch(() => { mine.preparing = false; });
|
|
169
|
+
return view();
|
|
100
170
|
}
|
|
171
|
+
await ready;
|
|
172
|
+
if (setup !== mine || mine.error) return view();
|
|
173
|
+
await present();
|
|
101
174
|
return view();
|
|
102
175
|
},
|
|
103
176
|
status: view,
|
|
177
|
+
/**
|
|
178
|
+
* The setup page saw the extension's content script on this server's port (POST …/setup/seen): the browser runs
|
|
179
|
+
* the folder's manifest for this port, so the Reload a port change asked for is done. A repair's Reload is not: the
|
|
180
|
+
* copy the browser still runs answers the page just the same, so only the owner's confirmation in Settings clears it
|
|
181
|
+
* (POST …/reload/confirm, browser-extension-package.js confirmRepairReload).
|
|
182
|
+
*/
|
|
183
|
+
seen() { confirmReload(); return view(); },
|
|
104
184
|
/**
|
|
105
185
|
* The one-time token for the setup page (POST …/setup/ticket): only while the setup waits for the extension.
|
|
106
186
|
* Returns { token, bridgePort, expiresAt }.
|
|
@@ -111,11 +191,14 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
111
191
|
if (current !== 'waiting-for-extension') fail(current === 'error' ? setup.error?.code || 'SETUP_NOT_ACTIVE' : 'SETUP_NOT_WAITING');
|
|
112
192
|
if (setup.tickets >= maxTickets) fail('SETUP_TICKETS_USED');
|
|
113
193
|
setup.tickets++;
|
|
194
|
+
// A ticket clears no pending Reload: the page sends `seen` for that (it does before it asks for a ticket).
|
|
114
195
|
const until = Math.min(setup.until, now() + ticketMs);
|
|
115
196
|
const made = await bridge.beginSetupPairing({ until });
|
|
116
197
|
return { token: made.token, bridgePort: made.port, expiresAt: made.expiresAt };
|
|
117
198
|
},
|
|
118
|
-
cancel() { if (setup) bridge.endSetupPairing(); setup = null; return view(); },
|
|
199
|
+
cancel() { attempt?.stop.abort(); attempt = null; if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); } setup = null; return view(); },
|
|
200
|
+
/** Resolves when a download this setup waits for has ended, either way (tests). */
|
|
201
|
+
settled: () => setup?.settled || Promise.resolve(),
|
|
119
202
|
reveal,
|
|
120
203
|
/** Opens the setup page again (in the setup's browser). */
|
|
121
204
|
async reopen() { if (!setup?.browser?.supported) fail('SETUP_NOT_ACTIVE'); setup.opened = await open(setup.browser); return view(); },
|
|
@@ -130,6 +213,10 @@ export const SETUP_ERROR_TEXT = Object.freeze({
|
|
|
130
213
|
SETUP_EXPIRED: 'This setup ran out of time (15 minutes). Start "Connect your browser" again.',
|
|
131
214
|
BROWSER_NOT_INSTALLED: 'That browser was not found on this computer.',
|
|
132
215
|
EXTENSION_FOLDER_FAILED: 'SynaBun could not prepare the extension folder in its data folder.',
|
|
216
|
+
EXTENSION_FOLDER_UNSAFE: 'SynaBun did not use the extension folder in its data folder (browser-extension): it is a link, belongs to another user, or others can write to it (on Linux, a group that is not your own private group counts as others). Nothing was changed. Fix or remove that folder, then start "Connect your browser" again.',
|
|
217
|
+
EXTENSION_DOWNLOAD_OFFLINE: 'SynaBun could not reach synabun.ai to download the extension. Check the internet connection, then start "Connect your browser" again.',
|
|
218
|
+
EXTENSION_DOWNLOAD_UNAVAILABLE: 'synabun.ai did not have the extension this SynaBun version needs. Try again later, or update SynaBun.',
|
|
219
|
+
EXTENSION_VERIFY_FAILED: 'The downloaded extension was not the file this SynaBun version expects, so it was not installed. Try again; if it keeps failing, update SynaBun.',
|
|
133
220
|
OPEN_FAILED: 'SynaBun could not open the setup page in the browser. Open it yourself from Settings → Browser.',
|
|
134
221
|
REVEAL_FAILED: 'SynaBun could not show the folder. Copy its path from the setup page.',
|
|
135
222
|
INVALID_MESSAGE: 'Invalid setup request.',
|
|
@@ -249,6 +249,11 @@ async function writeAll(handle, buffer) {
|
|
|
249
249
|
/**
|
|
250
250
|
* Download `url` into `destination` (a new file), HTTPS only and only through
|
|
251
251
|
* hosts `allow` accepts. Checks the size and, when given, the SHA-256.
|
|
252
|
+
* `identityOnly`: an answer with any Content-Encoding but identity is refused
|
|
253
|
+
* before its body is read, so `maxBytes` bounds the bytes on the wire and no
|
|
254
|
+
* decoding work is done (fetch would otherwise decode gzip or br by itself and
|
|
255
|
+
* count the decoded bytes). Every answer that is refused, and every transfer
|
|
256
|
+
* that fails, ends its request: the body is cancelled and the request aborted.
|
|
252
257
|
* Resolves { sha256, size, url } (the address the file came from).
|
|
253
258
|
*/
|
|
254
259
|
export async function downloadFile({
|
|
@@ -263,6 +268,7 @@ export async function downloadFile({
|
|
|
263
268
|
onProgress = () => {},
|
|
264
269
|
stallMs = 60_000,
|
|
265
270
|
accept = 'application/octet-stream',
|
|
271
|
+
identityOnly = false,
|
|
266
272
|
}) {
|
|
267
273
|
let current;
|
|
268
274
|
try { current = new URL(url); } catch { throw new CliInstallError('internal', `Not an address: ${url}`); }
|
|
@@ -280,26 +286,33 @@ export async function downloadFile({
|
|
|
280
286
|
let made = false;
|
|
281
287
|
let answered = false;
|
|
282
288
|
let received = 0;
|
|
289
|
+
// The body still open (an answer being looked at, then the reader): cancelled whenever the download is given up.
|
|
290
|
+
let release = null;
|
|
283
291
|
const hash = createHash('sha256');
|
|
284
292
|
try {
|
|
285
293
|
alive();
|
|
286
294
|
let response = null;
|
|
287
295
|
for (let hop = 0; ; hop++) {
|
|
288
296
|
response = await fetchImpl(current, { redirect: 'manual', signal: stop.signal, headers: { accept, 'accept-encoding': 'identity', 'user-agent': 'synabun' } });
|
|
297
|
+
const answer = response;
|
|
298
|
+
release = () => answer.body?.cancel();
|
|
289
299
|
if (response.status < 300 || response.status >= 400) break;
|
|
290
300
|
const next = nextHop(response, current, allow);
|
|
291
301
|
try { await response.body?.cancel(); } catch { /* nothing to drain */ }
|
|
302
|
+
release = null;
|
|
292
303
|
if (hop >= MAX_REDIRECTS) throw new CliInstallError('http', 'The download server redirected too many times.');
|
|
293
304
|
current = next;
|
|
294
305
|
alive();
|
|
295
306
|
}
|
|
296
307
|
if (response.status !== 200 || !response.body) {
|
|
297
|
-
try { await response.body?.cancel(); } catch { /* nothing to drain */ }
|
|
298
308
|
throw new CliInstallError('http', `${current.hostname} answered ${response.status} instead of the file.`, { detail: String(response.status) });
|
|
299
309
|
}
|
|
310
|
+
const encoding = String(response.headers.get('content-encoding') || '').trim().toLowerCase();
|
|
311
|
+
if (identityOnly && encoding && encoding !== 'identity') {
|
|
312
|
+
throw new CliInstallError('http', `${current.hostname} sent the file encoded (${encoding.slice(0, 20)}) although it was asked for the file as it is. It was not downloaded.`, { detail: 'content-encoding' });
|
|
313
|
+
}
|
|
300
314
|
const announced = Number(response.headers.get('content-length'));
|
|
301
315
|
if (Number.isFinite(announced) && announced > 0 && ((expectedSize && announced !== expectedSize) || announced > maxBytes)) {
|
|
302
|
-
try { await response.body.cancel(); } catch { /* nothing to drain */ }
|
|
303
316
|
throw new CliInstallError('checksum', `${current.hostname} offered ${announced} bytes${expectedSize ? `; the published file has ${expectedSize}` : ''}. It was not downloaded.`);
|
|
304
317
|
}
|
|
305
318
|
answered = true;
|
|
@@ -310,6 +323,7 @@ export async function downloadFile({
|
|
|
310
323
|
// Read through a reader of our own, cancelled on a stall or a stop: the transfer ends then whatever the
|
|
311
324
|
// transport does with the signal.
|
|
312
325
|
const reader = response.body.getReader();
|
|
326
|
+
release = () => reader.cancel();
|
|
313
327
|
const onStop = () => { reader.cancel(stop.signal.reason).catch(() => {}); };
|
|
314
328
|
stop.signal.addEventListener('abort', onStop, { once: true });
|
|
315
329
|
try {
|
|
@@ -336,12 +350,18 @@ export async function downloadFile({
|
|
|
336
350
|
await handle.sync();
|
|
337
351
|
await handle.close();
|
|
338
352
|
handle = null;
|
|
353
|
+
release = null;
|
|
339
354
|
return { sha256: digest, size: received, url: current.href };
|
|
340
355
|
} catch (error) {
|
|
356
|
+
const stoppedFor = stop.signal.aborted && stop.signal.reason instanceof CliInstallError ? stop.signal.reason : null;
|
|
357
|
+
// Whatever ended it, the request ends here too: nothing more arrives, is decoded or is read.
|
|
358
|
+
if (!stop.signal.aborted) stop.abort(new CliInstallError('cancelled', 'The download was given up.'));
|
|
359
|
+
try { await release?.(); } catch { /* cancelled already */ }
|
|
360
|
+
release = null;
|
|
341
361
|
try { await handle?.close(); } catch { /* closed */ }
|
|
342
362
|
handle = null;
|
|
343
363
|
if (made) rmSync(destination, { force: true });
|
|
344
|
-
if (
|
|
364
|
+
if (stoppedFor) throw stoppedFor;
|
|
345
365
|
if (error instanceof CliInstallError) throw error;
|
|
346
366
|
if (DISK_CODES.has(errorCode(error))) throw asInstallError(error, 'disk', `The download could not be saved (${errorCode(error)}).`);
|
|
347
367
|
if (answered) throw new CliInstallError('interrupted', `The download from ${current.hostname} ended after ${received} bytes.`, { cause: error, detail: errorCode(error) || error?.message });
|