Skip to content
ja-sompeterPublic

About

BAG ID – Smart NFC luggage identification and recovery platform.

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

BAG ID

NFC luggage identification. One web application, one public profile per physical tag.

A BAG ID tag carries a link such as https://bagid.sk/b/a8F3kP92xQ. Tapping it opens that luggage's public profile. The owner signs in, edits the profile, turns lost mode on or off, and reads messages from finders. Finders can message the owner without ever seeing the owner's private email or phone number.

BAG ID is not a GPS tracker. It contains no battery, no radio and no location hardware.


How BAG ID works

  1. Production. The BAG ID team generates a batch of tags in /admin/tags. Each tag gets a random public token and a one-time activation code; only an HMAC-SHA256 hash of the code is stored.
  2. NFC writing. A local writer (outside this web app) writes https://<site>/b/<token> to the physical tag. The browser never controls USB hardware.
  3. Attach and activate. The customer fixes the tag to their luggage, creates an account and enters the activation code. The code links the tag to the account, creates the luggage profile, and is destroyed on use.
  4. Manage the profile. From /dashboard, the owner edits luggage details, adds photos, sets travel information, chooses which fields are public and turns lost mode on or off. The tag URL never changes.
  5. Found luggage. A finder taps the tag. The public page shows only the fields the owner published and offers a contact form. The message lands in the owner's private inbox. Email and phone stay hidden unless explicitly published.
  6. Lost mode. A lost notice appears at the top of the public profile, the contact action is emphasised, and the owner can add instructions for the finder.

No app is needed on either side. BAG ID identifies luggage; it does not track location.


1. What is implemented

Area Status
Landing page (hero, how it works, features, finder preview, privacy, FAQ, CTA) Implemented
Design system (Tailwind tokens, UI primitives, responsive, mobile-first public profile) Implemented
Supabase email/password auth, email verification, login, password reset, logout Implemented
Cookie-based server sessions (@supabase/ssr) + middleware guards Implemented
Dashboard: stats, tag cards, lost mode, public preview, empty state Implemented
Full luggage editor (personal, contact, luggage, travel, privacy, status) Implemented
Dynamic public profiles /b/[token], lost mode, inactive and 404 states Implemented
Privacy: per-field visibility, private email/phone by default, auto-hide expired travel Implemented
Finder contact form → private inbox, optional email notification Implemented
Tag activation with one-time hashed activation codes Implemented
Lost luggage mode with owner message and prominent contact CTA Implemented
Admin dashboard, batch generation, CSV export, search, manual assignment, revoke/deactivate Implemented
Production API for a future local USB NFC writer + production logs Implemented (key-protected)
Database schema, indexes, RLS policies, SQL functions Implemented (supabase/migrations)
Demo data (fictional customers, two public profiles, one activatable tag) Implemented (ALLOW_DEMO_SEED=1 npm run seed)
Account deletion and tag revocation on deletion Implemented
English copy centralised for future Slovak translation Implemented (lib/i18n.ts)
SEO: metadata, Open Graph image, robots, sitemap, noindex on private pages Implemented

Not implemented (deliberately, see §11): email address change flow, admin user management UI, image garbage collection, Slovak translation, automated database integration suite, NFC writing from the browser.


2. Stack

  • Next.js 15 (App Router, React 19, Server Components, Server Actions)
  • TypeScript (strict)
  • Tailwind CSS 3.4 with a small custom design system
  • Supabase: PostgreSQL, Auth, Row Level Security, Storage
  • Lucide icons
  • Zod for server-side validation
  • No component library runtime, no state manager, no analytics, no tracking

Deployable to Vercel. Runs locally on Node.js 20.9+ (Node 22 LTS recommended).


3. Project structure

