feat: split web and api into separate apps
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { createHash } from "crypto";
|
||||
import sql from "../db";
|
||||
|
||||
function generateKey(): string {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
function hashEmail(email: string): string {
|
||||
return createHash("sha256").update(email.toLowerCase().trim()).digest("hex");
|
||||
}
|
||||
|
||||
async function resolveKey(key: string): Promise<{ accountId: string; keyId: string | null } | null> {
|
||||
const [account] = await sql`SELECT id FROM accounts WHERE key = ${key}`;
|
||||
if (account) return { accountId: account.id, keyId: null };
|
||||
|
||||
const [apiKey] = await sql`SELECT id, account_id FROM api_keys WHERE key = ${key}`;
|
||||
if (apiKey) {
|
||||
sql`UPDATE api_keys SET last_used_at = now() WHERE id = ${apiKey.id}`.catch(() => {});
|
||||
return { accountId: apiKey.account_id, keyId: apiKey.id };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export { resolveKey };
|
||||
|
||||
export function requireAuth(app: Elysia) {
|
||||
return app
|
||||
.derive(async ({ headers, cookie, set }) => {
|
||||
const authHeader = headers["authorization"] ?? "";
|
||||
const bearer = authHeader.match(/^bearer\s+(.+)$/i)?.[1]?.trim();
|
||||
const cookieKey = cookie?.pingql_key?.value;
|
||||
|
||||
const key = bearer || cookieKey;
|
||||
if (!key) {
|
||||
set.status = 401;
|
||||
return { accountId: null as string | null, keyId: null as string | null };
|
||||
}
|
||||
|
||||
const resolved = await resolveKey(key);
|
||||
if (resolved) return { accountId: resolved.accountId, keyId: resolved.keyId };
|
||||
|
||||
set.status = 401;
|
||||
return { accountId: null as string | null, keyId: null as string | null };
|
||||
})
|
||||
.onBeforeHandle(({ accountId, set }) => {
|
||||
if (!accountId) {
|
||||
set.status = 401;
|
||||
return { error: "Invalid or missing account key" };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const COOKIE_OPTS = {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV !== "development",
|
||||
sameSite: "lax" as const,
|
||||
path: "/",
|
||||
domain: process.env.COOKIE_DOMAIN ?? ".pingql.com",
|
||||
maxAge: 60 * 60 * 24 * 365,
|
||||
};
|
||||
|
||||
export const account = new Elysia({ prefix: "/account" })
|
||||
|
||||
.post("/login", async ({ body, cookie, set }) => {
|
||||
const key = (body.key as string)?.trim();
|
||||
if (!key) { set.status = 400; return { error: "Key required" }; }
|
||||
|
||||
const resolved = await resolveKey(key);
|
||||
if (!resolved) {
|
||||
set.status = 401;
|
||||
if ((body as any)._form) { set.redirect = "/dashboard?error=invalid"; return; }
|
||||
return { error: "Invalid account key" };
|
||||
}
|
||||
|
||||
cookie.pingql_key.set({ value: key, ...COOKIE_OPTS });
|
||||
if ((body as any)._form) { set.redirect = "/dashboard/home"; return; }
|
||||
return { ok: true };
|
||||
}, { detail: { hide: true } })
|
||||
|
||||
.get("/logout", ({ cookie, set }) => {
|
||||
cookie.pingql_key.set({ value: "", ...COOKIE_OPTS, maxAge: 0 });
|
||||
set.redirect = "/dashboard";
|
||||
}, { detail: { hide: true } })
|
||||
|
||||
.post("/register", async ({ body, cookie }) => {
|
||||
const key = generateKey();
|
||||
const emailHash = body.email ? hashEmail(body.email) : null;
|
||||
await sql`INSERT INTO accounts (key, email_hash) VALUES (${key}, ${emailHash})`;
|
||||
cookie.pingql_key.set({ value: key, ...COOKIE_OPTS });
|
||||
return {
|
||||
key,
|
||||
...(body.email ? { email_registered: true } : { email_registered: false }),
|
||||
};
|
||||
}, {
|
||||
body: t.Object({
|
||||
email: t.Optional(t.String({ format: "email", description: "Optional. Used for account recovery only." })),
|
||||
}),
|
||||
})
|
||||
|
||||
.use(requireAuth)
|
||||
|
||||
.get("/settings", async ({ accountId }) => {
|
||||
const [acc] = await sql`SELECT id, email_hash, created_at FROM accounts WHERE id = ${accountId}`;
|
||||
const keys = await sql`SELECT id, key, label, created_at, last_used_at FROM api_keys WHERE account_id = ${accountId} ORDER BY created_at DESC`;
|
||||
return {
|
||||
account_id: acc.id,
|
||||
has_email: !!acc.email_hash,
|
||||
created_at: acc.created_at,
|
||||
api_keys: keys,
|
||||
};
|
||||
})
|
||||
|
||||
.post("/email", async ({ accountId, body }) => {
|
||||
const emailHash = body.email ? hashEmail(body.email) : null;
|
||||
await sql`UPDATE accounts SET email_hash = ${emailHash} WHERE id = ${accountId}`;
|
||||
return { ok: true };
|
||||
}, {
|
||||
body: t.Object({
|
||||
email: t.Optional(t.Nullable(t.String({ description: "Email for account recovery only." }))),
|
||||
}),
|
||||
})
|
||||
|
||||
.post("/reset-key", async ({ accountId, cookie }) => {
|
||||
const key = generateKey();
|
||||
await sql`UPDATE accounts SET key = ${key} WHERE id = ${accountId}`;
|
||||
cookie.pingql_key.set({ value: key, ...COOKIE_OPTS });
|
||||
return { key, message: "Primary key rotated. Your old key is now invalid." };
|
||||
})
|
||||
|
||||
.post("/keys", async ({ accountId, body }) => {
|
||||
const key = generateKey();
|
||||
const [created] = await sql`INSERT INTO api_keys (key, account_id, label) VALUES (${key}, ${accountId}, ${body.label}) RETURNING id`;
|
||||
return { key, id: created.id, label: body.label };
|
||||
}, {
|
||||
body: t.Object({
|
||||
label: t.String({ description: "A name for this key, e.g. 'ci-pipeline' or 'mobile-app'" }),
|
||||
}),
|
||||
})
|
||||
|
||||
.delete("/keys/:id", async ({ accountId, params, error }) => {
|
||||
const [deleted] = await sql`
|
||||
DELETE FROM api_keys WHERE id = ${params.id} AND account_id = ${accountId} RETURNING id
|
||||
`;
|
||||
if (!deleted) return error(404, { error: "Key not found" });
|
||||
return { deleted: true };
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/// Internal endpoints used by the Rust monitor runner.
|
||||
/// Protected by MONITOR_TOKEN — not exposed to users.
|
||||
|
||||
import { Elysia } from "elysia";
|
||||
import sql from "../db";
|
||||
|
||||
export async function pruneOldPings(retentionDays = 90) {
|
||||
const result = await sql`DELETE FROM pings WHERE checked_at < now() - ${retentionDays + ' days'}::interval`;
|
||||
return result.count;
|
||||
}
|
||||
|
||||
// Run retention cleanup every hour
|
||||
setInterval(() => {
|
||||
const days = Number(process.env.PING_RETENTION_DAYS ?? 90);
|
||||
pruneOldPings(days).catch((err) => console.error("Retention cleanup failed:", err));
|
||||
}, 60 * 60 * 1000);
|
||||
|
||||
export const internal = new Elysia({ prefix: "/internal", detail: { hide: true } })
|
||||
.derive(({ headers, error }) => {
|
||||
if (headers["x-monitor-token"] !== process.env.MONITOR_TOKEN)
|
||||
return error(401, { error: "Unauthorized" });
|
||||
return {};
|
||||
})
|
||||
|
||||
// Returns monitors that are due for a check.
|
||||
// scheduled_at = last_checked_at + interval_s (ideal fire time), so jitter = actual_start - scheduled_at
|
||||
.get("/due", async () => {
|
||||
const monitors = await sql`
|
||||
SELECT m.id, m.url, m.method, m.request_headers, m.request_body, m.timeout_ms, m.interval_s, m.query,
|
||||
CASE
|
||||
WHEN last.checked_at IS NULL THEN now()
|
||||
ELSE last.checked_at + (m.interval_s || ' seconds')::interval
|
||||
END AS scheduled_at
|
||||
FROM monitors m
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT checked_at FROM pings
|
||||
WHERE monitor_id = m.id
|
||||
ORDER BY checked_at DESC LIMIT 1
|
||||
) last ON true
|
||||
WHERE m.enabled = true
|
||||
AND (last.checked_at IS NULL
|
||||
OR last.checked_at < now() - (m.interval_s || ' seconds')::interval)
|
||||
`;
|
||||
return monitors;
|
||||
})
|
||||
|
||||
// Manual retention cleanup trigger
|
||||
.post("/prune", async () => {
|
||||
const days = Number(process.env.PING_RETENTION_DAYS ?? 90);
|
||||
const deleted = await pruneOldPings(days);
|
||||
return { deleted, retention_days: days };
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { requireAuth } from "./auth";
|
||||
import sql from "../db";
|
||||
import { validateMonitorUrl } from "../utils/ssrf";
|
||||
|
||||
const MonitorBody = t.Object({
|
||||
name: t.String({ description: "Human-readable name" }),
|
||||
url: t.String({ format: "uri", description: "URL to check" }),
|
||||
method: t.Optional(t.String({ default: "GET", description: "HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD" })),
|
||||
request_headers: t.Optional(t.Any({ description: "Request headers as key-value object" })),
|
||||
request_body: t.Optional(t.Nullable(t.String({ description: "Request body for POST/PUT/PATCH" }))),
|
||||
timeout_ms: t.Optional(t.Number({ minimum: 1000, maximum: 60000, default: 30000, description: "Request timeout in ms" })),
|
||||
interval_s: t.Optional(t.Number({ minimum: 1, default: 60, description: "Check interval in seconds" })),
|
||||
query: t.Optional(t.Any({ description: "PingQL query — filter conditions for up/down" })),
|
||||
});
|
||||
|
||||
export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
.use(requireAuth)
|
||||
|
||||
// List monitors
|
||||
.get("/", async ({ accountId }) => {
|
||||
return sql`SELECT * FROM monitors WHERE account_id = ${accountId} ORDER BY created_at DESC`;
|
||||
}, { detail: { summary: "List monitors", tags: ["monitors"] } })
|
||||
|
||||
// Create monitor
|
||||
.post("/", async ({ accountId, body, error }) => {
|
||||
// SSRF protection
|
||||
const ssrfError = await validateMonitorUrl(body.url);
|
||||
if (ssrfError) return error(400, { error: ssrfError });
|
||||
|
||||
const [monitor] = await sql`
|
||||
INSERT INTO monitors (account_id, name, url, method, request_headers, request_body, timeout_ms, interval_s, query)
|
||||
VALUES (
|
||||
${accountId}, ${body.name}, ${body.url},
|
||||
${(body.method ?? 'GET').toUpperCase()},
|
||||
${body.request_headers ? sql.json(body.request_headers) : null},
|
||||
${body.request_body ?? null},
|
||||
${body.timeout_ms ?? 30000},
|
||||
${body.interval_s ?? 60},
|
||||
${body.query ? sql.json(body.query) : null}
|
||||
)
|
||||
RETURNING *
|
||||
`;
|
||||
return monitor;
|
||||
}, { body: MonitorBody, detail: { summary: "Create monitor", tags: ["monitors"] } })
|
||||
|
||||
// Get monitor + recent status
|
||||
.get("/:id", async ({ accountId, params, error }) => {
|
||||
const [monitor] = await sql`
|
||||
SELECT * FROM monitors WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
`;
|
||||
if (!monitor) return error(404, { error: "Not found" });
|
||||
|
||||
const results = await sql`
|
||||
SELECT * FROM pings WHERE monitor_id = ${params.id}
|
||||
ORDER BY checked_at DESC LIMIT 100
|
||||
`;
|
||||
return { ...monitor, results };
|
||||
}, { detail: { summary: "Get monitor with results", tags: ["monitors"] } })
|
||||
|
||||
// Update monitor
|
||||
.patch("/:id", async ({ accountId, params, body, error }) => {
|
||||
// SSRF protection on URL change
|
||||
if (body.url) {
|
||||
const ssrfError = await validateMonitorUrl(body.url);
|
||||
if (ssrfError) return error(400, { error: ssrfError });
|
||||
}
|
||||
|
||||
const [monitor] = await sql`
|
||||
UPDATE monitors SET
|
||||
name = COALESCE(${body.name ?? null}, name),
|
||||
url = COALESCE(${body.url ?? null}, url),
|
||||
method = COALESCE(${body.method ? body.method.toUpperCase() : null}, method),
|
||||
request_headers = COALESCE(${body.request_headers ? sql.json(body.request_headers) : null}, request_headers),
|
||||
request_body = COALESCE(${body.request_body ?? null}, request_body),
|
||||
timeout_ms = COALESCE(${body.timeout_ms ?? null}, timeout_ms),
|
||||
interval_s = COALESCE(${body.interval_s ?? null}, interval_s),
|
||||
query = COALESCE(${body.query ? sql.json(body.query) : null}, query)
|
||||
WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
RETURNING *
|
||||
`;
|
||||
if (!monitor) return error(404, { error: "Not found" });
|
||||
return monitor;
|
||||
}, { body: t.Partial(MonitorBody), detail: { summary: "Update monitor", tags: ["monitors"] } })
|
||||
|
||||
// Delete monitor
|
||||
.delete("/:id", async ({ accountId, params, error }) => {
|
||||
const [deleted] = await sql`
|
||||
DELETE FROM monitors WHERE id = ${params.id} AND account_id = ${accountId} RETURNING id
|
||||
`;
|
||||
if (!deleted) return error(404, { error: "Not found" });
|
||||
return { deleted: true };
|
||||
}, { detail: { summary: "Delete monitor", tags: ["monitors"] } })
|
||||
|
||||
// Toggle enabled
|
||||
.post("/:id/toggle", async ({ accountId, params, error }) => {
|
||||
const [monitor] = await sql`
|
||||
UPDATE monitors SET enabled = NOT enabled
|
||||
WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
RETURNING id, enabled
|
||||
`;
|
||||
if (!monitor) return error(404, { error: "Not found" });
|
||||
return monitor;
|
||||
}, { detail: { summary: "Toggle monitor on/off", tags: ["monitors"] } })
|
||||
|
||||
// Check history
|
||||
.get("/:id/pings", async ({ accountId, params, query, error }) => {
|
||||
const [monitor] = await sql`
|
||||
SELECT id FROM monitors WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
`;
|
||||
if (!monitor) return error(404, { error: "Not found" });
|
||||
const limit = Math.min(Number(query.limit ?? 100), 1000);
|
||||
return sql`
|
||||
SELECT * FROM pings
|
||||
WHERE monitor_id = ${params.id}
|
||||
ORDER BY checked_at DESC LIMIT ${limit}
|
||||
`;
|
||||
}, { detail: { summary: "Get ping history", tags: ["monitors"] } });
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import sql from "../db";
|
||||
import { resolveKey } from "./auth";
|
||||
|
||||
// ── SSE bus ───────────────────────────────────────────────────────────────────
|
||||
type SSEController = ReadableStreamDefaultController<Uint8Array>;
|
||||
const bus = new Map<string, Set<SSEController>>(); // keyed by accountId
|
||||
const enc = new TextEncoder();
|
||||
|
||||
function publish(accountId: string, data: object) {
|
||||
const subs = bus.get(accountId);
|
||||
if (!subs?.size) return;
|
||||
const msg = enc.encode(`data: ${JSON.stringify(data)}\n\n`);
|
||||
for (const ctrl of subs) {
|
||||
try { ctrl.enqueue(msg); } catch { subs.delete(ctrl); }
|
||||
}
|
||||
}
|
||||
|
||||
function makeSSEStream(accountId: string): Response {
|
||||
let ctrl: SSEController;
|
||||
let heartbeat: Timer;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(c) {
|
||||
ctrl = c;
|
||||
if (!bus.has(accountId)) bus.set(accountId, new Set());
|
||||
bus.get(accountId)!.add(ctrl);
|
||||
ctrl.enqueue(enc.encode(": connected\n\n"));
|
||||
heartbeat = setInterval(() => {
|
||||
try { ctrl.enqueue(enc.encode(": heartbeat\n\n")); } catch { clearInterval(heartbeat); }
|
||||
}, 10_000);
|
||||
},
|
||||
cancel() {
|
||||
clearInterval(heartbeat);
|
||||
bus.get(accountId)?.delete(ctrl);
|
||||
if (bus.get(accountId)?.size === 0) bus.delete(accountId);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||
export const ingest = new Elysia()
|
||||
|
||||
// Internal: called by Rust monitor runner
|
||||
.post("/internal/ingest", async ({ body, headers, error }) => {
|
||||
const token = headers["x-monitor-token"];
|
||||
if (token !== process.env.MONITOR_TOKEN) return error(401, { error: "Unauthorized" });
|
||||
|
||||
const meta = body.meta ? { ...body.meta } : {};
|
||||
if (body.cert_expiry_days != null) meta.cert_expiry_days = body.cert_expiry_days;
|
||||
|
||||
const scheduledAt = body.scheduled_at ? new Date(body.scheduled_at) : null;
|
||||
const jitterMs = body.jitter_ms ?? null;
|
||||
|
||||
const [ping] = await sql`
|
||||
INSERT INTO pings (monitor_id, scheduled_at, jitter_ms, status_code, latency_ms, up, error, meta)
|
||||
VALUES (
|
||||
${body.monitor_id},
|
||||
${scheduledAt},
|
||||
${jitterMs},
|
||||
${body.status_code ?? null},
|
||||
${body.latency_ms ?? null},
|
||||
${body.up},
|
||||
${body.error ?? null},
|
||||
${Object.keys(meta).length > 0 ? sql.json(meta) : null}
|
||||
)
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
// Look up account and publish to account-level bus
|
||||
const [monitor] = await sql`SELECT account_id FROM monitors WHERE id = ${body.monitor_id}`;
|
||||
if (monitor) publish(monitor.account_id, ping);
|
||||
|
||||
return { ok: true };
|
||||
}, {
|
||||
body: t.Object({
|
||||
monitor_id: t.String(),
|
||||
scheduled_at: t.Optional(t.Nullable(t.String())),
|
||||
jitter_ms: t.Optional(t.Nullable(t.Number())),
|
||||
status_code: t.Optional(t.Number()),
|
||||
latency_ms: t.Optional(t.Number()),
|
||||
up: t.Boolean(),
|
||||
error: t.Optional(t.Nullable(t.String())),
|
||||
cert_expiry_days: t.Optional(t.Nullable(t.Number())),
|
||||
meta: t.Optional(t.Any()),
|
||||
}),
|
||||
detail: { hide: true },
|
||||
})
|
||||
|
||||
// SSE: single stream for all of the account's monitors
|
||||
.get("/account/stream", async ({ headers, cookie }) => {
|
||||
const authHeader = headers["authorization"] ?? "";
|
||||
const bearer = authHeader.match(/^bearer\s+(.+)$/i)?.[1]?.trim();
|
||||
const key = bearer ?? cookie?.pingql_key?.value;
|
||||
|
||||
if (!key) return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
|
||||
|
||||
const resolved = await resolveKey(key);
|
||||
if (!resolved) return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
|
||||
|
||||
const limit = Number(process.env.MAX_SSE_PER_ACCOUNT ?? 10);
|
||||
if ((bus.get(resolved.accountId)?.size ?? 0) >= limit) {
|
||||
return new Response(JSON.stringify({ error: "Too many connections" }), { status: 429 });
|
||||
}
|
||||
|
||||
return makeSSEStream(resolved.accountId);
|
||||
}, { detail: { hide: true } });
|
||||
Reference in New Issue
Block a user