Skip to content
danielochubaPublic

About

A neighbourhood tool-lending board. Neighbours list tools, ask to borrow one for some dates, approve or decline requests and mark loans returned, while n8n handles notifications and overdue reminders.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

LendLoop logo

LendLoop

Borrow what you need. Lend what you don't.

📗 Table of Contents

📖 LendLoop

A neighbourhood tool-lending board. Neighbours list tools, ask to borrow one for some dates, approve or decline requests and mark loans returned, while n8n handles notifications and overdue reminders.

LendLoop is a full-stack TypeScript app:

  • Next.js App Router for the UI.
  • Clerk for sign-in and roles.
  • Convex for the database, server functions and authorization.
  • Self-hosted n8n for automation. It talks to Convex over HMAC-signed HTTP in both directions.

🛠 Built With

Tech Stack

Client
Server
  • Convex (queries, mutations, scheduled actions, HTTP actions)
  • n8n, self-hosted with Docker Compose (Postgres, task runner, Caddy, cloudflared)
Database
Tooling

Key Features

  • Borrowing.
    • Anyone can see a read-only list of tools.
    • Signed-in users browse tools by category and see whether each one is available.
    • They can ask to borrow a tool for a date range, then approve, decline, cancel or mark the loan returned.
    • The dashboard has three views: My listings, My requests and Incoming.
  • Permissions enforced in Convex.
    • Users act only on their own data.
    • Admins can remove any listing (with a reason), view all loans, mark people as Trusted Lenders and monitor the automation.
    • Every admin action is written to an audit log.
  • Reliable automation.
    • n8n sends a notification for every change to a request and a daily reminder for overdue loans.
    • It has an error workflow.
    • Calls are signed in both directions, writes back to Convex are safe to repeat, and failed calls are retried.
    • Each loan shows an activity line, e.g. "Owner notified of the request · 3 minutes ago".

(back to top)

🏗 Architecture

flowchart LR
  subgraph Browser
    UI["Next.js App Router<br/>(client components)"]
  end
  Clerk["Clerk<br/>(identity, role claim)"]
  subgraph Convex
    API["queries / mutations<br/>(userQuery, adminMutation…)"]
    DB[("users · tools · loans<br/>automationEvents · auditLog")]
    Out["outbox action<br/>(retry + backoff)"]
    HTTP["HTTP actions<br/>/n8n/* (HMAC-verified)"]
  end
  subgraph Docker["n8n stack (Docker)"]
    Tunnel["cloudflared<br/>quick tunnel"] --> Caddy["caddy<br/>/webhook/* only"] --> N8N["n8n + Postgres<br/>+ task runner"]
  end
  Discord["Discord<br/>(optional)"]

  UI -- sign in --> Clerk
  UI -- "JWT (aud=convex)" --> API
  API --> DB
  API -- "enqueue in same transaction" --> Out
  Out -- "signed POST" --> Tunnel
  N8N -- "signed POST: status write-backs,<br/>overdue list, workflow errors" --> HTTP
  HTTP --> DB
  N8N --> Discord
Loading

One request, from start to finish:

sequenceDiagram
  participant B as Borrower (browser)
  participant C as Convex
  participant N as n8n
  B->>C: loans.request (Clerk JWT)
  C->>C: validate, insert loan + automationEvent(queued) in one transaction
  C-->>B: live update: "Notifying the owner…"
  C->>N: POST /webhook/lendloop-notify (HMAC-signed, minimal payload)
  N->>N: verify signature (401 if bad), answer 202
  C->>C: event → delivered
  N->>N: mock email log (+ Discord)
  N->>C: POST /n8n/notification-status {eventId, sent} (HMAC-signed)
  C-->>B: "Owner notified of the request · just now"
Loading

Code layout

src/
  app/                    thin pages; (protected)/ for signed-in areas, admin/ for admins
  components/
    atoms/                shadcn primitives (no data access)
    molecules/            presentational compositions (no hooks, no Convex), by feature:
                          automation/ common/ layout/ loans/ tools/
    organisms/            feature blocks that call Convex hooks, by feature:
                          admin/ auth/ automation/ layout/ loans/ tools/
    templates/            page layouts
  config/routes.ts        the only place paths are written
  hooks/ lib/             useToday/useNow (clock read only in the browser), formatting
  proxy.ts                Clerk middleware: redirects only (UX); real checks live in Convex
convex/
  lib/                    auth (caller from token), function builders, guards, HMAC, signed requests
  shared/                 domain constants used by both Convex and the UI
  tools/ loans/ users/    feature modules: queries.ts, mutations.ts, rules.ts, views.ts
  admin/                  admin-only functions + audit log
  automation/             outbox, delivery, HTTP endpoints, idempotent write-backs
n8n/                      docker-compose stack, Caddyfile, workflow JSON, runbook

