Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,31 @@ jobs:
- name: Test database
run: npx supabase test db

edge-functions:
name: Edge Functions
runs-on: ubuntu-latest
timeout-minutes: 10
defaults:
run:
working-directory: server/supabase/functions
steps:
- name: Check out repository
uses: actions/checkout@v6

- name: Set up Deno
uses: denoland/setup-deno@22d081ff2d3a40755e97629de92e3bcbfa7cf2ed # v2.0.5
with:
deno-version: "2.9.8"

- name: Lint
run: deno lint

- name: Type check
run: deno check probe-measurements/index.ts

- name: Run tests
run: deno test --frozen

probe:
name: Probe
runs-on: ubuntu-latest
Expand Down
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,14 @@ Backend (from `server/`):

Install dependencies with `npm ci` from `server/`, then use the Supabase CLI from the same directory. Run database tests with `npx supabase test db`. See the [README](README.md) for local setup and the CLI service commands.

Edge Functions live in `server/supabase/functions/` and use Deno 2. Run their checks from that directory:

```bash
deno lint
deno check probe-measurements/index.ts
deno test
```

Probe-facing functions set `verify_jwt = false` in `server/supabase/config.toml` and must verify `X-Probe-Token` with `_shared/probe-auth.ts`. Never log tokens, request bodies, or service keys. Commit `server/supabase/functions/deno.lock` when it changes.

For frontend changes, use the scoped commands in `server/frontend/AGENTS.md`. Run the checks for every area you change.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ npx supabase test db

Future migrations should add tests for their schema changes, constraints, functions, and RLS policies. Keep fixtures synthetic, and wrap tests in a transaction that rolls back. See the [server README](server/README.md#database-tests) for details.

#### Edge Functions

Probe-facing Edge Functions live in `server/supabase/functions/`. Their tests use [Deno](https://docs.deno.com/runtime/getting_started/installation/) 2; see the [server README](server/README.md#edge-functions) for the endpoint contract, test commands, and a local upload check.

### Frontend

```bash
Expand Down
62 changes: 62 additions & 0 deletions server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,68 @@ npx supabase test db

Future migrations should add tests for their schema changes, constraints, functions, and RLS policies. Keep fixtures synthetic, and wrap tests in a transaction that rolls back.

## Edge Functions

Probe-facing functions live in `server/supabase/functions/`. They authenticate with the `X-Probe-Token` header instead of a Supabase JWT, so each has `verify_jwt = false` in `config.toml` and checks the token itself with `_shared/probe-auth.ts`. Error bodies are always `{"error":"<code>"}` and never echo request data.

### `POST /functions/v1/probe-measurements`

Uploads the result of one script run. The body has exactly these fields: `schema_version` (1), `id` (the run UUID), `probe_id`, `test_revision_id`, `started_at`, `finished_at`, `status`, `result_code`, `result_data`, and `location`. The server sets `received_at`.

- Timestamps are RFC 3339 with `Z` or an offset and at most microsecond precision. `finished_at` must not be before `started_at`, and neither may be more than 5 minutes in the future.
- `completed` runs need `result_code` 0 and a `result_data` with exactly the revision's `definition.metrics` keys. Values are finite numbers, or `null` where the metric is `nullable` (Ping latency when every packet is lost).
- `failed` and `timeout` runs need `result_data` `{}` and an integer or `null` `result_code`.
- `location` is `null` or `{"latitude": -90..90, "longitude": -180..180, "accuracy_m": >= 0}`; `accuracy_m` is optional.

| Outcome | Status | Body |
|---|---|---|
| Saved | 201 | `{"id":"<run id>"}` |
| Identical repeat; original row and `received_at` kept | 200 | `{"id":"<run id>"}` |
| Malformed or invalid data, including metrics | 400 | `{"error":"invalid_request"}` |
| Rejected token, revoked credential, or disabled probe | 401 | `{"error":"unauthorized"}` |
| Not `POST` | 405 | `{"error":"method_not_allowed"}` |
| Run ID already saved with different data or by another probe | 409 | `{"error":"conflict"}` |
| Body over 64 KiB | 413 | `{"error":"payload_too_large"}` |
| Unknown `test_revision_id` | 422 | `{"error":"unknown_revision"}` |
| Server failure | 500 | `{"error":"internal_error"}` |

### Function tests

Install [Deno](https://docs.deno.com/runtime/getting_started/installation/) 2, then run from `server/supabase/functions/`:

```bash
deno lint
deno check probe-measurements/index.ts
deno test
```

Handler tests use a stand-in identity check and an in-memory store, so they need no running backend.

### Local function check

With the local backend running, serve the functions from `server/`:

```bash
npx supabase functions serve
```

Save the synthetic example as `/tmp/connectivity-measurement.json`:

```json
{"schema_version":1,"id":"11111111-1111-4111-8111-111111111111","probe_id":"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb","test_revision_id":"dddddddd-dddd-4ddd-8ddd-dddddddddddd","started_at":"2026-11-09T20:00:00Z","finished_at":"2026-11-09T20:00:05Z","status":"completed","result_code":0,"result_data":{"rtt_avg_ms":18.4,"packet_loss_pct":0},"location":null}
```

Then upload it with the synthetic local token:

```bash
curl -i http://127.0.0.1:54421/functions/v1/probe-measurements \
-H 'Content-Type: application/json' \
-H 'X-Probe-Token: connectivity-local-probe-token' \
--data-binary @/tmp/connectivity-measurement.json
```

The first upload returns `201`, and sending it again returns `200` with the same ID. `npx supabase db reset` clears saved measurements.

If the frontend needs Supabase locally, copy `.env.example` to `.env.local` in `server/frontend` and use values from `npx supabase status` run in `server/`:

- `NEXT_PUBLIC_SUPABASE_URL` — the local API URL.
Expand Down
10 changes: 5 additions & 5 deletions server/frontend/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export default function HomePage() {
return (
<main>
<h1>Connectivity</h1>
</main>
);
return (
<main>
<h1>Connectivity</h1>
</main>
);
}
6 changes: 6 additions & 0 deletions server/supabase/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,12 @@ deno_version = 2
# [edge_runtime.secrets]
# secret_key = "env(SECRET_VALUE)"

# Probe-facing functions authenticate with a probe token, not a Supabase JWT, so
# the platform JWT check is off. Each such function must verify the probe itself
# (see functions/_shared/probe-auth.ts). Add a block like this for every one.
[functions.probe-measurements]
verify_jwt = false

[analytics]
enabled = true
port = 54427
Expand Down
42 changes: 42 additions & 0 deletions server/supabase/functions/_shared/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// JSON response helpers shared by probe-facing Edge Functions.
//
// Every error body is {"error": "<code>"} with no message, so responses never
// echo request data and the probe can switch on a stable code.

const ERROR_STATUS = {
invalid_request: 400,
unauthorized: 401,
method_not_allowed: 405,
conflict: 409,
payload_too_large: 413,
unknown_revision: 422,
internal_error: 500,
assignment_read_failed: 500,
signing_failed: 500,
} as const;

export type ErrorCode = keyof typeof ERROR_STATUS;

const BASE_HEADERS = {
"Content-Type": "application/json",
// Responses can carry signed download links, so never let anything cache them.
"Cache-Control": "no-store",
};

export function jsonResponse(
status: number,
body: unknown,
headers: Record<string, string> = {},
): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...BASE_HEADERS, ...headers },
});
}

export function errorResponse(
code: ErrorCode,
headers: Record<string, string> = {},
): Response {
return jsonResponse(ERROR_STATUS[code], { error: code }, headers);
}
74 changes: 74 additions & 0 deletions server/supabase/functions/_shared/probe-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Probe identity check shared by check-in and upload.
//
// A probe proves who it is with its probe ID and a device token sent in the
// X-Probe-Token header. The database stores only the SHA-256 hash of each
// token, so the token is hashed here and looked up by hash.
//
// Callers must serve these functions with verify_jwt = false (probes hold no
// Supabase JWT), which makes this check the only gate in front of the data.

import type { SupabaseClient } from "npm:@supabase/supabase-js@2.119.2";

export const PROBE_TOKEN_HEADER = "X-Probe-Token";

const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export interface ProbeIdentity {
probeId: string;
}

/** Returns the canonical lowercase probe ID, or null if the value is not a UUID. */
export function parseProbeId(value: unknown): string | null {
if (typeof value !== "string" || !UUID_PATTERN.test(value)) return null;
return value.toLowerCase();
}

/** Lowercase hex SHA-256 of the UTF-8 token, matching probe_credentials.token_hash. */
export async function hashToken(token: string): Promise<string> {
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(token),
);
return Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, "0")).join("");
}

/**
* Returns the probe's identity when the token belongs to this probe, the
* credential is not revoked, and the probe is not disabled. Returns null for
* every credential failure, so callers can respond identically to all of them.
*
* Throws when the database cannot be read: that is a server failure, not a
* rejected credential. The thrown error carries no request data.
*/
export async function verifyProbeToken(
client: SupabaseClient,
probeId: string,
token: string | null,
): Promise<ProbeIdentity | null> {
if (!token) return null;

const tokenHash = await hashToken(token);

const credential = await client
.from("probe_credentials")
.select("id")
.eq("token_hash", tokenHash)
.eq("probe_id", probeId)
.is("revoked_at", null)
.maybeSingle();
if (credential.error) throw new Error("probe credential lookup failed");
if (!credential.data) return null;

const probe = await client
.from("probes")
.select("id")
.eq("id", probeId)
.is("disabled_at", null)
.maybeSingle();
if (probe.error) throw new Error("probe lookup failed");
if (!probe.data) return null;

return { probeId };
}
46 changes: 46 additions & 0 deletions server/supabase/functions/_shared/supabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Service-role Supabase client for Edge Functions.
//
// Probe tables allow access to service_role only, so probe-facing functions
// read them with this client. The key comes from the environment that Supabase
// injects into functions; it must never be logged or returned.

import {
createClient,
type SupabaseClient,
} from "npm:@supabase/supabase-js@2.119.2";

function readServiceKey(): string | undefined {
/*
This is prob unessecary.... i'll keep it here just to be safe and not sure which version supabase got rid of service role and replaced with secret.
*/
const legacyKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
if (legacyKey) return legacyKey;

const singleKey = Deno.env.get("SUPABASE_SECRET_KEY");
if (singleKey) return singleKey;

// Newer projects inject named secret keys as a JSON object.
const namedKeys = Deno.env.get("SUPABASE_SECRET_KEYS");
if (!namedKeys) return undefined;
try {
const parsed = JSON.parse(namedKeys);
return typeof parsed?.default === "string" ? parsed.default : undefined;
} catch {
return undefined;
}
}

export function createServiceClient(): SupabaseClient {
const url = Deno.env.get("SUPABASE_URL");
const key = readServiceKey();
if (!url || !key) {
throw new Error("Supabase service client is not configured");
}
return createClient(url, key, {
auth: {
persistSession: false,
autoRefreshToken: false,
detectSessionInUrl: false,
},
});
}
8 changes: 8 additions & 0 deletions server/supabase/functions/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"nodeModulesDir": "none",
"lint": {
"rules": {
"exclude": ["no-import-prefix"]
}
}
}
59 changes: 59 additions & 0 deletions server/supabase/functions/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading