broke: a private money app that runs on your own accounts and your own AI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
f550865e93
359 files changed
+34290
No files matched your search
@@ -0,0 +1,49 @@
|
||||
// node src/lib/providers/akahu.test.ts
|
||||
// Sample JSON follows the example responses in Akahu's docs (2026-10-22); ids and amounts are made up.
|
||||
import assert from "node:assert/strict";
|
||||
import { akahuAccounts, akahuTransactions, toAccount, toTxn, type Tokens } from "./akahu.ts";
|
||||
|
||||
const ACCOUNTS = { success: true, items: [
|
||||
{ _id: "acc_1", name: "Everyday", status: "ACTIVE", type: "CHECKING", formatted_account: "38-9000-0123456-00",
|
||||
connection: { _id: "conn_kb", name: "Kiwibank", logo: "https://example.test/kb.png" }, balance: { current: 1520.33, available: 1500, currency: "NZD" } },
|
||||
{ _id: "acc_2", name: "Visa", status: "ACTIVE", type: "CREDITCARD", formatted_account: "4835-****-****-1234",
|
||||
connection: { name: "ASB" }, balance: { current: -412.5, available: 3587.5, limit: 4000, currency: "NZD" } },
|
||||
] };
|
||||
const PAGE1 = { success: true, items: [
|
||||
{ _id: "trans_1", _account: "acc_1", date: "2026-10-01T00:00:00.000Z", description: "COUNTDOWN PONSONBY", amount: -84.2, type: "EFTPOS",
|
||||
merchant: { name: "Countdown" }, category: { name: "Supermarkets and grocery stores" }, meta: { logo: "https://example.test/cd.png" } },
|
||||
], cursor: { next: "abc" } };
|
||||
const PAGE2 = { success: true, items: [
|
||||
{ _id: "trans_2", _account: "acc_1", date: "2026-10-02T00:00:00.000Z", description: "ACME LTD SALARY", amount: 3150, type: "CREDIT" },
|
||||
], cursor: { next: null } };
|
||||
|
||||
const tok: Tokens = { app: "app_token_x", user: "user_token_y" };
|
||||
const calls: { url: string; headers: Record<string, string> }[] = [];
|
||||
const fake = (async (url: string, init: { headers: Record<string, string> }) => {
|
||||
calls.push({ url, headers: init.headers });
|
||||
const body = url.includes("/accounts") ? ACCOUNTS : url.includes("cursor=abc") ? PAGE2 : PAGE1;
|
||||
return new Response(JSON.stringify(body), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const accts = (await akahuAccounts(tok, fake)).map(toAccount);
|
||||
assert.deepEqual(calls[0].headers, { Authorization: "Bearer user_token_y", "X-Akahu-Id": "app_token_x" });
|
||||
assert.equal(accts[0].plaid_account_id, "akahu:acc_1");
|
||||
assert.equal(accts[0].type, "depository");
|
||||
assert.equal(accts[0].mask, "3456");
|
||||
assert.equal(accts[1].type, "credit");
|
||||
assert.equal(accts[1].mask, "1234");
|
||||
assert.equal(accts[1].current_balance, 412.5, "card debt is positive, like Plaid");
|
||||
assert.equal(accts[1].credit_limit, 4000);
|
||||
|
||||
const txns = (await akahuTransactions(tok, "2026-09-01T00:00:00.000Z", fake)).map(toTxn);
|
||||
assert.equal(calls.length, 3, "follows cursor.next until null");
|
||||
assert.match(calls[1].url, /start=2026-09-01/);
|
||||
assert.deepEqual(txns.map((t) => [t.plaid_transaction_id, t.date, t.amount, t.merchant_name]), [
|
||||
["akahu:trans_1", "2026-10-01", 84.2, "Countdown"],
|
||||
["akahu:trans_2", "2026-10-02", -3150, null],
|
||||
]);
|
||||
|
||||
const failing = (async () => new Response(JSON.stringify({ success: false, message: "Unauthorized" }), { status: 401 })) as unknown as typeof fetch;
|
||||
await assert.rejects(akahuAccounts(tok, failing), (e: Error & { code?: string }) => e.code === "AKAHU_401");
|
||||
|
||||
console.log("akahu ok");
|
||||
@@ -0,0 +1,86 @@
|
||||
// Akahu (New Zealand open banking), personal app: one App ID Token + one User Access Token, both from
|
||||
// my.akahu.nz → Developers, and they only reach the Akahu account that made them (one person; a full app for
|
||||
// many users needs Akahu's approval and OAuth). Docs read 2026-10-22:
|
||||
// https://developers.akahu.nz/docs/personal-apps (headers, single user)
|
||||
// https://developers.akahu.nz/docs/accessing-account-data, /docs/the-account-model (account fields, types, signs)
|
||||
// https://developers.akahu.nz/docs/accessing-transactional-data (start exclusive, cursor.next, 100 a page, 730 days)
|
||||
// https://developers.akahu.nz/docs/reference-rate-limits (429, back off)
|
||||
// Pure mapping plus fetch, no "@/" imports, so akahu.test.ts runs with plain node.
|
||||
|
||||
export const AKAHU_API = "https://api.akahu.io/v1";
|
||||
|
||||
export type AkahuAccount = {
|
||||
_id: string; name: string; status?: string; type: string; formatted_account?: string;
|
||||
connection?: { _id?: string; name?: string; logo?: string };
|
||||
balance?: { current?: number; available?: number; limit?: number; currency?: string };
|
||||
};
|
||||
export type AkahuTxn = {
|
||||
_id: string; _account: string; date: string; description: string; amount: number; type?: string;
|
||||
merchant?: { name?: string }; category?: { name?: string }; meta?: { logo?: string };
|
||||
};
|
||||
export type Tokens = { app: string; user: string };
|
||||
|
||||
// Akahu type -> our accounts.type / subtype. Rewards are points, not money: kept out of totals as "other".
|
||||
const TYPES: Record<string, [string, string]> = {
|
||||
CHECKING: ["depository", "checking"], SAVINGS: ["depository", "savings"], TERMDEPOSIT: ["depository", "term deposit"],
|
||||
FOREIGN: ["depository", "foreign currency"], WALLET: ["depository", "wallet"], TAX: ["depository", "tax"],
|
||||
CREDITCARD: ["credit", "credit card"], LOAN: ["loan", "loan"],
|
||||
KIWISAVER: ["investment", "kiwisaver"], INVESTMENT: ["investment", "brokerage"], REWARDS: ["other", "rewards"],
|
||||
};
|
||||
|
||||
export function toAccount(a: AkahuAccount) {
|
||||
const [type, subtype] = TYPES[a.type] ?? ["other", a.type.toLowerCase()];
|
||||
// Akahu: negative = owed on cards and loans. Ours (Plaid's): debt is a positive balance.
|
||||
const flip = type === "credit" || type === "loan" ? -1 : 1;
|
||||
const n = (v?: number) => (v == null ? null : v * flip);
|
||||
return {
|
||||
plaid_account_id: `akahu:${a._id}`,
|
||||
name: a.name,
|
||||
official_name: a.connection?.name ?? null,
|
||||
// NZ accounts read bank-branch-account-suffix (38-9000-0123456-00): the mask is the account part.
|
||||
mask: (a.formatted_account?.match(/^\d{2}-\d{4}-(\d+)-\d+$/)?.[1] ?? a.formatted_account?.replace(/\D/g, ""))?.slice(-4) || null,
|
||||
type, subtype,
|
||||
current_balance: n(a.balance?.current),
|
||||
available_balance: a.balance?.available ?? null,
|
||||
credit_limit: a.balance?.limit ?? null,
|
||||
currency: a.balance?.currency ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// Akahu amounts are negative for money out; ours are positive.
|
||||
export const toTxn = (t: AkahuTxn) => ({
|
||||
plaid_transaction_id: `akahu:${t._id}`,
|
||||
akahu_account: t._account,
|
||||
date: t.date.slice(0, 10),
|
||||
amount: -t.amount,
|
||||
name: t.description,
|
||||
merchant_name: t.merchant?.name ?? null,
|
||||
logo_url: t.meta?.logo ?? null,
|
||||
pending: false,
|
||||
plaid_category: t.category?.name ?? null,
|
||||
});
|
||||
|
||||
export async function akahuGet<T>(tok: Tokens, path: string, f: typeof fetch = fetch): Promise<T> {
|
||||
const res = await f(`${AKAHU_API}${path}`, { headers: { Authorization: `Bearer ${tok.user}`, "X-Akahu-Id": tok.app }, signal: AbortSignal.timeout(20000) });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok || body.success === false) {
|
||||
const message = res.status === 401 || res.status === 403 ? "Akahu didn't accept the keys. Check them on the Setup page."
|
||||
: res.status === 429 ? "Akahu is busy. Sync again in a minute." : "Akahu couldn't be reached. Sync again later.";
|
||||
throw Object.assign(new Error(message), { code: `AKAHU_${res.status}` });
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
|
||||
export const akahuAccounts = async (tok: Tokens, f?: typeof fetch) => (await akahuGet<{ items: AkahuAccount[] }>(tok, "/accounts", f)).items;
|
||||
|
||||
// Settled transactions after `start` (exclusive), every page.
|
||||
export async function akahuTransactions(tok: Tokens, start: string, f?: typeof fetch) {
|
||||
const out: AkahuTxn[] = [];
|
||||
for (let cursor: string | null = null, first = true; first || cursor; first = false) {
|
||||
const q = new URLSearchParams({ start, ...(cursor ? { cursor } : {}) });
|
||||
const page: { items: AkahuTxn[]; cursor?: { next: string | null } } = await akahuGet(tok, `/transactions?${q}`, f);
|
||||
out.push(...page.items);
|
||||
cursor = page.cursor?.next ?? null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Run: node src/lib/providers/feeds.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { createVerify, generateKeyPairSync } from "node:crypto";
|
||||
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, pemFrom, validCpf } from "./feeds.ts";
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
||||
|
||||
// A key pasted into a one-line box still signs, and the JWT has the documented shape.
|
||||
const env = { ENABLE_BANKING_APP_ID: "app-1", ENABLE_BANKING_PRIVATE_KEY: pem.replace(/\n/g, " ") };
|
||||
assert.equal(pemFrom(pem.replace(/\n/g, "\\n")), pem);
|
||||
const jwt = ebJwt(env, 1_000_000);
|
||||
const [h, c, sig] = jwt.split(".");
|
||||
assert.deepEqual(JSON.parse(Buffer.from(h, "base64url").toString()), { typ: "JWT", alg: "RS256", kid: "app-1" });
|
||||
const claims = JSON.parse(Buffer.from(c, "base64url").toString());
|
||||
assert.equal(claims.iss, "enablebanking.com");
|
||||
assert.equal(claims.aud, "api.enablebanking.com");
|
||||
assert.ok(claims.exp - claims.iat <= 86400);
|
||||
assert.ok(createVerify("RSA-SHA256").update(`${h}.${c}`).verify(publicKey, Buffer.from(sig, "base64url")));
|
||||
|
||||
// Enable Banking: direction from the indicator, settled only, card balance owed as positive.
|
||||
const out = ebTxn({ transaction_id: "t1", booking_date: "2026-10-02", transaction_amount: { amount: "45.10" }, credit_debit_indicator: "DBIT", status: "BOOK", remittance_information: ["TESCO", "LONDON"], creditor: { name: "Tesco" } }, "u1")!;
|
||||
assert.deepEqual([out.amount, out.name, out.merchant_name, out.account_ref, out.date], [45.1, "TESCO LONDON", "Tesco", "enablebanking:u1", "2026-10-02"]);
|
||||
assert.equal(ebTxn({ transaction_id: "t2", booking_date: "2026-10-03", transaction_amount: { amount: "2000" }, credit_debit_indicator: "CRDT", status: "BOOK", debtor: { name: "Acme" } }, "u1")!.amount, -2000);
|
||||
assert.equal(ebTxn({ transaction_id: "t3", booking_date: "2026-10-03", transaction_amount: { amount: "5" }, credit_debit_indicator: "DBIT", status: "PDNG" }, "u1"), null);
|
||||
assert.equal(ebTxn({ transaction_id: "t4", booking_date: "2026-10-03", transaction_amount: { amount: "5" }, status: "BOOK" }, "u1"), null); // no direction: never guessed
|
||||
// No id from the bank: stable across syncs.
|
||||
const noId = { booking_date: "2026-10-03", transaction_amount: { amount: "5" }, credit_debit_indicator: "DBIT", status: "BOOK", note: "x" };
|
||||
assert.equal(ebTxn(noId, "u1")!.plaid_transaction_id, ebTxn(noId, "u1")!.plaid_transaction_id);
|
||||
const card = ebAccount({ uid: "u2", product: "Visa", cash_account_type: "CARD", currency: "EUR", account_id: { iban: "DE89370400440532013000" } }, [{ balance_type: "OTHR", balance_amount: { amount: "1", currency: "EUR" } }, { balance_type: "CLBD", balance_amount: { amount: "-250.5", currency: "EUR" } }], "ING");
|
||||
assert.deepEqual([card.type, card.current_balance, card.mask, card.name, card.currency], ["credit", 250.5, "3000", "Visa", "EUR"]);
|
||||
assert.equal(ebAccount({ uid: "u3", cash_account_type: "SVGS" }, [], "ING").subtype, "savings");
|
||||
|
||||
// Consent never asks for longer than the bank allows.
|
||||
{
|
||||
const calls: { url: string; body?: { access: { valid_until: string }; redirect_url: string } }[] = [];
|
||||
const f = (async (url: string, init?: RequestInit) => {
|
||||
calls.push({ url, body: init?.body ? JSON.parse(String(init.body)) : undefined });
|
||||
return new Response(JSON.stringify(String(url).includes("/aspsps") ? { aspsps: [{ name: "ING", country: "DE", maximum_consent_validity: 864000 }] } : { url: "https://bank/consent" }));
|
||||
}) as typeof fetch;
|
||||
assert.equal(await ebStart(env, { bank: "ING", country: "DE", state: "s", redirect: "https://me/cb" }, f, 0), "https://bank/consent");
|
||||
assert.equal(calls[1].body!.access.valid_until, new Date(864000 * 1000).toISOString());
|
||||
}
|
||||
|
||||
// Paging stops when there's no continuation key, and old balances still map.
|
||||
{
|
||||
const seen: string[] = [];
|
||||
const f = (async (url: string) => {
|
||||
seen.push(String(url));
|
||||
if (String(url).includes("/balances")) return new Response(JSON.stringify({ balances: [{ balance_type: "CLBD", balance_amount: { amount: "10", currency: "GBP" } }] }));
|
||||
const second = String(url).includes("continuation_key=k");
|
||||
return new Response(JSON.stringify({ transactions: [{ transaction_id: second ? "b" : "a", booking_date: "2026-10-02", transaction_amount: { amount: "1" }, credit_debit_indicator: "DBIT", status: "BOOK" }], continuation_key: second ? null : "k" }));
|
||||
}) as typeof fetch;
|
||||
const r = await feedData("enablebanking", env, JSON.stringify({ accounts: [{ uid: "u", cash_account_type: "CACC" }] }), "2026-01-01T00:00:00Z", f);
|
||||
assert.equal(r.txns.length, 2);
|
||||
assert.equal(r.accounts[0].current_balance, 10);
|
||||
}
|
||||
|
||||
// Basiq: outgoing is negative there, positive here; only posted rows.
|
||||
assert.equal(basiqTxn({ id: "1", account: "a", postDate: "2026-10-02T00:00:00Z", amount: "-45.10", status: "posted", description: "WOOLWORTHS" })!.amount, 45.1);
|
||||
assert.equal(basiqTxn({ id: "2", account: "a", postDate: "2026-10-02", amount: "100.00", status: "posted" })!.amount, -100);
|
||||
assert.equal(basiqTxn({ id: "3", account: "a", postDate: null, amount: "-1", status: "pending" }), null);
|
||||
assert.deepEqual([basiqAccount({ id: "x", class: { type: "credit-card" }, balance: "-90.00" }).type, basiqAccount({ id: "x", class: { type: "credit-card" }, balance: "-90.00" }).current_balance], ["credit", 90]);
|
||||
assert.equal(basiqAccount({ id: "y", class: { type: "transaction" }, balance: "5" }).subtype, "checking");
|
||||
{
|
||||
const f = (async (url: string, init?: RequestInit) => {
|
||||
if (String(url).endsWith("/token")) { assert.equal((init!.headers as Record<string, string>).Authorization, "Basic key"); return new Response(JSON.stringify({ access_token: String(init!.body).includes("CLIENT") ? "client" : "server" })); }
|
||||
return new Response(JSON.stringify({ id: "user1" }));
|
||||
}) as typeof fetch;
|
||||
const s = await basiqStart({ BASIQ_API_KEY: "key" }, { email: "a@b.co", state: "st" }, f);
|
||||
assert.equal(s.userId, "user1");
|
||||
assert.equal(s.url, "https://consent.basiq.io/home?token=client&state=st");
|
||||
}
|
||||
|
||||
// Belvo: always positive, type gives direction; no type is skipped, never guessed.
|
||||
assert.equal(belvoTxn({ id: "1", account: { id: "a" }, value_date: "2026-10-02", amount: 45.1, type: "OUTFLOW", status: "PROCESSED" })!.amount, 45.1);
|
||||
assert.equal(belvoTxn({ id: "2", account: { id: "a" }, value_date: "2026-10-02", amount: 45.1, type: "INFLOW", status: "PROCESSED" })!.amount, -45.1);
|
||||
assert.equal(belvoTxn({ id: "3", account: { id: "a" }, value_date: "2026-10-02", amount: 45.1, type: null }), null);
|
||||
assert.equal(belvoTxn({ id: "4", account: { id: "a" }, value_date: "2026-10-02", amount: 1, type: "OUTFLOW", status: "PENDING" }), null);
|
||||
assert.deepEqual([belvoAccount({ id: "c", category: "CREDIT_CARD", balance_type: "LIABILITY", balance: { current: -300 } }).type, belvoAccount({ id: "c", category: "CREDIT_CARD", balance_type: "LIABILITY", balance: { current: -300 } }).current_balance], ["credit", 300]);
|
||||
assert.equal(validCpf("761.092.776-73"), true);
|
||||
assert.equal(validCpf("123"), false);
|
||||
{
|
||||
let sent: Record<string, unknown> = {};
|
||||
const f = (async (_: string, init?: RequestInit) => { sent = JSON.parse(String(init!.body)); return new Response(JSON.stringify({ access: "tok" })); }) as typeof fetch;
|
||||
const url = await belvoStart({ BELVO_SECRET_ID: "i", BELVO_SECRET_PASSWORD: "p", BELVO_TERMS_URL: "https://t" }, { cpf: "761.092.776-73", name: " Ana ", origin: "https://me", callback: "https://me/cb", state: "st", externalId: "u-1" }, f);
|
||||
const w = sent.widget as { openfinance_feature: string; consent: { identification_info: { number: string; name: string }[] }; callback_urls: { success: string } };
|
||||
assert.equal(w.openfinance_feature, "consent_link_creation");
|
||||
assert.deepEqual(w.consent.identification_info[0], { type: "CPF", number: "76109277673", name: "Ana" });
|
||||
assert.ok(w.callback_urls.success.includes("kind=success"));
|
||||
assert.equal(url, "https://widget.belvo.io/?access_token=tok&locale=pt&access_mode=recurrent&external_id=u-1");
|
||||
}
|
||||
|
||||
console.log("feeds: ok");
|
||||
@@ -0,0 +1,219 @@
|
||||
// Bank connections through a hosted consent page: the user approves at the vendor or their bank, then broke reads accounts
|
||||
// and settled transactions. Pure mapping plus fetch, no "@/" imports, so feeds.test.ts runs with plain node.
|
||||
// Built from the vendors' public docs on 2026-11-02 and tested against stand-ins, not their live APIs: check field names
|
||||
// against one real sandbox response before trusting a new connector.
|
||||
// Enable Banking: https://enablebanking.com/docs/api/reference/
|
||||
// Basiq: https://api.basiq.io/reference/gettransactions.md
|
||||
// Belvo: https://developers.belvo.com/products/aggregation_brazil/aggregation-brazil-integration-widget
|
||||
import { createPrivateKey, createSign, randomBytes } from "node:crypto";
|
||||
|
||||
export type FeedId = "enablebanking" | "basiq" | "belvo";
|
||||
export type FeedAccount = { plaid_account_id: string; name: string; official_name: string | null; mask: string | null; type: string; subtype: string; current_balance: number | null; available_balance: number | null; credit_limit: number | null; currency: string | null };
|
||||
// amount: broke's sign, positive = money out. account_ref: the plaid_account_id it belongs to.
|
||||
export type FeedTxn = { plaid_transaction_id: string; account_ref: string; date: string; amount: number; name: string; merchant_name: string | null; logo_url: string | null; pending: boolean; plaid_category: string | null };
|
||||
export type Env = Record<string, string | undefined>;
|
||||
type Fetch = typeof fetch;
|
||||
|
||||
const num = (v: unknown) => (v == null || v === "" || !Number.isFinite(Number(v)) ? null : Number(v));
|
||||
const owed = (type: string, n: number | null) => (n != null && (type === "credit" || type === "loan") ? Math.abs(n) : n);
|
||||
const last4 = (s?: string | null) => (s ? s.replace(/\W/g, "").slice(-4) || null : null);
|
||||
|
||||
async function call<T>(f: Fetch, label: string, url: string, init?: RequestInit): Promise<T> {
|
||||
const res = await f(url, { ...init, signal: AbortSignal.timeout(30000) });
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw Object.assign(new Error(`${label} said ${res.status}: ${text.slice(0, 200)}`), { code: `${label.toUpperCase().replace(/\W/g, "")}_${res.status}`, status: res.status });
|
||||
return (text ? JSON.parse(text) : {}) as T;
|
||||
}
|
||||
|
||||
// ---- Enable Banking (UK and Europe) ----
|
||||
// A pasted key loses its line breaks in a one-line box: rebuild the PEM from whatever came in.
|
||||
export function pemFrom(raw: string) {
|
||||
const body = raw.replace(/\\n/g, "\n").replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
|
||||
return `-----BEGIN PRIVATE KEY-----\n${body.match(/.{1,64}/g)?.join("\n") ?? ""}\n-----END PRIVATE KEY-----\n`;
|
||||
}
|
||||
const b64 = (v: unknown) => Buffer.from(JSON.stringify(v)).toString("base64url");
|
||||
export function ebJwt(env: Env, now = Date.now()) {
|
||||
const iat = Math.floor(now / 1000);
|
||||
const head = `${b64({ typ: "JWT", alg: "RS256", kid: env.ENABLE_BANKING_APP_ID })}.${b64({ iss: "enablebanking.com", aud: "api.enablebanking.com", iat, exp: iat + 3600 })}`;
|
||||
return `${head}.${createSign("RSA-SHA256").update(head).sign(createPrivateKey(pemFrom(env.ENABLE_BANKING_PRIVATE_KEY ?? ""))).toString("base64url")}`;
|
||||
}
|
||||
const ebBase = (env: Env) => env.ENABLE_BANKING_BASE || "https://api.enablebanking.com";
|
||||
const eb = <T>(env: Env, path: string, init: RequestInit = {}, f: Fetch = fetch) =>
|
||||
call<T>(f, "Enable Banking", `${ebBase(env)}${path}`, { ...init, headers: { Authorization: `Bearer ${ebJwt(env)}`, "content-type": "application/json" } });
|
||||
|
||||
type Aspsp = { name: string; country: string; maximum_consent_validity?: number };
|
||||
export const ebBanks = async (env: Env, country: string, f?: Fetch) => (await eb<{ aspsps: Aspsp[] }>(env, `/aspsps?country=${encodeURIComponent(country)}`, {}, f)).aspsps.map((a) => ({ name: a.name, maxSeconds: a.maximum_consent_validity ?? null }));
|
||||
|
||||
const DEFAULT_CONSENT_S = 90 * 864e2;
|
||||
export async function ebStart(env: Env, o: { bank: string; country: string; state: string; redirect: string }, f?: Fetch, now = Date.now()) {
|
||||
const max = (await ebBanks(env, o.country, f)).find((b) => b.name === o.bank)?.maxSeconds ?? DEFAULT_CONSENT_S;
|
||||
const r = await eb<{ url: string }>(env, "/auth", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ access: { valid_until: new Date(now + max * 1000).toISOString() }, aspsp: { name: o.bank, country: o.country }, state: o.state, redirect_url: o.redirect, psu_type: "personal" }),
|
||||
}, f);
|
||||
return r.url;
|
||||
}
|
||||
type EbAccount = { uid: string; name?: string; product?: string; details?: string; cash_account_type?: string; currency?: string; account_id?: { iban?: string; other?: { identification?: string } } };
|
||||
export async function ebFinish(env: Env, code: string, f?: Fetch) {
|
||||
const s = await eb<{ session_id: string; accounts: EbAccount[]; aspsp?: { name?: string } }>(env, "/sessions", { method: "POST", body: JSON.stringify({ code }) }, f);
|
||||
return { ref: s.session_id, institution: s.aspsp?.name ?? "Bank", token: JSON.stringify({ session_id: s.session_id, accounts: s.accounts }) };
|
||||
}
|
||||
const EB_TYPES: Record<string, [string, string]> = { CACC: ["depository", "checking"], CASH: ["depository", "checking"], SVGS: ["depository", "savings"], CARD: ["credit", "credit card"], LOAN: ["loan", "loan"] };
|
||||
type EbBalance = { balance_amount?: { amount?: string | number; currency?: string }; balance_type?: string };
|
||||
// Booked balances first: the closing or interim figure on the account, then whatever the bank sends.
|
||||
const ebBalance = (bs: EbBalance[]) => ["CLBD", "ITBD", "XPCD", "ITAV", "CLAV"].map((t) => bs.find((b) => b.balance_type === t)).find(Boolean) ?? bs[0];
|
||||
export function ebAccount(a: EbAccount, bs: EbBalance[], bank: string): FeedAccount {
|
||||
const [type, subtype] = EB_TYPES[a.cash_account_type ?? ""] ?? ["other", (a.cash_account_type ?? "other").toLowerCase()];
|
||||
const b = ebBalance(bs);
|
||||
return {
|
||||
plaid_account_id: `enablebanking:${a.uid}`, name: a.product || a.details || a.name || bank, official_name: bank,
|
||||
mask: last4(a.account_id?.iban ?? a.account_id?.other?.identification), type, subtype,
|
||||
current_balance: owed(type, num(b?.balance_amount?.amount)), available_balance: null, credit_limit: null, currency: b?.balance_amount?.currency ?? a.currency ?? null,
|
||||
};
|
||||
}
|
||||
export type EbTxn = {
|
||||
transaction_id?: string | null; entry_reference?: string | null; booking_date?: string | null; value_date?: string | null; transaction_date?: string | null;
|
||||
transaction_amount?: { amount?: string | number }; credit_debit_indicator?: string; status?: string; remittance_information?: string[] | string | null; note?: string | null;
|
||||
creditor?: { name?: string | null } | null; debtor?: { name?: string | null } | null; bank_transaction_code?: { code?: string } | null;
|
||||
};
|
||||
/** Settled rows only: pending ones get new ids when they book, which would double them up. Direction comes from the indicator. */
|
||||
export function ebTxn(t: EbTxn, uid: string): FeedTxn | null {
|
||||
const date = t.booking_date ?? t.value_date ?? t.transaction_date;
|
||||
const n = num(t.transaction_amount?.amount);
|
||||
if (t.status !== "BOOK" || !date || n == null || !t.credit_debit_indicator) return null;
|
||||
const out = t.credit_debit_indicator === "DBIT";
|
||||
const text = (Array.isArray(t.remittance_information) ? t.remittance_information.join(" ") : t.remittance_information) || t.note || "";
|
||||
const other = (out ? t.creditor?.name : t.debtor?.name) ?? null;
|
||||
const id = t.transaction_id || t.entry_reference || `${date}|${n}|${text}`; // no id from the bank: same day, amount and text is the same row
|
||||
return { plaid_transaction_id: `enablebanking:${uid}:${id}`, account_ref: `enablebanking:${uid}`, date: date.slice(0, 10), amount: out ? Math.abs(n) : -Math.abs(n), name: text || other || "Transaction", merchant_name: other, logo_url: null, pending: false, plaid_category: t.bank_transaction_code?.code ?? null };
|
||||
}
|
||||
async function ebFeed(env: Env, token: string, since: string, f?: Fetch) {
|
||||
const s = JSON.parse(token) as { accounts: EbAccount[]; institution?: string };
|
||||
const accounts: FeedAccount[] = [], txns: FeedTxn[] = [];
|
||||
for (const a of s.accounts) {
|
||||
const { balances } = await eb<{ balances: EbBalance[] }>(env, `/accounts/${a.uid}/balances`, {}, f);
|
||||
accounts.push(ebAccount(a, balances ?? [], s.institution ?? "Bank"));
|
||||
for (let key: string | null = null, first = true; first || key; first = false) {
|
||||
const q = new URLSearchParams({ date_from: since.slice(0, 10), ...(key ? { continuation_key: key } : {}) });
|
||||
const page: { transactions?: EbTxn[]; continuation_key?: string | null } = await eb(env, `/accounts/${a.uid}/transactions?${q}`, {}, f);
|
||||
for (const t of page.transactions ?? []) {
|
||||
const row = ebTxn(t, a.uid);
|
||||
if (row) txns.push(row);
|
||||
}
|
||||
key = page.continuation_key ?? null;
|
||||
}
|
||||
}
|
||||
return { accounts, txns };
|
||||
}
|
||||
|
||||
// ---- Basiq (Australia) ----
|
||||
const basiqBase = (env: Env) => env.BASIQ_BASE || "https://au-api.basiq.io";
|
||||
async function basiqToken(env: Env, body: string, f: Fetch = fetch) {
|
||||
const r = await call<{ access_token: string }>(f, "Basiq", `${basiqBase(env)}/token`, { method: "POST", headers: { Authorization: `Basic ${env.BASIQ_API_KEY}`, "basiq-version": "3.0", "content-type": "application/x-www-form-urlencoded" }, body });
|
||||
return r.access_token;
|
||||
}
|
||||
const basiq = async <T>(env: Env, path: string, init: RequestInit = {}, f: Fetch = fetch) =>
|
||||
call<T>(f, "Basiq", path.startsWith("http") ? path : `${basiqBase(env)}${path}`, { ...init, headers: { Authorization: `Bearer ${await basiqToken(env, "scope=SERVER_ACCESS", f)}`, "basiq-version": "3.0", "content-type": "application/json", accept: "application/json" } });
|
||||
/** A Basiq user for this person (reused when they have one), and the hosted consent page. The return address is set in Basiq's dashboard. */
|
||||
export async function basiqStart(env: Env, o: { email: string; state: string; userId?: string | null }, f?: Fetch) {
|
||||
const userId = o.userId || (await basiq<{ id: string }>(env, "/users", { method: "POST", body: JSON.stringify({ email: o.email }) }, f)).id;
|
||||
const client = await basiqToken(env, `scope=CLIENT_ACCESS&userId=${encodeURIComponent(userId)}`, f);
|
||||
const consent = env.BASIQ_CONSENT_URL || "https://consent.basiq.io/home";
|
||||
return { userId, url: `${consent}?${new URLSearchParams({ token: client, state: o.state })}` };
|
||||
}
|
||||
type BasiqAccount = { id: string; name?: string; displayName?: string; class?: { type?: string; product?: string }; balance?: string | null; availableFunds?: string | null; currency?: string; maskedNumber?: string; accountNo?: string; institution?: string };
|
||||
export function basiqAccount(a: BasiqAccount): FeedAccount {
|
||||
const k = (a.class?.type ?? "").toLowerCase();
|
||||
const [type, subtype] = /credit/.test(k) ? ["credit", "credit card"] : /loan|mortgage/.test(k) ? ["loan", k] : /saving|term/.test(k) ? ["depository", "savings"] : /invest/.test(k) ? ["investment", "brokerage"] : /transaction/.test(k) ? ["depository", "checking"] : ["other", k || "other"];
|
||||
return { plaid_account_id: `basiq:${a.id}`, name: a.displayName || a.name || "Account", official_name: a.class?.product ?? null, mask: last4(a.maskedNumber ?? a.accountNo), type, subtype, current_balance: owed(type, num(a.balance)), available_balance: num(a.availableFunds), credit_limit: null, currency: a.currency ?? null };
|
||||
}
|
||||
export type BasiqTxn = { id: string; account?: string; postDate?: string | null; transactionDate?: string | null; amount?: string | number; description?: string; status?: string; enrich?: { cleanDescription?: string; merchant?: { businessName?: string } | null } | null; class?: string; subClass?: { title?: string } | null };
|
||||
/** Basiq: money out is negative. Ours: positive. Posted rows only. */
|
||||
export function basiqTxn(t: BasiqTxn): FeedTxn | null {
|
||||
const n = num(t.amount), date = t.postDate ?? t.transactionDate;
|
||||
if (t.status !== "posted" || n == null || !date || !t.account) return null;
|
||||
return { plaid_transaction_id: `basiq:${t.id}`, account_ref: `basiq:${t.account}`, date: date.slice(0, 10), amount: -n, name: t.enrich?.cleanDescription || t.description || "Transaction", merchant_name: t.enrich?.merchant?.businessName ?? null, logo_url: null, pending: false, plaid_category: t.subClass?.title ?? t.class ?? null };
|
||||
}
|
||||
async function basiqFeed(env: Env, token: string, since: string, f?: Fetch) {
|
||||
const { userId } = JSON.parse(token) as { userId: string };
|
||||
const accts = await basiq<{ data: BasiqAccount[] }>(env, `/users/${userId}/accounts`, {}, f);
|
||||
const txns: FeedTxn[] = [];
|
||||
let next: string | null = `/users/${userId}/transactions?limit=500`;
|
||||
// Newest first, so stop paging once a whole page is older than the window.
|
||||
while (next) {
|
||||
const page: { data: BasiqTxn[]; links?: { next?: string | null } } = await basiq(env, next, {}, f);
|
||||
const rows = page.data.map(basiqTxn).filter((t): t is FeedTxn => !!t);
|
||||
txns.push(...rows.filter((t) => t.date >= since.slice(0, 10)));
|
||||
next = page.data.length && rows.some((t) => t.date >= since.slice(0, 10)) ? page.links?.next ?? null : null;
|
||||
}
|
||||
return { accounts: accts.data.map(basiqAccount), txns };
|
||||
}
|
||||
|
||||
// ---- Belvo (Brazil, Open Finance) ----
|
||||
const belvoBase = (env: Env) => env.BELVO_BASE || (env.BELVO_ENV === "production" ? "https://api.belvo.com" : "https://sandbox.belvo.com");
|
||||
const belvo = <T>(env: Env, path: string, init: RequestInit = {}, f: Fetch = fetch) =>
|
||||
call<T>(f, "Belvo", path.startsWith("http") ? path : `${belvoBase(env)}${path}`, { ...init, headers: { Authorization: `Basic ${Buffer.from(`${env.BELVO_SECRET_ID}:${env.BELVO_SECRET_PASSWORD}`).toString("base64")}`, "content-type": "application/json" } });
|
||||
/** Brazilian Open Finance needs the person's CPF and full name before the consent page. They go to Belvo only, never stored by broke. */
|
||||
export const validCpf = (cpf: string) => /^\d{11}$/.test(cpf.replace(/\D/g, ""));
|
||||
export async function belvoStart(env: Env, o: { cpf: string; name: string; origin: string; callback: string; state: string; externalId: string }, f?: Fetch) {
|
||||
const back = (kind: string) => `${o.callback}?${new URLSearchParams({ state: o.state, kind })}`;
|
||||
const r = await belvo<{ access: string }>(env, "/api/token/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
id: env.BELVO_SECRET_ID, password: env.BELVO_SECRET_PASSWORD,
|
||||
scopes: "read_institutions,write_links,read_consents,write_consents,write_consent_callback,delete_consents",
|
||||
stale_in: "300d", fetch_resources: ["ACCOUNTS", "TRANSACTIONS"],
|
||||
widget: {
|
||||
purpose: "Organizar suas finanças pessoais, mostrando suas contas e transações em um só lugar.",
|
||||
openfinance_feature: "consent_link_creation",
|
||||
callback_urls: { success: back("success"), exit: back("exit"), event: back("event") },
|
||||
consent: { terms_and_conditions_url: env.BELVO_TERMS_URL, permissions: ["REGISTER", "ACCOUNTS", "CREDIT_CARDS", "CREDIT_OPERATIONS"], identification_info: [{ type: "CPF", number: o.cpf.replace(/\D/g, ""), name: o.name.trim() }] },
|
||||
branding: { company_icon: `${o.origin}/icon.svg`, company_logo: `${o.origin}/icon.svg`, company_name: "broke", company_terms_url: env.BELVO_TERMS_URL },
|
||||
},
|
||||
}),
|
||||
}, f);
|
||||
return `${env.BELVO_WIDGET_URL || "https://widget.belvo.io/"}?${new URLSearchParams({ access_token: r.access, locale: "pt", access_mode: "recurrent", external_id: o.externalId })}`;
|
||||
}
|
||||
type BelvoAccount = { id: string; name?: string; type?: string; subtype?: string; category?: string; balance_type?: string; balance?: { current?: number | string; available?: number | string }; currency?: string; number?: string; public_identification_value?: string; credit_data?: { credit_limit?: number | string; cards?: { identification_number?: string }[] | null } | null; institution?: { name?: string } | string };
|
||||
export function belvoAccount(a: BelvoAccount): FeedAccount {
|
||||
const c = `${a.category ?? ""} ${a.type ?? ""}`.toLowerCase();
|
||||
const liability = a.balance_type === "LIABILITY";
|
||||
const [type, subtype] = /credit/.test(c) ? ["credit", "credit card"] : liability || /loan/.test(c) ? ["loan", "loan"] : /pension|invest/.test(c) ? ["investment", "brokerage"] : /saving/.test(c) ? ["depository", "savings"] : /check/.test(c) ? ["depository", "checking"] : ["depository", "checking"];
|
||||
return { plaid_account_id: `belvo:${a.id}`, name: a.name || "Conta", official_name: typeof a.institution === "object" ? a.institution?.name ?? null : a.institution ?? null, mask: last4(a.credit_data?.cards?.[0]?.identification_number ?? a.number ?? a.public_identification_value), type, subtype, current_balance: owed(type, num(a.balance?.current)), available_balance: num(a.balance?.available), credit_limit: num(a.credit_data?.credit_limit), currency: a.currency ?? null };
|
||||
}
|
||||
export type BelvoTxn = { id: string; account?: { id?: string } | string; value_date?: string | null; accounting_date?: string | null; transacted_at?: string | null; amount?: number | string; type?: string | null; status?: string; description?: string; category?: string | null; merchant?: { merchant_name?: string; logo?: string } | null };
|
||||
/** Belvo: amount is always positive, type says which way. No type: skipped rather than guessed. PROCESSED rows only. */
|
||||
export function belvoTxn(t: BelvoTxn): FeedTxn | null {
|
||||
const n = num(t.amount), date = t.value_date ?? t.accounting_date ?? t.transacted_at;
|
||||
const account = typeof t.account === "string" ? t.account : t.account?.id;
|
||||
if (n == null || !date || !account || t.status === "PENDING" || (t.type !== "INFLOW" && t.type !== "OUTFLOW")) return null;
|
||||
return { plaid_transaction_id: `belvo:${t.id}`, account_ref: `belvo:${account}`, date: date.slice(0, 10), amount: t.type === "OUTFLOW" ? Math.abs(n) : -Math.abs(n), name: t.description || t.merchant?.merchant_name || "Transação", merchant_name: t.merchant?.merchant_name ?? null, logo_url: t.merchant?.logo ?? null, pending: false, plaid_category: t.category ?? null };
|
||||
}
|
||||
async function belvoPages<T>(env: Env, first: string, f?: Fetch) {
|
||||
const out: T[] = [];
|
||||
for (let next: string | null = first; next; ) {
|
||||
const page: { results?: T[]; next?: string | null } = await belvo(env, next, {}, f);
|
||||
out.push(...(page.results ?? []));
|
||||
next = page.next ?? null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
async function belvoFeed(env: Env, token: string, since: string, f?: Fetch) {
|
||||
const { link } = JSON.parse(token) as { link: string };
|
||||
const accounts = (await belvoPages<BelvoAccount>(env, `/api/accounts/?link=${encodeURIComponent(link)}&page_size=100`, f)).map(belvoAccount);
|
||||
const txns = (await belvoPages<BelvoTxn>(env, `/api/transactions/?link=${encodeURIComponent(link)}&page_size=100`, f)).map(belvoTxn).filter((t): t is FeedTxn => !!t && t.date >= since.slice(0, 10));
|
||||
return { accounts, txns };
|
||||
}
|
||||
|
||||
// ---- Shared ----
|
||||
export const FEEDS: Record<FeedId, { label: string; envKeys: string[]; banksStep: boolean }> = {
|
||||
enablebanking: { label: "Enable Banking", envKeys: ["ENABLE_BANKING_APP_ID", "ENABLE_BANKING_PRIVATE_KEY"], banksStep: true },
|
||||
basiq: { label: "Basiq", envKeys: ["BASIQ_API_KEY"], banksStep: false },
|
||||
belvo: { label: "Belvo", envKeys: ["BELVO_SECRET_ID", "BELVO_SECRET_PASSWORD", "BELVO_TERMS_URL"], banksStep: false },
|
||||
};
|
||||
export const isFeed = (p?: string | null): p is FeedId => !!p && p in FEEDS;
|
||||
export const newState = () => randomBytes(16).toString("base64url");
|
||||
|
||||
export function feedData(id: FeedId, env: Env, token: string, since: string, f?: Fetch) {
|
||||
return id === "enablebanking" ? ebFeed(env, token, since, f) : id === "basiq" ? basiqFeed(env, token, since, f) : belvoFeed(env, token, since, f);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import "server-only";
|
||||
import type { CountryCode } from "plaid";
|
||||
import { countryOf, type Provider } from "@/lib/countries";
|
||||
import { isPlaceholder } from "@/lib/envfile";
|
||||
import { PLAID_COUNTRIES } from "@/lib/plaid";
|
||||
import type { Tokens } from "@/lib/providers/akahu";
|
||||
import { FEEDS, isFeed, type FeedId } from "@/lib/providers/feeds";
|
||||
|
||||
// Which bank providers this server has keys for. CSV import needs none.
|
||||
// GoCardless Bank Account Data: not built. Actual Budget's docs (read 2026-10-22,
|
||||
// https://actualbudget.org/docs/advanced/bank-sync/gocardless/) say GoCardless stopped taking new accounts in July 2025,
|
||||
// so UK and EU fall back to Plaid (where it covers the country) and CSV.
|
||||
export const akahuTokens = (env: Record<string, string | undefined> = process.env): Tokens | null =>
|
||||
!isPlaceholder(env.AKAHU_APP_TOKEN) && !isPlaceholder(env.AKAHU_USER_TOKEN) ? { app: env.AKAHU_APP_TOKEN!, user: env.AKAHU_USER_TOKEN! } : null;
|
||||
const plaidKeys = () => !isPlaceholder(process.env.PLAID_CLIENT_ID) && !isPlaceholder(process.env.PLAID_SECRET);
|
||||
|
||||
export const configured = (p: Provider) => p === "csv" || (p === "plaid" ? plaidKeys() : p === "akahu" ? !!akahuTokens() : isFeed(p) && FEEDS[p].envKeys.every((k) => !isPlaceholder(process.env[k])));
|
||||
|
||||
/** The Add account options for a country, in its order, only those this server can run. CSV is always there. */
|
||||
export const addOptions = (country?: string | null) => countryOf(country).providers.filter(configured);
|
||||
|
||||
// Plaid Link's country_codes enum, from https://plaid.com/docs/api/link/ (read 2026-10-22).
|
||||
const PLAID_LINK = ["US", "GB", "ES", "NL", "FR", "IE", "CA", "DE", "IT", "PL", "DK", "NO", "SE", "EE", "LT", "LV", "PT", "BE", "AT", "FI"];
|
||||
/** Link shows the user's own country's banks when Plaid covers it, else the server's PLAID_COUNTRY_CODES. */
|
||||
export const plaidCountries = (country?: string | null): CountryCode[] =>
|
||||
country && PLAID_LINK.includes(country) ? [country as CountryCode] : PLAID_COUNTRIES;
|
||||
|
||||
/** What the Add accounts screen (and the empty state) offers this user. Statement import and manual accounts need no keys. */
|
||||
export function addChoices(country?: string | null, alsoNz = false) {
|
||||
const code = countryOf(country).code;
|
||||
const options = addOptions(code);
|
||||
const plaid = options.includes("plaid");
|
||||
return {
|
||||
bank: plaid ? ("plaid" as const) : options.includes("akahu") ? ("akahu" as const) : null,
|
||||
// Hosted-consent connections this server has keys for. Offered first: they reach more of the country's banks.
|
||||
feeds: options.filter((p): p is FeedId => isFeed(p)),
|
||||
investments: plaid && code === "US",
|
||||
sandbox: plaid && process.env.PLAID_ENV === "sandbox",
|
||||
// NZ without Akahu keys: say where to add them.
|
||||
akahuMissing: (countryOf(code).providers.includes("akahu") || alsoNz) && !configured("akahu"),
|
||||
// Lives elsewhere but also banks in NZ (Settings, money profile): the NZ option beside their own.
|
||||
alsoAkahu: alsoNz && code !== "NZ" && configured("akahu"),
|
||||
};
|
||||
}
|
||||
export type AddChoices = ReturnType<typeof addChoices>;
|
||||
Reference in new issue
Block a user