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
5 changes: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ jobs:
- name: Build
run: pnpm build

# CI-C1: unit tests are part of CI, which the deploy workflow gates on —
# so a regression in auth/links/redirect can no longer auto-deploy.
- name: Test
run: pnpm test

# Deploy scripts: local D1 migration scenarios plus smoke/verify checks.
# No Cloudflare credentials needed.
- name: Shellcheck deploy scripts
Expand Down
48 changes: 48 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,54 @@ jobs:
permissions:
contents: write
steps:
# CI-C9: validate the tag's format and origin before creating a release —
# a release must point at a real tag that is reachable from main.
- name: Validate tag
uses: actions/github-script@v9
env:
TAG: ${{ inputs.tag || github.ref_name }}
with:
script: |
const tag = process.env.TAG;
if (!/^v\d+\.\d+\.\d+$/.test(tag)) {
core.setFailed(`Invalid tag format "${tag}"; must match v<major>.<minor>.<patch>.`);
return;
}
let ref;
try {
({ data: ref } = await github.rest.git.getRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `tags/${tag}`,
}));
} catch {
core.setFailed(`Tag "${tag}" does not exist in the repository.`);
return;
}
// Resolve annotated tags down to the commit they point at.
let sha = ref.object.sha;
if (ref.object.type === 'tag') {
const { data: tagObj } = await github.rest.git.getTag({
owner: context.repo.owner,
repo: context.repo.repo,
tag_sha: sha,
});
sha = tagObj.object.sha;
}
const { data: cmp } = await github.rest.repos.compareCommits({
owner: context.repo.owner,
repo: context.repo.repo,
base: 'main',
head: sha,
});
if (cmp.status === 'ahead' || cmp.status === 'diverged') {
core.setFailed(
`Tag "${tag}" (${sha}) is not on main (status: ${cmp.status}); refusing to release.`,
);
return;
}
core.info(`Tag "${tag}" (${sha}) is on main (status: ${cmp.status}).`);

- name: Create GitHub Release
uses: actions/github-script@v9
env:
Expand Down
32 changes: 32 additions & 0 deletions .github/workflows/tag.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
actions: read
env:
TAG: ${{ inputs.tag }}

Expand Down Expand Up @@ -46,6 +47,37 @@ jobs:
fi
echo "✅ Tag '$TAG' does not exist, proceeding..."

# CI-C9: never tag a commit whose CI did not pass — a tag feeds straight
# into release.yml, so it must only point at a verified main HEAD.
- name: Verify main CI passed
uses: actions/github-script@v9
env:
WORKFLOW_FILE: ci.yml
with:
script: |
const { stdout } = await exec.getExecOutput('git', ['rev-parse', 'HEAD']);
const sha = stdout.trim();
core.info(`Checking CI status for main@${sha}`);
// Filter by workflow file (not the repo-wide list) so this very tag
// workflow run is not mistaken for CI, and only accept a push run.
const { data } = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: process.env.WORKFLOW_FILE,
head_sha: sha,
event: 'push',
});
const ciRun = data.workflow_runs.find(
(run) => run.status === 'completed' && run.conclusion === 'success',
);
if (!ciRun) {
core.setFailed(
`No successful CI (push) run found for main@${sha}; run CI on main before tagging.`,
);
return;
}
core.info(`CI for main@${sha} succeeded (run ${ciRun.id}).`);

- name: Configure Git
run: |
git config user.name "github-actions[bot]"
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,9 @@ export const authApi = {

// TOTP
totpSetup: () =>
request<{ secret: string; uri: string }>('/auth/2fa/totp/setup'),
request<{ secret: string; uri: string }>('/auth/2fa/totp/setup', {
method: 'POST',
}),
totpConfirm: (code: string) =>
request<{ success: boolean; backupCodes: string[] }>(
'/auth/2fa/totp/confirm',
Expand Down
4 changes: 3 additions & 1 deletion apps/web/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:8787',
// CI-C9: the worker origin is configurable so local setups that run the
// worker on a different host/port don't have to edit this file.
target: process.env.API_PROXY_TARGET ?? 'http://localhost:8787',
changeOrigin: true,
},
},
Expand Down
10 changes: 2 additions & 8 deletions apps/worker/migrations/0001_init.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
-- This is the canonical schema for a fresh deployment.
-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).
-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations

