Skip to content
clFasterPublic

About

Open-source app for fair expense splitting with custom ratios, payment tracking, and balance calculation.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

TeilFair

An open-source expense splitting application that helps groups fairly divide shared costs. It supports custom split ratios, tracks individual payments, and provides a clear overview of outstanding balances so everyone knows who owes whom.

Features

  • No Registration Required: Access groups via capability links (tokens) - no user accounts needed
  • Multiple Payers: Track expenses where multiple people contributed to payment
  • Flexible Splitting:
    • Equal splits among members
    • Fixed amount splits
    • Percentage-based splits
    • Custom ratio-based splits (e.g., 2:1 for pro-rata share)
  • Smart Settlements: Greedy algorithm minimizes the number of transactions needed to settle all debts
  • Cross-Platform: Web (React + Vite), iOS, and Android (React Native + Expo) with shared TypeScript business logic
  • Lightweight Backend: Uses Supabase free tier with Row Level Security for token-based access control
  • Real-Time Balance Tracking: See who owes whom and outstanding balances at a glance
  • Secure Sharing: Separate read-only and full-access tokens for group sharing

Architecture

Tech Stack

Shared Library (@teilfair/shared):

  • TypeScript 7 compiler (TypeScript 6 API compatibility for tooling)
  • Vitest (testing framework)
  • Focuses on calculation logic and data validation

Web Application (@teilfair/web):

  • React 19
  • Vite 8 (build tool)
  • React Router 7 (routing)
  • Zustand (state management)
  • Supabase JS client
  • FontAwesome (icons)
  • Vercel Analytics & Speed Insights

Mobile Application (@teilfair/mobile):

  • React Native 0.88
  • Expo SDK 58
  • Zustand (state management)
  • React Navigation (native stack navigation)
  • Async Storage (local persistence)
  • Secure Store (sensitive data)
  • Supabase JS client

Backend:

  • Supabase (PostgreSQL database with RLS)
  • Row Level Security policies (token-based access)
  • UUID generation for secure IDs

Project Structure

teilfair/
├── packages/
│   ├── shared/                 # Shared TypeScript library
│   │   ├── src/
│   │   │   ├── calculations.ts # Core calculation logic
│   │   │   ├── types.ts        # Shared types
│   │   │   └── index.ts
│   │   ├── __tests__/
│   │   └── package.json
│   ├── web/                    # React web application
│   │   ├── src/
│   │   │   ├── components/     # React components
│   │   │   ├── pages/          # Page components
│   │   │   ├── store/          # Zustand stores
│   │   │   ├── lib/            # API/Supabase services
│   │   │   └── App.tsx
│   │   ├── index.html
│   │   └── package.json
│   └── mobile/                 # React Native application
│       ├── src/
│       ├── app.json            # Expo config
│       └── package.json
├── supabase/
│   ├── schemas/                # Declarative DDL: edit these for schema changes
│   ├── migrations/             # Generated deployment SQL
│   │   └── 20261108112650_initial_schema.sql
│   └── config.toml
├── pnpm-workspace.yaml         # Monorepo workspace config
└── package.json

Security Model

TeilFair uses capability-based security instead of user accounts:

  • Each group has two tokens: readToken and writeToken
  • Share the read link for view-only access
  • Share the write link for full edit access
  • Tokens are validated via Supabase Row Level Security
  • Database quotas bound anonymous creation and per-group writes; a writer-only RPC can replace compromised sharing links. See the database security controls for limits and token rotation.
  • Groups cannot be guessed (cryptographically random IDs and tokens)

Getting Started

Prerequisites

  • Node.js 26 (used in CI), or the Node.js 24 line starting at 24.3
  • pnpm 12.16.1 (pinned in package.json)
  • Docker Desktop (Linux containers) for local Supabase and full-stack tests
  • A hosted Supabase project only when working against a deployed backend
  • For mobile development: the project-local Expo CLI (pnpm mobile)
  • For iOS development: Xcode
  • For Android development: Android Studio

1. Clone and Install

git clone https://github.com/clFaster/TeilFair.git
cd TeilFair
pnpm install

See dependency advisories for the CI audit gate and the remaining accepted audit findings.

2. Set Up Supabase

For local development, no hosted project or credentials are required:

pnpm aspire:start

Open the printed dashboard link and follow the web resource endpoint. This starts local Supabase, applies migrations, and injects its public settings into Vite. Run pnpm test:stack for the full-stack API and desktop/mobile browser suite. See local development and testing for setup and cleanup, and schema-first database development for DB changes.