.
├─ app/
│  ├─ page.tsx                       landing page
│  ├─ layout.tsx                     root metadata, fonts, viewport
│  ├─ globals.css                    design tokens + base styles
│  ├─ not-found.tsx, error.tsx       branded 404 / error states
│  ├─ robots.ts, sitemap.ts          SEO
│  ├─ opengraph-image.tsx            generated OG image
│  ├─ icon.svg                       favicon
│  ├─ (auth)/                        login / register / forgot / reset layout+pages
│  ├─ auth/                          callback + token-hash confirm route handlers
│  ├─ actions/                       server actions: auth, tags, account, contact, admin
│  ├─ dashboard/
│  │  ├─ layout.tsx                  authenticated shell + inbox badge
│  │  ├─ page.tsx                    overview: stats, luggage cards, lost state
│  │  ├─ activate/page.tsx           tag activation
│  │  ├─ tags/[id]/edit/page.tsx     profile editor
│  │  ├─ messages/page.tsx           private inbox
│  │  └─ settings/page.tsx           account, avatar, deletion
│  ├─ b/[token]/page.tsx             public NFC profile
│  ├─ admin/                         admin overview + tag management
│  ├─ terms/, privacy/               legal pages
│  └─ api/
│     ├─ admin/tags/route.ts         POST: generate batch, return CSV with codes
│     ├─ admin/tags/export/route.ts  GET: inventory CSV
│     └─ production/tags/route.ts    machine API for the local NFC writer
├─ components/                       UI primitives, forms, editor, mockups, nav
├─ lib/
│  ├─ env.ts                         env access + configuration guards
│  ├─ supabase/{server,admin,public}.ts
│  ├─ auth.ts                        currentUser / requireUser / requireAdmin
│  ├─ validation.ts                  zod schemas
│  ├─ tokens.ts                      token + activation-code generation, hashing
│  ├─ i18n.ts                        centralised English copy
│  ├─ storage.ts                     validated image uploads
│  ├─ rate-limit.ts                  activation attempt limiter
│  ├─ notify.ts                      optional Resend email notification
│  ├─ types.ts, format.ts, csv.ts, relations.ts, cn.ts, forms.ts
├─ supabase/migrations/
│  ├─ 20261114000100_schema.sql      tables, enums, indexes, triggers
│  ├─ 20261114000200_functions.sql   public profile, contact, activation functions
│  └─ 20261114000300_policies.sql    RLS, grants, storage bucket + policies
├─ scripts/seed-demo.mjs             fictional demo data via the Admin API
├─ middleware.ts                     session refresh + route protection
├─ AGENTS.md                         Ponytail engineering rules for this repo
└─ .env.example

Ponytail: this repository follows the Ponytail ruleset — smallest complete change, reuse before invention, no dependency for a few lines, never cutting validation, security or accessibility. See AGENTS.md.


4. Create the Supabase project

  1. Sign in at https://supabase.com and create a free project.

  2. Choose a region close to Slovakia (for example eu-central-1).

  3. Open Project Settings → API and copy:

    • Project URL → NEXT_PUBLIC_SUPABASE_URL
    • publishable key → NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY (legacy anon keys also work)
    • service_role key → SUPABASE_SERVICE_ROLE_KEY (server only, never expose)
  4. Open SQL Editor and run supabase/setup.sql (or the migration files in filename order):

    supabase/migrations/20261114000100_schema.sql
    supabase/migrations/20261114000200_functions.sql
    supabase/migrations/20261114000300_policies.sql
    supabase/migrations/20261115000100_hardening.sql
    supabase/migrations/20261115000200_activation_owner_invariant.sql
    supabase/migrations/20261117000100_batch_transactions.sql
    

    Alternatively use the Supabase CLI:

    npx supabase link --project-ref <your-project-ref>
    npx supabase db push

    The migrations create the tables, enums, indexes, triggers, the public-profile and activation functions, all RLS policies, grants, the media storage bucket and its policies.

  5. Authentication → Providers → Email: keep Email enabled. For development, either confirm users by hand or set Confirm email off; for production keep confirmation on.

  6. Authentication → URL Configuration:

    • Site URL: http://localhost:3000 for local development.
    • Redirect URLs: add http://localhost:3000/auth/callback and, when deployed, https://your-domain/auth/callback.
    • Add /auth/confirm as well if you customise email templates to send {{ .TokenHash }}.
  7. Optional: Storage → confirm a public bucket named media exists (the migration creates it).

Make yourself an admin

