befibeforbefire SF Vault - Documentation
Open Source · Salesforce · Consultant Management

SF Vault

A full-stack platform for managing consultant user access across Salesforce orgs. Control who is active, who is frozen, and which users can access which environments - all from a single dashboard.

Next.js 15 + React 19 Salesforce Apex REST PostgreSQL + Prisma NextAuth v5 Salesforce API v66.0

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.

💡
Core use case: A consulting firm deploys SF Vault to control when individual consultants are "active" in a client's Salesforce org. The admin can enable a consultant for a workday, then disable or freeze them when off-site - preventing unauthorized access without deleting the user record.

02 - ArchitectureSystem Architecture

SF Vault is a client-server system with two independently deployable components that communicate over HTTPS.

Browser
Admin UI
React 19 + Tailwind
HTTP / Server Actions
Web App
Next.js 15
API Routes + Auth
Database
PostgreSQL
via Prisma ORM
OAuth 2.0 + X-Api-Key
Salesforce Org A
Apex REST API
/services/apexrest/consultants
Salesforce Org B
Apex REST API
/services/apexrest/consultants
Salesforce Org N
Apex REST API
...

Data Flow

1

Admin logs in

NextAuth authenticates via email/password. Session is established with role (ADMIN or USER).

2

Org selection

User navigates to their assigned orgs on the dashboard. Each org card shows connection status and environment type.

3

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.

4

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.

5

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

Next.js 15 React 19 📘 TypeScript 🔐 NextAuth v5 🗄 Prisma ORM 🐘 PostgreSQL 🎨 Tailwind CSS 🔑 bcryptjs

Salesforce Package

Salesforce Apex REST API (v66.0) Custom Metadata Types 🔧 SFDX / SF CLI 🧪 Apex Test Classes Jest (LWC) 🪝 Husky Pre-commit

04 - FeaturesFeature Overview

Everything SF Vault can do, at a glance. Each feature is covered in depth in its own section.

Multi-Org Dashboard
Central access point
  • 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
Consultant Activation
Enable / Disable
  • Flip a consultant's IsActive flag 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
User Freezing
Freeze / Unfreeze
  • 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
Bulk Disable
Disable All
  • 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
Consultant Provisioning
Create users
  • Create new consultant User records 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
Per-User Org Access
Granular grants
  • 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
OAuth Connectivity
Auto-refresh tokens
  • 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
Role-Based Access
Admin vs User
  • 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)
Internal User Mgmt
App accounts
  • 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
Zero License Cost
Free API-only user
  • 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
Runtime Configuration
No redeployment
  • 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.

Login
Credentials Provider
  • 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
Force Password Change
First-login enforcement
  • Admin-created users have mustChangePassword = true by default
  • Middleware redirects to change-password page until cleared
  • Flag cleared only after user sets a new password
Route Protection
Middleware-based
  • All /dashboard and /admin routes 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.

ADMIN

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
USER

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
⚠️
Admin cannot delete themselves. A safety guard prevents the last admin account from being deactivated or deleted.

07 - UsersUser Management

Admins manage the internal application users - the team members who will access Salesforce orgs through SF Vault.

Create User
Admin only
  • 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
Edit User
Admin only
  • Update name, email, or role at any time
  • Admin can reset any user's password (triggers mustChangePassword again)
  • Toggle active/inactive status without deleting the account
Org Access
Per-user grants
  • 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
User List
Admin overview
  • 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.

Add Org
Admin only
  • 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

Connection Status
OAuth health
  • Each org shows connected / disconnected status
  • Last activated timestamp and username tracked
  • Admin can re-trigger OAuth if tokens expire
User Assignment
Per-org roster
  • 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.

List Consultants
Live from Salesforce
  • Fetches all active User records with Consultant__c = true from the org
  • Displays name, email, profile, active status, and frozen status
  • Data is real-time - directly from Salesforce on each page load
Activate / Deactivate
User.IsActive toggle
  • 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 / Unfreeze
UserLogin.IsFrozen toggle
  • 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 Consultant
Controlled provisioning
  • Create new User records 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
Disable All
Bulk operation
  • 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
Activate vs Freeze distinction: Deactivating a user releases their Salesforce license and is reversible. Freezing a user keeps their license allocated but blocks login - ideal for short-term lockout scenarios where the license cost is acceptable.

11 - OAuthOAuth Integration

Each Salesforce org connection uses standard OAuth 2.0. Tokens are encrypted at rest and automatically refreshed.

1

Initiate OAuth

Admin clicks "Connect" on an org. The web app redirects to Salesforce's authorization endpoint with the configured login URL.

2

Callback received

Salesforce redirects back with an authorization code. The Next.js API route exchanges it for an access token and refresh token.

3

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.

4

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-Key header matched against SF_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.

Enabled__c

API Toggle

Master switch. When false, all API endpoints return an error immediately.

Default: true
Allow_User_Creation__c

User Creation Gate

When false, the /create endpoint is disabled and returns an error.

Default: false
Api_Key__c

API Key

Optional shared secret. If set, every incoming request must include a matching X-Api-Key header.

Default: empty (disabled)
Available_Domains__c

Email Domain Whitelist

Comma-separated list of allowed email domains for user creation. Blocks creation of users outside these domains.

Example: "acme.com,contractor.io"
Available_Emails__c

Email Address Whitelist

Comma-separated list of individual email addresses allowed to be created, regardless of domain.

Example: "partner@external.com"
💡
Settings are read from the 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

1

Authorize your org

sf org login web --alias my-org
2

Deploy the package

sf project deploy start --target-org my-org
3

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.

4

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

1

Install dependencies

npm install
2

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"
3

Run database migrations

npx prisma migrate deploy
npx prisma db seed
4

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

FieldTypeNotes
idString (UUID)Primary key, auto-generated
nameStringDisplay name
emailStringUnique, used for login
passwordStringbcrypt hash
roleEnumADMIN | USER
isActiveBooleanSoft-delete / block login
mustChangePasswordBooleanForces password reset on next login
createdAt / updatedAtDateTimeAuto-managed by Prisma

SalesforceOrg

FieldTypeNotes
idString (UUID)Primary key
nameStringDisplay name
environmentEnumPRODUCTION | SANDBOX | SCRATCH | DEVELOPER | CUSTOM
instanceUrlStringe.g. https://myorg.my.salesforce.com
orgIdString18-char Salesforce Org ID
usernameStringIntegration user's Salesforce username
loginUrlStringOAuth login endpoint
accessTokenString?AES-256 encrypted
refreshTokenString?AES-256 encrypted
isConnectedBooleanOAuth handshake completed
lastActivatedAtDateTime?Timestamp of last consultant activation
lastActivatedUsernameString?SF Vault user who last activated a consultant

UserOrgAccess

FieldTypeNotes
idString (UUID)Primary key
userIdString (FK)References User
orgIdString (FK)References SalesforceOrg
grantedByStringID of admin who granted access
grantedAtDateTimeWhen 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.

🔴
Production deployment note: The 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.