The following instructions apply when configuring a hosted project:

  1. Create a new project at supabase.com (free tier is fine)
  2. Link the project with pnpm exec supabase link.
  3. For a new, empty database, review pnpm exec supabase db push --dry-run --remote, then apply with pnpm exec supabase db push --remote.
  4. Existing databases must reconcile their retired migration history before using the single baseline; follow the database workflow. Future schema changes start in supabase/schemas/ and generate migrations with pnpm db:diff --file describe_the_change.
  5. In Settings > API, copy:
    • Project URL: https://[project-id].supabase.co
    • Anon Public Key: The public API key
    • Service Role Key: Keep this safe, only for backend use

The initial schema includes member_id indexes on expense payers and splits, supporting foreign-key checks and member-deletion cascades. It also retains the expense-date and group-token indexes: Supabase's unused-index notices alone do not establish that they are unnecessary. Review representative query plans and the statistics collection period before removing them.

The internal access check lives in the private schema. Keep private out of the Supabase Data API's exposed schemas. Clients continue to call public.get_group. The two SECURITY DEFINER execution warnings for get_group are intentional: capability links work without login, and this function checks the supplied group token before returning data, hiding the write token from readers. Revoking its execution privilege or making it SECURITY INVOKER would break that access path.

3. Configure Environment Variables

For Web (packages/web/.env):

VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key

Create the file if it doesn't exist:

cd packages/web
cat > .env << EOF
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key
EOF

For Mobile (packages/mobile/.env):

EXPO_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
EXPO_PUBLIC_SUPABASE_ANON_KEY=your-anon-key

4. Run Development Servers

Web (recommended to start here):

pnpm web
# Opens at http://127.0.0.1:3000

Mobile (requires an Expo Go version supporting SDK 58, or a new development build):

pnpm mobile
# Scan the QR code with Expo Go app

The root mobile commands build the shared library first. After upgrading from SDK 57, rebuild any development clients; an existing native binary cannot load the SDK 58 runtime.

Run Tests:

pnpm test
pnpm test:coverage
pnpm typecheck:shared

The shared unit suite checks split calculations, pairwise debts, settlements, capability tokens, database conversion, and group-store success and failure paths. It uses deterministic fixtures and mocked API boundaries, with real calculation logic; no database credentials are needed. The accounting checks verify money conservation and each member's remaining balance after applying settlements, including one-cent debts and fractional splits.

pnpm test:coverage writes HTML, LCOV, and JSON reports to packages/shared/coverage/. Open packages/shared/coverage/index.html for the annotated report. CI enforces coverage for each shared business-logic file: 95% statements and lines, 90% branches, and 100% functions. Static theme/locale data, type declarations, and barrel exports are excluded; these figures do not measure web/mobile UI or database RLS coverage. CI also typechecks the tests and uploads the coverage report even when a test fails.

Run Local Migration Checks:

pnpm lint
pnpm typecheck:mobile
pnpm --filter @teilfair/web exec playwright install chromium
pnpm test:smoke
pnpm export:mobile --platform all

The smoke tests build into packages/web/dist-smoke, use placeholder Supabase settings, and block external network requests. They check production startup, routing, forms, language, and theme persistence without accessing a database. Mobile export validates JavaScript/Hermes bundles for Android, iOS, and web; device builds are a separate check.

Run Web System Tests (Playwright):

For comprehensive disposable local tests, use pnpm test:stack. The suite below is the separate production monitoring suite; its scheduled workflow still targets the production BASE_URL repository variable.

pnpm --filter @teilfair/web exec playwright install
pnpm --filter @teilfair/web run test:system

Before running, copy packages/web/.env.systemtest.example to packages/web/.env.systemtest.local and fill SYSTEM_TEST_GROUP_ID plus SYSTEM_TEST_TOKEN for a writable test group.

The system test opens the configured group, adds one expense, and removes it again.

Build All Packages:

pnpm build

Troubleshooting

pnpm install fails or missing dependencies

  • Confirm the Node.js version and use the pnpm version pinned in package.json
  • Run pnpm install --frozen-lockfile from the repository root
  • Keep the committed lockfile so dependency resolution remains reproducible

Web dev server won't start

  • Ensure .env file exists in packages/web/ with valid Supabase credentials
  • Check that port 3000 is not in use
  • Try: pnpm --filter @teilfair/web run dev --port 3001 to use a different port

Mobile app won't connect to backend

  • Verify .env in packages/mobile/ has correct Supabase URL and key
  • Ensure your phone and dev machine are on the same network
  • Try restarting the Expo dev server

