mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
The permission window's identity card shows the requester's icon: a native app's own, a website's favicon on the tile, else the glyph. A native app leads with its verified name, its identifier under it; each verification kind has its own line (Signed by, Flatpak/Snap app, Not signed · path). On macOS the name (CFBundleDisplayName, else CFBundleName) and icon come from the bundle at the path Security.framework reports for the peer's verified static code, used only when its code-directory hash matches the grant's identity; bounded, cached, off any UI thread (local_api/mac_app.rs). A page may send its favicon as a PNG or ICO data: URL (64 KiB, 1024 px), decoded and scaled locally; anything else is ignored and nothing is ever fetched. Ask bodies grow to 96 KiB for it. Saved permissions keep the display name and icon (small PNG), allowed and blocked websites their favicon; matching ignores both, and a broken icon is dropped. Labs › Connected apps now adds a Connected apps pane to the sidebar: Connected (icon, name, who, what, how long, Revoke; an empty state), then Websites (the switch; Asking to connect with its count; Allowed and Blocked websites folded). The lab card keeps its switch and a summary that fits. The browser demo sends its favicon. Docs, feature map, labs.md, translations and labs.json follow.
239 lines
9.6 KiB
HTML
239 lines
9.6 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<meta charset="utf-8" />
|
||
<title>Hex browser connect</title>
|
||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||
<style>
|
||
:root { color-scheme: light dark; font: 15px/1.5 ui-sans-serif, system-ui, sans-serif; }
|
||
body { max-width: 40rem; margin: 4rem auto; padding: 0 1.5rem; }
|
||
h1 { font-size: 1.3rem; }
|
||
label { display: block; margin-top: 1rem; font-weight: 600; }
|
||
input, button { font: inherit; padding: 0.45rem 0.6rem; margin-top: 0.35rem; }
|
||
input[type="file"] { width: 100%; }
|
||
button { cursor: pointer; }
|
||
#log { white-space: pre-wrap; background: color-mix(in oklab, currentColor 8%, transparent);
|
||
padding: 1rem; border-radius: 0.5rem; margin-top: 1.5rem; }
|
||
.hint { opacity: 0.75; font-size: 0.9rem; }
|
||
</style>
|
||
<h1>Hex browser connect</h1>
|
||
<p class="hint">
|
||
This page asks Hex's window to transcribe one recording, or to record
|
||
from your microphone for as long as the page keeps checking in. Hex must have
|
||
Labs › Connected apps on, with Allow websites to use Hex. The first ask
|
||
from this page (<code id="origin"></code>) shows no dialog: it answers
|
||
<code>website-not-allowed</code> and lists the page in Hex's Connected
|
||
apps pane under Asking to connect. Press Allow there, then
|
||
ask again. The API port comes from Hex's discovery file; this page never
|
||
reads the token.
|
||
</p>
|
||
|
||
<label for="port">Hex's local API port</label>
|
||
<input id="port" inputmode="numeric" placeholder="60529" />
|
||
|
||
<label for="file">One WAV recording</label>
|
||
<input id="file" type="file" accept="audio/wav" />
|
||
|
||
<p><button id="ask">Ask Hex for one transcription</button></p>
|
||
|
||
<p>
|
||
<button id="record">Record with Hex</button>
|
||
<button id="stop" disabled>Stop and get the transcript</button>
|
||
</p>
|
||
<p class="hint">
|
||
A recording runs until you stop it here or in Hex. The page checks in
|
||
every few seconds; close the tab and Hex stops the microphone within a
|
||
lease (10 s).
|
||
</p>
|
||
<pre id="log">Nothing asked yet.</pre>
|
||
|
||
<script type="module">
|
||
const origin = location.origin;
|
||
|
||
// The page's favicon, drawn here and used as the tab's icon too. Each ask
|
||
// sends it as a PNG data: URL (64 KiB at most, PNG or ICO); Hex shows it
|
||
// beside the address and never fetches anything. It is only a claim:
|
||
// Hex names the page by its address.
|
||
const favicon = (() => {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = canvas.height = 64;
|
||
const c = canvas.getContext("2d");
|
||
c.fillStyle = "#2563eb";
|
||
c.beginPath();
|
||
c.roundRect(2, 2, 60, 60, 14);
|
||
c.fill();
|
||
c.fillStyle = "#fff";
|
||
c.font = "bold 40px system-ui, sans-serif";
|
||
c.textAlign = "center";
|
||
c.textBaseline = "middle";
|
||
c.fillText("H", 32, 35);
|
||
const url = canvas.toDataURL("image/png");
|
||
const link = document.createElement("link");
|
||
link.rel = "icon";
|
||
link.href = url;
|
||
document.head.append(link);
|
||
return url;
|
||
})();
|
||
document.querySelector("#origin").textContent = origin;
|
||
const log = (line) => {
|
||
document.querySelector("#log").textContent += `\n${line}`;
|
||
};
|
||
document.querySelector("#log").textContent = "";
|
||
|
||
const base64url = (bytes) =>
|
||
btoa(String.fromCharCode(...bytes))
|
||
.replaceAll("+", "-")
|
||
.replaceAll("/", "_")
|
||
.replaceAll("=", "");
|
||
|
||
async function pkce() {
|
||
const random = crypto.getRandomValues(new Uint8Array(48));
|
||
const verifier = base64url(random);
|
||
const digest = await crypto.subtle.digest(
|
||
"SHA-256",
|
||
new TextEncoder().encode(verifier),
|
||
);
|
||
return { verifier, challenge: base64url(new Uint8Array(digest)) };
|
||
}
|
||
|
||
async function post(url, body, token) {
|
||
const response = await fetch(url, {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
...(token ? { "X-Hex-Connect-Token": token } : {}),
|
||
},
|
||
body,
|
||
});
|
||
const text = await response.text();
|
||
if (text.includes('"website-not-allowed"')) {
|
||
throw new Error(
|
||
"Hex doesn't know this page yet. In Hex, open Connected apps, press Allow beside this page under Asking to connect, then ask again.",
|
||
);
|
||
}
|
||
if (text.includes('"website-blocked"')) {
|
||
throw new Error("This page is blocked in Labs › Connected apps.");
|
||
}
|
||
if (!response.ok) throw new Error(`${response.status} ${text}`);
|
||
return text ? JSON.parse(text) : null;
|
||
}
|
||
|
||
// Recording: pair once (kept in memory), then each recording is a
|
||
// session the page keeps alive with check-ins until it finishes.
|
||
let recordGrant = null;
|
||
let recording = null;
|
||
|
||
async function call(url, header, value) {
|
||
const response = await fetch(url, { method: "POST", headers: { [header]: value } });
|
||
const text = await response.text();
|
||
return { status: response.status, json: text ? JSON.parse(text) : null, text };
|
||
}
|
||
|
||
document.querySelector("#record").addEventListener("click", async () => {
|
||
const port = document.querySelector("#port").value.trim();
|
||
if (!port) return log("Enter Hex's local API port first.");
|
||
const api = `http://127.0.0.1:${port}`;
|
||
try {
|
||
if (!recordGrant) {
|
||
const { verifier, challenge } = await pkce();
|
||
const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
|
||
log("Asking Hex's window to record…");
|
||
const paired = await post(
|
||
`${api}/record/pair`,
|
||
JSON.stringify({
|
||
codeChallenge: challenge,
|
||
codeChallengeMethod: "S256",
|
||
clientName: "Hex browser connect demo",
|
||
icon: favicon,
|
||
permissionProof: localStorage.getItem("hex.record.proof"),
|
||
state,
|
||
}),
|
||
);
|
||
if (paired.state !== state) throw new Error("Hex answered another request.");
|
||
if (paired.permissionProof) localStorage.setItem("hex.record.proof", paired.permissionProof);
|
||
const { grantToken } = await post(
|
||
`${api}/record/token`,
|
||
JSON.stringify({ code: paired.code, codeVerifier: verifier }),
|
||
);
|
||
recordGrant = grantToken;
|
||
}
|
||
const started = await call(`${api}/record/start`, "X-Hex-Record-Grant", recordGrant);
|
||
if (started.status !== 201) {
|
||
recordGrant = started.status === 401 ? null : recordGrant; // spent or revoked
|
||
return log(`Could not start: ${started.status} ${started.text}`);
|
||
}
|
||
const { sessionToken, leaseMs } = started.json;
|
||
// Check in well inside the lease; a refused check-in means the
|
||
// recording already ended (stopped, cancelled, or revoked in Hex).
|
||
const beat = setInterval(async () => {
|
||
const answer = await call(`${api}/record/heartbeat`, "X-Hex-Record-Token", sessionToken)
|
||
.catch((error) => ({ status: 0, text: String(error) }));
|
||
if (answer.status !== 204) {
|
||
clearInterval(beat);
|
||
log(`Recording ended in Hex: ${answer.status} ${answer.text}`);
|
||
}
|
||
}, leaseMs / 3);
|
||
recording = { api, sessionToken, beat };
|
||
document.querySelector("#stop").disabled = false;
|
||
log("Recording…");
|
||
} catch (error) {
|
||
log(String(error));
|
||
}
|
||
});
|
||
|
||
document.querySelector("#stop").addEventListener("click", async () => {
|
||
if (!recording) return;
|
||
const { api, sessionToken, beat } = recording;
|
||
recording = null;
|
||
document.querySelector("#stop").disabled = true;
|
||
clearInterval(beat);
|
||
const finished = await call(`${api}/record/finish`, "X-Hex-Record-Token", sessionToken);
|
||
log(finished.status === 200 ? `Transcript: ${finished.json.transcript}` : `${finished.status} ${finished.text}`);
|
||
});
|
||
|
||
document.querySelector("#ask").addEventListener("click", async () => {
|
||
const port = document.querySelector("#port").value.trim();
|
||
const file = document.querySelector("#file").files[0];
|
||
if (!port) return log("Enter Hex's local API port first.");
|
||
const api = `http://127.0.0.1:${port}`;
|
||
try {
|
||
const { verifier, challenge } = await pkce();
|
||
const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
|
||
log("Asking Hex's window…");
|
||
const grant = await post(
|
||
`${api}/connect/authorize`,
|
||
JSON.stringify({
|
||
codeChallenge: challenge,
|
||
codeChallengeMethod: "S256",
|
||
clientName: "Hex browser connect demo",
|
||
icon: favicon,
|
||
permissionProof: localStorage.getItem("hex.transcribe.proof"),
|
||
state,
|
||
}),
|
||
);
|
||
if (grant.state !== state) throw new Error("Hex answered another request.");
|
||
if (grant.permissionProof) localStorage.setItem("hex.transcribe.proof", grant.permissionProof);
|
||
log(`Allowed. Code expires in ${grant.expiresInMs} ms.`);
|
||
const { audioToken } = await post(
|
||
`${api}/connect/token`,
|
||
JSON.stringify({ code: grant.code, codeVerifier: verifier }),
|
||
);
|
||
if (!file) {
|
||
log("No recording chosen; the one-use token is left unused.");
|
||
return;
|
||
}
|
||
log("Transcribing audio…");
|
||
const response = await fetch(`${api}/transcriptions`, {
|
||
method: "POST",
|
||
headers: {
|
||
"X-Hex-Connect-Token": audioToken,
|
||
"Content-Type": "audio/wav",
|
||
},
|
||
body: await file.arrayBuffer(),
|
||
});
|
||
log(`${response.status}\n${await response.text()}`);
|
||
} catch (error) {
|
||
log(String(error));
|
||
}
|
||
});
|
||
</script>
|
||
</html>
|