# הארכיטקטורה המקורית

> תיעוד היסטורי. מקור: docs/architecture.md · 6a466bf.

> The additive B2C/B2B platform implementation and current integration boundaries are documented in [platform/architecture.md](/platform-architecture). The original driver demo below remains local.

# LinkNodes Energy — DigitalOps architecture

LinkNodes Energy uses Next.js App Router, React and strict TypeScript. The supplied application
is a driver-facing demonstration with sample stations and simulated charging.
Browser persistence is local to that browser; it is not a shared database, real
vehicle telemetry, a reservation, or a payment. Adding environment variables alone
does not switch the UI to production data.

## Stack and delivery boundaries

| Service       | Responsibility                      | Included / remaining                                                                                                                                                               |
| ------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Git / GitHub  | Version history and CI              | Source and Node 22 / pnpm check workflow are ready for a dedicated repository.                                                                                                     |
| Vercel        | Next.js hosting and API routes      | Build locally, then create a project and configure environment variables.                                                                                                          |
| Cloudflare    | DNS, TLS and edge protection        | Configure the owned domain and DNS against the Vercel project; follow Vercel proxy guidance.                                                                                       |
| Supabase      | PostgreSQL and storage              | SQL migration and public-key client factory supplied; no database provisioned or migration applied.                                                                                |
| Clerk         | Identity and authorization context  | Conditional Clerk provider and sign-in UI supplied; configure credentials and server authentication before protected APIs. Authentication alone does not migrate local demo data.  |
| RabbitMQ      | Durable charger commands and events | Worker topology below; no broker, producer, consumer or hardware gateway connected.                                                                                                |
| Grafana Cloud | Metrics, logs and traces            | OTLP environment contract; instrument server and worker before rollout.                                                                                                            |
| PostHog       | Product analytics                   | Optional SDK initialization behind the settings consent toggle; automatic page capture and session recording disabled. Add intentional product events before production analytics. |
| Bitwarden     | Credential management               | Store secrets in the team vault and inject them into deployment environments; never commit `.env.local`.                                                                           |

The framework choice follows an existing DigitalOps Next.js/React application;
the current screenshot defines the infrastructure providers. No provider account,
billing resource, database or domain has been created by this delivery.

## Data integration

1. Create a dedicated Supabase project and apply
   `supabase/migrations/0001_ev1.sql` with a privileged migration connection.
2. Configure a Clerk application and enable Clerk as a trusted third-party auth
   provider in Supabase, using that application's issuer. The JWT must be verified
   by Supabase and mapped to the authenticated role. A decoded `sub` alone is
   never proof of identity. Use the native Clerk integration, not an unverified
   custom token or an arbitrary client-supplied user ID.
3. Set the public URL/publishable key and Clerk public/secret keys in the correct
   server/browser scopes. Keep the Supabase service-role key exclusively in the
   backend; it bypasses row-level security.
4. The app conditionally uses its Clerk provider when
   `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` is set. Verify the middleware and
   server-side authentication with valid credentials, then pass
   `useAuth().getToken` to `createSupabaseBrowserClient(getToken)` in a data
   provider. Memoize that client. Use the anonymous client only for public
   station reads. The supplied UI still uses local demo state after sign-in.
5. Replace the demo station/favorite/vehicle adapters with Supabase queries.
   Handle loading, errors and expired sessions explicitly. Clear private cached
   data on sign-out. Demo distances are preset until the user grants location
   access; then the UI calculates straight-line distance from that location.
   Distance is intentionally not stored as a global station column. Acquire
   location only after a user action.
6. Verify RLS with two separate Clerk users and an anonymous client. User A must
   not access user B's favorites, vehicles or sessions. Clients must be unable
   to write station availability, session status, measured energy or billing.

The migration exposes only station metadata publicly. Favorites and vehicles are
owned by the Clerk subject (`auth.jwt()->>'sub'`). Sessions are readable by their
owner and writable only by the trusted backend. Vehicles are editable preferences,
not verified vehicle telemetry. No station or customer sample data is inserted
into a live database by the migration.

## Charging and payment integration still required

The driver submits a charging request to an authenticated Next.js API. The API
must validate station access, connector availability, user entitlement, a fixed
server-side tariff, and payment authorization. It writes a session and an outbox
event in one database transaction. An outbox relay publishes the event with
publisher confirmation to RabbitMQ; retried delivery is expected.

A separately hosted, persistent worker and OCPP gateway consume those commands
and communicate with chargers. A long-running WebSocket/OCPP service must not be
hosted inside a Vercel function. Choose and implement the provider's protocol
(OCPP 1.6J or 2.0.1) and authentication after selecting charger hardware.

The backend uses idempotency keys, connector locking, an explicit state machine,
retry limits and a dead-letter queue. It records `charging` only after a verified
charger acknowledgement; a UI click must not establish this state. A stop request
remains `stopping` until acknowledged. Reconcile timeouts and disconnected
chargers using provider transaction IDs and meter values. The SQL uniqueness
constraint prevents simultaneous active assignments of one connector; it is only
one part of command coordination.

Integrate a payment service using hosted/tokenized payment collection, server-side
authorization/capture, signed idempotent webhooks and reconciled receipts. Never
collect card numbers in this app or calculate final bills from browser counters.
Store currency amounts in minor units and validate tariffs on the server.

## Before real use

The local build and demo tests cannot validate cloud credentials, real RLS,
payment settlement or charger behavior. Complete integration tests for those
systems before enabling live mode. Define a freshness threshold for station
availability and display stale/offline states instead of claiming live data.
Apply endpoint rate limits, validate request bodies, verify webhook signatures,
and enforce server-side user access even when the browser is authenticated.
Add observability for stale connectors, command failures, queue age and payment
reconciliation, with private user/location/payment data redacted from telemetry.
