First Commit

This commit is contained in:
2025-08-21 20:56:38 -04:00
commit 9502d1b1be
29 changed files with 1667 additions and 0 deletions

183
client/app.js Normal file
View File

@@ -0,0 +1,183 @@
import { encryptString, decryptToString, toBlob } from "./crypto.js";
const els = {
shardUrl: document.getElementById("shardUrl"),
bearer: document.getElementById("bearer"),
passphrase: document.getElementById("passphrase"),
saveConn: document.getElementById("saveConn"),
health: document.getElementById("health"),
visibility: document.getElementById("visibility"),
title: document.getElementById("title"),
body: document.getElementById("body"),
publish: document.getElementById("publish"),
publishStatus: document.getElementById("publishStatus"),
posts: document.getElementById("posts"),
discordStart: document.getElementById("discordStart"),
};
const LS_KEY = "gc_client_config_v1";
const POSTS_KEY = "gc_posts_index_v1";
const cfg = loadConfig(); applyConfig(); checkHealth(); 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);
};
els.publish.onclick = publish;
els.discordStart.onclick = discordStart;
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 ?? location.origin; els.bearer.value = cfg.bearer ?? ""; els.passphrase.value = cfg.passphrase ?? ""; }
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 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";
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 });
setPosts(posts);
els.body.value = ""; msg(`Published ${enc?"private":"public"} post. Hash: ${j.hash}`);
} catch(e){ msg("Publish failed: " + (e?.message||e), true); }
}
function msg(t, err=false){ els.publishStatus.textContent=t; els.publishStatus.style.color = err ? "#ff6b6b" : "#8b949e"; }
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 });
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 })));
} catch(e){ console.warn("index sync failed", e); }
}
let sseCtrl;
function sse(restart=false){
if (!cfg.url) return;
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;
fetch(url, { 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 });
setPosts(posts);
}
} else if (ev.event === "delete") {
const h = ev.data.hash; setPosts(getPosts().filter(p => p.hash !== h));
}
} catch {}
}
}
}
}).catch(()=>{});
}
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">private</span>` : `<span class="badge">public</span>`;
div.innerHTML = `
<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>`;
const pre = div.querySelector(".content");
div.querySelector('[data-act="view"]').onclick = () => viewPost(p, pre);
div.querySelector('[data-act="save"]').onclick = () => saveBlob(p);
div.querySelector('[data-act="delete"]').onclick = () => delServer(p);
div.querySelector('[data-act="remove"]').onclick = () => { setPosts(getPosts().filter(x=>x.hash!==p.hash)); };
els.posts.appendChild(div);
}
}
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 });
if (!r.ok) throw new Error("fetch failed " + r.status);
const buf = new Uint8Array(await r.arrayBuffer());
let text;
if (p.enc) {
if (!cfg.passphrase) throw new Error("passphrase required");
text = await decryptToString(buf, cfg.passphrase);
} else { text = new TextDecoder().decode(buf); }
try {
const j = JSON.parse(text);
pre.textContent = (j.title ? `# ${j.title}\n\n` : "") + (j.body ?? text);
} catch { pre.textContent = text; }
} catch (e) { pre.textContent = "Error: " + (e?.message || e); }
}
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 });
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 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 });
if (!r.ok) return alert("delete failed " + r.status);
setPosts(getPosts().filter(x=>x.hash!==p.hash));
}
async function discordStart() {
if (!cfg.url) { alert("Set shard URL first."); return; }
// Require explicit assent for third-party auth
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; // redirect to Discord; after consent, it returns to /auth-callback.html
}

44
client/auth_callback.html Normal file
View File

@@ -0,0 +1,44 @@
<!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();
// Save token into client config
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();
</script>
</body>
</html>

36
client/crypto.js Normal file
View File

