# PerfectRide Partner API: sample server (Node)

A reference partner in one file. No dependencies. Node 18 or newer.

It hosts the endpoints PerfectRide calls, checks every signature and timestamp,
keeps trips in memory, and drives a trip through its events (assign, location,
arrive, start with the rider's code, complete), sending each one signed to
PerfectRide with a unique `event_id` and retrying on 409, 429 and 5xx.

Spec: https://developers.perfectride.io/docs

## Quickstart (5 minutes)

1. Get your sandbox keys from PerfectRide: your `prk_test_` key, the shared
   secret, and the key PerfectRide will use to call you.

2. Start the server:

   ```bash
   PR_API_KEY=prk_test_xxx \
   PR_SECRET=your_shared_secret \
   OUR_KEY=the_key_perfectride_uses \
   node server.js
   ```

   On Windows PowerShell: `$env:PR_API_KEY="prk_test_xxx"; $env:PR_SECRET="..."; $env:OUR_KEY="..."; node server.js`

3. Make it reachable over HTTPS (for example with a tunnel) and give PerfectRide
   the base URL, plus `<base URL>/webhook` as your webhook URL.

4. Book a test trip from the PerfectRide sandbox. The terminal shows:

   ```
   [book] t_1 for pr_55a9. Type "run t_1 <code>" to drive it.
   ```

5. Type `run t_1 4821` with the rider's 4-digit code from the sandbox app. The
   server sends `trip.driver_assigned`, `trip.driver_location`,
   `trip.driver_arrived`, `trip.started` (with the code), another location, and
   `trip.completed` with the quoted price.

## Commands

Type in the terminal, or POST from the same machine to
`http://localhost:8787/_control/<trip id>/<action>` with an optional JSON body
`{ "pin": "4821" }`.

| Command | Sends |
|---|---|
| `trips` | Lists trips in memory |
| `assign t_1` | `trip.driver_assigned` |
| `location t_1` | `trip.driver_location` |
| `arrive t_1` | `trip.driver_arrived` |
| `start t_1 4821` | `trip.started` with `pin` |
| `complete t_1` | `trip.completed` with `final_price` |
| `cancel t_1` | `trip.cancelled` by the driver |
| `nodriver t_1` | `trip.no_driver` |
| `rate t_1` | `trip.rider_rated` |
| `run t_1 4821` | The whole happy path |

A wrong code gets 422 `wrong_pin`: run `start` again with the right one. After 5
wrong codes PerfectRide answers `pin_locked`.

## Settings

| Variable | Meaning |
|---|---|
| `PR_API_KEY` | Your key for calling PerfectRide (`prk_test_...` in sandbox) |
| `PR_SECRET` | The shared signing secret |
| `OUR_KEY` | The key PerfectRide uses to call you |
| `PR_EVENTS_URL` | Default `https://www.perfectride.io/api/partner/v1/events` |
| `PORT` | Default `8787` |
| `BASE_PATH` | A prefix your endpoints live under, for example `/pr` |
| `WEBHOOK_PATH` | Where PerfectRide sends you events. Default `/webhook` |
| `NO_SUPPLY` | `1` answers every quote with `{ "available": false }` |

## What it shows

- Signing: `sha256=` + HMAC-SHA256 of `"<timestamp>.<METHOD>.<path>.<body>"`.
  Paths are relative to your base URL, with the query string. Events to us use
  `/events`; events we send you use `/`.
- Requests older or newer than 300 seconds are refused with 401.
- `POST /trips` and cancel are idempotent by `Idempotency-Key`.
- Each event is retried with the same `event_id`, a fresh timestamp and a fresh
  signature, waiting 1 s, then doubling up to 1 hour, for 24 hours.

This is a sample. Trips live in memory and are lost on restart. Keep keys and the
secret on your server only.

## server.js

Save this as `server.js` and run `node server.js`.

```js
#!/usr/bin/env node
// PerfectRide Partner API v1: a reference partner server.
// Zero dependencies. Node 18+ (node:http, node:crypto, global fetch).
//
// What it does:
//   - Hosts the endpoints PerfectRide calls: POST /quotes, POST /trips,
//     POST /trips/:id/cancel, GET /trips/:id, plus the optional
//     POST /trips/:id/rating and GET /settlements?date=YYYY-MM-DD.
//   - Receives the events PerfectRide sends you at WEBHOOK_PATH (signed with path "/").
//   - Checks every call: Bearer key, X-PR-Timestamp within 300 s, X-PR-Signature.
//   - Keeps trips in memory and drives them through the trip events, which it
//     POSTs signed to PerfectRide with a unique event_id, retrying on 409/429/5xx.
//
// Env:
//   PR_API_KEY     your key for calling PerfectRide (prk_test_...)
//   PR_SECRET      the shared signing secret
//   OUR_KEY        the key PerfectRide uses to call you
//   PR_EVENTS_URL  default https://www.perfectride.io/api/partner/v1/events
//   PORT           default 8787
//   BASE_PATH      optional prefix your endpoints live under (for example /pr)
//   WEBHOOK_PATH   where PerfectRide sends you events, default /webhook
//   NO_SUPPLY=1    answer every quote with { available: false }
//
// Drive a trip from the terminal (type "help") or over HTTP from this machine:
//   curl -X POST localhost:8787/_control/t_1/run -d '{"pin":"4821"}'

"use strict";

const http = require("node:http");
const crypto = require("node:crypto");
const readline = require("node:readline");

const PR_API_KEY = process.env.PR_API_KEY || "";
const PR_SECRET = process.env.PR_SECRET || "";
const OUR_KEY = process.env.OUR_KEY || "";
const PR_EVENTS_URL = process.env.PR_EVENTS_URL || "https://www.perfectride.io/api/partner/v1/events";
const PORT = Number(process.env.PORT || 8787);
const BASE_PATH = (process.env.BASE_PATH || "").replace(/\/$/, "");
const WEBHOOK_PATH = process.env.WEBHOOK_PATH || "/webhook";
const NO_SUPPLY = process.env.NO_SUPPLY === "1";

const WINDOW_SECONDS = 300;
const MAX_BODY = 64 * 1024;
const RETRY_FOR_MS = 24 * 60 * 60 * 1000; // keep trying for 24 hours
const RETRY_CAP_MS = 60 * 60 * 1000; // never wait more than 1 hour between tries

for (const [name, v] of [["PR_API_KEY", PR_API_KEY], ["PR_SECRET", PR_SECRET], ["OUR_KEY", OUR_KEY]]) {
  if (!v) console.warn(`[warn] ${name} is not set`);
}

// ---------- signing ----------

function signature(secret, ts, method, path, body) {
  return crypto.createHmac("sha256", secret).update(`${ts}.${method}.${path}.${body}`, "utf8").digest("hex");
}

function safeEqual(a, b) {
  const x = Buffer.from(a, "utf8");
  const y = Buffer.from(b, "utf8");
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

/** Returns null when the request is good, else an error code. */
function checkRequest(req, signedPath, body) {
  const auth = req.headers["authorization"] || "";
  const key = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
  if (!key || !OUR_KEY || !safeEqual(key, OUR_KEY)) return "unauthorized";
  const ts = String(req.headers["x-pr-timestamp"] || "");
  if (!/^\d{9,11}$/.test(ts) || Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > WINDOW_SECONDS) return "stale_timestamp";
  const got = String(req.headers["x-pr-signature"] || "").replace(/^sha256=/i, "").toLowerCase();
  const want = signature(PR_SECRET, ts, req.method, signedPath, body);
  if (!/^[0-9a-f]{64}$/.test(got) || !safeEqual(got, want)) return "bad_signature";
  return null;
}

// ---------- state (in memory) ----------

const quotes = new Map(); // quote_id -> quote
const trips = new Map(); // partner_trip_id -> trip
const idem = new Map(); // Idempotency-Key -> { status, body }
const seenEvents = new Set(); // event_id of events PerfectRide sent us
let tripSeq = 0;

const DRIVER = { id: "d_771", name: "Musa A.", rating: 4.9, trips: 2140 };
const VEHICLE = { make: "Toyota", model: "Corolla", color: "Black", plate: "PHC-123-AB" };

function newId(prefix) {
  return `${prefix}_${crypto.randomBytes(5).toString("hex")}`;
}

function haversineKm(a, b) {
  const r = (d) => (d * Math.PI) / 180;
  const dLat = r(b.lat - a.lat);
  const dLng = r(b.lng - a.lng);
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(r(a.lat)) * Math.cos(r(b.lat)) * Math.sin(dLng / 2) ** 2;
  return 6371 * 2 * Math.asin(Math.sqrt(h));
}

function priceKobo(pickup, dropoff, rideClass) {
  const km = haversineKm(pickup, dropoff);
  const mult = { standard: 1, comfort: 1.3, premium: 1.8 }[rideClass] || 1;
  const naira = Math.max(2000, 1000 + km * 350) * mult;
  return Math.round(naira / 100) * 100 * 100; // whole hundreds of naira, in kobo
}

function publicTrip(t) {
  return {
    partner_trip_id: t.partner_trip_id,
    pr_trip_id: t.pr_trip_id,
    status: t.status,
    driver: t.driver || undefined,
    vehicle: t.vehicle || undefined,
    location: t.location || undefined,
    updated_at: t.updated_at,
  };
}

function touch(t, status) {
  if (status) t.status = status;
  t.updated_at = new Date().toISOString();
}

// ---------- sending events to PerfectRide ----------

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

/**
 * POST one signed event. Same event_id on every try; a fresh timestamp and
 * signature each time. 200 = done (applied or duplicate). 409 / 429 / 5xx /
 * network = retry with backoff (1 s, doubling, up to 1 hour, for 24 hours).
 * 400 / 401 / 404 / 422 = stop and report.
 */
async function sendEvent(trip, event, extra = {}) {
  const payload = {
    event,
    event_id: newId("ev"),
    partner_trip_id: trip.partner_trip_id,
    pr_trip_id: trip.pr_trip_id,
    occurred_at: new Date().toISOString(),
    ...extra,
  };
  const body = JSON.stringify(payload);
  const started = Date.now();
  let wait = 1000;
  for (let attempt = 1; ; attempt++) {
    const ts = Math.floor(Date.now() / 1000).toString();
    let status = 0;
    let data = null;
    let retryAfter = 0;
    try {
      const res = await fetch(PR_EVENTS_URL, {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${PR_API_KEY}`,
          "x-pr-timestamp": ts,
          "x-pr-signature": `sha256=${signature(PR_SECRET, ts, "POST", "/events", body)}`,
        },
        body,
        signal: AbortSignal.timeout(10_000),
      });
      status = res.status;
      retryAfter = Number(res.headers.get("retry-after") || 0) * 1000;
      data = await res.json().catch(() => null);
    } catch (e) {
      data = { error: { code: "network", message: String(e && e.message ? e.message : e) } };
    }
    const code = data && data.error ? data.error.code : data && data.result;
    console.log(`[out] ${event} ${payload.event_id} try ${attempt} -> ${status || "no answer"} ${code || ""}`);
    if (status >= 200 && status < 300) return { ok: true, status, data };
    const retry = status === 0 || status === 409 || status === 429 || status >= 500;
    if (!retry) return { ok: false, status, data };
    if (Date.now() - started + wait > RETRY_FOR_MS) return { ok: false, status, data, gaveUp: true };
    await sleep(Math.max(wait, retryAfter));
    wait = Math.min(wait * 2, RETRY_CAP_MS);
  }
}

