# Technical Security Testing & DPDP Compliance Verification Manual (Consultation Portal)

This document is a step-by-step Standard Operating Procedure (SOP) to test, audit, and verify the security and legal compliance measures implemented on the Consultation portal. 

All verification steps are designed to be executed directly within a standard **Web Browser (e.g., Google Chrome)** using either the user interface or the browser's built-in **Developer Tools**. No external terminal commands (like `curl`) or command-line tools are required.

---

## Environment URL Reference Sheet
Use the appropriate root URL for the environment you are currently testing:

*   **Local Development**: `http://localhost:3020`
*   **Staging Environment**: `https://staging.myconsultation.sevenpointfour.in`
*   **Production Environment**: `https://myconsultation.sevenpointfour.in`

In the steps below, **`[PORTAL_URL]`** refers to the active environment URL selected from the list above (for example, `http://localhost:3020` if testing locally).

---

## Part 1: Technical Security Controls

### SEC-01: Secure Session Cookies & HTTPS Redirection
*   **What does this mean?**
    A "cookie" is a small digital badge the server gives your browser so it remembers you are logged in. If a hacker runs bad code in your browser, they could try to steal this badge and pretend to be you. This test ensures the browser locks your badge down so that other website scripts cannot see or steal it, and that all standard HTTP connection lines are automatically redirected to secure, encrypted HTTPS lines.
*   **Measure Applied**: 
    Protects client and staff authentication tokens from extraction via Cross-Site Scripting (XSS) by dynamically setting strict flags (`httpOnly`, `sameSite: 'Strict'`, and environment-aware `secure: process.env.NODE_ENV === 'production'`). It also actively redirects all plain HTTP traffic to secure HTTPS in production environments.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open your web browser and navigate to: **`[PORTAL_URL]/login.html`**
    2. Open **Developer Tools** (Press `F12` or Right-Click anywhere and select **Inspect**).
    3. Log in successfully using your account credentials (or request and verify OTP).
    4. Select the **Application** tab in the top menu of Developer Tools.
    5. In the left panel under *Storage*, expand **Cookies** and click on the portal URL.
    6. Locate the cookie named **`token`**.
    7. **Pass Criteria**:
        *   Verify the **HttpOnly** checkbox/column is **checked (true)**.
        *   Verify the **SameSite** column displays **`Strict`**.
        *   *(For Staging/Production environments)*: Verify the **Secure** checkbox/column is **checked (true)**.
        *   *(For Production environments)*: Navigate to the plain HTTP link (e.g., `http://myconsultation.sevenpointfour.in`). Verify that the browser immediately redirects you to `https://myconsultation.sevenpointfour.in`.
(THIS TEST WAS SUCCESSFUL)

---

### SEC-02: Login and Reset Password Rate Limiting
*   **What does this mean?**
   
    Hackers use fast computers to guess passwords or request thousands of login codes to crash the system. This test proves that if anyone tries to request codes or log in too many times (more than 5 times in 15 minutes) from the same computer connection, the server locks them out. They are blocked and forced to wait, making automated guessing attacks impossible.
*   **Measure Applied**: 
    Throttles brute-force attempts on credentials, OTPs, and password reset routes by restricting connections to a maximum of 5 requests per 15 minutes per IP address.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to: **`[PORTAL_URL]/login.html`**
    2. Enter an email address and click the login/OTP submission button.
    3. Consecutively submit/request 5 more times (6 times total).
    4. **Pass Criteria**:
        *   On the 6th attempt, the application must block the request.
        *   An error message must display on the UI: **"Too many attempts from this IP, please try again after 15 minutes"** (or return an HTTP status code **`429 Too Many Requests`** in the DevTools Network tab).
(THIS TEST WAS SUCCESSFUL)

---

### SEC-03: Security HTTP Headers (Helmet & Hardened CSP)
*   **What does this mean?**
    Sometimes hackers try to display your website inside a hidden, invisible frame on another website (like placing a fake invisible page on top of yours) to trick you into clicking buttons or typing details you didn't mean to. They also try to inject malicious script code directly into your pages. This test confirms that our server tells the browser: "Never display my website inside any other website's frame, and never execute unauthorized inline scripts." This stops click-tricking and script injection attacks.
