Skip to Content
truemetrics Docs

Driver authentication

Add driver tokens with an AI Agent

Copy-paste prompt that lets a coding agent add driver authentication for the truemetrics module or navigation app: the key pair, the token at login, its rotation, and the handover from your courier app

How to use this prompt

The token has two sides: your backend issues it, your courier app hands it over. Paste the prompt below into your coding agent (Claude Code, Cursor, Copilot or similar) with the repository open that you want to change first, usually the backend. Paste it again in the courier app’s repository; the prompt tells the agent to do only the part that belongs to the open repository. If both live in one repository, one run does both.

Before you start, read Driver authentication once: it explains what the agent is going to build. The module or the standalone app should already be integrated (module, standalone app); the prompts for those point here for the token.

The prompt

Copy everything inside the block.

# Task: Add truemetrics driver tokens to this repository

truemetrics shows a courier the "last meter" of a delivery stop (where to park, which entrance,
the walk between) in the truemetrics last meter module inside this courier app, or in the
truemetrics standalone navigation app. That data belongs to the company and is shown only to a
driver who is logged in. For this, the company's backend issues a **driver token** at login, the
courier app hands the token to the module or the navigation app with every stop, and the
truemetrics backend checks the token before it answers. Without a token no stop shows its last
meter. This task adds that token: on the backend
side (issue it), on the app side (keep it, rotate it, hand it over), or both, depending on what
this repository is.

The full description is at https://docu.truemetrics.cloud/navigation_authentication (Markdown:
https://docu.truemetrics.cloud/navigation_authentication.md). This prompt repeats what you need.

