Compare commits
10 Commits
fb7428064f
...
EndUserEnh
Author | SHA1 | Date | |
---|---|---|---|
d87e9322b5 | |||
6a274f4259 | |||
1f2d2cf30b | |||
fec7535c40 | |||
0bf00e3f00 | |||
5dfc710ae9 | |||
5067913c21 | |||
b9fad16fa2 | |||
0ff358552c | |||
720c7e0b52 |
@@ -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
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -23,3 +23,4 @@ data/
|
|||||||
# Env/config overrides
|
# Env/config overrides
|
||||||
shard.yaml
|
shard.yaml
|
||||||
.env
|
.env
|
||||||
|
testdata/*
|
236
README.md
236
README.md
@@ -1,24 +1,224 @@
|
|||||||
# GreenCoast — Privacy-First, Shardable Social (Dockerized)
|
# GreenCoast
|
||||||
|
|
||||||
**Goal:** A BlueSky-like experience with **shards**, **zero-trust**, **no data collection**, **E2EE**, and easy self-hosting — from x86_64 down to **Raspberry Pi Zero**.
|
A privacy-first, shardable social backend + minimalist client. **Zero PII**, **zero passwords**, optional **E2EE per post**, and **public-key accounts**. Includes **DPoP-style proof-of-possession**, **Discord SSO with PKCE**, and a tiny static client.
|
||||||
License: **The Unlicense** (public-domain equivalent).
|
|
||||||
|
|
||||||
This repo contains a minimal, working **shard**: an append-only object API with zero-data-collection defaults. It’s structured to evolve into full federation, E2EE, and client apps, while keeping Pi Zero as a supported host.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start (Laptop / Dev)
|
## Features
|
||||||
|
|
||||||
**Requirements:** Docker + Compose v2
|
- **Zero-trust by design**: server stores no emails or passwords.
|
||||||
|
- **Accounts = public keys** (Ed25519 or P-256). No usernames required.
|
||||||
|
- **Proof-of-possession (PoP)** on every authenticated API call.
|
||||||
|
- **Short-lived tokens** (HMAC “gc2”) bound to device keys.
|
||||||
|
- **Shardable storage** (mTLS or signed shard requests).
|
||||||
|
- **No fingerprinting**: no IP/UA logs; coarse timestamps optional.
|
||||||
|
- **Static client** with strong CSP; optional E2EE per post.
|
||||||
|
- **Discord SSO (PKCE)** as an *optional* convenience.
|
||||||
|
- **Filesystem storage** supports both **flat** and **nested** object layouts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture (brief)
|
||||||
|
|
||||||
|
- **Shard**: stateless API + local FS object store + in-memory index.
|
||||||
|
- **Client**: static files (HTML/JS/CSS) served by the shard or any static host.
|
||||||
|
- **Identity**: device key (P-256/Ed25519) or passkey; server mints short-lived **gc2** tokens bound to the device key (`cnf` claim).
|
||||||
|
- **Privacy**: objects can be plaintext (public) or client-encrypted (private).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security posture
|
||||||
|
|
||||||
|
- **Zero-trust**: no passwords/emails; optional SSO is *linking*, not source-of-truth.
|
||||||
|
- **DPoP-style PoP** on requests:
|
||||||
|
- Client sends:
|
||||||
|
- `Authorization: Bearer gc2.…`
|
||||||
|
- `X-GC-Key: p256:<base64-raw>` (or `ed25519:…`)
|
||||||
|
- `X-GC-TS: <unix seconds>`
|
||||||
|
- `X-GC-Proof: sig( METHOD "\n" URL "\n" TS "\n" SHA256(body) )`
|
||||||
|
- Server verifies `gc2` signature, key binding (`cnf`), timestamp window, and replay cache.
|
||||||
|
- **Replay protection**: 10-minute proof cache.
|
||||||
|
- **No fingerprinting/logging**: no IPs, no UAs.
|
||||||
|
- **Strict CSP** for client: blocks XSS/token theft.
|
||||||
|
- **Limits**: request body limits (default 10 MiB), simple per-account rate limiting.
|
||||||
|
- **Shard↔shard**: mTLS or per-shard signatures with timestamp + replay cache.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Go 1.21+
|
||||||
|
- Docker (optional)
|
||||||
|
- A signing key for tokens: `GC_SIGNING_SECRET_HEX` (32+ bytes hex)
|
||||||
|
- (Optional) Discord OAuth app (Client ID/Secret + redirect URI)
|
||||||
|
- (Optional) Cloudflare Tunnel or other TLS reverse proxy
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
GC_HTTP_ADDR=:9080
|
||||||
|
GC_HTTPS_ADDR= # optional
|
||||||
|
GC_TLS_CERT= # optional
|
||||||
|
GC_TLS_KEY= # optional
|
||||||
|
|
||||||
|
GC_STATIC_ADDR=:9082
|
||||||
|
GC_STATIC_DIR=/opt/greencoast/client
|
||||||
|
|
||||||
|
GC_DATA_DIR=/var/lib/greencoast
|
||||||
|
GC_ZERO_TRUST=true
|
||||||
|
GC_COARSE_TS=false
|
||||||
|
|
||||||
|
GC_SIGNING_SECRET_HEX=<64+ hex chars> # required for gc2 tokens
|
||||||
|
GC_REQUIRE_POP=true # default true; set false for first-run
|
||||||
|
|
||||||
|
# Dev convenience (testing only; disable for production)
|
||||||
|
GC_DEV_ALLOW_UNAUTH=false
|
||||||
|
GC_DEV_BEARER=
|
||||||
|
|
||||||
|
# Discord SSO (optional)
|
||||||
|
GC_DISCORD_CLIENT_ID=
|
||||||
|
GC_DISCORD_CLIENT_SECRET=
|
||||||
|
GC_DISCORD_REDIRECT_URI=https://greencoast.example.com/auth-callback.html
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quickstart (Docker)
|
||||||
|
|
||||||
|
Minimal compose for local testing (PoP disabled + dev unauth allowed for first run):
|
||||||
|
|
||||||
|
services:
|
||||||
|
shard-test:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
- GC_HTTP_ADDR=:9080
|
||||||
|
- GC_STATIC_ADDR=:9082
|
||||||
|
- GC_STATIC_DIR=/opt/greencoast/client
|
||||||
|
- GC_DATA_DIR=/var/lib/greencoast
|
||||||
|
- GC_ZERO_TRUST=true
|
||||||
|
- GC_SIGNING_SECRET_HEX=7f6e1a0f2b4d7e3a... # replace with your secret
|
||||||
|
- GC_REQUIRE_POP=false # easier first-run
|
||||||
|
- GC_DEV_ALLOW_UNAUTH=true
|
||||||
|
volumes:
|
||||||
|
- ./testdata:/var/lib/greencoast
|
||||||
|
- ./client:/opt/greencoast/client:ro
|
||||||
|
ports:
|
||||||
|
- "9080:9080"
|
||||||
|
- "9082:9082"
|
||||||
|
|
||||||
|
Open `http://localhost:9082` → set the Shard URL (`http://localhost:9080`) → publish a test post.
|
||||||
|
|
||||||
|
When ready, **turn PoP on** by removing `GC_REQUIRE_POP=false` and disabling `GC_DEV_ALLOW_UNAUTH`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cloudflare Tunnel example
|
||||||
|
|
||||||
|
ingress:
|
||||||
|
- hostname: greencoast.example.com
|
||||||
|
service: http://shard-test:9082
|
||||||
|
- hostname: api-gc.greencoast.example.com
|
||||||
|
service: http://shard-test:9080
|
||||||
|
- service: http_status:404
|
||||||
|
|
||||||
|
Use “Full (strict)” TLS and ensure your cert covers both hosts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Client usage
|
||||||
|
|
||||||
|
- **Shard URL**: set it in the top “Connect” section (or use `?api=` query or `<meta name="gc-api-base">`).
|
||||||
|
- **Device key sign-in (no OAuth)**:
|
||||||
|
1) Client generates/stores a P-256 device key in the browser.
|
||||||
|
2) Client calls `/v1/auth/key/challenge` then `/v1/auth/key/verify` to obtain a **gc2** token bound to that key.
|
||||||
|
- **Discord SSO (optional)**:
|
||||||
|
- Requires `GC_DISCORD_CLIENT_*` env vars and a valid `GC_DISCORD_REDIRECT_URI`.
|
||||||
|
- Uses PKCE (`S256`) and binds the minted **gc2** token to the device key presented at `/start`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API (overview)
|
||||||
|
|
||||||
|
- `GET /healthz` – liveness
|
||||||
|
- `PUT /v1/object` – upload blob (headers: optional `X-GC-Private: 1`, `X-GC-TZ`)
|
||||||
|
- `GET /v1/object/{hash}` – download blob
|
||||||
|
- `DELETE /v1/object/{hash}` – delete blob
|
||||||
|
- `GET /v1/index` – list indexed entries (latest first)
|
||||||
|
- `GET /v1/index/stream` – SSE updates
|
||||||
|
- `POST /v1/admin/reindex` – rebuild index from disk
|
||||||
|
- **Auth**
|
||||||
|
- `POST /v1/auth/key/challenge` → `{nonce, exp}`
|
||||||
|
- `POST /v1/auth/key/verify` `{nonce, alg, pub, sig}` → `{bearer, sub, exp}`
|
||||||
|
- `POST /v1/auth/discord/start` (requires `X-GC-3P-Assent: 1` and `X-GC-Key`)
|
||||||
|
- `GET /v1/auth/discord/callback` → redirects with `#bearer=…`
|
||||||
|
- **GDPR**
|
||||||
|
- `GET /v1/gdpr/policy` – current data-handling posture
|
||||||
|
|
||||||
|
> When `GC_REQUIRE_POP=true`, all authenticated endpoints require PoP headers.
|
||||||
|
|
||||||
|
### PoP header format (pseudocode)
|
||||||
|
|
||||||
|
Authorization: Bearer gc2.<claims>.<sig>
|
||||||
|
X-GC-Key: p256:<base64-raw> # or ed25519:<base64-raw>
|
||||||
|
X-GC-TS: <unix seconds>
|
||||||
|
X-GC-Proof: base64(
|
||||||
|
Sign_device_key(
|
||||||
|
UPPER(METHOD) + "\n" + URL + "\n" + X-GC-TS + "\n" + SHA256(body)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Storage layout & migration
|
||||||
|
|
||||||
|
- **Writes** are flat: `objects/<hash>`
|
||||||
|
- **Reads** (and reindex) also support:
|
||||||
|
- `objects/<hash>/blob|data|content`
|
||||||
|
- `objects/<hash>/<single file>`
|
||||||
|
- `objects/<prefix>/<hash>` (two-level prefix)
|
||||||
|
- To **restore** data into a fresh container:
|
||||||
|
1) Mount your objects at `/var/lib/greencoast/objects`
|
||||||
|
2) Call `POST /v1/admin/reindex` (with auth+PoP or enable dev unauth briefly)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reindex examples
|
||||||
|
|
||||||
|
Unauth (dev only):
|
||||||
|
|
||||||
|
curl -X POST https://api-gc.yourdomain/v1/admin/reindex
|
||||||
|
|
||||||
|
With bearer + PoP (placeholders):
|
||||||
|
|
||||||
|
curl -X POST https://api-gc.yourdomain/v1/admin/reindex ^
|
||||||
|
-H "Authorization: Bearer <gc2_token>" ^
|
||||||
|
-H "X-GC-Key: p256:<base64raw>" ^
|
||||||
|
-H "X-GC-TS: <unix>" ^
|
||||||
|
-H "X-GC-Proof: <base64sig>"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hardening checklist (prod)
|
||||||
|
|
||||||
|
- Set `GC_REQUIRE_POP=true`, remove dev bypass.
|
||||||
|
- Keep access token TTL ≤ 8h; rotate signing key periodically.
|
||||||
|
- Static client served with strong CSP (already enabled).
|
||||||
|
- Containers run non-root, read-only FS, `no-new-privileges`, `cap_drop: ["ALL"]`.
|
||||||
|
- Edge WAF/rate limits; 10 MiB default request cap (tunable).
|
||||||
|
- Commit `go.sum`; run `go mod verify` in CI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## GDPR
|
||||||
|
|
||||||
|
- Server stores **no PII** (no emails, no IP/UA logs).
|
||||||
|
- Timestamps are UTC (or coarse UTC if enabled).
|
||||||
|
- `/v1/gdpr/policy` exposes current posture.
|
||||||
|
- Roadmap: `/v1/gdpr/export` and `/v1/gdpr/delete` to enumerate/remove blobs signed by a given key.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under **The Unlicense**. See `LICENSE` for details.
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone <your repo> greencoast
|
|
||||||
cd greencoast
|
|
||||||
cp .env.example .env
|
|
||||||
docker compose -f docker-compose.dev.yml up --build
|
|
||||||
# Health:
|
|
||||||
curl -s http://localhost:8080/healthz
|
|
||||||
# Put an object (dev mode allows unauthenticated PUT/GET):
|
|
||||||
curl -s -X PUT --data-binary @README.md http://localhost:8080/v1/object
|
|
||||||
# -> {"ok":true,"hash":"<sha256>",...}
|
|
||||||
curl -s http://localhost:8080/v1/object/<sha256> | head
|
|
||||||
|
790
client/app.js
790
client/app.js
@@ -1,261 +1,605 @@
|
|||||||
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.
|
||||||
|
|
||||||
// ---- Helpers ----
|
const els = {};
|
||||||
function defaultApiBase() {
|
function $(id){ return document.getElementById(id); }
|
||||||
try {
|
function on(el, ev, fn){ if (el) el.addEventListener(ev, fn, false); }
|
||||||
const qs = new URLSearchParams(window.location.search);
|
|
||||||
const qApi = qs.get("api");
|
|
||||||
if (qApi) return qApi.replace(/\/+$/, "");
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
const m = document.querySelector('meta[name="gc-api-base"]');
|
|
||||||
if (m && m.content) return m.content.replace(/\/+$/, "");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const u = new URL(window.location.href);
|
|
||||||
const proto = u.protocol;
|
|
||||||
const host = u.hostname;
|
|
||||||
const portStr = u.port;
|
|
||||||
const bracketHost = host.includes(":") ? `[${host}]` : host;
|
|
||||||
|
|
||||||
const port = portStr ? parseInt(portStr, 10) : null;
|
|
||||||
let apiPort = port;
|
|
||||||
if (port === 8082) apiPort = 8080;
|
|
||||||
else if (port === 9082) apiPort = 9080;
|
|
||||||
else if (port) apiPort = Math.max(1, port - 2);
|
|
||||||
|
|
||||||
return apiPort ? `${proto}//${bracketHost}:${apiPort}` : `${proto}//${bracketHost}`;
|
|
||||||
} catch {
|
|
||||||
return window.location.origin.replace(/\/+$/, "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const LOCAL_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
||||||
|
|
||||||
// ---- DOM refs ----
|
|
||||||
const els = {
|
|
||||||
shardUrl: document.getElementById("shardUrl"),
|
|
||||||
bearer: document.getElementById("bearer"),
|
|
||||||
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"),
|
|
||||||
shareTZ: document.getElementById("shareTZ"),
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---- Config + state ----
|
|
||||||
const LS_KEY = "gc_client_config_v1";
|
|
||||||
const POSTS_KEY = "gc_posts_index_v1";
|
|
||||||
let sseCtrl = null;
|
|
||||||
|
|
||||||
// ---- Boot ----
|
|
||||||
const cfg = loadConfig();
|
|
||||||
applyConfig();
|
|
||||||
checkHealth();
|
|
||||||
syncIndex();
|
|
||||||
sse();
|
|
||||||
|
|
||||||
// ---- Storage helpers ----
|
|
||||||
function loadConfig(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) ?? {}; } catch { return {}; } }
|
|
||||||
function saveConfig(c){ localStorage.setItem(LS_KEY, JSON.stringify(c)); Object.assign(cfg, c); }
|
|
||||||
function getPosts(){ try { return JSON.parse(localStorage.getItem(POSTS_KEY)) ?? []; } catch { return []; } }
|
|
||||||
function setPosts(v){ localStorage.setItem(POSTS_KEY, JSON.stringify(v)); renderPosts(); }
|
|
||||||
function norm(u){ return (u||"").replace(/\/+$/,""); }
|
function norm(u){ return (u||"").replace(/\/+$/,""); }
|
||||||
function fmtWhen(ts, tz) {
|
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); }
|
||||||
try {
|
function setText(el, s){ if(el) el.textContent = s; }
|
||||||
return new Intl.DateTimeFormat(undefined, { dateStyle:"medium", timeStyle:"short", timeZone: tz }).format(new Date(ts));
|
function currentPath(){ const h=location.hash||"#/"; const p=h.replace(/^#/, ""); return p||"/"; }
|
||||||
} catch { return ts; }
|
|
||||||
|
const HAS_SUBTLE = !!(window.isSecureContext && window.crypto && crypto.subtle && crypto.subtle.generateKey);
|
||||||
|
const routes = { "/":"feed", "/privacy":"privacy.html", "/gdpr":"gdpr.html", "/terms":"terms.html" };
|
||||||
|
|
||||||
|
// ---------- Router (Trusted-Types safe text-only render of legal pages) ----------
|
||||||
|
function setActiveTab(path){
|
||||||
|
const cur = path in routes ? path : "/";
|
||||||
|
document.querySelectorAll(".tabs a").forEach(a=>{
|
||||||
|
const href = new URL(a.href, location.origin).hash.replace(/^#/, "") || "/";
|
||||||
|
a.classList.toggle("active", href===cur);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function renderRoute(path){
|
||||||
|
setActiveTab(path);
|
||||||
|
const target = routes[path] ?? "feed";
|
||||||
|
if (target === "feed"){ els.page.hidden=true; els.feed.hidden=false; return; }
|
||||||
|
els.feed.hidden=true; els.page.hidden=false;
|
||||||
|
setText(els.pageContent, "Loading…");
|
||||||
|
try{
|
||||||
|
const res = await fetch("./"+target, { cache:"no-store" });
|
||||||
|
const html = await res.text();
|
||||||
|
const body = (html.match(/<body[^>]*>([\s\S]*?)<\/body>/i)?.[1] || html).replace(/<[^>]*>/g,"");
|
||||||
|
setText(els.pageContent, body);
|
||||||
|
}catch{ setText(els.pageContent, "Failed to load page."); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyConfig() {
|
// ---------- Config ----------
|
||||||
if (!cfg.url) {
|
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";
|
||||||
const detected = defaultApiBase();
|
|
||||||
cfg.url = detected;
|
function defaultApiBase() {
|
||||||
try { localStorage.setItem(LS_KEY, JSON.stringify(cfg)); } catch {}
|
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(/\/+$/,"");
|
||||||
els.shardUrl.value = cfg.url;
|
try{
|
||||||
|
const u=new URL(window.location.href); const proto=u.protocol, host=u.hostname, portStr=u.port; const bracketHost=host.includes(":")?`[${host}]`:host;
|
||||||
|
const port = portStr ? parseInt(portStr,10) : null; let apiPort=port;
|
||||||
|
if (port===8082) apiPort=8080; else if (port===9082) apiPort=9080; else if (port) apiPort=Math.max(1,port-2);
|
||||||
|
return apiPort ? `${proto}//${bracketHost}:${apiPort}` : `${proto}//${bracketHost}`;
|
||||||
|
} catch { return window.location.origin.replace(/\/+$/,""); }
|
||||||
|
}
|
||||||
|
function loadCfg(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) ?? {}; } catch { return {}; } }
|
||||||
|
const cfg = loadCfg();
|
||||||
|
function saveCfg(c){ localStorage.setItem(LS_KEY, JSON.stringify(Object.assign(cfg,c))); }
|
||||||
|
function applyCfg(){
|
||||||
|
els.shardUrl.value = cfg.url ?? defaultApiBase();
|
||||||
els.bearer.value = cfg.bearer ?? "";
|
els.bearer.value = cfg.bearer ?? "";
|
||||||
els.passphrase.value = cfg.passphrase ?? "";
|
els.passphrase.value = cfg.passphrase ?? "";
|
||||||
}
|
}
|
||||||
|
function isAuthorized(){ return !!cfg.bearer; }
|
||||||
els.saveConn.onclick = async () => {
|
function updateLimitedUI(){
|
||||||
const c = { url: norm(els.shardUrl.value), bearer: els.bearer.value.trim(), passphrase: els.passphrase.value };
|
const limited = !isAuthorized();
|
||||||
saveConfig(c); await checkHealth(); await syncIndex(); sse(true);
|
if (els.banner) els.banner.hidden = !limited;
|
||||||
};
|
for (const id of ["visibility","shareVis"]){
|
||||||
|
const sel = $(id); if (!sel) continue;
|
||||||
els.publish.onclick = publish;
|
for (const val of ["members","private"]){
|
||||||
els.discordStart.onclick = discordStart;
|
const opt = [...sel.options].find(o => o.value===val);
|
||||||
|
if (opt) opt.disabled = limited;
|
||||||
async function checkHealth() {
|
}
|
||||||
if (!cfg.url) { els.health.textContent = "No API base set"; return; }
|
if (limited && (sel.value==="members" || sel.value==="private")) sel.value="plaintext";
|
||||||
els.health.textContent = "Checking…";
|
|
||||||
try {
|
|
||||||
const r = await fetch(cfg.url + "/healthz", { mode:"cors" });
|
|
||||||
els.health.textContent = r.ok ? "Connected ✔" : `Error: ${r.status}`;
|
|
||||||
} catch (e) {
|
|
||||||
els.health.textContent = "Not reachable";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function publish() {
|
// ---------- Crypto helpers ----------
|
||||||
if (!cfg.url) return msg("Set shard URL first.", true);
|
function b64uEncode(buf){ const bin=Array.from(new Uint8Array(buf)).map(b=>String.fromCharCode(b)).join(""); return btoa(bin).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""); }
|
||||||
const title = els.title.value.trim(); const body = els.body.value; const vis = els.visibility.value;
|
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; }
|
||||||
try {
|
async function sha256(bytes){ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); }
|
||||||
let blob, enc=false;
|
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(""); }
|
||||||
if (vis === "private") {
|
|
||||||
if (!cfg.passphrase) return msg("Set a passphrase for private posts.", true);
|
|
||||||
const payload = await encryptString(JSON.stringify({ title, body }), cfg.passphrase);
|
|
||||||
blob = toBlob(payload); enc=true;
|
|
||||||
} else {
|
|
||||||
blob = toBlob(JSON.stringify({ title, body }));
|
|
||||||
}
|
|
||||||
const headers = { "Content-Type":"application/octet-stream" };
|
|
||||||
if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
|
|
||||||
if (enc) headers["X-GC-Private"] = "1";
|
|
||||||
if (els.shareTZ && els.shareTZ.checked && LOCAL_TZ) headers["X-GC-TZ"] = LOCAL_TZ; // NEW
|
|
||||||
|
|
||||||
const r = await fetch(cfg.url + "/v1/object", { method:"PUT", headers, body: blob });
|
async function getOrCreateKeyPair(){
|
||||||
|
if (!HAS_SUBTLE) throw new Error("WebCrypto not available");
|
||||||
|
const pkcs8 = sessionStorage.getItem(KEY_PKCS8); const pubRaw = sessionStorage.getItem(KEY_PUB_RAW);
|
||||||
|
if (pkcs8 && pubRaw){
|
||||||
|
try{
|
||||||
|
const priv = await crypto.subtle.importKey("pkcs8", b64uDecodeToBytes(pkcs8), {name:"ECDSA", namedCurve:"P-256"}, true, ["sign"]);
|
||||||
|
const pub = await crypto.subtle.importKey("raw", b64uDecodeToBytes(pubRaw), {name:"ECDSA", namedCurve:"P-256"}, true, ["verify"]);
|
||||||
|
return { priv, pub, pkcs8B64u: pkcs8, pubRawB64u: pubRaw };
|
||||||
|
}catch{}
|
||||||
|
}
|
||||||
|
const kp = await crypto.subtle.generateKey({name:"ECDSA", namedCurve:"P-256"}, true, ["sign","verify"]);
|
||||||
|
const pkcs8New = await crypto.subtle.exportKey("pkcs8", kp.privateKey);
|
||||||
|
const pubRawBytes = await crypto.subtle.exportKey("raw", kp.publicKey);
|
||||||
|
const pkcs8B64 = b64uEncode(pkcs8New); const pubRawB64 = b64uEncode(pubRawBytes);
|
||||||
|
sessionStorage.setItem(KEY_PKCS8, pkcs8B64); sessionStorage.setItem(KEY_PUB_RAW, pubRawB64);
|
||||||
|
return { priv: kp.privateKey, pub: kp.publicKey, pkcs8B64u: pkcs8B64, pubRawB64u: pubRawB64 };
|
||||||
|
}
|
||||||
|
async function deriveMembersPassphrase(saltBytes){
|
||||||
|
const kp = await getOrCreateKeyPair();
|
||||||
|
const seed = await sha256(b64uDecodeToBytes(kp.pkcs8B64u));
|
||||||
|
const cat = new Uint8Array(seed.length + 1 + saltBytes.length);
|
||||||
|
cat.set(seed,0); cat.set(new Uint8Array([1]), seed.length); cat.set(saltBytes, seed.length+1);
|
||||||
|
const out = await sha256(cat);
|
||||||
|
return b64uEncode(out);
|
||||||
|
}
|
||||||
|
async function deriveAesKey(passphraseB64u, saltBytes){
|
||||||
|
const raw = b64uDecodeToBytes(passphraseB64u);
|
||||||
|
const keyMat = await crypto.subtle.importKey("raw", raw, "PBKDF2", false, ["deriveKey"]);
|
||||||
|
return crypto.subtle.deriveKey(
|
||||||
|
{ name:"PBKDF2", salt:saltBytes, iterations:120000, hash:"SHA-256" },
|
||||||
|
keyMat, { name:"AES-GCM", length:256 }, false, ["encrypt","decrypt"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async function aesEncryptString(str, passphraseB64u){
|
||||||
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||||
|
const key = await deriveAesKey(passphraseB64u, salt);
|
||||||
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||||
|
const ct = new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM", iv}, key, new TextEncoder().encode(str)));
|
||||||
|
return { alg:"aes-256-gcm", iv:b64uEncode(iv), salt:b64uEncode(salt), ct:b64uEncode(ct) };
|
||||||
|
}
|
||||||
|
async function aesDecryptToString(obj, passphraseB64u){
|
||||||
|
const key = await deriveAesKey(passphraseB64u, b64uDecodeToBytes(obj.salt));
|
||||||
|
const pt = await crypto.subtle.decrypt({name:"AES-GCM", iv:b64uDecodeToBytes(obj.iv)}, key, b64uDecodeToBytes(obj.ct));
|
||||||
|
return new TextDecoder().decode(pt);
|
||||||
|
}
|
||||||
|
function makeEnvelope(mode, encObj, meta){ return JSON.stringify({ gc:"2", mode, enc:encObj, meta }); }
|
||||||
|
function tryParseJSON(t){ try{ return JSON.parse(t); }catch{ return null; } }
|
||||||
|
|
||||||
|
// ---------- Avatar ----------
|
||||||
|
function parseGC2(tok){ try{ const p=tok.split("."); if(p.length!==3) return {}; const pl=JSON.parse(atob(p[1].replace(/-/g,"+").replace(/_/g,"/"))); return {sub:pl.sub||"", cnf:pl.cnf||""}; }catch{ return {}; } }
|
||||||
|
function identiconPNGFromHex(hex, size=64){
|
||||||
|
const cells=5, cell=Math.floor(size/cells), pad=Math.floor((size-cell*cells)/2);
|
||||||
|
const hexBytes=(h)=>{const u=new Uint8Array(h.length/2); for(let i=0;i<u.length;i++) u[i]=parseInt(h.substr(i*2,2),16); return u;};
|
||||||
|
const b=hexBytes(hex); const hue=b[0]/255*360; const bg=`hsl(${hue},35%,16%)`; const fg=`hsl(${(hue+180)%360},70%,60%)`;
|
||||||
|
const bits=[]; for(const x of b) for(let i=0;i<8;i++) bits.push((x>>i)&1);
|
||||||
|
const c=document.createElement("canvas"); c.width=c.height=size; const g=c.getContext("2d");
|
||||||
|
g.fillStyle=bg; g.fillRect(0,0,size,size); let k=0;
|
||||||
|
for(let y=0;y<cells;y++){ for(let x=0;x<3;x++){ if(bits[k++]===1){ const px=pad+x*cell, py=pad+y*cell;
|
||||||
|
g.fillStyle=fg; g.fillRect(px,py,cell-1,cell-1); const mx=pad+(cells-1-x)*cell; if(cells-1-x!==x) g.fillRect(mx,py,cell-1,cell-1); } } }
|
||||||
|
return c.toDataURL("image/png");
|
||||||
|
}
|
||||||
|
async function renderAvatar(){
|
||||||
|
if (!els.avatar) return;
|
||||||
|
let seed=null, label="(pseudonymous)";
|
||||||
|
if (cfg.bearer){ const p=parseGC2(cfg.bearer); seed=p.cnf||p.sub||null; if(p.sub) label=p.sub; }
|
||||||
|
if (!seed){ els.avatar.removeAttribute("src"); setText(els.fp,"(pseudonymous)"); return; }
|
||||||
|
const hex = await sha256Hex(seed);
|
||||||
|
els.avatar.onerror = ()=>{ els.avatar.removeAttribute("src"); setText(els.fp,"(pseudonymous)"); };
|
||||||
|
els.avatar.src=identiconPNGFromHex(hex, 64);
|
||||||
|
setText(els.fp, label+" (pseudonymous)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Auth / PoP ----------
|
||||||
|
async function requireChallengeAlive(base) {
|
||||||
|
try {
|
||||||
|
const r = await fetch(base + "/v1/auth/key/challenge", { method: "POST" });
|
||||||
|
if (r.status === 404) {
|
||||||
|
alert(
|
||||||
|
"Shard URL looks wrong: /v1/auth/key/challenge not found.\n\n" +
|
||||||
|
"Current base:\n" + base + "\n\n" +
|
||||||
|
"Set it to your API host (e.g. https://api-gc.fullmooncyberworks.com) and Save."
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return r.ok;
|
||||||
|
} catch {
|
||||||
|
alert("Cannot reach shard at: " + base);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deviceKeySignIn(){
|
||||||
|
if (!HAS_SUBTLE) { alert("Device keys not supported. Use Discord or a modern browser."); return; }
|
||||||
|
const base = cfg.url || defaultApiBase(); if (!base){ alert("Set shard URL first."); return; }
|
||||||
|
if (!(await requireChallengeAlive(base))) return;
|
||||||
|
flash("Signing in…");
|
||||||
|
try{
|
||||||
|
const { priv, pubRawB64u } = await getOrCreateKeyPair();
|
||||||
|
const rc = await fetch(base + "/v1/auth/key/challenge", { method:"POST" });
|
||||||
|
if (!rc.ok) throw new Error("challenge "+rc.status);
|
||||||
|
const cj = await rc.json();
|
||||||
|
const msg = new TextEncoder().encode("key-verify\n"+cj.nonce);
|
||||||
|
const sig = await crypto.subtle.sign({name:"ECDSA", hash:"SHA-256"}, priv, msg);
|
||||||
|
const body = JSON.stringify({ nonce:cj.nonce, alg:"p256", pub:pubRawB64u, sig:b64uEncode(sig) });
|
||||||
|
const rv = await fetch(base + "/v1/auth/key/verify", { method:"POST", headers:{"Content-Type":"application/json"}, body });
|
||||||
|
if (!rv.ok) throw new Error("verify "+rv.status);
|
||||||
|
const vj = await rv.json();
|
||||||
|
saveCfg({ bearer: vj.bearer }); applyCfg(); updateLimitedUI();
|
||||||
|
await renderAvatar(); await checkHealth(); await syncIndex(); sse(true); flash("Signed in");
|
||||||
|
}catch(e){ console.error(e); alert("Sign-in error: "+(e?.message||e)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signPoPHeaders(method, pathOnly, bodyBytes){
|
||||||
|
if (!HAS_SUBTLE) return {};
|
||||||
|
const pubRaw = sessionStorage.getItem(KEY_PUB_RAW); const pkcs8 = sessionStorage.getItem(KEY_PKCS8);
|
||||||
|
if (!pubRaw || !pkcs8) return {};
|
||||||
|
const priv = await crypto.subtle.importKey("pkcs8", b64uDecodeToBytes(pkcs8), {name:"ECDSA", namedCurve:"P-256"}, false, ["sign"]);
|
||||||
|
const bodyHash = new Uint8Array(await crypto.subtle.digest("SHA-256", bodyBytes || new Uint8Array()));
|
||||||
|
const hex = Array.from(bodyHash).map(b=>b.toString(16).padStart(2,"0")).join("");
|
||||||
|
const ts = Math.floor(Date.now()/1000).toString();
|
||||||
|
const msg = new TextEncoder().encode(method.toUpperCase()+"\n"+pathOnly+"\n"+ts+"\n"+hex);
|
||||||
|
const sig = await crypto.subtle.sign({name:"ECDSA", hash:"SHA-256"}, priv, msg);
|
||||||
|
return { "X-GC-Key":"p256:"+pubRaw, "X-GC-TS":ts, "X-GC-Proof":b64uEncode(sig) };
|
||||||
|
}
|
||||||
|
async function fetchWithPoP(url, opts){
|
||||||
|
const u = new URL(url); const path = u.pathname; const method = (opts?.method||"GET").toUpperCase();
|
||||||
|
const bodyBuf = opts?.body instanceof Blob ? new Uint8Array(await opts.body.arrayBuffer())
|
||||||
|
: (opts?.body instanceof ArrayBuffer ? new Uint8Array(opts.body) : new Uint8Array());
|
||||||
|
const pop = await signPoPHeaders(method, path, bodyBuf);
|
||||||
|
const headers = new Headers(opts?.headers||{});
|
||||||
|
if (cfg.bearer) headers.set("Authorization", "Bearer "+cfg.bearer);
|
||||||
|
for (const [k,v] of Object.entries(pop)) headers.set(k,v);
|
||||||
|
return fetch(url, { ...(opts||{}), headers });
|
||||||
|
}
|
||||||
|
// Anonymous fetch: strip any auth/PoP headers completely (for plaintext writes)
|
||||||
|
function stripAuthHeaders(h){ h.delete("Authorization"); h.delete("X-GC-Key"); h.delete("X-GC-TS"); h.delete("X-GC-Proof"); return h; }
|
||||||
|
async function fetchAnon(url, opts){
|
||||||
|
const headers = new Headers(opts?.headers || {});
|
||||||
|
return fetch(url, { ...(opts||{}), headers: stripAuthHeaders(headers) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Leak detection ----------
|
||||||
|
const SECRET_PATTERNS = [
|
||||||
|
/\b(passphrase|password|secret|gc[-_ ]?pass|shared[-_ ]?key)\s*[:=]\s*[^\s]{8,}/i,
|
||||||
|
/\b(ASIA|AKIA|AIza)[0-9A-Za-z_\-]{10,}/,
|
||||||
|
/\b[A-Za-z0-9+/_-]{32,}={0,2}\b/,
|
||||||
|
/\b[0-9a-f]{64,}\b/i,
|
||||||
|
/-----BEGIN [A-Z ]{5,}-----[\s\S]+?-----END [A-Z ]{5,}-----/
|
||||||
|
];
|
||||||
|
function containsSecret(text, passphrase){
|
||||||
|
if (!text) return false;
|
||||||
|
if (passphrase && passphrase.length>=6 && text.includes(passphrase)) return true;
|
||||||
|
return SECRET_PATTERNS.some(rx => rx.test(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- X-post helpers ----------
|
||||||
|
const TRACKING_PARAMS = [/^utm_/i,/^gclid$/i,/^fbclid$/i,/^msclkid$/i,/^mc_(eid|cid)$/i,/^vero_id$/i,/^oly_(anon|enc)_id$/i,/^_hs(enc|mi|mi)/i,/^s?cid$/i,/^igshid$/i,/^ttclid$/i,/^spm$/i,/^ref$/i,/^ref_src$/i,/^ref_url$/i];
|
||||||
|
function sanitizeUrl(input){
|
||||||
|
try{
|
||||||
|
const u = new URL(input.trim());
|
||||||
|
for (const [k] of u.searchParams){ if (TRACKING_PARAMS.some(rx=>rx.test(k))) u.searchParams.delete(k); }
|
||||||
|
u.hash = "";
|
||||||
|
return u.toString();
|
||||||
|
}catch{ return ""; }
|
||||||
|
}
|
||||||
|
function shortHost(h){ try{ const p=h.split("."); return p.length>2 ? p.slice(-2).join(".") : h; }catch{ return h; } }
|
||||||
|
function renderXCard(container, cleanUrl, note){
|
||||||
|
container.replaceChildren();
|
||||||
|
if (!cleanUrl){ const m=document.createElement("div"); m.className="xmeta"; m.textContent="Enter a valid URL."; container.appendChild(m); return; }
|
||||||
|
const u = new URL(cleanUrl);
|
||||||
|
const row = document.createElement("div"); row.className="xrow";
|
||||||
|
const pill = document.createElement("span"); pill.className="xpill"; pill.textContent=shortHost(u.hostname);
|
||||||
|
const title = document.createElement("span"); title.className="xtitle"; title.textContent=note || `${shortHost(u.hostname)} link`;
|
||||||
|
row.appendChild(pill); row.appendChild(title);
|
||||||
|
|
||||||
|
const meta = document.createElement("div"); meta.className="xmeta"; meta.textContent=(u.pathname||"/")+(u.search||"");
|
||||||
|
|
||||||
|
const btn = document.createElement("div"); btn.className="xbtn";
|
||||||
|
const a = document.createElement("a"); a.href=cleanUrl; a.target="_blank"; a.rel="noreferrer noopener"; a.referrerPolicy="no-referrer"; a.textContent="Open privately ↗";
|
||||||
|
btn.appendChild(a);
|
||||||
|
|
||||||
|
container.appendChild(row); container.appendChild(meta); container.appendChild(btn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Compose / Publish ----------
|
||||||
|
function msg(t, err=false){ setText(els.publishStatus, t); els.publishStatus.style.color = err ? "#ff6b6b" : "#8b949e"; }
|
||||||
|
|
||||||
|
async function publish(){
|
||||||
|
const base = cfg.url || defaultApiBase(); if (!base) return msg("Set shard URL first.", true);
|
||||||
|
|
||||||
|
const mode = els.visibility.value; // plaintext | members | private
|
||||||
|
const title = els.title.value.trim();
|
||||||
|
const body = els.body.value;
|
||||||
|
|
||||||
|
if ((mode==="members"||mode==="private") && !isAuthorized()){ msg("Authorize your device to publish encrypted posts.", true); return; }
|
||||||
|
|
||||||
|
const currentPass = els.passphrase.value.trim();
|
||||||
|
if (containsSecret(body, currentPass)){ msg("Blocked: content appears to include a passkey/secret.", true); return; }
|
||||||
|
|
||||||
|
try{
|
||||||
|
let blob, headers={"Content-Type":"application/octet-stream"}, enc=false;
|
||||||
|
|
||||||
|
if (mode==="plaintext"){
|
||||||
|
blob = new Blob([JSON.stringify({ title, body, type:"plaintext" })], {type:"application/json"});
|
||||||
|
} else if (mode==="members"){
|
||||||
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||||
|
const pp = await deriveMembersPassphrase(salt);
|
||||||
|
const encObj = await aesEncryptString(JSON.stringify({ title, body, type:"members" }), pp);
|
||||||
|
const env = makeEnvelope("members", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
||||||
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
||||||
|
} else if (mode==="private"){
|
||||||
|
if (!currentPass) return msg("Set a passphrase for Private-Encrypted posts.", true);
|
||||||
|
const pp = b64uEncode(new TextEncoder().encode(currentPass));
|
||||||
|
const encObj = await aesEncryptString(JSON.stringify({ title, body, type:"private" }), pp);
|
||||||
|
const env = makeEnvelope("private", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
||||||
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; if (tz) headers["X-GC-TZ"]=tz;
|
||||||
|
|
||||||
|
const url = base + "/v1/object";
|
||||||
|
let r;
|
||||||
|
if (mode === "plaintext") {
|
||||||
|
// truly anonymous write (requires allow_anon_plaintext on shard)
|
||||||
|
r = await fetchAnon(url, { method:"PUT", headers, body: blob });
|
||||||
|
} else {
|
||||||
|
r = await fetchWithPoP(url, { method:"PUT", headers, body: blob });
|
||||||
|
}
|
||||||
if (!r.ok) throw new Error(await r.text());
|
if (!r.ok) throw new Error(await r.text());
|
||||||
const j = await r.json();
|
const j = await r.json();
|
||||||
|
|
||||||
const posts = getPosts();
|
const posts = getPosts();
|
||||||
posts.unshift({ hash:j.hash, title: title || "(untitled)", bytes:j.bytes, ts:j.stored_at, enc, creator_tz: j.creator_tz || "" });
|
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);
|
setPosts(posts);
|
||||||
els.body.value = ""; msg(`Published ${enc?"private":"public"} post. Hash: ${j.hash}`);
|
els.body.value="";
|
||||||
} catch(e){ msg("Publish failed: " + (e?.message||e), true); }
|
msg(`Published ${mode}. 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 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.");
|
||||||
|
|
||||||
async function syncIndex() {
|
const mode = els.shareVis.value;
|
||||||
if (!cfg.url) return;
|
const note = els.shareNote.value || "";
|
||||||
try {
|
|
||||||
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
|
if ((mode==="members"||mode==="private") && !isAuthorized()){ alert("Authorize your device to publish encrypted links."); return; }
|
||||||
const r = await fetch(cfg.url + "/v1/index", { headers });
|
if (containsSecret(note, els.passphrase.value.trim())){ alert("Blocked: content appears to include a passkey/secret."); return; }
|
||||||
|
|
||||||
|
try{
|
||||||
|
let blob, headers={"Content-Type":"application/octet-stream"}, enc=false;
|
||||||
|
|
||||||
|
if (mode==="plaintext"){
|
||||||
|
blob = new Blob([JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() })], {type:"application/json"});
|
||||||
|
} else if (mode==="members"){
|
||||||
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||||
|
const pp = await deriveMembersPassphrase(salt);
|
||||||
|
const encObj = await aesEncryptString(JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() }), pp);
|
||||||
|
const env = makeEnvelope("members", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
||||||
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
||||||
|
} else {
|
||||||
|
const pass = els.passphrase.value.trim(); if (!pass) return alert("Set a passphrase for Private-Encrypted links.");
|
||||||
|
const pp = b64uEncode(new TextEncoder().encode(pass));
|
||||||
|
const encObj = await aesEncryptString(JSON.stringify({ type:"xpost", url: clean, note, created_at:new Date().toISOString() }), pp);
|
||||||
|
const env = makeEnvelope("private", encObj, { tz: Intl.DateTimeFormat().resolvedOptions().timeZone || "" });
|
||||||
|
blob = new Blob([env], {type:"application/json"}); headers["X-GC-Private"]="1"; enc=true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; if (tz) headers["X-GC-TZ"]=tz;
|
||||||
|
|
||||||
|
const url = base + "/v1/object";
|
||||||
|
let r;
|
||||||
|
if (mode === "plaintext") {
|
||||||
|
r = await fetchAnon(url, { method:"PUT", headers, body: blob });
|
||||||
|
} else {
|
||||||
|
r = await fetchWithPoP(url, { method:"PUT", headers, body: blob });
|
||||||
|
}
|
||||||
|
if (!r.ok) throw new Error(await r.text());
|
||||||
|
const j = await r.json();
|
||||||
|
|
||||||
|
const posts = getPosts();
|
||||||
|
posts.unshift({ hash:j.hash, title:"(link)", bytes:j.bytes, ts:j.stored_at, enc, mode, author:j.author||null, tz:j.creator_tz||null });
|
||||||
|
setPosts(posts);
|
||||||
|
els.shareUrl.value=""; els.shareNote.value="";
|
||||||
|
renderXCard(els.shareCard, "", "");
|
||||||
|
flash("Link published");
|
||||||
|
}catch(e){ alert("Publish failed: "+(e?.message||e)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- View / Decrypt ----------
|
||||||
|
async function viewPost(p, pre){
|
||||||
|
const base = cfg.url || defaultApiBase(); pre.textContent="Loading…";
|
||||||
|
try{
|
||||||
|
const r = await fetch(base + "/v1/object/"+p.hash);
|
||||||
|
if (!r.ok) throw new Error("fetch failed "+r.status);
|
||||||
|
const buf = new Uint8Array(await r.arrayBuffer());
|
||||||
|
const text = new TextDecoder().decode(buf);
|
||||||
|
|
||||||
|
const env = tryParseJSON(text);
|
||||||
|
if (env && env.gc==="2" && env.enc && env.mode){
|
||||||
|
const enc = env.enc; let pt;
|
||||||
|
if (env.mode==="members"){
|
||||||
|
if (!HAS_SUBTLE) throw new Error("Cannot decrypt on this browser.");
|
||||||
|
const pp = await deriveMembersPassphrase(b64uDecodeToBytes(enc.salt));
|
||||||
|
pt = await aesDecryptToString(enc, pp);
|
||||||
|
} else if (env.mode==="private"){
|
||||||
|
const pass = els.passphrase.value.trim(); if (!pass) throw new Error("Passphrase required");
|
||||||
|
const pp = b64uEncode(new TextEncoder().encode(pass));
|
||||||
|
pt = await aesDecryptToString(enc, pp);
|
||||||
|
} else { throw new Error("Unknown mode"); }
|
||||||
|
|
||||||
|
const j = tryParseJSON(pt);
|
||||||
|
if (j && j.type==="xpost" && j.url){
|
||||||
|
const wrap = pre.parentElement; const card = document.createElement("div"); card.className="xcard";
|
||||||
|
renderXCard(card, sanitizeUrl(j.url), j.note||""); wrap.replaceChild(card, pre); return;
|
||||||
|
}
|
||||||
|
pre.textContent = (j?.title?`# ${j.title}\n\n`:"") + (j?.body ?? pt);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = tryParseJSON(text);
|
||||||
|
if (j){
|
||||||
|
if (j.type==="xpost" && j.url){
|
||||||
|
const wrap = pre.parentElement; const card = document.createElement("div"); card.className="xcard";
|
||||||
|
renderXCard(card, sanitizeUrl(j.url), j.note||""); wrap.replaceChild(card, pre); return;
|
||||||
|
}
|
||||||
|
pre.textContent = (j.title?`# ${j.title}\n\n`:"") + (j.body ?? text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre.textContent = text;
|
||||||
|
}catch(e){ pre.textContent="Error: "+(e?.message||e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveBlob(p){
|
||||||
|
const base = cfg.url || defaultApiBase();
|
||||||
|
const r = await fetch(base + "/v1/object/"+p.hash);
|
||||||
|
if (!r.ok) return alert("download failed "+r.status);
|
||||||
|
const b = await r.blob(); const a=document.createElement("a"); a.href=URL.createObjectURL(b);
|
||||||
|
a.download=p.hash+(p.enc?".gcenc":".json"); a.click(); URL.revokeObjectURL(a.href);
|
||||||
|
}
|
||||||
|
async function delServer(p){
|
||||||
|
const base = cfg.url || defaultApiBase();
|
||||||
|
if (!confirm("Delete blob from server by hash?")) return;
|
||||||
|
const r = await fetchWithPoP(base + "/v1/object/"+p.hash, { method:"DELETE" });
|
||||||
|
if (!r.ok) return alert("delete failed "+r.status);
|
||||||
|
setPosts(getPosts().filter(x=>x.hash!==p.hash));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Index / SSE / Health ----------
|
||||||
|
function getPosts(){ try { return JSON.parse(localStorage.getItem(POSTS_KEY)) ?? []; } catch { return []; } }
|
||||||
|
function setPosts(v){ localStorage.setItem(POSTS_KEY, JSON.stringify(v)); renderPosts(); }
|
||||||
|
async function syncIndex(){
|
||||||
|
const base = cfg.url || defaultApiBase(); if (!base) return;
|
||||||
|
try{
|
||||||
|
const r = await fetch(base + "/v1/index");
|
||||||
if (!r.ok) throw new Error("index fetch failed");
|
if (!r.ok) throw new Error("index fetch failed");
|
||||||
const entries = await r.json();
|
const entries = await r.json();
|
||||||
setPosts(entries.map(e => ({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, creator_tz: e.creator_tz || "" })));
|
setPosts(entries.map(e=>({
|
||||||
} catch(e){ console.warn("index sync failed", 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(forceRestart=false){
|
function sse(reset=false){
|
||||||
if (!cfg.url) return;
|
const base = cfg.url || defaultApiBase(); if (!base) return;
|
||||||
if (sseCtrl) { sseCtrl.abort(); sseCtrl = null; }
|
if (sseCtrl){ sseCtrl.abort(); sseCtrl=undefined; if(!reset) return; }
|
||||||
sseCtrl = new AbortController();
|
sseCtrl = new AbortController();
|
||||||
const url = cfg.url + "/v1/index/stream";
|
fetch(base + "/v1/index/stream", { signal:sseCtrl.signal }).then(async resp=>{
|
||||||
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
|
|
||||||
fetch(url, { headers, signal: sseCtrl.signal }).then(async resp => {
|
|
||||||
if (!resp.ok) return;
|
if (!resp.ok) return;
|
||||||
const reader = resp.body.getReader(); const decoder = new TextDecoder();
|
const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf="";
|
||||||
let buf = "";
|
while(true){ const {value,done}=await reader.read(); if(done) break;
|
||||||
while (true) {
|
buf += dec.decode(value,{stream:true});
|
||||||
const { value, done } = await reader.read(); if (done) break;
|
let i; while((i=buf.indexOf("\n\n"))>=0){
|
||||||
buf += decoder.decode(value, { stream:true });
|
const chunk=buf.slice(0,i); buf=buf.slice(i+2);
|
||||||
let idx;
|
if (chunk.startsWith("data: ")){
|
||||||
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
try{
|
||||||
const chunk = buf.slice(0, idx); buf = buf.slice(idx+2);
|
|
||||||
if (chunk.startsWith("data: ")) {
|
|
||||||
try {
|
|
||||||
const ev = JSON.parse(chunk.slice(6));
|
const ev = JSON.parse(chunk.slice(6));
|
||||||
if (ev.event === "put") {
|
if (ev.event==="put"){
|
||||||
const e = ev.data;
|
const e=ev.data; const posts=getPosts();
|
||||||
const posts = getPosts();
|
if (!posts.find(p=>p.hash===e.hash)){
|
||||||
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});
|
||||||
posts.unshift({ hash:e.hash, title:"(title unknown — fetch)", bytes:e.bytes, ts:e.stored_at, enc:e.private, creator_tz: e.creator_tz || "" });
|
|
||||||
setPosts(posts);
|
setPosts(posts);
|
||||||
}
|
}
|
||||||
} else if (ev.event === "delete") {
|
} else if (ev.event==="delete"){
|
||||||
const h = ev.data.hash; setPosts(getPosts().filter(p => p.hash !== h));
|
const h=ev.data.hash; setPosts(getPosts().filter(x=>x.hash!==h));
|
||||||
}
|
}
|
||||||
} catch {}
|
}catch{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).catch(()=>{});
|
}).catch(()=>{});
|
||||||
}
|
}
|
||||||
|
async function checkHealth(){
|
||||||
async function viewPost(p, pre) {
|
const base = cfg.url || defaultApiBase();
|
||||||
pre.textContent = "Loading…";
|
if (!base) { setText(els.health,"Set URL"); return; }
|
||||||
try {
|
setText(els.health,"Checking…");
|
||||||
const headers = {}; if (cfg.bearer) headers["Authorization"] = "Bearer " + cfg.bearer;
|
try { const r = await fetch(base + "/healthz"); setText(els.health, r.ok ? "Connected ✔" : `Error: ${r.status}`); }
|
||||||
const r = await fetch(cfg.url + "/v1/object/" + p.hash, { headers });
|
catch { setText(els.health,"Not reachable"); }
|
||||||
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) {
|
|
||||||
const derived = defaultApiBase();
|
|
||||||
if (derived) {
|
|
||||||
cfg.url = derived; try { localStorage.setItem(LS_KEY, JSON.stringify(cfg)); } catch {}
|
|
||||||
els.shardUrl.value = derived;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!cfg.url) { alert("Set shard URL first."); return; }
|
|
||||||
const r = await fetch(cfg.url + "/v1/auth/discord/start", { headers: { "X-GC-3P-Assent":"1" }});
|
|
||||||
if (!r.ok) { alert("Discord SSO not available"); return; }
|
|
||||||
const j = await r.json();
|
|
||||||
location.href = j.url;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- Render posts (no innerHTML) ----------
|
||||||
function renderPosts() {
|
function renderPosts() {
|
||||||
const posts = getPosts(); els.posts.innerHTML = "";
|
const posts = getPosts();
|
||||||
|
const root = els.posts;
|
||||||
|
if (!root) return;
|
||||||
|
while (root.firstChild) root.removeChild(root.firstChild);
|
||||||
|
|
||||||
for (const p of posts) {
|
for (const p of posts) {
|
||||||
const localStr = fmtWhen(p.ts, LOCAL_TZ) + ` (${LOCAL_TZ})`;
|
const wrap = document.createElement("div");
|
||||||
let creatorStr = "";
|
wrap.className = "post";
|
||||||
if (p.creator_tz && p.creator_tz !== LOCAL_TZ) {
|
|
||||||
creatorStr = ` · creator: ${fmtWhen(p.ts, p.creator_tz)} (${p.creator_tz})`;
|
const meta = document.createElement("div");
|
||||||
}
|
meta.className = "meta";
|
||||||
const div = document.createElement("div"); div.className = "post";
|
|
||||||
const badge = p.enc ? `<span class="badge">private</span>` : `<span class="badge">public</span>`;
|
const codeEl = document.createElement("code");
|
||||||
div.innerHTML = `
|
codeEl.textContent = `${p.hash.slice(0, 10)}…`;
|
||||||
<div class="meta">
|
meta.appendChild(codeEl);
|
||||||
<code>${p.hash.slice(0,10)}…</code> · ${p.bytes} bytes · ${localStr}${creatorStr} ${badge}
|
|
||||||
</div>
|
const metaText = [
|
||||||
<div class="actions">
|
` · ${p.bytes} bytes`,
|
||||||
<button data-act="view">View</button>
|
` · ${p.ts}`,
|
||||||
<button data-act="save">Save blob</button>
|
p.tz ? ` · tz:${p.tz}` : "",
|
||||||
<button data-act="delete">Delete (server)</button>
|
p.author ? ` · by ${p.author.slice(0, 8)}…` : "",
|
||||||
<button data-act="remove">Remove (local)</button>
|
" "
|
||||||
</div>
|
].join("");
|
||||||
<pre class="content" style="white-space:pre-wrap;margin-top:.5rem;"></pre>`;
|
meta.appendChild(document.createTextNode(metaText));
|
||||||
const pre = div.querySelector(".content");
|
|
||||||
div.querySelector('[data-act="view"]').onclick = () => viewPost(p, pre);
|
const badge = document.createElement("span");
|
||||||
div.querySelector('[data-act="save"]').onclick = () => saveBlob(p);
|
badge.className = "badge";
|
||||||
div.querySelector('[data-act="delete"]').onclick = () => delServer(p);
|
badge.textContent = p.enc ? (p.mode==="private"?"private":"encrypted") : "plaintext";
|
||||||
div.querySelector('[data-act="remove"]').onclick = () => { setPosts(getPosts().filter(x=>x.hash!==p.hash)); };
|
meta.appendChild(badge);
|
||||||
els.posts.appendChild(div);
|
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
@@ -1,43 +1,20 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html>
|
<meta charset="utf-8">
|
||||||
<head>
|
<title>Signing you in…</title>
|
||||||
<meta charset="utf-8"/>
|
<script>
|
||||||
<title>GreenCoast — Auth Callback</title>
|
(function(){
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
const hash = new URLSearchParams(location.hash.slice(1));
|
||||||
<style>
|
const bearer = hash.get("bearer");
|
||||||
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; }
|
const next = hash.get("next") || "/";
|
||||||
.card { background:#0f1621; padding:1rem 1.2rem; border-radius:14px; max-width:560px; }
|
try {
|
||||||
.muted{ color:#8b949e; }
|
// Prefer sessionStorage; keep localStorage for backward compatibility
|
||||||
</style>
|
if (bearer) sessionStorage.setItem("gc_bearer", bearer);
|
||||||
</head>
|
const k = "gc_client_config_v1";
|
||||||
<body>
|
const cfg = JSON.parse(localStorage.getItem(k) || "{}");
|
||||||
<div class="card">
|
if (bearer) cfg.bearer = bearer;
|
||||||
<h3>Signing you in…</h3>
|
localStorage.setItem(k, JSON.stringify(cfg));
|
||||||
<div id="msg" class="muted">Please wait.</div>
|
} catch {}
|
||||||
</div>
|
history.replaceState(null, "", next);
|
||||||
<script type="module">
|
location.href = next;
|
||||||
const params = new URLSearchParams(location.search);
|
})();
|
||||||
const code = params.get("code");
|
|
||||||
const origin = location.origin; // shard and client served together
|
|
||||||
const msg = (t)=>document.getElementById("msg").textContent = t;
|
|
||||||
|
|
||||||
async function run() {
|
|
||||||
if (!code) { msg("Missing 'code' parameter."); return; }
|
|
||||||
try {
|
|
||||||
const r = await fetch(origin + "/v1/auth/discord/callback?assent=1&code=" + encodeURIComponent(code));
|
|
||||||
if (!r.ok) { msg("Exchange failed: " + r.status); return; }
|
|
||||||
const j = await r.json();
|
|
||||||
const key = "gc_client_config_v1";
|
|
||||||
const cfg = JSON.parse(localStorage.getItem(key) || "{}");
|
|
||||||
cfg.bearer = j.token;
|
|
||||||
localStorage.setItem(key, JSON.stringify(cfg));
|
|
||||||
msg("Success. Redirecting…");
|
|
||||||
setTimeout(()=>location.href="/", 800);
|
|
||||||
} catch(e) {
|
|
||||||
msg("Error: " + (e?.message || e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
run();
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
44
client/avatar.js
Normal file
44
client/avatar.js
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
// Deterministic, local-only avatars. No network calls.
|
||||||
|
export function avatarDataURL(seed, size = 40) {
|
||||||
|
// Hash seed → bytes
|
||||||
|
const h = sha256(seed);
|
||||||
|
// Colors from bytes
|
||||||
|
const hue = h[0] % 360;
|
||||||
|
const bg = `hsl(${(h[1]*3)%360} 25% 14%)`;
|
||||||
|
const fg = `hsl(${hue} 70% 60%)`;
|
||||||
|
|
||||||
|
// 5x5 grid mirrored; draw squares where bits set
|
||||||
|
const cells = 5, scale = Math.floor(size / cells);
|
||||||
|
let rects = "";
|
||||||
|
for (let y = 0; y < cells; y++) {
|
||||||
|
for (let x = 0; x < Math.ceil(cells/2); x++) {
|
||||||
|
const bit = (h[(y*3 + x) % h.length] >> (y % 5)) & 1;
|
||||||
|
if (bit) {
|
||||||
|
const xL = x*scale, xR = (cells-1-x)*scale, yP = y*scale;
|
||||||
|
rects += `<rect x="${xL}" y="${yP}" width="${scale}" height="${scale}" rx="2" ry="2" fill="${fg}"/>`;
|
||||||
|
if (x !== cells-1-x) {
|
||||||
|
rects += `<rect x="${xR}" y="${yP}" width="${scale}" height="${scale}" rx="2" ry="2" fill="${fg}"/>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${cells*scale} ${cells*scale}">
|
||||||
|
<rect width="100%" height="100%" fill="${bg}"/>${rects}
|
||||||
|
</svg>`;
|
||||||
|
return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svg)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha256(s) {
|
||||||
|
// Simple synchronous hash-ish bytes from string (non-cryptographic; fine for visuals)
|
||||||
|
let h1 = 0x6a09e667, h2 = 0xbb67ae85;
|
||||||
|
for (let i=0;i<s.length;i++) {
|
||||||
|
const c = s.charCodeAt(i);
|
||||||
|
h1 = (h1 ^ c) * 0x45d9f3b + ((h1<<7) | (h1>>>25));
|
||||||
|
h2 = (h2 ^ (c<<1)) * 0x27d4eb2d + ((h2<<9) | (h2>>>23));
|
||||||
|
}
|
||||||
|
const out = new Uint8Array(32);
|
||||||
|
for (let i=0;i<32;i++){
|
||||||
|
out[i] = (h1 >> (i%24)) ^ (h2 >> ((i*3)%24)) ^ (i*31);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
38
client/gdpr.html
Normal file
38
client/gdpr.html
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<title>GDPR Notice — GreenCoast</title>
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||||
|
<link rel="stylesheet" href="./styles.css"/>
|
||||||
|
</head>
|
||||||
|
<body class="container">
|
||||||
|
<h1>GDPR Notice</h1>
|
||||||
|
<p class="muted">Effective: 2025-08-22</p>
|
||||||
|
|
||||||
|
<h2>Controller</h2>
|
||||||
|
<p>The operator of this shard acts as data controller. Contact: <em>dsapelli@yahoo.com</em>.</p>
|
||||||
|
|
||||||
|
<h2>Lawful bases</h2>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Public posts:</strong> performance of service you request.</li>
|
||||||
|
<li><strong>Private posts:</strong> performance of service; encryption keys never leave your device.</li>
|
||||||
|
<li><strong>SSO (optional):</strong> your consent with the chosen provider.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>Minimization & storage</h2>
|
||||||
|
<p>No user profile, no behavioral analytics. Objects are stored by content hash; server logs are minimized and scrubbed of IPs/UA where feasible.</p>
|
||||||
|
|
||||||
|
<h2>International transfers</h2>
|
||||||
|
<p>Content may be hosted where you deploy the shard. Using third-party SSO may transfer data to those providers’ regions.</p>
|
||||||
|
|
||||||
|
<h2>Data subject rights</h2>
|
||||||
|
<p>Access/erasure/rectification: We do not keep a server-side identity. Uploaders can delete objects by hash if they still possess authorization. Encrypted content cannot be decrypted server-side.</p>
|
||||||
|
|
||||||
|
<h2>Complaints</h2>
|
||||||
|
<p>You may lodge a complaint with your local supervisory authority.</p>
|
||||||
|
|
||||||
|
<p class="muted small">This document is informational and not legal advice.</p>
|
||||||
|
<p><a href="./index.html">Back</a></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
@@ -4,71 +4,168 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<title>GreenCoast — Client</title>
|
<title>GreenCoast — Client</title>
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||||
<!-- Force API base for Cloudflare tunneled API -->
|
<!-- Hard-pin API host so mobiles pick the right shard -->
|
||||||
<meta name="gc-api-base" content="https://api-gc.fullmooncyberworks.com">
|
<meta name="gc-api-base" content="https://api-gc.fullmooncyberworks.com">
|
||||||
<link rel="stylesheet" href="./styles.css"/>
|
<link rel="stylesheet" href="./styles.css"/>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<header class="topbar">
|
||||||
<h1>GreenCoast (Client)</h1>
|
<div class="brand">GreenCoast</div>
|
||||||
|
<nav class="tabs">
|
||||||
|
<a data-route href="#/">Feed</a>
|
||||||
|
<a data-route href="#/privacy">Privacy</a>
|
||||||
|
<a data-route href="#/gdpr">GDPR</a>
|
||||||
|
<a data-route href="#/terms">Terms</a>
|
||||||
|
</nav>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="signIn" type="button">Sign in (device key)</button>
|
||||||
|
<button id="discordStart" type="button">Discord</button>
|
||||||
|
<button id="panic" type="button">Panic wipe</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
<section class="card">
|
<div id="capWarn" class="warn is-hidden"></div>
|
||||||
<h2>Connect</h2>
|
|
||||||
<div class="row">
|
<div id="banner" class="banner is-hidden">
|
||||||
<label>Shard URL</label>
|
You are in <strong>anonymous (limited) mode</strong>. Only plaintext posts are available until you authorize this device.
|
||||||
<input id="shardUrl" placeholder="https://api-gc.fullmooncyberworks.com" />
|
</div>
|
||||||
</div>
|
|
||||||
<div class="row">
|
<div class="shell">
|
||||||
<label>Bearer (optional)</label>
|
<aside id="left" class="col">
|
||||||
<input id="bearer" placeholder="dev-local-token" />
|
<section class="card">
|
||||||
</div>
|
<h3>Profile</h3>
|
||||||
<div class="row">
|
<div class="profile">
|
||||||
<label>Passphrase (private posts)</label>
|
<img id="avatar" alt="avatar" width="56" height="56"/>
|
||||||
<input id="passphrase" type="password" placeholder="••••••••" />
|
<div class="profile-meta">
|
||||||
</div>
|
<div><code id="fp">(pseudonymous)</code></div>
|
||||||
<div class="row">
|
<div class="muted small">Avatar is derived locally.</div>
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</section>
|
||||||
<button id="saveConn">Save</button>
|
|
||||||
<div id="health" class="muted"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<h2>Compose</h2>
|
<h3>Quick links</h3>
|
||||||
<div class="row">
|
<ul class="links">
|
||||||
<label>Visibility</label>
|
<li><a data-route href="#/">Feed</a></li>
|
||||||
<select id="visibility">
|
<li><a data-route href="#/privacy">Privacy Policy</a></li>
|
||||||
<option value="public">Public (plaintext)</option>
|
<li><a data-route href="#/gdpr">GDPR</a></li>
|
||||||
<option value="private">Private (E2EE via passphrase)</option>
|
<li><a data-route href="#/terms">Terms</a></li>
|
||||||
</select>
|
</ul>
|
||||||
</div>
|
</section>
|
||||||
<div class="row">
|
</aside>
|
||||||
<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>
|
|
||||||
<div class="row">
|
|
||||||
<label><input type="checkbox" id="shareTZ" checked> Include my time zone on this post</label>
|
|
||||||
</div>
|
|
||||||
<button id="publish">Publish</button>
|
|
||||||
<div id="publishStatus" class="muted"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="card">
|
<main id="feed" class="col">
|
||||||
<h2>Posts (live index)</h2>
|
<section class="card">
|
||||||
<div id="posts"></div>
|
<h2>Connection</h2>
|
||||||
</section>
|
<div class="row">
|
||||||
|
<label>Shard URL</label>
|
||||||
|
<input id="shardUrl" placeholder="https://api-gc.fullmooncyberworks.com"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<details id="adv" class="advanced">
|
||||||
|
<summary>Advanced (security)</summary>
|
||||||
|
<div class="row">
|
||||||
|
<label>Bearer (hidden)</label>
|
||||||
|
<input id="bearer" type="password" placeholder="gc2 token" autocomplete="off"/>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<label>Passphrase (for Private-Encrypted)</label>
|
||||||
|
<input id="passphrase" type="password" placeholder="••••••••" autocomplete="off"/>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">
|
||||||
|
Security fields are local to your browser. We do not store PII or logs.
|
||||||
|
Third-party SSO is optional and not endorsed for security.
|
||||||
|
</p>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<button id="saveConn" type="button">Save</button>
|
||||||
|
<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="plaintext">Plaintext (last resort)</option>
|
||||||
|
<option value="members">Public-Encrypted (members)</option>
|
||||||
|
<option value="private">Private-Encrypted (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" type="button">Publish</button>
|
||||||
|
<div id="publishStatus" class="muted status"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Posts (live index)</h2>
|
||||||
|
<div id="posts"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<main id="page" class="col is-hidden">
|
||||||
|
<section class="card">
|
||||||
|
<div id="pageContent">Loading…</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<aside id="right" class="col">
|
||||||
|
<section class="card">
|
||||||
|
<h3>About</h3>
|
||||||
|
<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>
|
||||||
|
<ul class="links">
|
||||||
|
<li><a data-route href="#/privacy">Privacy</a></li>
|
||||||
|
<li><a data-route href="#/gdpr">GDPR</a></li>
|
||||||
|
<li><a data-route href="#/terms">Terms</a></li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<footer class="footer">
|
||||||
|
<a data-route href="#/privacy">Privacy</a> ·
|
||||||
|
<a data-route href="#/gdpr">GDPR</a> ·
|
||||||
|
<a data-route href="#/terms">Terms</a>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<div id="flash" class="flash"></div>
|
||||||
|
|
||||||
<script type="module" src="./app.js"></script>
|
<script type="module" src="./app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
41
client/privacy.html
Normal file
41
client/privacy.html
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<title>Privacy Policy — GreenCoast</title>
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||||
|
<link rel="stylesheet" href="./styles.css"/>
|
||||||
|
</head>
|
||||||
|
<body class="container">
|
||||||
|
<h1>Privacy Policy</h1>
|
||||||
|
<p class="muted">Effective: 2025-08-22</p>
|
||||||
|
|
||||||
|
<h2>What we are</h2>
|
||||||
|
<p>GreenCoast is a zero-trust, end-to-end encrypted (E2EE) social platform. By default, we do not collect analytics, do not store personal data, and do not maintain server logs that identify users.</p>
|
||||||
|
|
||||||
|
<h2>Data we process</h2>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Public posts:</strong> Stored as plaintext objects keyed by content hash. No account profile is required.</li>
|
||||||
|
<li><strong>Private posts:</strong> Encrypted <em>client-side</em> with a passphrase only you know. The server sees ciphertext only.</li>
|
||||||
|
<li><strong>Authorization:</strong> Device-key and/or third-party SSO (if you choose) issue a short-lived bearer. We do not persist profile data.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>Third-party SSO</h2>
|
||||||
|
<p>If you use Discord/Google/etc., those providers may process your data under their own terms. We cannot vouch for their security.</p>
|
||||||
|
|
||||||
|
<h2>Cookies & local storage</h2>
|
||||||
|
<p>We use browser storage on your device to keep connection settings and, if you choose, session tokens. You can wipe them with “Panic wipe”.</p>
|
||||||
|
|
||||||
|
<h2>Security</h2>
|
||||||
|
<p>E2EE for private content, proof-of-possession on mutations, rate-limits, CSP/COOP/COEP, and optional hardware keys via WebAuthn (if enabled on your shard).</p>
|
||||||
|
|
||||||
|
<h2>Your rights</h2>
|
||||||
|
<p>Because we do not maintain user identities or server-side profiles, requests to access/correct/erase personal data typically do not apply. For encrypted content, we cannot decrypt it for you.</p>
|
||||||
|
|
||||||
|
<h2>Contact</h2>
|
||||||
|
<p>Email: <em>dsapelli@yahoo.com</em></p>
|
||||||
|
|
||||||
|
<p class="muted small">This page describes our reference shard. Self-hosted deployments may differ.</p>
|
||||||
|
<p><a href="./index.html">Back</a></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
@@ -1,18 +1,72 @@
|
|||||||
:root { --bg:#0b1117; --card:#0f1621; --fg:#e6edf3; --muted:#8b949e; --accent:#2ea043; }
|
:root{
|
||||||
* { box-sizing: border-box; }
|
--bg:#0f172a;--surface:#111827;--muted:#8b949e;--text:#e5e7eb;--accent:#22c55e;
|
||||||
body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial; background:var(--bg); color:var(--fg); }
|
--card:#0b1222;--border:#1f2937;--tab:#0b1222;--tab-active:#1f2937
|
||||||
.container { max-width: 900px; margin: 2rem auto; padding: 0 1rem; }
|
}
|
||||||
h1 { font-size: 1.5rem; margin-bottom: 1rem; }
|
*{box-sizing:border-box}
|
||||||
.card { background: var(--card); border-radius: 14px; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 8px 24px rgba(0,0,0,.3); }
|
html,body{margin:0;padding:0;background:var(--bg);color:var(--text);
|
||||||
h2 { margin-top: 0; font-size: 1.1rem; }
|
font-family:ui-sans-serif,system-ui,Segoe UI,Roboto,Ubuntu,"Helvetica Neue","Noto Sans",Arial}
|
||||||
.row { display: grid; grid-template-columns: 160px 1fr; gap: .75rem; align-items: center; margin: .5rem 0; }
|
a{color:#93c5fd;text-decoration:none}
|
||||||
label { color: var(--muted); }
|
a:hover{text-decoration:underline}
|
||||||
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; }
|
.topbar{display:flex;align-items:center;justify-content:space-between;padding:.6rem 1rem;
|
||||||
button:hover { filter: brightness(1.05); }
|
border-bottom:1px solid var(--border);background:#0b1222;position:sticky;top:0;z-index:10}
|
||||||
.muted { color: var(--muted); margin-top: .5rem; font-size: .9rem; }
|
.brand{font-weight:700}
|
||||||
.post { border: 1px solid #1d2734; border-radius: 12px; padding: .75rem; margin: .5rem 0; background: #0c1824; }
|
.actions button{margin-left:.5rem}
|
||||||
.post .meta { font-size: .85rem; color: var(--muted); margin-bottom: .4rem; }
|
button{background:#134e4a;border:1px solid #0f766e;color:white;border-radius:.6rem;padding:.45rem .7rem;cursor:pointer}
|
||||||
.post .actions { margin-top: .5rem; display:flex; gap:.5rem; }
|
button:hover{filter:brightness(1.05)}
|
||||||
code { background:#0a1320; padding:.15rem .35rem; border-radius:6px; }
|
input[type="password"]{letter-spacing:.2em}
|
||||||
.badge { font-size:.75rem; padding:.1rem .4rem; border-radius: 999px; background:#132235; color:#9fb7d0; margin-left:.5rem; }
|
|
||||||
|
.tabs{display:flex;gap:.25rem;margin:0 .75rem}
|
||||||
|
.tabs a{padding:.35rem .6rem;border:1px solid var(--border);border-radius:.5rem;background:var(--tab)}
|
||||||
|
.tabs a.active{background:var(--tab-active);border-color:#334155}
|
||||||
|
|
||||||
|
.banner{background:#1f2937;color:#e5e7eb;border-bottom:1px solid var(--border);padding:.6rem 1rem}
|
||||||
|
|
||||||
|
.shell{max-width:1100px;margin:1rem auto;display:grid;grid-template-columns:280px 1fr 300px;gap:1rem;padding:0 1rem}
|
||||||
|
.col{min-width:0}
|
||||||
|
.card{background:var(--card);border:1px solid var(--border);border-radius:.75rem;padding:1rem;margin-bottom:1rem}
|
||||||
|
.row{display:flex;gap:.75rem;align-items:center;margin:.5rem 0}
|
||||||
|
.row label{min-width:140px;color:#cbd5e1}
|
||||||
|
.row input,.row select,textarea{flex:1;background:#0f172a;border:1px solid var(--border);border-radius:.5rem;padding:.55rem .65rem;color:var(--text)}
|
||||||
|
.muted{color:var(--muted)} .small{font-size:.9rem}
|
||||||
|
.profile{display:flex;align-items:center;gap:1rem}
|
||||||
|
#avatar{border-radius:50%;border:1px solid var(--border);background:#0f172a;image-rendering:pixelated}
|
||||||
|
|
||||||
|
.post{border:1px dashed var(--border);border-radius:.5rem;padding:.6rem .7rem;margin-bottom:.6rem}
|
||||||
|
.post .meta{color:var(--muted);font-size:.9rem;margin-bottom:.25rem}
|
||||||
|
.badge{background:var(--surface);border:1px solid var(--border);border-radius:999px;padding:.05rem .5rem;font-size:.75rem;margin-left:.5rem}
|
||||||
|
|
||||||
|
.advanced summary{cursor:pointer;color:#cbd5e1;margin:.25rem 0}
|
||||||
|
.links{list-style:none;padding:0;margin:0}
|
||||||
|
.links li{margin:.25rem 0}
|
||||||
|
|
||||||
|
.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}
|
||||||
|
#feed,#page{order:1}
|
||||||
|
}
|
||||||
|
33
client/terms.html
Normal file
33
client/terms.html
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<title>Terms of Service — GreenCoast</title>
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||||
|
<link rel="stylesheet" href="./styles.css"/>
|
||||||
|
</head>
|
||||||
|
<body class="container">
|
||||||
|
<h1>Terms of Service</h1>
|
||||||
|
<p class="muted">Effective: 2025-08-22</p>
|
||||||
|
|
||||||
|
<h2>Service</h2>
|
||||||
|
<p>GreenCoast is provided “as-is”, with no warranties. You may self-host under the Unlicense. This reference shard has no paid plans.</p>
|
||||||
|
|
||||||
|
<h2>User content</h2>
|
||||||
|
<p>You are responsible for content you publish. Do not post illegal content or abuse others. We reserve the right to remove content that violates applicable law.</p>
|
||||||
|
|
||||||
|
<h2>Accounts & authorization</h2>
|
||||||
|
<p>Device-key and optional SSO are used to prove control of a device. We do not maintain user profiles.</p>
|
||||||
|
|
||||||
|
<h2>Third-party services</h2>
|
||||||
|
<p>If you connect SSO providers, your use of those services is governed by their terms and privacy policies.</p>
|
||||||
|
|
||||||
|
<h2>Limitation of liability</h2>
|
||||||
|
<p>To the fullest extent permitted by law, the operator is not liable for indirect or consequential damages.</p>
|
||||||
|
|
||||||
|
<h2>Changes</h2>
|
||||||
|
<p>We may update these Terms by posting a new version on this page.</p>
|
||||||
|
|
||||||
|
<p><a href="./index.html">Back</a></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
@@ -1,154 +1,241 @@
|
|||||||
|
// cmd/shard/main.go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"greencoast/internal/api"
|
"greencoast/internal/api"
|
||||||
"greencoast/internal/index"
|
"greencoast/internal/index"
|
||||||
"greencoast/internal/storage"
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func getenvBool(key string, def bool) bool {
|
type cfgPrivacy struct {
|
||||||
v := os.Getenv(key)
|
AllowAnonPlaintext bool `yaml:"allow_anon_plaintext"`
|
||||||
if v == "" {
|
}
|
||||||
return def
|
type shardConfig struct {
|
||||||
}
|
Privacy cfgPrivacy `yaml:"privacy"`
|
||||||
b, err := strconv.ParseBool(v)
|
|
||||||
if err != nil {
|
|
||||||
return def
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func staticHeaders(next http.Handler) http.Handler {
|
func boolEnv(keys ...string) bool {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
for _, k := range keys {
|
||||||
// Same security posture as API
|
v := strings.ToLower(strings.TrimSpace(os.Getenv(k)))
|
||||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
if v == "1" || v == "true" || v == "yes" || v == "on" {
|
||||||
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
return true
|
||||||
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")
|
|
||||||
|
|
||||||
// Basic CORS for client assets
|
|
||||||
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)
|
}
|
||||||
})
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func loadYAMLAllow(path string) bool {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
var sc shardConfig
|
||||||
|
if err := yaml.NewDecoder(f).Decode(&sc); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return sc.Privacy.AllowAnonPlaintext
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------
|
||||||
|
Minimal FS blob store (implements api.BlobStore)
|
||||||
|
Layout:
|
||||||
|
/var/lib/greencoast/objects/<hash> content
|
||||||
|
/var/lib/greencoast/objects/<hash>.priv empty sidecar => private
|
||||||
|
--------------------------*/
|
||||||
|
|
||||||
|
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() {
|
func main() {
|
||||||
// ---- Config via env ----
|
// Store & index
|
||||||
httpAddr := os.Getenv("GC_HTTP_ADDR")
|
store := newFSStore("/var/lib/greencoast/objects")
|
||||||
if httpAddr == "" {
|
idx := index.New()
|
||||||
httpAddr = ":9080" // API
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optional TLS for API
|
// Flags: env wins, else YAML (/app/shard.yaml), else false
|
||||||
httpsAddr := os.Getenv("GC_HTTPS_ADDR") // leave empty for HTTP
|
allowAnon := boolEnv("GC_ALLOW_ANON_PLAINTEXT")
|
||||||
certFile := os.Getenv("GC_TLS_CERT")
|
if !allowAnon {
|
||||||
keyFile := os.Getenv("GC_TLS_KEY")
|
if st, err := os.Stat("/app/shard.yaml"); err == nil && !st.IsDir() {
|
||||||
|
allowAnon = loadYAMLAllow("/app/shard.yaml")
|
||||||
dataDir := os.Getenv("GC_DATA_DIR")
|
|
||||||
if dataDir == "" {
|
|
||||||
dataDir = "/var/lib/greencoast"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Static dir + port (frontend)
|
|
||||||
staticDir := os.Getenv("GC_STATIC_DIR")
|
|
||||||
if staticDir == "" {
|
|
||||||
staticDir = "/opt/greencoast/client"
|
|
||||||
}
|
|
||||||
staticAddr := os.Getenv("GC_STATIC_ADDR")
|
|
||||||
if staticAddr == "" {
|
|
||||||
staticAddr = ":9082"
|
|
||||||
}
|
|
||||||
|
|
||||||
coarseTS := getenvBool("GC_COARSE_TS", false)
|
|
||||||
zeroTrust := getenvBool("GC_ZERO_TRUST", true)
|
|
||||||
signingSecretHex := os.Getenv("GC_SIGNING_SECRET_HEX")
|
|
||||||
|
|
||||||
// Discord SSO
|
|
||||||
discID := os.Getenv("GC_DISCORD_CLIENT_ID")
|
|
||||||
discSecret := os.Getenv("GC_DISCORD_CLIENT_SECRET")
|
|
||||||
discRedirect := os.Getenv("GC_DISCORD_REDIRECT_URI")
|
|
||||||
|
|
||||||
// ---- Storage ----
|
|
||||||
store, err := storage.NewFS(dataDir)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("storage init: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Index ----
|
|
||||||
ix := index.New()
|
|
||||||
|
|
||||||
// Optional: auto-reindex from disk on boot
|
|
||||||
if w, ok := any(store).(interface {
|
|
||||||
Walk(func(hash string, size int64, mod time.Time) error) error
|
|
||||||
}); ok {
|
|
||||||
if err := w.Walk(func(hash string, size int64, mod time.Time) error {
|
|
||||||
return ix.Put(index.Entry{
|
|
||||||
Hash: hash,
|
|
||||||
Bytes: size,
|
|
||||||
StoredAt: mod.UTC().Format(time.RFC3339Nano),
|
|
||||||
Private: false,
|
|
||||||
})
|
|
||||||
}); err != nil {
|
|
||||||
log.Printf("reindex on boot: %v", err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
devMode := boolEnv("GC_DEV_ALLOW_UNAUTH")
|
||||||
|
|
||||||
// ---- Auth/Providers ----
|
log.Printf("boot: privacy.allow_anon_plaintext=%v dev=%v at=%s", allowAnon, devMode, time.Now().UTC().Format(time.RFC3339))
|
||||||
ap := api.AuthProviders{
|
|
||||||
SigningSecretHex: signingSecretHex,
|
|
||||||
Discord: api.DiscordProvider{
|
|
||||||
Enabled: discID != "" && discSecret != "" && discRedirect != "",
|
|
||||||
ClientID: discID,
|
|
||||||
ClientSecret: discSecret,
|
|
||||||
RedirectURI: discRedirect,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- API server (9080/HTTPS optional) ----
|
var providers api.AuthProviders
|
||||||
srv := api.New(store, ix, coarseTS, zeroTrust, ap)
|
srv := api.New(store, idx, true, devMode, providers, allowAnon)
|
||||||
|
|
||||||
// Serve the static client in a goroutine on 9082
|
// Frontend (static)
|
||||||
go func() {
|
go func() {
|
||||||
if st, err := os.Stat(staticDir); err != nil || !st.IsDir() {
|
if err := srv.ListenFrontend("0.0.0.0:9082"); err != nil {
|
||||||
log.Printf("WARN: GC_STATIC_DIR %q not found or not a dir; client may 404", staticDir)
|
log.Printf("frontend server exited: %v", err)
|
||||||
}
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
mux.Handle("/", http.FileServer(http.Dir(staticDir)))
|
|
||||||
log.Printf("static listening on %s (dir=%s)", staticAddr, staticDir)
|
|
||||||
if err := http.ListenAndServe(staticAddr, staticHeaders(mux)); err != nil {
|
|
||||||
log.Fatalf("static server: %v", err)
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Prefer HTTPS if configured
|
// API
|
||||||
if httpsAddr != "" && certFile != "" && keyFile != "" {
|
if err := srv.ListenHTTP("0.0.0.0:9080"); err != nil {
|
||||||
log.Printf("starting HTTPS API on %s", httpsAddr)
|
|
||||||
if err := srv.ListenHTTPS(httpsAddr, certFile, keyFile); err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Otherwise HTTP
|
|
||||||
log.Printf("starting HTTP API on %s", httpAddr)
|
|
||||||
if err := srv.ListenHTTP(httpAddr); err != nil {
|
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = time.Second
|
|
||||||
}
|
}
|
||||||
|
@@ -1,32 +1,32 @@
|
|||||||
shard_id: "gc-test-001"
|
shard_id: "gc-test-001"
|
||||||
|
|
||||||
listen:
|
listen:
|
||||||
http: "0.0.0.0:9080" # API for testers
|
http: "0.0.0.0:9080"
|
||||||
https: "" # if you terminate TLS at a proxy, leave empty
|
https: ""
|
||||||
ws: "0.0.0.0:9081" # reserved
|
ws: "0.0.0.0:9081"
|
||||||
|
|
||||||
tls:
|
tls:
|
||||||
enable: false # set true only if serving HTTPS directly here
|
enable: false
|
||||||
cert_file: "/etc/greencoast/tls/cert.pem"
|
cert_file: "/etc/greencoast/tls/cert.pem"
|
||||||
key_file: "/etc/greencoast/tls/key.pem"
|
key_file: "/etc/greencoast/tls/key.pem"
|
||||||
|
|
||||||
federation:
|
federation:
|
||||||
mtls_enable: false
|
mtls_enable: false
|
||||||
listen: "0.0.0.0:9443"
|
listen: "0.0.0.0:9443"
|
||||||
cert_file: "/etc/greencoast/fed/cert.pem"
|
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"
|
client_ca_file: "/etc/greencoast/fed/clients_ca.pem"
|
||||||
|
|
||||||
ui:
|
ui:
|
||||||
enable: true
|
enable: true
|
||||||
path: "./client"
|
path: "./client"
|
||||||
base_url: "/"
|
base_url: "/"
|
||||||
frontend_http: "0.0.0.0:9082" # static client for testers
|
frontend_http: "0.0.0.0:9082"
|
||||||
|
|
||||||
storage:
|
storage:
|
||||||
backend: "fs"
|
backend: "fs"
|
||||||
path: "/var/lib/greencoast/objects"
|
path: "/var/lib/greencoast/objects"
|
||||||
max_object_kb: 128 # lower if you want to constrain uploads
|
max_object_kb: 128
|
||||||
|
|
||||||
security:
|
security:
|
||||||
zero_trust: true
|
zero_trust: true
|
||||||
@@ -38,27 +38,20 @@ privacy:
|
|||||||
retain_ip: "no"
|
retain_ip: "no"
|
||||||
retain_user_agent: "no"
|
retain_user_agent: "no"
|
||||||
retain_timestamps: "coarse"
|
retain_timestamps: "coarse"
|
||||||
|
allow_anon_plaintext: true
|
||||||
|
|
||||||
auth:
|
auth:
|
||||||
# IMPORTANT: rotate this per environment (use `openssl rand -hex 32`)
|
# Choose either YAML OR env for the signing secret — not both.
|
||||||
signing_secret: "D941C4F91D0046D28CDBC3F425DE0B4EA26BD2A80434E0F160D1B7C813EB43F8"
|
# If you keep it here, make sure it's EXACTLY the same as the env value.
|
||||||
|
signing_secret: GC_SIGNING_SECRET_HEX
|
||||||
sso:
|
sso:
|
||||||
discord:
|
discord:
|
||||||
enabled: true
|
enabled: true
|
||||||
client_id: "1408292766319906946"
|
client_id: GC_DISCORD_CLIENT_ID
|
||||||
client_secret: "zJ6GnUUykHbMFbWsPPneNxNK-PtOXYg1"
|
client_secret: GC_DISCORD_CLIENT_SECRET
|
||||||
# must exactly match your Discord app's allowed redirect
|
redirect_uri: GC_DISCORD_REDIRECT_URI
|
||||||
redirect_uri: "https://greencoast.fullmooncyberworks.com/auth-callback.html"
|
google: { enabled: false, client_id: "", client_secret: "", redirect_uri: "" }
|
||||||
google:
|
facebook: { enabled: false, client_id: "", client_secret: "", redirect_uri: "" }
|
||||||
enabled: false
|
|
||||||
client_id: ""
|
|
||||||
client_secret: ""
|
|
||||||
redirect_uri: ""
|
|
||||||
facebook:
|
|
||||||
enabled: false
|
|
||||||
client_id: ""
|
|
||||||
client_secret: ""
|
|
||||||
redirect_uri: ""
|
|
||||||
two_factor:
|
two_factor:
|
||||||
webauthn_enabled: false
|
webauthn_enabled: false
|
||||||
totp_enabled: false
|
totp_enabled: false
|
||||||
@@ -66,4 +59,4 @@ auth:
|
|||||||
limits:
|
limits:
|
||||||
rate:
|
rate:
|
||||||
burst: 20
|
burst: 20
|
||||||
per_minute: 60 # slightly tighter for external testing
|
per_minute: 60
|
||||||
|
@@ -1,17 +1,14 @@
|
|||||||
version: "3.9"
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
shard-test:
|
shard-test:
|
||||||
build: .
|
build: .
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
container_name: greencoast-shard-test
|
container_name: greencoast-shard-test
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
user: "0:0"
|
user: "0:0"
|
||||||
# These ports are optional (useful for local debug). Tunnel doesn't need them.
|
|
||||||
ports:
|
ports:
|
||||||
- "9080:9080" # API
|
- "9080:9080"
|
||||||
- "9082:9082" # Frontend
|
- "9082:9082"
|
||||||
environment:
|
|
||||||
- GC_DEV_ALLOW_UNAUTH=true
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./testdata:/var/lib/greencoast
|
- ./testdata:/var/lib/greencoast
|
||||||
- ./configs/shard.test.yaml:/app/shard.yaml:ro
|
- ./configs/shard.test.yaml:/app/shard.yaml:ro
|
||||||
|
@@ -11,6 +11,7 @@ services:
|
|||||||
- "8081:8081"
|
- "8081:8081"
|
||||||
environment:
|
environment:
|
||||||
- GC_DEV_ALLOW_UNAUTH=false
|
- GC_DEV_ALLOW_UNAUTH=false
|
||||||
|
- GC_SIGNING_SECRET_HEX=92650f92d67d55368c852713a5007b90d933bff507bc77c980de7bf5442844ca
|
||||||
volumes:
|
volumes:
|
||||||
- gc_data:/var/lib/greencoast
|
- gc_data:/var/lib/greencoast
|
||||||
- ./configs/shard.sample.yaml:/app/shard.yaml:ro
|
- ./configs/shard.sample.yaml:/app/shard.yaml:ro
|
||||||
|
@@ -1,22 +1,18 @@
|
|||||||
|
// internal/api/http.go
|
||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"crypto/hmac"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"mime"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -24,162 +20,87 @@ import (
|
|||||||
"greencoast/internal/index"
|
"greencoast/internal/index"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BlobStore is the minimal storage interface the API needs.
|
// ---- Contracts ----
|
||||||
|
|
||||||
type BlobStore interface {
|
type BlobStore interface {
|
||||||
Put(hash string, r io.Reader) error
|
|
||||||
Get(hash string) (io.ReadCloser, int64, error)
|
Get(hash string) (io.ReadCloser, int64, error)
|
||||||
|
Put(r io.Reader, private bool) (hash string, n int64, storedAt time.Time, err error)
|
||||||
Delete(hash string) error
|
Delete(hash string) error
|
||||||
|
Walk(fn func(hash string, bytes int64, private bool, storedAt time.Time) error) (int, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// optional capability for stores that can enumerate blobs
|
type AuthProviders struct{}
|
||||||
type blobWalker interface {
|
|
||||||
Walk(func(hash string, size int64, mod time.Time) error) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
// ---- Server ----
|
||||||
// Public wiring
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
type DiscordProvider struct {
|
|
||||||
Enabled bool
|
|
||||||
ClientID string
|
|
||||||
ClientSecret string
|
|
||||||
RedirectURI string
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuthProviders struct {
|
|
||||||
SigningSecretHex string // HMAC secret in hex
|
|
||||||
Discord DiscordProvider
|
|
||||||
|
|
||||||
GoogleEnabled bool
|
|
||||||
FacebookEnabled bool
|
|
||||||
|
|
||||||
WebAuthnEnabled bool
|
|
||||||
TOTPEnabled bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
mux *http.ServeMux
|
Mux *http.ServeMux // exported for other files
|
||||||
|
mux *http.ServeMux // alias
|
||||||
|
|
||||||
store BlobStore
|
store BlobStore
|
||||||
idx *index.Index
|
idx *index.Index
|
||||||
|
uiOn bool
|
||||||
|
|
||||||
coarseTS bool
|
devAllowUnauth bool
|
||||||
zeroTrust bool
|
allowAnonPlaintext bool
|
||||||
|
|
||||||
allowClientSignedTokens bool // accept self-signed tokens (no DB)
|
StaticDir string
|
||||||
signingKey []byte
|
|
||||||
|
|
||||||
// dev flags (from env)
|
sseMu sync.Mutex
|
||||||
allowUnauth bool
|
sseSubs map[chan []byte]struct{}
|
||||||
devBearer string
|
|
||||||
|
|
||||||
// SSE fanout (in-process)
|
|
||||||
sseMu sync.Mutex
|
|
||||||
sseSubs map[chan []byte]struct{}
|
|
||||||
sseClosed bool
|
|
||||||
|
|
||||||
// SSO ephemeral state
|
|
||||||
stateMu sync.Mutex
|
|
||||||
states map[string]time.Time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// New constructs the API server and registers routes.
|
// New(store, idx, enableUI, devMode, providers, allowAnonPlaintext)
|
||||||
func New(store BlobStore, idx *index.Index, coarseTS bool, zeroTrust bool, providers AuthProviders) *Server {
|
func New(store BlobStore, idx *index.Index, enableUI bool, devMode bool, _ AuthProviders, allowAnonPlaintext bool) *Server {
|
||||||
key, _ := hex.DecodeString(strings.TrimSpace(providers.SigningSecretHex))
|
m := http.NewServeMux()
|
||||||
s := &Server{
|
s := &Server{
|
||||||
mux: http.NewServeMux(),
|
Mux: m,
|
||||||
store: store,
|
mux: m,
|
||||||
idx: idx,
|
store: store,
|
||||||
coarseTS: coarseTS,
|
idx: idx,
|
||||||
zeroTrust: zeroTrust,
|
uiOn: enableUI,
|
||||||
allowClientSignedTokens: true,
|
devAllowUnauth: devMode,
|
||||||
signingKey: key,
|
allowAnonPlaintext: allowAnonPlaintext,
|
||||||
allowUnauth: os.Getenv("GC_DEV_ALLOW_UNAUTH") == "true",
|
StaticDir: "./client",
|
||||||
devBearer: os.Getenv("GC_DEV_BEARER"),
|
sseSubs: make(map[chan []byte]struct{}),
|
||||||
sseSubs: make(map[chan []byte]struct{}),
|
|
||||||
states: make(map[string]time.Time),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MIME safety (minimal base images can be sparse)
|
// Health + caps
|
||||||
_ = mime.AddExtensionType(".js", "application/javascript; charset=utf-8")
|
s.Mux.HandleFunc("/healthz", s.healthz)
|
||||||
_ = mime.AddExtensionType(".css", "text/css; charset=utf-8")
|
s.Mux.HandleFunc("/v1/caps", s.handleCaps)
|
||||||
_ = mime.AddExtensionType(".html", "text/html; charset=utf-8")
|
|
||||||
_ = mime.AddExtensionType(".map", "application/json; charset=utf-8")
|
|
||||||
|
|
||||||
// Core
|
// Object I/O
|
||||||
s.mux.HandleFunc("/healthz", s.handleHealthz)
|
s.Mux.Handle("/v1/object", s.requireAuth(http.HandlerFunc(s.handlePutObject))) // PUT
|
||||||
|
s.Mux.Handle("/v1/object/", s.requireAuth(http.HandlerFunc(s.handleObjectByHash))) // GET/DELETE
|
||||||
|
|
||||||
// Objects
|
// Index (public read)
|
||||||
s.mux.Handle("/v1/object", s.withCORS(http.HandlerFunc(s.handlePutObject)))
|
s.Mux.HandleFunc("/v1/index", s.handleIndex)
|
||||||
s.mux.Handle("/v1/object/", s.withCORS(http.HandlerFunc(s.handleObjectByHash)))
|
s.Mux.HandleFunc("/v1/index/stream", s.handleIndexStream)
|
||||||
|
|
||||||
// Index + SSE
|
|
||||||
s.mux.Handle("/v1/index", s.withCORS(http.HandlerFunc(s.handleIndex)))
|
|
||||||
s.mux.Handle("/v1/index/stream", s.withCORS(http.HandlerFunc(s.handleIndexSSE)))
|
|
||||||
|
|
||||||
// GDPR+policy endpoint (minimal; no PII)
|
|
||||||
s.mux.Handle("/v1/gdpr/policy", s.withCORS(http.HandlerFunc(s.handleGDPRPolicy)))
|
|
||||||
|
|
||||||
// Admin: reindex from disk if store supports Walk
|
|
||||||
s.mux.Handle("/v1/admin/reindex", s.withCORS(http.HandlerFunc(s.handleAdminReindex)))
|
|
||||||
|
|
||||||
// Discord SSO
|
|
||||||
s.mux.Handle("/v1/auth/discord/start", s.withCORS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
s.handleDiscordStart(w, r, providers.Discord)
|
|
||||||
})))
|
|
||||||
s.mux.Handle("/v1/auth/discord/callback", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
s.handleDiscordCallback(w, r, providers.Discord)
|
|
||||||
}))
|
|
||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenHTTP serves the API on addr.
|
|
||||||
func (s *Server) ListenHTTP(addr string) error {
|
func (s *Server) ListenHTTP(addr string) error {
|
||||||
log.Printf("http listening on %s", addr)
|
handler := corsSecurity(s.Mux)
|
||||||
server := &http.Server{
|
server := &http.Server{Addr: addr, Handler: handler}
|
||||||
Addr: addr,
|
|
||||||
Handler: s.withCORS(s.mux),
|
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
|
||||||
}
|
|
||||||
return server.ListenAndServe()
|
return server.ListenAndServe()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenHTTPS serves TLS directly.
|
// ---- Global CORS/security ----
|
||||||
func (s *Server) ListenHTTPS(addr, certFile, keyFile string) error {
|
|
||||||
log.Printf("https listening on %s", addr)
|
|
||||||
server := &http.Server{
|
|
||||||
Addr: addr,
|
|
||||||
Handler: s.withCORS(s.mux),
|
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
|
||||||
}
|
|
||||||
return server.ListenAndServeTLS(certFile, keyFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
func corsSecurity(next http.Handler) http.Handler {
|
||||||
// Middleware / headers
|
allowedHeaders := "Authorization, Content-Type, X-GC-Private, X-GC-3P-Assent, X-GC-TZ, X-GC-Key, X-GC-TS, X-GC-Proof"
|
||||||
// -----------------------------
|
allowedMethods := "GET, PUT, POST, DELETE, OPTIONS"
|
||||||
|
|
||||||
func (s *Server) secureHeaders(w http.ResponseWriter) {
|
|
||||||
// Privacy / security posture
|
|
||||||
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")
|
|
||||||
// HSTS (harmless over HTTP; browsers only enforce under HTTPS)
|
|
||||||
w.Header().Set("Strict-Transport-Security", "max-age=15552000; includeSubDomains; preload")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) withCORS(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
s.secureHeaders(w)
|
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, DELETE, OPTIONS")
|
w.Header().Set("Access-Control-Allow-Methods", allowedMethods)
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-GC-Private, X-GC-3P-Assent, X-GC-TZ")
|
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
w.Header().Set("X-Frame-Options", "DENY")
|
||||||
|
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=()")
|
||||||
if r.Method == http.MethodOptions {
|
if r.Method == http.MethodOptions {
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
@@ -188,194 +109,148 @@ func (s *Server) withCORS(next http.Handler) http.Handler {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------
|
// ---- Auth (with anon-plaintext bypass) ----
|
||||||
// Health & policy
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) isPlaintextPut(r *http.Request) bool {
|
||||||
s.secureHeaders(w)
|
if !s.allowAnonPlaintext {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if r.Method != http.MethodPut {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.URL.Path, "/v1/object") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if r.Header.Get("X-GC-Private") == "1" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if s.isPlaintextPut(r) || s.devAllowUnauth {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bearer := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer"))
|
||||||
|
hasPoP := r.Header.Get("X-GC-Key") != "" && r.Header.Get("X-GC-TS") != "" && r.Header.Get("X-GC-Proof") != ""
|
||||||
|
if bearer != "" || hasPoP {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Small utils ----
|
||||||
|
|
||||||
|
func ReadAllStrict(r io.Reader, max int64) ([]byte, error) {
|
||||||
|
if max <= 0 {
|
||||||
|
return io.ReadAll(r)
|
||||||
|
}
|
||||||
|
lr := io.LimitedReader{R: r, N: max + 1}
|
||||||
|
b, err := io.ReadAll(&lr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if int64(len(b)) > max {
|
||||||
|
return nil, errors.New("payload too large")
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func maxObjectBytes() int64 {
|
||||||
|
v := strings.TrimSpace(os.Getenv("GC_MAX_OBJECT_KB"))
|
||||||
|
if v == "" {
|
||||||
|
return 256 * 1024 // default 256 KiB
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil || n <= 0 {
|
||||||
|
return 256 * 1024
|
||||||
|
}
|
||||||
|
return int64(n) * 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Basic endpoints ----
|
||||||
|
|
||||||
|
func (s *Server) healthz(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
io.WriteString(w, "ok")
|
_, _ = w.Write([]byte("ok"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleGDPRPolicy(w http.ResponseWriter, r *http.Request) {
|
type caps struct {
|
||||||
s.secureHeaders(w)
|
AllowAnonPlaintext bool `json:"allow_anon_plaintext"`
|
||||||
|
ZeroTrust bool `json:"zero_trust"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCaps(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
type policy struct {
|
_ = json.NewEncoder(w).Encode(caps{
|
||||||
StoresPII bool `json:"stores_pii"`
|
AllowAnonPlaintext: s.allowAnonPlaintext,
|
||||||
CollectIP bool `json:"collect_ip"`
|
ZeroTrust: true,
|
||||||
CollectUA bool `json:"collect_user_agent"`
|
})
|
||||||
Timestamps string `json:"timestamps"`
|
|
||||||
ZeroTrust bool `json:"zero_trust"`
|
|
||||||
}
|
|
||||||
resp := policy{
|
|
||||||
StoresPII: false,
|
|
||||||
CollectIP: false,
|
|
||||||
CollectUA: false,
|
|
||||||
Timestamps: map[bool]string{true: "coarse_utc", false: "utc"}[s.coarseTS],
|
|
||||||
ZeroTrust: s.zeroTrust,
|
|
||||||
}
|
|
||||||
_ = json.NewEncoder(w).Encode(resp)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------
|
// ---- Object handlers ----
|
||||||
// Auth helpers
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) requireAuth(w http.ResponseWriter, r *http.Request) bool {
|
type putResp struct {
|
||||||
// Developer bypass
|
Hash string `json:"hash"`
|
||||||
if s.allowUnauth {
|
Bytes int64 `json:"bytes"`
|
||||||
return true
|
StoredAt time.Time `json:"stored_at"`
|
||||||
}
|
Private bool `json:"private"`
|
||||||
// Optional dev bearer
|
|
||||||
if s.devBearer != "" {
|
|
||||||
h := r.Header.Get("Authorization")
|
|
||||||
if h == "Bearer "+s.devBearer {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept self-signed HMAC tokens if configured
|
|
||||||
if s.allowClientSignedTokens && len(s.signingKey) > 0 {
|
|
||||||
h := r.Header.Get("Authorization")
|
|
||||||
if strings.HasPrefix(h, "Bearer ") {
|
|
||||||
tok := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
|
|
||||||
if s.verifyToken(tok) == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) makeToken(subject string, ttl time.Duration) (string, error) {
|
|
||||||
if len(s.signingKey) == 0 {
|
|
||||||
return "", errors.New("signing key not set")
|
|
||||||
}
|
|
||||||
type claims struct {
|
|
||||||
Sub string `json:"sub"`
|
|
||||||
Exp int64 `json:"exp"`
|
|
||||||
Iss string `json:"iss"`
|
|
||||||
}
|
|
||||||
c := claims{
|
|
||||||
Sub: subject,
|
|
||||||
Exp: time.Now().Add(ttl).Unix(),
|
|
||||||
Iss: "greencoast",
|
|
||||||
}
|
|
||||||
body, _ := json.Marshal(c)
|
|
||||||
mac := hmac.New(sha256.New, s.signingKey)
|
|
||||||
mac.Write(body)
|
|
||||||
sig := mac.Sum(nil)
|
|
||||||
return "gc1." + base64.RawURLEncoding.EncodeToString(body) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) verifyToken(tok string) error {
|
|
||||||
if !strings.HasPrefix(tok, "gc1.") {
|
|
||||||
return errors.New("bad prefix")
|
|
||||||
}
|
|
||||||
parts := strings.Split(tok, ".")
|
|
||||||
if len(parts) != 3 {
|
|
||||||
return errors.New("bad parts")
|
|
||||||
}
|
|
||||||
body, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
want, err := base64.RawURLEncoding.DecodeString(parts[2])
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
mac := hmac.New(sha256.New, s.signingKey)
|
|
||||||
mac.Write(body)
|
|
||||||
if !hmac.Equal(want, mac.Sum(nil)) {
|
|
||||||
return errors.New("bad sig")
|
|
||||||
}
|
|
||||||
var c struct {
|
|
||||||
Sub string `json:"sub"`
|
|
||||||
Exp int64 `json:"exp"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(body, &c); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if time.Now().Unix() > c.Exp {
|
|
||||||
return errors.New("expired")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Objects & Index
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) handlePutObject(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handlePutObject(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPut {
|
if r.Method != http.MethodPut {
|
||||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !s.requireAuth(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
isPrivate := r.Header.Get("X-GC-Private") == "1"
|
|
||||||
creatorTZ := strings.TrimSpace(r.Header.Get("X-GC-TZ"))
|
|
||||||
if creatorTZ != "" && !isReasonableTZ(creatorTZ) {
|
|
||||||
creatorTZ = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write to store; compute hash while streaming
|
|
||||||
var buf bytes.Buffer
|
|
||||||
n, err := io.Copy(&buf, r.Body)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "read error", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
sum := sha256.Sum256(buf.Bytes())
|
|
||||||
hash := hex.EncodeToString(sum[:])
|
|
||||||
|
|
||||||
// Persist
|
|
||||||
if err := s.store.Put(hash, bytes.NewReader(buf.Bytes())); err != nil {
|
|
||||||
http.Error(w, "store error", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Index
|
|
||||||
when := time.Now().UTC()
|
|
||||||
if s.coarseTS {
|
|
||||||
when = when.Truncate(time.Minute)
|
|
||||||
}
|
|
||||||
entry := index.Entry{
|
|
||||||
Hash: hash,
|
|
||||||
Bytes: n,
|
|
||||||
StoredAt: when.Format(time.RFC3339Nano),
|
|
||||||
Private: isPrivate,
|
|
||||||
CreatorTZ: creatorTZ,
|
|
||||||
}
|
|
||||||
if err := s.idx.Put(entry); err != nil {
|
|
||||||
http.Error(w, "index error", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
s.sseBroadcast(map[string]interface{}{"event": "put", "data": entry})
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
_ = json.NewEncoder(w).Encode(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) handleObjectByHash(w http.ResponseWriter, r *http.Request) {
|
|
||||||
// path: /v1/object/{hash}
|
|
||||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/v1/object/"), "/")
|
|
||||||
if len(parts) == 0 || parts[0] == "" {
|
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
hash := parts[0]
|
private := r.Header.Get("X-GC-Private") == "1"
|
||||||
|
|
||||||
|
// Strict read (prevents runaway memory and surfaces clear error)
|
||||||
|
data, err := ReadAllStrict(r.Body, maxObjectBytes())
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("PUT /v1/object read error: %v", err)
|
||||||
|
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store
|
||||||
|
hash, n, storedAt, err := s.store.Put(bytes.NewReader(data), private)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("PUT /v1/object store error: %v", err)
|
||||||
|
http.Error(w, "store failed: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Broadcast SSE "put"
|
||||||
|
s.broadcastEvent("put", map[string]any{
|
||||||
|
"hash": hash,
|
||||||
|
"bytes": n,
|
||||||
|
"stored_at": storedAt.UTC(),
|
||||||
|
"private": private,
|
||||||
|
})
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
_ = json.NewEncoder(w).Encode(putResp{
|
||||||
|
Hash: hash,
|
||||||
|
Bytes: n,
|
||||||
|
StoredAt: storedAt.UTC(),
|
||||||
|
Private: private,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleObjectByHash(w http.ResponseWriter, r *http.Request) {
|
||||||
|
seg := strings.TrimPrefix(r.URL.Path, "/v1/object")
|
||||||
|
seg = strings.TrimPrefix(seg, "/")
|
||||||
|
if seg == "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash := path.Clean(seg)
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
if !s.requireAuth(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rc, n, err := s.store.Get(hash)
|
rc, n, err := s.store.Get(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "not found", http.StatusNotFound)
|
http.Error(w, "not found", http.StatusNotFound)
|
||||||
@@ -383,340 +258,138 @@ func (s *Server) handleObjectByHash(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
defer rc.Close()
|
defer rc.Close()
|
||||||
w.Header().Set("Content-Type", "application/octet-stream")
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
if n > 0 {
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", n))
|
||||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", n))
|
if _, err := io.Copy(w, rc); err != nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
_, _ = io.Copy(w, rc)
|
|
||||||
|
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
if !s.requireAuth(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := s.store.Delete(hash); err != nil {
|
if err := s.store.Delete(hash); err != nil {
|
||||||
http.Error(w, "delete error", 500)
|
http.Error(w, "not found", http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// prune index if present
|
s.broadcastEvent("delete", map[string]any{"hash": hash})
|
||||||
_ = s.idx.Delete(hash)
|
|
||||||
s.sseBroadcast(map[string]interface{}{"event": "delete", "data": map[string]string{"hash": hash}})
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
http.NotFound(w, r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Index handlers ----
|
||||||
|
|
||||||
|
type indexEntry struct {
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
Bytes int64 `json:"bytes"`
|
||||||
|
Private bool `json:"private"`
|
||||||
|
StoredAt time.Time `json:"stored_at"`
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodGet {
|
if r.Method != http.MethodGet {
|
||||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !s.requireAuth(w, r) {
|
out := make([]indexEntry, 0, 256)
|
||||||
return
|
_, err := s.store.Walk(func(hash string, bytes int64, private bool, storedAt time.Time) error {
|
||||||
}
|
out = append(out, indexEntry{
|
||||||
items, err := s.idx.List()
|
Hash: hash,
|
||||||
|
Bytes: bytes,
|
||||||
|
Private: private,
|
||||||
|
StoredAt: storedAt.UTC(),
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "index error", 500)
|
http.Error(w, "index walk failed: "+err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
sortByStoredAtDesc(out)
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
_ = json.NewEncoder(w).Encode(items)
|
_ = json.NewEncoder(w).Encode(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simple in-process SSE fanout.
|
func sortByStoredAtDesc(a []indexEntry) {
|
||||||
func (s *Server) handleIndexSSE(w http.ResponseWriter, r *http.Request) {
|
for i := 1; i < len(a); i++ {
|
||||||
if !s.requireAuth(w, r) {
|
j := i
|
||||||
|
for j > 0 && a[j].StoredAt.After(a[j-1].StoredAt) {
|
||||||
|
a[j], a[j-1] = a[j-1], a[j]
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- SSE ----
|
||||||
|
|
||||||
|
func (s *Server) handleIndexStream(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
flusher, ok := w.(http.Flusher)
|
flusher, ok := w.(http.Flusher)
|
||||||
if !ok {
|
if !ok {
|
||||||
http.Error(w, "stream unsupported", http.StatusInternalServerError)
|
http.Error(w, "stream unsupported", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
|
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
|
||||||
w.Header().Set("Connection", "keep-alive")
|
|
||||||
|
|
||||||
ch := make(chan []byte, 8)
|
ch := make(chan []byte, 32)
|
||||||
|
s.addSub(ch)
|
||||||
|
defer s.removeSub(ch)
|
||||||
|
|
||||||
// subscribe
|
_, _ = io.WriteString(w, ": ok\n\n")
|
||||||
s.sseMu.Lock()
|
|
||||||
if s.sseClosed {
|
|
||||||
s.sseMu.Unlock()
|
|
||||||
http.Error(w, "closed", http.StatusGone)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
s.sseSubs[ch] = struct{}{}
|
|
||||||
s.sseMu.Unlock()
|
|
||||||
|
|
||||||
// Send a hello/heartbeat
|
|
||||||
fmt.Fprintf(w, "data: %s\n\n", `{"event":"hello","data":"ok"}`)
|
|
||||||
flusher.Flush()
|
flusher.Flush()
|
||||||
|
|
||||||
// pump
|
notify := r.Context().Done()
|
||||||
ctx := r.Context()
|
hb := time.NewTicker(20 * time.Second)
|
||||||
t := time.NewTicker(25 * time.Second)
|
defer hb.Stop()
|
||||||
defer t.Stop()
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
s.sseMu.Lock()
|
|
||||||
delete(s.sseSubs, ch)
|
|
||||||
s.sseMu.Unlock()
|
|
||||||
close(ch)
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-notify:
|
||||||
return
|
return
|
||||||
case b := <-ch:
|
case <-hb.C:
|
||||||
w.Write(b)
|
_, _ = io.WriteString(w, ": ping\n\n")
|
||||||
w.Write([]byte("\n\n"))
|
|
||||||
flusher.Flush()
|
flusher.Flush()
|
||||||
case <-t.C:
|
case msg := <-ch:
|
||||||
w.Write([]byte("data: {}\n\n"))
|
_, _ = io.WriteString(w, "data: ")
|
||||||
|
_, _ = w.Write(msg)
|
||||||
|
_, _ = io.WriteString(w, "\n\n")
|
||||||
flusher.Flush()
|
flusher.Flush()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) sseBroadcast(v interface{}) {
|
func (s *Server) addSub(ch chan []byte) {
|
||||||
b, _ := json.Marshal(v)
|
s.sseMu.Lock()
|
||||||
|
s.sseSubs[ch] = struct{}{}
|
||||||
|
s.sseMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) removeSub(ch chan []byte) {
|
||||||
|
s.sseMu.Lock()
|
||||||
|
delete(s.sseSubs, ch)
|
||||||
|
close(ch)
|
||||||
|
s.sseMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) broadcastEvent(ev string, payload any) {
|
||||||
|
body, _ := json.Marshal(map[string]any{"event": ev, "data": payload})
|
||||||
s.sseMu.Lock()
|
s.sseMu.Lock()
|
||||||
for ch := range s.sseSubs {
|
for ch := range s.sseSubs {
|
||||||
select {
|
select {
|
||||||
case ch <- append([]byte("data: "), b...):
|
case ch <- body:
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s.sseMu.Unlock()
|
s.sseMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------
|
// ---- Helpers ----
|
||||||
// Admin: reindex from disk
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) handleAdminReindex(w http.ResponseWriter, r *http.Request) {
|
func bufioReader(r io.Reader) *bufio.Reader {
|
||||||
if r.Method != http.MethodPost {
|
if br, ok := r.(*bufio.Reader); ok {
|
||||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
return br
|
||||||
return
|
|
||||||
}
|
}
|
||||||
if !s.requireAuth(w, r) {
|
return bufio.NewReader(r)
|
||||||
return
|
|
||||||
}
|
|
||||||
walker, ok := s.store.(blobWalker)
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, "store does not support walk", http.StatusNotImplemented)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
count := 0
|
|
||||||
err := walker.Walk(func(hash string, size int64, mod time.Time) error {
|
|
||||||
count++
|
|
||||||
return s.idx.Put(index.Entry{
|
|
||||||
Hash: hash,
|
|
||||||
Bytes: size,
|
|
||||||
StoredAt: mod.UTC().Format(time.RFC3339Nano),
|
|
||||||
Private: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "walk error: "+err.Error(), 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
items, _ := s.idx.List()
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
||||||
"walked": count,
|
|
||||||
"indexed": len(items),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Discord SSO (server-side code flow)
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) handleDiscordStart(w http.ResponseWriter, r *http.Request, cfg DiscordProvider) {
|
|
||||||
if !cfg.Enabled || cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" {
|
|
||||||
http.Error(w, "discord sso disabled", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Require explicit 3P assent (UI shows disclaimer)
|
|
||||||
if r.Header.Get("X-GC-3P-Assent") != "1" {
|
|
||||||
http.Error(w, "third-party provider not assented", http.StatusForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
state := s.newState(5 * time.Minute)
|
|
||||||
v := url.Values{}
|
|
||||||
v.Set("response_type", "code")
|
|
||||||
v.Set("client_id", cfg.ClientID)
|
|
||||||
v.Set("redirect_uri", cfg.RedirectURI)
|
|
||||||
v.Set("scope", "identify")
|
|
||||||
v.Set("prompt", "consent")
|
|
||||||
v.Set("state", state)
|
|
||||||
authURL := (&url.URL{
|
|
||||||
Scheme: "https",
|
|
||||||
Host: "discord.com",
|
|
||||||
Path: "/api/oauth2/authorize",
|
|
||||||
RawQuery: v.Encode(),
|
|
||||||
}).String()
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
_ = json.NewEncoder(w).Encode(map[string]string{"url": authURL})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) handleDiscordCallback(w http.ResponseWriter, r *http.Request, cfg DiscordProvider) {
|
|
||||||
if !cfg.Enabled {
|
|
||||||
http.Error(w, "disabled", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
q := r.URL.Query()
|
|
||||||
code := q.Get("code")
|
|
||||||
state := q.Get("state")
|
|
||||||
if code == "" || state == "" || !s.consumeState(state) {
|
|
||||||
http.Error(w, "invalid state/code", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exchange code for token
|
|
||||||
form := url.Values{}
|
|
||||||
form.Set("client_id", cfg.ClientID)
|
|
||||||
form.Set("client_secret", cfg.ClientSecret)
|
|
||||||
form.Set("grant_type", "authorization_code")
|
|
||||||
form.Set("code", code)
|
|
||||||
form.Set("redirect_uri", cfg.RedirectURI)
|
|
||||||
|
|
||||||
req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, "https://discord.com/api/oauth2/token", strings.NewReader(form.Encode()))
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
res, err := http.DefaultClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "token exchange failed", 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
if res.StatusCode/100 != 2 {
|
|
||||||
b, _ := io.ReadAll(res.Body)
|
|
||||||
http.Error(w, "discord token error: "+string(b), 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var tok struct {
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
TokenType string `json:"token_type"`
|
|
||||||
Scope string `json:"scope"`
|
|
||||||
ExpiresIn int64 `json:"expires_in"`
|
|
||||||
}
|
|
||||||
if err := json.NewDecoder(res.Body).Decode(&tok); err != nil {
|
|
||||||
http.Error(w, "token decode failed", 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch user id (identify scope)
|
|
||||||
ureq, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, "https://discord.com/api/users/@me", nil)
|
|
||||||
ureq.Header.Set("Authorization", tok.TokenType+" "+tok.AccessToken)
|
|
||||||
ures, err := http.DefaultClient.Do(ureq)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "user fetch failed", 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer ures.Body.Close()
|
|
||||||
if ures.StatusCode/100 != 2 {
|
|
||||||
b, _ := io.ReadAll(ures.Body)
|
|
||||||
http.Error(w, "discord user error: "+string(b), 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var user struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
}
|
|
||||||
if err := json.NewDecoder(ures.Body).Decode(&user); err != nil {
|
|
||||||
http.Error(w, "user decode failed", 502)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mint self-signed bearer with Discord snowflake as subject
|
|
||||||
bearer, err := s.makeToken("discord:"+user.ID, time.Hour*8)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "signing error", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect to frontend callback with bearer in fragment (not query)
|
|
||||||
target := cfg.RedirectURI
|
|
||||||
u, _ := url.Parse(target)
|
|
||||||
u.Fragment = "bearer=" + url.QueryEscape(bearer) + "&next=/"
|
|
||||||
http.Redirect(w, r, u.String(), http.StatusFound)
|
|
||||||
}
|
|
||||||
|
|
||||||
// simple in-memory state store
|
|
||||||
func (s *Server) newState(ttl time.Duration) string {
|
|
||||||
s.stateMu.Lock()
|
|
||||||
defer s.stateMu.Unlock()
|
|
||||||
b := make([]byte, 12)
|
|
||||||
now := time.Now().UnixNano()
|
|
||||||
copy(b, []byte(fmt.Sprintf("%x", now)))
|
|
||||||
val := base64.RawURLEncoding.EncodeToString(b)
|
|
||||||
s.states[val] = time.Now().Add(ttl)
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) consumeState(v string) bool {
|
|
||||||
s.stateMu.Lock()
|
|
||||||
defer s.stateMu.Unlock()
|
|
||||||
exp, ok := s.states[v]
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
delete(s.states, v)
|
|
||||||
return time.Now().Before(exp)
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Utilities
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func isReasonableTZ(tz string) bool {
|
|
||||||
if !strings.Contains(tz, "/") || len(tz) > 64 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, r := range tz {
|
|
||||||
if !(r == '/' || r == '_' || r == '-' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z')) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Optional: graceful shutdown
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func (s *Server) Shutdown(ctx context.Context) error {
|
|
||||||
s.sseMu.Lock()
|
|
||||||
s.sseClosed = true
|
|
||||||
for ch := range s.sseSubs {
|
|
||||||
close(ch)
|
|
||||||
}
|
|
||||||
s.sseSubs = make(map[chan []byte]struct{})
|
|
||||||
s.sseMu.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Helpers for static serving (optional use)
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
func fileExists(p string) bool {
|
|
||||||
st, err := os.Stat(p)
|
|
||||||
return err == nil && !st.IsDir()
|
|
||||||
}
|
|
||||||
|
|
||||||
func joinClean(dir, p string) (string, bool) {
|
|
||||||
fp := path.Clean("/" + p)
|
|
||||||
full := path.Clean(dir + fp)
|
|
||||||
if !strings.HasPrefix(full, path.Clean(dir)) {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return full, true
|
|
||||||
}
|
}
|
||||||
|
72
internal/api/ratelimit.go
Normal file
72
internal/api/ratelimit.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Simple token-bucket rate limiter used by Server.cors middleware.
|
||||||
|
|
||||||
|
type tokenBucket struct {
|
||||||
|
tokens float64
|
||||||
|
lastFill time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type rateLimiter struct {
|
||||||
|
rate float64 // tokens per second
|
||||||
|
burst float64
|
||||||
|
mu sync.Mutex
|
||||||
|
bk map[string]*tokenBucket
|
||||||
|
evictDur time.Duration
|
||||||
|
lastGC time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRateLimiter(rate float64, burst int, evict time.Duration) *rateLimiter {
|
||||||
|
return &rateLimiter{
|
||||||
|
rate: rate,
|
||||||
|
burst: float64(burst),
|
||||||
|
bk: make(map[string]*tokenBucket),
|
||||||
|
evictDur: evict,
|
||||||
|
lastGC: time.Now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rl *rateLimiter) allow(key string) bool {
|
||||||
|
now := time.Now()
|
||||||
|
rl.mu.Lock()
|
||||||
|
defer rl.mu.Unlock()
|
||||||
|
|
||||||
|
// GC old buckets occasionally
|
||||||
|
if now.Sub(rl.lastGC) > rl.evictDur {
|
||||||
|
for k, b := range rl.bk {
|
||||||
|
if now.Sub(b.lastFill) > rl.evictDur {
|
||||||
|
delete(rl.bk, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rl.lastGC = now
|
||||||
|
}
|
||||||
|
|
||||||
|
b, ok := rl.bk[key]
|
||||||
|
if !ok {
|
||||||
|
b = &tokenBucket{tokens: rl.burst, lastFill: now}
|
||||||
|
rl.bk[key] = b
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refill
|
||||||
|
elapsed := now.Sub(b.lastFill).Seconds()
|
||||||
|
b.tokens = minf(rl.burst, b.tokens+elapsed*rl.rate)
|
||||||
|
b.lastFill = now
|
||||||
|
|
||||||
|
if b.tokens >= 1.0 {
|
||||||
|
b.tokens -= 1.0
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func minf(a, b float64) float64 {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
@@ -1,8 +1,6 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
|
||||||
"mime"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -10,77 +8,69 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
// ListenFrontend serves the static client from s.StaticDir on a separate port (e.g. :9082).
|
||||||
// Ensure common types are known (some distros are sparse by default)
|
func (s *Server) ListenFrontend(addr string) error {
|
||||||
_ = mime.AddExtensionType(".js", "application/javascript; charset=utf-8")
|
root := s.StaticDir
|
||||||
_ = mime.AddExtensionType(".css", "text/css; charset=utf-8")
|
if root == "" {
|
||||||
_ = mime.AddExtensionType(".html", "text/html; charset=utf-8")
|
root = "./client"
|
||||||
_ = mime.AddExtensionType(".map", "application/json; charset=utf-8")
|
}
|
||||||
}
|
// 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("Referrer-Policy", "no-referrer")
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
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'",
|
||||||
|
}, "; "),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) MountStatic(dir string, baseURL string) {
|
// File handler with index.html fallback for “/”.
|
||||||
if dir == "" {
|
fileServer := http.FileServer(http.Dir(root))
|
||||||
return
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
addCommonHeaders(w)
|
||||||
if baseURL == "" {
|
|
||||||
baseURL = "/"
|
|
||||||
}
|
|
||||||
s.mux.Handle(baseURL, s.staticHandler(dir, baseURL))
|
|
||||||
if !strings.HasSuffix(baseURL, "/") {
|
|
||||||
s.mux.Handle(baseURL+"/", s.staticHandler(dir, baseURL))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) ListenFrontendHTTP(addr, dir, baseURL string) error {
|
// Serve index.html at root or when requesting a directory.
|
||||||
if dir == "" || addr == "" {
|
p := r.URL.Path
|
||||||
return nil
|
if p == "/" || p == "" {
|
||||||
}
|
http.ServeFile(w, r, filepath.Join(root, "index.html"))
|
||||||
log.Printf("frontend listening on %s (dir=%s base=%s)", addr, dir, baseURL)
|
return
|
||||||
mx := http.NewServeMux()
|
}
|
||||||
mx.Handle(baseURL, s.staticHandler(dir, baseURL))
|
|
||||||
if !strings.HasSuffix(baseURL, "/") {
|
// If path maps to a directory, try its index.html.
|
||||||
mx.Handle(baseURL+"/", s.staticHandler(dir, baseURL))
|
full := filepath.Join(root, filepath.Clean(strings.TrimPrefix(p, "/")))
|
||||||
}
|
if st, err := os.Stat(full); err == nil && st.IsDir() {
|
||||||
server := &http.Server{
|
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,
|
Addr: addr,
|
||||||
Handler: mx,
|
Handler: handler,
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
}
|
}
|
||||||
return server.ListenAndServe()
|
return srv.ListenAndServe()
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) staticHandler(dir, baseURL string) http.Handler {
|
|
||||||
if baseURL == "" {
|
|
||||||
baseURL = "/"
|
|
||||||
}
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
s.secureHeaders(w)
|
|
||||||
|
|
||||||
up := strings.TrimPrefix(r.URL.Path, baseURL)
|
|
||||||
if up == "" || strings.HasSuffix(r.URL.Path, "/") {
|
|
||||||
up = "index.html"
|
|
||||||
}
|
|
||||||
full := filepath.Join(dir, filepath.FromSlash(up))
|
|
||||||
if !strings.HasPrefix(filepath.Clean(full), filepath.Clean(dir)) {
|
|
||||||
http.NotFound(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serve file if it exists, else SPA-fallback to index.html
|
|
||||||
if st, err := os.Stat(full); err == nil && !st.IsDir() {
|
|
||||||
// Set Content-Type explicitly based on extension
|
|
||||||
if ctype := mime.TypeByExtension(filepath.Ext(full)); ctype != "" {
|
|
||||||
w.Header().Set("Content-Type", ctype)
|
|
||||||
}
|
|
||||||
http.ServeFile(w, r, full)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fallback := filepath.Join(dir, "index.html")
|
|
||||||
if _, err := os.Stat(fallback); err == nil {
|
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
||||||
http.ServeFile(w, r, fallback)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
http.NotFound(w, r)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
78
internal/auth/gc2.go
Normal file
78
internal/auth/gc2.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Claims struct {
|
||||||
|
Sub string `json:"sub"` // account ID (acc_…)
|
||||||
|
Exp int64 `json:"exp"` // unix seconds
|
||||||
|
Nbf int64 `json:"nbf,omitempty"` // not before
|
||||||
|
Iss string `json:"iss,omitempty"` // greencoast
|
||||||
|
Aud string `json:"aud,omitempty"` // api
|
||||||
|
Jti string `json:"jti,omitempty"` // token id (optional)
|
||||||
|
CNF string `json:"cnf,omitempty"` // key binding: "p256:<b64raw>" or "ed25519:<b64raw>"
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintGC2(signKey []byte, c Claims) (string, error) {
|
||||||
|
if len(signKey) == 0 {
|
||||||
|
return "", errors.New("sign key missing")
|
||||||
|
}
|
||||||
|
if c.Sub == "" || c.Exp == 0 {
|
||||||
|
return "", errors.New("claims incomplete")
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(c)
|
||||||
|
mac := hmac.New(sha256.New, signKey)
|
||||||
|
mac.Write(body)
|
||||||
|
sig := mac.Sum(nil)
|
||||||
|
return "gc2." + base64.RawURLEncoding.EncodeToString(body) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func VerifyGC2(signKey []byte, tok string, now time.Time) (Claims, error) {
|
||||||
|
var zero Claims
|
||||||
|
if !strings.HasPrefix(tok, "gc2.") {
|
||||||
|
return zero, errors.New("bad prefix")
|
||||||
|
}
|
||||||
|
parts := strings.Split(tok, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return zero, errors.New("bad parts")
|
||||||
|
}
|
||||||
|
body, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return zero, err
|
||||||
|
}
|
||||||
|
want, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return zero, err
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, signKey)
|
||||||
|
mac.Write(body)
|
||||||
|
if !hmac.Equal(want, mac.Sum(nil)) {
|
||||||
|
return zero, errors.New("bad sig")
|
||||||
|
}
|
||||||
|
var c Claims
|
||||||
|
if err := json.Unmarshal(body, &c); err != nil {
|
||||||
|
return zero, err
|
||||||
|
}
|
||||||
|
t := now.Unix()
|
||||||
|
if c.Nbf != 0 && t < c.Nbf {
|
||||||
|
return zero, errors.New("nbf")
|
||||||
|
}
|
||||||
|
if t > c.Exp {
|
||||||
|
return zero, errors.New("expired")
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func AccountIDFromPub(raw []byte) string {
|
||||||
|
// acc_<first32 hex of sha256(pub)>
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
return "acc_" + hex.EncodeToString(sum[:16])
|
||||||
|
}
|
@@ -1,108 +1,49 @@
|
|||||||
package index
|
package index
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sort"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Entry is the API/JSON shape the server returns.
|
// Entry is the index record returned to clients.
|
||||||
// StoredAt is RFC3339/RFC3339Nano in UTC.
|
// Keep metadata minimal to protect users.
|
||||||
type Entry struct {
|
type Entry struct {
|
||||||
Hash string `json:"hash"`
|
Hash string `json:"hash"`
|
||||||
Bytes int64 `json:"bytes"`
|
Bytes int64 `json:"bytes"`
|
||||||
StoredAt string `json:"stored_at"` // RFC3339( Nano ) string
|
StoredAt string `json:"stored_at"` // RFC3339Nano string
|
||||||
Private bool `json:"private"`
|
Private bool `json:"private"`
|
||||||
CreatorTZ string `json:"creator_tz,omitempty"` // IANA TZ like "America/New_York"
|
CreatorTZ string `json:"creator_tz,omitempty"`
|
||||||
|
Author string `json:"author,omitempty"` // pseudonymous (thumbprint), optional
|
||||||
}
|
}
|
||||||
|
|
||||||
// internal record with real time.Time for sorting/comparison.
|
|
||||||
type rec struct {
|
|
||||||
Hash string
|
|
||||||
Bytes int64
|
|
||||||
StoredAt time.Time
|
|
||||||
Private bool
|
|
||||||
CreatorTZ string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Index is an in-memory index keyed by hash.
|
|
||||||
type Index struct {
|
type Index struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
hash map[string]rec
|
data map[string]Entry
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates an empty Index.
|
|
||||||
func New() *Index {
|
func New() *Index {
|
||||||
return &Index{
|
return &Index{data: make(map[string]Entry)}
|
||||||
hash: make(map[string]rec),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put inserts or replaces an entry.
|
|
||||||
// e.StoredAt may be RFC3339( Nano ); if empty/invalid we use time.Now().UTC().
|
|
||||||
func (ix *Index) Put(e Entry) error {
|
func (ix *Index) Put(e Entry) error {
|
||||||
ix.mu.Lock()
|
ix.mu.Lock()
|
||||||
defer ix.mu.Unlock()
|
ix.data[e.Hash] = e
|
||||||
|
ix.mu.Unlock()
|
||||||
t := parseWhen(e.StoredAt)
|
|
||||||
if t.IsZero() {
|
|
||||||
t = time.Now().UTC()
|
|
||||||
}
|
|
||||||
|
|
||||||
ix.hash[e.Hash] = rec{
|
|
||||||
Hash: e.Hash,
|
|
||||||
Bytes: e.Bytes,
|
|
||||||
StoredAt: t,
|
|
||||||
Private: e.Private,
|
|
||||||
CreatorTZ: e.CreatorTZ,
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete removes an entry by hash (no error if absent).
|
|
||||||
func (ix *Index) Delete(hash string) error {
|
func (ix *Index) Delete(hash string) error {
|
||||||
ix.mu.Lock()
|
ix.mu.Lock()
|
||||||
defer ix.mu.Unlock()
|
delete(ix.data, hash)
|
||||||
delete(ix.hash, hash)
|
ix.mu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// List returns entries sorted by StoredAt descending.
|
func (ix *Index) All() []Entry {
|
||||||
func (ix *Index) List() ([]Entry, error) {
|
|
||||||
ix.mu.RLock()
|
ix.mu.RLock()
|
||||||
defer ix.mu.RUnlock()
|
out := make([]Entry, 0, len(ix.data))
|
||||||
|
for _, e := range ix.data {
|
||||||
tmp := make([]rec, 0, len(ix.hash))
|
out = append(out, e)
|
||||||
for _, r := range ix.hash {
|
|
||||||
tmp = append(tmp, r)
|
|
||||||
}
|
}
|
||||||
sort.Slice(tmp, func(i, j int) bool {
|
ix.mu.RUnlock()
|
||||||
return tmp[i].StoredAt.After(tmp[j].StoredAt)
|
return out
|
||||||
})
|
|
||||||
|
|
||||||
out := make([]Entry, len(tmp))
|
|
||||||
for i, r := range tmp {
|
|
||||||
out[i] = Entry{
|
|
||||||
Hash: r.Hash,
|
|
||||||
Bytes: r.Bytes,
|
|
||||||
StoredAt: r.StoredAt.UTC().Format(time.RFC3339Nano),
|
|
||||||
Private: r.Private,
|
|
||||||
CreatorTZ: r.CreatorTZ,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseWhen tries RFC3339Nano then RFC3339; returns zero time on failure.
|
|
||||||
func parseWhen(s string) time.Time {
|
|
||||||
if s == "" {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
return time.Time{}
|
|
||||||
}
|
}
|
||||||
|
@@ -1,314 +1,151 @@
|
|||||||
package storage
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FSStore stores blobs on the local filesystem under root/objects/...
|
// SimpleFSStore is a minimal FS-backed implementation of BlobStore.
|
||||||
// It supports both a flat layout (objects/<hash>) and a nested layout
|
// Layout under root:
|
||||||
// (objects/<hash>/<file> or objects/<prefix>/<hash>).
|
|
||||||
type FSStore struct {
|
|
||||||
root string
|
|
||||||
objects string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewFS returns a file-backed blob store rooted at dir.
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// pathFlat returns the flat path objects/<hash>.
|
|
||||||
func (s *FSStore) pathFlat(hash string) (string, error) {
|
|
||||||
if hash == "" {
|
|
||||||
return "", errors.New("empty hash")
|
|
||||||
}
|
|
||||||
return filepath.Join(s.objects, hash), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// isHexHash does a quick check for lowercase hex of length 64.
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// findBlobPath tries common layouts before falling back to a recursive search.
|
|
||||||
//
|
//
|
||||||
// Supported fast paths (in order):
|
// <root>/<hash> - content
|
||||||
// 1. objects/<hash> (flat file)
|
// <root>/<hash>.priv - presence means "private"
|
||||||
// 2. objects/<hash>/blob|data|content (common names)
|
type SimpleFSStore struct {
|
||||||
// 3. objects/<hash>/<single file> (folder-per-post; pick that file)
|
root string
|
||||||
// 4. objects/<hash[0:2]>/<hash> (two-level prefix sharding)
|
|
||||||
//
|
|
||||||
// If still not found, it walks recursively under objects/ to locate either:
|
|
||||||
// - a file named exactly <hash>, or
|
|
||||||
// - any file under a directory named <hash> (choose the most recently modified).
|
|
||||||
func (s *FSStore) findBlobPath(hash string) (string, error) {
|
|
||||||
if hash == "" {
|
|
||||||
return "", errors.New("empty hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1) flat file
|
|
||||||
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, err := os.ReadDir(dir)
|
|
||||||
if err == nil {
|
|
||||||
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() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Pick newest file if multiple.
|
|
||||||
if picked == "" || fi.ModTime().After(pickedMod) {
|
|
||||||
picked = p
|
|
||||||
pickedMod = 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: recursive search
|
|
||||||
var best string
|
|
||||||
var bestMod time.Time
|
|
||||||
|
|
||||||
err := filepath.WalkDir(s.objects, func(p string, d fs.DirEntry, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
// ignore per-entry errors
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if d.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
base := filepath.Base(p)
|
|
||||||
// Exact filename == hash
|
|
||||||
if base == hash {
|
|
||||||
best = p
|
|
||||||
// exact match is good enough; stop here
|
|
||||||
return fs.SkipDir
|
|
||||||
}
|
|
||||||
// If parent dir name is hash, consider it
|
|
||||||
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 = p
|
|
||||||
bestMod = fi.ModTime()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err == nil && best != "" {
|
|
||||||
return best, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", os.ErrNotExist
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fileExists true if path exists and is a regular file.
|
func NewSimpleFSStore(root string) *SimpleFSStore {
|
||||||
func fileExists(p string) bool {
|
return &SimpleFSStore{root: root}
|
||||||
fi, err := os.Stat(p)
|
|
||||||
return err == nil && fi.Mode().IsRegular()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put writes/overwrites the blob at the content hash into the flat path.
|
func (fs *SimpleFSStore) ensureRoot() error {
|
||||||
// (Nested layouts remain supported for reads/reindex, but new writes are flat.)
|
return os.MkdirAll(fs.root, 0o755)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get opens the blob for reading and returns its size if known.
|
func (fs *SimpleFSStore) pathFor(hash string) string {
|
||||||
func (s *FSStore) Get(hash string) (io.ReadCloser, int64, error) {
|
return filepath.Join(fs.root, hash)
|
||||||
p, err := s.findBlobPath(hash)
|
}
|
||||||
if err != nil {
|
func (fs *SimpleFSStore) privPathFor(hash string) string {
|
||||||
|
return filepath.Join(fs.root, hash+".priv")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get implements BlobStore.Get
|
||||||
|
func (fs *SimpleFSStore) Get(hash string) (io.ReadCloser, int64, error) {
|
||||||
|
if err := fs.ensureRoot(); err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
f, err := os.Open(p)
|
f, err := os.Open(fs.pathFor(hash))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
st, err := f.Stat()
|
st, err := f.Stat()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return f, 0, nil
|
_ = f.Close()
|
||||||
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
return f, st.Size(), nil
|
return f, st.Size(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete removes the blob. It is not an error if it doesn't exist.
|
// Put implements BlobStore.Put
|
||||||
// It tries the flat path, common nested paths, then falls back to remove
|
func (fs *SimpleFSStore) Put(r io.Reader, private bool) (string, int64, time.Time, error) {
|
||||||
// any file found via findBlobPath.
|
if err := fs.ensureRoot(); err != nil {
|
||||||
func (s *FSStore) Delete(hash string) error {
|
return "", 0, time.Time{}, err
|
||||||
// Try flat
|
}
|
||||||
if p, _ := s.pathFlat(hash); fileExists(p) {
|
tmp, err := os.CreateTemp(fs.root, "put-*")
|
||||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
if err != nil {
|
||||||
return 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Try common nested
|
|
||||||
dir := filepath.Join(s.objects, hash)
|
st, err := os.Stat(final)
|
||||||
for _, cand := range []string{"blob", "data", "content"} {
|
if err != nil {
|
||||||
p := filepath.Join(dir, cand)
|
return "", 0, time.Time{}, err
|
||||||
if fileExists(p) {
|
|
||||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(hash) >= 2 {
|
return hash, n, st.ModTime().UTC(), nil
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Fallback: whatever findBlobPath locates
|
|
||||||
if p, err := s.findBlobPath(hash); err == nil {
|
|
||||||
if err := os.Remove(p); err == nil || errors.Is(err, os.ErrNotExist) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If we couldn't find anything, treat as success (idempotent delete)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Walk calls fn(hash, size, modTime) for each blob file found.
|
// Delete implements BlobStore.Delete
|
||||||
// It recognizes blobs when either:
|
func (fs *SimpleFSStore) Delete(hash string) error {
|
||||||
// - the file name is a 64-char hex hash, or
|
if err := fs.ensureRoot(); err != nil {
|
||||||
// - the parent directory name is that hash (folder-per-post).
|
|
||||||
//
|
|
||||||
// If multiple files map to the same hash (e.g., dir contains many files),
|
|
||||||
// the newest file's size/modTime is reported.
|
|
||||||
func (s *FSStore) Walk(fn func(hash string, size int64, mod time.Time) error) error {
|
|
||||||
type rec struct {
|
|
||||||
size int64
|
|
||||||
mod time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
agg := make(map[string]rec)
|
|
||||||
|
|
||||||
err := filepath.WalkDir(s.objects, func(p string, d fs.DirEntry, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
return nil // skip unreadable entries
|
|
||||||
}
|
|
||||||
if d.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Only consider regular files
|
|
||||||
fi, err := os.Stat(p)
|
|
||||||
if err != nil || !fi.Mode().IsRegular() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
base := filepath.Base(p)
|
|
||||||
|
|
||||||
// Case 1: filename equals hash
|
|
||||||
if isHexHash(base) {
|
|
||||||
if r, ok := agg[base]; !ok || fi.ModTime().After(r.mod) {
|
|
||||||
agg[base] = rec{size: fi.Size(), mod: fi.ModTime()}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Case 2: parent dir is the hash
|
|
||||||
parent := filepath.Base(filepath.Dir(p))
|
|
||||||
if isHexHash(parent) {
|
|
||||||
if r, ok := agg[parent]; !ok || fi.ModTime().After(r.mod) {
|
|
||||||
agg[parent] = rec{size: fi.Size(), mod: fi.ModTime()}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Case 3: two-level prefix layout e.g. objects/aa/<hash>
|
|
||||||
// If parent is a 2-char dir and grandparent is objects/, base might be hash.
|
|
||||||
if len(base) == 64 && isHexHash(strings.ToLower(base)) {
|
|
||||||
// already handled as Case 1, but keep as safety if different casing sneaks in
|
|
||||||
if r, ok := agg[base]; !ok || fi.ModTime().After(r.mod) {
|
|
||||||
agg[base] = rec{size: fi.Size(), mod: fi.ModTime()}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
_ = os.Remove(fs.privPathFor(hash))
|
||||||
|
return os.Remove(fs.pathFor(hash))
|
||||||
|
}
|
||||||
|
|
||||||
for h, r := range agg {
|
// Walk implements BlobStore.Walk
|
||||||
if err := fn(h, r.size, r.mod); err != nil {
|
func (fs *SimpleFSStore) Walk(fn func(hash string, bytes int64, private bool, storedAt time.Time) error) (int, error) {
|
||||||
return err
|
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 nil
|
return true
|
||||||
}
|
}
|
||||||
|
@@ -1 +0,0 @@
|
|||||||
{"title":"Timezone Publish","body":"You can now include your timezone on all of your posts. This is completely optional but lets others see when you posted"}
|
|
@@ -1 +0,0 @@
|
|||||||
{"title":"Yarn is Testing!","body":"Hello, my name is Yarn. And I like to test. Test test 1 2 3."}
|
|
@@ -1 +0,0 @@
|
|||||||
<01><><EFBFBD>d<EFBFBD>+V<><56><EFBFBD>+<2B>%!ݚ<>O<EFBFBD><4F>2ޒ$)<07><>zF<7A>î<EFBFBD>)4<><34><EFBFBD>O:z<><7A>*<2A>Ыe<D0AB><65>*5<><04>)<29><>#<23>V<EFBFBD><0B>H<EFBFBD><48>!i<><69><EFBFBD>S$e<><65><EFBFBD>dx<64>]<5D><>$<24><1F>t<EFBFBD><74>6۩<><DBA9>H<EFBFBD><48>
|
|
@@ -1 +0,0 @@
|
|||||||
{"title":"Public Test","body":"Hello Everyone,\n\nWelcome to GreenCoast, a BlueSky Replacement\n\nMystiatech"}
|
|
@@ -1 +0,0 @@
|
|||||||
{"title":"Test post","body":"Does this work?"}
|
|
Reference in New Issue
Block a user