Compare commits
3 Commits
fec7535c40
...
d87e9322b5
Author | SHA1 | Date | |
---|---|---|---|
d87e9322b5 | |||
6a274f4259 | |||
1f2d2cf30b |
@@ -0,0 +1,7 @@
|
||||
CF_TUNNEL_TOKEN=YOUR_CF_TUNNEL_TOKEN_HERE
|
||||
GC_DISCORD_CLIENT_ID=YOUR_DISCORD_CLIENT_ID_HERE
|
||||
GC_DISCORD_CLIENT_SECRET=YOUR_DISCORD_CLIENT_SECRET_HERE
|
||||
GC_DISCORD_REDIRECT_URI=YOUR_DISCORD_REDIRECT_URI_HERE
|
||||
GC_SIGNING_SECRET_HEX=YOUR_SIGNING_SECRET_HEXKEY_HERE
|
||||
GC_ALLOW_ANON_PLAINTEXT=true # Enable PlainText
|
||||
GC_DEV_ALLOW_UNAUTH=true # False when public
|
771
client/app.js
771
client/app.js
@@ -1,117 +1,18 @@
|
||||
import { encryptString, decryptToString, toBlob } from "./crypto.js";
|
||||
// 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); }
|
||||
|
||||
// ---- Trusted Types policy & safe HTML setter ----
|
||||
const ttPolicy = (() => {
|
||||
try {
|
||||
if (window.trustedTypes) {
|
||||
// Allow only our sanitized HTML chunks (legal pages). Strip scripts & inline handlers.
|
||||
return window.trustedTypes.createPolicy("gc", {
|
||||
createHTML: (s) =>
|
||||
s
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, "")
|
||||
.replace(/\son\w+=/gi, "") // remove inline event handlers
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
return null;
|
||||
})();
|
||||
function setHTML(el, html) {
|
||||
if (!el) return;
|
||||
if (ttPolicy) {
|
||||
el.innerHTML = ttPolicy.createHTML(html);
|
||||
} else {
|
||||
// Very defensive fallback if TT creation is blocked: render as plain text.
|
||||
el.textContent = html.replace(/<[^>]*>/g, "");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Hash routes map (SPA) ----
|
||||
const routes = {
|
||||
"/": "feed",
|
||||
"/privacy": "privacy.html",
|
||||
"/gdpr": "gdpr.html",
|
||||
"/terms": "terms.html"
|
||||
};
|
||||
|
||||
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"),
|
||||
});
|
||||
|
||||
// Buttons
|
||||
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);
|
||||
|
||||
// Route navigation (hash-based)
|
||||
document.querySelectorAll('a[data-route]').forEach(a=>{
|
||||
a.addEventListener('click', (e)=>{
|
||||
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; // allow new tab etc.
|
||||
// hash change will trigger render
|
||||
});
|
||||
});
|
||||
window.addEventListener('hashchange', ()=>renderRoute(currentPath()));
|
||||
|
||||
applyConfig();
|
||||
updateLimitedModeUI();
|
||||
init();
|
||||
renderRoute(currentPath());
|
||||
flash("GC client loaded");
|
||||
});
|
||||
|
||||
// ---------- init ----------
|
||||
async function init(){
|
||||
await checkHealth(); await syncIndex(); sse(); await renderAvatar();
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
function on(el, ev, fn){ if (el) el.addEventListener(ev, fn, false); }
|
||||
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 norm(u){ return (u||"").replace(/\/+$/,""); }
|
||||
function currentPath(){
|
||||
const h = location.hash || "#/";
|
||||
const p = h.replace(/^#/, "");
|
||||
return p || "/";
|
||||
}
|
||||
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||"/"; }
|
||||
|
||||
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 LS_KEY = "gc_client_config_v6";
|
||||
const POSTS_KEY = "gc_posts_index_v6";
|
||||
const KEY_PKCS8 = "gc_key_pkcs8";
|
||||
const KEY_PUB_RAW = "gc_key_pub_raw";
|
||||
|
||||
function loadConfig(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) ?? {}; } catch { return {}; } }
|
||||
const cfg = loadConfig();
|
||||
|
||||
function saveConfig(c){ localStorage.setItem(LS_KEY, JSON.stringify(Object.assign(cfg,c))); }
|
||||
function applyConfig(){
|
||||
if (!els.shardUrl) return;
|
||||
els.shardUrl.value = cfg.url ?? defaultApiBase();
|
||||
els.bearer.value = cfg.bearer ?? "";
|
||||
els.passphrase.value = cfg.passphrase ?? "";
|
||||
}
|
||||
function isAuthorized(){ return !!cfg.bearer; }
|
||||
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=>{
|
||||
@@ -119,154 +20,69 @@ function setActiveTab(path){
|
||||
a.classList.toggle("active", href===cur);
|
||||
});
|
||||
}
|
||||
function updateLimitedModeUI(){
|
||||
const limited = !isAuthorized();
|
||||
if (els.banner) els.banner.hidden = !limited;
|
||||
if (els.visibility){
|
||||
const priv = [...els.visibility.options].find(o => o.value === "private");
|
||||
if (priv) { priv.disabled = limited; if (limited && els.visibility.value === "private") els.visibility.value = "public"; }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- router (hash-based) ----------
|
||||
async function renderRoute(path){
|
||||
setActiveTab(path);
|
||||
const target = routes[path] ?? "feed";
|
||||
if (target === "feed"){
|
||||
els.page.hidden = true;
|
||||
els.feed.hidden = false;
|
||||
return;
|
||||
}
|
||||
// Load static page into #pageContent (Trusted Types aware)
|
||||
els.feed.hidden = true;
|
||||
els.page.hidden = false;
|
||||
setHTML(els.pageContent, "Loading…");
|
||||
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 m = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
|
||||
setHTML(els.pageContent, m ? m[1] : html);
|
||||
}catch{
|
||||
setHTML(els.pageContent, `<p class="muted">Failed to load page.</p>`);
|
||||
}
|
||||
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."); }
|
||||
}
|
||||
|
||||
// ---------- health / posts / SSE ----------
|
||||
async function checkHealth(){
|
||||
const base = cfg.url || defaultApiBase();
|
||||
if (!base) { if (els.health) els.health.textContent="Set URL"; return; }
|
||||
els.health.textContent="Checking…";
|
||||
try { const r = await fetch(base + "/healthz"); els.health.textContent = r.ok ? "Connected ✔" : `Error: ${r.status}`; }
|
||||
catch { els.health.textContent = "Not reachable"; }
|
||||
}
|
||||
function getPosts(){ try { return JSON.parse(localStorage.getItem(POSTS_KEY)) ?? []; } catch { return []; } }
|
||||
function setPosts(v){ localStorage.setItem(POSTS_KEY, JSON.stringify(v)); renderPosts(); }
|
||||
// ---------- 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";
|
||||
|
||||
async function syncIndex(){
|
||||
const base = cfg.url || defaultApiBase();
|
||||
if (!base) return;
|
||||
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 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, author:e.author||null, tz:e.creator_tz||null})));
|
||||
}catch(e){ console.warn("index sync failed", e); }
|
||||
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(/\/+$/,""); }
|
||||
}
|
||||
|
||||
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,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(()=>{});
|
||||
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 ?? "";
|
||||
}
|
||||
|
||||
// ---------- avatar (canvas PNG) ----------
|
||||
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; }
|
||||
function b64urlToJSON(b){ return JSON.parse(new TextDecoder().decode(b64uDecodeToBytes(b))); }
|
||||
function parseGC2(tok){ try{ const p=tok.split("."); if(p.length!==3) return {}; const pl=b64urlToJSON(p[1]); return {sub:pl.sub||"", cnf:pl.cnf||""}; }catch{ return {}; } }
|
||||
async function sha256Hex(str){ const out = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)); return Array.from(new Uint8Array(out)).map(b=>b.toString(16).padStart(2,"0")).join(""); }
|
||||
function hexBytes(hex){ const u=new Uint8Array(hex.length/2); for(let i=0;i<u.length;i++) u[i]=parseInt(hex.substr(i*2,2),16); return u; }
|
||||
function identiconPNG(hex, size=64){
|
||||
const cells=5, cell=Math.floor(size/cells), pad=Math.floor((size-cell*cells)/2);
|
||||
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);
|
||||
}
|
||||
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";
|
||||
}
|
||||
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"); if (els.fp) els.fp.textContent="(pseudonymous)"; return; }
|
||||
const hex=await sha256Hex(seed);
|
||||
els.avatar.onerror = ()=>{ els.avatar.removeAttribute("src"); if (els.fp) els.fp.textContent="(pseudonymous)"; };
|
||||
els.avatar.src=identiconPNG(hex, 64);
|
||||
if (els.fp) els.fp.textContent=label+" (pseudonymous)";
|
||||
}
|
||||
|
||||
// ---------- security / PoP ----------
|
||||
async function onSaveConn(){
|
||||
const c = { url: norm(els.shardUrl.value || defaultApiBase()), bearer: els.bearer.value.trim(), passphrase: els.passphrase.value };
|
||||
saveConfig(c); flash("Saved");
|
||||
updateLimitedModeUI(); 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;
|
||||
}
|
||||
// ---------- 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, pubRawB64u: pubRaw };
|
||||
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"]);
|
||||
@@ -274,10 +90,86 @@ async function getOrCreateKeyPair(){
|
||||
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, pubRawB64u: 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();
|
||||
@@ -290,16 +182,18 @@ async function deviceKeySignIn(){
|
||||
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();
|
||||
saveConfig({ bearer: vj.bearer }); applyConfig(); updateLimitedModeUI();
|
||||
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 = await crypto.subtle.digest("SHA-256", bodyBytes || new Uint8Array());
|
||||
const hex = Array.from(new Uint8Array(bodyHash)).map(b=>b.toString(16).padStart(2,"0")).join("");
|
||||
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);
|
||||
@@ -315,67 +209,206 @@ async function fetchWithPoP(url, opts){
|
||||
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"; }
|
||||
|
||||
// ---------- compose / posts ----------
|
||||
function msg(t, err=false){ els.publishStatus.textContent=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 title = els.title.value.trim(); const body = els.body.value; const vis = els.visibility.value;
|
||||
if (!isAuthorized() && vis === "private"){ msg("Private posts require authorizing this device. Publishing as public.", true); els.visibility.value = "public"; }
|
||||
|
||||
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, enc=false;
|
||||
if (els.visibility.value==="private"){
|
||||
if (!els.passphrase.value) return msg("Set a passphrase for private posts.", true);
|
||||
const payload = await encryptString(JSON.stringify({title,body}), els.passphrase.value);
|
||||
blob = toBlob(payload); enc=true;
|
||||
} else { blob = toBlob(JSON.stringify({title,body})); }
|
||||
const headers = {"Content-Type":"application/octet-stream"};
|
||||
if (enc) headers["X-GC-Private"]="1";
|
||||
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 r = await fetchWithPoP(base + "/v1/object", { method:"PUT", headers, body: blob });
|
||||
|
||||
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 || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc, author:j.author||null, tz:j.creator_tz||null });
|
||||
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 ${enc?"private":"public"} post. Hash: ${j.hash}`);
|
||||
els.body.value="";
|
||||
msg(`Published ${mode}. Hash: ${j.hash}`);
|
||||
}catch(e){ msg("Publish failed: "+(e?.message||e), true); }
|
||||
}
|
||||
function renderPosts(){
|
||||
const posts = getPosts(); if (!els.posts) return; 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>`;
|
||||
const tz = p.tz?` · tz:${p.tz}`:""; const who = p.author?` · by ${p.author.slice(0,8)}…`:"";
|
||||
div.innerHTML = `
|
||||
<div class="meta"><code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${p.ts}${tz}${who} ${badge}</div>
|
||||
<div class="actions">
|
||||
<button data-act="view" type="button">View</button>
|
||||
<button data-act="save" type="button">Save blob</button>
|
||||
<button data-act="delete" type="button">Delete (server)</button>
|
||||
<button data-act="remove" type="button">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 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());
|
||||
let text;
|
||||
if (p.enc){ if (!els.passphrase.value) throw new Error("passphrase required"); text = await decryptToString(buf, els.passphrase.value); }
|
||||
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; }
|
||||
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);
|
||||
@@ -390,3 +423,183 @@ async function delServer(p){
|
||||
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");
|
||||
});
|
||||
|
@@ -4,13 +4,9 @@
|
||||
<meta charset="utf-8"/>
|
||||
<title>GreenCoast — Client</title>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||
<!-- Hard-pin API host so mobiles pick the right shard -->
|
||||
<meta name="gc-api-base" content="https://api-gc.fullmooncyberworks.com">
|
||||
<link rel="stylesheet" href="./styles.css"/>
|
||||
<!-- Optional: pin API base -->
|
||||
<!-- <meta name="gc-api-base" content="https://api-gc.fullmooncyberworks.com"> -->
|
||||
<style>
|
||||
#flash{position:fixed;right:12px;bottom:12px;background:#0b1222;border:1px solid #1f2937;color:#e5e7eb;
|
||||
padding:.55rem .7rem;border-radius:.5rem;box-shadow:0 6px 18px rgba(0,0,0,.35);display:none;z-index:9999}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
@@ -28,11 +24,12 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="banner" class="banner" hidden>
|
||||
You are in <strong>anonymous (limited) mode</strong>. Only public text posts are available until you authorize this device.
|
||||
<div id="capWarn" class="warn is-hidden"></div>
|
||||
|
||||
<div id="banner" class="banner is-hidden">
|
||||
You are in <strong>anonymous (limited) mode</strong>. Only plaintext posts are available until you authorize this device.
|
||||
</div>
|
||||
|
||||
<!-- Three-column shell -->
|
||||
<div class="shell">
|
||||
<aside id="left" class="col">
|
||||
<section class="card">
|
||||
@@ -72,7 +69,7 @@
|
||||
<input id="bearer" type="password" placeholder="gc2 token" autocomplete="off"/>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Passphrase</label>
|
||||
<label>Passphrase (for Private-Encrypted)</label>
|
||||
<input id="passphrase" type="password" placeholder="••••••••" autocomplete="off"/>
|
||||
</div>
|
||||
<p class="muted small">
|
||||
@@ -85,13 +82,40 @@
|
||||
<div id="health" class="muted"></div>
|
||||
</section>
|
||||
|
||||
<!-- Cross-post -->
|
||||
<section class="card">
|
||||
<h2>Share (x-post, privacy-safe)</h2>
|
||||
<div class="row">
|
||||
<label>Link</label>
|
||||
<input id="shareUrl" placeholder="https://www.tiktok.com/@user/video/..." />
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Note</label>
|
||||
<input id="shareNote" placeholder="Optional caption…"/>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Visibility</label>
|
||||
<select id="shareVis">
|
||||
<option value="plaintext">Plaintext</option>
|
||||
<option value="members">Public-Encrypted (members)</option>
|
||||
<option value="private">Private-Encrypted (passphrase)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row">
|
||||
<button id="sharePreview" type="button">Preview</button>
|
||||
<button id="sharePublish" type="button">Publish link</button>
|
||||
</div>
|
||||
<div id="shareCard" class="xcard muted small"></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>
|
||||
<option value="plaintext">Plaintext (last resort)</option>
|
||||
<option value="members">Public-Encrypted (members)</option>
|
||||
<option value="private">Private-Encrypted (passphrase)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row">
|
||||
@@ -103,7 +127,7 @@
|
||||
<textarea id="body" rows="6" placeholder="Write your post..."></textarea>
|
||||
</div>
|
||||
<button id="publish" type="button">Publish</button>
|
||||
<div id="publishStatus" class="muted"></div>
|
||||
<div id="publishStatus" class="muted status"></div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
@@ -112,8 +136,7 @@
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Legal/other pages render here (SPA routing) -->
|
||||
<main id="page" class="col" hidden>
|
||||
<main id="page" class="col is-hidden">
|
||||
<section class="card">
|
||||
<div id="pageContent">Loading…</div>
|
||||
</section>
|
||||
@@ -122,7 +145,7 @@
|
||||
<aside id="right" class="col">
|
||||
<section class="card">
|
||||
<h3>About</h3>
|
||||
<p class="muted small">Zero-trust, E2EE optional, no analytics, no PII.</p>
|
||||
<p class="muted small">Welcome to GreenCoast, a privacy-focused social media site. Zero-trust, E2EE optional, no analytics, no PII.</p>
|
||||
</section>
|
||||
<section class="card">
|
||||
<h3>Legal</h3>
|
||||
@@ -141,7 +164,7 @@
|
||||
<a data-route href="#/terms">Terms</a>
|
||||
</footer>
|
||||
|
||||
<div id="flash"></div>
|
||||
<div id="flash" class="flash"></div>
|
||||
|
||||
<script type="module" src="./app.js"></script>
|
||||
</body>
|
||||
|
@@ -14,6 +14,7 @@ a:hover{text-decoration:underline}
|
||||
.actions button{margin-left:.5rem}
|
||||
button{background:#134e4a;border:1px solid #0f766e;color:white;border-radius:.6rem;padding:.45rem .7rem;cursor:pointer}
|
||||
button:hover{filter:brightness(1.05)}
|
||||
input[type="password"]{letter-spacing:.2em}
|
||||
|
||||
.tabs{display:flex;gap:.25rem;margin:0 .75rem}
|
||||
.tabs a{padding:.35rem .6rem;border:1px solid var(--border);border-radius:.5rem;background:var(--tab)}
|
||||
@@ -41,6 +42,29 @@ button:hover{filter:brightness(1.05)}
|
||||
|
||||
.footer{max-width:1100px;margin:1rem auto 2rem auto;padding:0 1rem;color:#94a3b8}
|
||||
|
||||
.flash{position:fixed;right:12px;bottom:12px;background:#0b1222;border:1px solid #1f2937;color:#e5e7eb;
|
||||
padding:.55rem .7rem;border-radius:.5rem;box-shadow:0 6px 18px rgba(0,0,0,.35);display:none;z-index:9999}
|
||||
.flash.visible{display:block}
|
||||
|
||||
.warn{background:#3b1d1d;border:1px solid #7f1d1d;color:#ffd7d7;padding:.6rem .8rem;border-radius:.6rem;margin:0 1rem 1rem}
|
||||
.banner{margin:0 1rem 1rem;padding:.6rem .8rem;border-radius:.6rem;background:#10212b;border:1px solid #1d3340;color:#dbeafe}
|
||||
|
||||
.is-hidden{display:none !important}
|
||||
.mt-4{margin-top:.4rem}
|
||||
|
||||
/* content presentation that was previously set via JS */
|
||||
.pre-content{white-space:pre-wrap;margin-top:.5rem}
|
||||
.status.error{color:#ff6b6b}
|
||||
.status.ok{color:#8b949e}
|
||||
|
||||
/* x-post chips */
|
||||
.xcard{border:1px solid #263444;border-radius:.5rem;padding:.6rem}
|
||||
.xrow{display:flex;gap:.5rem;align-items:center}
|
||||
.xpill{font-size:.85rem;border:1px solid #30445a;border-radius:999px;padding:.1rem .5rem}
|
||||
.xtitle{font-weight:600}
|
||||
.xmeta{opacity:.85;margin:.25rem 0}
|
||||
.xbtn{margin-top:.25rem}
|
||||
code{background:#0f172a;border:1px solid var(--border);border-radius:.35rem;padding:.05rem .35rem}
|
||||
@media (max-width: 980px){
|
||||
.shell{grid-template-columns:1fr;gap:.75rem}
|
||||
#left,#right{order:2}
|
||||
|
@@ -1,163 +1,241 @@
|
||||
// cmd/shard/main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"greencoast/internal/api"
|
||||
"greencoast/internal/index"
|
||||
"greencoast/internal/storage"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func getenvBool(key string, def bool) bool {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
type cfgPrivacy struct {
|
||||
AllowAnonPlaintext bool `yaml:"allow_anon_plaintext"`
|
||||
}
|
||||
type shardConfig struct {
|
||||
Privacy cfgPrivacy `yaml:"privacy"`
|
||||
}
|
||||
|
||||
func boolEnv(keys ...string) bool {
|
||||
for _, k := range keys {
|
||||
v := strings.ToLower(strings.TrimSpace(os.Getenv(k)))
|
||||
if v == "1" || v == "true" || v == "yes" || v == "on" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
return false
|
||||
}
|
||||
|
||||
func loadYAMLAllow(path string) bool {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return def
|
||||
return false
|
||||
}
|
||||
return b
|
||||
defer f.Close()
|
||||
var sc shardConfig
|
||||
if err := yaml.NewDecoder(f).Decode(&sc); err != nil {
|
||||
return false
|
||||
}
|
||||
return sc.Privacy.AllowAnonPlaintext
|
||||
}
|
||||
|
||||
func staticHeaders(next http.Handler) http.Handler {
|
||||
onion := os.Getenv("GC_ONION_LOCATION") // optional: e.g., http://xxxxxxxx.onion/
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Security headers + strict CSP (no inline) + COEP
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-site")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), interest-cohort=(), browsing-topics=()")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=15552000; includeSubDomains; preload")
|
||||
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
|
||||
// Allow only self + HTTPS for fetch/SSE; no inline styles/scripts
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self'; "+
|
||||
"style-src 'self'; "+
|
||||
"img-src 'self' data:; "+
|
||||
"connect-src 'self' https:; "+
|
||||
"frame-ancestors 'none'; object-src 'none'; base-uri 'none'; form-action 'self'; "+
|
||||
"require-trusted-types-for 'script'")
|
||||
if onion != "" {
|
||||
w.Header().Set("Onion-Location", onion)
|
||||
}
|
||||
/* -------------------------
|
||||
Minimal FS blob store (implements api.BlobStore)
|
||||
Layout:
|
||||
/var/lib/greencoast/objects/<hash> content
|
||||
/var/lib/greencoast/objects/<hash>.priv empty sidecar => private
|
||||
--------------------------*/
|
||||
|
||||
// Basic CORS for static (GET only effectively)
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
type fsStore struct {
|
||||
root string
|
||||
}
|
||||
|
||||
func newFSStore(root string) *fsStore { return &fsStore{root: root} }
|
||||
|
||||
func (s *fsStore) ensureRoot() error {
|
||||
// create both parent and leaf to be safe on fresh volumes
|
||||
if err := os.MkdirAll(filepath.Dir(s.root), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.MkdirAll(s.root, 0o755)
|
||||
}
|
||||
func (s *fsStore) pathFor(hash string) string { return filepath.Join(s.root, hash) }
|
||||
func (s *fsStore) privPathFor(hash string) string { return filepath.Join(s.root, hash+".priv") }
|
||||
|
||||
func (s *fsStore) Get(hash string) (io.ReadCloser, int64, error) {
|
||||
if err := s.ensureRoot(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
f, err := os.Open(s.pathFor(hash))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return f, st.Size(), nil
|
||||
}
|
||||
|
||||
func (s *fsStore) Put(r io.Reader, private bool) (string, int64, time.Time, error) {
|
||||
if err := s.ensureRoot(); err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp(s.root, "put-*")
|
||||
if err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() {
|
||||
// best-effort cleanup of temp path (original name)
|
||||
_ = os.Remove(tmpName)
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
w := io.MultiWriter(tmp, h)
|
||||
n, err := io.Copy(w, r)
|
||||
if err != nil {
|
||||
_ = tmp.Close()
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
// IMPORTANT on Windows bind mounts: flush & close before rename
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
hash := hex.EncodeToString(h.Sum(nil))
|
||||
final := s.pathFor(hash)
|
||||
|
||||
// If a previous file with this hash exists, remove it first (idempotent writes)
|
||||
_ = os.Remove(final)
|
||||
|
||||
if err := os.Rename(tmpName, final); err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
// Optional: fsync directory to harden the rename on some filesystems
|
||||
if df, err := os.Open(s.root); err == nil {
|
||||
_ = syscall.Fsync(int(df.Fd()))
|
||||
_ = df.Close()
|
||||
}
|
||||
|
||||
st, err := os.Stat(final)
|
||||
if err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
// create sidecar only after main content is durable
|
||||
if private {
|
||||
if err := os.WriteFile(s.privPathFor(hash), nil, 0o600); err != nil {
|
||||
_ = os.Remove(final)
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return hash, n, st.ModTime().UTC(), nil
|
||||
}
|
||||
|
||||
func (s *fsStore) Delete(hash string) error {
|
||||
if err := s.ensureRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(s.privPathFor(hash))
|
||||
return os.Remove(s.pathFor(hash))
|
||||
}
|
||||
|
||||
func (s *fsStore) Walk(fn func(hash string, bytes int64, private bool, storedAt time.Time) error) (int, error) {
|
||||
if err := s.ensureRoot(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ents, err := os.ReadDir(s.root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
count := 0
|
||||
for _, e := range ents {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
// skip sidecars and non-64-hex filenames
|
||||
if strings.HasSuffix(name, ".priv") || len(name) != 64 || !isHex(name) {
|
||||
continue
|
||||
}
|
||||
full := s.pathFor(name)
|
||||
st, err := os.Stat(full)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
private := false
|
||||
if _, err := os.Stat(s.privPathFor(name)); err == nil {
|
||||
private = true
|
||||
}
|
||||
if err := fn(name, st.Size(), private, st.ModTime().UTC()); err != nil {
|
||||
return count, err
|
||||
}
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func isHex(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/* -------------------------
|
||||
main
|
||||
--------------------------*/
|
||||
|
||||
func main() {
|
||||
// ---- Config ----
|
||||
httpAddr := os.Getenv("GC_HTTP_ADDR")
|
||||
if httpAddr == "" {
|
||||
httpAddr = ":9080"
|
||||
}
|
||||
httpsAddr := os.Getenv("GC_HTTPS_ADDR")
|
||||
certFile := os.Getenv("GC_TLS_CERT")
|
||||
keyFile := os.Getenv("GC_TLS_KEY")
|
||||
// Store & index
|
||||
store := newFSStore("/var/lib/greencoast/objects")
|
||||
idx := index.New()
|
||||
|
||||
staticAddr := os.Getenv("GC_STATIC_ADDR")
|
||||
if staticAddr == "" {
|
||||
staticAddr = ":9082"
|
||||
}
|
||||
staticDir := os.Getenv("GC_STATIC_DIR")
|
||||
if staticDir == "" {
|
||||
staticDir = "/opt/greencoast/client"
|
||||
}
|
||||
|
||||
dataDir := os.Getenv("GC_DATA_DIR")
|
||||
if dataDir == "" {
|
||||
dataDir = "/var/lib/greencoast"
|
||||
}
|
||||
|
||||
coarseTS := getenvBool("GC_COARSE_TS", true) // safer default (less precise metadata)
|
||||
zeroTrust := getenvBool("GC_ZERO_TRUST", true)
|
||||
encRequired := getenvBool("GC_ENCRYPTION_REQUIRED", true) // operator-blind by default
|
||||
requirePOP := getenvBool("GC_REQUIRE_POP", true) // logged only here
|
||||
|
||||
signingSecretHex := os.Getenv("GC_SIGNING_SECRET_HEX")
|
||||
if len(signingSecretHex) < 64 {
|
||||
log.Printf("WARN: GC_SIGNING_SECRET_HEX length=%d (need >=64 hex chars)", len(signingSecretHex))
|
||||
} else {
|
||||
log.Printf("GC_SIGNING_SECRET_HEX OK (len=%d)", len(signingSecretHex))
|
||||
}
|
||||
|
||||
discID := os.Getenv("GC_DISCORD_CLIENT_ID")
|
||||
discSecret := os.Getenv("GC_DISCORD_CLIENT_SECRET")
|
||||
discRedirect := os.Getenv("GC_DISCORD_REDIRECT_URI")
|
||||
|
||||
// ---- Storage & Index ----
|
||||
store, err := storage.NewFS(dataDir)
|
||||
if err != nil {
|
||||
log.Fatalf("storage init: %v", err)
|
||||
}
|
||||
ix := index.New()
|
||||
|
||||
// Reindex on boot from existing files (coarse time if enabled)
|
||||
if err := store.Walk(func(hash string, size int64, mod time.Time) error {
|
||||
when := mod.UTC()
|
||||
if coarseTS {
|
||||
when = when.Truncate(time.Minute)
|
||||
// Flags: env wins, else YAML (/app/shard.yaml), else false
|
||||
allowAnon := boolEnv("GC_ALLOW_ANON_PLAINTEXT")
|
||||
if !allowAnon {
|
||||
if st, err := os.Stat("/app/shard.yaml"); err == nil && !st.IsDir() {
|
||||
allowAnon = loadYAMLAllow("/app/shard.yaml")
|
||||
}
|
||||
return ix.Put(index.Entry{
|
||||
Hash: hash,
|
||||
Bytes: size,
|
||||
StoredAt: when.Format(time.RFC3339Nano),
|
||||
Private: false, // unknown here
|
||||
})
|
||||
}); err != nil {
|
||||
log.Printf("reindex on boot: %v", err)
|
||||
}
|
||||
devMode := boolEnv("GC_DEV_ALLOW_UNAUTH")
|
||||
|
||||
// ---- Auth providers ----
|
||||
providers := api.AuthProviders{
|
||||
SigningSecretHex: signingSecretHex,
|
||||
Discord: api.DiscordProvider{
|
||||
Enabled: discID != "" && discSecret != "" && discRedirect != "",
|
||||
ClientID: discID,
|
||||
ClientSecret: discSecret,
|
||||
RedirectURI: discRedirect,
|
||||
},
|
||||
}
|
||||
log.Printf("boot: privacy.allow_anon_plaintext=%v dev=%v at=%s", allowAnon, devMode, time.Now().UTC().Format(time.RFC3339))
|
||||
|
||||
// ---- API server ----
|
||||
srv := api.New(store, ix, coarseTS, zeroTrust, providers, encRequired)
|
||||
var providers api.AuthProviders
|
||||
srv := api.New(store, idx, true, devMode, providers, allowAnon)
|
||||
|
||||
// ---- Static file server (separate listener) ----
|
||||
// Frontend (static)
|
||||
go func() {
|
||||
fs := http.FileServer(http.Dir(staticDir))
|
||||
h := staticHeaders(fs)
|
||||
log.Printf("static listening on %s (dir=%s)", staticAddr, staticDir)
|
||||
if err := http.ListenAndServe(staticAddr, h); err != nil {
|
||||
log.Fatalf("static server: %v", err)
|
||||
if err := srv.ListenFrontend("0.0.0.0:9082"); err != nil {
|
||||
log.Printf("frontend server exited: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// ---- Start API (HTTP or HTTPS) ----
|
||||
if httpsAddr != "" && certFile != "" && keyFile != "" {
|
||||
log.Printf("API HTTPS %s POP:%v ENC_REQUIRED:%v", httpsAddr, requirePOP, encRequired)
|
||||
if err := srv.ListenHTTPS(httpsAddr, certFile, keyFile); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Printf("API HTTP %s POP:%v ENC_REQUIRED:%v", httpAddr, requirePOP, encRequired)
|
||||
if err := srv.ListenHTTP(httpAddr); err != nil {
|
||||
// API
|
||||
if err := srv.ListenHTTP("0.0.0.0:9080"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
@@ -1,32 +1,32 @@
|
||||
shard_id: "gc-test-001"
|
||||
|
||||
listen:
|
||||
http: "0.0.0.0:9080" # API for testers
|
||||
https: "" # if you terminate TLS at a proxy, leave empty
|
||||
ws: "0.0.0.0:9081" # reserved
|
||||
http: "0.0.0.0:9080"
|
||||
https: ""
|
||||
ws: "0.0.0.0:9081"
|
||||
|
||||
tls:
|
||||
enable: false # set true only if serving HTTPS directly here
|
||||
enable: false
|
||||
cert_file: "/etc/greencoast/tls/cert.pem"
|
||||
key_file: "/etc/greencoast/tls/key.pem"
|
||||
key_file: "/etc/greencoast/tls/key.pem"
|
||||
|
||||
federation:
|
||||
mtls_enable: false
|
||||
listen: "0.0.0.0:9443"
|
||||
cert_file: "/etc/greencoast/fed/cert.pem"
|
||||
key_file: "/etc/greencoast/fed/key.pem"
|
||||
key_file: "/etc/greencoast/fed/key.pem"
|
||||
client_ca_file: "/etc/greencoast/fed/clients_ca.pem"
|
||||
|
||||
ui:
|
||||
enable: true
|
||||
path: "./client"
|
||||
base_url: "/"
|
||||
frontend_http: "0.0.0.0:9082" # static client for testers
|
||||
frontend_http: "0.0.0.0:9082"
|
||||
|
||||
storage:
|
||||
backend: "fs"
|
||||
path: "/var/lib/greencoast/objects"
|
||||
max_object_kb: 128 # lower if you want to constrain uploads
|
||||
max_object_kb: 128
|
||||
|
||||
security:
|
||||
zero_trust: true
|
||||
@@ -38,27 +38,20 @@ privacy:
|
||||
retain_ip: "no"
|
||||
retain_user_agent: "no"
|
||||
retain_timestamps: "coarse"
|
||||
allow_anon_plaintext: true
|
||||
|
||||
auth:
|
||||
# IMPORTANT: rotate this per environment (use `openssl rand -hex 32`)
|
||||
signing_secret: "D941C4F91D0046D28CDBC3F425DE0B4EA26BD2A80434E0F160D1B7C813EB43F8"
|
||||
# Choose either YAML OR env for the signing secret — not both.
|
||||
# If you keep it here, make sure it's EXACTLY the same as the env value.
|
||||
signing_secret: GC_SIGNING_SECRET_HEX
|
||||
sso:
|
||||
discord:
|
||||
enabled: true
|
||||
client_id: "1408292766319906946"
|
||||
client_secret: "zJ6GnUUykHbMFbWsPPneNxNK-PtOXYg1"
|
||||
# must exactly match your Discord app's allowed redirect
|
||||
redirect_uri: "https://greencoast.fullmooncyberworks.com/auth-callback.html"
|
||||
google:
|
||||
enabled: false
|
||||
client_id: ""
|
||||
client_secret: ""
|
||||
redirect_uri: ""
|
||||
facebook:
|
||||
enabled: false
|
||||
client_id: ""
|
||||
client_secret: ""
|
||||
redirect_uri: ""
|
||||
client_id: GC_DISCORD_CLIENT_ID
|
||||
client_secret: GC_DISCORD_CLIENT_SECRET
|
||||
redirect_uri: GC_DISCORD_REDIRECT_URI
|
||||
google: { enabled: false, client_id: "", client_secret: "", redirect_uri: "" }
|
||||
facebook: { enabled: false, client_id: "", client_secret: "", redirect_uri: "" }
|
||||
two_factor:
|
||||
webauthn_enabled: false
|
||||
totp_enabled: false
|
||||
@@ -66,4 +59,4 @@ auth:
|
||||
limits:
|
||||
rate:
|
||||
burst: 20
|
||||
per_minute: 60 # slightly tighter for external testing
|
||||
per_minute: 60
|
||||
|
@@ -1,18 +1,14 @@
|
||||
version: "3.9"
|
||||
|
||||
services:
|
||||
shard-test:
|
||||
build: .
|
||||
env_file:
|
||||
- .env
|
||||
container_name: greencoast-shard-test
|
||||
restart: unless-stopped
|
||||
user: "0:0"
|
||||
# These ports are optional (useful for local debug). Tunnel doesn't need them.
|
||||
ports:
|
||||
- "9080:9080" # API
|
||||
- "9082:9082" # Frontend
|
||||
environment:
|
||||
- GC_DEV_ALLOW_UNAUTH=true
|
||||
- GC_SIGNING_SECRET_HEX=92650f92d67d55368c852713a5007b90d933bff507bc77c980de7bf5442844ca
|
||||
- "9080:9080"
|
||||
- "9082:9082"
|
||||
volumes:
|
||||
- ./testdata:/var/lib/greencoast
|
||||
- ./configs/shard.test.yaml:/app/shard.yaml:ro
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -2,28 +2,75 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// secureHeaders adds strict, privacy-preserving headers to static responses.
|
||||
func (s *Server) secureHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
// ListenFrontend serves the static client from s.StaticDir on a separate port (e.g. :9082).
|
||||
func (s *Server) ListenFrontend(addr string) error {
|
||||
root := s.StaticDir
|
||||
if root == "" {
|
||||
root = "./client"
|
||||
}
|
||||
// Basic security/CSP headers for static content.
|
||||
addCommonHeaders := func(w http.ResponseWriter) {
|
||||
// CORS: static site can be embedded by any origin if you want, keep strict by default
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-site")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), interest-cohort=(), browsing-topics=()")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=15552000; includeSubDomains; preload")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// MountStatic mounts a static file server under a prefix onto the provided mux.
|
||||
// Usage (from main): s.MountStatic(mux, "/", http.Dir(staticDir))
|
||||
func (s *Server) MountStatic(mux *http.ServeMux, prefix string, fs http.FileSystem) {
|
||||
if prefix == "" {
|
||||
prefix = "/"
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
// Cache: avoid caching during test
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
// CSP: no inline scripts/styles; allow XHR/SSE/Ws to any (tunnel/api) host
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
strings.Join([]string{
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src *",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
}, "; "),
|
||||
)
|
||||
}
|
||||
h := http.StripPrefix(prefix, http.FileServer(fs))
|
||||
mux.Handle(prefix, s.secureHeaders(h))
|
||||
|
||||
// File handler with index.html fallback for “/”.
|
||||
fileServer := http.FileServer(http.Dir(root))
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
addCommonHeaders(w)
|
||||
|
||||
// Serve index.html at root or when requesting a directory.
|
||||
p := r.URL.Path
|
||||
if p == "/" || p == "" {
|
||||
http.ServeFile(w, r, filepath.Join(root, "index.html"))
|
||||
return
|
||||
}
|
||||
|
||||
// If path maps to a directory, try its index.html.
|
||||
full := filepath.Join(root, filepath.Clean(strings.TrimPrefix(p, "/")))
|
||||
if st, err := os.Stat(full); err == nil && st.IsDir() {
|
||||
indexFile := filepath.Join(full, "index.html")
|
||||
if _, err := os.Stat(indexFile); err == nil {
|
||||
http.ServeFile(w, r, indexFile)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Normal static file.
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
return srv.ListenAndServe()
|
||||
}
|
||||
|
@@ -1,240 +1,151 @@
|
||||
package storage
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FSStore struct {
|
||||
root string
|
||||
objects string
|
||||
// SimpleFSStore is a minimal FS-backed implementation of BlobStore.
|
||||
// Layout under root:
|
||||
//
|
||||
// <root>/<hash> - content
|
||||
// <root>/<hash>.priv - presence means "private"
|
||||
type SimpleFSStore struct {
|
||||
root string
|
||||
}
|
||||
|
||||
func NewFS(dir string) (*FSStore, error) {
|
||||
if dir == "" {
|
||||
return nil, errors.New("empty storage dir")
|
||||
}
|
||||
o := filepath.Join(dir, "objects")
|
||||
if err := os.MkdirAll(o, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &FSStore{root: dir, objects: o}, nil
|
||||
func NewSimpleFSStore(root string) *SimpleFSStore {
|
||||
return &SimpleFSStore{root: root}
|
||||
}
|
||||
|
||||
func (s *FSStore) pathFlat(hash string) (string, error) {
|
||||
if hash == "" {
|
||||
return "", errors.New("empty hash")
|
||||
}
|
||||
return filepath.Join(s.objects, hash), nil
|
||||
func (fs *SimpleFSStore) ensureRoot() error {
|
||||
return os.MkdirAll(fs.root, 0o755)
|
||||
}
|
||||
|
||||
func isHexHash(name string) bool {
|
||||
if len(name) != 64 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < 64; i++ {
|
||||
c := name[i]
|
||||
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
func (fs *SimpleFSStore) pathFor(hash string) string {
|
||||
return filepath.Join(fs.root, hash)
|
||||
}
|
||||
func (fs *SimpleFSStore) privPathFor(hash string) string {
|
||||
return filepath.Join(fs.root, hash+".priv")
|
||||
}
|
||||
|
||||
func (s *FSStore) findBlobPath(hash string) (string, error) {
|
||||
if hash == "" {
|
||||
return "", errors.New("empty hash")
|
||||
}
|
||||
// 1) flat
|
||||
if p, _ := s.pathFlat(hash); fileExists(p) {
|
||||
return p, nil
|
||||
}
|
||||
// 2) objects/<hash>/{blob,data,content}
|
||||
dir := filepath.Join(s.objects, hash)
|
||||
for _, cand := range []string{"blob", "data", "content"} {
|
||||
p := filepath.Join(dir, cand)
|
||||
if fileExists(p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
// 3) objects/<hash>/<single file>
|
||||
if st, err := os.Stat(dir); err == nil && st.IsDir() {
|
||||
ents, _ := os.ReadDir(dir)
|
||||
var picked string
|
||||
var pickedMod time.Time
|
||||
for _, de := range ents {
|
||||
if de.IsDir() {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, de.Name())
|
||||
fi, err := os.Stat(p)
|
||||
if err == nil && fi.Mode().IsRegular() {
|
||||
if picked == "" || fi.ModTime().After(pickedMod) {
|
||||
picked, pickedMod = p, fi.ModTime()
|
||||
}
|
||||
}
|
||||
}
|
||||
if picked != "" {
|
||||
return picked, nil
|
||||
}
|
||||
}
|
||||
// 4) two-level prefix objects/aa/<hash>
|
||||
if len(hash) >= 2 {
|
||||
p := filepath.Join(s.objects, hash[:2], hash)
|
||||
if fileExists(p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
// 5) recursive search
|
||||
var best string
|
||||
var bestMod time.Time
|
||||
_ = filepath.WalkDir(s.objects, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
base := filepath.Base(p)
|
||||
if base == hash {
|
||||
best = p
|
||||
return fs.SkipDir
|
||||
}
|
||||
parent := filepath.Base(filepath.Dir(p))
|
||||
if parent == hash {
|
||||
if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() {
|
||||
if best == "" || fi.ModTime().After(bestMod) {
|
||||
best, bestMod = p, fi.ModTime()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if best != "" {
|
||||
return best, nil
|
||||
}
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
|
||||
func fileExists(p string) bool {
|
||||
fi, err := os.Stat(p)
|
||||
return err == nil && fi.Mode().IsRegular()
|
||||
}
|
||||
|
||||
func (s *FSStore) Put(hash string, r io.Reader) error {
|
||||
p, err := s.pathFlat(hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
f, err := os.Create(tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, werr := io.Copy(f, r)
|
||||
cerr := f.Close()
|
||||
if werr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return werr
|
||||
}
|
||||
if cerr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return cerr
|
||||
}
|
||||
return os.Rename(tmp, p)
|
||||
}
|
||||
|
||||
func (s *FSStore) Get(hash string) (io.ReadCloser, int64, error) {
|
||||
p, err := s.findBlobPath(hash)
|
||||
if err != nil {
|
||||
// Get implements BlobStore.Get
|
||||
func (fs *SimpleFSStore) Get(hash string) (io.ReadCloser, int64, error) {
|
||||
if err := fs.ensureRoot(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
f, err := os.Open(p)
|
||||
f, err := os.Open(fs.pathFor(hash))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
return f, 0, nil
|
||||
_ = f.Close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return f, st.Size(), nil
|
||||
}
|
||||
|
||||
func (s *FSStore) Delete(hash string) error {
|
||||
if p, _ := s.pathFlat(hash); fileExists(p) {
|
||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
// Put implements BlobStore.Put
|
||||
func (fs *SimpleFSStore) Put(r io.Reader, private bool) (string, int64, time.Time, error) {
|
||||
if err := fs.ensureRoot(); err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
tmp, err := os.CreateTemp(fs.root, "put-*")
|
||||
if err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
w := io.MultiWriter(tmp, h)
|
||||
|
||||
n, err := io.Copy(w, r)
|
||||
if err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
hash := hex.EncodeToString(h.Sum(nil))
|
||||
|
||||
final := fs.pathFor(hash)
|
||||
if err := os.Rename(tmp.Name(), final); err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
|
||||
if private {
|
||||
if err := os.WriteFile(fs.privPathFor(hash), nil, 0o600); err != nil {
|
||||
_ = os.Remove(final)
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
}
|
||||
dir := filepath.Join(s.objects, hash)
|
||||
for _, cand := range []string{"blob", "data", "content"} {
|
||||
p := filepath.Join(dir, cand)
|
||||
if fileExists(p) {
|
||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
st, err := os.Stat(final)
|
||||
if err != nil {
|
||||
return "", 0, time.Time{}, err
|
||||
}
|
||||
if len(hash) >= 2 {
|
||||
p := filepath.Join(s.objects, hash[:2], hash)
|
||||
if fileExists(p) {
|
||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if p, err := s.findBlobPath(hash); err == nil {
|
||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return hash, n, st.ModTime().UTC(), nil
|
||||
}
|
||||
|
||||
func (s *FSStore) Walk(fn func(hash string, size int64, mod time.Time) error) error {
|
||||
type rec struct {
|
||||
size int64
|
||||
mod time.Time
|
||||
// Delete implements BlobStore.Delete
|
||||
func (fs *SimpleFSStore) Delete(hash string) error {
|
||||
if err := fs.ensureRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
agg := make(map[string]rec)
|
||||
_ = filepath.WalkDir(s.objects, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
fi, err := os.Stat(p)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
base := filepath.Base(p)
|
||||
if isHexHash(base) {
|
||||
if r, ok := agg[base]; !ok || fi.ModTime().After(r.mod) {
|
||||
agg[base] = rec{fi.Size(), fi.ModTime()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
parent := filepath.Base(filepath.Dir(p))
|
||||
if isHexHash(parent) {
|
||||
if r, ok := agg[parent]; !ok || fi.ModTime().After(r.mod) {
|
||||
agg[parent] = rec{fi.Size(), fi.ModTime()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(base) == 64 && isHexHash(strings.ToLower(base)) {
|
||||
if r, ok := agg[base]; !ok || fi.ModTime().After(r.mod) {
|
||||
agg[base] = rec{fi.Size(), fi.ModTime()}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
for h, r := range agg {
|
||||
if err := fn(h, r.size, r.mod); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
_ = os.Remove(fs.privPathFor(hash))
|
||||
return os.Remove(fs.pathFor(hash))
|
||||
}
|
||||
|
||||
// Walk implements BlobStore.Walk
|
||||
func (fs *SimpleFSStore) Walk(fn func(hash string, bytes int64, private bool, storedAt time.Time) error) (int, error) {
|
||||
if err := fs.ensureRoot(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ents, err := os.ReadDir(fs.root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
count := 0
|
||||
for _, e := range ents {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
// skip sidecars and non-64-hex filenames
|
||||
if strings.HasSuffix(name, ".priv") || len(name) != 64 || !isHex(name) {
|
||||
continue
|
||||
}
|
||||
full := fs.pathFor(name)
|
||||
st, err := os.Stat(full)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
private := false
|
||||
if _, err := os.Stat(fs.privPathFor(name)); err == nil {
|
||||
private = true
|
||||
}
|
||||
if err := fn(name, st.Size(), private, st.ModTime().UTC()); err != nil {
|
||||
return count, err
|
||||
}
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func isHex(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if !((c >= '0' && c <= '9') ||
|
||||
(c >= 'a' && c <= 'f') ||
|
||||
(c >= 'A' && c <= 'F')) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
Reference in New Issue
Block a user