Skip to content
Closed
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
11 changes: 9 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,24 @@ on:
permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
verify:
name: Lint, TypeCheck & Tests
runs-on: ubuntu-latest
timeout-minutes: 15

steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false

- name: Setup Deno 2.x
uses: denoland/setup-deno@v2
uses: denoland/setup-deno@22d081ff2d3a40755e97629de92e3bcbfa7cf2ed # v2
with:
deno-version: v2.x

Expand Down
14 changes: 10 additions & 4 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,29 @@ permissions:
contents: read
security-events: write

concurrency:
group: codeql-${{ github.ref }}
cancel-in-progress: true

jobs:
analyze:
name: CodeQL AppSec Vulnerability Scan
runs-on: ubuntu-latest
timeout-minutes: 360
timeout-minutes: 60

steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@aaf92c3279600a7c7217a1cd605774c6c791c6c3 # v3
with:
languages: javascript-typescript
queries: security-extended,security-and-quality

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@aaf92c3279600a7c7217a1cd605774c6c791c6c3 # v3
with:
category: "/language:javascript-typescript"
6 changes: 5 additions & 1 deletion example.env
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
# Si se define, solo las peticiones con 'Authorization: Bearer <token>' o 'x-statuszero-token' serán admitidas.
# PING_SECRET=your_ping_secret_here

# GITHUB_WEBHOOK_SECRET (Opcional - AppSec)
# GITHUB_WEBHOOK_SECRET (Requerido en producción - fail-closed)
# Clave secreta para verificar firmas HMAC-SHA256 (x-hub-signature-256) en /api/webhook/github.
# GITHUB_WEBHOOK_SECRET=your_webhook_secret_here

# Solo desarrollo local (NO activar en producción):
# ALLOW_UNAUTHENTICATED_PINGS=false
# ALLOW_UNAUTHENTICATED_WEBHOOKS=false
9 changes: 8 additions & 1 deletion routes/_middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export async function handler(
// Baseline Security Headers
resp.headers.set("X-Content-Type-Options", "nosniff");
resp.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
resp.headers.set(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains",
);
resp.headers.set(
"Permissions-Policy",
"camera=(), microphone=(), geolocation=()",
Expand All @@ -21,7 +25,10 @@ export async function handler(
// Badges need to be embeddable across any domain (GitHub README, docs, etc.)
if (url.pathname.startsWith("/badge/")) {
resp.headers.set("Access-Control-Allow-Origin", "*");
resp.headers.set("X-Frame-Options", "ALLOWALL");
resp.headers.set(
"Content-Security-Policy",
"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors *",
);
} else {
resp.headers.set("X-Frame-Options", "SAMEORIGIN");
resp.headers.set(
Expand Down
43 changes: 33 additions & 10 deletions routes/api/ping/[owner]/[repo].ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
// routes/api/ping/[owner]/[repo].ts
import { FreshContext } from "$fresh/server.ts";
import {
getKv,
consumeRateLimit,
getRepoPingSecret,
invalidateRepoCache,
PingRecord,
savePing,
} from "../../../../services/kv.ts";
import {
isValidGitHubIdentifier,
readBoundedBody,
sanitizeText,
timingSafeEqualString,
verifyHmacSha256,
} from "../../../../services/security.ts";

const RATE_LIMIT_MAX_PER_MINUTE = 30;
const MAX_PING_BODY_BYTES = 32 * 1024; // 32 KiB

export const handler = async (
req: Request,
Expand Down Expand Up @@ -47,19 +49,21 @@ export const handler = async (
);
}

// AppSec: Rate Limiting via Deno KV sliding minute
const kv = await getKv();
// AppSec: Atomic Rate Limiting via Deno KV sliding minute
const currentMinute = Math.floor(Date.now() / 60000);
const rateLimitKey = [
"ratelimit_ping",
owner.toLowerCase(),
repo.toLowerCase(),
currentMinute,
];
const rateLimitEntry = await kv.get<number>(rateLimitKey);
const currentCount = rateLimitEntry.value || 0;
const rateLimit = await consumeRateLimit(
rateLimitKey,
RATE_LIMIT_MAX_PER_MINUTE,
120 * 1000,
);

if (currentCount >= RATE_LIMIT_MAX_PER_MINUTE) {
if (!rateLimit.allowed) {
return new Response(
JSON.stringify({
error:
Expand All @@ -75,9 +79,14 @@ export const handler = async (
);
}

await kv.set(rateLimitKey, currentCount + 1, { expireIn: 120 * 1000 });

const rawBody = await req.text();
const bodyResult = await readBoundedBody(req, MAX_PING_BODY_BYTES);
if (!bodyResult.ok) {
return new Response(JSON.stringify({ error: bodyResult.error }), {
status: 413,
headers: { "Content-Type": "application/json" },
});
}
const rawBody = bodyResult.text;
let body: Record<string, unknown> = {};
if (rawBody.trim()) {
try {
Expand All @@ -93,8 +102,22 @@ export const handler = async (
}
}

// AppSec: Authentication check (HMAC-SHA256 or Bearer secret token)
// AppSec: Fail-closed authentication check (HMAC-SHA256 or Bearer secret token)
const configuredSecret = await getRepoPingSecret(owner, repo);
const allowUnauthenticated =
Deno.env.get("ALLOW_UNAUTHENTICATED_PINGS") === "true";
if (!configuredSecret && !allowUnauthenticated) {
return new Response(
JSON.stringify({
error:
"Endpoint de pings protegido (fail-closed): configura PING_SECRET o un secreto por repositorio.",
}),
{
status: 503,
headers: { "Content-Type": "application/json" },
},
);
}
if (configuredSecret) {
const authHeader = req.headers.get("Authorization") || "";
const tokenHeader = req.headers.get("x-statuszero-token") || "";
Expand Down
6 changes: 5 additions & 1 deletion routes/api/status/[owner]/[repo].ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// routes/api/status/[owner]/[repo].ts
import { FreshContext } from "$fresh/server.ts";
import { fetchRepoStatus } from "../../../../services/github.ts";
import { canForceRefresh } from "../../../../services/kv.ts";
import { isValidGitHubIdentifier } from "../../../../services/security.ts";

export const handler = async (
Expand All @@ -10,7 +11,7 @@ export const handler = async (
const owner = ctx.params.owner;
const repo = ctx.params.repo;
const url = new URL(req.url);
const forceRefresh = url.searchParams.get("refresh") === "true";
const requestedRefresh = url.searchParams.get("refresh") === "true";

// AppSec: Strict input validation
if (!isValidGitHubIdentifier(owner) || !isValidGitHubIdentifier(repo)) {
Expand All @@ -36,6 +37,9 @@ export const handler = async (
}

try {
const forceRefresh = requestedRefresh
? await canForceRefresh(owner, repo)
: false;
const data = await fetchRepoStatus(owner, repo, forceRefresh);
return new Response(JSON.stringify(data, null, 2), {
status: 200,
Expand Down
32 changes: 29 additions & 3 deletions routes/api/webhook/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { fetchRepoStatus } from "../../../services/github.ts";
import { invalidateRepoCache } from "../../../services/kv.ts";
import {
isValidGitHubIdentifier,
readBoundedBody,
verifyHmacSha256,
} from "../../../services/security.ts";

const MAX_WEBHOOK_BODY_BYTES = 256 * 1024; // 256 KiB

export const handler = async (
req: Request,
_ctx: FreshContext,
Expand All @@ -21,12 +24,35 @@ export const handler = async (
);
}

// AppSec: Fail-closed if GITHUB_WEBHOOK_SECRET is not configured
const webhookSecret = Deno.env.get("GITHUB_WEBHOOK_SECRET")?.trim();
const allowUnauthenticated =
Deno.env.get("ALLOW_UNAUTHENTICATED_WEBHOOKS") === "true";
if (!webhookSecret && !allowUnauthenticated) {
return new Response(
JSON.stringify({
error:
"Webhook deshabilitado: configura GITHUB_WEBHOOK_SECRET en el entorno (fail-closed).",
}),
{
status: 503,
headers: { "Content-Type": "application/json" },
},
);
}

const event = req.headers.get("x-github-event") || "unknown";
const signature = req.headers.get("x-hub-signature-256") || "";
const rawBody = await req.text();
const bodyResult = await readBoundedBody(req, MAX_WEBHOOK_BODY_BYTES);
if (!bodyResult.ok) {
return new Response(JSON.stringify({ error: bodyResult.error }), {
status: 413,
headers: { "Content-Type": "application/json" },
});
}
const rawBody = bodyResult.text;

// AppSec: Verify HMAC-SHA256 signature if GITHUB_WEBHOOK_SECRET is configured
const webhookSecret = Deno.env.get("GITHUB_WEBHOOK_SECRET");
// AppSec: Verify HMAC-SHA256 signature
if (webhookSecret) {
if (!signature) {
return new Response(
Expand Down
Loading
Loading