// ---------- trip actions (what your driver app would trigger) ----------

const ACTIONS = {
  async assign(t) {
    t.driver = DRIVER;
    t.vehicle = VEHICLE;
    t.location = { lat: t.pickup.lat + 0.004, lng: t.pickup.lng + 0.004 };
    touch(t, "driver_assigned");
    return sendEvent(t, "trip.driver_assigned", { driver: DRIVER, vehicle: VEHICLE, eta_seconds: 240, location: t.location });
  },
  async location(t) {
    const base = t.location || t.pickup;
    t.location = { lat: +(base.lat - 0.001).toFixed(6), lng: +(base.lng - 0.001).toFixed(6) };
    touch(t);
    return sendEvent(t, "trip.driver_location", { location: t.location });
  },
  async arrive(t) {
    t.location = { lat: t.pickup.lat, lng: t.pickup.lng };
    touch(t, "driver_arrived");
    return sendEvent(t, "trip.driver_arrived");
  },
  async start(t, arg) {
    const pin = String(arg && arg.pin ? arg.pin : arg || "");
    if (!/^\d{4}$/.test(pin)) return { ok: false, data: { error: { code: "local", message: "start needs the rider's 4-digit code" } } };
    const r = await sendEvent(t, "trip.started", { pin });
    if (r.ok) touch(t, "started");
    else if (r.data && r.data.error && r.data.error.code === "wrong_pin") console.log("[driver] wrong code: ask the rider again");
    else if (r.data && r.data.error && r.data.error.code === "pin_locked") console.log("[driver] code locked: the rider contacts PerfectRide support");
    return r;
  },
  async complete(t) {
    t.location = { lat: t.dropoff.lat, lng: t.dropoff.lng };
    touch(t, "completed");
    t.completed_at = new Date().toISOString();
    return sendEvent(t, "trip.completed", { final_price: t.price }); // the quoted price is final
  },
  async cancel(t) {
    touch(t, "cancelled");
    return sendEvent(t, "trip.cancelled", { cancelled_by: "driver", reason: "driver_cancelled" });
  },
  async nodriver(t) {
    touch(t, "no_driver");
    return sendEvent(t, "trip.no_driver");
  },
  async rate(t) {
    return sendEvent(t, "trip.rider_rated", { stars: 5, tags: ["polite"] });
  },
  /** The happy path end to end. */
  async run(t, arg) {
    for (const step of ["assign", "location", "arrive"]) {
      const r = await ACTIONS[step](t);
      if (!r.ok) return r;
      await sleep(500);
    }
    const s = await ACTIONS.start(t, arg);
    if (!s.ok) return s;
    await sleep(500);
    const l = await ACTIONS.location(t);
    if (!l.ok) return l;
    await sleep(500);
    return ACTIONS.complete(t);
  },
};