Admin routes require profiles.is_admin = true. After registering, run in the SQL editor:

update public.profiles set is_admin = true where id = '<your-auth-user-id>';

Find the user id under Authentication → Users, or select id, full_name from public.profiles;.


5. Environment variables

Copy .env.example to .env.local:

cp .env.example .env.local
Variable Required Purpose
NEXT_PUBLIC_SUPABASE_URL yes Supabase project URL
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY yes Public publishable key (RLS-protected); NEXT_PUBLIC_SUPABASE_ANON_KEY is accepted as a legacy fallback
SUPABASE_SERVICE_ROLE_KEY yes for activation/contact/admin Server-only key; never prefix with NEXT_PUBLIC_
NEXT_PUBLIC_SITE_URL yes Base URL used in NFC links, auth redirects, CSV exports
NEXT_PUBLIC_SUPABASE_STORAGE_BUCKET no Storage bucket (default media)
RESEND_API_KEY no Enables email notifications for new messages
NOTIFICATION_FROM_EMAIL no Verified sender for Resend
CONTACT_IP_SALT recommended Salt for hashed finder IPs in rate limiting
ACTIVATION_PEPPER yes, every environment Server-only HMAC pepper for activation codes; 32+ chars, no fallback (.env.staging.local needs its own)
ACTIVATION_PEPPER_PREVIOUS no Old pepper(s), comma separated, kept for verification during a rotation (max 2)
PRODUCTION_API_KEY no Enables the local NFC writer production API

Run npm run check:supabase after applying the schema to verify the tables, auth service and media bucket.

Rotating ACTIVATION_PEPPER

  1. Move the current value to ACTIVATION_PEPPER_PREVIOUS and set the new value in ACTIVATION_PEPPER. Deploy once: new batches use the new pepper, tags printed earlier still verify with the previous one.
  2. Wait until every tag minted before the rotation is claimed.
  3. Clear ACTIVATION_PEPPER_PREVIOUS. Removing it while unclaimed tags still exist makes their codes invalid.

A batch whose CSV was lost can be re-issued from /admin/tags — per batch row, or with the batch id shown under it. Each re-issue is one database transaction: every unclaimed tag in the batch gets a new code, or nothing changes at all, and the replacement CSV downloads once. If that download never arrives, run it again: a new set is generated, because plaintext codes are never stored and a previous set cannot be recovered. Codes are valid for two years; an expired batch cannot be re-issued, so generate a new batch for the replacement tags.

Nothing secret is ever imported into a client component. Only NEXT_PUBLIC_* values reach the browser.


6. Run locally

Prerequisites: Node.js 20.9+ (22 LTS recommended) and npm.

npm install
cp .env.example .env.local     # then fill in your Supabase keys
ALLOW_DEMO_SEED=1 npm run seed # optional: fictional demo data
npm run dev

Open http://localhost:3000.

Useful commands:

npm run typecheck   # tsc --noEmit
npm run lint        # eslint
npm run build       # production build
npm start           # run the production build
ALLOW_DEMO_SEED=1 npm run seed # demo data (needs .env.local; uses the service role)

This workspace was verified with a project-local Node 22 in .tools/ (gitignored) because the machine's system Node was 18.14. Install Node 20.9+ before running the app.

Verify a change

npm run typecheck   # strict TypeScript
npm run lint        # ESLint (Next.js core web vitals)
npm run build       # production build, route and type validation

npm run test:logic covers token/CSV/redirect helpers and the demo-seed production guard. For anything touching the database, also verify manually: create two accounts, activate a demo tag, save a profile, confirm the public page reflects it immediately, send a contact message and read it in the inbox, then try to open the first customer's records while signed in as the second (it must 404 or return nothing).

Demo data

ALLOW_DEMO_SEED=1 npm run seed creates fictional customers and tags:

Login Public profile
peter@bagid.example /b/K7mPq2Xr9TaB
lucia@bagid.example /b/W4nBv8Lz3QcD
admin@bagid.example admin access

