Added panic mode protections to make the server more secure
This commit is contained in:
402
client/app.js
402
client/app.js
@@ -1,10 +1,13 @@
|
||||
import { encryptString, decryptToString, toBlob } from "./crypto.js";
|
||||
|
||||
// ---------- DOM ----------
|
||||
const els = {
|
||||
shardUrl: document.getElementById("shardUrl"),
|
||||
bearer: document.getElementById("bearer"),
|
||||
passphrase: document.getElementById("passphrase"),
|
||||
saveConn: document.getElementById("saveConn"),
|
||||
keySignIn: document.getElementById("keySignIn"),
|
||||
panicWipe: document.getElementById("panicWipe"),
|
||||
health: document.getElementById("health"),
|
||||
visibility: document.getElementById("visibility"),
|
||||
title: document.getElementById("title"),
|
||||
@@ -13,170 +16,258 @@ const els = {
|
||||
publishStatus: document.getElementById("publishStatus"),
|
||||
posts: document.getElementById("posts"),
|
||||
discordStart: document.getElementById("discordStart"),
|
||||
signinDevice: document.getElementById("signinDevice"),
|
||||
};
|
||||
|
||||
// ---------- Config (no bearer in localStorage) ----------
|
||||
const LS_KEY = "gc_client_config_v1";
|
||||
const POSTS_KEY = "gc_posts_index_v1";
|
||||
const DEVKEY_KEY = "gc_device_key_v1"; // pkcs8/spki (p256) base64url
|
||||
|
||||
function defaultApiBase() {
|
||||
try { const qs = new URLSearchParams(window.location.search); const qApi = qs.get("api"); if (qApi) return qApi.replace(/\/+$/,""); } catch {}
|
||||
const m = document.querySelector('meta[name="gc-api-base"]'); if (m && m.content) return m.content.replace(/\/+$/,"");
|
||||
try {
|
||||
const u = new URL(window.location.href);
|
||||
const proto = u.protocol; const host = u.hostname; const portStr = u.port;
|
||||
const bracketHost = host.includes(":") ? `[${host}]` : host;
|
||||
const port = portStr ? parseInt(portStr,10) : null;
|
||||
let apiPort = port;
|
||||
if (port === 8082) apiPort = 8080; else if (port === 9082) apiPort = 9080; else if (port) apiPort = Math.max(1, port - 2);
|
||||
return apiPort ? `${proto}//${bracketHost}:${apiPort}` : `${proto}//${bracketHost}`;
|
||||
} catch { return window.location.origin.replace(/\/+$/,""); }
|
||||
}
|
||||
|
||||
function loadConfig(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) ?? {}; } catch { return {}; } }
|
||||
function saveConfig(c){ localStorage.setItem(LS_KEY, JSON.stringify(c)); Object.assign(cfg, c); }
|
||||
function saveConfig(c){ localStorage.setItem(LS_KEY, JSON.stringify({ url: c.url, passphrase: c.passphrase })); Object.assign(cfg, c); }
|
||||
function getPosts(){ try { return JSON.parse(localStorage.getItem(POSTS_KEY)) ?? []; } catch { return []; } }
|
||||
function setPosts(v){ localStorage.setItem(POSTS_KEY, JSON.stringify(v)); renderPosts(); }
|
||||
function norm(u){ return (u||"").replace(/\/+$/,""); }
|
||||
function applyConfig(){ els.shardUrl.value = cfg.url ?? defaultApiBase(); els.bearer.value = cfg.bearer ?? ""; els.passphrase.value = cfg.passphrase ?? ""; }
|
||||
function msg(t, err=false){ els.publishStatus.textContent=t; els.publishStatus.style.color = err ? "#ff6b6b" : "#8b949e"; }
|
||||
function getBearer(){ return sessionStorage.getItem("gc_bearer") || cfg.bearer || ""; }
|
||||
function getBearer(){ return sessionStorage.getItem("gc_bearer") || ""; }
|
||||
function setBearer(tok){ if (!tok) sessionStorage.removeItem("gc_bearer"); else sessionStorage.setItem("gc_bearer", tok); els.bearer.value = tok ? "••• (session)" : ""; }
|
||||
const cfg = loadConfig();
|
||||
|
||||
const cfg = loadConfig(); applyConfig();
|
||||
// ---------- Security helpers ----------
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder();
|
||||
const b64 = (u) => { let s=""; u=new Uint8Array(u); for (let i=0;i<u.length;i++) s+=String.fromCharCode(u[i]); return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""); };
|
||||
const ub64 = (s) => { s=s.replace(/-/g,"+").replace(/_/g,"/"); while(s.length%4) s+="="; const bin=atob(s); const b=new Uint8Array(bin.length); for(let i=0;i<bin.length;i++) b[i]=bin.charCodeAt(i); return b.buffer; };
|
||||
async function sha256Hex(buf){ const h = await crypto.subtle.digest("SHA-256", buf); return [...new Uint8Array(h)].map(x=>x.toString(16).padStart(2,"0")).join(""); }
|
||||
|
||||
// ---- Device key management (P-256) ----
|
||||
async function ensureDeviceKey() {
|
||||
const stored = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "null");
|
||||
if (stored && stored.priv && stored.pub) return;
|
||||
const kp = await crypto.subtle.generateKey({ name:"ECDSA", namedCurve:"P-256" }, true, ["sign","verify"]);
|
||||
const pkcs8 = await crypto.subtle.exportKey("pkcs8", kp.privateKey);
|
||||
const rawPub = await crypto.subtle.exportKey("raw", kp.publicKey); // 65B uncompressed
|
||||
localStorage.setItem(DEVKEY_KEY, JSON.stringify({ alg:"p256", priv: b64(rawPub ? pkcs8 : pkcs8), pub: b64(rawPub) }));
|
||||
}
|
||||
async function getDevicePriv(){
|
||||
const s = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "{}");
|
||||
if (s.alg !== "p256") throw new Error("unsupported alg");
|
||||
return crypto.subtle.importKey("pkcs8", ub64(s.priv), { name:"ECDSA", namedCurve:"P-256" }, false, ["sign"]);
|
||||
}
|
||||
function getDevicePubHdr(){
|
||||
const s = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "{}");
|
||||
return s && s.pub ? "p256:" + s.pub : "";
|
||||
// Device key (P-256), stored locally (not a bearer)
|
||||
async function getDevice() {
|
||||
let dev = JSON.parse(localStorage.getItem('gc_device_key_v1')||'null');
|
||||
if (!dev) {
|
||||
const kp = await crypto.subtle.generateKey({name:"ECDSA", namedCurve:"P-256"}, true, ["sign","verify"]);
|
||||
const pkcs8 = await crypto.subtle.exportKey("pkcs8", kp.privateKey);
|
||||
const rawPub = await crypto.subtle.exportKey("raw", kp.publicKey); // 65B 0x04||X||Y
|
||||
dev = { alg:"p256", priv: b64(pkcs8), pub: b64(rawPub) };
|
||||
localStorage.setItem('gc_device_key_v1', JSON.stringify(dev));
|
||||
}
|
||||
return dev;
|
||||
}
|
||||
|
||||
// ---- DPoP-style proof headers (sign path, not absolute URL) ----
|
||||
async function popHeaders(method, pathOnly, bodyBytes){
|
||||
// Proof-of-Possession headers for this request
|
||||
async function popHeaders(method, pathOnly, bodyBuf){
|
||||
const dev = await getDevice();
|
||||
const ts = Math.floor(Date.now()/1000).toString();
|
||||
const pub = getDevicePubHdr();
|
||||
const digest = await sha256Hex(bodyBytes || new Uint8Array());
|
||||
const msg = (method.toUpperCase()+"\n"+pathOnly+"\n"+ts+"\n"+digest);
|
||||
const priv = await getDevicePriv();
|
||||
const sig = await crypto.subtle.sign({ name:"ECDSA", hash:"SHA-256" }, priv, new TextEncoder().encode(msg));
|
||||
return { "X-GC-Key": pub, "X-GC-TS": ts, "X-GC-Proof": b64(new Uint8Array(sig)) };
|
||||
const hashHex = await sha256Hex(bodyBuf || new Uint8Array());
|
||||
const msg = enc.encode(method.toUpperCase()+"\n"+pathOnly+"\n"+ts+"\n"+hashHex);
|
||||
const priv = await crypto.subtle.importKey("pkcs8", ub64(dev.priv), { name:"ECDSA", namedCurve:"P-256" }, false, ["sign"]);
|
||||
const sig = await crypto.subtle.sign({ name:"ECDSA", hash:"SHA-256" }, priv, msg);
|
||||
return {
|
||||
"X-GC-Key": "p256:"+dev.pub,
|
||||
"X-GC-TS": ts,
|
||||
"X-GC-Proof": b64(sig),
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchAPI(path, opts = {}, bodyBytes){
|
||||
if (!cfg.url) throw new Error("Set shard URL first.");
|
||||
const method = (opts.method || "GET").toUpperCase();
|
||||
const headers = Object.assign({}, opts.headers || {});
|
||||
const bearer = getBearer(); if (bearer) headers["Authorization"] = "Bearer " + bearer;
|
||||
const pop = await popHeaders(method, path, bodyBytes);
|
||||
Object.assign(headers, pop);
|
||||
const r = await fetch(cfg.url + path, Object.assign({}, opts, { method, headers }));
|
||||
return r;
|
||||
// Idle timeout → clear bearer
|
||||
(function idleGuard(){
|
||||
let idle;
|
||||
const bump=()=>{ clearTimeout(idle); idle=setTimeout(()=>setBearer(""), 30*60*1000); }; // 30 min
|
||||
["click","keydown","mousemove","touchstart","focus","visibilitychange"].forEach(ev=>addEventListener(ev,bump,{passive:true}));
|
||||
bump();
|
||||
})();
|
||||
|
||||
// ---------- API base detection ----------
|
||||
function defaultApiBase() {
|
||||
try {
|
||||
const qs = new URLSearchParams(window.location.search);
|
||||
const qApi = qs.get("api"); if (qApi) return qApi.replace(/\/+$/, "");
|
||||
} catch {}
|
||||
const m = document.querySelector('meta[name="gc-api-base"]');
|
||||
if (m && m.content) return m.content.replace(/\/+$/, "");
|
||||
try {
|
||||
const u = new URL(window.location.href);
|
||||
const proto = u.protocol, host = u.hostname, portStr = u.port;
|
||||
const bracketHost = host.includes(":") ? `[${host}]` : host;
|
||||
const port = portStr ? parseInt(portStr, 10) : null;
|
||||
let apiPort = port;
|
||||
if (port === 8082) apiPort = 8080;
|
||||
else if (port === 9082) apiPort = 9080;
|
||||
else if (port) apiPort = Math.max(1, port - 2);
|
||||
return apiPort ? `${proto}//${bracketHost}:${apiPort}` : `${proto}//${bracketHost}`;
|
||||
} catch {
|
||||
return window.location.origin.replace(/\/+$/, "");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Health / Index / SSE ----
|
||||
// ---------- App init ----------
|
||||
function applyConfig(){
|
||||
els.shardUrl.value = cfg.url ?? defaultApiBase();
|
||||
els.passphrase.value = cfg.passphrase ?? "";
|
||||
els.bearer.value = getBearer() ? "••• (session)" : "";
|
||||
}
|
||||
applyConfig(); checkHealth(); syncIndex(); sse();
|
||||
|
||||
// ---------- UI wiring ----------
|
||||
els.saveConn.onclick = async () => {
|
||||
const c = { url: norm(els.shardUrl.value), passphrase: els.passphrase.value };
|
||||
saveConfig(c); await checkHealth(); await syncIndex(); sse(true);
|
||||
};
|
||||
els.publish.onclick = publish;
|
||||
els.discordStart.onclick = discordStart;
|
||||
els.keySignIn.onclick = keySignIn;
|
||||
els.panicWipe.onclick = panicWipe;
|
||||
|
||||
// Panic wipe hotkey (double-tap ESC)
|
||||
let escT=0;
|
||||
addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") {
|
||||
const now = Date.now();
|
||||
if (now - escT < 600) panicWipe();
|
||||
escT = now;
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- Health / Index / SSE ----------
|
||||
async function checkHealth() {
|
||||
if (!cfg.url) return; els.health.textContent = "Checking…";
|
||||
try {
|
||||
const r = await fetch(cfg.url + "/healthz");
|
||||
els.health.textContent = r.ok ? "Connected ✔" : `Error: ${r.status}`;
|
||||
} catch { els.health.textContent = "Not reachable"; }
|
||||
try { const r = await fetch(cfg.url + "/healthz"); els.health.textContent = r.ok ? "Connected ✔" : `Error: ${r.status}`; }
|
||||
catch { els.health.textContent = "Not reachable"; }
|
||||
}
|
||||
|
||||
async function syncIndex() {
|
||||
if (!cfg.url) return;
|
||||
try {
|
||||
const r = await fetchAPI("/v1/index");
|
||||
const hdrs = {};
|
||||
const b = getBearer();
|
||||
if (b) Object.assign(hdrs, await popHeaders("GET", "/v1/index", new Uint8Array()));
|
||||
const r = await fetch(cfg.url + "/v1/index", { headers: Object.assign(hdrs, b?{Authorization:"Bearer "+b}:{}) });
|
||||
if (!r.ok) throw new Error("index fetch failed");
|
||||
const entries = await r.json();
|
||||
setPosts(entries.map(e => ({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, tz:e.creator_tz })));
|
||||
setPosts(entries.map(e => ({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, tz:e.creator_tz||"" })));
|
||||
} catch(e){ console.warn("index sync failed", e); }
|
||||
}
|
||||
|
||||
let sseCtrl;
|
||||
async function sse(){
|
||||
function sse(reset){
|
||||
if (!cfg.url) return;
|
||||
if (sseCtrl) { sseCtrl.abort(); sseCtrl = undefined; }
|
||||
sseCtrl = new AbortController();
|
||||
const path = "/v1/index/stream";
|
||||
const headers = {};
|
||||
const b = getBearer(); if (b) headers["Authorization"] = "Bearer " + b;
|
||||
Object.assign(headers, await popHeaders("GET", path, new Uint8Array()));
|
||||
fetch(cfg.url + path, { headers, signal: sseCtrl.signal }).then(async resp => {
|
||||
if (!resp.ok) return;
|
||||
const reader = resp.body.getReader(); const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { value, done } = await reader.read(); if (done) break;
|
||||
buf += decoder.decode(value, { stream:true });
|
||||
let idx;
|
||||
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
||||
const chunk = buf.slice(0, idx); buf = buf.slice(idx+2);
|
||||
if (chunk.startsWith("data: ")) {
|
||||
try {
|
||||
const ev = JSON.parse(chunk.slice(6));
|
||||
if (ev.event === "put") {
|
||||
const e = ev.data;
|
||||
const posts = getPosts();
|
||||
if (!posts.find(p => p.hash === e.hash)) {
|
||||
posts.unshift({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, tz:e.creator_tz });
|
||||
setPosts(posts);
|
||||
const url = cfg.url + "/v1/index/stream";
|
||||
const b = getBearer();
|
||||
const start = async () => {
|
||||
const hdrs = {};
|
||||
if (b) Object.assign(hdrs, await popHeaders("GET", "/v1/index/stream", new Uint8Array()), { Authorization: "Bearer "+b });
|
||||
fetch(url, { headers: hdrs, signal: sseCtrl.signal }).then(async resp => {
|
||||
if (!resp.ok) return;
|
||||
const reader = resp.body.getReader(); const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { value, done } = await reader.read(); if (done) break;
|
||||
buf += decoder.decode(value, { stream:true });
|
||||
let idx; while ((idx = buf.indexOf("\n\n")) >= 0) {
|
||||
const chunk = buf.slice(0, idx); buf = buf.slice(idx+2);
|
||||
if (chunk.startsWith("data: ")) {
|
||||
try {
|
||||
const ev = JSON.parse(chunk.slice(6));
|
||||
if (ev.event === "put") {
|
||||
const e = ev.data;
|
||||
const posts = getPosts();
|
||||
if (!posts.find(p => p.hash === e.hash)) {
|
||||
posts.unshift({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, tz:e.creator_tz||"" });
|
||||
setPosts(posts);
|
||||
}
|
||||
} else if (ev.event === "delete") {
|
||||
const h = ev.data.hash; setPosts(getPosts().filter(p => p.hash !== h));
|
||||
}
|
||||
} else if (ev.event === "delete") {
|
||||
const h = ev.data.hash; setPosts(getPosts().filter(p => p.hash !== h));
|
||||
}
|
||||
} catch {}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).catch(()=>{});
|
||||
}).catch(()=>{});
|
||||
};
|
||||
start();
|
||||
}
|
||||
|
||||
// ---- Actions ----
|
||||
// ---------- Auth ----------
|
||||
async function keySignIn(){
|
||||
try {
|
||||
if (!cfg.url) { alert("Set shard URL first."); return; }
|
||||
// 1) challenge
|
||||
const cResp = await fetch(cfg.url + "/v1/auth/key/challenge", { method:"POST" });
|
||||
const cTxt = await cResp.text();
|
||||
if (!cResp.ok) { alert("Challenge failed: " + cTxt); return; }
|
||||
const c = JSON.parse(cTxt);
|
||||
// 2) sign and verify
|
||||
const dev = await getDevice();
|
||||
const priv = await crypto.subtle.importKey("pkcs8", ub64(dev.priv), { name:"ECDSA", namedCurve:"P-256" }, false, ["sign"]);
|
||||
const msg = enc.encode("key-verify\n" + c.nonce);
|
||||
const sig = await crypto.subtle.sign({ name:"ECDSA", hash:"SHA-256" }, priv, msg);
|
||||
const vResp = await fetch(cfg.url + "/v1/auth/key/verify", {
|
||||
method:"POST",
|
||||
headers: { "Content-Type":"application/json" },
|
||||
body: JSON.stringify({ nonce:c.nonce, alg:"p256", pub: dev.pub, sig: b64(sig) })
|
||||
});
|
||||
const vTxt = await vResp.text();
|
||||
if (!vResp.ok) { alert("Verify failed: " + vTxt); return; }
|
||||
const j = JSON.parse(vTxt);
|
||||
setBearer(j.bearer);
|
||||
alert("Signed in ✔ (session)");
|
||||
await syncIndex();
|
||||
} catch (e) {
|
||||
alert("Key sign-in exception: " + (e?.message || e));
|
||||
}
|
||||
}
|
||||
|
||||
async function panicWipe(){
|
||||
try {
|
||||
if (cfg.url) await fetch(cfg.url + "/v1/session/clear", { method:"POST" });
|
||||
} catch {}
|
||||
sessionStorage.clear();
|
||||
localStorage.clear();
|
||||
caches && caches.keys().then(keys => keys.forEach(k => caches.delete(k)));
|
||||
location.replace("about:blank");
|
||||
}
|
||||
|
||||
// ---------- Publishing / Viewing ----------
|
||||
function msg(t, err=false){ els.publishStatus.textContent=t; els.publishStatus.style.color = err ? "#ff6b6b" : "inherit"; }
|
||||
|
||||
async function publish() {
|
||||
if (!cfg.url) return msg("Set shard URL first.", true);
|
||||
const title = els.title.value.trim(); const body = els.body.value; const vis = els.visibility.value;
|
||||
const b = getBearer(); if (!b) return msg("Sign in first (device key).", true);
|
||||
|
||||
const title = els.title.value.trim();
|
||||
const body = els.body.value;
|
||||
const vis = els.visibility.value;
|
||||
try {
|
||||
let blob, enc=false;
|
||||
let blob, encp=false;
|
||||
if (vis === "private") {
|
||||
if (!cfg.passphrase) return msg("Set a passphrase (community key) for encrypted posts.", true);
|
||||
if (!cfg.passphrase) return msg("Set a passphrase for private posts.", true);
|
||||
const payload = await encryptString(JSON.stringify({ title, body }), cfg.passphrase);
|
||||
blob = toBlob(payload); enc=true;
|
||||
blob = toBlob(payload); encp=true;
|
||||
} else {
|
||||
blob = toBlob(JSON.stringify({ title, body }));
|
||||
}
|
||||
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
|
||||
const headers = { "Content-Type":"application/octet-stream", "X-GC-TZ": tz };
|
||||
const bearer = getBearer(); if (bearer) headers["Authorization"] = "Bearer " + bearer;
|
||||
if (enc) headers["X-GC-Private"] = "1";
|
||||
const bodyBytes = new Uint8Array(await blob.arrayBuffer());
|
||||
Object.assign(headers, await popHeaders("PUT", "/v1/object", bodyBytes));
|
||||
const r = await fetch(cfg.url + "/v1/object", { method:"PUT", headers, body: blob });
|
||||
const buf = new Uint8Array(await blob.arrayBuffer());
|
||||
const path = "/v1/object";
|
||||
const headers = { "Content-Type":"application/octet-stream", Authorization: "Bearer "+b };
|
||||
if (encp) headers["X-GC-Private"] = "1";
|
||||
const pop = await popHeaders("PUT", path, buf);
|
||||
Object.assign(headers, pop);
|
||||
const r = await fetch(cfg.url + path, { method:"PUT", headers, body: buf });
|
||||
if (!r.ok) throw new Error(await r.text());
|
||||
const j = await r.json();
|
||||
const posts = getPosts();
|
||||
posts.unshift({ hash:j.hash, title: title || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc:j.private, tz:j.creator_tz });
|
||||
posts.unshift({ hash:j.hash, title: title || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc:j.private, tz:j.creator_tz||"" });
|
||||
setPosts(posts);
|
||||
els.body.value = ""; msg(`Published ${enc?"encrypted":"plaintext"} post. Hash: ${j.hash}`);
|
||||
els.body.value = ""; msg(`Published ${encp?"private":"public"} post. Hash: ${j.hash}`);
|
||||
} catch(e){ msg("Publish failed: " + (e?.message||e), true); }
|
||||
}
|
||||
|
||||
async function viewPost(p, pre) {
|
||||
pre.textContent = "Loading…";
|
||||
try {
|
||||
const r = await fetchAPI("/v1/object/" + p.hash);
|
||||
const path = "/v1/object/" + p.hash;
|
||||
const headers = {};
|
||||
const b = getBearer();
|
||||
if (b) Object.assign(headers, await popHeaders("GET", path, new Uint8Array()), { Authorization: "Bearer "+b });
|
||||
const r = await fetch(cfg.url + path, { headers });
|
||||
if (!r.ok) throw new Error("fetch failed " + r.status);
|
||||
const buf = new Uint8Array(await r.arrayBuffer());
|
||||
let text;
|
||||
@@ -192,91 +283,52 @@ async function viewPost(p, pre) {
|
||||
}
|
||||
|
||||
async function saveBlob(p) {
|
||||
const r = await fetchAPI("/v1/object/" + p.hash);
|
||||
const path = "/v1/object/" + p.hash;
|
||||
const headers = {};
|
||||
const b = getBearer();
|
||||
if (b) Object.assign(headers, await popHeaders("GET", path, new Uint8Array()), { Authorization: "Bearer "+b });
|
||||
const r = await fetch(cfg.url + path, { headers });
|
||||
if (!r.ok) return alert("download failed " + r.status);
|
||||
const b = await r.blob();
|
||||
const a = document.createElement("a"); a.href = URL.createObjectURL(b);
|
||||
const bl = await r.blob();
|
||||
const a = document.createElement("a"); a.href = URL.createObjectURL(bl);
|
||||
a.download = p.hash + (p.enc ? ".gcenc" : ".json"); a.click(); URL.revokeObjectURL(a.href);
|
||||
}
|
||||
|
||||
async function delServer(p) {
|
||||
const path = "/v1/object/" + p.hash;
|
||||
const b = getBearer(); if (!b) return alert("Sign in first.");
|
||||
const headers = { Authorization: "Bearer "+b };
|
||||
Object.assign(headers, await popHeaders("DELETE", path, new Uint8Array()));
|
||||
if (!confirm("Delete blob from server by hash?")) return;
|
||||
const r = await fetchAPI("/v1/object/" + p.hash, { method:"DELETE" });
|
||||
const r = await fetch(cfg.url + path, { method:"DELETE", headers });
|
||||
if (!r.ok) return alert("delete failed " + r.status);
|
||||
setPosts(getPosts().filter(x=>x.hash!==p.hash));
|
||||
}
|
||||
|
||||
// ---------- Discord SSO ----------
|
||||
async function discordStart() {
|
||||
if (!cfg.url) { alert("Set shard URL first."); return; }
|
||||
const headers = { "X-GC-3P-Assent":"1", "X-GC-Key": getDevicePubHdr() };
|
||||
const r = await fetch(cfg.url + "/v1/auth/discord/start", { headers });
|
||||
const r = await fetch(cfg.url + "/v1/auth/discord/start", { headers: { "X-GC-3P-Assent":"1" }});
|
||||
if (!r.ok) { alert("Discord SSO not available"); return; }
|
||||
const j = await r.json();
|
||||
location.href = j.url;
|
||||
}
|
||||
|
||||
async function signInWithDeviceKey(){
|
||||
try {
|
||||
if (!cfg.url) { alert("Set shard URL first."); return; }
|
||||
|
||||
// 1) challenge
|
||||
const cResp = await fetch(cfg.url + "/v1/auth/key/challenge", { method:"POST" });
|
||||
const cTxt = await cResp.text();
|
||||
if (!cResp.ok) { alert("Challenge failed: " + cTxt); return; }
|
||||
const c = JSON.parse(cTxt);
|
||||
if (!c.nonce) { alert("Challenge bad JSON: " + cTxt); return; }
|
||||
|
||||
// 2) sign "key-verify\n<nonce>"
|
||||
const msg = "key-verify\n" + c.nonce;
|
||||
const priv = await getDevicePriv();
|
||||
const sig = await crypto.subtle.sign({ name:"ECDSA", hash:"SHA-256" }, priv, new TextEncoder().encode(msg));
|
||||
|
||||
// 3) send verify
|
||||
const body = JSON.stringify({
|
||||
nonce: c.nonce,
|
||||
alg: "p256",
|
||||
pub: (getDevicePubHdr()||"").slice("p256:".length),
|
||||
sig: b64(new Uint8Array(sig))
|
||||
});
|
||||
|
||||
const vResp = await fetch(cfg.url + "/v1/auth/key/verify", {
|
||||
method:"POST",
|
||||
headers:{ "Content-Type":"application/json" },
|
||||
body
|
||||
});
|
||||
const vTxt = await vResp.text();
|
||||
if (!vResp.ok) { alert("Verify failed: " + vTxt); return; }
|
||||
|
||||
const j = JSON.parse(vTxt);
|
||||
if (!j.bearer) { alert("Verify returned no bearer: " + vTxt); return; }
|
||||
|
||||
sessionStorage.setItem("gc_bearer", j.bearer);
|
||||
const k = "gc_client_config_v1"; const cfg0 = JSON.parse(localStorage.getItem(k) || "{}"); cfg0.bearer = j.bearer; localStorage.setItem(k, JSON.stringify(cfg0));
|
||||
els.bearer.value = j.bearer;
|
||||
alert("Signed in ✔");
|
||||
} catch (e) {
|
||||
alert("Key sign-in exception: " + (e?.message || e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---- Render ----
|
||||
// ---------- Render ----------
|
||||
function renderPosts() {
|
||||
const posts = getPosts(); els.posts.innerHTML = "";
|
||||
for (const p of posts) {
|
||||
const div = document.createElement("div"); div.className = "post";
|
||||
const badge = p.enc ? `<span class="badge">encrypted</span>` : `<span class="badge">plaintext</span>`;
|
||||
const tsLocal = new Date(p.ts).toLocaleString();
|
||||
const tz = p.tz ? ` · author TZ: ${p.tz}` : "";
|
||||
const badge = p.enc ? `<span class="badge">private</span>` : `<span class="badge">public</span>`;
|
||||
div.innerHTML = `
|
||||
<div class="meta"><code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${tsLocal}${tz} ${badge}</div>
|
||||
<div class="meta"><code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${p.ts} ${badge}</div>
|
||||
<div class="actions">
|
||||
<button data-act="view">View</button>
|
||||
<button data-act="save">Save blob</button>
|
||||
<button data-act="delete">Delete (server)</button>
|
||||
<button data-act="remove">Remove (local)</button>
|
||||
</div>
|
||||
<pre class="content" style="white-space:pre-wrap;margin-top:.5rem;"></pre>`;
|
||||
<pre class="content"></pre>`;
|
||||
const pre = div.querySelector(".content");
|
||||
div.querySelector('[data-act="view"]').onclick = () => viewPost(p, pre);
|
||||
div.querySelector('[data-act="save"]').onclick = () => saveBlob(p);
|
||||
@@ -285,23 +337,3 @@ function renderPosts() {
|
||||
els.posts.appendChild(div);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Boot ----
|
||||
(async () => {
|
||||
await ensureDeviceKey();
|
||||
await checkHealth(); await syncIndex(); await sse();
|
||||
})();
|
||||
|
||||
els.saveConn.onclick = async () => {
|
||||
const c = { url: norm(els.shardUrl.value), bearer: els.bearer.value.trim(), passphrase: els.passphrase.value };
|
||||
saveConfig(c);
|
||||
await checkHealth(); await syncIndex(); await sse();
|
||||
};
|
||||
els.publish.onclick = publish;
|
||||
els.discordStart.onclick = discordStart;
|
||||
els.signinDevice.onclick = signInWithDeviceKey;
|
||||
|
||||
// ---- utils ----
|
||||
function b64(buf){ const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf); let s=""; for (let i=0;i<b.length;i++) s+=String.fromCharCode(b[i]); return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""); }
|
||||
function ub64(s){ s=s.replace(/-/g,"+").replace(/_/g,"/"); while (s.length%4) s+="="; const bin=atob(s); const b=new Uint8Array(bin.length); for (let i=0;i<bin.length;i++) b[i]=bin.charCodeAt(i); return b.buffer; }
|
||||
async function sha256Hex(bytes){ const d = await crypto.subtle.digest("SHA-256", bytes); return Array.from(new Uint8Array(d)).map(b=>b.toString(16).padStart(2,"0")).join(""); }
|
||||
|
Reference in New Issue
Block a user