Compare commits

...

2 Commits

Author SHA1 Message Date
Khalid Abdi 01dbc07e92 fix: default RELAY_URL to the hosted relay (v0.8.2)
The default http://localhost:8080 silently failed for clinics that joined
the network without setting RELAY_URL — inside Docker localhost is the
container itself, so the hub connection never reached the relay (endless
"relay unreachable" retries) and pairing QRs encoded an unreachable
localhost. Default to https://network.temetro.com so "Join Temetro Network"
works out of the box; self-hosters running their own relay still override
it. Also (re)ensure the hub is connected before pre-registering a pairing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 22:50:46 +03:00
Khalid Abdi 233ce9f854 fix: QR wallet pairing broken by multi-clinic routing (v0.8.1)
QR "scan to connect" pairing has no wallet number, so nothing registered
the request with the relay and the scanning device's response was rejected
("unknown or expired request"). The backend now pre-registers the pairing
request over the relay's new hub:expect event on POST /pair, and
re-registers still-pending requests on hub (re)connect so routing survives
a relay restart. /pair now requires the clinic to have joined the network
(clear 409, surfaced in the import dialog, localized in all five langs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 19:16:33 +03:00
15 changed files with 98 additions and 13 deletions
+24 -1
View File
@@ -7,7 +7,30 @@ for how releases are cut and published.
## [Unreleased]
## [0.8.0] — 2026-07-05
## [0.8.2] — 2026-07-05
### Fixed
- **`RELAY_URL` now defaults to the hosted relay** (`https://network.temetro.com`) instead of
`http://localhost:8080`. The old default silently failed for anyone who joined the network without
explicitly setting `RELAY_URL` — the backend's hub connection could never reach the relay (inside
Docker `localhost` is the container itself), so it never authenticated and QR pairing generated a
QR pointing at an unreachable `localhost`. Self-hosters running their own relay still override
`RELAY_URL`. Updated `.env.example` accordingly.
### Changed
- Generating a pairing QR (`POST /api/patients/wallet/pair`) now ensures the clinic's relay hub is
connected before pre-registering the request, so the routing is set up even if the connection was
opened lazily.
### Fixed
- **QR "scan to connect" pairing** was broken by the multi-clinic relay routing (v0.8.0): pairing
has no wallet number, so the clinic never sent a `wallet:send` to register the request, and the
relay rejected the scanning device's response as "unknown or expired". The clinic now
**pre-registers** the pairing request with the relay (a new `hub:expect { requestId }` event on
`POST /api/patients/wallet/pair`), so the device's response routes back correctly. On hub
(re)connect the backend re-registers its still-pending requests, so routing also survives a relay
restart. `POST /pair` now also requires the clinic to have joined the network (clear 409 instead of
a dead QR), surfaced in the import dialog.
### Added
- **Multi-clinic Temetro Network.** The relay now serves many self-hosted clinics at once. Each
+5 -1
View File
@@ -40,7 +40,11 @@ FRONTEND_PORT=3000
# /hub with its own Ed25519 signing key, so no shared secret is needed.
# RELAY_TOKEN is OPTIONAL/LEGACY — set it only for a private relay that also
# gates on a shared token (then use the SAME value here and on the relay).
RELAY_URL=http://localhost:8080
# Defaults to the hosted relay (https://network.temetro.com) when unset, so
# "Join Temetro Network" works out of the box; set RELAY_URL only to point at
# your own relay. Do NOT use http://localhost — inside Docker that's the
# container itself and the relay connection will silently fail.
RELAY_URL=https://network.temetro.com
RELAY_TOKEN=
# (Legacy, pre-relay self-hosting.) A phone-reachable URL for the QR when NOT
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "temetro-backend",
"version": "0.8.0",
"version": "0.8.2",
"private": true,
"type": "module",
"description": "temetro backend — Express + Postgres API with Better Auth (email/password, organizations) and org-scoped patient records.",
+5 -1
View File
@@ -35,7 +35,11 @@ const schema = z.object({
// its own Ed25519 signing key, so no shared secret is needed. RELAY_TOKEN is
// now *optional/legacy* — set it only for a private relay that also gates on a
// shared token (must then match the relay's RELAY_TOKEN).
RELAY_URL: z.string().min(1).default("http://localhost:8080"),
//
// Defaults to the hosted relay so "Join Temetro Network" works out of the box;
// override only when running your own relay. (A `localhost` default silently
// fails inside Docker, where localhost is the container itself.)
RELAY_URL: z.string().min(1).default("https://network.temetro.com"),
RELAY_TOKEN: z.string().default(""),
// Public, device-reachable URL of this backend's wallet relay, baked into the
// QR a patient scans. Optional — when unset we derive it from the request host
+8
View File
@@ -17,6 +17,7 @@ import {
} from "../middleware/auth.js";
import { emitToWallet } from "../realtime.js";
import { recordActivity } from "../services/activity.js";
import { connectOrg, expectResponse } from "../services/relay-client.js";
import * as patientService from "../services/patients.js";
import { awaitQuickTunnelUrl } from "../services/relay-url.js";
import { getNetworkEnabled } from "../services/signing.js";
@@ -84,6 +85,7 @@ patientsWalletRouter.post(
requirePermission({ patient: ["write"] }),
async (req, res, next) => {
try {
await requireNetwork(req.organizationId!);
const input = pairSchema.parse(req.body);
const { view, ephemeralPubKey } = await walletShare.createPairingRequest(
req.organizationId!,
@@ -91,6 +93,12 @@ patientsWalletRouter.post(
input.mode,
input.durationHours,
);
// No wallet number to `wallet:send` to yet, so pre-register the request id
// with the relay so the scanning device's response routes back to us.
// Ensure the hub is (re)connected first; if it's still mid-handshake the
// on-auth re-registration of pending requests will catch this one.
await connectOrg(req.organizationId!);
expectResponse(req.organizationId!, view.id);
res.status(201).json({
...view,
ephemeralPubKey,
+24 -5
View File
@@ -41,8 +41,17 @@ export function sendToWallet(
hubs.get(orgId)?.emit("wallet:send", { walletNumber, event, data });
}
// Tell the relay to expect a device response for `requestId` and route it back
// to this clinic — used by **QR pairing**, where there's no wallet number to
// `wallet:send` to yet, so nothing would otherwise register the request.
export function expectResponse(orgId: string, requestId: string): void {
hubs.get(orgId)?.emit("hub:expect", { requestId });
}
// Open (and authenticate) a hub connection for a clinic, if not already open.
// Idempotent — safe to call on startup and again when an org joins the network.
// Idempotent — safe to call on startup, when an org joins the network, and
// before generating a pairing QR. The socket auto-reconnects on its own, so an
// existing entry is left as-is.
export async function connectOrg(orgId: string): Promise<void> {
if (hubs.has(orgId)) return;
@@ -92,11 +101,21 @@ function registerHubHandlers(orgId: string, hub: Socket): void {
// `token` is only meaningful for a private relay (optional shared gate);
// an empty value is ignored by an open relay.
{ clinicId: publicKey, signature, token: env.RELAY_TOKEN || undefined },
(ack: { ok?: boolean } | undefined) => {
if (ack?.ok) {
console.log(`Temetro Network: clinic ${orgId} authenticated on the relay`);
} else {
async (ack: { ok?: boolean } | undefined) => {
if (!ack?.ok) {
console.warn(`Temetro Network: relay rejected clinic ${orgId}`);
return;
}
console.log(`Temetro Network: clinic ${orgId} authenticated on the relay`);
// The relay keeps routing state in memory, so re-register this clinic's
// still-pending requests — restores QR-pairing / share routing after a
// relay restart or a reconnect.
try {
for (const requestId of await walletShare.pendingRequestIds(orgId)) {
expectResponse(orgId, requestId);
}
} catch {
/* best-effort */
}
},
);
+16
View File
@@ -137,6 +137,22 @@ export async function listShareRequests(
return rows.map(toView);
}
// Ids of this clinic's still-pending share/pairing requests. Used to re-register
// them with the relay when the clinic's hub (re)connects (the relay keeps
// routing state in memory, so it's lost on a relay restart / redeploy).
export async function pendingRequestIds(orgId: string): Promise<string[]> {
const rows = await db
.select({ id: walletShareRequests.id })
.from(walletShareRequests)
.where(
and(
eq(walletShareRequests.organizationId, orgId),
eq(walletShareRequests.status, "pending"),
),
);
return rows.map((r) => r.id);
}
// Apply a response relayed back from the patient's device. On approval we
// decrypt the sealed bundle with the request's ephemeral private key and verify
// the wallet's Ed25519 signature over it (provenance: it really came from that
@@ -141,6 +141,8 @@ export function ImportFromWalletDialog({
} catch (err) {
if (err instanceof ApiError && err.status === 400) {
setError(t("patients.importApp.invalidWallet"));
} else if (err instanceof ApiError && err.status === 409) {
setError(t("patients.importApp.networkOff"));
} else {
setError(t("patients.importApp.error"));
}
@@ -171,8 +173,12 @@ export function ImportFromWalletDialog({
setPairUri(`temetro-pair:?${params.toString()}`);
setRequest(pairing);
setPhase("waiting");
} catch {
setError(t("patients.importApp.error"));
} catch (err) {
if (err instanceof ApiError && err.status === 409) {
setError(t("patients.importApp.networkOff"));
} else {
setError(t("patients.importApp.error"));
}
setPhase("error");
}
};
@@ -322,6 +322,7 @@
"expiredTitle": "انتهت صلاحية الطلب",
"expiredBody": "انتهت مهلة الطلب قبل أن يستجيب المريض.",
"invalidWallet": "لا يبدو هذا رقم محفظة صالحًا.",
"networkOff": "انضم أولاً إلى شبكة Temetro (الإعدادات ← التوقيع) للمشاركة مع تطبيقات المرضى.",
"errorTitle": "تعذّر الوصول إلى المحفظة",
"error": "يرجى التحقّق من رقم المحفظة والمحاولة مرة أخرى.",
"savedTitle": "تم استيراد المريض",
@@ -310,6 +310,7 @@
"expiredTitle": "Anfrage abgelaufen",
"expiredBody": "Die Anfrage ist abgelaufen, bevor der Patient geantwortet hat.",
"invalidWallet": "Das sieht nicht nach einer gültigen Wallet-Nummer aus.",
"networkOff": "Treten Sie zuerst dem Temetro-Netzwerk bei (Einstellungen → Signierung), um mit Patienten-Apps zu teilen.",
"errorTitle": "Wallet nicht erreichbar",
"error": "Bitte prüfen Sie die Wallet-Nummer und versuchen Sie es erneut.",
"savedTitle": "Patient importiert",
@@ -310,6 +310,7 @@
"expiredTitle": "Request expired",
"expiredBody": "The request timed out before the patient responded.",
"invalidWallet": "That doesn't look like a valid wallet number.",
"networkOff": "Join the Temetro Network first (Settings → Signing) to share with patient apps.",
"errorTitle": "Couldn't reach the wallet",
"error": "Please check the wallet number and try again.",
"savedTitle": "Patient imported",
@@ -310,6 +310,7 @@
"expiredTitle": "Demande expirée",
"expiredBody": "La demande a expiré avant que le patient ne réponde.",
"invalidWallet": "Cela ne ressemble pas à un numéro de portefeuille valide.",
"networkOff": "Rejoignez d'abord le Réseau Temetro (Paramètres → Signature) pour partager avec les applications des patients.",
"errorTitle": "Impossible de joindre le portefeuille",
"error": "Veuillez vérifier le numéro de portefeuille et réessayer.",
"savedTitle": "Patient importé",
@@ -310,6 +310,7 @@
"expiredTitle": "Codsiga waa dhacay",
"expiredBody": "Codsiga wuu dhacay ka hor inta uusan bukaanku ka jawaabin.",
"invalidWallet": "Taasi uma muuqato lambar wallet oo sax ah.",
"networkOff": "Marka hore ku biir Shabakadda Temetro (Dejinta → Saxiixa) si aad ula wadaagto abaabulka bukaannada.",
"errorTitle": "Wallet-ka lama gaari karin",
"error": "Fadlan hubi lambarka wallet-ka oo isku day mar kale.",
"savedTitle": "Bukaanka waa la soo dejiyay",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "0.8.0",
"version": "0.8.2",
"private": true,
"scripts": {
"dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "temetro",
"version": "0.8.0",
"version": "0.8.2",
"private": true,
"devDependencies": {
"shadcn": "^4.11.0"