@@ -0,0 +1,36 @@
export async function deriveKey(passphrase, saltBytes) {
const enc = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey("raw", enc.encode(passphrase), { name: "PBKDF2" }, false, ["deriveKey"]);
return crypto.subtle.deriveKey(
{ name: "PBKDF2", salt: saltBytes, iterations: 120_000, hash: "SHA-256" },
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
export async function encryptString(plaintext, passphrase) {
const enc = new TextEncoder();
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await deriveKey(passphrase, salt);
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, enc.encode(plaintext));
const version = new Uint8Array([1]);
const out = new Uint8Array(1 + 16 + 12 + ct.byteLength);
out.set(version, 0); out.set(salt, 1); out.set(iv, 17); out.set(new Uint8Array(ct), 29);
return out;
}
export async function decryptToString(payload, passphrase) {
const dec = new TextDecoder();
if (!(payload instanceof Uint8Array)) payload = new Uint8Array(payload);
if (payload.length < 29) throw new Error("ciphertext too short");
if (payload[0] !== 1) throw new Error("unknown version");
const salt = payload.slice(1, 17), iv = payload.slice(17, 29), ct = payload.slice(29);
const key = await deriveKey(passphrase, salt);
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct);
return dec.decode(pt);
}
export function toBlob(data) {
if (data instanceof Uint8Array) return new Blob([data], { type: "application/octet-stream" });
return new Blob([data], { type: "application/json;charset=utf-8" });
}

69
client/index.html Normal file
View File

@@ -0,0 +1,69 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>GreenCoast — Client</title>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<link rel="stylesheet" href="./styles.css"/>
</head>
<body>
<div class="container">
<h1>GreenCoast (Client)</h1>
<section class="card">
<h2>Connect</h2>
<div class="row">
<label>Shard URL</label>
<input id="shardUrl" placeholder="http://localhost:8080" />
</div>
<div class="row">
<label>Bearer (optional)</label>
<input id="bearer" placeholder="dev-local-token" />
</div>
<div class="row">
<label>Passphrase (private posts)</label>
<input id="passphrase" type="password" placeholder="••••••••" />
</div>
<div class="row">
<label>3rd-party SSO</label>
<div>
<button id="discordStart">Sign in with Discord</button>
<div class="muted" style="margin-top:.4rem;">
We use external providers only if you choose to. We cannot vouch for their security.
</div>
</div>
</div>
<button id="saveConn">Save</button>
<div id="health" class="muted"></div>
</section>
<section class="card">
<h2>Compose</h2>
<div class="row">
<label>Visibility</label>
<select id="visibility">
<option value="public">Public (plaintext)</option>
<option value="private">Private (E2EE via passphrase)</option>
</select>
</div>
<div class="row">
<label>Title</label>
<input id="title" placeholder="Optional title"/>
</div>
<div class="row">
<label>Body</label>
<textarea id="body" rows="6" placeholder="Write your post..."></textarea>
</div>
<button id="publish">Publish</button>
<div id="publishStatus" class="muted"></div>
</section>
<section class="card">
<h2>Posts (live index)</h2>
<div id="posts"></div>
</section>
</div>
<script type="module" src="./app.js"></script>
</body>
</html>

18
client/styles.css Normal file
View File

@@ -0,0 +1,18 @@
:root { --bg:#0b1117; --card:#0f1621; --fg:#e6edf3; --muted:#8b949e; --accent:#2ea043; }
* { box-sizing: border-box; }
body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial; background:var(--bg); color:var(--fg); }
.container { max-width: 900px; margin: 2rem auto; padding: 0 1rem; }
h1 { font-size: 1.5rem; margin-bottom: 1rem; }
.card { background: var(--card); border-radius: 14px; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 8px 24px rgba(0,0,0,.3); }
h2 { margin-top: 0; font-size: 1.1rem; }
.row { display: grid; grid-template-columns: 160px 1fr; gap: .75rem; align-items: center; margin: .5rem 0; }
label { color: var(--muted); }
input, select, textarea { width: 100%; padding: .6rem .7rem; border-radius: 10px; border: 1px solid #233; background: #0b1520; color: var(--fg); }
button { background: var(--accent); color: #08130b; border: none; padding: .6rem .9rem; border-radius: 10px; cursor: pointer; font-weight: 700; }
button:hover { filter: brightness(1.05); }
.muted { color: var(--muted); margin-top: .5rem; font-size: .9rem; }
.post { border: 1px solid #1d2734; border-radius: 12px; padding: .75rem; margin: .5rem 0; background: #0c1824; }
.post .meta { font-size: .85rem; color: var(--muted); margin-bottom: .4rem; }
.post .actions { margin-top: .5rem; display:flex; gap:.5rem; }
code { background:#0a1320; padding:.15rem .35rem; border-radius:6px; }
.badge { font-size:.75rem; padding:.1rem .4rem; border-radius: 999px; background:#132235; color:#9fb7d0; margin-left:.5rem; }