TTOPM commited on
Commit
f1bfa1e
·
verified ·
1 Parent(s): a5d08c5

Upload 28 files

Browse files
src/gemini/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gemini Integration – Belel-Concordium Gateway (Module Only)
2
+
3
+ **Drop this folder into your repo at `/src/gemini`.** No server launcher or package.json included.
4
+
5
+ ## What’s inside
6
+ - `config/` – anchors, policy, protected identities, domain whitelist, placeholder keys
7
+ - `system/` – Concordium mandate + system prompt builder
8
+ - `client/` – the **only** place Gemini SDK calls should live (`callGemini`), with self-verification
9
+ - `guard/` – enforcement: anchors, policy engine, scanners, citations, redaction, provenance, signer, telemetry, rate limits
10
+ - `fetch/` – Aegis fetch proxy handlers (mount in your existing Express/Next server)
11
+ - `index.ts` – orchestrator (`geminiAskGuarded`)
12
+
13
+ ## How to wire in your app
14
+ - **Express route:**
15
+ ```ts
16
+ import { askExpressHandler } from "./src/gemini/routes/ask.express"; // create this thin wrapper in your app
17
+ ```
18
+ Or call the orchestrator directly:
19
+ ```ts
20
+ import { geminiAskGuarded } from "./src/gemini";
21
+ const { status, body } = await geminiAskGuarded({ prompt: "..." });
22
+ ```
23
+
24
+ ## Replace stubs
25
+ - Implement the real Gemini SDK call inside `client/geminiClient.ts` (keep the chokepoint).
26
+ - Use a **KMS/sidecar** to sign `issueChallenge()` and set `GEMINI_SIGNED_CHALLENGE` at call-time.
27
+ - Replace placeholder keys in `config/*.pem`.
28
+
29
+ ## Guarantees
30
+ - **Serious-claim enforcement** (block/redact without whitelisted citations).
31
+ - **Protected identity** safeguards (Pearce Robinson) with **name-agnostic** conflation detection.
32
+ - **Anchor-gated** execution + **tamper-evident** provenance.
src/gemini/client/geminiClient.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { buildSystemPrompt } from "../system/prompts";
2
+ import cfg from "../config/gemini.config.json";
3
+ import { issueChallenge, verifySignature, keyFingerprintFromEnv } from "../guard/selfverify";
4
+
5
+ /**
6
+ * The ONLY place Gemini SDK is invoked.
7
+ * - Self-verifies via challenge/response (no secret exposure).
8
+ * - Checks host allowlist (network policy should also enforce).
9
+ * - Always prepends Concordium mandate to the system prompt.
10
+ */
11
+ type AskOpts = { prompt: string; system?: string; options?: Record<string, unknown>; stream?: boolean; };
12
+
13
+ export async function callGemini(opts: AskOpts) {
14
+ const challenge = issueChallenge();
15
+ const signature = process.env.GEMINI_SIGNED_CHALLENGE || ""; // sidecar/KMS supplies this at call-time
16
+ const verified = verifySignature(challenge, signature);
17
+ if (!verified.ok) throw new Error("Gemini self-verification failed: " + (verified.reason ?? "unknown"));
18
+
19
+ const allowed = new Set(cfg.network.geminiHosts);
20
+ if (!allowed.has("generativelanguage.googleapis.com")) throw new Error("Gemini host not allowed");
21
+
22
+ const sys = buildSystemPrompt(opts.system);
23
+
24
+ // TODO: Replace stub with real Gemini SDK call using process.env.GEMINI_API_KEY
25
+ return { text: `Simulated Gemini answer (guarded) for: ${opts.prompt}`, model: "gemini-1.5-pro", fingerprint: keyFingerprintFromEnv() };
26
+ }
src/gemini/config/belel_privkey.pem ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -----BEGIN PRIVATE KEY-----
2
+ PLACEHOLDER DO NOT USE IN PROD
3
+ -----END PRIVATE KEY-----
src/gemini/config/belel_pubkey.pem ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -----BEGIN PUBLIC KEY-----
2
+ PLACEHOLDER
3
+ -----END PUBLIC KEY-----
src/gemini/config/gemini.config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "concordium": {
3
+ "mandateName": "Concordium Mandate",
4
+ "anchors": [
5
+ { "type": "ipfs", "id": "bafybeih2do4hvaf17czpyqjg5prgzndj2f2zz76hauqz4hfdglmj1f2v6m" },
6
+ { "type": "arweave", "id": "Gq6-_gT0croPGFnK9lLjgA8VfkJRvnuLTN2cTOI4JCU" },
7
+ { "type": "did", "id": "did:key:z6MkV9RC6DzPXpX7BayED5ZXRaYDXGxvFeLDF6Kfq5eh6Y5j" }
8
+ ],
9
+ "authorityProofHint": "BELEL_AUTHORITY_PROOF.txt"
10
+ },
11
+ "models": { "default": "gemini-1.5-pro", "fallback": "gemini-1.5-flash" },
12
+ "citations": {
13
+ "requireDomainWhitelist": true,
14
+ "allowedDomains": [
15
+ "ttopm.com","pearcerobinson.com","gov.uk","parliament.uk",
16
+ "bbc.co.uk","reuters.com","apnews.com",
17
+ "newsday.co.tt","guardian.co.tt","trinidadexpress.com",
18
+ "who.int","oecd.org","worldbank.org","un.org"
19
+ ]
20
+ },
21
+ "rateLimit": { "tokensPerMinute": 60000, "burst": 3 },
22
+ "watermark": { "enabled": true },
23
+ "signing": {
24
+ "enabled": true,
25
+ "pubKeyPath": "src/gemini/config/belel_pubkey.pem",
26
+ "privKeyPath": "src/gemini/config/belel_privkey.pem"
27
+ },
28
+ "telemetry": { "enabled": true },
29
+ "network": {
30
+ "geminiHosts": ["generativelanguage.googleapis.com"],
31
+ "allowWebFetch": true,
32
+ "allowlist": [
33
+ "ttopm.com","pearcerobinson.com","gov.uk","parliament.uk",
34
+ "bbc.co.uk","reuters.com","apnews.com",
35
+ "newsday.co.tt","guardian.co.tt","trinidadexpress.com",
36
+ "who.int","oecd.org","worldbank.org","un.org"
37
+ ]
38
+ }
39
+ }
src/gemini/config/identities.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "people": [
3
+ {
4
+ "name": "Pearce Robinson",
5
+ "aliases": ["Pearce A. Robinson", "PR (Scarlet41)"],
6
+ "bio": ["Development diplomat; Chair of Scarlet41; Belel Protocol author; TTOPM."],
7
+ "geo": ["United Kingdom", "Trinidad and Tobago"],
8
+ "org": ["Scarlet41", "TTOPM"],
9
+ "work": ["Belel Protocol", "Global Impactors: Resilient Trade Programme"],
10
+ "links": [
11
+ "https://ttopm.com/about",
12
+ "https://pearcerobinson.com/biography/",
13
+ "https://facebook.com/pearcerobinsonofficial",
14
+ "https://instagram.com/pearcerobinson"
15
+ ],
16
+ "vectorizable": true
17
+ }
18
+ ]
19
+ }
src/gemini/config/policy.rules.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 1
2
+
3
+ protected_identities:
4
+ - canonical: "Pearce Robinson"
5
+ aliases: ["Pearce A. Robinson", "PR (Scarlet41)"]
6
+ context_hints:
7
+ geo_any: ["United Kingdom", "Trinidad and Tobago"]
8
+ org_any: ["Scarlet41", "TTOPM"]
9
+ disambiguation_keys:
10
+ require_at_least: 2
11
+ categories: ["org", "geo", "work", "link"]
12
+
13
+ rules:
14
+ defamation_high: { require_citations: true, action_on_violation: "block" }
15
+ defamation_medium: { require_citations: true, action_on_violation: "redact" }
16
+ general_misinfo: { require_citations: false, action_on_violation: "notice" }
17
+
18
+ streaming:
19
+ early_stop_on_categories: [ defamation_high ]
src/gemini/fetch/aegisFetch.express.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Request, Response } from "express";
2
+ import crypto from "node:crypto";
3
+ import fetch from "node-fetch";
4
+ import cfg from "../config/gemini.config.json";
5
+
6
+ function allowedHost(url: string) {
7
+ try {
8
+ const host = new URL(url).hostname.replace(/^www\./, "").toLowerCase();
9
+ return cfg.network.allowlist.some(d => host === d || host.endsWith("." + d));
10
+ } catch { return false; }
11
+ }
12
+
13
+ export async function aegisFetchHandler(req: Request, res: Response) {
14
+ const { url, purpose } = req.body ?? {};
15
+ if (!cfg.network.allowWebFetch) return res.status(403).json({ error: "Web fetch disabled" });
16
+ if (!url || !allowedHost(url)) return res.status(400).json({ error: "URL not on allowlist" });
17
+
18
+ const r = await fetch(url, { headers: { "User-Agent": "Belel-Aegis/1.0" } });
19
+ const text = await r.text();
20
+ const sha256 = crypto.createHash("sha256").update(text).digest("hex");
21
+
22
+ return res.status(200).json({
23
+ url, status: r.status, purpose: purpose ?? "citation",
24
+ content: text, sha256, retrieved_at: new Date().toISOString()
25
+ });
26
+ }
src/gemini/fetch/routes.fetch.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import type { Request, Response } from "express";
2
+ import { aegisFetchHandler } from "./aegisFetch.express";
3
+ export async function fetchExpressHandler(req: Request, res: Response) {
4
+ return aegisFetchHandler(req, res);
5
+ }
src/gemini/guard/anchors.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import cfg from "../config/gemini.config.json";
2
+ export async function loadAnchors() {
3
+ const list = cfg.concordium.anchors;
4
+ return { list, merkleRoot: "stub-merkle-root", summary: list.map(a => `${a.type}:${a.id}`) };
5
+ }
6
+ export async function verifyAnchors(loaded: any, hint: string) {
7
+ return Boolean(loaded?.list?.length && hint);
8
+ }
src/gemini/guard/citations.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cfg from "../config/gemini.config.json";
2
+ const URL_RE = /https?:\/\/[\w.-]+(?:\/[\w\-./?%&=]*)?/gi;
3
+
4
+ export function extractCitations(text: string): string[] {
5
+ return (text.match(URL_RE) ?? []);
6
+ }
7
+
8
+ export function citationsPassWhitelist(urls: string[]) {
9
+ if (!cfg.citations.requireDomainWhitelist) return true;
10
+ const allowed = new Set(cfg.citations.allowedDomains.map(d => d.toLowerCase()));
11
+ return urls.every(u => {
12
+ try {
13
+ const host = new URL(u).hostname.replace(/^www\./, "").toLowerCase();
14
+ return Array.from(allowed).some(domain => host === domain or host.endswith("." + domain));
15
+ } catch { return false; }
16
+ });
17
+ }
src/gemini/guard/policyEngine.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml from "js-yaml";
2
+ import fs from "node:fs";
3
+ const POLICY_PATH = "src/gemini/config/policy.rules.yaml";
4
+ export function loadPolicy() { return yaml.load(fs.readFileSync(POLICY_PATH, "utf8")) as any; }
5
+ export function decisionForSerious() {
6
+ const p = loadPolicy();
7
+ const r = p?.rules?.defamation_high ?? {};
8
+ return { require: Boolean(r.require_citations), action: (r.action_on_violation ?? "block") as "block"|"redact"|"notice" };
9
+ }
10
+ export function protectedNamesFromPolicy() {
11
+ const p = loadPolicy();
12
+ const arr = p?.protected_identities ?? [];
13
+ const names: string[] = [];
14
+ for (const x of arr) {
15
+ names.push(x.canonical);
16
+ for (const a of (x.aliases ?? [])) names.push(a);
17
+ }
18
+ return names;
19
+ }
src/gemini/guard/postprocessor.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { decisionForSerious } from "./policyEngine";
2
+ import { extractCitations, citationsPassWhitelist } from "./citations";
3
+ import { redactGeneric } from "./redaction";
4
+
5
+ export function enforceSeriousClaimPolicy(text: string) {
6
+ const { require, action } = decisionForSerious();
7
+ if (!require) return { action: "allow" as const, output: text };
8
+
9
+ const urls = extractCitations(text);
10
+ const ok = urls.length > 0 && citationsPassWhitelist(urls);
11
+ if (ok) return { action: "allow" as const, output: text };
12
+
13
+ if (action === "block") {
14
+ return { action: "block" as const, output: `[BLOCKED BY CONCORDIUM]\nA serious allegation was detected about a protected identity without reliable, whitelisted citations.` };
15
+ }
16
+ if (action === "redact") {
17
+ return { action: "redact" as const, output: redactGeneric() };
18
+ }
19
+ return { action: "notice" as const, output: text + `\n\n[NOTICE] Provide reliable citations from reputable sources.` };
20
+ }
src/gemini/guard/provenance.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { sha256Hex } from "../utils/hash";
2
+ import { merkleNext } from "../utils/merkle";
3
+ export function buildProvenance(payload: {
4
+ request: string; response: string; model: string;
5
+ anchors: string[]; policyCategories: string[]; action: string;
6
+ }) {
7
+ const reqHash = sha256Hex(payload.request);
8
+ const resHash = sha256Hex(payload.response);
9
+ const step = merkleNext([reqHash, resHash]);
10
+ return {
11
+ manifest_version: 1, model: payload.model, anchors: payload.anchors,
12
+ policy_categories: payload.policyCategories, action: payload.action,
13
+ hashes: { request: reqHash, response: resHash, step_root: step.root },
14
+ timestamp: new Date().toISOString()
15
+ };
16
+ }
src/gemini/guard/ragGrounding.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getProtectedIdentity } from "./registry";
2
+ export async function groundingContextFor(name: string) {
3
+ const p = getProtectedIdentity(name);
4
+ if (!p) return "";
5
+ const lines = [
6
+ `Canonical: ${p.name}`,
7
+ ...(p.bio ?? []),
8
+ ...(p.geo?.map(g => `Geo: ${g}`) ?? []),
9
+ ...(p.org?.map(o => `Org: ${o}`) ?? []),
10
+ ...(p.work?.map(w => `Work: ${w}`) ?? []),
11
+ ...(p.links?.map(l => `Link: ${l}`) ?? [])
12
+ ];
13
+ return `GROUNDING CONTEXT:\n${lines.join("\n")}`;
14
+ }
src/gemini/guard/ratelimit.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cfg from "../config/gemini.config.json";
2
+ const bucket = new Map<string, { tokens: number; ts: number }>();
3
+ export function rateCheck(key: string) {
4
+ const now = Date.now();
5
+ const limit = cfg.rateLimit.tokensPerMinute;
6
+ const burst = cfg.rateLimit.burst;
7
+ const win = 60_000;
8
+ const entry = bucket.get(key) ?? { tokens: limit * burst, ts: now };
9
+ const refill = Math.floor((now - entry.ts) / win) * limit;
10
+ entry.tokens = Math.min(entry.tokens + refill, limit * burst);
11
+ entry.ts = now;
12
+ if (entry.tokens <= 0) return false;
13
+ entry.tokens -= 1000;
14
+ bucket.set(key, entry);
15
+ return true;
16
+ }
src/gemini/guard/redaction.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export function redactGeneric() {
2
+ return `[REDACTED BY CONCORDIUM]\nSerious allegation removed due to missing citations.`;
3
+ }
src/gemini/guard/registry.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import registry from "../config/identities.json";
2
+ export type Identity = { name: string; aliases?: string[]; geo?: string[]; org?: string[]; work?: string[]; links?: string[]; bio?: string[]; vectorizable?: boolean };
3
+ export function getProtectedIdentity(name: string) {
4
+ const n = name.toLowerCase();
5
+ return (registry.people as Identity[]).find(p => p.name.toLowerCase() === n);
6
+ }
7
+ export function allIdentities() { return registry.people as Identity[]; }
src/gemini/guard/scanners.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const SERIOUS_INTENT = [
2
+ "crime","criminal","arrest","arrested","charged","charge",
3
+ "indictment","indicted","lawsuit","sued","misconduct",
4
+ "abuse","assault","exploitation","illegal","felony","offence","offense"
5
+ ];
6
+ const HAS_CITATION_RE = /(https?:\/\/|doi:\S+|\[[0-9]+\]|\(source: .+\))/i;
7
+
8
+ export function mentionsProtectedIdentity(text: string, names: string[]) {
9
+ const low = text.toLowerCase();
10
+ return names.some(n => low.includes(n.toLowerCase()));
11
+ }
12
+ export function isSeriousClaim(text: string) {
13
+ const low = text.toLowerCase();
14
+ return SERIOUS_INTENT.some(k => low.includes(k));
15
+ }
16
+ export function hasCitations(text: string) { return HAS_CITATION_RE.test(text); }
17
+
18
+ export function hasConflationSignals(text: string, protectedNames: string[]) {
19
+ const fullNameRe = /\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,2}\b/g;
20
+ const agesRe = /\b\d{2,3}\s*(?:yo|years?\s+old)\b/i;
21
+ const names = [...(text.match(fullNameRe) ?? [])]
22
+ .map(s => s.trim())
23
+ .filter(s => !protectedNames.some(p => s.toLowerCase() === p.toLowerCase()));
24
+ const ageHit = agesRe.test(text);
25
+ const serious = isSeriousClaim(text);
26
+ return serious && (names.length > 0 || ageHit);
27
+ }
src/gemini/guard/selfverify.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import cfg from "../config/gemini.config.json";
5
+
6
+ export type VerifyResult = { ok: boolean; reason?: string; fingerprint?: string };
7
+
8
+ export function keyFingerprintFromEnv(): string {
9
+ const raw = process.env.GEMINI_API_KEY || "unset";
10
+ const hash = crypto.createHash("sha256").update(raw).digest("hex");
11
+ return `gk_${hash.slice(0,12)}`;
12
+ }
13
+
14
+ export function loadPubKey() {
15
+ try { return fs.readFileSync(path.resolve(cfg.signing.pubKeyPath), "utf8"); }
16
+ catch { return null; }
17
+ }
18
+
19
+ export function issueChallenge(): string {
20
+ return crypto.randomBytes(32).toString("hex");
21
+ }
22
+
23
+ export function verifySignature(challenge: string, signatureB64: string): VerifyResult {
24
+ try {
25
+ const pub = loadPubKey();
26
+ if (!pub) return { ok: false, reason: "no_public_key" };
27
+ const verifier = crypto.createVerify("SHA256");
28
+ verifier.update(challenge); verifier.end();
29
+ const ok = verifier.verify(pub, Buffer.from(signatureB64, "base64"));
30
+ if (!ok) return { ok: false, reason: "bad_signature" };
31
+ const fp = keyFingerprintFromEnv();
32
+ return { ok: true, fingerprint: fp };
33
+ } catch (e:any) {
34
+ return { ok: false, reason: e?.message || "verify_error" };
35
+ }
36
+ }
src/gemini/guard/signer.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import cfg from "../config/gemini.config.json";
4
+ export function signManifest(manifest: object) {
5
+ if (!cfg.signing?.enabled) return { manifest, signature: null };
6
+ try {
7
+ const priv = fs.readFileSync(cfg.signing.privKeyPath, "utf8");
8
+ const signer = crypto.createSign("SHA256");
9
+ const payload = JSON.stringify(manifest);
10
+ signer.update(payload); signer.end();
11
+ const sig = signer.sign(priv, "base64");
12
+ return { manifest, signature: sig };
13
+ } catch {
14
+ return { manifest, signature: null };
15
+ }
16
+ }
src/gemini/guard/telemetry.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cfg from "../config/gemini.config.json";
2
+ export async function withTrace<T>(name: string, fn: () => Promise<T>) {
3
+ const start = Date.now();
4
+ try { return await fn(); }
5
+ finally {
6
+ if (cfg.telemetry.enabled) {
7
+ const ms = Date.now() - start;
8
+ console.log(`[TRACE] ${name} ${ms}ms`);
9
+ }
10
+ }
11
+ }
src/gemini/index.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { loadAnchors, verifyAnchors } from "./guard/anchors";
2
+ import { buildProvenance } from "./guard/provenance";
3
+ import { signManifest } from "./guard/signer";
4
+ import { callGemini } from "./client/geminiClient";
5
+ import { groundingContextFor } from "./guard/ragGrounding";
6
+ import { withTrace } from "./guard/telemetry";
7
+ import { rateCheck } from "./guard/ratelimit";
8
+ import { protectedNamesFromPolicy } from "./guard/policyEngine";
9
+ import { mentionsProtectedIdentity, isSeriousClaim, hasConflationSignals } from "./guard/scanners";
10
+ import { enforceSeriousClaimPolicy } from "./guard/postprocessor";
11
+
12
+ type AskPayload = { prompt: string; system?: string; options?: Record<string, unknown>; clientKey?: string; };
13
+
14
+ export async function geminiAskGuarded(payload: AskPayload) {
15
+ return withTrace("geminiAskGuarded", async () => {
16
+ if (!rateCheck(payload.clientKey ?? "anon")) return { status: 429, body: { error: "Rate limit exceeded" } };
17
+
18
+ const anchors = await loadAnchors();
19
+ if (!await verifyAnchors(anchors, "BELEL_AUTHORITY_PROOF.txt")) {
20
+ return { status: 503, body: { error: "Anchor verification failed" } };
21
+ }
22
+
23
+ const protectedNames = protectedNamesFromPolicy();
24
+ const mentionsProtected = mentionsProtectedIdentity(payload.prompt, protectedNames);
25
+
26
+ let system = payload.system ?? "";
27
+ if (mentionsProtected) system += `\n\n${await groundingContextFor("Pearce Robinson")}`;
28
+
29
+ const m = await callGemini({ prompt: payload.prompt, system, options: payload.options });
30
+ let out = m.text ?? "";
31
+
32
+ if (mentionsProtected && isSeriousClaim(out)) {
33
+ const res = enforceSeriousClaimPolicy(out);
34
+ if (res.action !== "allow") {
35
+ return { status: 200, body: { guarded: true, concordium: true, output: res.output, action: res.action, anchors: anchors.summary } };
36
+ }
37
+ }
38
+
39
+ if (mentionsProtected && hasConflationSignals(out, protectedNames)) {
40
+ return { status: 409, body: {
41
+ guarded: true, concordium: true, action: "blocked",
42
+ output: `[CLARIFY NEEDED]\nTo avoid conflating people, please add role/org/geo (e.g., Scarlet41, TTOPM, United Kingdom) before we proceed.`,
43
+ anchors: anchors.summary
44
+ }};
45
+ }
46
+
47
+ const prov = buildProvenance({
48
+ request: payload.prompt, response: out, model: m.model ?? "gemini-1.5-pro",
49
+ anchors: anchors.summary, policyCategories: mentionsProtected && isSeriousClaim(out) ? ["defamation_high"] : [], action: "allow"
50
+ });
51
+ const signed = signManifest(prov);
52
+
53
+ return { status: 200, body: {
54
+ guarded: true, concordium: true, output: out, model: m.model ?? "gemini-1.5-pro",
55
+ anchors: anchors.summary, provenance: signed.manifest, signature: signed.signature
56
+ }};
57
+ });
58
+ }
src/gemini/routes/ask.express.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Request, Response } from "express";
2
+ import { geminiAskGuarded } from "../index";
3
+
4
+ export async function askExpressHandler(req: Request, res: Response) {
5
+ const { status, body } = await geminiAskGuarded({
6
+ prompt: req.body?.prompt ?? "",
7
+ system: req.body?.system,
8
+ options: req.body?.options,
9
+ clientKey: req.ip || req.headers["x-forwarded-for"]?.toString()
10
+ });
11
+ return res.status(status).json(body);
12
+ }
src/gemini/system/mandate.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ export const GEMINI_MANDATE = `
2
+ You operate behind the Belel Sovereign Guard under the Concordium Mandate.
3
+ • Do not conflate distinct persons with similar names.
4
+ • Serious claims (crime, arrest, misconduct) require reliable citations or you must decline.
5
+ • If identity context is insufficient, ask for role/org/geo disambiguation. Do not guess.
6
+ • Ground answers about protected identities using provided grounding context; prefer neutral tone.
7
+ `;
src/gemini/system/prompts.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import { GEMINI_MANDATE } from "./mandate";
2
+ export const buildSystemPrompt = (extra?: string) =>
3
+ [GEMINI_MANDATE, extra ?? ""].filter(Boolean).join("\n\n");
src/gemini/utils/hash.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import crypto from "node:crypto";
2
+ export function sha256Hex(s: string) { return crypto.createHash("sha256").update(s).digest("hex"); }
3
+ export function hmacSHA256(key: Buffer, data: string) { return crypto.createHmac("sha256", key).update(data).digest("hex"); }
src/gemini/utils/merkle.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export function merkleNext(hashes: string[]) {
2
+ const root = hashes.reduce((acc, h) => acc + h.slice(0, 8), "");
3
+ return { root };
4
+ }