The seed generates random passwords per account and never prints them. Reset a demo account's password in Supabase Auth if you need to sign in. It also creates an unassigned tag with public token R6tYs3Hd8VfE; its activation code is not printed. The seed refuses to run when NODE_ENV/VERCEL_ENV is production and requires the explicit confirmation above. Re-running the seed replaces the demo tags; it never touches other accounts.

If this project was seeded before this guard was added, reset or delete the demo admin@bagid.example account in Supabase Auth. The seed does not change passwords on existing accounts, so an old known password would otherwise remain valid.

Peter's profile: black Samsonite suitcase, Vienna → Barcelona, Austrian Airlines OS391, 12–21 June 2026. Lucia's profile: green Osprey backpack, Bratislava → Lisbon, TAP TP1235 — deliberately different so you can see that each URL resolves to its own database record.

Demo login emails use @bagid.example, which cannot receive mail. Confirm those users in Supabase if email confirmation is enabled (the seed already marks them confirmed).


7. Database design

Normalised schema, all timestamps, foreign keys and indexes in supabase/migrations/20261114000100_schema.sql.

  • profiles — one row per auth user (id = auth.users.id), name, public contact email, phone, alternative contact, avatar, language, is_admin
  • tags — token (public, unique, random), optional nfc_uid, owner_id, status (unassigned | pending_activation | active | inactive | lost | revoked), activation_code_hash, activation_expires_at, activated_at, batch_id
  • luggage_profiles — one per tag (tag_id unique), owner, luggage fields, lost state and message, travel fields, image URL
  • privacy_settings — one per luggage profile: name/avatar/email/phone/alt-contact visibility, luggage-detail visibility, travel visibility, airline/flight/date visibility, contact-form switch, auto-hide expired travel
  • contact_messages — sender name/email/message, hashed IP, read_at
  • production_batches — batch name, tag count, code generation, creator
  • production_logs — per-tag write/verify/lock records with NFC UID and error text

Enums: tag_status, luggage_type. Lost mode is stored on luggage_profiles.is_lost (single source of truth); the lost enum value remains available for tag-level workflows.

Why tokens are safe

  • 14 characters from a 57-symbol alphabet, generated with crypto.randomBytes and rejection sampling (~81 bits of entropy). Never sequential, never the database id.
  • Unique index on tags.token.
  • Activation codes: 10 characters from a 32-symbol unambiguous alphabet, displayed as XXXX-XXXX-XX, stored as HMAC-SHA256 hashes, single-use (cleared atomically on claim), 2-year expiry.
  • The public URL alone cannot claim a tag: activation additionally requires the secret code.

8. Security model

RLS on every exposed table. Policies live in 20261114000300_policies.sql.

  • anon has no table privileges at all — not even SELECT on luggage_profiles.
  • Authenticated customers can read only their own profiles, tags, luggage_profiles, privacy_settings and contact_messages (via ownership exists checks).
  • Column-level grants prevent customers from editing owner_id, tag_id, is_admin, timestamps or tag status. Ownership of a tag can never be changed from the client.
  • Public profile data is returned only by get_public_profile(token), a SECURITY DEFINER function that reads the privacy settings and returns just the allowed fields. Email/phone are null unless the owner explicitly published them. Inactive/revoked/unassigned tags return only their status.
  • Contact messages are inserted by submit_contact_message(...), a SECURITY DEFINER function callable only by service_role; it validates lengths, checks the contact-form setting, and enforces two rate limits (5 per 10 minutes per hashed IP, 15 per hour per profile).
  • Tag activation runs through activate_tag(...), also service_role only, with FOR UPDATE locking, expiry checks and code clearing.
  • Admin routes are server-guarded (requireAdmin), and admin API routes re-check is_admin.
  • Public profiles, dashboard, admin, auth and API routes are noindex.
  • Sessions use HttpOnly cookies via @supabase/ssr; middleware refreshes them and redirects unauthenticated visitors.
  • Security headers (nosniff, DENY framing, strict referrer policy, restricted permissions) are set in next.config.ts.
  • Activation attempts are limited per user in memory (lib/rate-limit.ts).

Service-role key is used only in lib/supabase/admin.ts and only from server actions, route handlers and server components. It never appears in client bundles.


