Fixed the issue with PlainText (Complete Anon) posting Need to fix device sign on issues. Need to make it so that the non-signed in devices can only see their equalivant level of posts. (i.e. plaintext, public-encrypted, private-encrypted)
606 lines
29 KiB
JavaScript
606 lines
29 KiB
JavaScript
// GreenCoast client — Trusted-Types safe, 3 visibility modes, PoP auth, x-post,
|
|
// plaintext publishes are anonymous (no Authorization / PoP) when enabled server-side.
|
|
|
|
const els = {};
|
|
function $(id){ return document.getElementById(id); }
|
|
function on(el, ev, fn){ if (el) el.addEventListener(ev, fn, false); }
|
|
function norm(u){ return (u||"").replace(/\/+$/,""); }
|
|
function flash(msg, ms=1800){ if(!els.flash) return; els.flash.textContent=msg; els.flash.style.display="block"; setTimeout(()=>els.flash.style.display="none", ms); }
|
|
function setText(el, s){ if(el) el.textContent = s; }
|
|
function currentPath(){ const h=location.hash||"#/"; const p=h.replace(/^#/, ""); return p||"/"; }
|
|
|
|
const HAS_SUBTLE = !!(window.isSecureContext && window.crypto && crypto.subtle && crypto.subtle.generateKey);
|
|
const routes = { "/":"feed", "/privacy":"privacy.html", "/gdpr":"gdpr.html", "/terms":"terms.html" };
|
|
|
|
// ---------- Router (Trusted-Types safe text-only render of legal pages) ----------
|
|
function setActiveTab(path){
|
|
const cur = path in routes ? path : "/";
|
|
document.querySelectorAll(".tabs a").forEach(a=>{
|
|
const href = new URL(a.href, location.origin).hash.replace(/^#/, "") || "/";
|
|
a.classList.toggle("active", href===cur);
|
|
});
|
|
}
|
|
async function renderRoute(path){
|
|
setActiveTab(path);
|
|
const target = routes[path] ?? "feed";
|
|
if (target === "feed"){ els.page.hidden=true; els.feed.hidden=false; return; }
|
|
els.feed.hidden=true; els.page.hidden=false;
|
|
setText(els.pageContent, "Loading…");
|
|
try{
|
|
const res = await fetch("./"+target, { cache:"no-store" });
|
|
const html = await res.text();
|
|
const body = (html.match(/<body[^>]*>([\s\S]*?)<\/body>/i)?.[1] || html).replace(/<[^>]*>/g,"");
|
|
setText(els.pageContent, body);
|
|
}catch{ setText(els.pageContent, "Failed to load page."); }
|
|
}
|
|
|
|
// ---------- Config ----------
|
|
const LS_KEY="gc_client_config_v10", POSTS_KEY="gc_posts_index_v10", KEY_PKCS8="gc_key_pkcs8", KEY_PUB_RAW="gc_key_pub_raw";
|
|
|
|
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(/\/+$/,""); }
|
|
}
|
|
function loadCfg(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) ?? {}; } catch { return {}; } }
|
|
const cfg = loadCfg();
|
|
function saveCfg(c){ localStorage.setItem(LS_KEY, JSON.stringify(Object.assign(cfg,c))); }
|
|
function applyCfg(){
|
|
els.shardUrl.value = cfg.url ?? defaultApiBase();
|
|
els.bearer.value = cfg.bearer ?? "";
|
|
els.passphrase.value = cfg.passphrase ?? "";
|
|
}
|
|
function isAuthorized(){ return !!cfg.bearer; }
|
|
function updateLimitedUI(){
|
|
const limited = !isAuthorized();
|
|
if (els.banner) els.banner.hidden = !limited;
|
|
for (const id of ["visibility","shareVis"]){
|
|
const sel = $(id); if (!sel) continue;
|
|
for (const val of ["members","private"]){
|
|
const opt = [...sel.options].find(o => o.value===val);
|
|
if (opt) opt.disabled = limited;
|
|
}
|
|
if (limited && (sel.value==="members" || sel.value==="private")) sel.value="plaintext";
|
|
}
|
|
}
|
|
|
|
// ---------- Crypto helpers ----------
|
|
function b64uEncode(buf){ const bin=Array.from(new Uint8Array(buf)).map(b=>String.fromCharCode(b)).join(""); return btoa(bin).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""); }
|
|
function b64uDecodeToBytes(s){ s=s.replace(/-/g,"+").replace(/_/g,"/"); while(s.length%4) s+="="; const bin=atob(s); const out=new Uint8Array(bin.length); for(let i=0;i<bin.length;i++) out[i]=bin.charCodeAt(i); return out; }
|
|
async function sha256(bytes){ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); }
|
|
async function sha256Hex(str){ const out=await sha256(new TextEncoder().encode(str)); return Array.from(out).map(b=>b.toString(16).padStart(2,"0")).join(""); }
|
|
|
|
async function getOrCreateKeyPair(){
|
|
if (!HAS_SUBTLE) throw new Error("WebCrypto not available");
|
|
const pkcs8 = sessionStorage.getItem(KEY_PKCS8); const pubRaw = sessionStorage.getItem(KEY_PUB_RAW);
|
|
if (pkcs8 && pubRaw){
|
|
try{
|
|
const priv = await crypto.subtle.importKey("pkcs8", b64uDecodeToBytes(pkcs8), {name:"ECDSA", namedCurve:"P-256"}, true, ["sign"]);
|
|
const pub = await crypto.subtle.importKey("raw", b64uDecodeToBytes(pubRaw), {name:"ECDSA", namedCurve:"P-256"}, true, ["verify"]);
|
|
return { priv, pub, pkcs8B64u: pkcs8, pubRawB64u: pubRaw };
|
|
}catch{}
|
|
}
|
|
const kp = await crypto.subtle.generateKey({name:"ECDSA", namedCurve:"P-256"}, true, ["sign","verify"]);
|
|
const pkcs8New = await crypto.subtle.exportKey("pkcs8", kp.privateKey);
|
|
const pubRawBytes = await crypto.subtle.exportKey("raw", kp.publicKey);
|
|
const pkcs8B64 = b64uEncode(pkcs8New); const pubRawB64 = b64uEncode(pubRawBytes);
|
|
sessionStorage.setItem(KEY_PKCS8, pkcs8B64); sessionStorage.setItem(KEY_PUB_RAW, pubRawB64);
|
|
return { priv: kp.privateKey, pub: kp.publicKey, pkcs8B64u: pkcs8B64, pubRawB64u: pubRawB64 };
|
|
}
|
|
async function deriveMembersPassphrase(saltBytes){
|
|
const kp = await getOrCreateKeyPair();
|
|
const seed = await sha256(b64uDecodeToBytes(kp.pkcs8B64u));
|
|
const cat = new Uint8Array(seed.length + 1 + saltBytes.length);
|
|
cat.set(seed,0); cat.set(new Uint8Array([1]), seed.length); cat.set(saltBytes, seed.length+1);
|
|
const out = await sha256(cat);
|
|
return b64uEncode(out);
|
|
}
|
|
async function deriveAesKey(passphraseB64u, saltBytes){
|
|
const raw = b64uDecodeToBytes(passphraseB64u);
|
|
const keyMat = await crypto.subtle.importKey("raw", raw, "PBKDF2", false, ["deriveKey"]);
|
|
return crypto.subtle.deriveKey(
|
|
{ name:"PBKDF2", salt:saltBytes, iterations:120000, hash:"SHA-256" },
|
|
keyMat, { name:"AES-GCM", length:256 }, false, ["encrypt","decrypt"]
|
|
);
|
|
}
|
|
async function aesEncryptString(str, passphraseB64u){
|
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
const key = await deriveAesKey(passphraseB64u, salt);
|
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
const ct = new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM", iv}, key, new TextEncoder().encode(str)));
|
|
return { alg:"aes-256-gcm", iv:b64uEncode(iv), salt:b64uEncode(salt), ct:b64uEncode(ct) };
|
|
}
|
|
async function aesDecryptToString(obj, passphraseB64u){
|
|
const key = await deriveAesKey(passphraseB64u, b64uDecodeToBytes(obj.salt));
|
|
const pt = await crypto.subtle.decrypt({name:"AES-GCM", iv:b64uDecodeToBytes(obj.iv)}, key, b64uDecodeToBytes(obj.ct));
|
|
return new TextDecoder().decode(pt);
|
|
}
|
|
function makeEnvelope(mode, encObj, meta){ return JSON.stringify({ gc:"2", mode, enc:encObj, meta }); }
|
|
function tryParseJSON(t){ try{ return JSON.parse(t); }catch{ return null; } }
|
|
|
|
// ---------- Avatar ----------
|
|
function parseGC2(tok){ try{ const p=tok.split("."); if(p.length!==3) return {}; const pl=JSON.parse(atob(p[1].replace(/-/g,"+").replace(/_/g,"/"))); return {sub:pl.sub||"", cnf:pl.cnf||""}; }catch{ return {}; } }
|
|
function identiconPNGFromHex(hex, size=64){
|
|
const cells=5, cell=Math.floor(size/cells), pad=Math.floor((size-cell*cells)/2);
|
|
const hexBytes=(h)=>{const u=new Uint8Array(h.length/2); for(let i=0;i<u.length;i++) u[i]=parseInt(h.substr(i*2,2),16); return u;};
|
|
const b=hexBytes(hex); const hue=b[0]/255*360; const bg=`hsl(${hue},35%,16%)`; const fg=`hsl(${(hue+180)%360},70%,60%)`;
|
|
const bits=[]; for(const x of b) for(let i=0;i<8;i++) bits.push((x>>i)&1);
|
|
const c=document.createElement("canvas"); c.width=c.height=size; const g=c.getContext("2d");
|
|
g.fillStyle=bg; g.fillRect(0,0,size,size); let k=0;
|
|
for(let y=0;y<cells;y++){ for(let x=0;x<3;x++){ if(bits[k++]===1){ const px=pad+x*cell, py=pad+y*cell;
|
|
g.fillStyle=fg; g.fillRect(px,py,cell-1,cell-1); const mx=pad+(cells-1-x)*cell; if(cells-1-x!==x) g.fillRect(mx,py,cell-1,cell-1); } } }
|
|
return c.toDataURL("image/png");
|
|
}
|
|
async function renderAvatar(){
|
|
if (!els.avatar) return;
|
|
let seed=null, label="(pseudonymous)";
|
|
if (cfg.bearer){ const p=parseGC2(cfg.bearer); seed=p.cnf||p.sub||null; if(p.sub) label=p.sub; }
|
|
if (!seed){ els.avatar.removeAttribute("src"); setText(els.fp,"(pseudonymous)"); return; }
|
|
const hex = await sha256Hex(seed);
|
|
els.avatar.onerror = ()=>{ els.avatar.removeAttribute("src"); setText(els.fp,"(pseudonymous)"); };
|
|
els.avatar.src=identiconPNGFromHex(hex, 64);
|
|
setText(els.fp, label+" (pseudonymous)");
|
|
}
|
|
|
|
// ---------- Auth / PoP ----------
|
|
async function requireChallengeAlive(base) {
|
|
try {
|
|
const r = await fetch(base + "/v1/auth/key/challenge", { method: "POST" });
|
|
if (r.status === 404) {
|
|
alert(
|
|
"Shard URL looks wrong: /v1/auth/key/challenge not found.\n\n" +
|
|
"Current base:\n" + base + "\n\n" +
|
|
"Set it to your API host (e.g. https://api-gc.fullmooncyberworks.com) and Save."
|
|
);
|
|
return false;
|
|
}
|
|
return r.ok;
|
|
} catch {
|
|
alert("Cannot reach shard at: " + base);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function deviceKeySignIn(){
|
|
if (!HAS_SUBTLE) { alert("Device keys not supported. Use Discord or a modern browser."); return; }
|
|
const base = cfg.url || defaultApiBase(); if (!base){ alert("Set shard URL first."); return; }
|
|
if (!(await requireChallengeAlive(base))) return;
|
|
flash("Signing in…");
|
|
try{
|
|
const { priv, pubRawB64u } = await getOrCreateKeyPair();
|
|
const rc = await fetch(base + "/v1/auth/key/challenge", { method:"POST" });
|
|
if (!rc.ok) throw new Error("challenge "+rc.status);
|
|
const cj = await rc.json();
|
|
const msg = new TextEncoder().encode("key-verify\n"+cj.nonce);
|
|
const sig = await crypto.subtle.sign({name:"ECDSA", hash:"SHA-256"}, priv, msg);
|
|
const body = JSON.stringify({ nonce:cj.nonce, alg:"p256", pub:pubRawB64u, sig:b64uEncode(sig) });
|
|
const rv = await fetch(base + "/v1/auth/key/verify", { method:"POST", headers:{"Content-Type":"application/json"}, body });
|
|
if (!rv.ok) throw new Error("verify "+rv.status);
|
|
const vj = await rv.json();
|
|
saveCfg({ bearer: vj.bearer }); applyCfg(); updateLimitedUI();
|
|
await renderAvatar(); await checkHealth(); await syncIndex(); sse(true); flash("Signed in");
|
|
}catch(e){ console.error(e); alert("Sign-in error: "+(e?.message||e)); }
|
|
}
|
|
|
|
async function signPoPHeaders(method, pathOnly, bodyBytes){
|
|
if (!HAS_SUBTLE) return {};
|
|
const pubRaw = sessionStorage.getItem(KEY_PUB_RAW); const pkcs8 = sessionStorage.getItem(KEY_PKCS8);
|
|
if (!pubRaw || !pkcs8) return {};
|
|
const priv = await crypto.subtle.importKey("pkcs8", b64uDecodeToBytes(pkcs8), {name:"ECDSA", namedCurve:"P-256"}, false, ["sign"]);
|
|
const bodyHash = new Uint8Array(await crypto.subtle.digest("SHA-256", bodyBytes || new Uint8Array()));
|
|
const hex = Array.from(bodyHash).map(b=>b.toString(16).padStart(2,"0")).join("");
|
|
const ts = Math.floor(Date.now()/1000).toString();
|
|
const msg = new TextEncoder().encode(method.toUpperCase()+"\n"+pathOnly+"\n"+ts+"\n"+hex);
|
|
const sig = await crypto.subtle.sign({name:"ECDSA", hash:"SHA-256"}, priv, msg);
|
|
return { "X-GC-Key":"p256:"+pubRaw, "X-GC-TS":ts, "X-GC-Proof":b64uEncode(sig) };
|
|
}
|
|
async function fetchWithPoP(url, opts){
|
|
const u = new URL(url); const path = u.pathname; const method = (opts?.method||"GET").toUpperCase();
|
|
const bodyBuf = opts?.body instanceof Blob ? new Uint8Array(await opts.body.arrayBuffer())
|
|
: (opts?.body instanceof ArrayBuffer ? new Uint8Array(opts.body) : new Uint8Array());
|
|
const pop = await signPoPHeaders(method, path, bodyBuf);
|
|
const headers = new Headers(opts?.headers||{});
|
|
if (cfg.bearer) headers.set("Authorization", "Bearer "+cfg.bearer);
|
|
for (const [k,v] of Object.entries(pop)) headers.set(k,v);
|
|
return fetch(url, { ...(opts||{}), headers });
|
|
}
|
|
// Anonymous fetch: strip any auth/PoP headers completely (for plaintext writes)
|
|
function stripAuthHeaders(h){ h.delete("Authorization"); h.delete("X-GC-Key"); h.delete("X-GC-TS"); h.delete("X-GC-Proof"); return h; }
|
|
async function fetchAnon(url, opts){
|
|
const headers = new Headers(opts?.headers || {});
|
|
return fetch(url, { ...(opts||{}), headers: stripAuthHeaders(headers) });
|
|
}
|
|
|
|
// ---------- Leak detection ----------
|
|
const SECRET_PATTERNS = [
|
|
/\b(passphrase|password|secret|gc[-_ ]?pass|shared[-_ ]?key)\s*[:=]\s*[^\s]{8,}/i,
|
|
/\b(ASIA|AKIA|AIza)[0-9A-Za-z_\-]{10,}/,
|
|
/\b[A-Za-z0-9+/_-]{32,}={0,2}\b/,
|
|
/\b[0-9a-f]{64,}\b/i,
|
|
/-----BEGIN [A-Z ]{5,}-----[\s\S]+?-----END [A-Z ]{5,}-----/
|
|
];
|
|
function containsSecret(text, passphrase){
|
|
if (!text) return false;
|
|
if (passphrase && passphrase.length>=6 && text.includes(passphrase)) return true;
|
|
return SECRET_PATTERNS.some(rx => rx.test(text));
|
|
}
|
|
|
|
// ---------- X-post helpers ----------
|
|
const TRACKING_PARAMS = [/^utm_/i,/^gclid$/i,/^fbclid$/i,/^msclkid$/i,/^mc_(eid|cid)$/i,/^vero_id$/i,/^oly_(anon|enc)_id$/i,/^_hs(enc|mi|mi)/i,/^s?cid$/i,/^igshid$/i,/^ttclid$/i,/^spm$/i,/^ref$/i,/^ref_src$/i,/^ref_url$/i];
|
|
function sanitizeUrl(input){
|
|
try{
|
|
const u = new URL(input.trim());
|
|
for (const [k] of u.searchParams){ if (TRACKING_PARAMS.some(rx=>rx.test(k))) u.searchParams.delete(k); }
|
|
u.hash = "";
|
|
return u.toString();
|
|
}catch{ return ""; }
|
|
}
|
|
function shortHost(h){ try{ const p=h.split("."); return p.length>2 ? p.slice(-2).join(".") : h; }catch{ return h; } }
|
|
function renderXCard(container, cleanUrl, note){
|
|
container.replaceChildren();
|
|
if (!cleanUrl){ const m=document.createElement("div"); m.className="xmeta"; m.textContent="Enter a valid URL."; container.appendChild(m); return; }
|
|
const u = new URL(cleanUrl);
|
|
const row = document.createElement("div"); row.className="xrow";
|
|
const pill = document.createElement("span"); pill.className="xpill"; pill.textContent=shortHost(u.hostname);
|
|
const title = document.createElement("span"); title.className="xtitle"; title.textContent=note || `${shortHost(u.hostname)} link`;
|
|
row.appendChild(pill); row.appendChild(title);
|
|
|
|
const meta = document.createElement("div"); meta.className="xmeta"; meta.textContent=(u.pathname||"/")+(u.search||"");
|
|
|
|
const btn = document.createElement("div"); btn.className="xbtn";
|
|
const a = document.createElement("a"); a.href=cleanUrl; a.target="_blank"; a.rel="noreferrer noopener"; a.referrerPolicy="no-referrer"; a.textContent="Open privately ↗";
|
|
btn.appendChild(a);
|
|
|
|
container.appendChild(row); container.appendChild(meta); container.appendChild(btn);
|
|
}
|
|
|
|
// ---------- Compose / Publish ----------
|
|
function msg(t, err=false){ setText(els.publishStatus, t); els.publishStatus.style.color = err ? "#ff6b6b" : "#8b949e"; }
|
|
|
|
async function publish(){
|
|
const base = cfg.url || defaultApiBase(); if (!base) return msg("Set shard URL first.", true);
|
|
|
|
const mode = els.visibility.value; // plaintext | members | private
|
|
const title = els.title.value.trim();
|
|
const body = els.body.value;
|
|
|
|
if ((mode==="members"||mode==="private") && !isAuthorized()){ msg("Authorize your device to publish encrypted posts.", true); return; }
|
|
|
|
const currentPass = els.passphrase.value.trim();
|
|
if (containsSecret(body, currentPass)){ msg("Blocked: content appears to include a passkey/secret.", true); return; }
|
|
|
|
try{
|
|
let blob, headers={"Content-Type":"application/octet-stream"}, enc=false;
|
|
|
|
if (mode==="plaintext"){
|
|
blob = new Blob([JSON.stringify({ title, body, type:"plaintext" })], {type:"application/json"});
|
|
} else if (mode==="members"){
|
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
const pp = await deriveMembersPassphrase(salt);
|
|
const encObj = await aesEncryptString(JSON.stringify({ title, body, type:"members" }), pp);
|
|
const env = makeEnvelope("members", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
|
} else if (mode==="private"){
|
|
if (!currentPass) return msg("Set a passphrase for Private-Encrypted posts.", true);
|
|
const pp = b64uEncode(new TextEncoder().encode(currentPass));
|
|
const encObj = await aesEncryptString(JSON.stringify({ title, body, type:"private" }), pp);
|
|
const env = makeEnvelope("private", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
|
}
|
|
|
|
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; if (tz) headers["X-GC-TZ"]=tz;
|
|
|
|
const url = base + "/v1/object";
|
|
let r;
|
|
if (mode === "plaintext") {
|
|
// truly anonymous write (requires allow_anon_plaintext on shard)
|
|
r = await fetchAnon(url, { method:"PUT", headers, body: blob });
|
|
} else {
|
|
r = await fetchWithPoP(url, { method:"PUT", headers, body: blob });
|
|
}
|
|
if (!r.ok) throw new Error(await r.text());
|
|
const j = await r.json();
|
|
|
|
const posts = getPosts();
|
|
posts.unshift({ hash:j.hash, title: title || (enc?"(encrypted)":"(untitled)"), bytes:j.bytes, ts:j.stored_at, enc, mode, author:j.author||null, tz:j.creator_tz||null });
|
|
setPosts(posts);
|
|
els.body.value="";
|
|
msg(`Published ${mode}. Hash: ${j.hash}`);
|
|
}catch(e){ msg("Publish failed: "+(e?.message||e), true); }
|
|
}
|
|
|
|
async function publishShare(){
|
|
const base = cfg.url || defaultApiBase(); if (!base) return alert("Set shard URL first.");
|
|
const clean = sanitizeUrl(els.shareUrl.value); if (!clean) return alert("Enter a valid URL.");
|
|
|
|
const mode = els.shareVis.value;
|
|
const note = els.shareNote.value || "";
|
|
|
|
if ((mode==="members"||mode==="private") && !isAuthorized()){ alert("Authorize your device to publish encrypted links."); return; }
|
|
if (containsSecret(note, els.passphrase.value.trim())){ alert("Blocked: content appears to include a passkey/secret."); return; }
|
|
|
|
try{
|
|
let blob, headers={"Content-Type":"application/octet-stream"}, enc=false;
|
|
|
|
if (mode==="plaintext"){
|
|
blob = new Blob([JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() })], {type:"application/json"});
|
|
} else if (mode==="members"){
|
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
const pp = await deriveMembersPassphrase(salt);
|
|
const encObj = await aesEncryptString(JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() }), pp);
|
|
const env = makeEnvelope("members", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
|
} else {
|
|
const pass = els.passphrase.value.trim(); if (!pass) return alert("Set a passphrase for Private-Encrypted links.");
|
|
const pp = b64uEncode(new TextEncoder().encode(pass));
|
|
const encObj = await aesEncryptString(JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() }), pp);
|
|
const env = makeEnvelope("private", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
|
}
|
|
|
|
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; if (tz) headers["X-GC-TZ"]=tz;
|
|
|
|
const url = base + "/v1/object";
|
|
let r;
|
|
if (mode === "plaintext") {
|
|
r = await fetchAnon(url, { method:"PUT", headers, body: blob });
|
|
} else {
|
|
r = await fetchWithPoP(url, { method:"PUT", headers, body: blob });
|
|
}
|
|
if (!r.ok) throw new Error(await r.text());
|
|
const j = await r.json();
|
|
|
|
const posts = getPosts();
|
|
posts.unshift({ hash:j.hash, title:"(link)", bytes:j.bytes, ts:j.stored_at, enc, mode, author:j.author||null, tz:j.creator_tz||null });
|
|
setPosts(posts);
|
|
els.shareUrl.value=""; els.shareNote.value="";
|
|
renderXCard(els.shareCard, "", "");
|
|
flash("Link published");
|
|
}catch(e){ alert("Publish failed: "+(e?.message||e)); }
|
|
}
|
|
|
|
// ---------- View / Decrypt ----------
|
|
async function viewPost(p, pre){
|
|
const base = cfg.url || defaultApiBase(); pre.textContent="Loading…";
|
|
try{
|
|
const r = await fetch(base + "/v1/object/"+p.hash);
|
|
if (!r.ok) throw new Error("fetch failed "+r.status);
|
|
const buf = new Uint8Array(await r.arrayBuffer());
|
|
const text = new TextDecoder().decode(buf);
|
|
|
|
const env = tryParseJSON(text);
|
|
if (env && env.gc==="2" && env.enc && env.mode){
|
|
const enc = env.enc; let pt;
|
|
if (env.mode==="members"){
|
|
if (!HAS_SUBTLE) throw new Error("Cannot decrypt on this browser.");
|
|
const pp = await deriveMembersPassphrase(b64uDecodeToBytes(enc.salt));
|
|
pt = await aesDecryptToString(enc, pp);
|
|
} else if (env.mode==="private"){
|
|
const pass = els.passphrase.value.trim(); if (!pass) throw new Error("Passphrase required");
|
|
const pp = b64uEncode(new TextEncoder().encode(pass));
|
|
pt = await aesDecryptToString(enc, pp);
|
|
} else { throw new Error("Unknown mode"); }
|
|
|
|
const j = tryParseJSON(pt);
|
|
if (j && j.type==="xpost" && j.url){
|
|
const wrap = pre.parentElement; const card = document.createElement("div"); card.className="xcard";
|
|
renderXCard(card, sanitizeUrl(j.url), j.note||""); wrap.replaceChild(card, pre); return;
|
|
}
|
|
pre.textContent = (j?.title?`# ${j.title}\n\n`:"") + (j?.body ?? pt);
|
|
return;
|
|
}
|
|
|
|
const j = tryParseJSON(text);
|
|
if (j){
|
|
if (j.type==="xpost" && j.url){
|
|
const wrap = pre.parentElement; const card = document.createElement("div"); card.className="xcard";
|
|
renderXCard(card, sanitizeUrl(j.url), j.note||""); wrap.replaceChild(card, pre); return;
|
|
}
|
|
pre.textContent = (j.title?`# ${j.title}\n\n`:"") + (j.body ?? text);
|
|
return;
|
|
}
|
|
|
|
pre.textContent = text;
|
|
}catch(e){ pre.textContent="Error: "+(e?.message||e); }
|
|
}
|
|
|
|
async function saveBlob(p){
|
|
const base = cfg.url || defaultApiBase();
|
|
const r = await fetch(base + "/v1/object/"+p.hash);
|
|
if (!r.ok) return alert("download failed "+r.status);
|
|
const b = await r.blob(); const a=document.createElement("a"); a.href=URL.createObjectURL(b);
|
|
a.download=p.hash+(p.enc?".gcenc":".json"); a.click(); URL.revokeObjectURL(a.href);
|
|
}
|
|
async function delServer(p){
|
|
const base = cfg.url || defaultApiBase();
|
|
if (!confirm("Delete blob from server by hash?")) return;
|
|
const r = await fetchWithPoP(base + "/v1/object/"+p.hash, { method:"DELETE" });
|
|
if (!r.ok) return alert("delete failed "+r.status);
|
|
setPosts(getPosts().filter(x=>x.hash!==p.hash));
|
|
}
|
|
|
|
// ---------- Index / SSE / Health ----------
|
|
function getPosts(){ try { return JSON.parse(localStorage.getItem(POSTS_KEY)) ?? []; } catch { return []; } }
|
|
function setPosts(v){ localStorage.setItem(POSTS_KEY, JSON.stringify(v)); renderPosts(); }
|
|
async function syncIndex(){
|
|
const base = cfg.url || defaultApiBase(); if (!base) return;
|
|
try{
|
|
const r = await fetch(base + "/v1/index");
|
|
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, mode: e.private ? "encrypted" : "plaintext",
|
|
author:e.author||null, tz:e.creator_tz||null
|
|
})));
|
|
}catch(e){ console.warn("index sync failed", e); }
|
|
}
|
|
let sseCtrl;
|
|
function sse(reset=false){
|
|
const base = cfg.url || defaultApiBase(); if (!base) return;
|
|
if (sseCtrl){ sseCtrl.abort(); sseCtrl=undefined; if(!reset) return; }
|
|
sseCtrl = new AbortController();
|
|
fetch(base + "/v1/index/stream", { signal:sseCtrl.signal }).then(async resp=>{
|
|
if (!resp.ok) return;
|
|
const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf="";
|
|
while(true){ const {value,done}=await reader.read(); if(done) break;
|
|
buf += dec.decode(value,{stream:true});
|
|
let i; while((i=buf.indexOf("\n\n"))>=0){
|
|
const chunk=buf.slice(0,i); buf=buf.slice(i+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,mode:e.private?"encrypted":"plaintext",author:e.author||null,tz:e.creator_tz||null});
|
|
setPosts(posts);
|
|
}
|
|
} else if (ev.event==="delete"){
|
|
const h=ev.data.hash; setPosts(getPosts().filter(x=>x.hash!==h));
|
|
}
|
|
}catch{}
|
|
}
|
|
}
|
|
}
|
|
}).catch(()=>{});
|
|
}
|
|
async function checkHealth(){
|
|
const base = cfg.url || defaultApiBase();
|
|
if (!base) { setText(els.health,"Set URL"); return; }
|
|
setText(els.health,"Checking…");
|
|
try { const r = await fetch(base + "/healthz"); setText(els.health, r.ok ? "Connected ✔" : `Error: ${r.status}`); }
|
|
catch { setText(els.health,"Not reachable"); }
|
|
}
|
|
|
|
// ---------- Render posts (no innerHTML) ----------
|
|
function renderPosts() {
|
|
const posts = getPosts();
|
|
const root = els.posts;
|
|
if (!root) return;
|
|
while (root.firstChild) root.removeChild(root.firstChild);
|
|
|
|
for (const p of posts) {
|
|
const wrap = document.createElement("div");
|
|
wrap.className = "post";
|
|
|
|
const meta = document.createElement("div");
|
|
meta.className = "meta";
|
|
|
|
const codeEl = document.createElement("code");
|
|
codeEl.textContent = `${p.hash.slice(0, 10)}…`;
|
|
meta.appendChild(codeEl);
|
|
|
|
const metaText = [
|
|
` · ${p.bytes} bytes`,
|
|
` · ${p.ts}`,
|
|
p.tz ? ` · tz:${p.tz}` : "",
|
|
p.author ? ` · by ${p.author.slice(0, 8)}…` : "",
|
|
" "
|
|
].join("");
|
|
meta.appendChild(document.createTextNode(metaText));
|
|
|
|
const badge = document.createElement("span");
|
|
badge.className = "badge";
|
|
badge.textContent = p.enc ? (p.mode==="private"?"private":"encrypted") : "plaintext";
|
|
meta.appendChild(badge);
|
|
|
|
wrap.appendChild(meta);
|
|
|
|
const actions = document.createElement("div");
|
|
actions.className = "actions";
|
|
|
|
const mkBtn = (label, onClick) => {
|
|
const b = document.createElement("button");
|
|
b.type = "button";
|
|
b.textContent = label;
|
|
b.addEventListener("click", onClick);
|
|
return b;
|
|
};
|
|
|
|
const pre = document.createElement("pre");
|
|
pre.className = "content";
|
|
pre.style.whiteSpace = "pre-wrap";
|
|
pre.style.marginTop = ".5rem";
|
|
|
|
actions.appendChild(mkBtn("View", () => viewPost(p, pre)));
|
|
actions.appendChild(mkBtn("Save blob", () => saveBlob(p)));
|
|
actions.appendChild(mkBtn("Delete (server)", () => delServer(p)));
|
|
actions.appendChild(mkBtn("Remove (local)", () => {
|
|
setPosts(getPosts().filter((x) => x.hash !== p.hash));
|
|
}));
|
|
|
|
wrap.appendChild(actions);
|
|
|
|
const contentWrap = document.createElement("div");
|
|
contentWrap.className = "content-wrap";
|
|
contentWrap.appendChild(pre);
|
|
wrap.appendChild(contentWrap);
|
|
|
|
root.appendChild(wrap);
|
|
}
|
|
}
|
|
|
|
// ---------- Save/Init ----------
|
|
async function onSaveConn(){
|
|
const c = { url: norm(els.shardUrl.value || defaultApiBase()), bearer: els.bearer.value.trim(), passphrase: els.passphrase.value };
|
|
saveCfg(c); flash("Saved");
|
|
updateLimitedUI(); await checkHealth(); await syncIndex(); sse(true); await renderAvatar();
|
|
}
|
|
async function panicWipe(){
|
|
flash("Wiping local state…");
|
|
try { const base = cfg.url || defaultApiBase(); if (base) await fetch(base + "/v1/session/clear", { method:"POST" }); } catch {}
|
|
localStorage.clear(); sessionStorage.clear(); caches?.keys?.().then(keys => keys.forEach(k => caches.delete(k)));
|
|
flash("Cleared — reloading"); setTimeout(()=>location.reload(), 300);
|
|
}
|
|
async function discordStart(){
|
|
const base = cfg.url || defaultApiBase(); if (!base){ alert("Set shard URL first."); return; }
|
|
const r = await fetch(base + "/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;
|
|
}
|
|
|
|
// ---------- Boot ----------
|
|
window.addEventListener("DOMContentLoaded", () => {
|
|
Object.assign(els, {
|
|
shardUrl:$("shardUrl"), bearer:$("bearer"), passphrase:$("passphrase"),
|
|
saveConn:$("saveConn"), health:$("health"), visibility:$("visibility"),
|
|
title:$("title"), body:$("body"), publish:$("publish"), publishStatus:$("publishStatus"),
|
|
posts:$("posts"), discordStart:$("discordStart"), signIn:$("signIn"), panic:$("panic"),
|
|
avatar:$("avatar"), fp:$("fp"), flash:$("flash"), banner:$("banner"),
|
|
feed:$("feed"), page:$("page"), pageContent:$("pageContent"),
|
|
shareUrl:$("shareUrl"), shareNote:$("shareNote"), shareVis:$("shareVis"),
|
|
sharePreview:$("sharePreview"), sharePublish:$("sharePublish"), shareCard:$("shareCard")
|
|
});
|
|
|
|
on(els.saveConn, "click", onSaveConn);
|
|
on(els.publish, "click", publish);
|
|
on(els.discordStart, "click", discordStart);
|
|
on(els.signIn, "click", deviceKeySignIn);
|
|
on(els.panic, "click", panicWipe);
|
|
|
|
on(els.sharePreview, "click", ()=>renderXCard(els.shareCard, sanitizeUrl(els.shareUrl.value), els.shareNote.value));
|
|
on(els.sharePublish, "click", publishShare);
|
|
|
|
window.addEventListener('hashchange', ()=>renderRoute(currentPath()));
|
|
|
|
if (!HAS_SUBTLE) {
|
|
const cap = $("capWarn");
|
|
if (cap){
|
|
cap.hidden=false;
|
|
cap.textContent = "This browser lacks secure WebCrypto. Device-key and members-encrypted posts require a modern browser over HTTPS. Discord sign-in remains available.";
|
|
}
|
|
if (els.signIn){ els.signIn.disabled = true; els.signIn.textContent = "Device key not supported"; }
|
|
}
|
|
|
|
applyCfg(); updateLimitedUI();
|
|
(async () => { await checkHealth(); await syncIndex(); sse(); await renderAvatar(); })();
|
|
renderRoute(currentPath());
|
|
flash("GC client loaded");
|
|
});
|