brickproof-adb 0.0.0-stage → 1.1.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/src/http.js ADDED
@@ -0,0 +1,326 @@
1
+ 'use strict';
2
+ /**
3
+ * brickproof-adb over HTTP: the auth front and the Streamable HTTP transport (JSON
4
+ * responses, no SSE) in one listener.
5
+ *
6
+ * Auth, in front of everything:
7
+ * - secret path /private_<token>/mcp (works as a claude.ai custom connector), or
8
+ * - /mcp with Authorization: Bearer <token>.
9
+ * A wrong path is a bare 404 without WWW-Authenticate, /.well-known/* is 404 (so
10
+ * clients treat the server as authless and never start OAuth), and 401 is
11
+ * returned only when an Authorization header was sent and is wrong. Neither the
12
+ * token nor the request path is logged; log_requests prints the path with the
13
+ * token masked.
14
+ *
15
+ * On a localhost bind (127.0.0.1, localhost, ::1) a Host or Origin header that
16
+ * is not localhost, nor a name in allowed_hosts, is refused with 403 (DNS
17
+ * rebinding). On any other address there are no Host/Origin checks and the
18
+ * token alone protects the server.
19
+ *
20
+ * The body is read only after both checks passed, up to MAX_BODY_BYTES; a
21
+ * larger body gets 413 with Connection: close (body.js).
22
+ */
23
+
24
+ const crypto = require('crypto');
25
+ const http = require('http');
26
+ const S = require('./server');
27
+ const B = require('./body');
28
+
29
+ const DEFAULT_HOST = '127.0.0.1';
30
+ // Request body limit of /mcp; a larger body gets 413. No tool needs more:
31
+ // files go by path.
32
+ const MAX_BODY_BYTES = 1024 * 1024;
33
+ const LOCAL_BINDS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
34
+ // Hostnames accepted in Host and Origin on a localhost bind, port-agnostic.
35
+ const LOCAL_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
36
+
37
+ function isLocalBind(host) {
38
+ return LOCAL_BINDS.has(String(host).toLowerCase());
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Token
43
+ // ---------------------------------------------------------------------------
44
+
45
+ const MIN_TOKEN_LENGTH = 32;
46
+ // The token is also a path segment: only characters that need no URL encoding.
47
+ const TOKEN_CHARS = /^[A-Za-z0-9._~-]+$/;
48
+
49
+ class TokenError extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = 'TokenError';
53
+ }
54
+ }
55
+
56
+ // Never echoes the token.
57
+ function validateToken(token) {
58
+ if (typeof token !== 'string' || token.length === 0) throw new TokenError('the token is empty');
59
+ if (token.length < MIN_TOKEN_LENGTH) throw new TokenError(`the token is too short: ${token.length} chars, at least ${MIN_TOKEN_LENGTH} required`);
60
+ if (!TOKEN_CHARS.test(token)) throw new TokenError('the token may contain only A-Z a-z 0-9 . _ ~ - (it is also a URL path segment)');
61
+ return token;
62
+ }
63
+
64
+ // Constant time for any lengths: SHA-256 digests are compared (equal-length
65
+ // buffers).
66
+ function sameSecret(given, token) {
67
+ const a = crypto.createHash('sha256').update(String(given)).digest();
68
+ const b = crypto.createHash('sha256').update(token).digest();
69
+ return crypto.timingSafeEqual(a, b);
70
+ }
71
+
72
+ const PRIVATE_PREFIX = '/private_';
73
+ const MCP_SUFFIX = '/mcp';
74
+
75
+ // 'ok' | 'not_found' | 'unauthorized'
76
+ function authorize(req, token) {
77
+ let pathname;
78
+ try {
79
+ pathname = new URL(req.url || '/', 'http://localhost').pathname;
80
+ } catch {
81
+ return 'not_found';
82
+ }
83
+ if (pathname.startsWith('/.well-known/')) return 'not_found';
84
+ if (pathname.startsWith(PRIVATE_PREFIX) && pathname.endsWith(MCP_SUFFIX)) {
85
+ const candidate = pathname.slice(PRIVATE_PREFIX.length, -MCP_SUFFIX.length);
86
+ return sameSecret(candidate, token) ? 'ok' : 'not_found';
87
+ }
88
+ if (pathname === MCP_SUFFIX) {
89
+ const header = req.headers.authorization;
90
+ if (header === undefined) return 'not_found';
91
+ const m = /^Bearer[ \t]+(\S+)[ \t]*$/i.exec(header);
92
+ return m && sameSecret(m[1], token) ? 'ok' : 'unauthorized';
93
+ }
94
+ return 'not_found';
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Host / Origin on a localhost bind
99
+ // ---------------------------------------------------------------------------
100
+ // null = allowed, otherwise the message for the 403. A missing Origin passes:
101
+ // non-browser clients do not send one. `allowed` (allowed_hosts, normalized by
102
+ // allowedHostnames) is accepted like localhost: the public name a tunnel or a
103
+ // proxy on this machine passes on.
104
+
105
+ // allowed_hosts as the URL parser writes host names: lower case, IPv6 in its
106
+ // short form.
107
+ function allowedHostnames(list = []) {
108
+ return list.map(h => new URL(`http://${h}`).hostname);
109
+ }
110
+
111
+ function hostRefusal(header, allowed = []) {
112
+ if (!header) return 'Missing Host header';
113
+ let hostname;
114
+ try { hostname = new URL(`http://${header}`).hostname; }
115
+ catch { return `Invalid Host header: ${header}`; }
116
+ return LOCAL_HOSTNAMES.includes(hostname) || allowed.includes(hostname) ? null : `Invalid Host: ${hostname}`;
117
+ }
118
+
119
+ function originRefusal(header, allowed = []) {
120
+ if (header === undefined || header === null || header === '') return null;
121
+ let hostname;
122
+ try { hostname = new URL(header).hostname; }
123
+ catch { return `Invalid Origin header: ${header}`; }
124
+ if (hostname === '') return `Invalid Origin header: ${header}`;
125
+ return LOCAL_HOSTNAMES.includes(hostname) || allowed.includes(hostname) ? null : `Invalid Origin: ${hostname}`;
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Request log (log_requests)
130
+ // ---------------------------------------------------------------------------
131
+
132
+ // A token in a path (this one or any other) is masked before it is logged.
133
+ function maskPath(url) {
134
+ return url.replace(/\/private_[^/?]+/g, '/private_***').slice(0, 120);
135
+ }
136
+
137
+ function clientIp(req) {
138
+ return req.headers['cf-connecting-ip']
139
+ || (req.headers['x-forwarded-for'] || '').split(',')[0].trim()
140
+ || req.socket.remoteAddress
141
+ || '-';
142
+ }
143
+
144
+ function requestLine(req, status, bytes, note) {
145
+ const ua = req.headers['user-agent'] || '-';
146
+ const pv = req.headers['mcp-protocol-version'];
147
+ return `[req] ${new Date().toISOString()} ${clientIp(req)} ${req.method} ${maskPath(req.url)} -> ${status} ${bytes}B pv=${pv === undefined ? '-' : pv.slice(0, 40)} ua="${ua}"${note ? ' ' + note : ''}`;
148
+ }
149
+
150
+ // Counts the body bytes written to res.
151
+ function countBytes(res) {
152
+ let n = 0;
153
+ const count = chunk => { if (chunk && typeof chunk !== 'function') n += Buffer.byteLength(chunk); };
154
+ const write = res.write, end = res.end;
155
+ res.write = function (chunk, ...rest) { count(chunk); return write.call(this, chunk, ...rest); };
156
+ res.end = function (chunk, ...rest) { count(chunk); return end.call(this, chunk, ...rest); };
157
+ return () => n;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Streamable HTTP
162
+ // ---------------------------------------------------------------------------
163
+
164
+ // MCP-Protocol-Version header check. Returns null when the request may
165
+ // proceed, or the JSON-RPC error body for a 400. No header passes; initialize
166
+ // (alone or inside a batch) is never checked, its version is not agreed yet.
167
+ function protocolHeaderError(rawHeaders, body) {
168
+ const items = Array.isArray(body) ? body : [body];
169
+ if (items.some(r => r && typeof r === 'object' && r.method === 'initialize')) return null;
170
+ const values = [];
171
+ for (let i = 0; i + 1 < rawHeaders.length; i += 2) {
172
+ if (String(rawHeaders[i]).toLowerCase() === 'mcp-protocol-version') values.push(String(rawHeaders[i + 1]));
173
+ }
174
+ if (!values.length) return null;
175
+ if (values.length === 1 && S.SUPPORTED_PROTOCOL_VERSIONS.includes(values[0])) return null;
176
+ return { jsonrpc: '2.0', id: null, error: { code: -32600,
177
+ message: `Unsupported MCP-Protocol-Version: ${values.join(', ').slice(0, 40)}. Supported: ${S.SUPPORTED_PROTOCOL_VERSIONS.join(', ')}` } };
178
+ }
179
+
180
+ // Accept is split on commas, parameters (;q=...) dropped, case ignored.
181
+ // An empty or missing header is not accepted.
182
+ const ACCEPTED_MEDIA = new Set(['application/json', 'text/event-stream', 'application/*', '*/*']);
183
+
184
+ function acceptsMcp(header) {
185
+ return String(header || '').split(',')
186
+ .map(part => part.split(';')[0].trim().toLowerCase())
187
+ .some(type => ACCEPTED_MEDIA.has(type));
188
+ }
189
+
190
+ // /mcp, past the auth front. onTooLarge runs before a 413 is sent.
191
+ async function transport(req, res, { onTooLarge }) {
192
+ res.setHeader('Access-Control-Allow-Origin', '*');
193
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE');
194
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, mcp-session-id, mcp-protocol-version');
195
+
196
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
197
+
198
+ // The server sends no notifications, so the GET SSE channel is declined with
199
+ // 405 (allowed by the Streamable HTTP transport).
200
+ if (req.method !== 'POST') { res.writeHead(405, { 'Allow': 'POST, OPTIONS' }); res.end(); return; }
201
+
202
+ if (!acceptsMcp(req.headers['accept'])) {
203
+ res.writeHead(406);
204
+ res.end(JSON.stringify({ error: 'Not Acceptable: Client must accept application/json or text/event-stream' }));
205
+ return;
206
+ }
207
+
208
+ const r = await B.readBody(req, { limit: MAX_BODY_BYTES });
209
+ if (r.aborted) return;
210
+ if (!r.ok) {
211
+ onTooLarge();
212
+ B.sendTooLarge(req, res, 413, { 'Content-Type': 'application/json' }, JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: `Request body too large (limit ${MAX_BODY_BYTES} bytes).` } }), r.destroy);
213
+ return;
214
+ }
215
+ await answer(req, res, r.body);
216
+ }
217
+
218
+ // An unexpected exception answers 500; the process keeps serving.
219
+ function internalError(res, e) {
220
+ process.stderr.write(`request failed: ${e && e.stack || e}\n`);
221
+ if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'application/json' });
222
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Internal error' } }));
223
+ }
224
+
225
+ async function answer(req, res, raw) {
226
+ let body;
227
+ try { body = JSON.parse(raw.toString('utf8')); }
228
+ catch { res.writeHead(400); res.end('Bad JSON'); return; }
229
+
230
+ const versionError = protocolHeaderError(req.rawHeaders, body);
231
+ if (versionError) {
232
+ res.writeHead(400, { 'Content-Type': 'application/json' });
233
+ res.end(JSON.stringify(versionError));
234
+ return;
235
+ }
236
+
237
+ const requests = Array.isArray(body) ? body : [body];
238
+ const responses = [];
239
+ for (const r of requests) {
240
+ const resp = await S.handleMcpRequest(r);
241
+ if (resp !== null) responses.push(resp);
242
+ }
243
+
244
+ const result = Array.isArray(body) ? responses : (responses[0] || null);
245
+ if (result === null) { res.writeHead(202); res.end(); return; }
246
+
247
+ // Plain JSON, not SSE: the transport allows either, and JSON is not
248
+ // affected by SSE buffering in tunnels.
249
+ res.writeHead(200, { 'Content-Type': 'application/json' });
250
+ res.end(JSON.stringify(result));
251
+ }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // Listener
255
+ // ---------------------------------------------------------------------------
256
+
257
+ function bare(res, status) {
258
+ res.writeHead(status, { 'content-length': '0', 'cache-control': 'no-store' });
259
+ res.end();
260
+ }
261
+
262
+ function forbidden(res, message) {
263
+ res.writeHead(403, { 'Content-Type': 'application/json' });
264
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message }, id: null }));
265
+ }
266
+
267
+ /**
268
+ * The request listener: auth front → (localhost bind only) Host/Origin checks
269
+ * → /mcp. `log` receives lines without tokens. `legacyToken` skips the token
270
+ * rules (a ha-adb-mcp 1.x token kept inside Home Assistant, see token.js).
271
+ */
272
+ function createHttpHandler({ token, host = DEFAULT_HOST, allowedHosts = [], logRequests = false, legacyToken = false, log = m => process.stderr.write(m + '\n') }) {
273
+ if (!legacyToken) validateToken(token);
274
+ const localGuards = isLocalBind(host);
275
+ const allowed = allowedHostnames(allowedHosts);
276
+
277
+ const listener = (req, res) => {
278
+ let note = '';
279
+ if (logRequests) {
280
+ const bytes = countBytes(res);
281
+ res.on('finish', () => log(requestLine(req, res.statusCode, bytes(), note)));
282
+ }
283
+
284
+ const verdict = authorize(req, token);
285
+ if (verdict === 'not_found') { note = '(not found)'; return bare(res, 404); }
286
+ if (verdict === 'unauthorized') {
287
+ note = '(unauthorized)';
288
+ log(`brickproof-adb: http ${req.method} 401 (wrong bearer token)`);
289
+ return bare(res, 401);
290
+ }
291
+ if (localGuards) {
292
+ const h = hostRefusal(req.headers.host, allowed);
293
+ if (h) { note = '(Host not local)'; log(`brickproof-adb: http ${req.method} 403 (Host not local)`); return forbidden(res, h); }
294
+ const o = originRefusal(req.headers.origin, allowed);
295
+ if (o) { note = '(Origin not local)'; log(`brickproof-adb: http ${req.method} 403 (Origin not local)`); return forbidden(res, o); }
296
+ }
297
+ transport(req, res, {
298
+ onTooLarge: () => { note = '(too large)'; log(`brickproof-adb: http ${req.method} 413 (body too large)`); },
299
+ }).catch(e => internalError(res, e));
300
+ };
301
+ listener.localGuards = localGuards;
302
+ return listener;
303
+ }
304
+
305
+ function bindNote(localGuards) {
306
+ return localGuards ? '' : ' — non-local bind: no Host/Origin checks, the token alone protects the server';
307
+ }
308
+
309
+ function startHttp({ port, host = DEFAULT_HOST, token, allowedHosts = [], logRequests = false, legacyToken = false, log }) {
310
+ const listener = createHttpHandler({ token, host, allowedHosts, logRequests, legacyToken, log });
311
+ const server = http.createServer(listener);
312
+ return new Promise((resolve, reject) => {
313
+ server.once('error', reject);
314
+ server.listen(port, host, () => {
315
+ server.off('error', reject);
316
+ resolve({ server, localGuards: listener.localGuards });
317
+ });
318
+ });
319
+ }
320
+
321
+ module.exports = {
322
+ DEFAULT_HOST, MIN_TOKEN_LENGTH, MAX_BODY_BYTES, TokenError,
323
+ isLocalBind, validateToken, sameSecret, authorize, allowedHostnames, hostRefusal, originRefusal,
324
+ maskPath, protocolHeaderError, acceptsMcp,
325
+ createHttpHandler, startHttp, bindNote,
326
+ };
package/src/image.js ADDED
@@ -0,0 +1,209 @@
1
+ 'use strict';
2
+ /**
3
+ * image.js — the screenshot image pipeline, pure JavaScript.
4
+ *
5
+ * processFrame() reads a PNG file in a worker thread: decode (pngjs), fit into
6
+ * px × px without enlarging (area average), brightness statistics of the
7
+ * downscaled frame, JPEG (jpeg-js). A new worker per frame, ended after it, so
8
+ * the decoded frame (about 33 MB for 4K) goes back to the system; no pool, no
9
+ * long-lived worker.
10
+ *
11
+ * ⚠ The PNG never passes through the main thread: adb writes it into a file,
12
+ * only the worker reads it. Buffering screenshots in the main thread is what
13
+ * leaked memory frame after frame.
14
+ *
15
+ * Statistics follow ImageMagick's %[fx:mean] and %[fx:standard_deviation]
16
+ * without a channel qualifier: the composite of the R, G and B channels is the
17
+ * arithmetic mean of the per-channel means and of the per-channel sample
18
+ * standard deviations (denominator n-1), scaled to 0..1. It is not the
19
+ * deviation of all samples pooled. Computed on the downscaled pixels before
20
+ * JPEG encoding.
21
+ *
22
+ * `check` and the tests run processFrame() itself, never a copy of it.
23
+ */
24
+
25
+ const fs = require('fs');
26
+ const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
27
+ const { PNG } = require('pngjs');
28
+ const jpeg = require('jpeg-js');
29
+
30
+ // "Almost uniformly dark": both below.
31
+ const DARK_MEAN_THRESHOLD = 0.03;
32
+ const DARK_SD_THRESHOLD = 0.01;
33
+
34
+ const IMAGE_TIMEOUT_MS = 30000;
35
+
36
+ /** Fit W×H into px×px keeping the aspect ratio; never enlarges. */
37
+ function fitSize(W, H, px) {
38
+ if (W <= px && H <= px) return { w: W, h: H };
39
+ const s = Math.min(px / W, px / H);
40
+ return { w: Math.max(1, Math.round(W * s)), h: Math.max(1, Math.round(H * s)) };
41
+ }
42
+
43
+ // For each destination index: the source indices it covers and their share.
44
+ function areaTaps(src, dst) {
45
+ const scale = src / dst;
46
+ const start = new Int32Array(dst);
47
+ const count = new Int32Array(dst);
48
+ const weights = [];
49
+ for (let i = 0; i < dst; i++) {
50
+ const a = i * scale, b = (i + 1) * scale;
51
+ const lo = Math.floor(a), hi = Math.min(src, Math.ceil(b));
52
+ start[i] = lo;
53
+ count[i] = hi - lo;
54
+ for (let s = lo; s < hi; s++) weights.push((Math.min(b, s + 1) - Math.max(a, s)) / scale);
55
+ }
56
+ return { start, count, weights: Float64Array.from(weights) };
57
+ }
58
+
59
+ /**
60
+ * Area-average downscale of RGBA to w×h RGBA (alpha 255). Separable: each
61
+ * output pixel is the coverage-weighted mean of the source pixels under it.
62
+ */
63
+ function resizeArea(rgba, W, H, w, h) {
64
+ const out = new Uint8Array(w * h * 4);
65
+ if (w === W && h === H) {
66
+ for (let i = 0; i < W * H; i++) {
67
+ out[i * 4] = rgba[i * 4]; out[i * 4 + 1] = rgba[i * 4 + 1]; out[i * 4 + 2] = rgba[i * 4 + 2]; out[i * 4 + 3] = 255;
68
+ }
69
+ return out;
70
+ }
71
+ const hx = areaTaps(W, w);
72
+ const vy = areaTaps(H, h);
73
+ // Horizontal pass: H rows of w RGB floats.
74
+ const tmp = new Float32Array(w * H * 3);
75
+ for (let y = 0; y < H; y++) {
76
+ const row = y * W * 4;
77
+ let wi = 0;
78
+ for (let x = 0; x < w; x++) {
79
+ let r = 0, g = 0, b = 0;
80
+ const s0 = hx.start[x], n = hx.count[x];
81
+ for (let k = 0; k < n; k++) {
82
+ const p = row + (s0 + k) * 4;
83
+ const wt = hx.weights[wi++];
84
+ r += rgba[p] * wt; g += rgba[p + 1] * wt; b += rgba[p + 2] * wt;
85
+ }
86
+ const o = (y * w + x) * 3;
87
+ tmp[o] = r; tmp[o + 1] = g; tmp[o + 2] = b;
88
+ }
89
+ }
90
+ // Vertical pass.
91
+ let wi = 0;
92
+ for (let y = 0; y < h; y++) {
93
+ const s0 = vy.start[y], n = vy.count[y];
94
+ const wts = vy.weights.subarray(wi, wi + n);
95
+ wi += n;
96
+ for (let x = 0; x < w; x++) {
97
+ let r = 0, g = 0, b = 0;
98
+ for (let k = 0; k < n; k++) {
99
+ const p = ((s0 + k) * w + x) * 3;
100
+ r += tmp[p] * wts[k]; g += tmp[p + 1] * wts[k]; b += tmp[p + 2] * wts[k];
101
+ }
102
+ const o = (y * w + x) * 4;
103
+ out[o] = Math.min(255, Math.round(r));
104
+ out[o + 1] = Math.min(255, Math.round(g));
105
+ out[o + 2] = Math.min(255, Math.round(b));
106
+ out[o + 3] = 255;
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * Composite brightness statistics of an RGBA buffer, 0..1: the mean of the
114
+ * R, G, B means and the mean of the R, G, B sample standard deviations.
115
+ */
116
+ function frameStats(rgba, w, h) {
117
+ const n = w * h;
118
+ const sum = [0, 0, 0], sq = [0, 0, 0];
119
+ for (let i = 0; i < n; i++) {
120
+ const p = i * 4;
121
+ for (let c = 0; c < 3; c++) {
122
+ const v = rgba[p + c];
123
+ sum[c] += v;
124
+ sq[c] += v * v;
125
+ }
126
+ }
127
+ let mean = 0, sd = 0;
128
+ for (let c = 0; c < 3; c++) {
129
+ const m = sum[c] / n;
130
+ const variance = n > 1 ? Math.max(0, (sq[c] - sum[c] * m) / (n - 1)) : 0;
131
+ mean += m;
132
+ sd += Math.sqrt(variance);
133
+ }
134
+ return { mean: mean / 3 / 255, sd: sd / 3 / 255 };
135
+ }
136
+
137
+ function isDark(mean, sd) {
138
+ return mean < DARK_MEAN_THRESHOLD && sd < DARK_SD_THRESHOLD;
139
+ }
140
+
141
+ /**
142
+ * The whole pipeline on PNG bytes, synchronously (the worker's job; tests call
143
+ * it directly). Returns { jpeg, W, H, w, h, mean, sd }.
144
+ */
145
+ function processPngBuffer(buf, px, quality) {
146
+ const png = PNG.sync.read(buf);
147
+ const W = png.width, H = png.height;
148
+ const { w, h } = fitSize(W, H, px);
149
+ const small = resizeArea(png.data, W, H, w, h);
150
+ const { mean, sd } = frameStats(small, w, h);
151
+ const encoded = jpeg.encode({ data: small, width: w, height: h }, quality).data;
152
+ return { jpeg: Buffer.from(encoded), W, H, w, h, mean, sd };
153
+ }
154
+
155
+ /**
156
+ * Run the pipeline on a PNG file in a fresh worker. Resolves { jpeg (Buffer),
157
+ * W, H, w, h, mean, sd }; rejects on a decode error, a worker failure or the
158
+ * timeout (the worker is terminated).
159
+ */
160
+ function processFrame(pngPath, px, quality, { timeoutMs = IMAGE_TIMEOUT_MS } = {}) {
161
+ return new Promise((resolve, reject) => {
162
+ const worker = new Worker(__filename, { workerData: { brickproofImage: true, pngPath, px, quality } });
163
+ let done = false;
164
+ const finish = (err, value) => {
165
+ if (done) return;
166
+ done = true;
167
+ clearTimeout(timer);
168
+ if (err) reject(err); else resolve(value);
169
+ };
170
+ const timer = setTimeout(() => {
171
+ finish(new Error(`image conversion timed out after ${timeoutMs / 1000} s`));
172
+ worker.terminate();
173
+ }, timeoutMs);
174
+ worker.once('message', m => {
175
+ if (m && m.ok) finish(null, { ...m.result, jpeg: Buffer.from(m.result.jpeg) });
176
+ else finish(new Error((m && m.error) || 'image worker returned nothing'));
177
+ });
178
+ worker.once('error', e => finish(e));
179
+ worker.once('exit', code => finish(new Error(`image worker exited with code ${code} before answering`)));
180
+ });
181
+ }
182
+
183
+ /** A PNG of the given size, pixels from fill(x, y) -> [r, g, b]. For check and fixtures. */
184
+ function makePng(width, height, fill) {
185
+ const png = new PNG({ width, height });
186
+ for (let y = 0; y < height; y++) {
187
+ for (let x = 0; x < width; x++) {
188
+ const [r, g, b] = fill(x, y);
189
+ const p = (y * width + x) * 4;
190
+ png.data[p] = r; png.data[p + 1] = g; png.data[p + 2] = b; png.data[p + 3] = 255;
191
+ }
192
+ }
193
+ return PNG.sync.write(png);
194
+ }
195
+
196
+ if (!isMainThread && workerData && workerData.brickproofImage) {
197
+ try {
198
+ const buf = fs.readFileSync(workerData.pngPath);
199
+ const result = processPngBuffer(buf, workerData.px, workerData.quality);
200
+ parentPort.postMessage({ ok: true, result });
201
+ } catch (e) {
202
+ parentPort.postMessage({ ok: false, error: e && e.message ? e.message : String(e) });
203
+ }
204
+ }
205
+
206
+ module.exports = {
207
+ DARK_MEAN_THRESHOLD, DARK_SD_THRESHOLD, IMAGE_TIMEOUT_MS,
208
+ fitSize, resizeArea, frameStats, isDark, processPngBuffer, processFrame, makePng,
209
+ };
package/src/main.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // The program: the npm bin and the entry point of the Claude Desktop
4
+ // extension. It runs the CLI whatever loaded it: a launcher that loads the
5
+ // entry through its own wrapper leaves require.main pointing elsewhere.
6
+
7
+ require('./cli.js').run(process.argv.slice(2));