Work in this order:
1. Find out what this repository is: the backend that the courier app logs in to, the courier app,
   or both. Analyze accordingly: the login endpoint and session handling (backend), the login flow,
   session storage, the truemetrics SDK integration (where `TruemetricsSdk.init` runs and whether
   the app already observes the SDK's status; Flutter / React Native: the truemetrics plugin) and
   the places where a stop is handed to the truemetrics module
   (`NavigationRequest`) or the truemetrics navigation app (the `google.navigation:` /
   `truemetrics.navigation://` handover) (app).
2. For EACH integration point below that applies, propose the exact file, function and line,
   explain why, and ASK ME TO CONFIRM before writing code. Ask all questions in one batch where
   possible.
3. Implement only what I confirmed. Keep changes minimal and isolated (backend: one module, e.g.
   `truemetrics_token`; app: one holder, e.g. `TruemetricsSession`).
4. Never put a private key, a token or a key ID into source code or git. Keys and secrets go into
   the existing secrets mechanism. Never log a token.

## 0. What this repository is

Tell me which parts apply: "backend" (sections 1 to 3), "app" (sections 4 to 6), or both. If the
backend is not in this repository, also tell me what the app will expect from it (section 3's
response shape), so I can hand that to whoever changes the backend.

Confirm with me before going on.

## 1. Backend: the key pair

- Generate nothing into the repository. Give me the commands to make the key pair and tell me
  where the private key has to go (the existing secrets store, like a database password):

      openssl ecparam -name prime256v1 -genkey -noout -out truemetrics-token-key.pem
      openssl ec -in truemetrics-token-key.pem -pubout -out truemetrics-token-key.pub.pem

- The public key (`truemetrics-token-key.pub.pem`) is to be sent to truemetrics
  (info@truemetrics.io) together with the name of the API key the courier app runs the truemetrics
  SDK with (if the app runs the SDK with several API keys: all of them). truemetrics registers it
  under that key's ID, switches the last meter on for the company, and tells us the ID. That ID is
  the token's `iss` and is configuration, not a secret, but keep it out of source as well. Ask me
  for it; if I do not have it yet, use a placeholder configuration value and tell me it has to be
  filled in before tokens are accepted.
- To replace the key later: a new pair, the new public key to truemetrics, the backend switched to
  the new private key once truemetrics confirms. Make the key path configurable so this needs no
  code change.
- Read the private key from configuration at startup; fail loudly if it is missing or not a P-256
  key.

Confirm with me: where the private key and the key ID are configured.

## 2. Backend: the token

A JWT signed with ES256 (ECDSA P-256, SHA-256). Use the JWT library the backend already has, or
the standard one for its language (Python: PyJWT with `cryptography`; Node.js: `jsonwebtoken` or
`jose`; Java/Kotlin: Nimbus JOSE+JWT or jjwt; .NET: `System.IdentityModel.Tokens.Jwt`; Go:
`golang-jwt`). ES256 only: `HS256` and `RS256` are not accepted. If no JWT library is available,
sign by hand: ECDSA over SHA-256 of `base64url(header) + "." + base64url(claims)`, signature as R
and S in 32 big-endian bytes each, concatenated (not DER), base64url without padding.

Header: `{"alg": "ES256", "typ": "JWT"}`, no `kid`.

Claims, all required:

| Claim | Content |
| --- | --- |
| `iss` | The ID truemetrics gave us for the API key (section 1). |
| `aud` | Exactly `truemetrics`. |
| `sub` | The driver's ID, as a string: stable per driver, different per driver. Use the identifier the backend already uses for the driver. |
| `iat` | Issue time, Unix seconds, server clock (kept right with NTP). |
| `exp` | End, Unix seconds. At most 24 hours after `iat`; a longer token is not accepted. Use 12 hours unless I say otherwise. |
| `jti` | A UUID per token. |

Implement one function, e.g. `truemetrics_driver_token(driver_id, lifetime_s=12*3600)`, with a
unit test that decodes the token with the public key and checks the claims and that
`exp - iat <= 24*3600`.

Confirm with me: the driver identifier used as `sub`, and the lifetime.

## 3. Backend: where tokens are issued

- At login: return the token with the session, in the login response, as a field of its own, e.g.
  `truemetrics: { token: "<jwt>", expires_at: "<ISO 8601, UTC>" }`. `expires_at` is the token's
  `exp`, so the app need not decode the token.
- At every shift start, and for sessions that can last longer than 24 hours (most courier apps
  keep drivers logged in for days): a fresh token without a new login. A token also stops working
  before `exp` when a newer token of the same driver was used, or when the navigation app (or,
  with the module, the courier app) was reinstalled; a fresh one at the shift start mends that.
  Prefer the request the app already makes at the start of a shift, such as loading the day's
  tour: add the same `truemetrics` field to its response. Else add an endpoint, e.g.
  `POST /truemetrics-token`, authenticated with the existing session, that returns the same
  shape.
- Do not issue a token per stop, and do not issue tokens to a session that is not authenticated.

Confirm with me: the login response change, and which request or endpoint refreshes the token.

## 4. App: keep the token

- Read `truemetrics.token` and `truemetrics.expires_at` from the login response (and from the
  refresh, section 3) and keep both with the session in the app's secure storage (Android:
  `EncryptedSharedPreferences` or whatever the app uses for its own session token; Flutter:
  `flutter_secure_storage` or the app's equivalent). Never in plain shared preferences, never in a
  log, never in a URL.
- A single accessor, e.g. `TruemetricsSession.token()`, that returns the stored token without any
  network call, or `null` when there is none or it has ended. The handover calls it on the main
  thread, so it must never block. A `null` token must not stop the handover: the stop is then
  shown without its last meter.
- The refresh (section 3) runs in the background, off the main thread, ahead of the handover:
  at every shift start (e.g. when the day's tour is loaded) and, whenever `expires_at` is less
  than an hour away, when the app comes to the front and on a timer. Offline, it tries again
  later; the stored token stays in use until it ends.
- Drop the token at logout.

Confirm with me: the storage, the accessor and the refresh triggers.

## 5. App: the phone's ID

The truemetrics SDK already runs in this app. Its device ID is the `id_phone` that goes with the
token, and with every stop also without one (truemetrics picks the company's settings by it). If
the module or app integration already keeps it (e.g. a `TruemetricsPhone` holder), use that.
Else add a holder fed by the SDK's status, not `getDeviceId()` at the moment of the handover: the
SDK answers `getDeviceId()` before truemetrics knows the ID.

    TruemetricsSdk.getInstance().observeSdkStatus().collect { status ->
        when (status) {
            is Status.Initialized -> id = status.deviceId
            is Status.RecordingInProgress -> id = status.deviceId
            is Status.DelayedStart -> id = status.deviceId
            else -> Unit
        }
    }

The ID changes every 30 days and after the app's data was cleared; the holder follows it.
Flutter / React Native: read it from the truemetrics plugin's status in the same way, and pass it
over the method channel or native module.

If the truemetrics SDK is not integrated in this app, stop and tell me: the token cannot work
without it (see https://docu.truemetrics.cloud/with_agent).

Confirm with me: where the device ID holder is.

## 6. App: hand it over

Find every place where a stop goes to the truemetrics module or navigation app and add the two
values:

- Module (`io.truemetrics.navigation`, a `NavigationRequest` per stop): the fields `token` and
  `idPhone`:

      NavigationRequest(
          destination = LatLon(stop.lat, stop.lon),
          stops = listOf(NavigationStop(id = stop.addressId)),
          routing = true,
          token = TruemetricsSession.token(),
          idPhone = TruemetricsPhone.id,
      )

- Standalone navigation app (an intent to `io.truemetrics.navigation`): the intent extras
  `token` and `id_phone`. Rules:
  - `token` and `id_phone` as intent extras only, never as query parameters of the link (they are
    ignored there: Android writes an intent's link into the system log). A handover from a web view
    or browser gets neither.
  - The intent must name the truemetrics app, `setPackage("io.truemetrics.navigation")`; without
    it the token would go to whichever app takes the link. The fallback when the truemetrics app
    is not installed is the app's original navigation call, without `token` and `id_phone`.
  - Before the handover, check that the app installed under `io.truemetrics.navigation` is signed
    by truemetrics: compare the SHA-256 fingerprint of its signing certificate
    (`PackageManager.getPackageInfo(pkg, GET_SIGNING_CERTIFICATES)`, API 28+;
    `GET_SIGNATURES` below) with the fingerprint truemetrics gave us. From Android 11 on this needs
    `<queries><package android:name="io.truemetrics.navigation" /></queries>` in the manifest; add
    it if it is missing. Ask me for the fingerprint; with none yet, implement the check against a
    configuration value and tell me it has to be filled in. If the check fails, hand over without
    the token and report it the way the app reports other integrity problems.
  - Flutter / React Native / Expo: a plain link (`url_launcher`, `Linking`) cannot carry extras.
    Use a package that starts an Android intent with a package name and extras (Flutter:
    `android_intent_plus` with `package` and `arguments`), or a small native module (React Native,
    Expo with a config plugin), which also does the signer check.

      val intent = Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${stop.lat},${stop.lon}&mode=d"))
          .setPackage("io.truemetrics.navigation")
          .putExtra("route", routeJson(tour, nextStop = index))
          .putExtra("returnApp", packageName)
          .putExtra("token", TruemetricsSession.token())
          .putExtra("id_phone", TruemetricsPhone.id)

Confirm with me: every call site, and the signature check.

## Behavior to know

- The module and the navigation app do not tell the app whether the token was accepted. A stop
  without a token or `id_phone`, or with a token that no longer works, is shown without its last
  meter (destination and building only). So the app has to keep the token valid on its own
  (section 4).
- A token stops working at `exp`, when a newer token of the same `sub` was used, after the
  navigation app (or, with the module, this app) was reinstalled or its data cleared, and on a
  phone truemetrics does not know for the company. A fresh token at every login and shift start
  covers the first three.
- One token per shift or day is right; one per stop gains nothing.
- One `sub` per driver and installation: if this app uses the module and also hands stops to the
  standalone navigation app on the same phone, issue each its own token with a distinct `sub`
  (e.g. `<driver>` for the module and `<driver>-app` for the standalone app).
- Without the public key registered at truemetrics, no stop shows its last meter. The token
  work can ship before that and be verified once truemetrics confirms.

## Done when

- Backend: the private key and the key ID come from configuration; `truemetrics_driver_token`
  (or its equivalent) issues ES256 tokens with `iss`, `aud`, `sub`, `iat`, `exp` (≤ 24 h), `jti`,
  with a unit test; the login response carries `truemetrics.token` and `truemetrics.expires_at`;
  a fresh token comes at every shift start and for sessions longer than the token.
- App: the token is kept in secure storage with `expires_at`, refreshed at the shift start and
  before it ends, dropped at logout, never logged; `id_phone` comes from the SDK's status; every
  handover to the module or the navigation app carries `token` and `idPhone` / `id_phone`; a
  handover to the navigation app names the package, checks its signer (with `<queries>` in the
  manifest), and falls back to the original call without either.
- Give me a short summary of every file changed, the commands to make the key pair, what to send
  to truemetrics (the public key, the API key's name, and the request for the signing fingerprint
  of the navigation app), and a test plan: a driver with a fresh token sees the last meter of a
  stop with known data; the same stop without the token, without `id_phone`, or with a token past
  `exp`, shows destination and building only; a new login or refresh after that works again;
  after a reinstall of the navigation app (or, with the module, this app) the last meter returns
  with the next fresh token; and, for the standalone app, the fallback when it is not installed.
  When a stop with known data shows no last meter despite a token, write to info@truemetrics.io
  with the driver's `sub`, the `id_phone`, the time and which app.

On this page