Updated the README

Added new security layers
This commit is contained in:
2025-08-22 12:39:51 -04:00
parent fb7428064f
commit 720c7e0b52
7 changed files with 695 additions and 552 deletions

View File

@@ -1,38 +1,5 @@
import { encryptString, decryptToString, toBlob } from "./crypto.js";
// ---- Helpers ----
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(/\/+$/, "");
}
}
const LOCAL_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
// ---- DOM refs ----
const els = {
shardUrl: document.getElementById("shardUrl"),
bearer: document.getElementById("bearer"),
@@ -46,109 +13,148 @@ const els = {
publishStatus: document.getElementById("publishStatus"),
posts: document.getElementById("posts"),
discordStart: document.getElementById("discordStart"),
shareTZ: document.getElementById("shareTZ"),
};
// ---- Config + state ----
const LS_KEY = "gc_client_config_v1";
const POSTS_KEY = "gc_posts_index_v1";
let sseCtrl = null;
const DEVKEY_KEY = "gc_device_key_v1"; // stores p256 private/public (pkcs8/spki b64)
// ---- Boot ----
const cfg = loadConfig();
applyConfig();
checkHealth();
syncIndex();
sse();
// ---- Storage helpers ----
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 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 fmtWhen(ts, tz) {
function defaultApiBase() {
try {
return new Intl.DateTimeFormat(undefined, { dateStyle:"medium", timeStyle:"short", timeZone: tz }).format(new Date(ts));
} catch { return ts; }
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 applyConfig() {
if (!cfg.url) {
const detected = defaultApiBase();
cfg.url = detected;
try { localStorage.setItem(LS_KEY, JSON.stringify(cfg)); } catch {}
}
els.shardUrl.value = cfg.url;
els.bearer.value = cfg.bearer ?? "";
els.passphrase.value = cfg.passphrase ?? "";
}
const cfg = loadConfig(); applyConfig(); (async () => {
await ensureDeviceKey();
await checkHealth(); await syncIndex(); 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(); sse(true);
saveConfig(c);
await checkHealth(); await syncIndex(); sse(true);
};
els.publish.onclick = publish;
els.discordStart.onclick = discordStart;
async function checkHealth() {
if (!cfg.url) { els.health.textContent = "No API base set"; return; }
els.health.textContent = "Checking…";
try {
const r = await fetch(cfg.url + "/healthz", { mode:"cors" });
els.health.textContent = r.ok ? "Connected ✔" : `Error: ${r.status}`;
} catch (e) {
els.health.textContent = "Not reachable";
}
}
// -------- local state helpers --------
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;
try {
let blob, enc=false;
if (vis === "private") {
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;
} else {
blob = toBlob(JSON.stringify({ title, body }));
}
const headers = { "Content-Type":"application/octet-stream" };
if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
if (enc) headers["X-GC-Private"] = "1";
if (els.shareTZ && els.shareTZ.checked && LOCAL_TZ) headers["X-GC-TZ"] = LOCAL_TZ; // NEW
const r = await fetch(cfg.url + "/v1/object", { 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 || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc, creator_tz: j.creator_tz || "" });
setPosts(posts);
els.body.value = ""; msg(`Published ${enc?"private":"public"} post. Hash: ${j.hash}`);
} catch(e){ msg("Publish failed: " + (e?.message||e), true); }
}
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 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"; }
// Prefer session bearer
function getBearer() { return sessionStorage.getItem("gc_bearer") || cfg.bearer || ""; }
// -------- device key (P-256) + PoP --------
async function ensureDeviceKey() {
try {
const stored = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "null");
if (stored && stored.priv && stored.pub) return;
} catch {}
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); // 65-byte uncompressed
const b64pk = b64(rawPub);
const b64sk = b64(pkcs8);
localStorage.setItem(DEVKEY_KEY, JSON.stringify({ priv: b64sk, pub: b64pk, alg: "p256" }));
}
async function getDevicePriv() {
const s = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "{}");
if (s.alg !== "p256") throw new Error("unsupported alg");
const pkcs8 = ub64(s.priv);
return crypto.subtle.importKey("pkcs8", pkcs8, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
}
function getDevicePubHdr() {
const s = JSON.parse(localStorage.getItem(DEVKEY_KEY) || "{}");
if (!s.pub) return "";
return s.alg === "p256" ? ("p256:" + s.pub) : "";
}
async function popHeaders(method, url, body) {
const ts = Math.floor(Date.now()/1000).toString();
const pub = getDevicePubHdr();
const digest = await sha256Hex(body || new Uint8Array());
const msg = (method.toUpperCase()+"\n"+url+"\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)) };
}
async function fetchAPI(path, opts = {}, bodyBytes) {
if (!cfg.url) throw new Error("Set shard URL first.");
const url = cfg.url + path;
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, url, bodyBytes);
Object.assign(headers, pop);
const init = Object.assign({}, opts, { method, headers, body: opts.body });
const r = await fetch(url, init);
return r;
}
// -------- 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"; }
}
async function syncIndex() {
if (!cfg.url) return;
try {
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
const r = await fetch(cfg.url + "/v1/index", { headers });
const r = await fetchAPI("/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, creator_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); }
}
function sse(forceRestart=false){
let sseCtrl;
function sse(restart){
if (!cfg.url) return;
if (sseCtrl) { sseCtrl.abort(); sseCtrl = null; }
if (sseCtrl) { sseCtrl.abort(); sseCtrl = undefined; }
sseCtrl = new AbortController();
const url = cfg.url + "/v1/index/stream";
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
const headers = {};
const b = getBearer(); if (b) headers["Authorization"] = "Bearer " + b;
headers["X-GC-Key"] = getDevicePubHdr();
headers["X-GC-TS"] = Math.floor(Date.now()/1000).toString();
headers["X-GC-Proof"] = "dummy"; // server ignores body hash for GET; proof not required for initial request in this demo SSE; if required, switch to EventSource polyfill
fetch(url, { headers, signal: sseCtrl.signal }).then(async resp => {
if (!resp.ok) return;
const reader = resp.body.getReader(); const decoder = new TextDecoder();
@@ -166,7 +172,7 @@ function sse(forceRestart=false){
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, creator_tz: e.creator_tz || "" });
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") {
@@ -179,11 +185,39 @@ function sse(forceRestart=false){
}).catch(()=>{});
}
// -------- actions --------
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;
try {
let blob, enc=false;
if (vis === "private") {
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;
} 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());
const pop = await popHeaders("PUT", cfg.url + "/v1/object", bodyBytes);
Object.assign(headers, pop);
const r = await fetch(cfg.url + "/v1/object", { 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 || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc:j.private, tz:j.creator_tz });
setPosts(posts);
els.body.value = ""; msg(`Published ${enc?"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 headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
const r = await fetch(cfg.url + "/v1/object/" + p.hash, { headers });
const r = await fetchAPI("/v1/object/" + p.hash);
if (!r.ok) throw new Error("fetch failed " + r.status);
const buf = new Uint8Array(await r.arrayBuffer());
let text;
@@ -199,8 +233,7 @@ async function viewPost(p, pre) {
}
async function saveBlob(p) {
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
const r = await fetch(cfg.url + "/v1/object/" + p.hash, { headers });
const r = await fetchAPI("/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);
@@ -208,42 +241,48 @@ async function saveBlob(p) {
}
async function delServer(p) {
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
if (!confirm("Delete blob from server by hash?")) return;
const r = await fetch(cfg.url + "/v1/object/" + p.hash, { method:"DELETE", headers });
const r = await fetchAPI("/v1/object/" + p.hash, { method:"DELETE" });
if (!r.ok) return alert("delete failed " + r.status);
setPosts(getPosts().filter(x=>x.hash!==p.hash));
}
async function discordStart() {
if (!cfg.url) {
const derived = defaultApiBase();
if (derived) {
cfg.url = derived; try { localStorage.setItem(LS_KEY, JSON.stringify(cfg)); } catch {}
els.shardUrl.value = derived;
}
}
if (!cfg.url) { alert("Set shard URL first."); return; }
const r = await fetch(cfg.url + "/v1/auth/discord/start", { headers: { "X-GC-3P-Assent":"1" }});
const headers = { "X-GC-3P-Assent":"1", "X-GC-Key": getDevicePubHdr() };
const r = await fetch(cfg.url + "/v1/auth/discord/start", { headers });
if (!r.ok) { alert("Discord SSO not available"); return; }
const j = await r.json();
location.href = j.url;
}
// Optional: Key-based login (no OAuth)
async function signInWithDeviceKey(){
if (!cfg.url) { alert("Set shard URL first."); return; }
const c = await fetch(cfg.url + "/v1/auth/key/challenge", { method:"POST" }).then(r=>r.json());
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));
const body = JSON.stringify({ nonce:c.nonce, alg:"p256", pub: getDevicePubHdr().slice("p256:".length), sig: b64(new Uint8Array(sig)) });
const r = await fetch(cfg.url + "/v1/auth/key/verify", { method:"POST", headers:{ "Content-Type":"application/json" }, body });
if (!r.ok) { alert("Key sign-in failed"); return; }
const j = await r.json();
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));
alert("Signed in");
}
// -------- render --------
function renderPosts() {
const posts = getPosts(); els.posts.innerHTML = "";
for (const p of posts) {
const localStr = fmtWhen(p.ts, LOCAL_TZ) + ` (${LOCAL_TZ})`;
let creatorStr = "";
if (p.creator_tz && p.creator_tz !== LOCAL_TZ) {
creatorStr = ` · creator: ${fmtWhen(p.ts, p.creator_tz)} (${p.creator_tz})`;
}
const div = document.createElement("div"); div.className = "post";
const badge = p.enc ? `<span class="badge">private</span>` : `<span class="badge">public</span>`;
const tsLocal = new Date(p.ts).toLocaleString();
const tz = p.tz ? ` · author TZ: ${p.tz}` : "";
div.innerHTML = `
<div class="meta">
<code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${localStr}${creatorStr} ${badge}
</div>
<div class="meta"><code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${tsLocal}${tz} ${badge}</div>
<div class="actions">
<button data-act="view">View</button>
<button data-act="save">Save blob</button>
@@ -259,3 +298,27 @@ function renderPosts() {
els.posts.appendChild(div);
}
}
// -------- utils --------
function b64(buf){ return base64url(buf); }
function ub64(s){ return base64urlDecode(s); }
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("");
}
// minimal base64url helpers
function base64url(buf){
let b = (buf instanceof Uint8Array) ? buf : new Uint8Array(buf);
let str = "";
for (let i=0; i<b.length; i++) str += String.fromCharCode(b[i]);
return btoa(str).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");
}
function base64urlDecode(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;
}

View File

@@ -1,43 +1,20 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>GreenCoast — Auth Callback</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial; background:#0b1117; color:#e6edf3; display:flex; align-items:center; justify-content:center; height:100vh; }
.card { background:#0f1621; padding:1rem 1.2rem; border-radius:14px; max-width:560px; }
.muted{ color:#8b949e; }
</style>
</head>
<body>
<div class="card">
<h3>Signing you in…</h3>
<div id="msg" class="muted">Please wait.</div>
</div>
<script type="module">
const params = new URLSearchParams(location.search);
const code = params.get("code");
const origin = location.origin; // shard and client served together
const msg = (t)=>document.getElementById("msg").textContent = t;
async function run() {
if (!code) { msg("Missing 'code' parameter."); return; }
try {
const r = await fetch(origin + "/v1/auth/discord/callback?assent=1&code=" + encodeURIComponent(code));
if (!r.ok) { msg("Exchange failed: " + r.status); return; }
const j = await r.json();
const key = "gc_client_config_v1";
const cfg = JSON.parse(localStorage.getItem(key) || "{}");
cfg.bearer = j.token;
localStorage.setItem(key, JSON.stringify(cfg));
msg("Success. Redirecting…");
setTimeout(()=>location.href="/", 800);
} catch(e) {
msg("Error: " + (e?.message || e));
}
}
run();
<meta charset="utf-8">
<title>Signing you in…</title>
<script>
(function(){
const hash = new URLSearchParams(location.hash.slice(1));
const bearer = hash.get("bearer");
const next = hash.get("next") || "/";
try {
// Prefer sessionStorage; keep localStorage for backward compatibility
if (bearer) sessionStorage.setItem("gc_bearer", bearer);
const k = "gc_client_config_v1";
const cfg = JSON.parse(localStorage.getItem(k) || "{}");
if (bearer) cfg.bearer = bearer;
localStorage.setItem(k, JSON.stringify(cfg));
} catch {}
history.replaceState(null, "", next);
location.href = next;
})();
</script>
</body>
</html>