async function runAction(tripId, action, arg) {
  const t = trips.get(tripId);
  if (!t) return { ok: false, data: { error: { code: "local", message: `no trip ${tripId}` } } };
  const fn = ACTIONS[action];
  if (!fn) return { ok: false, data: { error: { code: "local", message: `unknown action ${action}` } } };
  return fn(t, arg);
}

// ---------- HTTP ----------

function send(res, status, body) {
  const s = JSON.stringify(body);
  res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(s) });
  res.end(s);
}

const errBody = (code, message) => ({ error: { code, message } });

function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    req.on("data", (c) => {
      size += c.length;
      if (size > MAX_BODY) {
        reject(new Error("too_large"));
        req.destroy();
      } else chunks.push(c);
    });
    req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
    req.on("error", reject);
  });
}

function isLocal(req) {
  const a = req.socket.remoteAddress || "";
  return a === "127.0.0.1" || a === "::1" || a === "::ffff:127.0.0.1";
}

/** Replays the stored answer for a repeated Idempotency-Key. */
function idempotent(req, res, scope, make) {
  const key = String(req.headers["idempotency-key"] || "");
  if (key && idem.has(`${scope}|${key}`)) {
    const prev = idem.get(`${scope}|${key}`);
    return send(res, prev.status, prev.body);
  }
  const out = make();
  if (key && out.status < 300) idem.set(`${scope}|${key}`, out);
  return send(res, out.status, out.body);
}

