01 - OverviewWhat is SF Vault?
SF Vault is a two-part open-source system that gives organizations precise control over Salesforce consultant user accounts. It solves the problem of consultants needing temporary, controlled access to client Salesforce orgs.
Web Application
A Next.js admin dashboard where admins manage internal users, connect Salesforce orgs via OAuth, and grant/revoke per-org access to team members.
Salesforce Package
An Apex REST API deployed inside each Salesforce org that exposes secure endpoints for listing, activating, deactivating, and freezing consultant users.
Secure by Default
OAuth token encryption at rest, API key authentication, email domain whitelisting, and role-based access control throughout the stack.
Multi-Org Support
Manage unlimited Salesforce orgs from one interface. Production, sandbox, scratch, and developer orgs all supported with per-user access grants.
Zero License Cost
Uses the free Salesforce API Only System Integrations profile. No paid Admin or user license needed - the integration user occupies no billable seat.
02 - ArchitectureSystem Architecture
SF Vault is a client-server system with two independently deployable components that communicate over HTTPS.
Data Flow
Admin logs in
NextAuth authenticates via email/password. Session is established with role (ADMIN or USER).
Org selection
User navigates to their assigned orgs on the dashboard. Each org card shows connection status and environment type.
Consultant list fetched
Next.js retrieves the decrypted OAuth token from PostgreSQL, refreshes it if expired, then calls GET /services/apexrest/consultants/ on the target org.
Action dispatched
Admin clicks Enable/Disable/Freeze/Unfreeze. A server action calls the corresponding Apex endpoint with the user's ID in the request body.
Salesforce updates user
The Apex service validates the API key, checks email domain whitelist, and updates the User or UserLogin record in Salesforce.
03 - StackTech Stack
Each component uses technologies well-suited to its environment - standard Node.js/React ecosystem for the web app, native Salesforce Apex for the org package.
Web Application
Salesforce Package
04 - FeaturesFeature Overview
Everything SF Vault can do, at a glance. Each feature is covered in depth in its own section.
- Connect unlimited Salesforce orgs (Production, Sandbox, Scratch, Developer, Custom) to a single web app
- Each team member sees only the orgs an admin has explicitly granted them
- Live connection status per org so users immediately know when re-auth is needed
- Flip a consultant's
IsActiveflag in Salesforce with a single click - no Salesforce UI access required - Deactivating a user immediately revokes their login and frees the Salesforce license
- A 15-minute warning appears after activation to prevent accidental duplicate enables
- Blocks a consultant's login without deactivating their account - license stays allocated, all data and assignments remain intact
- Ideal for short-term lockouts (weekends, off-site days) where full deactivation is overkill
- Instantly reversible - unfreeze restores access in seconds
- Deactivates every consultant in an org in a single API call
- Automatically runs before creating a new consultant to enforce "one active at a time" patterns
- Also available as a standalone action from the consultant management screen
- Create new consultant
Userrecords in Salesforce directly from the web UI - no Salesforce admin login needed - Restricted by email domain and address whitelists configured in the org's Custom Metadata
- Can be enabled or disabled per org via a single metadata toggle
- Admins grant or revoke individual team members' access to specific orgs - not all-or-nothing
- Grants are time-stamped and attributed to the admin who created them
- Revoking access takes effect immediately; the org disappears from the user's dashboard
- Each Salesforce org is connected via standard OAuth 2.0 - no passwords stored for Salesforce accounts
- Access tokens are encrypted with AES-256 at rest and refreshed automatically when they expire
- A single "Connect" flow is all that's needed to wire up a new org
- Two roles: Admin manages the platform (users, orgs, access grants); User manages consultants inside assigned orgs
- All role checks happen server-side - not just UI guards
- Admins cannot accidentally lock themselves out (self-delete protection)
- Admins create, edit, activate/deactivate, and delete SF Vault user accounts
- Force-password-change on first login - new users must set their own password before accessing anything
- Admin can reset any user's password at any time
- The Salesforce integration runs under the Salesforce API Only System Integrations profile - a free, non-seat license included in every Salesforce org
- No paid Admin, Platform, or full Salesforce license is consumed by SF Vault - the integration user does not occupy a billable seat
- All consultant activate/deactivate/freeze operations are performed by this free service account, keeping operational costs at zero
- The Salesforce package is controlled entirely via Custom Metadata - toggle the API on/off, gate user creation, set an API key, or adjust email whitelists without redeploying code
- Settings are cached per request to minimize Salesforce governor limit consumption
05 - AuthAuthentication
The web app uses NextAuth v5 with credentials-based authentication. All routes are protected by default.
- Email + password login form
- Passwords hashed with bcryptjs
- Session stored as JWT, validated server-side on every request
- Inactive accounts blocked at login - no session created
- Admin-created users have
mustChangePassword = trueby default - Middleware redirects to change-password page until cleared
- Flag cleared only after user sets a new password
- All
/dashboardand/adminroutes require active session - Admin-only routes verified server-side - no client-only guard
- Unauthenticated requests redirect to
/login
06 - RolesRoles & Access
Two roles control what each user can see and do inside the application.
Administrator
- Create, edit, deactivate, delete app users
- Reset any user's password
- Assign/revoke org access per user
- Add, edit, delete Salesforce orgs
- Trigger OAuth connection for any org
- View all users and orgs in the system
- Manage consultants in any org
Standard User
- View orgs they have been granted access to
- View and manage consultants within those orgs
- Activate, deactivate, freeze, unfreeze consultants
- Create new consultant users (if allowed by settings)
- Change their own password
07 - UsersUser Management
Admins manage the internal application users - the team members who will access Salesforce orgs through SF Vault.
- Set name, email, temporary password, and role (ADMIN / USER)
- User is marked active by default with
mustChangePassword = true - Email must be unique in the system
- Update name, email, or role at any time
- Admin can reset any user's password (triggers
mustChangePasswordagain) - Toggle active/inactive status without deleting the account
- Admin grants or revokes access to specific Salesforce orgs per user
- Access grants stored with timestamp and granting admin's ID
- Revoking access immediately removes the org from the user's dashboard
- Table view of all users with role, status, and creation date
- Inline delete with confirmation (guarded against self-deletion)
08 - OrgsOrg Management
Admins register and configure Salesforce orgs. Each org stores the OAuth credentials needed to call its APIs.
- Name, environment type, instance URL, login URL, Org ID, username, description
- Supports Production, Sandbox, Scratch, Developer, and Custom environments
- OAuth tokens added via the Connect flow (see OAuth section)
Supported Environment Types
Production
Sandbox
Scratch
Developer
Custom
- Each org shows connected / disconnected status
- Last activated timestamp and username tracked
- Admin can re-trigger OAuth if tokens expire
- View all users who have access to a given org
- Grant or revoke access to individual users from the org page
09 - DashboardUser Dashboard
Every authenticated user sees a personal dashboard showing the orgs they can access.
Org Cards
Each assigned org appears as a card showing its name, environment type, instance URL, username, and live connection status.
Drill-Down
Click any org card to open the consultant management view for that org - all consultant users in that Salesforce instance.
Status Indicators
Visual indicators show whether the org is connected (OAuth valid) or disconnected, so users know immediately if action is needed.
Scoped View
Users only see orgs explicitly granted to them by an admin. No cross-org data leakage.
10 - ConsultantsConsultant Management
The core feature of SF Vault. Once inside an org, users can view and control every consultant user account in that Salesforce org.
- Fetches all active
Userrecords withConsultant__c = truefrom the org - Displays name, email, profile, active status, and frozen status
- Data is real-time - directly from Salesforce on each page load
- Activate sets
User.IsActive = true- consultant can log in - Deactivate sets
User.IsActive = false- consultant cannot log in, Salesforce license freed - A 15-minute warning appears in the UI when a consultant was recently activated, preventing accidental double-activations
- Freeze prevents login without deactivating the user - their record and data remain fully intact
- Unfreeze restores login capability immediately
- Useful for temporarily blocking access without losing the user's setup (queues, assignments, etc.)
- Create new
Userrecords directly in the Salesforce org from the web UI - New users automatically have
Consultant__c = true - Subject to email domain and whitelist restrictions configured in the org's Custom Metadata
- Feature can be disabled via
SF_Vault_Setting__mdt.Allow_User_Creation__c
- Deactivates all consultant users in the org simultaneously
- Automatically called before creating a new consultant to enforce "one active at a time" patterns
- Exposed as a standalone API endpoint for programmatic use
11 - OAuthOAuth Integration
Each Salesforce org connection uses standard OAuth 2.0. Tokens are encrypted at rest and automatically refreshed.
Initiate OAuth
Admin clicks "Connect" on an org. The web app redirects to Salesforce's authorization endpoint with the configured login URL.
Callback received
Salesforce redirects back with an authorization code. The Next.js API route exchanges it for an access token and refresh token.
Tokens encrypted and stored
Access and refresh tokens are encrypted using AES-256 before being written to the SalesforceOrg record in PostgreSQL. Org is marked isConnected = true.
Auto-refresh on expiry
Before each API call, if the access token is expired, the refresh token is used automatically to obtain a new one. The new token is re-encrypted and saved.
12 - APISalesforce REST API
The Salesforce package exposes a single Apex REST resource at /services/apexrest/consultants/ with multiple sub-routes.
| Method | Path | Description | Key Behavior |
|---|---|---|---|
| GET | /consultants/ |
List consultants | Returns all Users with Consultant__c = true, includes frozen status from UserLogin |
| POST | /consultants/create |
Create consultant | Validates domain/email whitelist. Requires Allow_User_Creation__c = true in metadata. |
| POST | /consultants/enable |
Activate user | Sets User.IsActive = true by userId in request body |
| POST | /consultants/disable |
Deactivate user | Sets User.IsActive = false by userId |
| POST | /consultants/disable-all |
Deactivate all consultants | Bulk update - deactivates every consultant in the org |
| POST | /consultants/freeze |
Freeze user | Sets UserLogin.IsFrozen = true; login blocked without deactivation |
| POST | /consultants/unfreeze |
Unfreeze user | Sets UserLogin.IsFrozen = false; login restored |
Authentication
All endpoints validate the incoming request with two mechanisms:
- Salesforce OAuth access token (standard Connected App authentication)
- Optional
X-Api-Keyheader matched againstSF_Vault_Setting__mdt.Api_Key__c
Request / Response Format
// POST /consultants/enable // Request body (JSON) { "userId": "0055g000001xxxAAA" } // Success response { "success": true, "message": "User activated successfully" } // Error response { "success": false, "message": "Email domain not allowed" }
13 - ConfigCustom Metadata Settings
The Salesforce package is controlled via a Custom Metadata Type (SF_Vault_Setting__mdt). Settings are cached per-request to avoid repeated SOQL queries.
Default record of SF_Vault_Setting__mdt and cached in memory during the request cycle to minimize governor limit consumption.
14 - FieldsCustom Fields
The package adds two custom fields to the standard Salesforce User object.
| Field API Name | Type | Purpose |
|---|---|---|
| User.Consultant__c | Boolean | Marks a user as a managed consultant. Only users with this flag = true appear in the SF Vault API responses and can be managed via the platform. |
| User.SF_Vault_Integration_User__c | Boolean | Identifies service account users created during installation. These users are excluded from consultant queries and reserved for API authentication. |
15 - SetupInstallation
SF Vault has two deployment targets - the Next.js web app and the Salesforce SFDX package.
Salesforce Package
Authorize your org
sf org login web --alias my-org
Deploy the package
sf project deploy start --target-org my-org
Create integration user
Navigate to /apex/AppInstallLink in the org and complete the setup form to provision the integration service account used for OAuth authentication.
Configure metadata
Edit the SF_Vault_Setting.Default Custom Metadata record to set your allowed email domains, API key, and user creation preference.
Web Application
Install dependencies
npm install
Configure environment variables
DATABASE_URL="postgresql://user:pass@host/db" AUTH_SECRET="your-nextauth-secret" ENCRYPTION_KEY="32-byte-aes-key-for-token-storage" SALESFORCE_CLIENT_ID="your-connected-app-client-id" SALESFORCE_CLIENT_SECRET="your-connected-app-secret"
Run database migrations
npx prisma migrate deploy npx prisma db seed
Start the app
npm run dev # development npm run build # production build npm start # production server
16 - SchemaDatabase Schema
The PostgreSQL database has three tables managed by Prisma ORM.
User
| Field | Type | Notes |
|---|---|---|
| id | String (UUID) | Primary key, auto-generated |
| name | String | Display name |
| String | Unique, used for login | |
| password | String | bcrypt hash |
| role | Enum | ADMIN | USER |
| isActive | Boolean | Soft-delete / block login |
| mustChangePassword | Boolean | Forces password reset on next login |
| createdAt / updatedAt | DateTime | Auto-managed by Prisma |
SalesforceOrg
| Field | Type | Notes |
|---|---|---|
| id | String (UUID) | Primary key |
| name | String | Display name |
| environment | Enum | PRODUCTION | SANDBOX | SCRATCH | DEVELOPER | CUSTOM |
| instanceUrl | String | e.g. https://myorg.my.salesforce.com |
| orgId | String | 18-char Salesforce Org ID |
| username | String | Integration user's Salesforce username |
| loginUrl | String | OAuth login endpoint |
| accessToken | String? | AES-256 encrypted |
| refreshToken | String? | AES-256 encrypted |
| isConnected | Boolean | OAuth handshake completed |
| lastActivatedAt | DateTime? | Timestamp of last consultant activation |
| lastActivatedUsername | String? | SF Vault user who last activated a consultant |
UserOrgAccess
| Field | Type | Notes |
|---|---|---|
| id | String (UUID) | Primary key |
| userId | String (FK) | References User |
| orgId | String (FK) | References SalesforceOrg |
| grantedBy | String | ID of admin who granted access |
| grantedAt | DateTime | When access was granted |
17 - SecuritySecurity Model
SF Vault applies multiple independent security layers at each boundary of the system.
Token Encryption at Rest
OAuth access and refresh tokens are encrypted with AES-256 before storage in PostgreSQL. The plaintext never persists to disk.
Password Hashing
All application passwords are hashed with bcrypt before storage. No plaintext passwords are ever stored or logged.
API Key Auth
An optional shared API key (X-Api-Key header) provides a second authentication layer on all Apex REST endpoints.
Email Whitelist
User creation is restricted to approved email domains and/or specific addresses configured in Salesforce Custom Metadata. No arbitrary accounts can be created.
Role Enforcement
Admin routes are verified server-side on every request. Role checks happen in Server Actions and API routes - not just client-side navigation guards.
Account Isolation
Users can only see orgs explicitly assigned to them. No user can access org data or consultant lists from unassigned orgs - enforced in every query.
Consultant Flag
Only Salesforce users with Consultant__c = true are returned by the API and manageable via SF Vault. Standard org users are invisible and untouchable.
Token Auto-Refresh
Expired OAuth tokens are refreshed automatically and re-encrypted before storage, preventing stale token errors without requiring manual re-auth.
Activation Warning
A 15-minute cooldown warning appears after a consultant is activated, preventing accidental repeat activations or license over-use.
ENCRYPTION_KEY environment variable must be kept secret and backed up separately. Losing it means encrypted OAuth tokens can no longer be decrypted and all orgs will need to be re-connected.