From 19fa64d176f75ea540bb580e032d860345c4bb95 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:17 +0000 Subject: [PATCH 1/9] feat(bridge): send the sandbox app's transfers to the Xtradot Bank sandbox, once, off the request path --- api/services/forge_bridge.py | 146 +++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 api/services/forge_bridge.py diff --git a/api/services/forge_bridge.py b/api/services/forge_bridge.py new file mode 100644 index 0000000..f70f42a --- /dev/null +++ b/api/services/forge_bridge.py @@ -0,0 +1,146 @@ +"""The bank bridge: the sandbox demo, connected to the Xtradot Bank sandbox. + +The sandbox app (the demo bank customers use) works on Fable's own simulated +ledger. For one institution, named in FORGE_BRIDGE_INSTITUTION, every transfer +that money actually moves on (a pass, a verified flag, a released hold) is also +sent to the Xtradot Bank sandbox, from the customer's own account there. The +app is unchanged; the bank's answer (reference, fee, VAT, stamp duty, status) +is then read from /v1/forge/transfers/{transaction id}. + +Sending happens off the request path, once per transfer, through the same +claim-then-send state machine as the rest of the Forge integration +(services/forge_transfers.py): a lost answer is only ever queried, never resent. +""" +import logging +import os +from concurrent.futures import ThreadPoolExecutor + +from core.db import cursor, row_to_dict +from services import forge_transfers + +logger = logging.getLogger("fable.forge") + +XTRADOT_NIP = "000014" + +# The sandbox's banks (platform guide, section 5.4): name -> NIP code. +BANKS = { + "Xtradot Bank": "000014", + "GTBank": "000013", + "Zenith Bank": "000015", + "First Bank of Nigeria": "000016", + "UBA": "000004", + "Wema Bank": "000017", + "OPay": "100004", + "Moniepoint MFB": "090405", + "Kuda MFB": "090267", + "PalmPay": "100033", +} + +# The team's own accounts at Xtradot Bank. The demo's customers use the account +# number as their reference, so a customer maps straight to their account. +TEAM_ACCOUNTS = { + "0123456789": ("Adaeze Chiamaka Okonkwo", 1_500_000), + "0123456790": ("Babatunde Olumide Adeyemi", 5_000_000), + "0123456791": ("Musa Ibrahim Abdullahi", 250_000), + "0123456792": ("Efosa Godwin Osagie", 40_000), + "0123456793": ("Mama Nkechi Provisions Ltd", 12_000_000), +} + +# The sandbox's beneficiaries: account -> (holder, bank name). +BENEFICIARIES = { + "0987654321": ("Ngozi Adaobi Eze", "Xtradot Bank"), + "0987654322": ("Aisha Hauwa Bello", "Xtradot Bank"), + "0987654399": ("Obinna Kelechi Okafor", "Xtradot Bank"), + "0123987001": ("Chukwuemeka Ifeanyi Nwosu", "GTBank"), + "0123987099": ("Garba Sani Danjuma", "GTBank"), + "0123987002": ("Funmilayo Abiola Ogunleye", "Zenith Bank"), + "0123987003": ("Zainab Halima Yusuf", "First Bank of Nigeria"), + "0123987004": ("Tamunotonye Briggs", "UBA"), + "0123987098": ("Blessing Oghenekaro Edeh", "Wema Bank"), + "8031234506": ("Ifeoluwa Grace Adebayo", "OPay"), + "8051234507": ("Iya Bisi Foods Enterprises", "Moniepoint MFB"), +} + +_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="fable-bridge") + + +def institution() -> str: + return os.getenv("FORGE_BRIDGE_INSTITUTION", "").strip() + + +def enabled_for(institution_id: str | None) -> bool: + target = institution() + return bool(target) and institution_id == target + + +def bank_code(account: str | None, bank: str | None, code: str | None = None) -> str | None: + """The NIP code for a recipient: as sent, else from the bank's name, else + from the sandbox's own beneficiary list.""" + if code and code in BANKS.values(): + return code + if bank and bank in BANKS: + return BANKS[bank] + if account in BENEFICIARIES: + return BANKS[BENEFICIARIES[account][1]] + if account in TEAM_ACCOUNTS: + return XTRADOT_NIP + return None + + +def _source_account(user_id: str) -> str | None: + with cursor() as cur: + cur.execute("SELECT external_ref FROM customers WHERE id = ?", (user_id,)) + row = cur.fetchone() + ref = row["external_ref"] if row else None + return ref if ref in TEAM_ACCOUNTS else None + + +def mirror(transaction_id: str, *, recipient_bank_code: str | None = None) -> dict | None: + """Send one decided, money-moving transfer to the bank, once. Returns the + transfer's row, or None when this institution is not bridged.""" + with cursor() as cur: + cur.execute("""SELECT id, user_id, institution_id, amount, recipient_account, recipient_bank, + recipient_name, narration, action_taken FROM transactions WHERE id = ?""", + (transaction_id,)) + txn = row_to_dict(cur.fetchone()) + if not txn or not enabled_for(txn["institution_id"]): + return None + existing = forge_transfers.get(transaction_id) + if existing: + return existing + + source = _source_account(txn["user_id"]) + code = bank_code(txn["recipient_account"], txn["recipient_bank"], recipient_bank_code) + row = forge_transfers.record( + transfer_id=transaction_id, institution_id=txn["institution_id"], user_id=txn["user_id"], + source_account=source or "unknown", destination_account=txn["recipient_account"] or "unknown", + destination_bank_code=code, intra=code == XTRADOT_NIP, recipient_name=txn["recipient_name"], + amount=float(txn["amount"]), narration=(txn["narration"] or "Fable sandbox")[:100], + name_enquiry_ref=None, action="PASS") + if not source or not code or not txn["recipient_account"]: + reason = ("This customer has no account at Xtradot Bank." if not source + else "The recipient's bank is not one of the sandbox's banks.") + forge_transfers._set(transaction_id, state="failed", last_error=reason) # noqa: SLF001 + return forge_transfers.get(transaction_id) + return forge_transfers.execute(row["id"], poll_attempts=6, poll_wait=2.0) + + +def mirror_later(transaction_id: str, *, recipient_bank_code: str | None = None) -> None: + """Queue the send off the request path. The decision has already been + returned; the bank's answer is read later by the app.""" + try: + with cursor() as cur: + cur.execute("SELECT institution_id FROM transactions WHERE id = ?", (transaction_id,)) + row = cur.fetchone() + if not row or not enabled_for(row["institution_id"]): + return + except Exception: # noqa: BLE001 - the bridge must never affect a decision + return + + def run(): + try: + mirror(transaction_id, recipient_bank_code=recipient_bank_code) + except Exception as exc: # noqa: BLE001 + logger.warning("Sending %s to the bank failed: %s", transaction_id, type(exc).__name__) + + _pool.submit(run) From 66fdb5219cc903a55fa744ac3546c4b189e99a8d Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:17 +0000 Subject: [PATCH 2/9] feat(bridge): a pass, a verified flag and a released hold each reach the bank when money moves --- api/agents/ghost/account.py | 4 ++++ api/routers/shield.py | 4 ++++ api/routers/transactions.py | 3 +++ 3 files changed, 11 insertions(+) diff --git a/api/agents/ghost/account.py b/api/agents/ghost/account.py index 6909cac..17c6621 100644 --- a/api/agents/ghost/account.py +++ b/api/agents/ghost/account.py @@ -461,6 +461,10 @@ def _debit_if_sandbox(container: dict, user_id: str) -> None: transaction_id=container.get("transaction_id") or container["ghost_id"], reference=f"ghost-release:{container['ghost_id']}", ) + if container.get("transaction_id"): + from services import forge_bridge + + forge_bridge.mirror_later(container["transaction_id"]) def release_ghost(ghost_id: str, user_id: str, stepup_token: str | None = None) -> dict: diff --git a/api/routers/shield.py b/api/routers/shield.py index dac1c7d..c2ab8ca 100644 --- a/api/routers/shield.py +++ b/api/routers/shield.py @@ -300,6 +300,10 @@ def _replayed(): payload.user_id, transaction["amount"], institution_id, transaction_id=transaction_id, reference=f"txn:{transaction_id}", ) + # A bank connected to the Xtradot sandbox also gets the transfer itself. + from services import forge_bridge + + forge_bridge.mirror_later(transaction_id, recipient_bank_code=transaction.get("recipient_bank_code")) return ShieldAnalyzeResponse( risk_score=result["risk_score"], diff --git a/api/routers/transactions.py b/api/routers/transactions.py index 566ed41..3e78e59 100644 --- a/api/routers/transactions.py +++ b/api/routers/transactions.py @@ -177,6 +177,9 @@ def approve(txid: str, payload: ApproveRequest, request: Request): ) debit(payload.user_id, row["amount"], institution_id, transaction_id=txid, reference=f"txn-approve:{txid}") + from services import forge_bridge + + forge_bridge.mirror_later(txid) # Verified and sent: the customer proved it was them, so this transfer now # teaches the baseline (recipient, device, amount, hour) for next time. From d453a93b7238336b3acb94a7548eb8865e22937a Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:18 +0000 Subject: [PATCH 3/9] feat(bridge): Xtradot Bank onboarded at startup with a console owner, its customers and their history imported --- api/services/forge_history.py | 49 +++++++++++++++++++++++++++++++ api/services/forge_seed.py | 55 ++++++++++++++++++++++++++++++----- 2 files changed, 97 insertions(+), 7 deletions(-) create mode 100644 api/services/forge_history.py diff --git a/api/services/forge_history.py b/api/services/forge_history.py new file mode 100644 index 0000000..2813818 --- /dev/null +++ b/api/services/forge_history.py @@ -0,0 +1,49 @@ +"""Sixty days of believable history for the bank sandbox's five customers. + +Fed through the same import the console uses (services/imports.py), so each +customer starts with real habits: who they pay, how much, at what hours. The +payees are the sandbox's own beneficiaries, so a saved recipient in the app is +an account the bank will accept. Deterministic: the same rows every time, with +dates counted back from today. +""" +import random +from datetime import datetime, timedelta, timezone + +from services.forge_bridge import BENEFICIARIES, TEAM_ACCOUNTS + +LAGOS = timezone(timedelta(hours=1)) + +# account -> (segment, usual payees, amount range, transfers in 60 days, usual hours) +HABITS = { + "0123456789": ("Salaried", ["0987654321", "0123987001", "8031234506"], (2_000, 30_000), 34, [8, 12, 18, 19, 20, 21]), + "0123456790": ("Trader", ["0123987002", "0123987004", "8051234507"], (50_000, 400_000), 46, [9, 10, 11, 13, 14, 15, 16]), + "0123456791": ("Salaried", ["0987654322", "0123987003"], (5_000, 40_000), 24, [7, 12, 17, 19, 20]), + "0123456792": ("Student", ["8031234506", "0987654321"], (1_000, 6_000), 30, [10, 13, 16, 20, 22, 23]), + "0123456793": ("Trader", ["8051234507", "0123987001", "0123987002"], (100_000, 1_500_000), 40, [8, 9, 10, 11, 14, 15]), +} + + +def customer_rows() -> list[dict]: + return [{"reference": account, "name": name, "segment": HABITS[account][0], "kind": "test", + "opening_balance": balance} for account, (name, balance) in TEAM_ACCOUNTS.items()] + + +def transaction_rows(now: datetime | None = None) -> list[dict]: + now = (now or datetime.now(timezone.utc)).astimezone(LAGOS) + rows = [] + for account, (_segment, payees, (low, high), count, hours) in HABITS.items(): + rng = random.Random(f"fable-forge-{account}") + for i in range(count): + day = rng.randint(1, 60) + when = (now - timedelta(days=day)).replace(hour=rng.choice(hours), minute=rng.randint(0, 59), + second=0, microsecond=0) + payee = rng.choice(payees) + name, bank = BENEFICIARIES[payee] + amount = round(rng.uniform(low, high) / 100) * 100 + rows.append({ + "customer_reference": account, "reference": f"HIST-{account}-{i:03d}", "amount": amount, + "occurred_at": when.isoformat(), "recipient_account": payee, "recipient_bank": bank, + "recipient_name": name, "channel": "mobile_app", "outcome": "completed", "city": "Lagos", + "country": "Nigeria", + }) + return rows diff --git a/api/services/forge_seed.py b/api/services/forge_seed.py index ee4597e..d0e306e 100644 --- a/api/services/forge_seed.py +++ b/api/services/forge_seed.py @@ -66,12 +66,53 @@ def ensure_demo(raw_key: str | None = None, *, new_key: bool = False) -> dict: return {"customers": made, "issued_key": issued} +def ensure_bank(institution_id: str, email: str, password: str) -> dict: + """The bank connected to the Xtradot sandbox, set up as a bank would be: + a sandbox institution with an owner who signs in to the console, and its + customers and their past transfers brought in through the console's own + import. Safe to run again: the import skips what it already has.""" + from core.utils import hash_password + from services import forge_history, imports + + if not email or "@" not in email or len(password) < 12: + raise ValueError("The console login needs an email and a password of at least 12 characters.") + register_institution(institution_id, "Xtradot Bank", email) + with cursor() as cur: + cur.execute("UPDATE institutions SET mode = 'sandbox' WHERE institution_id = ?", (institution_id,)) + cur.execute("SELECT 1 FROM admins WHERE email = ?", (email.lower(),)) + if cur.fetchone() is None: + cur.execute("INSERT INTO admins (email, institution_id, hashed_password, role, name, active) " + "VALUES (?, ?, ?, 'owner', 'Team Fable', 1)", + (email.lower(), institution_id, hash_password(password))) + made = imports.import_batch(institution_id, "customers", forge_history.customer_rows(), + sandbox=True, actor="forge-seed") + history = forge_history.transaction_rows() + inserted = 0 + for start in range(0, len(history), imports.MAX_ROWS_PER_BATCH): + inserted += imports.import_batch(institution_id, "transactions", history[start:start + imports.MAX_ROWS_PER_BATCH], + sandbox=True, actor="forge-seed")["inserted"] + for account in forge_history.HABITS: + customer = customers.get(institution_id, account) + if customer and not security.status(customer["id"]).get("pin_set"): + security.set_pin(customer["id"], DEMO_PIN, institution_id=institution_id) + return {"customers": made["inserted"], "history": inserted} + + def ensure_from_env() -> bool: - """At startup: set the demo up when its key is configured. Does nothing - otherwise, so only the Forge deployment ever creates this institution.""" + """At startup: set the demo up when it is configured. Does nothing + otherwise, so only the Forge deployment ever creates these institutions.""" + did = False raw = os.getenv("FORGE_DEMO_API_KEY", "").strip() - if not raw: - return False - ensure_demo(raw) - logger.info("The Forge demo institution is ready.") - return True + if raw: + ensure_demo(raw) + logger.info("The Forge demo institution is ready.") + did = True + bank = os.getenv("FORGE_BRIDGE_INSTITUTION", "").strip() + email = os.getenv("FORGE_CONSOLE_EMAIL", "").strip() + password = os.getenv("FORGE_CONSOLE_PASSWORD", "") + if bank and email and password: + result = ensure_bank(bank, email, password) + logger.info("The bank connected to the Xtradot sandbox is ready: %s customers and %s past transfers " + "imported.", result["customers"], result["history"]) + did = True + return did From bae84dd17c6468d30a78a10150143e7a9dcfeca9 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:18 +0000 Subject: [PATCH 4/9] test(bridge): habits from imported history, one send per transfer, nothing sent for holds or other banks --- api/tests/test_forge_bridge.py | 192 +++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 api/tests/test_forge_bridge.py diff --git a/api/tests/test_forge_bridge.py b/api/tests/test_forge_bridge.py new file mode 100644 index 0000000..09dbe41 --- /dev/null +++ b/api/tests/test_forge_bridge.py @@ -0,0 +1,192 @@ +"""The sandbox demo, connected to the Xtradot Bank sandbox: what the app does is +unchanged, and every transfer money moves on also reaches the bank, once.""" +import os +import socket +import sys +import tempfile +import time + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault("FABLE_DB_PATH", os.path.join(tempfile.mkdtemp(), "forge-bridge.db")) +os.environ.setdefault("FABLE_SESSION_SECRET", "test-secret") + +BANK = "xtradot" +EMAIL = "team11@fable.ng" +_n = [0] + + +class FakeBank: + def __init__(self): + self.calls = [] + + def sends(self): + return [c for c in self.calls if c["method"] == "POST" and c["url"].rsplit("/", 1)[-1] in ("intra", "interbank")] + + def __call__(self, method, url, payload, headers, timeout): + from services.forge_bank import Reply + from services.forge_bridge import BENEFICIARIES + + self.calls.append({"method": method, "url": url, "payload": payload}) + ok = lambda data, status=200: Reply(status, {"status": "success", "data": data}) # noqa: E731 + if url.endswith("/name-enquiry"): + acct = payload["account_number"] + return ok({"account_name": BENEFICIARIES[acct][0], "name_enquiry_ref": f"ne_{acct}_{time.time_ns()}"}) + if url.endswith("/transfers/intra"): + return ok({"status": "successful", "reference": payload["reference"], "fee": 0.0, "vat": 0.0, + "stamp_duty": 0.0, "total_debit": payload["amount"]}, 201) + if url.endswith("/transfers/interbank"): + if round(payload["amount"] * 100) % 100 == 2: + raise socket.timeout("timed out") + return ok({"status": "pending", "reference": payload["reference"]}, 202) + if url.endswith("/requery"): + return ok({"status": "successful", "reference": payload["reference"], "fee": 25.0, "vat": 1.88, + "stamp_duty": 0.0, "total_debit": 0.0}) + raise AssertionError(url) + + +@pytest.fixture +def bank(monkeypatch): + from services import forge_bank + + fake = FakeBank() + monkeypatch.setenv("GATEWAY_KEY", "test-team-key") + monkeypatch.setenv("FORGE_BRIDGE_INSTITUTION", BANK) + monkeypatch.setattr(forge_bank, "_send", fake) + monkeypatch.setattr(forge_bank.time, "sleep", lambda _s: None) + return fake + + +@pytest.fixture(scope="module") +def world(): + from fastapi.testclient import TestClient + + from core import sessions + from main import app + from services import forge_seed + + forge_seed.ensure_bank(BANK, EMAIL, "demo-password-123") + return TestClient(app), {"X-Fable-Session": sessions.issue(EMAIL, BANK)["token"]} + + +def _settled(txid, timeout=5.0): + from services import forge_transfers + + end = time.time() + timeout + while time.time() < end: + row = forge_transfers.get(txid) + if row and row["state"] in ("successful", "failed", "reversed"): + return row + time.sleep(0.05) + return forge_transfers.get(txid) + + +def _score(client, headers, customer, account, name, bank_name, code, amount): + _n[0] += 1 + res = client.post("/v1/shield/analyze", headers=headers, json={ + "user_id": customer, "client_reference": f"bridge-{_n[0]}-{time.time_ns()}", + "transaction": {"amount": amount, "recipient_account": account, "recipient_name": name, + "recipient_bank": bank_name, "recipient_bank_code": code, "channel": "mobile_app"}}) + assert res.status_code == 200, res.text + return res.json() + + +def test_the_bank_is_set_up_like_a_real_onboarding(world): + from core import customers + from core.db import cursor + + with cursor() as cur: + cur.execute("SELECT mode FROM institutions WHERE institution_id = ?", (BANK,)) + assert cur.fetchone()["mode"] == "sandbox" + cur.execute("SELECT COUNT(*) AS n FROM transaction_history WHERE institution_id = ?", (BANK,)) + assert cur.fetchone()["n"] > 100 + assert customers.get(BANK, "0123456789")["kind"] == "test" + + +def test_a_routine_transfer_to_a_usual_payee_passes_on_habits_and_reaches_the_bank(world, bank): + client, headers = world + body = _score(client, headers, "0123456789", "0987654321", "Ngozi Adaobi Eze", "Xtradot Bank", "000014", 5_000) + assert body["action"] == "PASS" + assert not any(s.startswith("cold_start") for s in body["signals"]) # judged on her history + row = _settled(body["transaction_id"]) + assert row["state"] == "successful" and row["source_account"] == "0123456789" + assert len(bank.sends()) == 1 and bank.sends()[0]["url"].endswith("/transfers/intra") + status = client.get(f"/v1/forge/transfers/{body['transaction_id']}", headers=headers, + params={"user_id": "0123456789"}) + assert status.status_code == 200 and status.json()["state"] == "successful" + + +def test_an_interbank_transfer_uses_the_bank_code_and_settles(world, bank): + client, headers = world + body = _score(client, headers, "0123456793", "0123987001", "Chukwuemeka Ifeanyi Nwosu", "GTBank", "000013", 150_000) + if body["action"] != "PASS": + pytest.skip("this amount was not a pass under the active engine version") + row = _settled(body["transaction_id"]) + assert row["state"] == "successful" and row["destination_bank_code"] == "000013" and row["fee"] == 25.0 + assert bank.sends()[0]["payload"]["destination_bank_code"] == "000013" + + +def test_a_lost_answer_is_queried_and_never_resent(world, bank): + client, headers = world + body = _score(client, headers, "0123456789", "0123987001", "Chukwuemeka Ifeanyi Nwosu", "GTBank", "000013", 5_000.02) + if body["action"] != "PASS": + pytest.skip("this amount was not a pass under the active engine version") + row = _settled(body["transaction_id"]) + assert len(bank.sends()) == 1 + from core.db import loads + + assert "unknown" in [s["state"] for s in loads(row["trail"], [])] + + +def test_a_held_or_flagged_transfer_is_not_sent_until_money_moves(world, bank): + client, headers = world + body = _score(client, headers, "0123456792", "0123987004", "Tamunotonye Briggs", "UBA", "000004", 38_000) + if body["action"] == "PASS": + pytest.skip("this amount passed under the active engine version") + time.sleep(0.3) + from services import forge_transfers + + assert forge_transfers.get(body["transaction_id"]) is None and bank.sends() == [] + + +def test_a_verified_flag_is_sent_when_approved(world, bank): + from core.db import cursor + from services import forge_bridge + + client, _ = world + with cursor() as cur: + cur.execute("SELECT id FROM customers WHERE institution_id = ? AND external_ref = '0123456790'", (BANK,)) + uid = cur.fetchone()["id"] + cur.execute("INSERT INTO transactions (id, user_id, amount, recipient_account, recipient_bank, recipient_name, " + "institution_id, action_taken, risk_score, shield_signals) VALUES " + "('txn_bridgeflag01', ?, 200000, '0123987002', 'Zenith Bank', 'Funmilayo Abiola Ogunleye', ?, " + "'FLAG', 0.6, '[]')", (uid, BANK)) + row = forge_bridge.mirror("txn_bridgeflag01") + assert row["state"] == "successful" and row["destination_bank_code"] == "000015" + assert forge_bridge.mirror("txn_bridgeflag01")["id"] == "txn_bridgeflag01" + assert len(bank.sends()) == 1 # a second call returns the same transfer, nothing new is sent + + +def test_an_unknown_bank_is_recorded_as_not_sent(world, bank): + from core.db import cursor + from services import forge_bridge + + with cursor() as cur: + cur.execute("SELECT id FROM customers WHERE institution_id = ? AND external_ref = '0123456791'", (BANK,)) + uid = cur.fetchone()["id"] + cur.execute("INSERT INTO transactions (id, user_id, amount, recipient_account, recipient_bank, recipient_name, " + "institution_id, action_taken, risk_score, shield_signals) VALUES " + "('txn_bridgeunknown', ?, 1000, '1234567890', 'Some Other Bank', 'Someone', ?, 'PASS', 0.1, '[]')", + (uid, BANK)) + row = forge_bridge.mirror("txn_bridgeunknown") + assert row["state"] == "failed" and "not one of the sandbox's banks" in row["last_error"] + assert bank.sends() == [] + + +def test_another_institution_is_never_sent_to_the_bank(world, bank, monkeypatch): + from services import forge_bridge + + monkeypatch.setenv("FORGE_BRIDGE_INSTITUTION", "someotherbank") + assert forge_bridge.mirror("txn_bridgeflag01") is None + assert bank.sends() == [] From 5cc1c27fc3e002694ea8df1332d931882d7c47c0 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:18 +0000 Subject: [PATCH 5/9] feat(web): the sandbox app uses the Xtradot sandbox's banks and its name enquiry when connected --- src/app/api/banks/route.ts | 3 ++ src/app/api/resolve-account/route.ts | 45 +++++++++++++++++++- src/app/demo/[institution]/transfer/page.tsx | 4 +- src/lib/forge/banks.ts | 24 +++++++++++ 4 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 src/lib/forge/banks.ts diff --git a/src/app/api/banks/route.ts b/src/app/api/banks/route.ts index 4cd479a..b751770 100644 --- a/src/app/api/banks/route.ts +++ b/src/app/api/banks/route.ts @@ -1,9 +1,12 @@ import { NextResponse } from "next/server"; +import { bridgeEnabled, SANDBOX_BANKS } from "@/lib/forge/banks"; import { getBankList } from "@/lib/paystack"; /** GET /api/banks — the real Paystack Nigerian bank list (cached server-side), * or the built-in fallback list (real NUBAN codes) when no key is set. */ export async function GET() { + // Connected to the Xtradot Bank sandbox: only its banks, with its NIP codes. + if (bridgeEnabled()) return NextResponse.json({ banks: SANDBOX_BANKS, source: "xtradot" }); const { banks, source } = await getBankList(); return NextResponse.json({ banks, source }); } diff --git a/src/app/api/resolve-account/route.ts b/src/app/api/resolve-account/route.ts index b86d851..6d7a3de 100644 --- a/src/app/api/resolve-account/route.ts +++ b/src/app/api/resolve-account/route.ts @@ -1,6 +1,8 @@ import { NextResponse } from "next/server"; import { findBank, paystackKey, PaystackError, resolveAccount, type PaystackFailure } from "@/lib/paystack"; import { guardLookup } from "@/lib/routeGuard"; +import { API_BASE } from "@/lib/fable/base"; +import { bridgeEnabled, SANDBOX_BANKS, XTRADOT_CODE } from "@/lib/forge/banks"; // With PAYSTACK_SECRET_KEY set (.env.local), this resolves real account // holders via the Paystack NUBAN lookup (free on test keys). Without a key it @@ -42,7 +44,13 @@ export async function POST(request: Request) { const refused = await guardLookup(request); if (refused) return NextResponse.json({ error: refused.error }, { status: refused.status }); try { - const { accountNumber, bankCode } = await request.json(); + const { accountNumber, bankCode, userId } = await request.json(); + + // Connected to the Xtradot Bank sandbox: the bank's own name enquiry, made by + // the API inside the cluster, as the signed-in console member. + if (bridgeEnabled()) { + return await bankEnquiry(request, String(accountNumber ?? ""), String(bankCode ?? ""), String(userId ?? "")); + } if (!accountNumber || accountNumber.length !== 10) { return NextResponse.json( @@ -114,3 +122,38 @@ export async function POST(request: Request) { ); } } + +async function bankEnquiry(request: Request, accountNumber: string, bankCode: string, userId: string) { + const bank = SANDBOX_BANKS.find((b) => b.code === bankCode || b.name === bankCode); + if (!/^\d{10}$/.test(accountNumber) || !bank || !userId) { + return NextResponse.json({ error: "Enter a 10-digit account number and choose its bank." }, { status: 400 }); + } + const intra = bank.code === XTRADOT_CODE; + try { + const res = await fetch(`${API_BASE}/v1/forge/enquiry`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Fable-Session": request.headers.get("x-fable-session") ?? "", + }, + body: JSON.stringify({ user_id: userId, account_number: accountNumber, bank_code: intra ? null : bank.code, intra }), + cache: "no-store", + signal: AbortSignal.timeout(20_000), + }); + const data = (await res.json().catch(() => ({}))) as { account_name?: string; detail?: { message?: string } }; + if (!res.ok || !data.account_name) { + const message = data.detail?.message ?? "The bank could not confirm this account. Check the number and bank."; + return NextResponse.json({ error: message }, { status: res.status === 200 ? 404 : res.status }); + } + return NextResponse.json({ + accountNumber, + accountName: data.account_name, + bankCode: bank.code, + bankName: bank.name, + source: "xtradot", + status: "success", + }); + } catch { + return NextResponse.json({ error: "The bank did not answer. Try again in a moment." }, { status: 504 }); + } +} diff --git a/src/app/demo/[institution]/transfer/page.tsx b/src/app/demo/[institution]/transfer/page.tsx index b895c88..fb441cc 100644 --- a/src/app/demo/[institution]/transfer/page.tsx +++ b/src/app/demo/[institution]/transfer/page.tsx @@ -222,7 +222,7 @@ export default function TransferPage() { // The lookup needs the signed-in session (src/lib/routeGuard.ts). method: "POST", headers: { "Content-Type": "application/json", ...authHeaders() }, - body: JSON.stringify({ accountNumber: acct, bankCode }), + body: JSON.stringify({ accountNumber: acct, bankCode, userId: customer?.user_id }), }); const data = await res.json(); if (!res.ok) { @@ -431,7 +431,7 @@ export default function TransferPage() { {contact.name} · {contact.bank} {mode === "new" && - (resolveSource === "paystack" ? ( + (resolveSource === "paystack" || resolveSource === "xtradot" ? ( Verified diff --git a/src/lib/forge/banks.ts b/src/lib/forge/banks.ts new file mode 100644 index 0000000..43e99b9 --- /dev/null +++ b/src/lib/forge/banks.ts @@ -0,0 +1,24 @@ +import type { Bank } from "@/lib/paystack"; + +// The banks the Xtradot Bank sandbox knows (platform guide, section 5.4), with +// the NIP codes its transfers use. The names match the API's bridge +// (api/services/forge_bridge.py), which maps a saved recipient's bank by name. +export const SANDBOX_BANKS: Bank[] = [ + { name: "Xtradot Bank", code: "000014", slug: "xtradot-bank" }, + { name: "GTBank", code: "000013", slug: "gtbank" }, + { name: "Zenith Bank", code: "000015", slug: "zenith-bank" }, + { name: "First Bank of Nigeria", code: "000016", slug: "first-bank-of-nigeria" }, + { name: "UBA", code: "000004", slug: "uba" }, + { name: "Wema Bank", code: "000017", slug: "wema-bank" }, + { name: "OPay", code: "100004", slug: "opay" }, + { name: "Moniepoint MFB", code: "090405", slug: "moniepoint-mfb" }, + { name: "Kuda MFB", code: "090267", slug: "kuda-mfb" }, + { name: "PalmPay", code: "100033", slug: "palmpay" }, +]; + +export const XTRADOT_CODE = "000014"; + +/** The site is connected to the Xtradot Bank sandbox (server-side setting). */ +export function bridgeEnabled(): boolean { + return process.env.FORGE_BRIDGE === "1"; +} From 02caff3db5439880f81d1ca88336e9f76996bcb3 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:18 +0000 Subject: [PATCH 6/9] feat(web): the receipt and transfer page show the bank's answer, with charges to the kobo --- src/app/demo/[institution]/result/page.tsx | 11 +- src/app/demo/[institution]/tx/[id]/page.tsx | 2 + src/components/demo/BankSettlement.tsx | 123 ++++++++++++++++++++ 3 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 src/components/demo/BankSettlement.tsx diff --git a/src/app/demo/[institution]/result/page.tsx b/src/app/demo/[institution]/result/page.tsx index 6e232aa..04b4213 100644 --- a/src/app/demo/[institution]/result/page.tsx +++ b/src/app/demo/[institution]/result/page.tsx @@ -6,6 +6,7 @@ import { Ghost, ShareNetwork, ShieldWarning } from "@phosphor-icons/react"; import { toast } from "sonner"; import { PageHeader } from "@/components/demo/PageHeader"; import { Button, Card, CardHeader, DetailRow, Eyebrow, Notice, Screen, SuccessTick } from "@/components/app-kit"; +import { BankSettlement } from "@/components/demo/BankSettlement"; import { PageSpinner } from "@/components/demo/Spinner"; import { RiskScoreCounter } from "@/components/demo/RiskScoreCounter"; import { SignalCard } from "@/components/demo/SignalCard"; @@ -86,7 +87,8 @@ export default function ResultPage() { if (pending.action === "PASS") { return ( + score={pending.riskScore} baselineSource={pending.baselineSource ?? null} + transactionId={pending.transactionId} /> ); } return ; @@ -98,15 +100,17 @@ function PassResult({ bank, score, baselineSource, + transactionId, }: { amount: number; recipient: string; bank: string; score: number; baselineSource: ScoreResult["baselineSource"]; + transactionId?: string; }) { const router = useRouter(); - const { href, name } = useInstitution(); + const { href, name, customer } = useInstitution(); // The moment this transfer cleared, fixed for the life of the screen. const [sentAt] = useState(() => Date.now()); @@ -157,6 +161,9 @@ function PassResult({ + +
diff --git a/src/components/demo/BankSettlement.tsx b/src/components/demo/BankSettlement.tsx new file mode 100644 index 0000000..cff56c6 --- /dev/null +++ b/src/components/demo/BankSettlement.tsx @@ -0,0 +1,123 @@ +"use client"; + +import useSWR from "swr"; +import { Bank } from "@phosphor-icons/react"; +import { Badge, Card, DetailRow, Eyebrow, Notice } from "@/components/app-kit"; +import { API_BASE } from "@/lib/fable/base"; +import { authHeaders } from "@/lib/fable/tenant"; + +/** + * What the bank did with a transfer Fable let through. + * + * Only a bank connected to the Xtradot Bank sandbox has this: for it, every + * transfer money moves on is also sent to the bank, and this shows the bank's + * own answer (reference, charges, status). For any other bank the API has no + * such transfer and this renders nothing. + */ + +type Step = { state: string; note: string | null }; +type BankTransfer = { + reference: string; + state: string; + fee: number | null; + vat: number | null; + stamp_duty: number | null; + total_debit: number | null; + last_error: string | null; + trail?: Step[]; +}; + +const FINAL = ["successful", "failed", "reversed", "cancelled"]; + +/** Bank charges are in kobo (VAT on a ₦25 fee is ₦1.88), so always two decimals. */ +const kobo = (n: number) => `₦${n.toLocaleString("en-NG", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + +const LABEL: Record = { + decided: "Cleared by Fable", + sending: "Sending to the bank", + unknown: "No answer yet, asking the bank", + pending: "Pending at the bank", + successful: "Paid", + failed: "Not paid", + reversed: "Reversed", + cancelled: "Cancelled", +}; + +const TONE: Record = { + successful: "success", + pending: "warning", + unknown: "warning", + sending: "warning", + decided: "warning", + failed: "danger", + reversed: "neutral", + cancelled: "neutral", +}; + +async function load(id: string, userId: string): Promise { + const res = await fetch( + `${API_BASE}/v1/forge/transfers/${encodeURIComponent(id)}?user_id=${encodeURIComponent(userId)}`, + { headers: authHeaders(), cache: "no-store" }, + ); + if (res.status === 404) return null; + if (!res.ok) throw new Error(`bank status ${res.status}`); + return (await res.json()) as BankTransfer; +} + +export function BankSettlement({ + transactionId, + userId, + asCard = false, + className = "", +}: { + transactionId: string; + userId: string | null | undefined; + /** Wrap it in its own card (the detail page), or sit inside another (the receipt). */ + asCard?: boolean; + className?: string; +}) { + const { data } = useSWR( + transactionId && userId ? ["bank-settlement", transactionId, userId] : null, + () => load(transactionId, userId!), + { + // The bank settles a transfer to another bank in about five seconds, and a + // lost answer takes longer: keep asking until the outcome is final. + refreshInterval: (latest) => (latest && FINAL.includes(latest.state) ? 0 : 3_000), + shouldRetryOnError: true, + }, + ); + if (!data) return null; + + const trail = (data.trail ?? []).filter((s) => s.state !== "decided"); + const body = ( +
+
+
+ + Xtradot Bank +
+ {LABEL[data.state] ?? data.state} +
+ {data.fee != null && ( + <> + {kobo(data.fee)} + {kobo(data.vat ?? 0)} + {data.stamp_duty ? {kobo(data.stamp_duty)} : null} + {data.total_debit != null && {kobo(data.total_debit)}} + + )} + + {data.reference} + + {trail.length > 1 && ( +

+ {trail.map((s) => (s.state === "unknown" ? "No answer, so Fable asked the bank (it never resends)" : LABEL[s.state] ?? s.state)).join(" → ")} +

+ )} + {data.last_error && data.state === "failed" && ( + {data.last_error} + )} +
+ ); + return asCard ? {body} : body; +} From 2324b35a2858786b1d6a57610eda67b6a3e0b618 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 07:12:18 +0000 Subject: [PATCH 7/9] docs(deploy): the console login secret, and a demo script in the sandbox app --- deploy/forge/app.yaml | 13 +++++++++++++ docs/DEPLOY-FORGE.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/deploy/forge/app.yaml b/deploy/forge/app.yaml index a740230..d2ed5c4 100644 --- a/deploy/forge/app.yaml +++ b/deploy/forge/app.yaml @@ -56,6 +56,17 @@ spec: - name: FORGE_DEMO_API_KEY valueFrom: secretKeyRef: { name: forge-demo, key: api-key, optional: true } + # The bank connected to the Xtradot sandbox: the sandbox app's + # transfers for this institution also go to the bank. Its console + # login comes from the `forge-console` secret; with it set, the API + # sets the bank up (customers and history imported) at every start. + - { name: FORGE_BRIDGE_INSTITUTION, value: xtradot } + - name: FORGE_CONSOLE_EMAIL + valueFrom: + secretKeyRef: { name: forge-console, key: email, optional: true } + - name: FORGE_CONSOLE_PASSWORD + valueFrom: + secretKeyRef: { name: forge-console, key: password, optional: true } envFrom: - secretRef: { name: huawei-gateway, optional: true } - secretRef: { name: fable-env, optional: true } @@ -121,6 +132,8 @@ spec: - name: FORGE_DEMO_API_KEY valueFrom: secretKeyRef: { name: forge-demo, key: api-key, optional: true } + # The sandbox app uses the Xtradot sandbox's banks and its name enquiry. + - { name: FORGE_BRIDGE, value: "1" } readinessProbe: httpGet: { path: /healthz, port: 8080 } periodSeconds: 5 diff --git a/docs/DEPLOY-FORGE.md b/docs/DEPLOY-FORGE.md index 463b65b..c57177f 100644 --- a/docs/DEPLOY-FORGE.md +++ b/docs/DEPLOY-FORGE.md @@ -121,6 +121,44 @@ kubectl patch secret fable-env -p "{\"stringData\":{\"FORGE_WEBHOOK_SECRET\":\"< kubectl rollout restart deployment/api ``` +## The demo: Xtradot Bank in the sandbox app + +The demo runs in the product's own sandbox app and console, connected to the +organizers' Xtradot Bank sandbox. At every start the API sets up the bank as a +bank would be onboarded: the institution "Xtradot Bank" (`xtradot`) in sandbox +mode, a console owner, and the bank's five customers with 60 days of their past +transfers, brought in through the console's own import. Every transfer money +moves on (a pass, a flag verified with the PIN, a released hold) is also sent to +the Xtradot sandbox from the customer's own account there, and the receipt and +transfer page show the bank's answer: status, fee, VAT, stamp duty, total debit +and reference. + +Create the console login once, then restart both: + +```bash +kubectl create secret generic forge-console --from-literal=email=team11@fable.ng --from-literal=password='' +kubectl rollout restart deployment/api +kubectl rollout restart deployment/app +kubectl logs deploy/api | grep -i "xtradot sandbox is ready" +``` + +Then open `/dashboard/login`, sign in with that email and password, and open +the sandbox (`/demo/xtradot`). The customers' PIN is `1234`. + +A demo that shows each path, in this order: + +| Who | What | What happens | +| --- | --- | --- | +| Adaeze | ₦5,000 to Ngozi (saved) | Passes on her habits; the receipt shows the bank's answer, Paid | +| Adaeze | New account 0123987001, GTBank | The bank's name enquiry confirms Chukwuemeka Ifeanyi Nwosu, Verified | +| Adaeze | ₦30,000 to 0123987004, UBA (new) | Flagged with reasons; she verifies with the PIN; the bank pays it | +| Babatunde | ₦1,500,000 to 0123987003, First Bank (new) | Paused and held by Ghost; nothing is sent; cancel is free | +| Babatunde | ₦700,000 to a usual payee | Passes: large, but normal for a trader | +| anyone | an amount ending in .02, interbank | The bank's answer is lost; Fable asks, never resends; the trail shows it | + +Do not restart the API during a demo: the database is temporary, so the +history of the session would start again. + ## The demo page `/forge` is the live demo: five scenarios against the bank sandbox. It needs a From 316eb91e7a37d378a5f4fd485013cff475a5a4ec Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 08:04:23 +0000 Subject: [PATCH 8/9] chore(web): remove the separate /forge page; the demo runs in the sandbox app --- src/app/api/forge-demo/route.ts | 115 ------------ src/app/forge/ForgeDemo.tsx | 323 -------------------------------- src/app/forge/forge.module.css | 50 ----- src/app/forge/page.tsx | 12 -- src/lib/forge/demo-data.ts | 84 --------- 5 files changed, 584 deletions(-) delete mode 100644 src/app/api/forge-demo/route.ts delete mode 100644 src/app/forge/ForgeDemo.tsx delete mode 100644 src/app/forge/forge.module.css delete mode 100644 src/app/forge/page.tsx delete mode 100644 src/lib/forge/demo-data.ts diff --git a/src/app/api/forge-demo/route.ts b/src/app/api/forge-demo/route.ts deleted file mode 100644 index 8ef0421..0000000 --- a/src/app/api/forge-demo/route.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { NextResponse } from "next/server"; -import { DEMO_CUSTOMERS, DEMO_PAYEES, MAX_AMOUNT } from "@/lib/forge/demo-data"; - -// What the demo page may ask of Fable, and nothing else. -// -// The page is public (anything at the team's address is reachable by anyone -// with the link), and the API wants the institution's key, which must never -// reach a browser. So the key lives here, on the server, and this route -// forwards only a short list of actions, only for the demo's own customers, -// accounts and payees, and slowly: the bank allows 60 requests a minute for -// the whole team. - -const API = (process.env.FABLE_INTERNAL_API_URL || process.env.NEXT_PUBLIC_FABLE_API_URL || "http://localhost:8000").replace(/\/+$/, ""); -const KEY = process.env.FORGE_DEMO_API_KEY || ""; -const TXN = /^txn_[a-f0-9]{12}$/; - -const hits = new Map(); -function allowed(ip: string): boolean { - const now = Date.now(); - const recent = (hits.get(ip) ?? []).filter((t) => now - t < 60_000); - if (recent.length >= 40) return false; - recent.push(now); - hits.set(ip, recent); - if (hits.size > 500) hits.clear(); - return true; -} - -function bad(message: string, status = 400) { - return NextResponse.json({ error: "refused", message }, { status }); -} - -type Body = Record; -const str = (v: unknown) => (typeof v === "string" ? v : ""); - -function customerOf(ref: string) { - return DEMO_CUSTOMERS.find((c) => c.ref === ref); -} -function payeeOf(account: string) { - return DEMO_PAYEES.find((p) => p.account === account); -} - -async function forward(method: "GET" | "POST", path: string, body?: Body) { - try { - const res = await fetch(`${API}${path}`, { - method, - headers: { "X-API-Key": KEY, "Content-Type": "application/json" }, - body: body ? JSON.stringify(body) : undefined, - cache: "no-store", - signal: AbortSignal.timeout(60_000), - }); - const text = await res.text(); - return new NextResponse(text, { status: res.status, headers: { "Content-Type": "application/json" } }); - } catch { - return NextResponse.json({ error: "unreachable", message: "Fable could not be reached." }, { status: 502 }); - } -} - -export async function POST(request: Request) { - if (!KEY) return bad("The demo is not configured yet.", 503); - const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown"; - if (!allowed(ip)) return bad("Too many requests. Wait a moment.", 429); - - const raw = await request.text(); - if (raw.length > 4000) return bad("Request too large.", 413); - let body: Body; - try { - body = JSON.parse(raw) as Body; - } catch { - return bad("Body is not JSON."); - } - - const user = customerOf(str(body.user_id)); - if (!user) return bad("Unknown demo customer."); - const action = str(body.action); - - if (action === "enquiry") { - const payee = payeeOf(str(body.account_number)); - if (!payee) return bad("Unknown demo payee."); - return forward("POST", "/v1/forge/enquiry", { - user_id: user.ref, account_number: payee.account, bank_code: payee.bankCode, intra: payee.intra, - }); - } - - if (action === "transfer") { - const payee = payeeOf(str(body.destination_account)); - const amount = Number(body.amount); - if (!payee) return bad("Unknown demo payee."); - if (str(body.source_account) !== user.account) return bad("That account does not belong to this customer."); - if (!(amount > 0 && amount <= MAX_AMOUNT)) return bad("Amount is outside the demo's range."); - return forward("POST", "/v1/forge/transfer", { - user_id: user.ref, - source_account: user.account, - destination_account: payee.account, - destination_bank_code: payee.bankCode, - intra: payee.intra, - name_enquiry_ref: str(body.name_enquiry_ref), - recipient_name: payee.name, - amount: Math.round(amount * 100) / 100, - narration: "Fable demo", - client_reference: str(body.client_reference).slice(0, 80), - }); - } - - const id = str(body.id); - if (!TXN.test(id)) return bad("Unknown transfer."); - if (action === "status") return forward("GET", `/v1/forge/transfers/${id}?user_id=${encodeURIComponent(user.ref)}`); - if (action === "cancel") return forward("POST", `/v1/forge/transfers/${id}/cancel`, { user_id: user.ref }); - if (action === "pin") { - return forward("POST", "/v1/stepup/pin/verify", { user_id: user.ref, pin: str(body.pin).slice(0, 12), purpose: "transfer", reference: id }); - } - if (action === "confirm") { - return forward("POST", `/v1/forge/transfers/${id}/confirm`, { user_id: user.ref, stepup_token: str(body.stepup_token) }); - } - return bad("Unknown action."); -} diff --git a/src/app/forge/ForgeDemo.tsx b/src/app/forge/ForgeDemo.tsx deleted file mode 100644 index dd8f038..0000000 --- a/src/app/forge/ForgeDemo.tsx +++ /dev/null @@ -1,323 +0,0 @@ -"use client"; - -import { useRef, useState } from "react"; -import { DEMO_CUSTOMERS, DEMO_PAYEES, DEMO_PIN, SCENARIOS, type Scenario } from "@/lib/forge/demo-data"; -import styles from "./forge.module.css"; - -type Decision = { - risk_score: number; - risk_level: string; - action: "PASS" | "FLAG" | "BLOCK"; - signals: string[]; - explanation: string; - decision_ms: number; -}; -type Transfer = { - id: string; - reference: string; - state: string; - amount: number; - fee: number | null; - vat: number | null; - stamp_duty: number | null; - total_debit: number | null; - last_error: string | null; - trail?: { state: string; note: string | null }[]; -}; -type Hold = { ghost_id: string; cooling_window_minutes?: number }; -type Run = { - key: string; - n: number; - user: string; - payeeName?: string; - decision?: Decision; - transfer?: Transfer; - next?: string | null; - hold?: Hold | null; - note?: string; - error?: string; - working?: string; -}; - -const FINAL = ["successful", "failed", "reversed", "cancelled"]; -const STATE_LABEL: Record = { - successful: "Sent", - failed: "Failed", - reversed: "Reversed", - cancelled: "Cancelled", - pending: "Pending at the bank", - unknown: "Outcome unknown, asking the bank", - sending: "Sending", - held: "Held, nothing sent", - awaiting_stepup: "Waiting for the customer to verify", -}; - -const TRAIL_LABEL: Record = { - decided: "Cleared by Fable", - awaiting_stepup: "Waiting for the customer to verify", - held: "Held by Ghost", - unknown: "No answer from the bank", - pending: "Pending at the bank", - successful: "Successful", - failed: "Failed", - reversed: "Reversed", - cancelled: "Cancelled", -}; - -const money = (n: number | null | undefined) => - n == null ? "n/a" : `₦${n.toLocaleString("en-NG", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -// Called only from button handlers, never while rendering. -const newKey = (n: number) => `${Date.now()}-${n}`; -const newReference = (n: number) => `demo-${Date.now()}-${n}-${Math.random().toString(36).slice(2, 8)}`; - -async function call(action: string, body: Record) { - const res = await fetch("/api/forge-demo", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ action, ...body }), - }); - const json = (await res.json().catch(() => ({}))) as Record; - return { ok: res.ok, json }; -} - -function failure(json: Record): string { - const d = json.detail as { message?: string } | string | undefined; - return (typeof d === "object" ? d?.message : d) || (json.message as string) || "Something went wrong."; -} - -export default function ForgeDemo() { - const [active, setActive] = useState(SCENARIOS[0]); - const [runs, setRuns] = useState([]); - const [busy, setBusy] = useState(false); - const [pins, setPins] = useState>({}); - const stop = useRef(false); - - const patch = (key: string, change: Partial) => - setRuns((prev) => prev.map((r) => (r.key === key ? { ...r, ...change } : r))); - - async function settle(run: Run, id: string) { - for (let i = 0; i < 40 && !stop.current; i++) { - const { ok, json } = await call("status", { user_id: run.user, id }); - if (ok) { - const t = json as unknown as Transfer; - patch(run.key, { transfer: t, working: FINAL.includes(t.state) ? undefined : STATE_LABEL[t.state] ?? t.state }); - if (FINAL.includes(t.state)) return; - } - await sleep(3000); - } - patch(run.key, { working: undefined }); - } - - async function one(s: Scenario, n: number) { - const customer = DEMO_CUSTOMERS.find((c) => c.ref === s.customer)!; - const payee = DEMO_PAYEES.find((p) => p.account === s.payee)!; - const run: Run = { key: newKey(n), n, user: customer.ref, working: "Checking who owns the account" }; - setRuns((prev) => [...prev, run]); - - const enq = await call("enquiry", { user_id: customer.ref, account_number: payee.account }); - if (!enq.ok) return patch(run.key, { working: undefined, error: failure(enq.json) }); - const nameRef = enq.json.name_enquiry_ref as string; - patch(run.key, { payeeName: enq.json.account_name as string, working: "Fable is scoring the transfer" }); - - const res = await call("transfer", { - user_id: customer.ref, - source_account: customer.account, - destination_account: payee.account, - amount: s.amount, - name_enquiry_ref: nameRef, - client_reference: newReference(n), - }); - if (!res.ok) return patch(run.key, { working: undefined, error: failure(res.json) }); - const j = res.json as unknown as { decision: Decision; transfer: Transfer; next: string | null; hold: Hold | null }; - patch(run.key, { decision: j.decision, transfer: j.transfer, next: j.next, hold: j.hold, working: undefined }); - if (!FINAL.includes(j.transfer.state) && j.transfer.state !== "held" && j.transfer.state !== "awaiting_stepup") { - patch(run.key, { working: "Waiting for the bank. Fable is asking, not resending." }); - await settle(run, j.transfer.id); - } - } - - async function start(s: Scenario) { - stop.current = false; - setBusy(true); - setRuns([]); - for (let i = 1; i <= (s.repeat ?? 1) && !stop.current; i++) await one(s, i); - setBusy(false); - } - - async function verify(run: Run) { - if (!run.transfer) return; - patch(run.key, { error: undefined, working: "Verifying the PIN" }); - const pin = await call("pin", { user_id: run.user, id: run.transfer.id, pin: pins[run.key] ?? "" }); - if (!pin.ok) return patch(run.key, { working: undefined, error: failure(pin.json) }); - patch(run.key, { working: "Sending to the bank" }); - const done = await call("confirm", { user_id: run.user, id: run.transfer.id, stepup_token: pin.json.token }); - if (!done.ok) return patch(run.key, { working: undefined, error: failure(done.json) }); - patch(run.key, { transfer: done.json as unknown as Transfer, next: null, working: undefined }); - await settle(run, run.transfer.id); - } - - async function cancel(run: Run) { - if (!run.transfer) return; - const res = await call("cancel", { user_id: run.user, id: run.transfer.id }); - if (!res.ok) return patch(run.key, { error: failure(res.json) }); - patch(run.key, { transfer: res.json as unknown as Transfer, next: null, note: "Cancelled by the customer. Nothing was ever sent." }); - } - - return ( -
-
-
-

Fable on the Xtradot Bank sandbox

-

Every transfer is judged before the money moves

-

- Real calls to the bank's sandbox, made from inside the cluster. Pick a scenario and watch one transfer from name enquiry to the bank's answer. -

-
-
- -
- - -
-
-
-

{active.title}

-

- {DEMO_CUSTOMERS.find((c) => c.ref === active.customer)?.name} sends {money(active.amount)} - {active.repeat ? ` × ${active.repeat}` : ""} to {DEMO_PAYEES.find((p) => p.account === active.payee)?.bank}. -

-

Expect: {active.expect}

-
- -
- - {runs.map((run) => ( -
- {run.n > 0 && active.repeat ?

Transfer {run.n} of {active.repeat}

: null} - -
- -
-

Name enquiry

-

{run.payeeName ? `The bank says this account belongs to ${run.payeeName}.` : "Asking the bank…"}

-
-
- -
- -
-

Fable's decision

- {run.decision ? ( - <> -

- {run.decision.action}{" "} - score {run.decision.risk_score.toFixed(2)}, {run.decision.risk_level.toLowerCase()} risk, decided in {run.decision.decision_ms} ms -

-
- -
-
    - {run.decision.signals.map((sig) => ( -
  • {sig}
  • - ))} -
-

{run.decision.explanation}

- - ) : ( -

{run.working ?? "Waiting"}

- )} -
-
- - {run.decision && ( -
- -
-

The bank

- {run.transfer && ( - <> -

- - {STATE_LABEL[run.transfer.state] ?? run.transfer.state} - - {run.working ? {run.working} : null} -

- {run.transfer.fee != null && ( -
-
Fee
{money(run.transfer.fee)}
-
VAT
{money(run.transfer.vat)}
-
Stamp duty
{money(run.transfer.stamp_duty)}
-
Total debit
{money(run.transfer.total_debit)}
-
- )} - {(run.transfer.trail?.length ?? 0) > 1 && ( -
    - {run.transfer.trail!.map((step, i) => ( -
  1. - {TRAIL_LABEL[step.state] ?? step.state} - {step.state === "unknown" ? " (asked the bank, did not resend)" : ""} -
  2. - ))} -
- )} -

Reference {run.transfer.reference}

- {run.transfer.last_error &&

{run.transfer.last_error}

} - - )} - - {run.next === "step_up" && ( -
-

Fable needs the customer to confirm it is them. Demo PIN: {DEMO_PIN}

- setPins((p) => ({ ...p, [run.key]: e.target.value }))} - aria-label="PIN" - /> - - -
- )} - - {run.next === "ghost_hold" && ( -
-

- Ghost is holding this transfer{run.hold?.cooling_window_minutes ? ` for ${run.hold.cooling_window_minutes} minutes` : ""}. Nothing was sent. Cancelling is free; releasing it needs proof a hijacked session cannot produce. -

- -
- )} - {run.note &&

{run.note}

} -
-
- )} - - {run.error &&

{run.error}

} -
- ))} -
-
-
- ); -} diff --git a/src/app/forge/forge.module.css b/src/app/forge/forge.module.css deleted file mode 100644 index 1773e42..0000000 --- a/src/app/forge/forge.module.css +++ /dev/null @@ -1,50 +0,0 @@ -.page { min-height: 100vh; background: #0a0117; color: #f5f3f5; font-family: var(--font-inter), system-ui, sans-serif; font-size: 15px; line-height: 1.5; padding: 32px clamp(16px, 4vw, 56px) 64px; } -.page h1, .page h2, .page h3 { font-family: var(--font-titillium), var(--font-inter), system-ui, sans-serif; margin: 0; } -.head h1 { font-size: clamp(26px, 4vw, 40px); line-height: 1.1; max-width: 22ch; } -.eyebrow { color: #a78bfa; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; margin: 0 0 8px; } -.lede { color: #cfc8dc; max-width: 62ch; margin: 12px 0 28px; } -.layout { display: grid; grid-template-columns: minmax(260px, 340px) 1fr; gap: 24px; align-items: start; } -@media (max-width: 860px) { .layout { grid-template-columns: 1fr; } } -.scenarios { display: grid; gap: 10px; } -.scenario { display: flex; gap: 12px; text-align: left; background: #150a26; color: inherit; border: 1px solid #2a1b47; border-radius: 14px; padding: 14px; cursor: pointer; font: inherit; } -.scenario small { display: block; color: #b6aecb; margin-top: 4px; font-size: 13px; } -.scenario:disabled { opacity: .6; cursor: default; } -.scenario.on { border-color: #7c3aed; background: #1d0f38; } -.num { flex: none; width: 26px; height: 26px; border-radius: 50%; background: #7c3aed; display: grid; place-items: center; font-weight: 700; font-size: 13px; } -.stage { display: grid; gap: 16px; } -.brief { display: flex; gap: 16px; justify-content: space-between; align-items: flex-start; background: #150a26; border: 1px solid #2a1b47; border-radius: 14px; padding: 18px; flex-wrap: wrap; } -.brief h2 { font-size: 22px; } -.brief p { margin: 6px 0 0; color: #d8d2e6; } -.expect { color: #00f5a0 !important; } -.run, .action button { background: #7c3aed; color: #fff; border: 0; border-radius: 10px; padding: 10px 18px; font: inherit; font-weight: 600; cursor: pointer; } -.run:disabled, .action button:disabled { opacity: .6; cursor: default; } -.card { background: #150a26; border: 1px solid #2a1b47; border-radius: 14px; padding: 18px; display: grid; gap: 14px; } -.count { margin: 0; color: #a78bfa; font-size: 13px; } -.step { display: grid; grid-template-columns: 14px 1fr; gap: 12px; } -.step h3 { font-size: 16px; margin-bottom: 4px; } -.step p { margin: 4px 0; } -.dot { width: 12px; height: 12px; border-radius: 50%; margin-top: 6px; background: #3b2a5e; } -.dot[data-done="true"] { background: #00f5a0; } -.badge { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 700; letter-spacing: .04em; background: #3b2a5e; } -.PASS, .successful { background: #003d2a; color: #00f5a0; } -.FLAG, .pending, .unknown, .sending, .awaiting_stepup { background: #3d2a00; color: #ffb547; } -.BLOCK, .failed, .held { background: #3d0a16; color: #ff6b85; } -.reversed, .cancelled { background: #2a2a3d; color: #c9c6e0; } -.meter { height: 8px; background: #2a1b47; border-radius: 99px; overflow: hidden; margin: 8px 0; } -.meter i { display: block; height: 100%; background: #00f5a0; } -.meter i[data-level="FLAG"] { background: #ffb547; } -.meter i[data-level="BLOCK"] { background: #ff3b5c; } -.signals { margin: 6px 0; padding-left: 18px; color: #cfc8dc; font-size: 13px; } -.explain { color: #d8d2e6; font-style: italic; } -.wait { color: #ffb547; } -.charges { display: grid; grid-template-columns: max-content 1fr; gap: 2px 16px; margin: 8px 0; font-variant-numeric: tabular-nums; } -.charges dt { color: #b6aecb; } -.charges dd { margin: 0; } -.ref { color: #8d84a6; font-size: 12px; word-break: break-all; } -.err { color: #ff6b85; } -.action { margin-top: 10px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } -.action p { flex-basis: 100%; margin: 0; } -.action input { background: #0a0117; color: inherit; border: 1px solid #3b2a5e; border-radius: 10px; padding: 9px 12px; font: inherit; width: 110px; } -.action .ghost { background: transparent; border: 1px solid #3b2a5e; color: #d8d2e6; } -.trail { display: flex; flex-wrap: wrap; gap: 6px 4px; list-style: none; padding: 0; margin: 8px 0; font-size: 13px; color: #cfc8dc; } -.trail li + li::before { content: "\2192"; margin: 0 6px 0 2px; color: #8d84a6; } diff --git a/src/app/forge/page.tsx b/src/app/forge/page.tsx deleted file mode 100644 index 2ce81f5..0000000 --- a/src/app/forge/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import type { Metadata } from "next"; -import ForgeDemo from "./ForgeDemo"; - -export const metadata: Metadata = { - title: "Fable on Xtradot Bank", - description: "Fable scoring real transfers against the Xtradot Bank sandbox: pass, check, hold, and a lost answer that is never resent.", - robots: { index: false, follow: false }, -}; - -export default function ForgePage() { - return ; -} diff --git a/src/lib/forge/demo-data.ts b/src/lib/forge/demo-data.ts deleted file mode 100644 index 861b497..0000000 --- a/src/lib/forge/demo-data.ts +++ /dev/null @@ -1,84 +0,0 @@ -// The Forge demo's cast: the Xtradot Bank sandbox's own synthetic people and -// accounts (platform guide, section 5.4), and the five scripted scenarios. -// Shared by the page and by the server route that guards what the page may do. - -export type DemoCustomer = { ref: string; name: string; account: string; note: string }; -export type DemoPayee = { account: string; name: string; bank: string; bankCode: string | null; intra: boolean }; - -export const DEMO_CUSTOMERS: DemoCustomer[] = [ - { ref: "demo_adaeze", name: "Adaeze Chiamaka Okonkwo", account: "0123456789", note: "Savings, tier 3" }, - { ref: "demo_babatunde", name: "Babatunde Olumide Adeyemi", account: "0123456790", note: "Current, tier 3" }, - { ref: "demo_musa", name: "Musa Ibrahim Abdullahi", account: "0123456791", note: "Savings, tier 2" }, - { ref: "demo_efosa", name: "Efosa Godwin Osagie", account: "0123456792", note: "Savings, tier 1" }, - { ref: "demo_mama", name: "Mama Nkechi Provisions Ltd", account: "0123456793", note: "Corporate" }, -]; - -export const DEMO_PAYEES: DemoPayee[] = [ - { account: "0123987001", name: "Chukwuemeka Ifeanyi Nwosu", bank: "GTBank", bankCode: "000013", intra: false }, - { account: "0987654321", name: "Ngozi Adaobi Eze", bank: "Xtradot Bank", bankCode: null, intra: true }, - { account: "0123987002", name: "Funmilayo Abiola Ogunleye", bank: "Zenith Bank", bankCode: "000015", intra: false }, - { account: "0123987004", name: "Tamunotonye Briggs", bank: "UBA", bankCode: "000004", intra: false }, -]; - -export type Scenario = { - id: string; - title: string; - story: string; - expect: string; - customer: string; - payee: string; - amount: number; - repeat?: number; -}; - -export const SCENARIOS: Scenario[] = [ - { - id: "normal", - title: "A normal transfer", - story: "Adaeze sends a small amount to GTBank. Nothing about it is unusual.", - expect: "Passes with no extra step. The bank's fee and VAT come straight from its reply.", - customer: "demo_adaeze", - payee: "0123987001", - amount: 5000, - }, - { - id: "large", - title: "A large amount to a new payee", - story: "A corporate account sends ₦6,000,000 to someone it has never paid. The amount has no history to compare against.", - expect: "Held by Ghost with the reasons. Nothing is sent to the bank.", - customer: "demo_mama", - payee: "0123987001", - amount: 6_000_000, - }, - { - id: "stepup", - title: "A transfer that needs a check", - story: "Babatunde sends ₦200,000 to a new payee. It is not alarming, but it is not routine either.", - expect: "Flagged. The customer verifies with a PIN, then it is sent.", - customer: "demo_babatunde", - payee: "0123987001", - amount: 200_000, - }, - { - id: "burst", - title: "A rapid burst", - story: "Efosa sends six small transfers to the same person in a row.", - expect: "The first looks new; the next ones are known and cheap, but the velocity signal climbs with every one.", - customer: "demo_efosa", - payee: "0123987001", - amount: 2000, - repeat: 6, - }, - { - id: "timeout", - title: "The bank's answer is lost", - story: "Musa sends ₦5,000.02. The sandbox's trigger for this amount is a timeout, then a failure and reversal 30 seconds later.", - expect: "Fable never resends. It asks the bank for the status until the outcome is final, so there is one debit and one reversal.", - customer: "demo_musa", - payee: "0123987001", - amount: 5000.02, - }, -]; - -export const DEMO_PIN = "1234"; -export const MAX_AMOUNT = 10_000_000; From 07b778e91c42dfe017c62f9e3660b829c188a2b3 Mon Sep 17 00:00:00 2001 From: kenzycodex Date: Wed, 11 Nov 2026 08:04:23 +0000 Subject: [PATCH 9/9] docs(deploy): drop the /forge page's key; the console login sets the demo up --- deploy/forge/app.yaml | 12 ------------ docs/DEPLOY-FORGE.md | 42 +++++++----------------------------------- 2 files changed, 7 insertions(+), 47 deletions(-) diff --git a/deploy/forge/app.yaml b/deploy/forge/app.yaml index d2ed5c4..629da93 100644 --- a/deploy/forge/app.yaml +++ b/deploy/forge/app.yaml @@ -50,12 +50,6 @@ spec: - { name: FABLE_DB_PATH, value: /data/fable.db } - { name: FORGE_BANK_BASE_URL, value: "http://bank-api.ingress-apisix.svc.cluster.local/v1" } - { name: FORGE_MAAS_BASE_URL, value: "http://huawei-maas.ingress-apisix.svc.cluster.local/openai/v1" } - # The demo's key, from the same `forge-demo` secret the site uses. With - # it set, the API recreates the demo institution and customers every - # time it starts, so a pod restart wipes nothing that matters. - - name: FORGE_DEMO_API_KEY - valueFrom: - secretKeyRef: { name: forge-demo, key: api-key, optional: true } # The bank connected to the Xtradot sandbox: the sandbox app's # transfers for this institution also go to the bank. Its console # login comes from the `forge-console` secret; with it set, the API @@ -126,12 +120,6 @@ spec: ports: - containerPort: 8080 env: - # The demo page's key for the API, from the `forge-demo` secret - # created after the seed script runs (docs/DEPLOY-FORGE.md). The - # server uses it; the browser never sees it. - - name: FORGE_DEMO_API_KEY - valueFrom: - secretKeyRef: { name: forge-demo, key: api-key, optional: true } # The sandbox app uses the Xtradot sandbox's banks and its name enquiry. - { name: FORGE_BRIDGE, value: "1" } readinessProbe: diff --git a/docs/DEPLOY-FORGE.md b/docs/DEPLOY-FORGE.md index c57177f..df88961 100644 --- a/docs/DEPLOY-FORGE.md +++ b/docs/DEPLOY-FORGE.md @@ -159,33 +159,6 @@ A demo that shows each path, in this order: Do not restart the API during a demo: the database is temporary, so the history of the session would start again. -## The demo page - -`/forge` is the live demo: five scenarios against the bank sandbox. It needs a -key shared by the site and the API. Make it once, as a secret, then restart both: - -```bash -KEY="fbl_live_$(docker run --rm --entrypoint python ghcr.io/kenzycodex/fable-access-api: -c 'import secrets;print(secrets.token_hex(16))' | tr -d '\r')" -kubectl create secret generic forge-demo --from-literal=api-key="$KEY" -unset KEY -kubectl rollout restart deployment/api -kubectl rollout restart deployment/app -``` - -On startup the API sees the key and creates the demo institution, its five -customers (demo PIN `1234`) and registers the key. Check that it did: - -```bash -kubectl logs deploy/api | grep -i "forge demo" -``` - -The page is public (anything at the team's address is), so it holds no key in -the browser: the site's server forwards only the demo's own customers, accounts -and payees, and slowly, because the bank allows 60 requests a minute for the -whole team. To change the key, delete and recreate the secret and restart both. -`scripts/forge_seed.py` does the same set-up on demand, and `--new-key` issues a -random key instead. - ## The API's data is temporary, and the demo puts itself back The cluster's block storage could not be created (the provider answered @@ -193,15 +166,14 @@ The cluster's block storage could not be created (the provider answered the API keeps its database in the pod's temporary storage. Every new API pod, so every API update or restart, starts with an empty database. -That does not need any manual work for the demo. When the `forge-demo` secret -exists, the API reads its key and, at startup, recreates the live institution, -the five customers and their PINs. The site holds the same key, so it keeps -working. What is lost is history: transfers, baselines and any console accounts, -which is fine because the scenarios are designed to start from a fresh customer. +That does not need any manual work for the demo. When the `forge-console` +secret exists, the API sets Xtradot Bank up again at startup: the console +owner, the five customers, their PINs and their imported history. What is lost +is what happened since the last start: the session's transfers, cases and holds, +and any console members added by hand. -Do not restart the API during a demo anyway: scenarios would start again from -nothing. When storage works, go back to a 10Gi PersistentVolumeClaim (the -provider's smallest volume) mounted at `/data`. +Do not restart the API during a demo. When storage works, go back to a 10Gi +PersistentVolumeClaim (the provider's smallest volume) mounted at `/data`. ## Sandbox data can reset