async function handle(req, res) {
  const url = new URL(req.url, "http://localhost");
  let body;
  try {
    body = req.method === "GET" ? "" : await readBody(req);
  } catch {
    return send(res, 413, errBody("too_large", "Body over 64 KB"));
  }

  // Local control: drive a trip without a driver app. This machine only.
  const ctl = /^\/_control\/([^/]+)\/([a-z]+)$/.exec(url.pathname);
  if (ctl && req.method === "POST") {
    if (!isLocal(req)) return send(res, 403, errBody("forbidden", "Control is local only"));
    let arg = {};
    try { arg = body ? JSON.parse(body) : {}; } catch { /* no args */ }
    return send(res, 200, await runAction(ctl[1], ctl[2], arg));
  }
  if (url.pathname === "/_control/trips" && req.method === "GET" && isLocal(req)) {
    return send(res, 200, [...trips.values()].map(publicTrip));
  }

  // Events PerfectRide sends you: signed with path "/".
  if (url.pathname === WEBHOOK_PATH && req.method === "POST") {
    const bad = checkRequest(req, "/", body);
    if (bad) return send(res, 401, errBody(bad, "Rejected"));
    let ev;
    try { ev = JSON.parse(body); } catch { return send(res, 400, errBody("invalid_json", "Body is not JSON")); }
    if (!ev || typeof ev.event_id !== "string") return send(res, 400, errBody("invalid_event", "event_id is required"));
    if (seenEvents.has(ev.event_id)) return send(res, 200, { ok: true, result: "duplicate" });
    seenEvents.add(ev.event_id);
    console.log(`[in] ${ev.event} ${ev.event_id}`, JSON.stringify(ev));
    return send(res, 200, { ok: true, result: "applied" });
  }

  if (BASE_PATH && !url.pathname.startsWith(BASE_PATH)) return send(res, 404, errBody("not_found", "Not found"));
  const path = url.pathname.slice(BASE_PATH.length) || "/";
  const signedPath = path + url.search;

  const bad = checkRequest(req, signedPath, body);
  if (bad) return send(res, 401, errBody(bad, "Rejected"));

  let json = {};
  if (body) {
    try { json = JSON.parse(body); } catch { return send(res, 400, errBody("invalid_json", "Body is not JSON")); }
  }

  // POST /quotes
  if (req.method === "POST" && path === "/quotes") {
    const { pickup, dropoff, ride_class } = json;
    if (!pickup || !dropoff || typeof pickup.lat !== "number" || typeof dropoff.lat !== "number") {
      return send(res, 400, errBody("invalid_request", "pickup and dropoff with lat/lng are required"));
    }
    if (NO_SUPPLY) return send(res, 200, { available: false });
    const q = {
      quote_id: newId("q"),
      price: priceKobo(pickup, dropoff, ride_class),
      eta_seconds: 300,
      expires_at: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
    };
    quotes.set(q.quote_id, { ...q, pickup, dropoff, ride_class });
    return send(res, 200, q);
  }

  // POST /trips (Idempotency-Key: book:<pr_trip_id>)
  if (req.method === "POST" && path === "/trips") {
    return idempotent(req, res, "book", () => {
      const q = quotes.get(json.quote_id);
      if (!q) return { status: 400, body: errBody("unknown_quote", "No such quote") };
      if (Date.parse(q.expires_at) < Date.now()) return { status: 400, body: errBody("quote_expired", "Quote expired") };
      if (!json.pr_trip_id) return { status: 400, body: errBody("invalid_request", "pr_trip_id is required") };
      // The same pr_trip_id is the same trip, even without the header.
      for (const t of trips.values()) {
        if (t.pr_trip_id === json.pr_trip_id) return { status: 201, body: { partner_trip_id: t.partner_trip_id, status: t.status } };
      }
      const t = {
        partner_trip_id: `t_${++tripSeq}`,
        pr_trip_id: json.pr_trip_id,
        rider: json.rider || {},
        price: q.price,
        pickup: q.pickup,
        dropoff: q.dropoff,
        status: "searching",
        updated_at: new Date().toISOString(),
      };
      trips.set(t.partner_trip_id, t);
      console.log(`[book] ${t.partner_trip_id} for ${t.pr_trip_id}. Type "run ${t.partner_trip_id} <code>" to drive it.`);
      return { status: 201, body: { partner_trip_id: t.partner_trip_id, status: "searching" } };
    });
  }

  const m = /^\/trips\/([^/]+)(\/cancel|\/rating)?$/.exec(path);
  if (m) {
    const t = trips.get(decodeURIComponent(m[1]));
    if (!t) return send(res, 404, errBody("unknown_trip", "No such trip"));

    // GET /trips/:id
    if (req.method === "GET" && !m[2]) return send(res, 200, publicTrip(t));

    // POST /trips/:id/cancel (Idempotency-Key: cancel:<partner_trip_id>)
    if (req.method === "POST" && m[2] === "/cancel") {
      return idempotent(req, res, "cancel", () => {
        if (t.status === "completed") return { status: 409, body: errBody("already_completed", "Trip is completed") };
        touch(t, "cancelled");
        t.cancel_reason = json.reason || null;
        return { status: 200, body: { status: "cancelled", cancellation_fee: 0 } };
      });
    }

    // POST /trips/:id/rating (optional)
    if (req.method === "POST" && m[2] === "/rating") {
      t.rating = { stars: json.stars, tags: json.tags || [], comment: json.comment || null, tip: json.tip || 0 };
      return send(res, 200, { ok: true });
    }
  }

  // GET /settlements?date=YYYY-MM-DD (optional). The day is WAT (UTC+1).
  if (req.method === "GET" && path === "/settlements") {
    const date = url.searchParams.get("date") || "";
    if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return send(res, 400, errBody("invalid_request", "date=YYYY-MM-DD is required"));
    const watDay = (iso) => new Date(Date.parse(iso) + 60 * 60 * 1000).toISOString().slice(0, 10);
    const rows = [...trips.values()]
      .filter((t) => t.status === "completed" && t.completed_at && watDay(t.completed_at) === date)
      .map((t) => ({ pr_trip_id: t.pr_trip_id, partner_trip_id: t.partner_trip_id, status: t.status, final_price: t.price, tip: t.rating ? t.rating.tip : 0 }));
    return send(res, 200, { date, trips: rows });
  }

  return send(res, 404, errBody("not_found", "Not found"));
}