Design decisions

  • No Redux.
    • Convex useQuery holds the server data. It updates live, so changes made by other users appear straight away.
    • The category filter lives in the URL.
    • Forms use useState.
  • Convex queries can't read the clock.
    • The browser passes in its own local "today", which queries use to work out availability and overdue flags.
    • Mutations use the server's time, with one day of slack so that a request starting on the user's own "today" works in any timezone.
  • One loans row covers the whole lifecycle: pending → approved → returned, or declined / cancelled. Every transition is defined in one table in convex/loans/transitions.ts.
  • Deletes are soft (deletedAt), so loan history and the audit log keep their references.
  • Structure is enforced, not just intended. ESLint fails the build when:
    • a component imports from a higher atomic layer
    • a file is longer than 100 lines (except convex/seed.ts)
    • a route is written as a string anywhere other than src/config/routes.ts

(back to top)

🔐 Roles and Permissions

Where roles come from

  • The role is stored in Clerk's publicMetadata.role. Only the Clerk dashboard or a backend can write it.
  • It reaches Convex as a claim in the signed session token.
  • Convex identifies the caller only from that verified token, never from function arguments.

How checks are enforced

  • Every public function is built with userQuery, userMutation, adminQuery or adminMutation (convex/lib/functions.ts), so the auth check can't be left out.
  • Ownership is checked against ids stored in the database.
Action Visitor Signed-in user Admin
See the public tool list (name, category) ✓ ✓ ✓
See tools with lender name and availability ✓ ✓
List a tool ✓ (the owner is always the caller) ✓
Edit or delete a listing own only, and no open requests or loans own only
Remove any listing ✓ with a reason, audited
Request to borrow not own tool, valid dates, no overlap same as a user
Approve, decline or mark returned tool owner only no override
Cancel a request borrower only, while pending no override
See loans own (as borrower or owner) all loans
Set Trusted Lender ✓ audited
See email addresses never anyone else's user list only
Automation health, retry a notification ✓ retry audited
Call the n8n endpoints not callable (internal* + HMAC) not callable

Notes

  • Admins oversee but don't act on someone's behalf. An admin can see every loan but can't approve another person's request.
  • The Next.js proxy also redirects non-admins away from /admin, but that is only for user experience.
  • The tests call each forbidden function directly and expect FORBIDDEN.

(back to top)

