howtocode 0.7.75 → 0.7.76
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/README.md +1 -1
- package/dist/assets/background.js.txt +92 -6
- package/dist/assets/manifest.json.txt +2 -1
- package/dist/assets/options.html.txt +2 -2
- package/dist/{chunk-QAXXSULF.js → chunk-42J3SVVD.js} +1 -1
- package/dist/{chunk-YB5UNXVA.js → chunk-6MW4XQH2.js} +1 -1
- package/dist/{chunk-L73LU5W5.js → chunk-AMYTGLTF.js} +1 -1
- package/dist/chunk-DBPJZUIT.js +17 -0
- package/dist/{chunk-QNBA2A2M.js → chunk-DQZCH2E4.js} +1 -1
- package/dist/{chunk-GLOEJWUF.js → chunk-EMFKTIYL.js} +1 -1
- package/dist/chunk-G3RLGCT7.js +187 -0
- package/dist/chunk-KBZERZVM.js +2 -0
- package/dist/{chunk-E2JC7MLI.js → chunk-MSEVYMAA.js} +1 -1
- package/dist/{chunk-VWHAFIOV.js → chunk-NARUJ2JE.js} +1 -1
- package/dist/{chunk-NLV4AD4X.js → chunk-SBWZZCV5.js} +1 -1
- package/dist/{chunk-YW4RNAH5.js → chunk-WXNRNAQ6.js} +32 -30
- package/dist/{chunk-Q57F6VH7.js → chunk-XORAIQWU.js} +1 -1
- package/dist/{chunk-IM52NDS4.js → chunk-XZBFNLPM.js} +1 -1
- package/dist/cli-auth.js +1 -1
- package/dist/main-app.js +6 -6
- package/package.json +1 -1
- package/dist/chunk-AMHJO4G3.js +0 -201
package/README.md
CHANGED
|
@@ -154,7 +154,7 @@ nothing to remember.
|
|
|
154
154
|
- **Tools** — `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, plus `think` (private scratchpad), `ask` (multiple-choice question to the user), and `task` (background agents).
|
|
155
155
|
- **Web search and fetch** — `web_search` and `web_fetch` read public http(s) URLs; local, loopback, and RFC1918 addresses are refused before any request is made. Search defaults to DuckDuckGo, with an optional `BRAVE_API_KEY` upgrade.
|
|
156
156
|
- **Language server queries** — the read-only `lsp` tool asks a language server for definition, references, hover, symbols, or diagnostics. It needs the matching server on PATH (`typescript-language-server` for this repo); a missing binary comes back as a tool result that says so.
|
|
157
|
-
- **Browser relay** — the `browser` tool drives the Chrome tabs you already have open, so signed-in sessions are reused instead of logging in again in a headless browser. Run `/browser-relay install` once, load the unpacked extension from `~/.howtocode/agent/browser-relay/extension` in `chrome://extensions`,
|
|
157
|
+
- **Browser relay** — the `browser` tool drives the Chrome tabs you already have open, so signed-in sessions are reused instead of logging in again in a headless browser. Run `/browser-relay install` once, load the unpacked extension from `~/.howtocode/agent/browser-relay/extension` in `chrome://extensions`, and restart Chrome so it picks up the native messaging host. The extension prefers Chrome native messaging (`id.howtofix.howtocode`) and falls back to the loopback WebSocket (`127.0.0.1:9224`) when the host is not registered. The token is never printed. `/browser-relay status` reports the connection. The relay binds `127.0.0.1` only and requires that token; set `HOWTOCODE_BROWSER_RELAY_PORT` if the default port is taken. Actions: `status`, `tabs`, `open`, `activate`, `navigate`, `evaluate`, `screenshot`, `close`. The tier is `exec` — in `suggest` mode each call asks first. The extension ships under the MIT license; its license text is installed alongside the files.
|
|
158
158
|
- **Discord Rich Presence** — shows the running session on your Discord profile: `HowToCode`, the model, and the project folder. It works with the bundled HowToCode application id; set `HOWTOCODE_DISCORD_CLIENT_ID=<id>` or `"discordClientId": "<id>"` in `~/.howtocode/agent/settings.json` to use your own Discord app, and `HOWTOCODE_DISCORD_DISABLE=1` to turn it off. Discord already shows the application icon, so set that icon to the howtofix.id logo; for a dedicated Rich Presence image, upload an asset under Rich Presence → Art Assets and set `HOWTOCODE_DISCORD_LARGE_IMAGE=<asset-key>`. The IPC client is dependency-free and picks the right socket on Windows (`\\?\\pipe\\discord-ipc-N`), Linux and macOS (`$XDG_RUNTIME_DIR` or `/tmp`); a missing Discord client is a silent no-op.
|
|
159
159
|
- **Hooks** — `hooks.json` in the config root attaches shell commands to seven lifecycle points (`PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `SessionStart`, `Stop`, `PreCompact`, `SessionEnd`). A hook reads a JSON payload on stdin and decides with its exit code: `0` allows, `2` blocks with its stderr as the reason. A `PreToolUse` hook can also **rewrite** a call's arguments with `updatedInput` — validated against the tool's own schema, so a hook cannot make the agent run something it never asked for. A `PreToolUse` hook outranks the approval mode, so it holds under `full-auto` too. `async` and `once` are supported. See `docs/hooks.md`.
|
|
160
160
|
- **Sessions** — stored as JSONL under `~/.howtocode/agent/sessions/<project>/`. `-c` continues the latest; `/resume` picks any of them. On startup, transcripts idle for more than 30 days are swept across every project — the session just opened is kept whatever its age — so the store does not grow for the life of the machine (the same window rewind's snapshots use).
|
|
@@ -138,8 +138,13 @@ var RECONNECT_MIN_MS = 1000;
|
|
|
138
138
|
var RECONNECT_MAX_MS = 1e4;
|
|
139
139
|
var REMOVE_TAB_ATTEMPTS = 3;
|
|
140
140
|
var REMOVE_TAB_RETRY_MS = 500;
|
|
141
|
+
var NATIVE_HOST = "id.howtofix.howtocode";
|
|
141
142
|
var ws = null;
|
|
143
|
+
var nativePort = null;
|
|
144
|
+
var nativeChunks = new Map;
|
|
145
|
+
var nativeAttempts = 0;
|
|
142
146
|
var reconnectDelay = RECONNECT_MIN_MS;
|
|
147
|
+
var reconnectTimer = null;
|
|
143
148
|
var pingTimer = null;
|
|
144
149
|
var relayInitiatedDetachTabs = new Set;
|
|
145
150
|
var instanceId = null;
|
|
@@ -248,6 +253,12 @@ async function restoreGroups() {
|
|
|
248
253
|
}
|
|
249
254
|
}
|
|
250
255
|
function post(msg) {
|
|
256
|
+
if (nativePort) {
|
|
257
|
+
try {
|
|
258
|
+
nativePort.postMessage(msg);
|
|
259
|
+
return;
|
|
260
|
+
} catch {}
|
|
261
|
+
}
|
|
251
262
|
if (ws?.readyState === WebSocket.OPEN)
|
|
252
263
|
ws.send(JSON.stringify(msg));
|
|
253
264
|
}
|
|
@@ -359,6 +370,20 @@ function handleRelayMessage(socket, raw) {
|
|
|
359
370
|
}
|
|
360
371
|
if (msg.t === "pong")
|
|
361
372
|
return;
|
|
373
|
+
if (msg.t === "linked") {
|
|
374
|
+
reconnectDelay = RECONNECT_MIN_MS;
|
|
375
|
+
nativeAttempts = 0;
|
|
376
|
+
setBadge(true);
|
|
377
|
+
buildHello().then((hello) => post(hello));
|
|
378
|
+
clearInterval(pingTimer ?? undefined);
|
|
379
|
+
pingTimer = setInterval(() => post({ t: "ping" }), PING_INTERVAL_MS);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (msg.t === "unlinked") {
|
|
383
|
+
setBadge(false);
|
|
384
|
+
restoreGroups();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
362
387
|
if (msg.t === "reload") {
|
|
363
388
|
chrome.runtime.reload();
|
|
364
389
|
return;
|
|
@@ -371,12 +396,69 @@ function handleRelayMessage(socket, raw) {
|
|
|
371
396
|
answer({ t: "rpcResult", id: msg.id, ok: false, error: err instanceof Error ? err.message : String(err) });
|
|
372
397
|
});
|
|
373
398
|
}
|
|
399
|
+
function clearTransport() {
|
|
400
|
+
clearTimeout(reconnectTimer ?? undefined);
|
|
401
|
+
clearInterval(pingTimer ?? undefined);
|
|
402
|
+
pingTimer = null;
|
|
403
|
+
nativeChunks.clear();
|
|
404
|
+
}
|
|
374
405
|
function scheduleReconnect() {
|
|
406
|
+
clearTransport();
|
|
375
407
|
const delay = reconnectDelay;
|
|
376
408
|
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
|
|
377
|
-
setTimeout(() => void connect(), delay);
|
|
409
|
+
reconnectTimer = setTimeout(() => void connect(), delay);
|
|
378
410
|
}
|
|
379
|
-
|
|
411
|
+
function nativeSocket() {
|
|
412
|
+
return {
|
|
413
|
+
readyState: 1,
|
|
414
|
+
send: (raw) => {
|
|
415
|
+
try {
|
|
416
|
+
post(JSON.parse(raw));
|
|
417
|
+
} catch {}
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
function connectNative() {
|
|
422
|
+
if (nativePort)
|
|
423
|
+
return true;
|
|
424
|
+
try {
|
|
425
|
+
const port = chrome.runtime.connectNative(NATIVE_HOST);
|
|
426
|
+
nativePort = port;
|
|
427
|
+
port.onMessage.addListener((message) => {
|
|
428
|
+
if (!message || typeof message !== "object")
|
|
429
|
+
return;
|
|
430
|
+
if (message.t === "chunk") {
|
|
431
|
+
const bucket = nativeChunks.get(message.id) ?? [];
|
|
432
|
+
bucket[message.index] = message.data;
|
|
433
|
+
nativeChunks.set(message.id, bucket);
|
|
434
|
+
if (!message.last)
|
|
435
|
+
return;
|
|
436
|
+
nativeChunks.delete(message.id);
|
|
437
|
+
handleRelayMessage(nativeSocket(), bucket.join(""));
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
handleRelayMessage(nativeSocket(), JSON.stringify(message));
|
|
441
|
+
});
|
|
442
|
+
port.onDisconnect.addListener(() => {
|
|
443
|
+
nativePort = null;
|
|
444
|
+
clearTransport();
|
|
445
|
+
setBadge(false);
|
|
446
|
+
restoreGroups();
|
|
447
|
+
nativeAttempts += 1;
|
|
448
|
+
if (nativeAttempts <= 3) {
|
|
449
|
+
reconnectTimer = setTimeout(() => void connect(), reconnectDelay);
|
|
450
|
+
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
|
|
451
|
+
} else {
|
|
452
|
+
void connectWs();
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
return true;
|
|
456
|
+
} catch {
|
|
457
|
+
nativeAttempts += 1;
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async function connectWs() {
|
|
380
462
|
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING))
|
|
381
463
|
return;
|
|
382
464
|
const settings = await loadSettings();
|
|
@@ -398,10 +480,7 @@ async function connect() {
|
|
|
398
480
|
if (ws !== socket)
|
|
399
481
|
return;
|
|
400
482
|
ws = null;
|
|
401
|
-
|
|
402
|
-
clearInterval(pingTimer);
|
|
403
|
-
pingTimer = null;
|
|
404
|
-
}
|
|
483
|
+
clearTransport();
|
|
405
484
|
setBadge(false);
|
|
406
485
|
restoreGroups();
|
|
407
486
|
scheduleReconnect();
|
|
@@ -410,6 +489,13 @@ async function connect() {
|
|
|
410
489
|
socket.close();
|
|
411
490
|
};
|
|
412
491
|
}
|
|
492
|
+
async function connect() {
|
|
493
|
+
if (nativePort || ws)
|
|
494
|
+
return;
|
|
495
|
+
if (chrome.runtime.connectNative && nativeAttempts < 3 && connectNative())
|
|
496
|
+
return;
|
|
497
|
+
await connectWs();
|
|
498
|
+
}
|
|
413
499
|
var downloads = new DownloadPairing;
|
|
414
500
|
chrome.downloads.onCreated.addListener((item) => downloads.created(item.id, item.finalUrl));
|
|
415
501
|
chrome.downloads.onChanged.addListener((delta) => {
|
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
"name": "OMP Browser Relay",
|
|
4
4
|
"version": "0.1.0",
|
|
5
5
|
"description": "Lets the omp coding agent drive your existing tabs through a local CDP relay.",
|
|
6
|
+
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqdTRDfm5+iPc+vFz00bc6BPmcS8HS/oit+ZeCgTZc1EmKvl7k09pzXiFwOA5vHUSubnxjfxhLxt6nhhZYh/wHCNeAjpZzt0AE7aclN1aaxCVuzYJNOL9RRMbcA8l4stC4kqhjdHdOW6Uqu7ErA1MO0XsAI5ELw/Tr0f8qTecO984pxFdZR3MtjrI09Gy3UKId/LsRs79ul3I0Yw5SG8gEbOF5/xoX/R3fxj2lT8bZkzBHUOiUtsz+ChwacIeFyrJpud45awbibrFmcZd7f9FhAMKjLd1izc+ZRoEolr4J1fCDCoIiSawEMTPx1n1TOY8MYBTKxFM6KVRheqQNrFUswIDAQAB",
|
|
6
7
|
"author": "Stencil Labs, Inc.",
|
|
7
8
|
"homepage_url": "https://omp.sh",
|
|
8
|
-
"permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms", "scripting", "downloads"],
|
|
9
|
+
"permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms", "scripting", "downloads", "nativeMessaging"],
|
|
9
10
|
"host_permissions": ["<all_urls>"],
|
|
10
11
|
"background": {
|
|
11
12
|
"service_worker": "background.js"
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
<body>
|
|
41
41
|
<h1>OMP Browser Relay</h1>
|
|
42
42
|
<p class="hint">
|
|
43
|
-
The extension
|
|
44
|
-
|
|
43
|
+
The extension prefers Chrome native messaging and falls back to this loopback WebSocket. The port and token
|
|
44
|
+
below only apply to the fallback; they must match the relay.
|
|
45
45
|
</p>
|
|
46
46
|
<label for="port">Relay port</label>
|
|
47
47
|
<input id="port" type="number" min="1" max="65535" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-
|
|
1
|
+
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-AMYTGLTF.js";import"./chunk-DQZCH2E4.js";import"./chunk-SBWZZCV5.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-
|
|
1
|
+
import{A,B,C,D,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-XZBFNLPM.js";import"./chunk-7LA2AMZB.js";import"./chunk-DQZCH2E4.js";import"./chunk-SBWZZCV5.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{g as CATALOG_CACHE_TTL_MS,m as DEFAULT_CONTEXT_WINDOW,a as HOWTOCODE_BASE_URL,b as HOWTOCODE_CONSOLE_URL,l as HOWTOCODE_MODEL_COMPAT,c as HOWTOCODE_PROVIDERS,j as HTTP_IDLE_TIMEOUT_MS,r as UNLIMITED_SENTINEL,w as applyCatalog,x as applyCompat,B as checkAccount,s as checkCreditPools,t as checkUsage,d as configuredProviderIds,y as countNewModels,k as ensureGatewaySettings,C as fetchGatewayPrices,A as findLiveModels,q as isHowtoCodeProvider,h as loadCatalog,o as looksLikeToken,n as maskToken,v as mergeModels,e as newProviderEntry,p as parseModelIds,z as probeModel,D as readProviderKey,f as repairGatewayModels,i as repairModelFacts,u as syncGatewayModelsOnStart};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{g as T,j as R}from"./chunk-QNBA2A2M.js";import{a as P}from"./chunk-UTYFLLSM.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??T(),o=R(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return P(b(e),`${JSON.stringify(t,null,2)}
|
|
1
|
+
import{g as T,j as R}from"./chunk-DQZCH2E4.js";import{a as P}from"./chunk-UTYFLLSM.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??T(),o=R(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return P(b(e),`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384}),!0}catch{return!1}}function Ce(e){try{let t=b(e);z(t)&&xe(t,{force:!0})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Se(e,t){let r=(t?.panelUrl??_).replace(/\/+$/,""),o=t?.fetchImpl??fetch,n=t?.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let a=await o(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:L()}),signal:s.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid; run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},g=C(c.token,u.token),l=C(c.refresh_token,u.refresh_token),f=C(c.device_id,u.device_id)??e.deviceId;return!g||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:g,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:f,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(n/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function C(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ke(e,t,r){let o=r?.now??Date.now();if(Ie(t,o)||!Le(t,o))return{credential:t,renewed:!1,terminal:!1};let n=await Se(t,r);if(!n.ok||!n.credential)return n.terminal&&Ce(e),{credential:t,renewed:!1,terminal:n.terminal,message:n.message};let s=Ae(e,n.credential);return{credential:n.credential,renewed:!0,terminal:!1,message:s?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{H as a,_ as b,He as c,b as d,_e as e,Ie as f,Le as g,Ge as h,Ae as i,Ce as j,Se as k,Ke as l};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{H as L}from"./chunk-5FIFNXLT.js";import{randomBytes as ue}from"node:crypto";import{existsSync as z,mkdirSync as K,readFileSync as j,renameSync as ge,writeFileSync as pe}from"node:fs";import{dirname as Z,join as E}from"node:path";import{fileURLToPath as me}from"node:url";import{chmodSync as ne,existsSync as H,mkdirSync as W,readFileSync as oe,renameSync as se,writeFileSync as ae}from"node:fs";import{homedir as G,platform as Y}from"node:os";import{dirname as ie,join as b,resolve as de}from"node:path";import{fileURLToPath as ce}from"node:url";function U(a,s,l){let p=l?`void chrome.storage.local.get({ token: "" }).then((stored) => { if (!stored.token) return chrome.storage.local.set({ token: ${JSON.stringify(l)} }); });
|
|
2
|
+
`:"";return`const OMP_INSTALL_VERSION = ${JSON.stringify(s)};
|
|
3
|
+
${p}${a}`}function J(a,s){let l=JSON.parse(a);return`${JSON.stringify({...l,name:"HowToCode Browser Relay",description:"Lets HowToCode CLI drive your existing tabs through a local CDP relay.",homepage_url:"https://howtofix.id",version_name:s,action:{default_title:"HowToCode Browser Relay (click for settings)"}},null," ")}
|
|
4
|
+
`}function $(a){return a.replaceAll("OMP Browser Relay","HowToCode Browser Relay").replaceAll("omp-browser-relay","howtocode-browser-relay").replaceAll("omp-relay-keepalive","howtocode-relay-keepalive")}var A="id.howtofix.howtocode",V="lejogbchopjpmgjcoelnnmnbeomcodkd";function X(a,s,l){let p=`${a}.${process.pid}.tmp`;ae(p,s,l===void 0?void 0:{mode:l}),se(p,a)}function _(a){return`'${a.replaceAll("'","'\\''")}'`}function le(){if(Y()==="darwin"){let s=b(G(),"Library","Application Support");return[b(s,"Google","Chrome"),b(s,"Chromium"),b(s,"BraveSoftware","Brave-Browser"),b(s,"Microsoft Edge")]}let a=process.env.XDG_CONFIG_HOME?.trim()||b(G(),".config");return[b(a,"google-chrome"),b(a,"chromium"),b(a,"BraveSoftware","Brave-Browser"),b(a,"microsoft-edge")]}function q(a=L){let s=b(a,"browser-relay");W(s,{recursive:!0,mode:448});let l=b(s,"native-host.sh"),p=process.argv[1]?de(process.argv[1]):"",w=p&&H(p)?p:ce(new URL("../../dist/main.js",import.meta.url)),u=["#!/bin/sh",`export HOWTOCODE_CODING_AGENT_DIR=${_(a)}`,`exec ${_(process.execPath)} ${_(w)} browser-relay native-host "$@"`,""].join(`
|
|
5
|
+
`);X(l,u,493),ne(l,493);let y=[];if(Y()==="win32")return{launcher:l,manifests:y};let T=`${JSON.stringify({name:A,description:"HowToCode browser relay native host",path:l,type:"stdio",allowed_origins:[`chrome-extension://${V}/`]},null," ")}
|
|
6
|
+
`;for(let h of le()){if(!H(h))continue;let d=b(h,"NativeMessagingHosts",`${A}.json`);W(ie(d),{recursive:!0}),(H(d)?oe(d,"utf8"):null)!==T&&X(d,T),y.push(d)}return{launcher:l,manifests:y}}var fe=E(Z(me(import.meta.url)),"assets");function be(a){let s=E(a,"browser-relay");return{extensionDir:E(s,"extension"),tokenPath:E(s,"token")}}function C(a){return j(E(fe,`${a}.txt`),"utf8")}function Q(a,s,l){let p=`${a}.${process.pid}.tmp`;pe(p,s,l===void 0?void 0:{mode:l}),ge(p,a)}function Be(a,s){let{extensionDir:l,tokenPath:p}=be(a);K(l,{recursive:!0,mode:448});let w="";z(p)?w=j(p,"utf8").trim():(w=ue(24).toString("hex"),K(Z(p),{recursive:!0}),Q(p,`${w}
|
|
7
|
+
`,384));let u={"manifest.json":J(C("manifest.json"),s),"options.html":$(C("options.html")),"options.js":$(C("options.js")),LICENSE:C("LICENSE"),"background.js":$(U(C("background.js"),s,w))},y=[];for(let[h,d]of Object.entries(u)){let v=E(l,h);(z(v)?j(v,"utf8"):null)!==d&&(Q(v,d,h==="background.js"?384:void 0),y.push(h))}let T=q(a);return{extensionDir:l,tokenPath:p,token:w,wrote:y,nativeLauncher:T.launcher,nativeManifests:T.manifests}}import{createServer as he}from"node:http";import{WebSocketServer as we}from"ws";import{randomBytes as ye,timingSafeEqual as Te}from"node:crypto";var Ie=9224,Se=3e4,ve=3e4;async function Je(a){let s=a.port??Ie,l=a.token??ye(16).toString("hex"),p=a.log??(()=>{}),w=Date.now(),u=null,y=!1,T="",h="",d=[],v=1,I=new Map,S=e=>{let{promise:o,resolve:r,reject:t}=Promise.withResolvers();if(!u||u.readyState!==u.OPEN)return t(new Error("Browser relay extension is not connected. Run /browser-relay install and check the toolbar badge.")),o;let n=v++,i=setTimeout(()=>{I.delete(n),t(new Error(`Browser relay RPC timed out: ${e.op}`))},Se);return I.set(n,{resolve:r,reject:t,timer:i}),u.send(JSON.stringify({t:"rpc",id:n,...e})),o},ee=(e,o)=>{let r;try{r=JSON.parse(o)}catch{return}switch(r.t){case"hello":y=!0,T=r.browserVersion,h=r.userAgent,d=r.tabs,p(`extension connected: ${r.tabs.length} tabs`);break;case"tabCreated":d=[...d.filter(t=>t.tabId!==r.tab.tabId),r.tab];break;case"tabUpdated":d=d.map(t=>t.tabId===r.tab.tabId?r.tab:t);break;case"tabRemoved":d=d.filter(t=>t.tabId!==r.tabId);break;case"rpcResult":{let t=I.get(r.id);if(!t)return;I.delete(r.id),clearTimeout(t.timer),r.ok?t.resolve(r.result):t.reject(new Error(r.error||`Browser relay RPC failed: ${r.id}`));break}case"cdpEvent":{for(let t of N.values()){let n=!1;for(let[i,c]of t.sessions)c===r.tabId&&(g(t,{method:r.method,params:r.params,sessionId:i}),n=!0);!n&&t.tabId===r.tabId&&g(t,{method:r.method,params:r.params})}break}case"detached":{for(let t of N.values()){let n=!1;for(let[i,c]of t.sessions)c===r.tabId&&(t.sessions.delete(i),g(t,{method:"Target.detachedFromTarget",params:{targetId:`tab:${r.tabId}`,sessionId:i,reason:r.reason}}),n=!0);!n&&t.tabId===r.tabId&&g(t,{method:"Target.detachedFromTarget",params:{targetId:`tab:${r.tabId}`,reason:r.reason}})}break}case"ping":e.send(JSON.stringify({t:"pong"}));break;default:break}},N=new Map,te=1,g=(e,o)=>{e.ws.readyState===e.ws.OPEN&&e.ws.send(JSON.stringify(o))},B=e=>{let o=typeof e=="string"?e:"",r=o.startsWith("tab:")?o.slice(4):o,t=Number(r);return Number.isInteger(t)&&t>0?t:void 0},k=e=>({targetId:`tab:${e.tabId}`,type:"page",title:e.title,url:e.url,attached:!1,canAccessOpener:!1}),M=async(e,o,r)=>{await S({op:"attach",tabId:o});let n=[...e.sessions.entries()].find(([,i])=>i===o)?.[0]??`cdp-${e.nextSession++}`;if(e.sessions.set(n,o),r){let i=d.find(c=>c.tabId===o);i&&g(e,{method:"Target.attachedToTarget",params:{sessionId:n,targetInfo:k(i),waitingForDebugger:!1}})}return n},F=(e,o)=>{let r;try{r=JSON.parse(o)}catch{return}if(typeof r.id!="number"||typeof r.method!="string")return;let t=r.id,n=r.method,i=r.params??{};(async()=>{try{if(n==="Browser.getVersion"){g(e,{id:t,result:{protocolVersion:"1.3",product:T||"HowToCode Browser Relay",revision:"",userAgent:h||"HowToCode",jsVersion:""}});return}if(n==="Target.getTargets"){g(e,{id:t,result:{targetInfos:d.map(k)}});return}if(n==="Target.getBrowserContexts"){g(e,{id:t,result:{browserContextIds:[]}});return}if(n==="Target.setDiscoverTargets"){g(e,{id:t,result:{}});for(let m of d)g(e,{method:"Target.targetCreated",params:{targetInfo:k(m)}});return}if(n==="Target.setAutoAttach"){e.autoAttach={flatten:i.flatten===!0},g(e,{id:t,result:{}});for(let m of d)await M(e,m.tabId,!0);return}if(n==="Target.getTargetInfo"){let m=B(i.targetId),x=m===void 0?void 0:d.find(re=>re.tabId===m);if(!x)throw new Error("Target.getTargetInfo needs a known targetId");g(e,{id:t,result:{targetInfo:k(x)}});return}if(n==="Target.createTarget"){let m=await S({op:"createTab",url:String(i.url??"about:blank"),active:!1});if(!m?.tab)throw new Error("Chrome created no tab");g(e,{id:t,result:{targetId:`tab:${m.tab.tabId}`}}),g(e,{method:"Target.targetCreated",params:{targetInfo:k(m.tab)}}),e.autoAttach&&await M(e,m.tab.tabId,!0);return}if(n==="Target.disposeBrowserContext"){g(e,{id:t,result:{}});return}if(n==="Target.attachToTarget"){let m=B(i.targetId);if(m===void 0)throw new Error("Target.attachToTarget needs a tab targetId");let x=await M(e,m,!1);g(e,{id:t,result:{sessionId:x}});return}if(n==="Target.detachFromTarget"){let m=typeof i.sessionId=="string"?i.sessionId:"";e.sessions.delete(m),g(e,{id:t,result:{}});return}if(n==="Target.sendMessageToTarget"){if(typeof i.message!="string")throw new Error("Target.sendMessageToTarget needs a message");F(e,i.message),g(e,{id:t,result:{}});return}let c=typeof r.sessionId=="string"?r.sessionId:void 0,f=c?e.sessions.get(c):e.tabId;if(f===void 0)throw new Error("CDP command has no attached tab session");if(n==="Target.activateTarget"){await S({op:"activateTab",tabId:f}),g(e,{id:t,result:{}});return}if(n==="Target.closeTarget"){await S({op:"removeTab",tabId:f}),g(e,{id:t,result:{success:!0}});return}await S({op:"attach",tabId:f});let O=await S({op:"send",tabId:f,method:n,params:i});g(e,{id:t,result:O??{}})}catch(c){g(e,{id:t,error:{code:-32e3,message:c instanceof Error?c.message:String(c)}})}})()},R=he((e,o)=>{let t=new URL(e.url??"/",`http://127.0.0.1:${s}`).pathname.replace(/\/+$/,"")||"/";if(e.headers.host!==`127.0.0.1:${s}`){o.writeHead(403).end("Forbidden");return}if(e.method!=="GET"){o.writeHead(405).end("Method not allowed");return}if(t==="/json/version"){let n=u!==null&&u.readyState===u.OPEN,i={Browser:T||"HowToCode Browser Relay","Protocol-Version":"1.3","User-Agent":h||"HowToCode",webSocketDebuggerUrl:`ws://127.0.0.1:${s}/cdp`,...n?{}:{error:"relay extension is not connected",extensionSeen:y,uptimeMs:Date.now()-w}};o.writeHead(n?200:503,{"content-type":"application/json"}).end(JSON.stringify(i));return}if(t==="/json"||t==="/json/list"){o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(d.map(n=>({id:String(n.tabId),type:"page",title:n.title,url:n.url,webSocketDebuggerUrl:`ws://127.0.0.1:${s}/cdp?tab=${n.tabId}`}))));return}if(t==="/health"){o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({ok:!0,ready:u!==null,tabs:d.length}));return}o.writeHead(404).end("Not found")}),P=new we({noServer:!0});R.on("upgrade",(e,o,r)=>{let t=new URL(e.url??"/",`http://127.0.0.1:${s}`),n=t.pathname.replace(/\/+$/,"")||"/";if(e.headers.host!==`127.0.0.1:${s}`){o.write(`HTTP/1.1 403 Forbidden\r
|
|
8
|
+
\r
|
|
9
|
+
`),o.destroy();return}let i=e.headers.origin;if(n==="/ext"){if(i&&!i.startsWith("chrome-extension://")){o.write(`HTTP/1.1 403 Forbidden\r
|
|
10
|
+
\r
|
|
11
|
+
`),o.destroy();return}let c=Buffer.from(t.searchParams.get("token")??""),f=Buffer.from(l);if(c.length!==f.length||!Te(c,f)){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
12
|
+
\r
|
|
13
|
+
`),o.destroy();return}}else if(n==="/cdp"){if(i){o.write(`HTTP/1.1 403 Forbidden\r
|
|
14
|
+
\r
|
|
15
|
+
`),o.destroy();return}}else{o.write(`HTTP/1.1 404 Not Found\r
|
|
16
|
+
\r
|
|
17
|
+
`),o.destroy();return}P.handleUpgrade(e,o,r,c=>{if(n==="/ext")u?.close(),u=c,c.on("message",f=>ee(c,f.toString())),c.on("close",()=>{u===c&&(u=null)});else if(n==="/cdp"){let f=Number(t.searchParams.get("tab")??""),O={ws:c,tabId:Number.isInteger(f)&&f>0?f:void 0,sessions:new Map,nextSession:1},m=te++;N.set(m,O),c.on("message",x=>F(O,x.toString())),c.on("close",()=>N.delete(m))}})}),await new Promise((e,o)=>{R.once("error",o),R.listen(s,"127.0.0.1",()=>{R.off("error",o);let r=R.address();r&&typeof r=="object"&&(s=r.port),e()})});let D=setInterval(()=>{for(let e of P.clients)e.readyState===e.OPEN&&e.ping()},ve);return D.unref?.(),p(`relay listening on 127.0.0.1:${s}`),{port:s,token:l,state:()=>({extensionConnected:u!==null&&u.readyState===u.OPEN,extensionSeen:y,browserVersion:T,userAgent:h,tabs:d,uptimeMs:Date.now()-w,port:s}),rpc:S,ready:()=>u!==null&&u.readyState===u.OPEN,stop:async()=>{clearInterval(D);for(let e of I.values())clearTimeout(e.timer),e.reject(new Error("Browser relay stopped"));I.clear();for(let e of P.clients)e.terminate();await new Promise(e=>P.close(()=>e())),await new Promise(e=>R.close(()=>e()))}}}export{be as a,Be as b,Ie as c,Je as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-SBWZZCV5.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as d,sign as y}from"node:crypto";import{arch as c,cpus as m,hostname as I,platform as s}from"node:os";var a="hf-cli-1",C="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",x="howtocode-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(C,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([x,t,e,n,r].join(`
|
|
2
2
|
`),"utf8")}function h(){return d(16).toString("hex")}var E="tQ91uspGl0sw5Y8x+soLYnFNX6a9vEzSzCuuvalzdKk=";function P(){let t=g().export({format:"der",type:"spki"});return t.subarray(t.length-32).toString("base64")===E}function N(){let t=g().export({format:"der",type:"spki"});return l("sha256").update(t).digest("hex").slice(0,16)}function $(){let e=(m()[0]?.model??"").replace(/\s+/g," ").trim(),n=I(),r=e?`${n} (${s()}/${c()}, ${e})`:`${n} (${s()}/${c()})`;return`CLI (${o}, ${r})`}var k="X-HowToCode-Client";function A(){return`CLI (${o})`}function B(t,e){let n=h(),r=y(null,K(a,t,e,n),u());return{keyId:a,nonce:n,signature:r.toString("base64")}}export{a,g as b,K as c,h as d,P as e,N as f,$ as g,k as h,A as i,B as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as We,B as De,C as Ce,E as R,F as q,Fa as ot,H as U,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,
|
|
1
|
+
import{$ as We,B as De,C as Ce,E as R,F as q,Fa as ot,H as U,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,Ta as Q,U as Le,V as Be,Va as rt,W as Ue,Y as Ge,_ as Y,a as M,b as F,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as z,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as k,u as Re,ua as Qe,va as et,w as Oe,x as H,xa as tt,y as Ie,ya as nt}from"./chunk-G3RLGCT7.js";import{t as me}from"./chunk-ZJL4OEXX.js";import{b as xe}from"./chunk-XODGJSB3.js";import"./chunk-DBPJZUIT.js";import{c as ue}from"./chunk-XZBFNLPM.js";import{h as pe,l as fe}from"./chunk-AMYTGLTF.js";import"./chunk-7LA2AMZB.js";import"./chunk-DQZCH2E4.js";import{b as W,c as ie,d as ae}from"./chunk-SBWZZCV5.js";import{H as S,K as de,v as ce,w as le}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{join as Nt}from"node:path";import{hostname as co}from"node:os";import{createAgentSession as lo,createCodemodeExtension as uo,createMcpExtension as po,createToolSearchExtension as fo,DefaultResourceLoader as mo,ProjectTrustStore as go,SessionManager as K,SettingsManager as ho}from"@netrodev/hxf-coding-agent";import{existsSync as Lt,readFileSync as Bt}from"node:fs";import{join as Ut}from"node:path";var it=Ut(S,"APPEND_SYSTEM.md"),Gt=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
|
|
2
2
|
`),Wt=16*1024;function Ht(e){try{if(!Lt(e))return;let t=Bt(e,"utf8").trim();return!t||Buffer.byteLength(t,"utf8")>Wt?void 0:t}catch{return}}function at(e,t){let s=[t?e:`${e}
|
|
3
3
|
|
|
4
4
|
${Gt}`],n=Ht(it);return n&&s.push(`# Standing instructions from ${it}
|