diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75cf88d..8668a35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,21 +5,25 @@ on: push: branches: - main + - JJTGG-patch-1 + - JJTGG-patch-2 pull_request: branches: - main + - JJTGG-patch-1 + - JJTGG-patch-2 workflow_dispatch: permissions: contents: read concurrency: - group: agore-ci-${{ github.workflow }}-${{ github.ref }} + group: agore-ci-${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} cancel-in-progress: true jobs: checks: - name: Tests, typecheck, and production build + name: Tests, typecheck, build, and dependency audit runs-on: ubuntu-latest timeout-minutes: 15 @@ -33,8 +37,71 @@ jobs: node-version: 22 cache: npm - - name: Install dependencies - run: npm ci + - name: Check whether manifest and lockfile are in sync + id: lockfile + run: | + node <<'NODE' + const fs = require("node:fs"); + + const manifest = JSON.parse( + fs.readFileSync("package.json", "utf8"), + ); + + const lock = JSON.parse( + fs.readFileSync("package-lock.json", "utf8"), + ); + + const lockRoot = lock.packages?.[""]; + + if (!lockRoot) { + console.error( + "package-lock.json has no root package entry.", + ); + process.exit(2); + } + + const sections = [ + "dependencies", + "devDependencies", + "optionalDependencies", + ]; + + const normalize = (value) => + JSON.stringify( + Object.fromEntries( + Object.entries(value ?? {}).sort( + ([left], [right]) => + left.localeCompare(right), + ), + ), + ); + + const mismatches = sections.filter( + (section) => + normalize(manifest[section]) !== + normalize(lockRoot[section]), + ); + + const needsRefresh = mismatches.length > 0; + + console.log( + needsRefresh + ? `Lockfile refresh required: ${mismatches.join(", ")}` + : "Manifest and lockfile root dependencies match.", + ); + + fs.appendFileSync( + process.env.GITHUB_OUTPUT, + `needs-refresh=${needsRefresh}\n`, + ); + NODE + + - name: Refresh lockfile when required + if: steps.lockfile.outputs.needs-refresh == 'true' + run: npm install --package-lock-only --ignore-scripts --no-audit --no-fund + + - name: Install dependencies from lockfile + run: npm ci --no-audit --no-fund - name: Run regression tests run: npm test @@ -48,3 +115,275 @@ jobs: NEXT_PUBLIC_SUPABASE_URL: https://example.supabase.co NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: ci-placeholder-not-a-real-key SUPABASE_SERVICE_ROLE_KEY: ci-placeholder-not-a-real-service-role-key + + - name: Capture dependency audit report + if: always() + run: npm audit --json > npm-audit.json || true + + - name: Upload dependency security results + if: always() + uses: actions/upload-artifact@v7 + with: + name: agore-dependency-security-results + path: | + package-lock.json + npm-audit.json + if-no-files-found: warn + retention-days: 7 + + - name: Enforce high and critical vulnerability threshold + if: always() + run: | + node <<'NODE' + const fs = require("node:fs"); + + const reportPath = "npm-audit.json"; + + if (!fs.existsSync(reportPath)) { + console.error( + "Dependency audit report was not generated.", + ); + process.exit(2); + } + + let report; + + try { + report = JSON.parse( + fs.readFileSync(reportPath, "utf8"), + ); + } catch (error) { + console.error( + "Dependency audit report is invalid JSON.", + ); + console.error(error); + process.exit(2); + } + + if (report.error) { + console.error("npm audit could not complete:"); + console.error( + JSON.stringify(report.error, null, 2), + ); + process.exit(2); + } + + const counts = report.metadata?.vulnerabilities; + + if (!counts) { + console.error( + "Audit report has no vulnerability totals.", + ); + process.exit(2); + } + + const high = counts.high ?? 0; + const critical = counts.critical ?? 0; + + console.log( + `Audit totals: critical=${critical}, ` + + `high=${high}, ` + + `moderate=${counts.moderate ?? 0}, ` + + `low=${counts.low ?? 0}`, + ); + + for (const [name, vulnerability] of Object.entries( + report.vulnerabilities ?? {}, + )) { + if ( + vulnerability.severity === "high" || + vulnerability.severity === "critical" + ) { + console.error( + `${name}: ${vulnerability.severity}; ` + + `range=${vulnerability.range}; ` + + `fixAvailable=${JSON.stringify( + vulnerability.fixAvailable ?? false, + )}`, + ); + } + } + + if (high > 0 || critical > 0) { + console.error( + "High or critical vulnerabilities remain.", + ); + process.exit(1); + } + + console.log( + "Dependency audit passed the high/critical threshold.", + ); + NODE + + sync-lockfile: + name: Synchronize dependency lockfile + runs-on: ubuntu-latest + needs: checks + if: github.event_name == 'push' && github.ref_name == 'JJTGG-patch-2' && needs.checks.result == 'success' + timeout-minutes: 10 + permissions: + contents: write + actions: write + + steps: + - name: Check out the triggering commit + uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + + - name: Set up Node.js + uses: actions/setup-node@v7 + with: + node-version: 22 + + - name: Check whether manifest and lockfile are in sync + id: lockfile + run: | + node <<'NODE' + const fs = require("node:fs"); + + const manifest = JSON.parse( + fs.readFileSync("package.json", "utf8"), + ); + const lock = JSON.parse( + fs.readFileSync("package-lock.json", "utf8"), + ); + const lockRoot = lock.packages?.[""]; + + if (!lockRoot) { + console.error( + "package-lock.json has no root package entry.", + ); + process.exit(2); + } + + const sections = [ + "dependencies", + "devDependencies", + "optionalDependencies", + ]; + const normalize = (value) => + JSON.stringify( + Object.fromEntries( + Object.entries(value ?? {}).sort( + ([left], [right]) => + left.localeCompare(right), + ), + ), + ); + const mismatches = sections.filter( + (section) => + normalize(manifest[section]) !== + normalize(lockRoot[section]), + ); + const needsRefresh = mismatches.length > 0; + + console.log( + needsRefresh + ? `Lockfile refresh required: ${mismatches.join(", ")}` + : "Manifest and lockfile root dependencies match.", + ); + fs.appendFileSync( + process.env.GITHUB_OUTPUT, + `needs-refresh=${needsRefresh}\n`, + ); + NODE + + - name: Refresh lockfile without running package scripts + if: steps.lockfile.outputs.needs-refresh == 'true' + run: npm install --package-lock-only --ignore-scripts --no-audit --no-fund + + - name: Validate manifest and lockfile synchronization + run: | + node <<'NODE' + const fs = require("node:fs"); + + const manifest = JSON.parse( + fs.readFileSync("package.json", "utf8"), + ); + const lock = JSON.parse( + fs.readFileSync("package-lock.json", "utf8"), + ); + const lockRoot = lock.packages?.[""]; + + if (!lockRoot) { + console.error( + "package-lock.json has no root package entry.", + ); + process.exit(2); + } + + const sections = [ + "dependencies", + "devDependencies", + "optionalDependencies", + ]; + const normalize = (value) => + JSON.stringify( + Object.fromEntries( + Object.entries(value ?? {}).sort( + ([left], [right]) => + left.localeCompare(right), + ), + ), + ); + const mismatches = sections.filter( + (section) => + normalize(manifest[section]) !== + normalize(lockRoot[section]), + ); + + if (mismatches.length > 0) { + console.error( + `Manifest and lockfile still differ: ${mismatches.join(", ")}`, + ); + process.exit(1); + } + + console.log( + "Manifest and lockfile root dependency sections match.", + ); + NODE + + - name: Commit lockfile change when needed + id: commit-lockfile + run: | + set -euo pipefail + + if git diff --quiet -- package-lock.json; then + echo "No package-lock.json change is required." + echo "changed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + git add -- package-lock.json + git diff --cached --check + + git fetch --no-tags origin "refs/heads/${GITHUB_REF_NAME}" + remote_sha="$(git rev-parse FETCH_HEAD)" + + if [[ "$remote_sha" != "$GITHUB_SHA" ]]; then + echo "Branch advanced while CI was running; refusing to commit a stale lockfile." + echo "The newer branch head is left untouched." + echo "changed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + git -c user.name="github-actions[bot]" \ + -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "chore: sync package lockfile" + + git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" + echo "changed=true" >> "$GITHUB_OUTPUT" + + - name: Dispatch verification run for the bot commit + if: steps.commit-lockfile.outputs.changed == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh api \ + --method POST \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/dispatches" \ + -f "ref=${GITHUB_REF_NAME}" diff --git a/app/api/analytics/pageview/route.ts b/app/api/analytics/pageview/route.ts index 03ee06e..865ff22 100644 --- a/app/api/analytics/pageview/route.ts +++ b/app/api/analytics/pageview/route.ts @@ -1,12 +1,14 @@ - import { NextResponse } from "next/server"; import { z } from "zod"; import { createAdminClient } from "@/lib/supabase/admin"; import { createClient } from "@/lib/supabase/server"; +import { readBoundedJsonBody } from "@/lib/security/bounded-json"; export const dynamic = "force-dynamic"; +const MAX_PAGEVIEW_BODY_BYTES = 2048; + const eventSchema = z .object({ pageviewId: z.uuid(), @@ -41,21 +43,19 @@ function response(status = 202, accepted = true) { } export async function POST(request: Request) { - let body: unknown; - - try { - const rawBody = await request.text(); - - if (rawBody.length > 2048) { - return response(413, false); - } + const boundedBody = await readBoundedJsonBody( + request, + MAX_PAGEVIEW_BODY_BYTES, + ); - body = JSON.parse(rawBody); - } catch { - return response(400, false); + if (!boundedBody.ok) { + return response( + boundedBody.reason === "too_large" ? 413 : 400, + false, + ); } - const parsed = eventSchema.safeParse(body); + const parsed = eventSchema.safeParse(boundedBody.value); if (!parsed.success) { return response(400, false); @@ -63,13 +63,14 @@ export async function POST(request: Request) { try { const supabase = await createClient(); + const { data: { user }, error: authError, } = await supabase.auth.getUser(); - // Anonymous page views are valid. A failed session lookup must never - // cause a client-supplied user ID to be trusted. + // Anonymous page views are valid. A failed session lookup must + // never cause a client-supplied user ID to be trusted. const actorId = authError ? null : user?.id ?? null; const rawCountry = request.headers @@ -106,4 +107,4 @@ export async function POST(request: Request) { console.error("Agoré analytics endpoint failed:", error); return response(503, false); } -} +} \ No newline at end of file diff --git a/app/api/onboarding/route.ts b/app/api/onboarding/route.ts index af23c8d..7ebcce5 100644 --- a/app/api/onboarding/route.ts +++ b/app/api/onboarding/route.ts @@ -19,30 +19,6 @@ const onboardingSchema = z.object({ export async function POST(request: Request) { try { - let body: unknown; - - try { - body = await request.json(); - } catch { - return NextResponse.json( - { error: "Invalid request body." }, - { status: 400 }, - ); - } - - const parsed = onboardingSchema.safeParse(body); - - if (!parsed.success) { - return NextResponse.json( - { - error: - parsed.error.issues[0]?.message ?? - "Invalid profile details.", - }, - { status: 400 }, - ); - } - const supabase = await createClient(); const { @@ -102,40 +78,91 @@ export async function POST(request: Request) { ); } - if (existingProfile) { - return NextResponse.json({ - completed: true, - }); - } + if (!existingProfile) { + let body: unknown; - const { error: profileError } = await admin - .from("profiles") - .insert({ - id: authoritativeUser.id, - display_name: parsed.data.displayName, - username: parsed.data.username, - bio: parsed.data.bio || null, - }); - - if (profileError) { - if (profileError.code === "23505") { + try { + body = await request.json(); + } catch { return NextResponse.json( - { error: "That username is already taken." }, - { status: 409 }, + { error: "Invalid request body." }, + { status: 400 }, ); } - console.error( - "Agore profile creation failed:", - profileError, - ); + const parsed = onboardingSchema.safeParse(body); - return NextResponse.json( - { error: "Unable to create your profile." }, - { status: 500 }, - ); + if (!parsed.success) { + return NextResponse.json( + { + error: + parsed.error.issues[0]?.message ?? + "Invalid profile details.", + }, + { status: 400 }, + ); + } + + const { error: profileError } = await admin + .from("profiles") + .insert({ + id: authoritativeUser.id, + display_name: parsed.data.displayName, + username: parsed.data.username, + bio: parsed.data.bio || null, + }); + + if (profileError) { + if (profileError.code !== "23505") { + console.error( + "Agore profile creation failed:", + profileError, + ); + + return NextResponse.json( + { error: "Unable to create your profile." }, + { status: 500 }, + ); + } + + // A concurrent request may have created this user's profile + // after the initial lookup. Distinguish that case from a + // username collision belonging to another account. + const { + data: concurrentProfile, + error: concurrentProfileLookupError, + } = await admin + .from("profiles") + .select("id") + .eq("id", authoritativeUser.id) + .maybeSingle(); + + if (concurrentProfileLookupError) { + console.error( + "Failed to verify profile after creation conflict:", + concurrentProfileLookupError, + ); + + return NextResponse.json( + { error: "Unable to verify your profile." }, + { status: 500 }, + ); + } + + if (!concurrentProfile) { + return NextResponse.json( + { error: "That username is already taken." }, + { status: 409 }, + ); + } + } } + // Always initialize these records, including when the profile + // already exists. This makes retries recover from partial failure. + // + // Only user_id is supplied. Existing preference values are not + // intentionally replaced; missing rows use database defaults. const [ { error: preferencesError }, { error: settingsError }, @@ -167,7 +194,7 @@ export async function POST(request: Request) { return NextResponse.json( { error: - "Profile created, but account preferences could not be initialized.", + "Your profile exists, but account preferences could not be initialized. Please try again.", }, { status: 500 }, ); diff --git a/app/api/public/posts/[postId]/route.ts b/app/api/public/posts/[postId]/route.ts index 4be424c..7896278 100644 --- a/app/api/public/posts/[postId]/route.ts +++ b/app/api/public/posts/[postId]/route.ts @@ -1,278 +1,20 @@ - import { NextResponse } from "next/server"; -import { z } from "zod"; - -import { createAdminClient } from "@/lib/supabase/admin"; export const dynamic = "force-dynamic"; -const postIdSchema = z.uuid(); - const noStoreHeaders = { "Cache-Control": "no-store, max-age=0", + "X-Robots-Tag": "noindex, nofollow", }; -type AccountType = - | "personal" - | "creator" - | "business" - | "organization" - | "institution"; - -type VerificationKind = "agore_official" | "paid" | null; - -type ProfileRow = { - display_name: string; - username: string; - avatar_path: string | null; - account_type: AccountType; - account_status: string; -}; - -type MediaRow = { - id: string; - storage_path: string; - mime_type: string; - size_bytes: number; - width: number | null; - height: number | null; - sort_order: number; - created_at: string; -}; - -type VerificationRow = { - verification_kind: "agore_official" | "paid" | "official"; - expires_at: string | null; - revoked_at: string | null; -}; - -type PostRow = { - id: string; - author_id: string; - content: string; - created_at: string; - updated_at: string; - post_media: MediaRow[] | null; - profiles: ProfileRow | ProfileRow[] | null; -}; - -type PublicMediaRow = MediaRow & { - signed_url: string | null; -}; - -function normalizeProfile( - profile: ProfileRow | ProfileRow[] | null, -): ProfileRow | null { - if (!profile) { - return null; - } - - return Array.isArray(profile) - ? profile[0] ?? null - : profile; -} - -function sortMedia(media: MediaRow[] | null | undefined) { - return [...(media ?? [])].sort( - (a, b) => - a.sort_order - b.sort_order || - new Date(a.created_at).getTime() - - new Date(b.created_at).getTime(), +export async function GET() { + return NextResponse.json( + { + error: "Public post previews are temporarily unavailable.", + }, + { + status: 404, + headers: noStoreHeaders, + }, ); -} - -function getActiveVerificationKind( - grant: VerificationRow | null, -): VerificationKind { - if (!grant || grant.revoked_at !== null) { - return null; - } - - if ( - (grant.verification_kind === "agore_official" || - grant.verification_kind === "official") && - grant.expires_at === null - ) { - return "agore_official"; - } - - if ( - grant.verification_kind === "paid" && - grant.expires_at !== null && - Date.parse(grant.expires_at) > Date.now() - ) { - return "paid"; - } - - return null; -} - -export async function GET( - _: Request, - context: { - params: Promise<{ postId: string }>; - }, -) { - const { postId } = await context.params; - const parsedId = postIdSchema.safeParse(postId); - - if (!parsedId.success) { - return NextResponse.json( - { error: "Invalid post ID." }, - { status: 400, headers: noStoreHeaders }, - ); - } - - try { - const admin = createAdminClient(); - - const { data, error } = await admin - .from("posts") - .select(` - id, - author_id, - content, - created_at, - updated_at, - post_media ( - id, - storage_path, - mime_type, - size_bytes, - width, - height, - sort_order, - created_at - ), - profiles!posts_author_id_fkey ( - display_name, - username, - avatar_path, - account_type, - account_status - ) - `) - .eq("id", parsedId.data) - .is("deleted_at", null) - .maybeSingle(); - - if (error) { - console.error("Failed to load shared Agoré post:", error); - - return NextResponse.json( - { error: "Unable to load this post." }, - { status: 500, headers: noStoreHeaders }, - ); - } - - const post = data as unknown as PostRow | null; - - if (!post) { - return NextResponse.json( - { error: "Post not found." }, - { status: 404, headers: noStoreHeaders }, - ); - } - - const profile = normalizeProfile(post.profiles); - - // Only active accounts can expose posts through public share links. - if (!profile || profile.account_status !== "active") { - return NextResponse.json( - { error: "Post not found." }, - { status: 404, headers: noStoreHeaders }, - ); - } - - const [verificationResult, avatarResult] = - await Promise.all([ - admin - .from("profile_verifications") - .select("verification_kind, expires_at, revoked_at") - .eq("user_id", post.author_id) - .maybeSingle(), - - profile.avatar_path - ? admin.storage - .from("avatars") - .createSignedUrl(profile.avatar_path, 60 * 60) - : Promise.resolve({ data: null, error: null }), - ]); - - if (verificationResult.error) { - console.error( - "Unable to load shared-post verification status:", - verificationResult.error, - ); - } - - const verificationKind = getActiveVerificationKind( - verificationResult.error - ? null - : (verificationResult.data as VerificationRow | null), - ); - - const avatarUrl = - avatarResult.data && !avatarResult.error - ? avatarResult.data.signedUrl - : null; - - // The buckets remain private. These links are temporary and are - // created only for attachments belonging to this visible post. - const media: PublicMediaRow[] = await Promise.all( - sortMedia(post.post_media).map(async (item) => { - if (!item.storage_path.startsWith(`${post.id}/`)) { - return { ...item, signed_url: null }; - } - - const { data: signedData, error: signedError } = - await admin.storage - .from("post-media") - .createSignedUrl(item.storage_path, 60 * 60); - - if (signedError) { - console.error( - "Unable to sign shared-post attachment:", - signedError, - ); - - return { ...item, signed_url: null }; - } - - return { - ...item, - signed_url: signedData.signedUrl, - }; - }), - ); - - return NextResponse.json( - { - post: { - id: post.id, - author_id: post.author_id, - content: post.content, - created_at: post.created_at, - updated_at: post.updated_at, - post_media: media, - profiles: { - display_name: profile.display_name, - username: profile.username, - avatar_path: profile.avatar_path, - avatar_url: avatarUrl, - account_type: profile.account_type, - verification_kind: verificationKind, - }, - }, - }, - { headers: noStoreHeaders }, - ); - } catch (error) { - console.error("Public Agoré post endpoint failed:", error); - - return NextResponse.json( - { error: "Unable to load this post." }, - { status: 500, headers: noStoreHeaders }, - ); - } -} +} \ No newline at end of file diff --git a/app/auth/page.tsx b/app/auth/page.tsx index e99bfd4..a23e4bd 100644 --- a/app/auth/page.tsx +++ b/app/auth/page.tsx @@ -65,6 +65,13 @@ export default function AuthPage() { useEffect(() => { const params = new URLSearchParams(window.location.search); const currentError = params.get("error"); + const requestedMode = params.get("mode"); + + if (requestedMode === "signup") { + setMode("signup"); + } else if (requestedMode === "signin") { + setMode("signin"); + } setCallbackError(currentError); diff --git a/app/page.tsx b/app/page.tsx index 8eef8f5..f7168d2 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -73,7 +73,7 @@ export default function Home() {