*   **Measure Applied**: 
    Loads security headers on HTTP responses to secure the client context from Clickjacking, MIME-sniffing, and cross-site scripting (XSS). It implements a hardened Content Security Policy (CSP) with Helmet that completely disables `'unsafe-inline'` for scripts, allowing script execution strictly from `'self'` and trusted CDN source (`https://cdn.ckeditor.com`), requiring all inline scripts to be extracted into external files.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to the homepage: **`[PORTAL_URL]/`**
    2. Open **Developer Tools** (`F12`) and select the **Network** tab.
    3. Reload the page (`Ctrl + R`).
    4. Click on the first document request in the list (e.g., `login.html` or the domain name).
    5. Select the **Headers** tab in the right pane and locate **Response Headers**.
    6. **Pass Criteria**:
        *   Verify that `X-Frame-Options: SAMEORIGIN` (or CSP frame-ancestors equivalent) is present in the list.
        *   Verify that `X-Content-Type-Options: nosniff` is present in the list.
        *   Verify that `Content-Security-Policy` is active and contains:
            *   `script-src 'self' https://cdn.ckeditor.com` (Note that **`'unsafe-inline'` must not be present** in the `script-src` directive).
            *   `object-src 'none'`
            *   `frame-src 'none'`
        *   Navigate to the **Console** tab in Developer Tools, reload the page, and verify that there are **no red CSP violation messages** regarding blocked inline scripts.
(THIS TEST WAS SUCCESSFUL)

---

### SEC-04: Sensitive Logging Redaction & Log Rotation
*   **What does this mean?**
    Our server writes a diary (logs) of what is happening so we can troubleshoot if something breaks. However, if a hacker gets access to this diary, we don't want them to see your email address or password. This test proves that before writing anything to the server log files, the system automatically crosses out emails and passwords (replacing them with `[REDACTED]`), keeping your private information safe. It also confirms that logs older than a year are automatically deleted to prevent data hoarding.
*   **Measure Applied**: 
    Automatically redacts sensitive details (passwords, tokens, database hashes, emails, authorization headers) from standard log files. It also implements an automated daily retention process that deletes log files older than 365 days.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Access your server environment (or locate the active log directory under `c:\Users\Madhav\Sevenpointfour\consultation\logs`).
    2. Open one of the active log files (formatted as `app-YYYY-MM-DD.log`).
    3. Search for occurrences of user login payloads, password attempts, or email addresses.
    4. **Pass Criteria**:
        *   Verify that password fields, tokens, and authorization fields are printed strictly as `[REDACTED]`.
        *   Verify that raw email formats in data objects or trace descriptions are fully replaced by `[REDACTED]`.
        *   Verify that only log files modified within the last 365 days exist in the log directory.
(THIS TEST WAS SUCCESSFUL)

---

### SEC-05: Password Complexity Policy Enforcement
*   **What does this mean?**
    To protect accounts, users must create strong passwords. This test proves that the server strictly inspects what is typed: if a user tries to register with a weak password, the server rejects it and explains the security rules (such as requiring at least 8 characters, numbers, uppercase and lowercase letters, and special symbols).
*   **Measure Applied**: 
    Rejects weak credentials during registration or reset by enforcing a strict password validator (minimum of 8 characters, containing uppercase, lowercase, numbers, and special characters).
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to the registration page: **`[PORTAL_URL]/register.html`**
    2. Fill out details and enter a simple password (e.g., `pass123` or `password`).
    3. Click the submit button.
    4. **Pass Criteria**:
        *   The registration must be rejected.
        *   An error message must display warning that the password must be at least 8 characters long and contain uppercase, lowercase, numbers, and special characters.
(THIS TEST WAS SUCCESSFUL)

---

### SEC-06: Database Encryption Key Management
*   **What does this mean?**
    To connect to the database securely, the server needs a password key. If a developer hardcodes this password inside the code, any hacker who views the source code could steal it. This test verifies that the server loads the database key dynamically from the server environment settings rather than having it typed out in the code files, preventing database key leaks.
