From 90ad185c1e53f56b8965d7fa225f0b239cf5e1ec Mon Sep 17 00:00:00 2001 From: ASHISH SINGH BORA Date: Fri, 30 Oct 2026 07:18:35 +0530 Subject: [PATCH] feat(platform): improve contributor integrity, privacy and governance (#13) --- .github/ISSUE_TEMPLATE/bug_report.md | 32 ++ .github/ISSUE_TEMPLATE/feature_request.md | 26 ++ .github/ISSUE_TEMPLATE/security_report.md | 32 ++ .github/pull_request_template.md | 29 ++ CODE_OF_CONDUCT.md | 74 +++++ PRIVACY.md | 95 ++++++ drizzle/0006_privacy_and_governance.sql | 3 + drizzle/meta/_journal.json | 7 + src/app/api/user/delete/route.ts | 56 ++++ src/app/api/user/export/route.ts | 121 +++++++ src/app/api/user/settings/route.ts | 8 +- src/app/dashboard/settings/SettingsForm.tsx | 351 ++++++++++++-------- src/lib/db/schema.ts | 3 +- src/lib/metrics/contributor-metrics.ts | 17 +- src/lib/passport/index.ts | 9 +- src/lib/privacy.test.ts | 161 +++++++++ 16 files changed, 877 insertions(+), 147 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/security_report.md create mode 100644 .github/pull_request_template.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 PRIVACY.md create mode 100644 drizzle/0006_privacy_and_governance.sql create mode 100644 src/app/api/user/delete/route.ts create mode 100644 src/app/api/user/export/route.ts create mode 100644 src/lib/privacy.test.ts diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..2c6e1b8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug Report +about: Create a report to help us improve TechNexusOrg +title: 'fix: ' +labels: ['bug'] +assignees: '' +--- + +### Describe the Bug +A clear and concise description of what the bug is. + +### Reproduction Steps +1. Navigate to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +### Expected Behavior +A clear and concise description of what you expected to happen. + +### Screenshots or Terminal Logs +If applicable, add screenshots or paste command logs to help explain your problem. + +### Environment Context +- OS: [e.g. Linux Ubuntu 24.04, macOS Sonoma, Windows 11 WSL2] +- Browser: [e.g. Chrome, Firefox, Safari] +- Node version: [e.g. v22.14.0] +- Shell: [e.g. bash, zsh] + +### Verification Checklist +- [ ] I have checked that no existing issue addresses this bug. +- [ ] I can consistently reproduce this behavior on the latest `main` branch. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..7f4d179 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,26 @@ +--- +name: Feature Proposal +about: Suggest an idea, track, or enhancement for TechNexusOrg +title: 'feat: ' +labels: ['enhancement'] +assignees: '' +--- + +### Problem Description +Is your feature request related to a problem? Please describe clearly. +*Example: As a student contributor, I find it difficult to track my milestone progress because...* + +### Proposed Solution +A clear and concise description of what you want to happen and the engineering approach. + +### Alternatives Considered +A clear and concise description of any alternative solutions or features you've considered. + +### Student Impact & Educational Value +Explain how this feature empowers students to build real software and verifiable proof of work. + +### Implementation Checklist +- [ ] Database schema changes needed (if any) +- [ ] Backend API endpoints needed +- [ ] Frontend UI / UX components needed +- [ ] Unit & integration tests to be written diff --git a/.github/ISSUE_TEMPLATE/security_report.md b/.github/ISSUE_TEMPLATE/security_report.md new file mode 100644 index 0000000..cc538f1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/security_report.md @@ -0,0 +1,32 @@ +--- +name: Security Vulnerability Report +about: Privately report a security issue in the TechNexusOrg platform +title: '[SECURITY]: ' +labels: ['security', 'priority: critical'] +assignees: '' +--- + +> **IMPORTANT:** Do NOT disclose vulnerabilities publicly in public issues or comments. +> If this vulnerability presents an active exploit risk or secret leakage, please report privately via GitHub Security Advisories or refer to [SECURITY.md](../SECURITY.md). + +### Vulnerability Summary +A brief description of the vulnerability. + +### Affected Components +- File(s) / Route(s): +- Subsystem: [e.g. Authentication, Webhook Ingestion, Trust Boundary, Database, API Authorization] + +### Impact & Severity +- [ ] Critical (Remote Code Execution, Unauthorized Admin Elevation, Secret Exposure) +- [ ] High (CSRF on State-Changing Admin Routes, Data Exfiltration, Claim Injection) +- [ ] Medium (Unverified Repository Ingestion, Information Leak) +- [ ] Low (UI Spoofing, Minor Informational Leak) + +### Proof of Concept (PoC) +Steps to reproduce the vulnerability safely in a local test environment: +1. +2. +3. + +### Recommended Remediation +Any proposed patches or hardening steps. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..a6f3b78 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,29 @@ +## Summary + + +## Changes + +- + +## Architecture & Design Decisions + + +## Security Considerations + + +## Database Migrations + + +## Testing & Quality Assurance + +- [ ] \`npm run lint\` passed +- [ ] \`npm run typecheck\` passed +- [ ] \`npm test\` passed +- [ ] \`npm run build\` passed + +## Deployment Considerations + + +## Related Issues + +Fixes # diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f5335a3 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Code of Conduct + +## Our Pledge + +In the interest of fostering an open, welcoming, and high-standard engineering environment, we as contributors and maintainers of **TechNexusOrg** pledge to make participation in our community a harassment-free and empowering experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy student engineering community. + +--- + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* **Demonstrating empathy and kindness:** Remember that everyone started as a beginner. When reviewing pull requests, provide constructive, actionable, and courteous feedback. +* **Respecting different viewpoints and experiences:** Welcome diverse engineering approaches, question assumptions respectfully, and prioritize collaborative learning over personal ego. +* **Giving and gracefully accepting constructive feedback:** Technical code reviews are intended to elevate engineering standards, not criticize individuals. Accept feedback as an opportunity to grow. +* **Focusing on what is best for the community and codebase:** Prioritize code quality, test coverage, and long-term maintainability. +* **Showing solidarity with fellow students:** Encourage peers, share insights on architecture and debugging, and assist teammates when they encounter blockers. + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind. +* Trolling, insulting or derogatory comments, and personal or political attacks. +* Public or private harassment. +* Publishing others' private information, such as physical or email addresses, without their explicit permission. +* Cheating, plagiarism, copy-pasting solutions without understanding, or submitting artificial PRs to game progression metrics. +* Other conduct which could reasonably be considered inappropriate in a professional setting. + +--- + +## Enforcement Responsibilities + +Community maintainers and project leads are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +--- + +## Scope + +This Code of Conduct applies within all official TechNexusOrg repositories, discussion forums, issue trackers, live cohort sessions, and in public spaces when an individual is representing the community. + +--- + +## Enforcement Guidelines + +Community maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction +**Community Impact:** Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. +**Consequence:** A private, written warning from community maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning +**Community Impact:** A violation through a single incident or series of actions. +**Consequence:** A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. + +### 3. Temporary Suspension +**Community Impact:** A serious violation of community standards, including sustained inappropriate behavior. +**Consequence:** A temporary ban from any sort of interaction or public communication with the community for a specified period of time. Violation of these terms may lead to a permanent ban. + +### 4. Permanent Ban +**Community Impact:** Demonstrating a pattern of violation of community standards, including sustained harassment of an individual, aggression toward or disparagement of classes of individuals, or intentional academic dishonesty/sabotage. +**Consequence:** A permanent ban from any sort of public interaction within the community and revocation of platform privileges. + +--- + +## Reporting + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the TechNexusOrg maintainers at `conduct@technexus.org` *(or by opening a confidential discussion with the organization administrators on GitHub)*. All complaints will be reviewed and investigated promptly and fairly. + +--- + +*Adapted from the Contributor Covenant, version 2.1.* diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..01fbec9 --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,95 @@ +# TechNexusOrg Privacy Policy + +> **NOTICE: DRAFT DOCUMENT REQUIRING RESPONSIBLE LEGAL REVIEW** +> *This document sets out the operational and technical privacy practices of the TechNexusOrg platform. It is currently in draft status and requires formal legal review by qualified counsel before being designated as a binding legal agreement. Entity details and contact addresses are marked with placeholders until formally incorporated.* + +--- + +## 1. Introduction and Philosophy + +TechNexusOrg operates a GitHub-native engineering platform for students and early-career developers. Our engineering philosophy is **Privacy by Default**: +- Student profiles are private by default upon registration. +- No personal data or email addresses are published without explicit contributor consent. +- GitHub activity records (commits, pull requests, issue claims) link directly to official GitHub public URLs rather than storing duplicate private repository data. + +--- + +## 2. Information We Collect + +### A. Authentication & GitHub Data +When you authenticate via GitHub OAuth, we receive from GitHub: +- Immutable GitHub numeric User ID. +- GitHub username (`login`). +- Public profile information (avatar URL, bio, location, public profile link). +- Primary verified email address (stored privately for authentication and critical security notifications; never published publicly). + +### B. Contributor Profile Data (Self-Reported) +- Technical skills, interests, and preferred programming languages. +- Optional portfolio and LinkedIn URLs. +- Self-selected learning track enrollment and assignment submissions. + +### C. Contribution & Progression Records +- Pull request numbers, titles, and merge statuses on official TechNexusOrg repositories. +- Code review participation on approved projects. +- Issue claim timestamps and completion records. +- Verifiable credentials and founding member sequence allocations. + +--- + +## 3. Purpose of Processing + +We process student data strictly to: +1. Facilitate open-source project matching and issue reservation (preventing claim conflicts). +2. Verify pull request merges on official TechNexusOrg projects. +3. Compute authoritative progression levels and mint verifiable credentials. +4. Provide structured mentorship and code review workflows. +5. Enable students to demonstrate verifiable public proof of work when they opt to make their Contributor Passport public. + +We do **not** sell student data, license student records to marketing brokers, or serve third-party behavioral advertisements. + +--- + +## 4. Profile Visibility & Consent + +- **Private by Default:** All newly created student accounts start in private mode (`is_public = false`). +- **Explicit Consent Toggle:** Contributor Passports at `/people/` and inclusion in `/people` directory become accessible only when a contributor explicitly toggles their passport to public in `Settings`. +- **Public Proof of Work:** When public mode is enabled, your passport showcases your GitHub username, display name, skills, and verified public contribution links. Private email addresses and internal database identifiers are never displayed. +- **Revocation of Consent:** Contributors may switch their profile back to private at any time in their dashboard settings. + +--- + +## 5. Data Sharing + +Data is only shared with: +- **GitHub API:** To verify repository permissions, pull request merge events, and review statuses. +- **Hosting and Database Infrastructure:** Secure cloud database infrastructure adhering to industry encryption standards (TLS in transit, encrypted storage at rest). + +--- + +## 6. Data Retention and Account Erasure (GDPR Rights) + +- **Data Portability:** Students have the right to download a complete export of all personal, profile, contribution, claim, and credential data in machine-readable JSON format at any time via `/api/user/export`. +- **Right to Erasure (Account Deletion):** Students may permanently delete their account and associated personal data at any time via `/api/user/delete` or the settings dashboard. Deletion permanently removes profile details, claims, mentor requests, and notifications. + +--- + +## 7. Security Safeguards + +- Session tokens use cryptographic signing with secure, HttpOnly, and SameSite cookie policies. +- Ingestion endpoints enforce HMAC SHA-256 signature verification and delivery idempotency. +- Role-based authorization is verified server-side against fresh database state for all privileged operations. + +--- + +## 8. Responsible Entity & Contact Information + +| Detail | Status / Placeholder | +| :--- | :--- | +| **Operating Entity** | TechNexusOrg Community Initiative *(Formal MSME / legal entity registration in progress)* | +| **Jurisdiction** | Uttarakhand, India | +| **Privacy Officer** | `privacy@technexus.org` *(placeholder until official domain email is provisioned)* | +| **Security Reports** | Please refer to [SECURITY.md](SECURITY.md) | + +--- + +*Last revised: October 2026. This policy will be updated as formal institutional and community registrations are finalized.* diff --git a/drizzle/0006_privacy_and_governance.sql b/drizzle/0006_privacy_and_governance.sql new file mode 100644 index 0000000..9036eed --- /dev/null +++ b/drizzle/0006_privacy_and_governance.sql @@ -0,0 +1,3 @@ +ALTER TABLE "users" ALTER COLUMN "is_public" SET DEFAULT false; +--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "public_consent_given_at" timestamp with time zone; diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index a132e80..c52be88 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1793325000000, "tag": "0005_project_trust_boundary", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1793326000000, + "tag": "0006_privacy_and_governance", + "breakpoints": true } ] } diff --git a/src/app/api/user/delete/route.ts b/src/app/api/user/delete/route.ts new file mode 100644 index 0000000..9c7c0bf --- /dev/null +++ b/src/app/api/user/delete/route.ts @@ -0,0 +1,56 @@ +import { NextRequest, NextResponse } from "next/server"; +import { verifySessionToken, COOKIE_NAME } from "@/lib/auth/session"; +import { getDb, schema } from "@/lib/db"; +import { eq } from "drizzle-orm"; + +/** + * Handles account deletion requests in compliance with GDPR / right to erasure. + * Permanently deletes the user record and cascades to profile, notifications, claims, etc. + */ +export async function POST(request: NextRequest) { + const token = request.cookies.get(COOKIE_NAME)?.value; + if (!token) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const sessionUser = await verifySessionToken(token); + if (!sessionUser) { + return NextResponse.json({ error: "Invalid session" }, { status: 401 }); + } + + try { + const db = await getDb(); + + // Audit log before deletion for compliance records + await db.insert(schema.auditLogs).values({ + id: `audit_${crypto.randomUUID()}`, + actorId: sessionUser.id, + action: "user.account_deleted", + targetType: "user", + targetId: sessionUser.id, + metadata: { + githubUsername: sessionUser.githubUsername, + deletedAt: new Date().toISOString(), + }, + }); + + // Delete user from database (cascades to profile, claims, notifications, mentor_requests) + await db.delete(schema.users).where(eq(schema.users.id, sessionUser.id)); + + const response = NextResponse.json({ + success: true, + message: "Your account and all associated personal records have been successfully deleted.", + }); + + // Clear session cookie + response.cookies.delete(COOKIE_NAME); + + return response; + } catch (error: any) { + console.error("Account deletion failed:", error); + return NextResponse.json( + { error: error.message || "Failed to delete account" }, + { status: 500 } + ); + } +} diff --git a/src/app/api/user/export/route.ts b/src/app/api/user/export/route.ts new file mode 100644 index 0000000..6f1ed97 --- /dev/null +++ b/src/app/api/user/export/route.ts @@ -0,0 +1,121 @@ +import { NextRequest, NextResponse } from "next/server"; +import { verifySessionToken, COOKIE_NAME } from "@/lib/auth/session"; +import { getDb, schema } from "@/lib/db"; +import { eq } from "drizzle-orm"; + +/** + * Handles personal data export requests in compliance with GDPR / data portability. + * Returns an exhaustive JSON document containing all personal and contribution records. + */ +export async function GET(request: NextRequest) { + const token = request.cookies.get(COOKIE_NAME)?.value; + if (!token) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const sessionUser = await verifySessionToken(token); + if (!sessionUser) { + return NextResponse.json({ error: "Invalid session" }, { status: 401 }); + } + + try { + const db = await getDb(); + + // 1. Fetch user core record + const [user] = await db + .select() + .from(schema.users) + .where(eq(schema.users.id, sessionUser.id)) + .limit(1); + + if (!user) { + return NextResponse.json({ error: "User not found" }, { status: 404 }); + } + + // 2. Fetch profile + const [profile] = await db + .select() + .from(schema.profiles) + .where(eq(schema.profiles.userId, sessionUser.id)) + .limit(1); + + // 3. Fetch contributions + const contributions = await db + .select() + .from(schema.contributions) + .where(eq(schema.contributions.userId, sessionUser.id)); + + // 4. Fetch credentials + const credentials = await db + .select() + .from(schema.credentials) + .where(eq(schema.credentials.userId, sessionUser.id)); + + // 5. Fetch issue claims + const claims = await db + .select() + .from(schema.issueClaims) + .where(eq(schema.issueClaims.userId, sessionUser.id)); + + // 6. Fetch mentor requests + const mentorRequests = await db + .select() + .from(schema.mentorRequests) + .where(eq(schema.mentorRequests.studentId, sessionUser.id)); + + // 7. Fetch notifications + const notifications = await db + .select() + .from(schema.notifications) + .where(eq(schema.notifications.userId, sessionUser.id)); + + const exportPayload = { + exportMetadata: { + platform: "TechNexusOrg", + schemaVersion: "1.0.0", + exportedAt: new Date().toISOString(), + subjectId: user.id, + githubUsername: user.githubUsername, + }, + account: { + id: user.id, + githubId: user.githubId, + githubUsername: user.githubUsername, + displayName: user.displayName, + email: user.email, + bio: user.bio, + location: user.location, + portfolioUrl: user.portfolioUrl, + linkedinUrl: user.linkedinUrl, + role: user.role, + level: user.level, + foundingNumber: user.foundingNumber, + isOnboarded: user.isOnboarded, + isPublic: user.isPublic, + publicConsentGivenAt: user.publicConsentGivenAt, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + }, + profile: profile || null, + contributions, + credentials, + issueClaims: claims, + mentorRequests, + notifications, + }; + + return new NextResponse(JSON.stringify(exportPayload, null, 2), { + status: 200, + headers: { + "Content-Type": "application/json; charset=utf-8", + "Content-Disposition": `attachment; filename="technexus-data-${user.githubUsername}.json"`, + }, + }); + } catch (error: any) { + console.error("Data export failed:", error); + return NextResponse.json( + { error: error.message || "Failed to export data" }, + { status: 500 } + ); + } +} diff --git a/src/app/api/user/settings/route.ts b/src/app/api/user/settings/route.ts index 7573a52..57ff430 100644 --- a/src/app/api/user/settings/route.ts +++ b/src/app/api/user/settings/route.ts @@ -10,7 +10,7 @@ const settingsSchema = z.object({ location: z.string().max(100).optional(), portfolioUrl: z.string().url().or(z.literal("")).optional(), linkedinUrl: z.string().url().or(z.literal("")).optional(), - isPublic: z.boolean().default(true), + isPublic: z.boolean().default(false), skills: z.array(z.string()).default([]), }); @@ -29,8 +29,9 @@ export async function PATCH(request: NextRequest) { const body = await request.json(); const data = settingsSchema.parse(body); const db = await getDb(); + const now = new Date(); - // Update user record + // Update user record and track public consent timestamp await db .update(schema.users) .set({ @@ -40,7 +41,8 @@ export async function PATCH(request: NextRequest) { portfolioUrl: data.portfolioUrl || null, linkedinUrl: data.linkedinUrl || null, isPublic: data.isPublic, - updatedAt: new Date(), + publicConsentGivenAt: data.isPublic ? now : null, + updatedAt: now, }) .where(eq(schema.users.id, sessionUser.id)); diff --git a/src/app/dashboard/settings/SettingsForm.tsx b/src/app/dashboard/settings/SettingsForm.tsx index 087c7da..2c398db 100644 --- a/src/app/dashboard/settings/SettingsForm.tsx +++ b/src/app/dashboard/settings/SettingsForm.tsx @@ -28,6 +28,7 @@ export function SettingsForm({ const [skillInput, setSkillInput] = useState(""); const [skills, setSkills] = useState(initialSkills || []); const [submitting, setSubmitting] = useState(false); + const [deleting, setDeleting] = useState(false); const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null); const addSkill = () => { @@ -76,174 +77,248 @@ export function SettingsForm({ } }; - return ( -
- {message && ( -
- {message.text} -
- )} + const handleDeleteAccount = async () => { + const confirmed = window.confirm( + "Are you absolutely sure you want to delete your TechNexusOrg account? This action is permanent and deletes your profile, claims, and stored records." + ); + if (!confirmed) return; - {/* Privacy Toggle */} -
-
-
-

- Public Contributor Passport -

-

- When enabled, your passport is visible at /people/{initialUser.githubUsername}. -

-
- + > + + +
- - - {/* Display Name */} -
- - setDisplayName(e.target.value)} - placeholder={initialUser.githubUsername} - className="w-full rounded-lg border border-slate-800 bg-slate-900/60 px-3 py-2 text-xs text-white placeholder-slate-500 focus:border-sky-500 focus:outline-none font-mono" - /> -
- - {/* Bio */} -
- -