Skip to content
Merged
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
32 changes: 0 additions & 32 deletions package-lock.json

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

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,8 @@
"drizzle-kit": "0.31.11",
"eslint": "10.12.0",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-jest": "29.16.6",
"jiti": "2.7.0",
"prettier": "3.9.9",
"tsx": "4.23.15",
"typescript": "6.0.3",
"typescript-eslint": "8.71.1",
"vitest": "4.1.11",
Expand Down
5 changes: 4 additions & 1 deletion src/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,7 @@ export default {
}
};

export { PreviewGitHubBudget } from "../lib/adapters/cloudflare/preview-github-budget";
// wrangler's main module must export the Durable Object classes bound in
// wrangler.jsonc; the implementation lives with the previews service, which
// owns its rate-limit policy.
export { PreviewGitHubBudget } from "../services/previews/v1/budget";
4 changes: 0 additions & 4 deletions src/lib/adapters/cloudflare/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,4 @@ export class CloudflareEnvironmentAdapter implements IEnvironment {
const value = this.env[key];
return typeof value === "string" ? value : undefined;
}

has(key: string): boolean {
return key in this.env && typeof this.env[key] === "string";
}
}
4 changes: 0 additions & 4 deletions src/lib/adapters/node/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,4 @@ export class NodeEnvironmentAdapter implements IEnvironment {
get(key: string): string | undefined {
return process.env[key];
}

has(key: string): boolean {
return key in process.env;
}
}
8 changes: 5 additions & 3 deletions src/lib/adapters/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { createMemoryCache, createFileCache } from "./cache";
import { NodeEnvironmentAdapter } from "./environment";

// No database entry here - Drizzle only wraps the real D1 bindings (see
// src/lib/db.ts); the Node path exists solely to test the cache/environment
// adapters outside Workers, so it never had a real production consumer for
// a database binding (only src/app/index.ts's createCloudflareBindings does).
// src/lib/db.ts). The Node path is the standing proof that the
// IPlatformBindings seam (KV-shaped caches + string environment) is
// implementable off-Cloudflare; handlers still reach for platform services
// (D1, R2, Durable Objects, typed env) directly, so a full port needs
// service-level changes too. It has no production consumer today by design.
export function createNodeBindings(cacheDbPath?: string): IPlatformBindings {
const cacheKv = cacheDbPath
? createFileCache(`${normalizePath(cacheDbPath)}.kv`)
Expand Down
2 changes: 1 addition & 1 deletion src/lib/cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context, MiddlewareHandler } from "hono";
import { cache } from "hono/cache";