const server = http.createServer((req, res) => {
  handle(req, res).catch((e) => {
    console.error(e);
    if (!res.headersSent) send(res, 500, errBody("server_error", "Something went wrong"));
  });
});

server.listen(PORT, () => {
  console.log(`Partner server on http://localhost:${PORT}${BASE_PATH || ""}`);
  console.log(`Events go to ${PR_EVENTS_URL}`);
  console.log(`PerfectRide events arrive at ${WEBHOOK_PATH}. Type "help" for commands.`);
});

// ---------- terminal commands ----------

if (process.stdin.isTTY) {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  rl.on("line", async (line) => {
    const [cmd, id, arg] = line.trim().split(/\s+/);
    if (!cmd) return;
    if (cmd === "help") {
      console.log("trips | assign <id> | location <id> | arrive <id> | start <id> <code> | complete <id> | cancel <id> | nodriver <id> | rate <id> | run <id> <code>");
      return;
    }
    if (cmd === "trips") {
      console.table([...trips.values()].map((t) => ({ id: t.partner_trip_id, pr: t.pr_trip_id, status: t.status, price: t.price })));
      return;
    }
    const r = await runAction(id, cmd, arg);
    console.log(r.ok ? "done" : `stopped: ${JSON.stringify(r.data)}`);
  });
}
```

## package.json (optional)

```json
{
  "name": "perfectride-partner-api-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Zero-dependency reference partner server for the PerfectRide Partner API v1",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "engines": {
    "node": ">=18"
  },
  "license": "MIT"
}
```