RLS policy errors on Supabase

  • Confirm all migrations from supabase/migrations/ were run in order
  • Check that RLS is enabled on all tables
  • Verify the x-group-token header is being sent with requests

"Cannot find module" errors

  • Run pnpm install from the root directory
  • Clear TypeScript cache: rm -rf packages/*/dist
  • Restart your IDE

API / Data Model

Database Schema

TeilFair uses a PostgreSQL database with the following core tables:

Groups

Represents a group of people sharing expenses.

Column Type Description
id UUID Primary key, auto-generated
name TEXT Group name (e.g., "Roommates", "Trip to Greece")
currency TEXT ISO currency code (EUR, USD, GBP, etc.)
read_token TEXT Token for read-only access (32+ chars, unique)
write_token TEXT Token for full edit access (32+ chars, unique)
created_at TIMESTAMPTZ When the group was created

Relationships: One-to-many with Members, Expenses

Members

People who are part of a group and can participate in expenses.

Column Type Description
id UUID Primary key, auto-generated
group_id UUID Foreign key to groups
name TEXT Member name (e.g., "Alice", "Bob")
created_at TIMESTAMPTZ When the member was added

Relationships: Many-to-one with Groups; One-to-many with ExpensePayers and ExpenseSplits

Expenses

Tracks shared expenses and how they were paid/split.

Column Type Description
id UUID Primary key, auto-generated
group_id UUID Foreign key to groups
description TEXT What the expense was for (e.g., "Groceries")
total_amount DECIMAL(12,2) Total cost (must be > 0)
expense_date DATE When the expense occurred
created_at TIMESTAMPTZ When created

Relationships: Many-to-one with Groups; One-to-many with ExpensePayers and ExpenseSplits

ExpensePayers

Records who paid for an expense and how much they paid.

Column Type Description
id UUID Primary key, auto-generated
expense_id UUID Foreign key to expenses
member_id UUID Foreign key to members
amount DECIMAL(12,2) Amount this person paid (must be > 0)

Constraints:

  • One person can only be listed once per expense
  • Must sum to total expense amount

Relationships: Many-to-one with Expenses and Members

ExpenseSplits

Records how an expense should be split among members (who owes what).

Column Type Description
id UUID Primary key, auto-generated
expense_id UUID Foreign key to expenses
member_id UUID Foreign key to members
share DECIMAL(12,4) The share value (meaning depends on share_type)
share_type TEXT One of: 'ratio', 'fixed', 'percentage'

Share Types:

  • ratio: Proportional share (e.g., Alice:1, Bob:2 means Alice pays 1/3, Bob pays 2/3)
  • fixed: Fixed amount (e.g., Alice:10.50 means Alice owes exactly €10.50)
  • percentage: Percentage of total (e.g., Alice:50 means Alice owes 50% of total)

Relationships: Many-to-one with Expenses and Members

Data Relationships

erDiagram
    GROUP ||--o{ MEMBER : contains
    GROUP ||--o{ EXPENSE : contains
    GROUP {
        string read_token PK
        string write_token PK
    }
    MEMBER ||--o{ EXPENSE_PAYER : participates_as
    MEMBER ||--o{ EXPENSE_SPLIT : participates_as
    EXPENSE ||--o{ EXPENSE_PAYER : has
    EXPENSE ||--o{ EXPENSE_SPLIT : has
Loading

Access Control via Row Level Security (RLS)

All tables have RLS enabled. Access is controlled via the x-group-token HTTP header:

  • Read Token: Can view group data
  • Write Token: Can view and modify group data

The check_group_access() function in Supabase validates tokens before allowing any database operation.

Calculation Logic

The calculation engine (in packages/shared/src/calculations.ts) handles:

  1. Split Types:

    • ratio: Divide proportionally (e.g., 1:1:1 = equal, 2:1 = 2/3 and 1/3)
    • fixed: Exact amounts
    • percentage: Percentage of total
  2. Settlement Optimization: Uses a greedy algorithm to minimize the number of transactions needed to settle all debts.

Releasing

The web app is released at https://teilfair.moritzreis.dev. CI checks the repository; the hosted settings in Supabase, Vercel and GitHub are confirmed by hand with the production release checklist, which also lists the known limits of the release.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: pnpm test
  5. Submit a pull request

License

MIT

About

Open-source app for fair expense splitting with custom ratios, payment tracking, and balance calculation.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Sponsor this project

Used by

Contributors

Languages