export function normalizePublicCacheKey(url: string): string {
function normalizePublicCacheKey(url: string): string {
const cacheUrl = new URL(url);
cacheUrl.search = "";
cacheUrl.hash = "";
Expand Down
54 changes: 9 additions & 45 deletions src/lib/github-errors.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
export enum ErrorPriority {
CRITICAL = 0,
HIGH = 1,
MEDIUM = 2,
LOW = 3
}

export class GitHubError extends Error {
constructor(
message: string,
public readonly httpStatus?: number,
public readonly errorCode?: string,
public readonly priority: ErrorPriority = ErrorPriority.MEDIUM,
public readonly url?: string,
public readonly details?: Record<string, unknown>
public readonly url?: string
) {
super(message);
this.name = this.constructor.name;
Expand All @@ -21,38 +12,31 @@ export class GitHubError extends Error {

export class AuthError extends GitHubError {
constructor(message: string, httpStatus: number = 401, url?: string) {
super(message, httpStatus, "auth_error", ErrorPriority.CRITICAL, url);
super(message, httpStatus, "auth_error", url);
}
}

export class RateLimitError extends GitHubError {
constructor(message: string, httpStatus: number = 403, url?: string) {
super(message, httpStatus, "rate_limit_error", ErrorPriority.CRITICAL, url);
super(message, httpStatus, "rate_limit_error", url);
}
}

export class NetworkError extends GitHubError {
constructor(message: string, url?: string) {
super(message, undefined, "network_error", ErrorPriority.HIGH, url);
super(message, undefined, "network_error", url);
}
}

export class NotFoundError extends GitHubError {
constructor(message: string, httpStatus: number = 404, url?: string) {
super(message, httpStatus, "not_found_error", ErrorPriority.MEDIUM, url);
super(message, httpStatus, "not_found_error", url);
}
}

export class ValidationError extends GitHubError {
constructor(message: string, details?: Record<string, unknown>) {
super(
message,
undefined,
"validation_error",
ErrorPriority.LOW,
undefined,
details
);
constructor(message: string) {
super(message, undefined, "validation_error");
}
}

Expand Down Expand Up @@ -130,28 +114,8 @@ export function classifyGitHubError(error: unknown, url?: string): GitHubError {
}

if (errorMessage.toLowerCase().includes("json")) {
return new ValidationError("Invalid JSON response from GitHub API", {
originalMessage: errorMessage
});
}

return new GitHubError(
errorMessage,
httpStatus,
"unknown_error",
ErrorPriority.HIGH,
url
);
}

export function getMostCriticalError(
errors: GitHubError[]
): GitHubError | null {
if (errors.length === 0) {
return null;
return new ValidationError("Invalid JSON response from GitHub API");
}

return errors.reduce((mostCritical, current) =>
current.priority < mostCritical.priority ? current : mostCritical
);
return new GitHubError(errorMessage, httpStatus, "unknown_error", url);
}
10 changes: 10 additions & 0 deletions src/lib/hash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// SHA-256 as lowercase hex - used for cache/DO key derivation, transfer
// token hashing, and content-digest columns.
export async function sha256Hex(input: string | BufferSource): Promise<string> {
const data =
typeof input === "string" ? new TextEncoder().encode(input) : input;
const digest = await crypto.subtle.digest("SHA-256", data);
return [...new Uint8Array(digest)]
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
1 change: 0 additions & 1 deletion src/lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export interface ICache {

export interface IEnvironment {
get(key: string): string | undefined;
has(key: string): boolean;
}

export interface IPlatformBindings {
Expand Down
40 changes: 9 additions & 31 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,6 @@ export enum LogLevel {
INFO = "info"
}

interface LogEntry {
timestamp: string;
service: string;
level: LogLevel;
message: string;
context?: Record<string, unknown>;
}

function redactSensitiveData(data: unknown): unknown {
if (typeof data === "string") {
return data.replace(/Bearer\s+[A-Za-z0-9\-_]+/g, "Bearer [REDACTED]");
Expand Down Expand Up @@ -41,36 +33,22 @@ function redactSensitiveData(data: unknown): unknown {
return data;
}

// One structured object per line: Workers Logs serializes object arguments
// as JSON and indexes the top-level fields, so `service` and the redacted
// `context` keys stay filterable in the dashboard instead of being baked
// into an unparseable message string. Timestamp and severity metadata are
// attached by the observability pipeline either way.
function log(
level: LogLevel,
service: string,
message: string,
context?: Record<string, unknown>
): void {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
service,
level,
message,
context: context
? (redactSensitiveData(context) as Record<string, unknown>)
: undefined
};

const logMessage = `[${entry.timestamp}] [${service.toUpperCase()}] [${level.toUpperCase()}] ${message}`;
const contextStr = entry.context ? ` ${JSON.stringify(entry.context)}` : "";

switch (level) {
case LogLevel.ERROR:
console.error(logMessage + contextStr);
break;
case LogLevel.WARN:
console.warn(logMessage + contextStr);
break;
case LogLevel.INFO:
console.info(logMessage + contextStr);
break;
const entry: Record<string, unknown> = { service, message };
if (context) {
entry.context = redactSensitiveData(context);
}
console[level](entry);
}

export function logError(
Expand Down
32 changes: 32 additions & 0 deletions src/lib/pagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Opt-in limit/offset pagination shared by the v1 list endpoints
// (extensions/v1 and central-alerts/v1). Absent params keep the full-list
// contract; a non-numeric limit is treated as absent rather than a 400 -
// these legacy surfaces have never validated query params and FOSSBilling's
// own client passes none. offset is the exception: only a caller opting into
// pagination can send it, so offset without a usable limit is invalid
// (matching the v2 pagination endpoints) rather than a silently ignored
// param that returns the full list.
export type LegacyPage = { limit: number; offset: number };

export function parseLegacyPagination(query: {
limit?: string;
offset?: string;
}): LegacyPage | "invalid" | undefined {
const limitParam = Number(query.limit);
const hasValidLimit =
Number.isInteger(limitParam) && limitParam >= 1 && limitParam <= 100;
if (query.offset !== undefined && !hasValidLimit) return "invalid";
const offsetParam = query.offset === undefined ? 0 : Number(query.offset);
// isSafeInteger, not isInteger: 1e100 is an integer but SQLite rejects an
// out-of-range OFFSET, which would surface as a 500. Unusable offsets
// follow the documented zero fallback instead.
return hasValidLimit
? {
limit: limitParam,
offset:
Number.isSafeInteger(offsetParam) && offsetParam >= 0
? offsetParam
: 0
}
: undefined;
}
27 changes: 8 additions & 19 deletions src/services/central-alerts/v1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { trimTrailingSlash } from "hono/trailing-slash";
import { CentralAlertsDatabase } from "./database";
import { getCentralAlertsDb } from "../../../lib/db";
import { logError } from "../../../lib/logger";
import { parseLegacyPagination } from "../../../lib/pagination";

const centralAlertsV1 = new Hono<{ Bindings: CloudflareBindings }>();

Expand All @@ -12,17 +13,11 @@ centralAlertsV1.use("/*", cors({ origin: "*" }), trimTrailingSlash());
// Admin panels poll this public representation constantly. Parse once before
// cache lookup so ignored inputs cannot create new entries for the same page.
centralAlertsV1.get("/list", async (c) => {
// Opt-in pagination: absent params keep the full-list contract. A
// non-numeric limit is treated as absent rather than a 400 - this route
// has never validated query params and FOSSBilling's client passes none.
// offset is the exception: only a caller opting into pagination can send
// it, so offset without a usable limit is a 422 (matching the v2
// pagination endpoints) rather than a silently ignored param.
const limitParam = Number(c.req.query("limit"));
const hasValidLimit =
Number.isInteger(limitParam) && limitParam >= 1 && limitParam <= 100;
const rawOffset = c.req.query("offset");
if (rawOffset !== undefined && !hasValidLimit) {
const page = parseLegacyPagination({
limit: c.req.query("limit"),
offset: c.req.query("offset")
});
if (page === "invalid") {
return c.json(
{
result: null,
Expand All @@ -31,14 +26,6 @@ centralAlertsV1.get("/list", async (c) => {
422
);
}
const offsetParam = rawOffset === undefined ? 0 : Number(rawOffset);
const page = hasValidLimit
? {
limit: limitParam,
offset:
Number.isInteger(offsetParam) && offsetParam >= 0 ? offsetParam : 0
}
: undefined;

const cacheUrl = new URL(c.req.url);
// Hono decodes path aliases before routing; key that same routed path.
Expand All @@ -51,6 +38,8 @@ centralAlertsV1.get("/list", async (c) => {
}
// This route never authenticates or varies by Authorization. Use a
// header-free key so that arbitrary credentials cannot force a D1 read.
// Degrade to serving uncached on runtimes without Cache Storage (the
// portability seam) rather than failing the route.
const edgeCache =
typeof caches !== "undefined"
? await caches.open("central-alerts-v1")
Expand Down
Loading
Loading