*   **Measure Applied**: 
    Protects database configuration credentials from hardcoded leaks by loading a decryption key (`ENC_KEY`) from environment variables, preventing plaintext database configuration leakage.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open and inspect [server.mjs](file:///c:/Users/Madhav/Sevenpointfour/consultation/server.mjs).
    2. Locate the database initialization function block.
    3. **Pass Criteria**: Verify that the database setup parameter loads the encryption key from `process.env.ENC_KEY` (or secure fallback check) rather than storing a hardcoded plaintext database password key in the source code files.
(THIS TEST WAS SUCCESSFUL)

---

### SEC-07: Client Authorization & JWT Separation
*   **What does this mean?**
    Only logged-in clients should be allowed to view their profile details, consultations, and medical records. This test proves that if a random visitor tries to call these client-only functions directly, the server instantly detects they are not logged in and blocks their access with an "Unauthorized" error.
*   **Measure Applied**: 
    Restricts access to client endpoints (profile details, consultation histories, comparative records) using validation middleware that inspects the JWT cookie, returning HTTP 401/403 errors if unauthorized.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to: **`[PORTAL_URL]/login.html`** (Ensure you are logged out, or open an Incognito window).
    2. Open **Developer Tools** (`F12`) and select the **Console** tab.
    3. Execute the following fetch script to simulate an unauthenticated attempt to access client details:
       ```javascript
       fetch('/api/client/me')
       .then(res => console.log("Response Status Code: " + res.status));
       ```
    4. **Pass Criteria**:
        *   The returned response status code must be **`401`** (Unauthorized).
        *   
(THIS TEST WAS SUCCESSFUL)

---

### SEC-08: Deactivated User Access Block (Backup Sync & Conflict Prevention)
*   **What does this mean?**
    If an account is deactivated or deleted, that user must be blocked from logging in immediately. This test proves that if someone tries to log in using a deactivated account, the server rejects the request and blocks access completely, preventing security conflicts.
*   **Measure Applied**: 
    Excludes deactivated users (marked with `deleted = 1` in the database) from accessing the application or generating credentials. This ensures no authentication session conflicts arise in the event of database backup restoration or data synchronization.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Access your database or administration client.
    2. Set a test user's `deleted` status column to `1` in the `users_v2` database table.
    3. Navigate to **`[PORTAL_URL]/login.html`** in a browser.
    4. Attempt to log in or request a login OTP using the credentials of the deactivated user.
    5. **Pass Criteria**:
       *   The request must fail, blocking access completely and displaying an error message on the UI such as **"Invalid credentials"** (returning a **`401 Unauthorized`** status code in the DevTools Network tab).
(THIS TEST WAS SUCCESSFUL)

---

### SEC-09: Data Encryption at Rest (Hosting Auditing & Migration Roadmap)
*   **What does this mean?**
    If a physical hard drive is stolen from the hosting provider, we want to ensure the data on it remains unreadable. Because standard shared hosting does not support hardware encryption, this test confirms that we have documented this security limitation, conducted a risk assessment, and created a clear roadmap to migrate to a dedicated server environment by Q3 2026 to enable disk partition encryption.
*   **Measure Applied**: 
    Formally audits and logs standard data-at-rest encryption constraints. Since standard shared hosting (Hostripples) does not support AES-256 or hardware-level volume encryption, the portal establishes a risk management register and a migration roadmap to a Virtual Private Server (VPS) / Dedicated Server to enable native disk partition encryption (LUKS).
*   **Auditor's Step-by-Step Verification Guide**:
    1. Locate and open the active encryption log in the portal root directory: [ENCRYPTION_LOG.md](file:///c:/Users/Madhav/Sevenpointfour/consultation/ENCRYPTION_LOG.md).
    2. **Pass Criteria**:
       *   Verify that the Hostripples support confirmation and FDE hardware limitations are documented.
       *   Verify that the compliance gap risk assessment outlines the migration remediation plan.
       *   Verify that the migration target date is defined or that the risk has been formally accepted by the Administrator.
(RISK ACCEPTED BY ADMIN - SHARED HOSTING LIMITATIONS ACKNOWLEDGED)

---
---

## Part 2: DPDP Act 2023 Compliance Controls

### DPDP-01: Mandatory Consent Collection & Evidence Logging
*   **What does this mean?**
    Under the DPDP Act, we are legally required to obtain your explicit consent before collecting or processing any personal information. This test proves that the registration form makes it impossible for a user to submit their details unless they first check the consent box, and once they do, the server logs their consent timestamp and IP address to serve as legal evidence.
*   **Measure Applied**: 
    Ensures data subject consent is obtained prior to data processing by making the registration form's privacy policy and data processing consent checkbox mandatory. It logs the consent timestamp and the user's consent IP address to serve as audit compliance evidence under the DPDP Act 2023.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to: **`[PORTAL_URL]/register.html`**
    2. Enter valid registration details (email, password, mobile), but **leave the consent checkbox unchecked**.
    3. Click submit.
    4. **Pass Criteria**:
        *   The form submission must fail.
        *   An error message must display (e.g., browser-native checkbox warning or "Please provide your consent by checking the box").
        *   *(Database verification)*: If submitted with consent checked, query the user row in the database. Verify that `consent_given` is set to `1`, `consent_timestamp` is populated, and `consent_ip_address` is populated with the correct client IP address.
(THIS TEST WAS SUCCESSFUL)

---

### DPDP-02: Age Verification Check (Child Safety)
*   **What does this mean?**
    Under the DPDP Act, companies must not process personal data of children (under 18) without parental verification. This test proves that the registration form validates the user's date of birth and automatically blocks registration if they are under 18 years old, preventing minor child safety issues.
*   **Measure Applied**: 
    Blocks minors from registering on the platform without parental verification by collecting and validating the user's date of birth (DOB) at registration.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to: **`[PORTAL_URL]/register.html`**
    2. Complete the form but enter a birth date that makes the applicant under 18 years old.
    3. Click submit.
    4. **Pass Criteria**:
        *   The registration must be rejected.
        *   An error message must display indicating that users must be at least 18 years of age to register.
(THIS TEST WAS SUCCESSFUL)

---

### DPDP-03: Daily Log Retention Automation
*   **What does this mean?**
    The DPDP Act requires companies to delete personal data as soon as the purpose for keeping it has ended. This test confirms that we have an automated schedule that cleans up old server logs daily, deleting any files older than 365 days to prevent unnecessary data storage.
*   **Measure Applied**: 
    Limits logs to a strict 365-day lifecycle retention period (in compliance with Section 12 of the DPDP Act) using a scheduled cron/interval process that scans the logs directory.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open the application directory on the server (or project root).
    2. Open and inspect the server's **`stderr.log`** file (or startup console logs).
    3. Open the **`logs/`** folder in the File Manager and check file modified dates.
    4. **Pass Criteria**:
        *   *(Localhost)*: Verify that startup logs print: `[Log Cleanup] Starting log cleanup...` and `Finished log cleanup...` showing the process runs cleanly.
        *   *(Production)*: Verify that **`stderr.log`** remains completely free of errors (the success print is handled by the server's background Passenger process and is not expected to write to the error log).
        *   Verify that the **`logs/`** directory exists and contains active log files, none of which are older than 365 days.
(THIS TEST WAS SUCCESSFUL)

---

### DPDP-04: Right to Erasure (User-Driven Deletion)
*   **What does this mean?**
    Under the DPDP Act, users have the "Right to be Forgotten"—meaning they can request that their account and all associated records be completely deleted. This test proves that when a client requests account deletion, the server permanently deletes their profile, consultation history, food plans, and medical records from all database tables, leaving no soft-deleted traces.
*   **Measure Applied**: 
    Fulfills the Data Principal's right to be forgotten under DPDP Section 12 by exposing a hard-delete API endpoint that completely wipes all personal profiles, roles, consultation history, food plans, and medical/blood records.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to the portal and log in as a client.
    2. Open **Developer Tools** (`F12`) and select the **Console** tab.
    3. Execute the following deletion script:
       ```javascript
       fetch('/api/client/me', { method: 'DELETE' })
       .then(res => res.json())
       .then(data => console.log(data));
       ```
    4. **Pass Criteria**:
        *   The console must return a confirmation message: `"Account and all associated data deleted successfully."`
        *   Query the database using your admin client. Confirm the user's row is fully removed from `users_v2`, `client_consultations`, `client_food_plans`, and `client_medical_history` tables (no soft-delete rows remain).
(THIS TEST WAS SUCCESSFUL - CONFIRMED ON LOCALHOST)

---

### DPDP-05: Inactivity Hard Erasure (Inactivity Cleanup)
*   **What does this mean?**
    To prevent storing user data forever, the DPDP Act requires cleanup of inactive accounts. This test proves that the system automatically checks for accounts inactive for over 2 years, sends them a 48-hour email warning, and then physically deletes their account and associated data from the database if they fail to log in.
*   **Measure Applied**: 
    Mitigates unauthorized data retention by automatically scanning for accounts inactive for over 24 months, issuing a 48-hour email warning, and executing a complete database hard-delete if they fail to log in.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open and inspect [inactive_user_cleanup.mjs](file:///c:/Users/Madhav/Sevenpointfour/consultation/scripts/inactive_user_cleanup.mjs).
    2. Review the SQL query finding users who have not logged in for 24 months and have not been warned (`last_login < DATE_SUB(NOW(), INTERVAL 24 MONTH)`).
    3. Review the deletion query targeting users warned over 48 hours ago.
    4. **Pass Criteria**: Verify that the script deletes the user record and child table data physically (using SQL `DELETE` instead of soft `UPDATE deleted = 1`), matching compliance expectations.
(THIS TEST WAS SUCCESSFUL - CONFIRMED BY CODE AUDIT)

---

### DPDP-06: Data Breach Response Readiness
*   **What does this mean?**
    Under the DPDP Act, if a security breach occurs, you must legally notify the authorities and affected users within 72 hours. This test confirms that we have a documented, step-by-step incident response playbook ready in the repository so that your staff can immediately contain the leak, rotate security keys, and notify the authorities within the mandatory 72-hour window.
*   **Measure Applied**: 
    Sets a clear, 72-hour operational response timeline and reporting checklist in the event of a personal data leak.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open and review [BREACH_RESPONSE.md](file:///c:/Users/Madhav/Sevenpointfour/consultation/BREACH_RESPONSE.md).
    2. **Pass Criteria**:
        *   Verify that a clear timeline (72 hours) for reporting to the Data Protection Board of India and affected users is defined.
        *   Verify that the notification content checklist covers the breach nature, categories of data, count of affected principals, and mitigation steps.
(THIS TEST WAS SUCCESSFUL - CONFIRMED BY DOCUMENTATION AUDIT)

---

### DPDP-07: Grievance Redressal officer & Privacy Fixes
*   **What does this mean?**
    Under the DPDP Act, companies must appoint a designated contact person (Grievance Redressal Officer) to handle privacy queries, corrections, or complaints. This test confirms that the privacy policy displays the Grievance Officer's email address in both English and Hindi translation format, and describes clear escalation protocols.
*   **Measure Applied**: 
    Appoints a Grievance Officer (contact details published in English and Hindi translation format in `privacy.html`), allowing users to easily raise queries, request corrections, or withdraw consent.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Navigate to: **`[PORTAL_URL]/privacy.html`** in a browser.
    2. Look at the Grievance Redressal section.
    2. **Pass Criteria**:
        *   Verify that the Grievance Officer's email address (**`madhavjoshi02@gmail.com`**) is clearly displayed.
        *   Verify that the notice is accessible and readable in Hindi translation, and clear escalation protocols are described.
(THIS TEST WAS SUCCESSFUL - CONFIRMED BY DOCUMENTATION AUDIT)


---

### DPDP-08: Inactive User UI Highlighting & Auditing
*   **What does this mean?**
    To help administrators keep track of data retention, the system should highlight inactive accounts. This test confirms that on the client management dashboard, accounts inactive for over 18 months are highlighted in orange, and accounts inactive for over 2 years are highlighted in red, alerting the admin that these accounts are due for deletion.
*   **Measure Applied**: 
    Highlights inactive client accounts based on their `last_login` timestamps within the client management console to help administrators audit retention policies at a glance.
*   **Auditor's Step-by-Step Verification Guide**:
    1. Open your web browser and navigate to: **`[PORTAL_URL]/manage-clients.html`**
    2. Log in as an administrator.
    3. Look at the **Last Login** column in the client list.
    4. **Pass Criteria**:
       *   Verify that accounts inactive for over 18 months are highlighted in **orange/bold**.
       *   Verify that accounts inactive for over 24 months are highlighted in **red/bold** (indicating they have crossed the threshold for cleanup execution).
(THIS TEST WAS SUCCESSFUL - CONFIRMED BY CODE AUDIT)