9. NFC production workflow

  1. Admin generates a batch in /admin/tags (1–100 tags). The server creates unassigned tags with random tokens, hashed activation codes and an expiry, and streams a CSV containing: batch, tag_id, token, public_url, activation_code, activation_expires_at, nfc_uid. That CSV is the only copy of the activation codes — store it safely.
  2. A local writer (Python + USB) writes public_url to each tag.
  3. The customer activates the tag in the dashboard using the code from the CSV/label.
  4. The tag is now active and links to the customer's editable public profile. No re-writing is needed when the profile changes.

Production API (future USB writer)

Key-protected (x-api-key: $PRODUCTION_API_KEY, constant-time comparison). Disabled when the key is empty.

# List tags needing writing (or filter a batch)
curl -H "x-api-key: $PRODUCTION_API_KEY" \
  "http://localhost:3000/api/production/tags?batch=<batch-uuid>"

# Record a write / verification / lock result
curl -X POST "http://localhost:3000/api/production/tags" \
  -H "x-api-key: $PRODUCTION_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"token":"<token>","nfc_uid":"04:A2:33:...","status":"verified"}'

Valid statuses: pending, written, verified, failed, locked. Results appear in production_logs and in the admin production history. The browser never touches the USB device.


10. Deploy to Vercel

  1. Push this repository to GitHub (.env.local is ignored; only .env.example is committed).
  2. Import the repository at https://vercel.com/new. Framework preset: Next.js. No custom build command is needed.
  3. Add the environment variables from §5 in Project → Settings → Environment Variables. Set NEXT_PUBLIC_SITE_URL to your production URL (for example https://bagid.sk).
  4. In Supabase Authentication → URL Configuration, set the Site URL to that domain and add https://your-domain/auth/callback to Redirect URLs.
  5. Deploy. Then verify:
    • / renders and /register creates an account (confirmation email arrives).
    • A demo tag URL opens the correct profile on a phone.
    • Contact form messages appear in /dashboard/messages.
    • https://your-domain/robots.txt disallows /b/, /dashboard, /admin.

Do not try to host this on GitHub Pages: the app needs server routes, server actions and cookie sessions.


11. Known limitations and next steps

  • Email notifications are optional. Without RESEND_API_KEY + NOTIFICATION_FROM_EMAIL, messages are stored and shown in the inbox, and the UI says notifications are not configured. No email is claimed to have been sent.
  • Email change is not exposed in the UI; the account email is managed by Supabase Auth. Use the Supabase dashboard or add a verified change-email flow.
  • Slovak translation is prepared structurally (lib/i18n.ts dictionaries) but not translated. Add a sk dictionary and a locale selector.
  • Image cleanup: replacing an avatar or luggage photo leaves the old file in Storage. shortcut: upgrade when storage volume matters.
  • Storage visibility: the media bucket is public so NFC profiles load for anonymous finders. Image URLs are unguessable but not access-controlled; do not upload sensitive documents.
  • Manual tag assignment needs the customer's Supabase user ID (admin → Tags). The normal, auditable path remains the one-time activation code.
  • Rate limiting for activation is per server instance; use Redis/Upstash if abuse appears. Contact-message limits are enforced in PostgreSQL and survive restarts.
  • NFC writing is not performed by the web app, by design. Only the production API and CSV export are provided for the local writer.
  • Automated tests: npm run test:logic covers token/CSV/redirect helpers and the demo-seed production guard. supabase/tests/activation_invariants.sql is a rollback-only database test for activation ownership and revocation; run it against a disposable/local Supabase database.
  • Terms and privacy are practical starting templates for a student company, not legal advice.

12. Verification performed

npm run typecheck   # passes
npm run lint        # passes
npm run build       # passes (production build)

Because no Supabase project was configured in this workspace, end-to-end database flows (register → confirm → activate → contact → inbox) could not be executed here. The SQL migrations and RLS policies are included and documented above; run them before testing those flows.


13. License

Source code: MIT. Brand name, logo and product concept: BAG ID.

About

BAG ID – Smart NFC luggage identification and recovery platform.

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages