Fix error handling in GlobalAuthGuard to allow public route access without session validation. Simplified catch block to ignore errors, enhancing user experience on public endpoints.

This commit is contained in:
barsa 2025-12-23 15:19:47 +09:00
parent 4573b94484
commit 3af18af502
3 changed files with 733 additions and 1 deletions

View File

@ -52,7 +52,7 @@ export class GlobalAuthGuard implements CanActivate {
try {
await this.attachUserFromToken(request, token);
this.logger.debug(`Authenticated session detected on public route: ${route}`);
} catch (_error) {
} catch {
// Public endpoints should remain accessible even if the session is missing/expired/invalid.
this.logger.debug(`Ignoring invalid session on public route: ${route}`);
}

View File

@ -0,0 +1,220 @@
# Security Monitoring Setup
## 🎯 Quick Start
Your project now has comprehensive security monitoring! Here's what was set up:
## 📦 What's Included
### 1. **GitHub Actions Workflows** (`.github/workflows/`)
#### `security.yml` - Main Security Pipeline
- **Daily scans** at 9 AM UTC
- **Pull request** security checks
- **Manual trigger** available
- Includes:
- Dependency vulnerability audit
- Dependency review (for PRs)
- CodeQL security analysis
- Outdated dependencies check
#### `pr-checks.yml` - Pull Request Quality Gate
- Runs on every PR
- Checks: linting, type safety, security audit, tests, formatting
#### `dependency-update.yml` - Auto-merge Helper
- Auto-approves safe dependency updates
- Auto-merges patch updates
- Works with Dependabot
### 2. **Dependabot Configuration** (`.github/dependabot.yml`)
- **Weekly** dependency updates (Mondays at 9 AM)
- Groups updates to reduce PR noise
- Monitors: npm, GitHub Actions, Docker
- Auto-labels PRs for easy tracking
### 3. **Git Hooks** (`.husky/`)
- **pre-commit**: Runs linting and type checks
- **pre-push**: Optional security audit (commented out by default)
### 4. **NPM Scripts** (Enhanced)
```bash
pnpm security:audit # Full security audit
pnpm security:check # Check high/critical vulnerabilities
pnpm security:fix # Auto-fix vulnerabilities when possible
pnpm security:report # Generate JSON report
pnpm update:check # Check for outdated packages
pnpm update:safe # Safe update with verification
```
## 🚀 Getting Started
### 1. Fix Current Vulnerability
```bash
# Update Next.js to fix the current high-severity issue
cd /home/barsa/projects/customer_portal/customer-portal
pnpm add next@latest --filter @customer-portal/portal
pnpm security:check
```
### 2. Enable GitHub Actions
- Push these changes to GitHub
- Go to **Settings → Actions → General**
- Enable **Read and write permissions** for workflows
- Go to **Settings → Code security → Dependabot**
- Enable **Dependabot alerts** and **security updates**
### 3. Optional: Enable Stricter Pre-push Checks
Edit `.husky/pre-push` and uncomment the security check lines to run audits before every push.
## 📊 Monitoring Dashboard
### View Security Status
1. **GitHub Actions**: Check `.github/workflows/security.yml` runs
2. **Dependabot**: View PRs in **Pull requests** tab
3. **Security Advisories**: Check **Security** tab
4. **Artifacts**: Download audit reports from workflow runs
### Email Notifications
GitHub will automatically notify you about:
- Security vulnerabilities
- Failed workflow runs
- Dependabot PRs
### Configure Notifications
1. Go to **Settings → Notifications**
2. Enable **Actions** and **Dependabot** notifications
3. Choose **Email** or **Web** notifications
## 🔄 Workflow Triggers
### Automatic
- **Daily**: Full security scan at 9 AM UTC
- **On Push**: Security checks when pushing to main/master
- **On PR**: Comprehensive checks including dependency review
- **Weekly**: Dependabot checks for updates (Mondays)
### Manual
```bash
# Trigger from GitHub UI
1. Go to Actions → Security Audit
2. Click "Run workflow"
3. Select branch and run
# Or use GitHub CLI
gh workflow run security.yml
```
## 🛠️ Local Development
### Before Committing
```bash
pnpm lint # Check code quality
pnpm type-check # Verify types
pnpm security:check # Check vulnerabilities
pnpm test # Run tests
```
### Weekly Maintenance
```bash
pnpm update:check # See what's outdated
pnpm update:safe # Update safely
```
### Generate Security Report
```bash
pnpm security:report
# Creates security-report.json with detailed findings
```
## 📋 Best Practices
### For Daily Development
- ✅ Run `pnpm security:check` weekly
- ✅ Review Dependabot PRs within 48 hours
- ✅ Keep dependencies up to date
- ✅ Never commit secrets (use `.env` files)
### For Security Issues
- 🚨 **High/Critical**: Fix within 24 hours
- ⚠️ **Medium**: Fix within 1 week
- **Low**: Fix in next maintenance window
### For Dependency Updates
- ✅ **Patch versions**: Auto-merge after CI passes
- ⚠️ **Minor versions**: Review and test
- 🚨 **Major versions**: Careful review and thorough testing
## 🔍 Troubleshooting
### If Security Scan Fails
```bash
# View detailed audit
pnpm audit
# Try to auto-fix
pnpm security:fix
# If auto-fix doesn't work, update manually
pnpm update [package-name]@latest
```
### If Workflow Fails
1. Check workflow logs in GitHub Actions
2. Run the same commands locally
3. Ensure all secrets are configured
4. Verify permissions are set correctly
## 📚 Additional Resources
- **Security Policy**: See `SECURITY.md`
- **Complete Guide**: See `docs/portal-guides/COMPLETE-GUIDE.md`
- **GitHub Security**: [https://docs.github.com/en/code-security](https://docs.github.com/en/code-security)
- **npm Security**: [https://docs.npmjs.com/security](https://docs.npmjs.com/security)
## 🎉 Next Steps
1. **Fix the current vulnerability**:
```bash
pnpm add next@16.0.10 --filter @customer-portal/portal
```
2. **Push to GitHub** to activate workflows:
```bash
git add .
git commit -m "feat: add comprehensive security monitoring"
git push
```
3. **Enable Dependabot** in GitHub repository settings
4. **Review first security scan** in GitHub Actions
---
**Need Help?** Check `SECURITY.md` for detailed security policies and contact information.

View File

@ -0,0 +1,512 @@
# Salesforce Requirements & Setup Guide
This document describes the Salesforce configuration required for the Customer Portal integration.
---
## Table of Contents
1. [Overview](#overview)
2. [Required Objects & Fields](#required-objects--fields)
3. [Platform Events](#platform-events)
4. [Record-Triggered Flows](#record-triggered-flows)
5. [Connected App (JWT Auth)](#connected-app-jwt-auth)
6. [Integration User Permissions](#integration-user-permissions)
7. [Data Flow Summary](#data-flow-summary)
---
## Overview
The Customer Portal integrates with Salesforce for:
- **Customer Data** Account, Contact information
- **Order Management** Order creation, approval, and tracking
- **Opportunity Lifecycle** Sales pipeline and service lifecycle tracking
- **Eligibility & Verification** Internet eligibility checks, ID verification status
- **Support Cases** Eligibility requests, cancellation requests, support tickets
### Integration Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ SALESFORCE │
│ │
│ ┌──────────────┐ ┌───────────────────┐ ┌───────────────────────┐ │
│ │ Objects │ │ Platform Events │ │ Record-Triggered │ │
│ │ │ │ │ │ Flows │ │
│ │ • Account │ │ OrderProvision │ │ │ │
│ │ • Contact │ │ Requested__e │ │ • On Order Approved │ │
│ │ • Order │ │ │ │ → Publish Event │ │
│ │ • Opportunity│ │ │ │ │ │
│ │ • Case │ │ │ │ │ │
│ └──────────────┘ └───────────────────┘ └───────────────────────┘ │
│ ▲ │ │
│ │ ▼ │
└─────────┼─────────────────────┼──────────────────────────────────────────┘
│ │
│ REST API │ Pub/Sub gRPC
│ (jsforce) │ (salesforce-pubsub-api-client)
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────────────────┐
│ PORTAL BFF (NestJS) │
│ │
│ ┌───────────────────────┐ ┌───────────────────────────────────────┐ │
│ │ SalesforceService │ │ Platform Events Subscriber │ │
│ │ │ │ │ │
│ │ • Query/Update │ │ • Subscribes to OrderProvision... │ │
│ │ • Create Orders │ │ • Enqueues provisioning job │ │
│ │ • Create Cases │ │ • Durable replay (Redis) │ │
│ └───────────────────────┘ └───────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
---
## Required Objects & Fields
### Account Object
The Account stores customer information and status fields.
#### Standard Fields Used
| Field | API Name | Purpose |
| ---------------- | ------------------ | ---------------------------- |
| Account Name | `Name` | Customer name |
| Customer Number | `SF_Account_No__c` | Unique customer identifier |
| WHMCS Account ID | `WH_Account__c` | Link to WHMCS billing system |
#### Custom Fields Required
**Internet Eligibility Fields:**
| Field | API Name | Type | Purpose |
| ------------------ | ------------------------------------------- | ------------- | ---------------------- |
| Eligibility Value | `Internet_Eligibility__c` | Text/Picklist | The eligibility result |
| Eligibility Status | `Internet_Eligibility_Status__c` | Picklist | `Pending`, `Checked` |
| Request Date | `Internet_Eligibility_Request_Date_Time__c` | DateTime | When request was made |
| Checked Date | `Internet_Eligibility_Checked_Date_Time__c` | DateTime | When checked by CS |
| Notes | `Internet_Eligibility_Notes__c` | Text Area | Agent notes |
| Case ID | `Internet_Eligibility_Case_Id__c` | Text | Linked Case ID |
**ID Verification Fields:**
| Field | API Name | Type | Purpose |
| ----------------- | ---------------------------------------- | --------- | --------------------------------- |
| Status | `Id_Verification_Status__c` | Picklist | `Pending`, `Verified`, `Rejected` |
| Submitted Date | `Id_Verification_Submitted_Date_Time__c` | DateTime | When documents submitted |
| Verified Date | `Id_Verification_Verified_Date_Time__c` | DateTime | When verified |
| Notes | `Id_Verification_Note__c` | Text Area | Agent notes |
| Rejection Message | `Id_Verification_Rejection_Message__c` | Text | Reason if rejected |
**Portal Status Fields:**
| Field | API Name | Type | Purpose |
| ------------------- | ------------------------------- | -------- | ----------------------- |
| Portal Status | `Portal_Status__c` | Picklist | `Active`, `Inactive` |
| Registration Source | `Portal_Registration_Source__c` | Picklist | How customer registered |
**Portal Registration Source Picklist Values:**
- `Legacy` Existing customer before portal
- `Portal Signup` Standard portal registration
- `Portal Checkout` Registered during checkout
---
### Order Object
Orders represent customer purchases.
#### Standard Fields Used
| Field | API Name | Purpose |
| -------------- | --------------- | --------------------------- |
| Order Number | `OrderNumber` | Auto-generated order number |
| Account | `AccountId` | Linked customer account |
| Opportunity | `OpportunityId` | Linked opportunity |
| Status | `Status` | Order status |
| Effective Date | `EffectiveDate` | Order date |
#### Custom Fields Required
| Field | API Name | Type | Purpose |
| --------------------- | ------------------------------ | -------- | -------------------------- |
| Activation Status | `Activation_Status__c` | Picklist | Portal provisioning status |
| Activation Error | `Activation_Error__c` | Text | Error message if failed |
| Activation Error Time | `Activation_Error_DateTime__c` | DateTime | When error occurred |
| WHMCS Order ID | `WHMCS_Order_Id__c` | Number | WHMCS order reference |
**Activation Status Picklist Values:**
- `Pending Review` Awaiting CS approval
- `Activating` Being provisioned to WHMCS
- `Provisioned` Successfully provisioned
- `Failed` Provisioning failed
**Order Status Picklist Values:**
- `Draft` Order being created
- `Pending Review` Awaiting approval
- `Approved` Approved by CS (triggers provisioning)
- `Activated` Successfully activated
- `Cancelled` Order cancelled
---
### Opportunity Object
Opportunities track the customer lifecycle from lead to active service.
#### Standard Fields Used
| Field | API Name | Purpose |
| ---------- | ----------- | ------------------- |
| Stage | `StageName` | Opportunity stage |
| Account | `AccountId` | Linked account |
| Close Date | `CloseDate` | Expected close date |
#### Custom Fields Required
| Field | API Name | Type | Purpose |
| ---------------------- | ------------------------------------- | -------- | --------------------------- |
| Commodity Type | `CommodityType` | Picklist | Product type |
| Application Stage | `Application_Stage__c` | Picklist | Internal CS workflow |
| Cancellation Notice | `CancellationNotice__c` | Picklist | Cancellation status |
| Scheduled Cancellation | `ScheduledCancellationDateAndTime__c` | DateTime | Cancellation date |
| Line Return Status | `LineReturn__c` | Picklist | Equipment return status |
| Portal Source | `Portal_Source__c` | Picklist | How opportunity was created |
| WHMCS Service ID | `WHMCS_Service_ID__c` | Number | Link to WHMCS service |
**Stage Picklist Values (Customer Journey):**
1. `Introduction` Initial inquiry/eligibility request
2. `Ready` Eligible and ready to order
3. `Post Processing` Order placed, being processed
4. `Active` Service is active
5. `△Cancelling` Cancellation requested
6. `△Cancelled` Service cancelled
7. `Void` Not eligible or abandoned
**Commodity Type Picklist Values:**
- `Personal SonixNet Home Internet`
- `Corporate SonixNet Home Internet`
- `SIM`
- `VPN`
**Portal Source Picklist Values:**
- `Portal - Internet Eligibility Request`
- `Portal - Order Placement`
- `Sales - Manual`
---
### Case Object
Cases are used for customer requests and support tickets.
#### Fields Used
| Field | API Name | Purpose |
| ----------- | --------------- | ---------------------------------- |
| Subject | `Subject` | Case subject |
| Description | `Description` | Case details |
| Type | `Type` | Case type |
| Status | `Status` | Case status |
| Account | `AccountId` | Customer account |
| Opportunity | `OpportunityId` | Linked opportunity (if applicable) |
**Case Type Values (Portal-Created):**
- `Eligibility Check` Internet eligibility request
- `ID Verification` Manual ID verification review
- `Cancellation Request` Service cancellation
- `General Inquiry` Support ticket
---
### OrderItem Object
Order line items with product details.
#### Fields Used
| Field | API Name | Purpose |
| ---------- | ------------ | ----------------- |
| Order | `OrderId` | Parent order |
| Product2 | `Product2Id` | Product reference |
| Quantity | `Quantity` | Item quantity |
| Unit Price | `UnitPrice` | Item price |
---
### Product2 Object
Product catalog synchronized from Salesforce.
#### Custom Fields Required
| Field | API Name | Type | Purpose |
| ------------------- | ------------------------------ | --------- | --------------------------------- |
| WHMCS Product ID | `WHMCS_Product_Id__c` | Text | WHMCS product mapping |
| Billing Cycle | `Billing_Cycle__c` | Picklist | `Monthly`, `Annually`, `One-time` |
| Item Class | `Item_Class__c` | Picklist | `Service`, `Activation`, `Add-on` |
| Config Options JSON | `Portal_ConfigOptions_JSON__c` | Long Text | WHMCS config options |
---
## Platform Events
### OrderProvisionRequested\_\_e
High-Volume Platform Event for order provisioning.
**Purpose:** Notifies the portal when an order is approved and ready for WHMCS provisioning.
#### Event Fields
| Field | API Name | Type | Required | Purpose |
| --------------- | ------------------ | -------- | -------- | ---------------------------- |
| Order ID | `OrderId__c` | Text(18) | Yes | Salesforce Order ID |
| Idempotency Key | `IdemKey__c` | Text(80) | No | Prevent duplicate processing |
| Correlation ID | `CorrelationId__c` | Text(80) | No | Request tracing |
| Requested By | `RequestedBy__c` | Text(80) | No | User who approved |
| Version | `Version__c` | Number | No | Event schema version |
#### Event Retention
- **Retention Period:** 72 hours (default for High-Volume Platform Events)
- **Replay:** Portal uses durable replay to resume from last processed event
---
## Record-Triggered Flows
### Order Approval Flow
**Trigger:** Record-Triggered Flow on Order object
**Entry Conditions:**
- `Status` changed to `Approved`
- OR `Activation_Status__c` changed to `Activating` (for retry)
**Actions:**
1. **Update Order Fields:**
```
Activation_Status__c = "Activating"
Activation_Error__c = null
Activation_Error_DateTime__c = null
```
2. **Create Platform Event:**
```
Create Record: OrderProvisionRequested__e
OrderId__c = {!$Record.Id}
IdemKey__c = {!$Record.Id} + "-" + {!$Flow.CurrentDateTime}
```
**Flow Diagram:**
```
┌─────────────────────────────────────────────────────────────────────────┐
│ ORDER APPROVAL FLOW (Record-Triggered) │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ TRIGGER: Order Status changed to "Approved" │
│ OR Activation_Status__c changed to "Activating" │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐│
│ │ 1. UPDATE ORDER ││
│ │ └─ Activation_Status__c = "Activating" ││
│ │ └─ Activation_Error__c = null ││
│ │ └─ Activation_Error_DateTime__c = null ││
│ └─────────────────────────────────────────────────────────────────────┘│
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐│
│ │ 2. CREATE PLATFORM EVENT ││
│ │ └─ OrderProvisionRequested__e ││
│ │ └─ OrderId__c = Order.Id ││
│ │ └─ IdemKey__c = Order.Id + timestamp ││
│ └─────────────────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
---
## Connected App (JWT Auth)
The portal authenticates to Salesforce using JWT Bearer Flow.
### Connected App Settings
| Setting | Value |
| --------------- | ----------------------------------------- |
| Name | `Customer Portal Integration` |
| OAuth Scopes | `api`, `refresh_token`, `offline_access` |
| Certificate | Upload public certificate |
| Permitted Users | `Admin approved users are pre-authorized` |
### Pre-Authorized Profile/User
Assign the integration user to the Connected App.
### Environment Variables (Portal)
```bash
SF_LOGIN_URL=https://login.salesforce.com # or https://test.salesforce.com for sandbox
SF_CLIENT_ID=<connected_app_consumer_key>
SF_USERNAME=integration.user@company.com
SF_PRIVATE_KEY_PATH=/path/to/private-key.pem
# OR base64 encoded:
SF_PRIVATE_KEY_BASE64=<base64_encoded_private_key>
```
---
## Integration User Permissions
### Required Object Permissions
| Object | Create | Read | Update | Delete |
| -------------- | ------ | ---- | ------ | ------ |
| Account | ✅ | ✅ | ✅ | ❌ |
| Contact | ✅ | ✅ | ✅ | ❌ |
| Order | ✅ | ✅ | ✅ | ❌ |
| OrderItem | ✅ | ✅ | ✅ | ❌ |
| Opportunity | ✅ | ✅ | ✅ | ❌ |
| Case | ✅ | ✅ | ✅ | ❌ |
| Product2 | ❌ | ✅ | ❌ | ❌ |
| PricebookEntry | ❌ | ✅ | ❌ | ❌ |
### Required Field-Level Security
All custom fields listed above must be **Visible** and **Editable** (where applicable) for the integration user's profile.
### Platform Event Permissions
| Event | Subscribe | Publish |
| ---------------------------- | --------- | ------------------- |
| OrderProvisionRequested\_\_e | ✅ | ❌ (Flow publishes) |
### API Limits
- **Daily API Requests:** Ensure sufficient API call limits
- **Platform Event Allocations:** High-Volume Platform Events have separate limits
---
## Data Flow Summary
### 1. Customer Registration
```
Portal → Salesforce
├─ Create Account (if new)
├─ Create Contact
└─ Update Portal_Status__c = "Active"
```
### 2. Internet Eligibility Request
```
Portal → Salesforce
├─ Find/Create Opportunity (Stage: Introduction)
├─ Create Case (Type: Eligibility Check)
└─ Update Account eligibility status = "Pending"
CS Action (Manual) → Salesforce
├─ Update Account eligibility result
└─ Update Opportunity stage (Ready or Void)
```
### 3. Order Placement
```
Portal → Salesforce
├─ Find/Create Opportunity (Stage: Post Processing)
├─ Create Order (Status: Pending Review)
└─ Create OrderItems
```
### 4. Order Approval & Provisioning
```
CS Action → Salesforce
└─ Update Order Status = "Approved"
Salesforce Flow → Platform Event
└─ Publish OrderProvisionRequested__e
Portal BFF (Subscriber)
├─ Receive event
├─ Provision to WHMCS
├─ Update Order (Provisioned/Failed)
└─ Update Opportunity (Stage: Active, WHMCS_Service_ID__c)
```
### 5. Cancellation Request
```
Portal → Salesforce
├─ Create Case (Type: Cancellation Request)
├─ Find Opportunity (via WHMCS_Service_ID__c)
├─ Update Opportunity Stage = "△Cancelling"
└─ Set ScheduledCancellationDateAndTime__c
CS Action (Manual)
└─ Process cancellation in WHMCS
```
---
## Checklist for Salesforce Setup
### Objects & Fields
- [ ] All Account custom fields created
- [ ] All Order custom fields created
- [ ] All Opportunity custom fields created
- [ ] Product2 WHMCS mapping fields created
### Platform Events
- [ ] `OrderProvisionRequested__e` event created
- [ ] Event fields configured
### Flows
- [ ] Order Approval Flow created and activated
- [ ] Flow publishes Platform Event on Order approval
### Security
- [ ] Connected App created with JWT settings
- [ ] Certificate uploaded
- [ ] Integration user created
- [ ] Profile permissions assigned
- [ ] Field-Level Security configured
- [ ] Platform Event subscribe permission granted
### Testing
- [ ] Test order approval → event published
- [ ] Test portal subscription → event received
- [ ] Test full provisioning flow end-to-end
---
## Related Documentation
- [Salesforce Order Communication](./SALESFORCE-ORDER-COMMUNICATION.md) Detailed order flow
- [Opportunity Lifecycle Guide](./OPPORTUNITY-LIFECYCLE-GUIDE.md) Opportunity stages and matching
- [Salesforce-WHMCS Mapping](./SALESFORCE-WHMCS-MAPPING-REFERENCE.md) Data mapping reference