🛡 Security and Data Minimisation

  • Authentication
    • Convex verifies Clerk JWTs: the audience must be convex and the issuer comes from an env var.
    • Only an exact role: "admin" claim counts as admin. Anything else means a plain user.
  • Validation
    • Every argument has a Convex validator.
    • The server re-checks the business rules: valid date ranges, at most 30 days per loan, a start date at most 90 days ahead, text length limits, no overlap with an approved loan, and one pending request per tool per borrower.
    • Errors are typed (UNAUTHENTICATED, FORBIDDEN, NOT_FOUND, INVALID, CONFLICT) and shown to users as friendly messages.
  • Data minimisation
    • Public list: name and category only.
    • Other participants: shown by display name and Trusted badge, never by email or id.
    • Activity lines: kind, status and time only. Error details are visible to admins only.
    • Notification payload: event name, the recipient's name and email (email is the channel), the other person's name, the tool name and the dates. No ids, messages or descriptions.
    • Overdue list: the borrower's name and email only.
    • Discord: first names only.
    • Mock email log: addresses are masked (t***@example.com).
  • HMAC-SHA256 in both directions
    • Each direction has its own secret.
    • The signed string is "<unix seconds>.<raw body>".
    • The receiver rejects a missing or invalid signature, or a timestamp more than 300 s from now, with 401.
    • Signatures are compared in constant time.
    • An endpoint that isn't configured answers 503; a body over 64 KB answers 413.
    • Request bodies are untrusted, so each field is checked by hand before calling an internal* function.
  • Exposure of n8n
    • The editor listens only on 127.0.0.1.
    • The tunnel reaches only Caddy, which forwards /webhook/* and returns 404 for everything else.
    • Code nodes run in a separate runner container that may only load the crypto module.
  • Secrets
    • Secrets live only in git-ignored env files, the Convex deployment, and n8n env vars (read as $env.*).
    • The committed workflow JSON contains no credentials, instance ids or owner data.

(back to top)

🔁 Automation Reliability

Risk How it's handled
n8n is down when a request is made Transactional outbox. The event row is written in the same mutation as the loan change, so neither is saved without the other. A scheduled action delivers it afterwards.
Convex → n8n call fails Times out after 10 s. Retries with exponential backoff at 30 s, 1 m, 2 m and 4 m, then the event is marked failed. Failed events show in the admin panel, where they can be retried.
n8n → Convex call fails Every HTTP Request node retries 3 times, 2 s apart.
Duplicates from retries and re-runs Idempotency keys notify:{loanId}:{status} and overdue:{loanId}:{date}. Write-backs update by key, never add a duplicate row, and never move a sent event back to an earlier state. Convex mutations are serializable.
Overdue workflow runs twice in a day /n8n/overdue-loans leaves out loans that already have a sent reminder for that date.
A workflow breaks An error workflow logs the failure, alerts Discord if configured, and records it in Convex. It then shows in the admin panel with a link to the failed run.
Automation isn't configured Events are recorded as skipped and the app keeps working. The admin panel lists the missing variables.

Event lifecycle: queued → delivered (n8n answered with a 2xx status) → sent (n8n confirmed the message went out). An event can also end as failed or skipped.

(back to top)

🚀 Live Demo

  • No hosted demo. The app runs locally against your own Clerk and Convex projects (see Getting Started). pnpm seed loads demo data.

(back to top)

💻 Getting Started

To get a local copy up and running, follow these steps.

Prerequisites

In order to run this project you need:

  • Node.js 22 or later
  • pnpm 11. Run corepack enable and the version is picked up from package.json.
  • A Clerk account and a Convex account (both have free tiers)
  • Docker, only for the n8n automation

Setup

Clone this repository to your desired folder:

git clone https://github.com/danielochuba/LendLoop.git
cd LendLoop

Install

Install this project with:

pnpm install
cp .env.example .env.local
pnpm convex dev

pnpm convex dev logs you in, creates a project and writes the CONVEX_* values to .env.local. Leave it running: it pushes your changes to convex/ as you work.

Connect Clerk:

  1. Create a Clerk application. Copy its publishable key and secret key into .env.local.
  2. In the Clerk dashboard, go to Integrations → Convex and activate it. Session tokens then carry aud: "convex", which convex/auth.config.ts expects.
  3. Go to Sessions → Customize session token and add the role claim:
    { "role": "{{user.public_metadata.role}}" }
  4. Tell Convex which issuer to trust. Use your Clerk Frontend API URL:
    pnpm convex env set CLERK_JWT_ISSUER_DOMAIN https://<your-instance>.clerk.accounts.dev

Connect n8n (optional). Follow n8n/README.md. In short:

  1. Fill in n8n/.env.
  2. Run docker compose up -d in n8n/.
  3. Import and publish the three workflows.
  4. Set the three automation variables below with pnpm convex env set.

Without n8n the app still works: notifications are recorded as skipped.

Environment Variables

Each direction of signing uses its own HMAC secret. Generate each secret with openssl rand -hex 32.

Where Variable Purpose
.env.local CONVEX_DEPLOYMENT, NEXT_PUBLIC_CONVEX_URL, NEXT_PUBLIC_CONVEX_SITE_URL Written by pnpm convex dev. The site URL is the base URL n8n calls.
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY Clerk keys. The secret key is a secret.
Convex (pnpm convex env set) CLERK_JWT_ISSUER_DOMAIN Required. The Clerk issuer that Convex trusts.
N8N_NOTIFY_WEBHOOK_URL https://<tunnel>/webhook/lendloop-notify
N8N_WEBHOOK_SECRET Secret. Signs Convex → n8n.
LENDLOOP_INBOUND_SECRET Secret. Verifies n8n → Convex.
n8n/.env POSTGRES_PASSWORD, N8N_ENCRYPTION_KEY, N8N_RUNNERS_AUTH_TOKEN Secrets for the n8n stack.
N8N_WEBHOOK_URL, GENERIC_TIMEZONE The tunnel's public URL; the timezone for the daily run and for "today".
LENDLOOP_CONVEX_SITE_URL https://<deployment>.convex.site
LENDLOOP_N8N_WEBHOOK_SECRET, LENDLOOP_INBOUND_SECRET The same values as Convex's N8N_WEBHOOK_SECRET and LENDLOOP_INBOUND_SECRET.
LENDLOOP_DISCORD_WEBHOOK_URL Optional real channel. Leave it empty to use the mock log only.

Usage

To run the project, execute the following command:

pnpm dev          # http://localhost:3000
pnpm seed         # optional demo data: 3 neighbours, 6 tools, an overdue loan and a pending request

To make yourself an admin:

  1. In the Clerk dashboard, go to Users → you → Metadata → Public and set { "role": "admin" }.
  2. Sign out and back in so your token picks up the claim.

Run tests

To run tests, run the following command:

pnpm test         # 92 Vitest tests: Convex functions (convex-test) + unit tests
pnpm check        # lint, typecheck, test, format check

GitHub Actions runs on every pull request and on every push to dev and main (.github/workflows/ci.yml):

Job What it checks
Check (Node 22, 24) pnpm install --frozen-lockfile, lint, typecheck, tests and format check, on the minimum and the current Node.
Production build pnpm build, with public placeholder keys (no secrets are needed to build).
Secret scan gitleaks over the whole git history.

The tests cover:

  • Permissions: every forbidden call returns FORBIDDEN, and the public list exposes no owner fields.
  • The loan lifecycle: date rules, overlaps and duplicate requests.
  • HMAC: valid, tampered, stale and missing signatures.
  • The outbox: a signed, minimal payload; backoff ending in failed; manual retry.
  • Write-backs: sending the same write-back twice changes nothing.
  • The overdue endpoint, the seed data and the activity wording.

The n8n workflows were also tested end to end against a dev deployment:

  • An unsigned call through the tunnel was rejected with 401.
  • A request went through the outbox to n8n and back, ending as sent.
  • A second overdue run on the same day sent nothing.
  • A broken write-back triggered the error workflow, which recorded the error in Convex.

Deployment

You can deploy this project using:

pnpm convex deploy     # push Convex functions to the production deployment
pnpm build             # build Next.js (e.g. on Vercel, with the .env.local values set)

On the production Convex deployment, set CLERK_JWT_ISSUER_DOMAIN (and the n8n variables if you use them). For n8n, use a named Cloudflare tunnel or another stable hostname rather than a quick tunnel (see Future Features).

(back to top)

👥 Authors

👤 Daniel Ochuba Ugochukwu

(back to top)

🔭 Future Features

What I'd change for production:

  • Stable, private n8n
    • A named tunnel or a private network instead of the quick tunnel, whose URL changes on every restart.
    • Queue mode (Redis plus workers), pinned versions and Postgres backups.
  • Secret rotation and replay protection
    • A secret manager.
    • Dual-secret verification during rotation.
    • A store of recent signatures, so a captured request can't be replayed inside the 5-minute window.
  • Exactly-once reminders
    • Reminders are currently at least once: if every write-back fails, a re-run sends the reminder again.
    • Mark a reminder sending in Convex before sending it, and page through overdue loans with a cursor instead of fetching 100 per run.
  • A real email provider (Resend or Postmark) with templates and notification preferences, and per-user timezones for due dates and reminder times.
  • Rate limits (@convex-dev/rate-limiter), pagination and search on the tool list (capped at 200 today), and tool photos via Convex file storage.
  • User sync and data retention
    • Clerk webhooks (svix) for profile changes and account deletion, plus GDPR-style export and delete.
    • Prune old automationEvents and n8n execution data.
  • Observability
    • Sentry and Convex log streams.
    • Alerts when failed events appear, instead of waiting for an admin to open the panel.
    • A paginated health panel (it shows the latest 100 events today).
  • CI and admin hardening
    • Playwright end-to-end tests and preview deployments for each PR.
    • In-app role management with audited changes, and MFA for admins.

(back to top)

🤝 Contributing

Contributions, issues, and feature requests are welcome!

Feel free to check the issues page.

Branching (Gitflow):

Branch Purpose
main Production. It only receives release merges from dev, each tagged (e.g. v1.0.0).
dev Development and integration. The default branch; every feature lands here first.
feat/*, fix/*, docs/*, ci/*, … One short-lived branch per change, cut from dev and merged back by pull request.
feat/borrow-requests ──PR──▶ dev ──release PR──▶ main (tag v1.0.0)

Conventions:

  • One branch and one PR per change into dev, merged with a merge commit so the history shows each change.
  • Conventional Commits for commit messages and PR titles.
  • CI (lint, typecheck, tests, format, build, secret scan) must pass before merging.

(back to top)

⭐️ Show your support

If you like this project, give it a ⭐️ on GitHub!

(back to top)

🙏 Acknowledgments

I would like to thank:

  • Fluence, for the brief. LendLoop borrows its parent-brand colour palette.
  • The Convex, Clerk and n8n teams, for their documentation.
  • shadcn/ui, for the component primitives.
  • Microverse, for this README template.

(back to top)

❓ FAQ

  • Why do I see "Automation is not configured" or "skipped" events?

    • The three n8n variables aren't set on your Convex deployment. The app works without them. See Install and n8n/README.md.
  • Notifications stopped arriving after I restarted Docker. Why?

    • Quick tunnel URLs change when the tunnel container restarts. Get the new URL with docker compose logs tunnel | grep trycloudflare, then update N8N_NOTIFY_WEBHOOK_URL. Failed notifications can be retried from Admin → Automation.
  • I set role: admin in Clerk, but I can't see the Admin page. Why?

    • The role comes from your session token. Sign out and back in to get a new token that includes the claim.

(back to top)

📝 License

This project is MIT licensed.

(back to top)

About

A neighbourhood tool-lending board. Neighbours list tools, ask to borrow one for some dates, approve or decline requests and mark loans returned, while n8n handles notifications and overdue reminders.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages