Register devices through Cloudflare API

This commit is contained in:
2026-05-08 17:54:40 -04:00
parent e8a33d53f5
commit c8ed3128ed
3 changed files with 337 additions and 6 deletions
+151 -3
View File
@@ -24,6 +24,36 @@ const DEVICE_LIST_QUERY = `
COALESCE(last_active_at, approved_at, created_at) DESC,
device_id ASC
`;
const DEVICE_REGISTER_QUERY = `
INSERT INTO user_devices (
user_id,
device_id,
public_key,
device_name,
platform,
approval_status,
created_at,
approved_at,
last_active_at,
revoked_at,
idempotency_key
) VALUES (?, ?, ?, ?, ?, 'pending', ?, NULL, ?, NULL, ?)
ON CONFLICT(user_id, idempotency_key) DO NOTHING
`;
const DEVICE_BY_IDEMPOTENCY_KEY_QUERY = `
SELECT
device_id,
public_key,
device_name,
platform,
approval_status,
created_at,
approved_at,
last_active_at,
revoked_at
FROM user_devices
WHERE user_id = ? AND idempotency_key = ?
`;
export interface DeviceListDocument {
version: 1;
@@ -31,6 +61,12 @@ export interface DeviceListDocument {
devices: DeviceDocument[];
}
export interface DeviceRegistrationDocument {
version: 1;
user_id: string;
device: DeviceDocument;
}
export interface DeviceDocument {
device_id: string;
public_key: string;
@@ -56,6 +92,16 @@ interface DeviceRow {
revoked_at: unknown;
}
interface DeviceRegistrationRequest {
deviceId: string;
publicKey: string;
deviceName: string;
platform: string;
idempotencyKey: string;
}
type DeviceRegistrationBody = Record<string, unknown>;
export class DeviceSchemaError extends Error {
constructor(message: string) {
super(message);
@@ -63,6 +109,20 @@ export class DeviceSchemaError extends Error {
}
}
export class DevicePermissionError extends Error {
constructor(message: string) {
super(message);
this.name = "DevicePermissionError";
}
}
export class DevicePersistenceError extends Error {
constructor(message: string) {
super(message);
this.name = "DevicePersistenceError";
}
}
export async function deviceListDocument(
env: Env,
context: AuthContext,
@@ -71,11 +131,79 @@ export async function deviceListDocument(
return {
version: 1,
user_id: context.userId,
devices: result.results.map((row) => deviceDocument(row, context)),
devices: result.results.map((row) => deviceDocument(row, context.deviceId)),
};
}
function deviceDocument(row: DeviceRow, context: AuthContext): DeviceDocument {
export async function registerDeviceDocument(
request: Request,
env: Env,
context: AuthContext,
nowSeconds = Math.floor(Date.now() / 1000),
): Promise<DeviceRegistrationDocument> {
const registration = await deviceRegistrationRequest(request);
if (context.deviceId !== undefined && context.deviceId !== registration.deviceId) {
throw new DevicePermissionError("device_context_mismatch");
}
await env.ELY_DB.prepare(DEVICE_REGISTER_QUERY)
.bind(
context.userId,
registration.deviceId,
registration.publicKey,
registration.deviceName,
registration.platform,
nowSeconds,
nowSeconds,
registration.idempotencyKey,
)
.run();
const row = await env.ELY_DB.prepare(DEVICE_BY_IDEMPOTENCY_KEY_QUERY)
.bind(context.userId, registration.idempotencyKey)
.first<DeviceRow>();
if (row === null) {
throw new DevicePersistenceError("device_registration_missing");
}
return {
version: 1,
user_id: context.userId,
device: deviceDocument(row, registration.deviceId),
};
}
async function deviceRegistrationRequest(request: Request): Promise<DeviceRegistrationRequest> {
let value: unknown;
try {
value = await request.json();
} catch {
throw new DeviceSchemaError("device_registration_json_invalid");
}
if (!isRecord(value)) {
throw new DeviceSchemaError("device_registration_must_be_object");
}
assertOnlyFields(value, [
"version",
"device_id",
"public_key",
"device_name",
"platform",
"idempotency_key",
]);
if (value.version !== 1) {
throw new DeviceSchemaError("device_registration_version_invalid");
}
return {
deviceId: deviceIdValue(value.device_id, "device_id"),
publicKey: publicKeyValue(value.public_key),
deviceName: deviceText(value.device_name, "device_name"),
platform: deviceText(value.platform, "platform"),
idempotencyKey: idempotencyKeyValue(value.idempotency_key),
};
}
function deviceDocument(row: DeviceRow, currentDeviceId: string | undefined): DeviceDocument {
const deviceId = deviceIdValue(row.device_id, "device_id");
return {
device_id: deviceId,
@@ -87,7 +215,7 @@ function deviceDocument(row: DeviceRow, context: AuthContext): DeviceDocument {
approved_at: nullableTimestamp(row.approved_at, "approved_at"),
last_active_at: nullableTimestamp(row.last_active_at, "last_active_at"),
revoked_at: nullableTimestamp(row.revoked_at, "revoked_at"),
current: context.deviceId === deviceId,
current: currentDeviceId === deviceId,
};
}
@@ -123,6 +251,13 @@ function approvalStatus(value: unknown): DeviceDocument["approval_status"] {
return value as DeviceDocument["approval_status"];
}
function idempotencyKeyValue(value: unknown): string {
if (typeof value !== "string" || !/^[a-zA-Z0-9._:-]{16,128}$/.test(value)) {
throw new DeviceSchemaError("idempotency_key_invalid");
}
return value;
}
function nullableTimestamp(value: unknown, label: string): number | null {
if (value === null) {
return null;
@@ -136,3 +271,16 @@ function timestamp(value: unknown, label: string): number {
}
return value;
}
function assertOnlyFields(value: DeviceRegistrationBody, fields: string[]): void {
const allowed = new Set(fields);
for (const field of Object.keys(value)) {
if (!allowed.has(field)) {
throw new DeviceSchemaError(`unexpected_field:${field}`);
}
}
}
function isRecord(value: unknown): value is DeviceRegistrationBody {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+45 -1
View File
@@ -1,6 +1,12 @@
import type { Env } from "./bindings.js";
import { withAuthenticatedApiControls, withPublicApiControls } from "./api_controls.js";
import { DeviceSchemaError, deviceListDocument } from "./devices.js";
import {
DevicePermissionError,
DevicePersistenceError,
DeviceSchemaError,
deviceListDocument,
registerDeviceDocument,
} from "./devices.js";
import {
PluginRegistrySchemaError,
parsePluginRegistryDocument,
@@ -47,6 +53,44 @@ export async function handleRequest(request: Request, env: Env): Promise<Respons
}
});
}
if (url.pathname === "/api/devices/register") {
return withAuthenticatedApiControls(
request,
env,
"devices.register",
["POST"],
async (context) => {
try {
return jsonResponse(await registerDeviceDocument(request, env, context), 201, {
"Cache-Control": "no-store",
});
} catch (error) {
if (error instanceof DevicePermissionError) {
return jsonResponse(
{ error: "device_context_mismatch" },
403,
{ "Cache-Control": "no-store" },
);
}
if (error instanceof DeviceSchemaError) {
return jsonResponse(
{ error: "invalid_device_registration" },
400,
{ "Cache-Control": "no-store" },
);
}
if (error instanceof DevicePersistenceError) {
return jsonResponse(
{ error: "device_registration_failed" },
500,
{ "Cache-Control": "no-store" },
);
}
throw error;
}
},
);
}
if (url.pathname === "/api/plugins/signing-keys") {
return withPublicApiControls(request, env, "plugins.signing_keys", ["GET"], () =>
handlePublicSigningKeys(env),
+141 -2
View File
@@ -13,6 +13,7 @@ import { handleRequest } from "../src/index.js";
const ACCESS_TOKEN = "D".repeat(48);
const PUBLIC_KEY = "a".repeat(64);
const IDEMPOTENCY_KEY = "device-register-0001";
describe("device routes", () => {
it("returns authenticated user devices from D1", async () => {
@@ -154,6 +155,133 @@ describe("device routes", () => {
assert.equal(response.status, 500);
assert.deepEqual(await response.json(), { error: "devices_invalid" });
});
it("registers the current device as a pending idempotent D1 write", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN);
const d1 = testD1Database([
{
device_id: "device-01",
public_key: PUBLIC_KEY.toUpperCase(),
device_name: "MacBook Pro",
platform: "macOS",
approval_status: "pending",
created_at: 1_780_000_100,
approved_at: null,
last_active_at: 1_780_000_100,
revoked_at: null,
},
]);
const response = await handleRequest(
new Request("https://elydora.test/api/devices/register", {
method: "POST",
headers: {
authorization: `Bearer ${ACCESS_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify(deviceRegistrationBody()),
}),
testEnv({
d1,
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
}),
);
assert.equal(response.status, 201);
assert.equal(response.headers.get("cache-control"), "no-store");
assert.deepEqual(await response.json(), {
version: 1,
user_id: "user-01",
device: {
device_id: "device-01",
public_key: PUBLIC_KEY,
device_name: "MacBook Pro",
platform: "macOS",
approval_status: "pending",
created_at: 1_780_000_100,
approved_at: null,
last_active_at: 1_780_000_100,
revoked_at: null,
current: true,
},
});
assert.ok(d1.queries[0]?.includes("INSERT INTO user_devices"));
assert.ok(d1.queries[0]?.includes("ON CONFLICT(user_id, idempotency_key) DO NOTHING"));
assert.ok(d1.queries[1]?.includes("WHERE user_id = ? AND idempotency_key = ?"));
assert.deepEqual(d1.binds[0]?.slice(0, 5), [
"user-01",
"device-01",
PUBLIC_KEY,
"MacBook Pro",
"macOS",
]);
assert.equal(typeof d1.binds[0]?.[5], "number");
assert.equal(typeof d1.binds[0]?.[6], "number");
assert.equal(d1.binds[0]?.[7], IDEMPOTENCY_KEY);
assert.deepEqual(d1.binds[1], ["user-01", IDEMPOTENCY_KEY]);
});
it("rejects invalid device registration payloads before D1 writes", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN);
const d1 = testD1Database([]);
const response = await handleRequest(
new Request("https://elydora.test/api/devices/register", {
method: "POST",
headers: {
authorization: `Bearer ${ACCESS_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify({ ...deviceRegistrationBody(), idempotency_key: "short" }),
}),
testEnv({
d1,
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
}),
);
assert.equal(response.status, 400);
assert.deepEqual(await response.json(), { error: "invalid_device_registration" });
assert.deepEqual(d1.queries, []);
});
it("rejects registration for a different authenticated device before D1 writes", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN);
const d1 = testD1Database([]);
const response = await handleRequest(
new Request("https://elydora.test/api/devices/register", {
method: "POST",
headers: {
authorization: `Bearer ${ACCESS_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify({ ...deviceRegistrationBody(), device_id: "device-02" }),
}),
testEnv({
d1,
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
}),
);
assert.equal(response.status, 403);
assert.deepEqual(await response.json(), { error: "device_context_mismatch" });
assert.deepEqual(d1.queries, []);
});
it("rejects unauthenticated device registration before D1 writes", async () => {
const d1 = testD1Database([]);
const response = await handleRequest(
new Request("https://elydora.test/api/devices/register", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(deviceRegistrationBody()),
}),
testEnv({ d1 }),
);
assert.equal(response.status, 401);
assert.deepEqual(await response.json(), { error: "authorization_missing" });
assert.deepEqual(d1.queries, []);
});
});
interface TestEnvOptions {
@@ -220,8 +348,8 @@ function testD1PreparedStatement(rows: unknown[], binds: unknown[][]): ElyD1Prep
binds.push(values);
return this;
},
first() {
return Promise.resolve(null);
first<T>() {
return Promise.resolve((rows[0] as T | undefined) ?? null);
},
all<T>() {
return Promise.resolve({ results: rows as T[] });
@@ -232,6 +360,17 @@ function testD1PreparedStatement(rows: unknown[], binds: unknown[][]): ElyD1Prep
};
}
function deviceRegistrationBody(): Record<string, unknown> {
return {
version: 1,
device_id: "device-01",
public_key: PUBLIC_KEY,
device_name: "MacBook Pro",
platform: "macOS",
idempotency_key: IDEMPOTENCY_KEY,
};
}
function testR2Bucket(): Env["ELY_STORAGE"] {
return {
get() {