CREATE TABLE users (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
Expand All @@ -15,7 +16,6 @@ CREATE TABLE users (
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE passkeys (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
Expand All @@ -28,7 +28,6 @@ CREATE TABLE passkeys (
last_used_at INTEGER
);
CREATE INDEX idx_passkeys_user_id ON passkeys(user_id);

CREATE TABLE links (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
Expand All @@ -44,7 +43,6 @@ CREATE TABLE links (
CREATE INDEX idx_links_slug ON links(slug);
CREATE INDEX idx_links_user_id ON links(user_id);
CREATE INDEX idx_links_expires_at ON links(expires_at) WHERE expires_at IS NOT NULL;

CREATE TABLE click_logs (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
link_id TEXT NOT NULL REFERENCES links(id) ON DELETE CASCADE,
Expand All @@ -61,7 +59,6 @@ CREATE TABLE click_logs (
CREATE INDEX idx_click_logs_link_id ON click_logs(link_id);
CREATE INDEX idx_click_logs_created_at ON click_logs(created_at);
CREATE INDEX idx_click_logs_link_time ON click_logs(link_id, created_at);

CREATE TABLE verifications (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
identifier TEXT NOT NULL,
Expand All @@ -73,7 +70,6 @@ CREATE TABLE verifications (
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX idx_verifications_identifier ON verifications(identifier, type);

CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
Expand All @@ -92,7 +88,6 @@ INSERT INTO settings (key, value) VALUES
('resend_api_key', ''),
('email_from_domain', ''),
('email_from_name', '');

CREATE TABLE audit_logs (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
admin_id TEXT REFERENCES users(id) ON DELETE SET NULL,
Expand All @@ -104,7 +99,6 @@ CREATE TABLE audit_logs (
CREATE INDEX idx_audit_logs_admin_id ON audit_logs(admin_id);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);
CREATE INDEX idx_audit_logs_target_id ON audit_logs(target_id);

CREATE TABLE totp_used (
user_id TEXT NOT NULL,
code TEXT NOT NULL,
Expand Down
5 changes: 2 additions & 3 deletions apps/worker/migrations/0002_token_version.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
-- BE-S3/S4: per-user token_version — bumping it revokes all of a user's sessions
-- (password change/reset, admin disable/demote). Keep in sync with the `schema_v2`
-- migration embedded in routes/setup.ts.
-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).
-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations

ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0;
4 changes: 3 additions & 1 deletion apps/worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"dev": "wrangler dev",
"build": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"test": "node --test test/*.test.ts",
"test": "node --import tsx --test test/*.test.ts",
"generate:migrations": "node --import tsx scripts/generate-migrations.ts",
"deploy": "wrangler deploy",
"db:migrate:local": "wrangler d1 migrations apply DB --local",
"db:migrate": "wrangler d1 migrations apply DB --remote"
Expand All @@ -20,6 +21,7 @@
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20241205.0",
"tsx": "^4.23.15",
"typescript": "^6.0.0",
"wrangler": "^4.0.0"
}
Expand Down
57 changes: 57 additions & 0 deletions apps/worker/scripts/generate-migrations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Generates apps/worker/migrations/*.sql from src/lib/migrations.ts
// (getMigrations('')), so the wrangler migration files and the setup-route /
// prefixed migrations share a single source of truth.
//
// Run from apps/worker: `node --import tsx scripts/generate-migrations.ts`
// (or `pnpm generate:migrations`). The consistency test in
// test/migrations.test.ts fails if a checked-in .sql file drifts from the
// generated content.
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { getMigrations } from '../src/lib/migrations.ts';

const here = dirname(fileURLToPath(import.meta.url));
const migrationsDir = join(here, '..', 'migrations');

const HEADER =
'-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).\n' +
'-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations\n';

// The setup route and the prefixed deploy path run getMigrations() directly,
// which uses idempotent forms (CREATE TABLE IF NOT EXISTS / INSERT OR IGNORE) so
// they can re-run safely. The wrangler migration files, by contrast, must keep
// their original fail-if-exists semantics: wrangler tracks applied migrations,
// so a repeated CREATE TABLE should error rather than silently skip. Strip the
// idempotency markers when rendering the .sql files.
function toWranglerSql(sql: string): string {
return sql
.replace(/CREATE TABLE IF NOT EXISTS /gi, 'CREATE TABLE ')
.replace(/CREATE INDEX IF NOT EXISTS /gi, 'CREATE INDEX ')
.replace(/INSERT OR IGNORE INTO /gi, 'INSERT INTO ');
}

// Map of wrangler migration file name -> file content.
export function renderMigrationFiles(): Record<string, string> {
const files: Record<string, string> = {};
for (const migration of getMigrations('')) {
files[migration.fileName] =
`${HEADER}\n${toWranglerSql(migration.sql).trim()}\n`;
}
return files;
}

function isMain(): boolean {
return (
process.argv[1] !== undefined &&
import.meta.url === pathToFileURL(process.argv[1]).href
);
}

if (isMain()) {
mkdirSync(migrationsDir, { recursive: true });
for (const [name, content] of Object.entries(renderMigrationFiles())) {
writeFileSync(join(migrationsDir, name), content);
console.log(`wrote migrations/${name}`);
}
}
68 changes: 50 additions & 18 deletions apps/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { tbl } from './lib/db.js';
import { getCachedSetting, setCachedSetting } from './lib/kv.js';
import { API_CSP, SPA_CSP, securityHeaders } from './lib/security.js';
import { RESERVED_SLUGS } from './lib/slug.js';
import adminRoutes from './routes/admin.js';
import analyticsRoutes from './routes/analytics.js';
Expand All @@ -13,33 +14,53 @@ import type { Env, Variables } from './types.js';

const app = new Hono<{ Bindings: Env; Variables: Variables }>();

// ─── Request ID + structured error handling (BE-Q3) ───────────────────────────
app.use('*', async (c, next) => {
c.set('requestId', crypto.randomUUID());
await next();
});

// BE-Q3: log unhandled errors with structured fields (path, error name,
// requestId) and never leak internal details to the client.
app.onError((err, c) => {
console.error(
JSON.stringify({
level: 'error',
path: c.req.path,
method: c.req.method,
error: err instanceof Error ? err.name : typeof err,
requestId: c.get('requestId'),
}),
);
return c.json({ error: 'Internal Server Error' }, 500);
});

// ─── Security headers ─────────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
await next();
c.header('X-Content-Type-Options', 'nosniff');
c.header('X-Frame-Options', 'DENY');
c.header('Referrer-Policy', 'strict-origin-when-cross-origin');
c.header(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'",
);
if (c.env.APP_URL.startsWith('https')) {
c.header(
'Strict-Transport-Security',
'max-age=63072000; includeSubDomains',
);
for (const [k, v] of Object.entries(
securityHeaders(c.env.APP_URL, API_CSP),
)) {
c.header(k, v);
}
});

// ─── CORS ─────────────────────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
const handler = cors({
origin: (origin) => {
const allowed = [
c.env.APP_URL,
'http://localhost:5173',
'http://localhost:4173',
];
const allowed = [c.env.APP_URL];
// BE-S10: allow the Vite dev-server origins only when the Worker is reached
// over plain http on a loopback host (i.e. wrangler dev). A deployed Worker
// is served from a real hostname, so neither condition holds in production.
const url = new URL(c.req.url);
const isLoopback =
url.hostname === 'localhost' ||
url.hostname === '127.0.0.1' ||
url.hostname === '::1';
if (url.protocol === 'http:' && isLoopback) {
allowed.push('http://localhost:5173', 'http://localhost:4173');
}
return allowed.includes(origin) ? origin : null;
},
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
Expand Down Expand Up @@ -112,7 +133,18 @@ app.get('/:slug', async (c, next) => {
});

// Fallback — forward all unmatched requests to Workers Assets (SPA + static files)
app.all('*', (c) => c.env.ASSETS.fetch(c.req.url) as unknown as Response);
app.all('*', async (c) => {
const res = await c.env.ASSETS.fetch(c.req.url);
// BE-S11: the /api/* middleware above does not cover SPA/static responses, so
// attach security headers (including a Vite-compatible CSP) here.
const headers = new Headers(res.headers);
for (const [k, v] of Object.entries(
securityHeaders(c.env.APP_URL, SPA_CSP),
)) {
headers.set(k, v);
}
return new Response(res.body, { status: res.status, headers });
});

export default {
fetch: app.fetch,
Expand Down
10 changes: 8 additions & 2 deletions apps/worker/src/lib/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,14 @@ export async function sendEmail(
});

if (!res.ok) {
const text = await res.text();
throw new Error(`Resend error ${res.status}: ${text}`);
// BE-R2: don't fold the upstream response body into the error — it can echo
// SMTP/credential configuration. Log a redacted summary (status only) and
// throw a generic error so nothing sensitive reaches the client or the logs.
console.error('sendEmail failed', {
provider: 'resend',
status: res.status,
});
throw new Error(`Resend request failed with status ${res.status}`);
}
}

Expand Down
Loading
Loading