diff --git a/next.config.ts b/next.config.ts
index ae1d9e0..b24ead9 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -1,9 +1,19 @@
+import { execSync } from "node:child_process";
import type { NextConfig } from "next";
+// When the code this copy runs was last changed (its newest commit), for "A new version of broke is ready".
+let builtFrom = "";
+try {
+ builtFrom = execSync("git log -1 --format=%cI", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
+} catch {
+ /* no git (a download without history): the update check stays quiet */
+}
+
const nextConfig: NextConfig = {
devIndicators: false,
distDir: process.env.NEXT_DIST_DIR || ".next", // a production build can sit beside the running dev server
serverExternalPackages: ["pg"],
+ env: { BROKE_BUILT_FROM: builtFrom },
// Keep pages you visited for 3 min, so going back or switching tabs is instant. Every edit calls router.refresh(),
// which drops the cache, so changes still show at once.
experimental: { staleTimes: { dynamic: 180 } },
diff --git a/scripts/start.mjs b/scripts/start.mjs
index 121b217..8575710 100755
--- a/scripts/start.mjs
+++ b/scripts/start.mjs
@@ -2,7 +2,7 @@
// Starts broke on this computer and opens it. Before the keys are in, it runs in development mode: the setup page saves
// keys and the server picks them up without a restart. After that it runs the faster production build.
import { spawn, spawnSync } from "node:child_process";
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -34,7 +34,14 @@ if (await fetch(url, { redirect: "manual" }).then(() => true, () => false)) {
openIt();
process.exit(0);
}
-if (ready && !npm("run", "build")) process.exit(1);
+// The last build is reused when nothing it was built from has changed since: code, packages, settings or keys.
+const newest = (p) => !existsSync(p) ? 0 : statSync(p).isDirectory()
+ ? Math.max(0, ...readdirSync(p, { recursive: true }).map((f) => statSync(join(p, String(f))).mtimeMs))
+ : statSync(p).mtimeMs;
+const built = existsSync(".next/BUILD_ID") ? statSync(".next/BUILD_ID").mtimeMs : 0;
+const stale = Math.max(...["src", "public", "package-lock.json", "next.config.ts", ".env", ".env.local"].map(newest)) > built;
+if (ready && !stale) console.log("Nothing changed since the last build: starting it.");
+if (ready && stale && !npm("run", "build")) process.exit(1);
const next = join("node_modules", ".bin", win ? "next.cmd" : "next");
// Listens on this computer only, which is what makes saving keys from the page safe (writeGate checks the rest).
const args = ready ? ["start", "-H", "127.0.0.1", "-p", port] : ["dev", "--turbopack", "-H", "127.0.0.1", "-p", port];
diff --git a/src/app/(app)/accounts/page.tsx b/src/app/(app)/accounts/page.tsx
index 72be2ca..dac943c 100644
--- a/src/app/(app)/accounts/page.tsx
+++ b/src/app/(app)/accounts/page.tsx
@@ -60,6 +60,12 @@ export default async function Accounts() {
supabase.from("accounts").select("id, name, custom_name, mask, type, subtype, current_balance:balance, currency, home:home_balance, included").eq("manual", true).eq("user_id", user!.id),
]);
const items = (data ?? []) as unknown as Item[];
+ // How far back each bank's transactions go, so a short history doesn't read as a strange month.
+ const since = new Map(await Promise.all(items.map(async (i) => {
+ const ids = i.accounts.map((a) => a.id);
+ const { data: first } = ids.length ? await supabase.from("transactions").select("date").in("account_id", ids).order("date").limit(1) : { data: [] };
+ return [i.id, (first?.[0]?.date as string | undefined) ?? null] as const;
+ })));
const manualItem = { id: "manual", institution_name: "Added by you", institution_logo: null, institution_color: null, last_synced_at: null, accounts: [] };
const all = [
...items.flatMap((i) => i.accounts.map((a) => ({ ...a, item: i }))),
@@ -164,7 +170,7 @@ export default async function Accounts() {
{item.status && item.status !== "ok"
? item.status === "ITEM_LOGIN_REQUIRED" ? "Sign in to your bank again to keep syncing." : (item.error ?? "This connection stopped syncing.")
- : `${holds(item.accounts) ? `${holds(item.accounts)} · ` : ""}${plural(item.accounts.length, "account")} · synced ${item.last_synced_at ? ago(item.last_synced_at) : "never"}`}
+ : `${holds(item.accounts) ? `${holds(item.accounts)} · ` : ""}${plural(item.accounts.length, "account")}${since.get(item.id) ? ` · history from ${new Date(`${since.get(item.id)}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" })}` : ""} · synced ${item.last_synced_at ? ago(item.last_synced_at) : "never"}`}
diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx
index 6eddb9f..08fe4e8 100644
--- a/src/app/(app)/layout.tsx
+++ b/src/app/(app)/layout.tsx
@@ -11,12 +11,14 @@ import { countryOf } from "@/lib/countries";
import { getUser, userTz } from "@/lib/data";
import { fmtFor, todayIn } from "@/lib/format";
import { modeOf } from "@/lib/privacy";
+import { updateReady } from "@/lib/updates";
import { createClient } from "@/utils/supabase/server";
// Accounts made before country support are treated as US (countryOf default) and get a dashboard nudge instead.
const FIRST_RUN_SINCE = "2026-10-22";
export default async function AppLayout({ children }: { children: React.ReactNode }) {
+ const update = await updateReady();
const [{ user }, tz] = await Promise.all([getUser(), userTz()]);
const profile = user?.user_metadata?.profile;
// created_at isn't in the token, so only users with no country pay for the full user record.
@@ -47,6 +49,7 @@ export default async function AppLayout({ children }: { children: React.ReactNod
+ {update && A new version of broke is ready}
broke is a personal project. Bank data comes from Plaid.
diff --git a/src/app/(app)/more/page.tsx b/src/app/(app)/more/page.tsx
index e26d610..9621580 100644
--- a/src/app/(app)/more/page.tsx
+++ b/src/app/(app)/more/page.tsx
@@ -1,25 +1,17 @@
import { ChevronRight, Sparkles } from "lucide-react";
import { DonateLink } from "@/components/Donate";
import Link from "next/link";
-import { countryOf } from "@/lib/countries";
-import { getUser } from "@/lib/data";
const PAGES = [
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
- { href: "/plan", label: "Money plan", what: "Every move broke found for you, in order." },
- { href: "/optimize", label: "Optimize", what: "Tax and savings ideas for your country." },
- { href: "/bonuses", label: "Bonuses", what: "Sign-up bonuses from banks and cards." },
- { href: "/cards", label: "Cards", what: "Your cards and which one to use." },
];
-// Everything that isn't part of the three steps on Home.
-export default async function More() {
- const { user } = await getUser();
- const cards = countryOf(user?.user_metadata?.profile?.country).cards;
+// What isn't in the main menu: Debt, connecting your AI and supporting broke.
+export default function More() {
return (
- {PAGES.filter((p) => cards || p.href !== "/cards").map((p) => (
+ {PAGES.map((p) => (
{p.label}{p.what}
diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx
index db1f9d6..78f9521 100644
--- a/src/app/(app)/page.tsx
+++ b/src/app/(app)/page.tsx
@@ -6,13 +6,16 @@ import { CountryBanner } from "@/components/CountryPicker";
import { EmptyBank } from "@/components/EmptyBank";
import { GoLiveCard } from "@/components/GoLiveCard";
import { Merchant } from "@/components/Merchant";
+import { PayFound } from "@/components/PayFound";
import { PayQuestion } from "@/components/PayQuestion";
import { SyncButton } from "@/components/PlaidButtons";
import { TxnList } from "@/components/TxnList";
+import { WeekCard } from "@/components/WeekCard";
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
import { deterministicMoves, ladder } from "@/lib/plan";
import { myPlanFacts } from "@/lib/plan-facts";
+import { payGuess } from "@/lib/pay";
import { moneyPicture } from "@/lib/steps";
import { fetchChecks } from "@/lib/unsure";
@@ -22,6 +25,23 @@ async function HomeCheck({ checks }: { checks: Promise }) {
return c.total > 0 ? : null;
}
+// Pay the bank filed as something else (lib/pay.ts). Streams in beside the rest.
+async function PayCheck({ uid, today, notPay }: { uid: string; today: string; notPay: string[] }) {
+ const { supabase } = await getUser();
+ const since = ymd(new Date(Date.parse(today) - 90 * 864e5));
+ const { data } = await supabase.from("transactions").select("date, amount, name, merchant_name, custom_name, category:categories(id, key, label, kind)")
+ .eq("user_id", uid).eq("ignored", false).lt("amount", -200).gte("date", since).limit(500);
+ type R = { date: string; amount: number; name: string; merchant_name: string | null; custom_name: string | null; category: { key: string; label: string; kind: string } | null };
+ const rows = (data ?? []) as unknown as R[];
+ const name = (r: R) => r.merchant_name ?? r.name;
+ const pay = payGuess(rows.map((r) => ({ name: name(r), date: r.date, amount: Number(r.amount), kind: r.category?.kind ?? null })), notPay);
+ if (!pay) return null;
+ const { data: income } = await supabase.from("categories").select("id").eq("key", "INCOME").is("user_id", null).maybeSingle();
+ if (!income) return null;
+ const filedAs = rows.find((r) => name(r) === pay.name)?.category?.label ?? "something else";
+ return ;
+}
+
// One line pointing at the plan, or the one question broke needs answered. Streams in: the plan facts are the slow part.
async function NextStep({ profile }: { profile: Record }) {
const facts = await myPlanFacts();
@@ -91,8 +111,10 @@ export default async function Dashboard() {
))}
+
+
diff --git a/src/app/(app)/settings/Settings.tsx b/src/app/(app)/settings/Settings.tsx
index 244ebf7..509aa8d 100644
--- a/src/app/(app)/settings/Settings.tsx
+++ b/src/app/(app)/settings/Settings.tsx
@@ -36,13 +36,13 @@ const NAV: { id: Group; label: string; icon: LucideIcon; what: string }[] = [
];
// Which settings page each /setup section belongs on. Sections added later land by what they're about.
-const PLACE: Record = { supabase: "database", database: "database", plaid: "banks", akahu: "banks", enablebanking: "banks", basiq: "banks", belvo: "banks", ai: "ai", referrals: "referrals", local: "advanced", mcp: "advanced", devlogin: "advanced" };
+const PLACE: Record = { supabase: "database", database: "database", codes: "database", plaid: "banks", akahu: "banks", enablebanking: "banks", basiq: "banks", belvo: "banks", ai: "ai", referrals: "referrals", local: "advanced", mcp: "advanced", devlogin: "advanced" };
const groupOf = (s: Section): Group => PLACE[s.id] ?? (/bank/i.test(`${s.title} ${s.what}`) ? "banks" : "advanced");
// Server setup (keys, database, model, testing shortcuts). Only shown on the machine that runs broke.
const SERVER: Group[] = ["banks", "database", "referrals", "advanced"];
const attention = (s: Section) => s.status === "error" || (s.status === "todo" && s.kind !== "more");
-export function Settings({ signedIn, local, folder, repo, email, profile, mode, testItems, message, aiMode }: { signedIn: boolean; local: boolean; folder: string; repo: string | null; email: string; profile: Profile; mode: Mode; testItems: { id: string; name: string }[]; message?: string; aiMode: AiMode }) {
+export function Settings({ signedIn, local, folder, repo, update, email, profile, mode, testItems, message, aiMode }: { signedIn: boolean; local: boolean; folder: string; repo: string | null; update: boolean; email: string; profile: Profile; mode: Mode; testItems: { id: string; name: string }[]; message?: string; aiMode: AiMode }) {
const [group, setGroup] = useState("profile");
const [data, setData] = useState(null);
const [failed, setFailed] = useState(false);
@@ -124,6 +124,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
)}
+ {group === "improve" && update && {folder && npm run update}}
{group === "improve" && }
{group === "database" && (
diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx
index 55ecca5..daac461 100644
--- a/src/app/(app)/settings/page.tsx
+++ b/src/app/(app)/settings/page.tsx
@@ -1,5 +1,6 @@
import { getUser } from "@/lib/data";
import { isHosted } from "@/lib/llm/providers";
+import { updateReady } from "@/lib/updates";
import { modeOf } from "@/lib/privacy";
import { currentEnv, fromLocalhost, setupAccess, supabaseReady } from "@/lib/setup";
import { createAdminClient } from "@/utils/supabase/admin";
@@ -21,6 +22,7 @@ export default async function SettingsPage({ searchParams }: { searchParams: Pro
signedIn={access.signedIn}
local={local}
folder={isHosted() ? "" : process.cwd()}
+ update={await updateReady()}
repo={process.env.VERCEL_GIT_REPO_OWNER && process.env.VERCEL_GIT_REPO_SLUG ? `${process.env.VERCEL_GIT_REPO_OWNER}/${process.env.VERCEL_GIT_REPO_SLUG}` : null}
email={user?.email ?? ""}
profile={user?.user_metadata?.profile ?? {}}
diff --git a/src/app/api/demo-bank/route.ts b/src/app/api/demo-bank/route.ts
new file mode 100644
index 0000000..7bd26b3
--- /dev/null
+++ b/src/app/api/demo-bank/route.ts
@@ -0,0 +1,52 @@
+import { NextResponse } from "next/server";
+import { demoBank } from "@/lib/demo";
+import { today as userToday } from "@/lib/data";
+import { ymd } from "@/lib/format";
+import { sameOrigin } from "@/lib/setup";
+import { createAdminClient } from "@/utils/supabase/admin";
+import { createClient } from "@/utils/supabase/server";
+
+// "Use made-up data": a demo bank for the signed-in user, for trying broke without a Plaid account. Its token starts
+// with access-sandbox-, so it counts as test data everywhere (Settings, Banks; switching to real banks clears it), and
+// sync and removal skip it (DEMO_TOKEN in lib/sync.ts and lib/plaid.ts). Written by the server: plaid_items is server-only.
+export async function POST(request: Request) {
+ const { data: { user } } = await (await createClient()).auth.getUser();
+ if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
+ if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ const db = createAdminClient();
+ const ref = `demo:${user.id}`;
+ const { data: had } = await db.from("plaid_items").select("id").eq("plaid_item_id", ref).maybeSingle();
+ if (had) return NextResponse.json({ error: "You already have the made-up bank." }, { status: 409 });
+
+ const { accounts, txns, streams } = demoBank(ymd(await userToday()));
+ const { data: cats } = await db.from("categories").select("id, key").is("user_id", null);
+ const cat = new Map((cats ?? []).map((c) => [c.key as string, c.id as string]));
+ const { data: item, error } = await db.from("plaid_items").insert({
+ user_id: user.id, provider: "plaid", plaid_item_id: ref, access_token: `access-sandbox-demo-${user.id}`,
+ institution_name: "Demo Bank (made-up)", status: "ok", last_synced_at: new Date().toISOString(), cursor: "demo",
+ }).select("id").single();
+ if (error) return NextResponse.json({ error: "Couldn't add the made-up bank." }, { status: 500 });
+ const fail = async (what: string, e: { message: string }) => {
+ console.error(`[broke] demo bank ${what}:`, e.message);
+ await db.from("plaid_items").delete().eq("id", item.id); // accounts and transactions go with it
+ return NextResponse.json({ error: "Couldn't add the made-up bank." }, { status: 500 });
+ };
+ const { data: saved, error: e1 } = await db.from("accounts").insert(accounts.map((a) => ({
+ user_id: user.id, item_id: item.id, plaid_account_id: `${ref}:${a.key}`, name: a.name, official_name: null, mask: a.mask,
+ type: a.type, subtype: a.subtype, current_balance: a.balance, available_balance: a.type === "credit" ? null : a.balance, credit_limit: a.type === "credit" ? 5000 : null, currency: "USD",
+ }))).select("id, plaid_account_id");
+ if (e1) return fail("accounts", e1);
+ const acct = new Map((saved ?? []).map((a) => [String(a.plaid_account_id).split(":").pop()!, a.id as string]));
+ const { error: e2 } = await db.from("transactions").insert(txns.map((t) => ({
+ user_id: user.id, account_id: acct.get(t.account)!, plaid_transaction_id: `${ref}:${t.key}`, date: t.date, amount: t.amount,
+ name: t.name, merchant_name: t.name, pending: false, plaid_category: t.category, category_id: cat.get(t.category) ?? null,
+ })));
+ if (e2) return fail("transactions", e2);
+ const { error: e3 } = await db.from("recurring").insert(streams.map((s) => ({
+ user_id: user.id, plaid_stream_id: `${ref}:${s.merchant}`, account_id: acct.get(s.account) ?? null, merchant_name: s.merchant,
+ frequency: s.frequency, average_amount: s.amount, last_amount: s.amount, last_date: s.last, next_date: s.next, is_income: s.income,
+ active: true, status: "MATURE", category_id: cat.get(s.category) ?? null,
+ })));
+ if (e3) return fail("bills", e3);
+ return NextResponse.json({ ok: true, institution: "Demo Bank (made-up)", accounts: accounts.length, added: txns.length });
+}
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
index b64154f..8ecf36d 100644
--- a/src/app/login/page.tsx
+++ b/src/app/login/page.tsx
@@ -4,9 +4,13 @@ import { useEffect, useState } from "react";
import { Logo } from "@/components/Logo";
import { createClient } from "@/utils/supabase/client";
+// Sign in with a code from your email. The same email also has a link, which still works (/auth/callback).
+// Rate limits and wrong-browser links were the common trouble with links alone; a code works in any tab.
export default function LoginPage() {
const [email, setEmail] = useState("");
- const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
+ const [code, setCode] = useState("");
+ const [state, setState] = useState<"idle" | "sending" | "sent" | "checking" | "error">("idle");
+ const [sent, setSent] = useState(false);
const [message, setMessage] = useState("");
const [firstRun, setFirstRun] = useState(null);
const [devLogin, setDevLogin] = useState(false);
@@ -21,8 +25,8 @@ export default function LoginPage() {
}).catch(() => {});
}, []);
- async function submit(e: React.FormEvent) {
- e.preventDefault();
+ async function send(e?: React.FormEvent) {
+ e?.preventDefault();
setState("sending");
const { error } = await createClient().auth.signInWithOtp({
email,
@@ -30,8 +34,23 @@ export default function LoginPage() {
});
if (error) {
setState("error");
- setMessage(error.message);
- } else setState("sent");
+ setMessage(/rate limit|too many/i.test(error.message) ? "Too many sign-in emails for now. Supabase's free email sends a few an hour. Wait a bit, or use the code or link from the last email." : error.message);
+ } else {
+ setSent(true);
+ setCode("");
+ setState("sent");
+ }
+ }
+
+ async function verify(e: React.FormEvent) {
+ e.preventDefault();
+ setState("checking");
+ const { error } = await createClient().auth.verifyOtp({ email, token: code.replace(/\s/g, ""), type: "email" });
+ if (error) {
+ setState("error");
+ setCode(""); // ready for the right one, not mixed in with the wrong one
+ setMessage(/expired|invalid/i.test(error.message) ? "That code didn't work. Codes work once, for about an hour. Check you typed the newest one, or send a new one." : error.message);
+ } else window.location.assign("/"); // a full load: the page cache may still hold "/" from before sign-in (a redirect back here)
}
return (
@@ -47,13 +66,34 @@ export default function LoginPage() {
)}
-
-
+ {!plan && }
+ {fixAll}
);
return (
{head}
Is this right? Tips are only as good as your categories.