Skip to content

Stock n8n Integration & OAuth2 PKCE ​

LatticeDX integrates stock n8nio/n8n:2.48.1 as an external orchestration runtime through its REST v1 bridge (n8n-api-client.js), AES-256-GCM Connector Vault (connector-vault.js), and CloudEvents 1.0 Event Bus (event-bus.js). This separation keeps external community workflow nodes isolated from LatticeDX's Apache-2.0 plugin core while centralizing credential encryption, SSRF enforcement, and OAuth2 token refreshes per tenant.

Stock n8n REST v1 Bridge, OAuth2 PKCE Vault & EventBus Outbox
LANE 1: CONNECTOR VAULT & 2-PHASE OAUTH2 PKCE S256LANE 2: STOCK N8N 2.48.1 BRIDGE & SIGNED CALLBACKpkcetokensecretsOAuth2RESTrunHMACConnector VaultAES-256-GCM (iv:tag)DX_VAULT_MASTER_KEY2-Phase OAuth2PKCE S256TX1 Consume Nonce ->HTTP -> TX2 EncryptAuto-Refresh(180s Buffer)180s expiry bufferWeakMap DedupdxosN8n StudioBridgeSSRF Host AllowlistIdempotency-KeyStock n8n REST v1:5678 /api/v1/creds · workflowsWorkflowExecution & Retry/api/v1/executions:retryExecutionSigned CallbackIngress:webhookIngressHMAC-SHA256 Verified
Inspector2-Phase OAuth2 PKCE S256Click any component to inspect bindings & boundaries
Role
RFC 7636 PKCE S256 handshake without holding DB locks
Package / Port
connector-vault.js · oauthStart / oauthCallback
Protocol
TX1 SELECT FOR UPDATE -> fetch(redirect:'error') -> TX2
Payload / Schema
32B verifier · 24B hex stateNonce (15m TTL)
Responsibilities
Atomically consumes the one-time nonce in TX1, exchanges authorization_code outside DB locks (10s timeout), then encrypts tokens in TX2.
Switch views to inspect Connector Vault / two-phase OAuth2 PKCE S256 syncing with Stock n8n REST v1 (:5678) and the PG16 Standard Webhooks outbox.

Deployment Topology & Environment Variables ​

Stock n8n runs as an isolated OCI container (n8nio/n8n:2.48.1) on internal port 5678 defined in infra/compose/integration.yml. When resolving an organization's n8n client, dxosN8n first looks up active n8n / n8n_api records in latticeConnectors and falls back to DX_N8N_API_URL and DX_N8N_API_KEY when no tenant-specific connector is configured.

n8n Bridge & Connector Vault Environment Variables
ParameterTypeDefaultDescription
DX_N8N_API_URL
stringhttp://n8n:5678Fallback base URL for Stock n8n when the tenant has no active n8n_api connector in Vault.
DX_N8N_API_KEY
string—Fallback X-N8N-API-KEY secret used for REST v1 authentication.
N8N_ENCRYPTION_KEYrequired
string—Internal credential encryption key for the n8nio/n8n:2.48.1 container.
N8N_RUNNERS_ENABLED
booleantrueEnables isolated task runners inside the n8n runtime.
DX_VAULT_MASTER_KEY
string—Primary key material for AES-256-GCM Vault encryption (takes precedence over ENCRYPTION_FIELD_KEY, NOCOBASE_APP_KEY, and APP_KEY).
DX_ALLOW_INTERNAL_CONNECTORS
booleantrueAllows connectors to target explicit internal Compose hostnames.
DX_INTERNAL_SERVICE_HOSTS
stringn8n,orion-ld,nodered,mosquittoComma-separated internal host allowlist exempted from private-IP SSRF blocking.

Stock n8n REST v1 Bridge (dxosN8n) ​

The dxosN8n resource exposes 10 actions covering health checks, workflow lifecycle, execution inspection/retry, and credential synchronization against /api/v1/*. Every call passes through requireN8nAdmin: callers must hold root, admin, or ldx_admin (or isOrgAdmin) and present matching PAT scopes (read, write, or ai).

GET/api/dxosN8n:status
Bearer JWT | ldx_pat_*read | write | ai
Probes n8n /healthz and verifies X-N8N-API-KEY connectivity via GET /api/v1/workflows?limit=1.
POST/api/dxosN8n:createWorkflow
Bearer JWT | ldx_pat_*write | ai
Creates an n8n workflow via POST /api/v1/workflows with an automatically attached Idempotency-Key header.
POST/api/dxosN8n:syncCredential
Bearer JWT | ldx_pat_*write | ai
Decrypts connector secrets or refreshes OAuth2 tokens from dxosVault, translates them to n8n credential schemas, and persists n8nCredentialId on latticeConnectors.

All 10 dxosN8n actions map to the following upstream Stock n8n endpoints:

dxosN8n ActionMethodStock n8n REST v1 EndpointResponsibility
statusGETGET /healthz, GET /api/v1/workflows?limit=1Returns ok, healthzOk, apiOk, hasApiKey, and latencyMs
appCatalogGET—Lists the 11 curated APP_CONNECTOR_CATALOG entries with per-tenant configuredCount
workflowsGETGET /api/v1/workflowsLists workflows filtered by active, tags, name, limit (1..250), and cursor
getWorkflowGETGET /api/v1/workflows/:idFetches full workflow node and connection JSON
createWorkflowPOSTPOST /api/v1/workflowsProvisions a workflow with Idempotency-Key protection
updateWorkflowPOSTPUT /api/v1/workflows/:idReplaces an existing workflow definition
activateWorkflowPOSTPOST /api/v1/workflows/:id/activate or /deactivateActivates or deactivates a workflow on n8n
executionsGETGET /api/v1/executionsLists execution history filtered by workflowId, status, includeData, limit, cursor
retryExecutionPOSTPOST /api/v1/executions/:id/retryRetries a failed execution with optional loadWorkflow
syncCredentialPOSTPOST /api/v1/credentialsPushes decrypted or OAuth2-refreshed Vault credentials to n8n and records n8nCredentialId

Every mutating HTTP request (POST, PUT, PATCH, DELETE) attaches Idempotency-Key (ldx-<uuid> by default, or ldx-cred-<orgId>-<connectorKey>-v<secretVersion> during credential sync). Upstream errors pass through scrubN8nSecrets so API keys and credential fields are replaced with [REDACTED] before returning to callers.

bash
# Verify n8n REST v1 bridge health
curl -sS "https://app.latticedx.example.com/api/dxosN8n:status" \
  -H "Authorization: Bearer ldx_pat_your_token"

# Sync a Telegram Vault connector into Stock n8n
curl -sS -X POST "https://app.latticedx.example.com/api/dxosN8n:syncCredential" \
  -H "Authorization: Bearer ldx_pat_your_token" \
  -H "Content-Type: application/json" \
  -d '{
    "targetConnectorKey": "tg-ops",
    "credentialName": "Ops Telegram Alert"
  }'

Connector Vault (dxosVault) & Credential Mapping ​

Direct CRUD access to latticeConnectors is blocked by registerConnectorVaultDirectGuard (403). All secret storage and probes run through the 8 dxosVault actions: list, save, rotateSecret, delete, testConnection, appCatalog, oauthStart, and oauthCallback.

Secrets in encryptedSecretsJson, oauthAccessTokenEnc, and oauthRefreshTokenEnc are encrypted using AES-256-GCM (iv:tag:cipher hex) with a SHA-256 key derived from DX_VAULT_MASTER_KEY (falling back to ENCRYPTION_FIELD_KEY, NOCOBASE_APP_KEY, or APP_KEY). During dxosN8n:syncCredential, buildCredentialPayloadFromConnector maps each of the 11 catalog apps to its Stock n8n credential schema:

appType in APP_CONNECTOR_CATALOGAuth TypesTarget n8nCredentialTypeMapped Secret Fields
telegramapi_key, bearertelegramApiaccessToken (from botToken / accessToken)
email_smtpbasic, nonesmtpuser, password, host, port, secure
gmail_oauth2oauth2gmailOAuth2clientId, clientSecret, oauthTokenData.access_token
google_sheets_oauth2oauth2googleSheetsOAuth2ApiclientId, clientSecret, oauthTokenData.access_token
slackoauth2, bearerslackOAuth2ApiaccessToken, oauthTokenData.access_token
discordbearer, nonediscordWebhookApiwebhookUrl, botToken
teamsoauth2, bearermicrosoftTeamsOAuth2ApiaccessToken, oauthTokenData.access_token
githuboauth2, bearergithubOAuth2ApiaccessToken, oauthTokenData.access_token
rustfs_s3api_key, basics3endpoint, region, accessKeyId, secretAccessKey
n8n_apiapi_key, hmac, bearerhttpHeaderAuthapiKey, webhookSecret
partner_webhookhmac, bearer, api_keyhttpHeaderAuthHeader name (Authorization / X-API-Key) and value

OAuth2 PKCE S256 Handshake & Single-Flight Refresh ​

For OAuth2-capable apps (gmail_oauth2, google_sheets_oauth2, slack, teams, github), connector-vault.js enforces RFC 7636 PKCE (S256) with a two-transaction handshake that avoids holding database locks across outbound HTTP calls:

StepStage / EndpointExecution Behavior
1Initiate (POST /api/dxosVault:oauthStart)Generates a 32-byte base64url codeVerifier, derives codeChallenge = SHA256(codeVerifier) (codeChallengeMethod: "S256"), and issues a 24-byte hex stateNonce valid for OAUTH_STATE_TTL_MS = 15 min. The _oauthPkce metadata is AES-256-GCM encrypted inside encryptedSecretsJson and authorizeUrl is returned.
2Consume Nonce in TX1 (GET/POST /api/dxosVault:oauthCallback)Acquires a row-level lock (SELECT ... FOR UPDATE), verifies state via timingSafeEqual, checks the 15-minute TTL, strips oauthStateNonce and _oauthPkce from storage, and commits TX1 before any outbound network I/O.
3Token Exchange Outside DB TransactionSubmits an application/x-www-form-urlencoded POST (grant_type=authorization_code, code, code_verifier, redirect_uri, client_id) with redirect: 'error' and a 10,000 ms abort timeout.
4Persist Encrypted Tokens in TX2Encrypts access_token and refresh_token into oauthAccessTokenEnc and oauthRefreshTokenEnc alongside oauthTokenExpiresAt.
5Single-Flight Refresh (getFreshConnectorToken)Whenever expiresAt - now <= 180s (OAUTH_REFRESH_BUFFER_SEC_DEFAULT), concurrent callers for the same (organizationId, connectorId) share one in-flight promise stored in dbInflightTokenRefresh (WeakMap) so only a single refresh request reaches the OAuth2 provider.
POST/api/dxosVault:oauthStart
Bearer JWT | ldx_pat_*write
Issues a 15-minute stateNonce and PKCE S256 challenge for an OAuth2 connector and returns authorizeUrl.
POST/api/dxosVault:oauthCallback
Bearer JWT | ldx_pat_*write
Atomically consumes the one-time oauthStateNonce, exchanges the authorization code, and stores AES-256-GCM encrypted tokens.

Bidirectional Webhook & Event Sync (dxosEvents & dxosAutomations) ​

Synchronization between LatticeDX and Stock n8n operates bidirectionally with explicit signature verification on both boundaries:

  • Outbound (LatticeDX to n8n): Domain events published via dxosEvents:publish (alarm.triggered, device.offline, lot.held_mkt) are queued in latticeWebhookDeliveries and delivered as CloudEvents 1.0 payloads with Standard Webhooks headers (webhook-id, webhook-timestamp, webhook-signature: v1,<b64>, ce-type) to n8n Webhook Trigger nodes configured with rawBody: true. Reference workflows in lattice-templates/n8n-workflows/ verify the HMAC-SHA256 signature and 300-second replay window before processing.
  • Inbound (n8n to LatticeDX): Workflows in n8n invoke /api/dxosAutomations:runNow (authenticated with a least-privilege ldx_pat_* token) or /api/dxosAutomations:webhookIngress (verified with X-Lattice-Signature-256 or Standard Webhooks headers) to trigger internal LatticeFlow v2 DAGs.

SSRF Controls & Error Codes ​

Every connector URL and outbound n8n request undergoes synchronous assertSafeConnectorUrl and asynchronous DNS-resolving assertSafeConnectorUrlAsync validation. The guard rejects non-HTTP(S) schemes, embedded URL credentials (user:pass@host), loopback/private/link-local IPs, and cloud metadata endpoints (169.254.*, fd00:ec2::254), while permitting explicit DX_INTERNAL_SERVICE_HOSTS when DX_ALLOW_INTERNAL_CONNECTORS=true. Outbound fetch() calls always set redirect: 'error' with a 10,000 ms timeout, mapping upstream 4xx responses directly and 5xx/network failures to 502 N8N_API_HTTP_ERROR or N8N_API_REQUEST_FAILED.

Common error codes surfaced by dxosN8n and dxosVault:

Error CodeHTTPCause and Remediation
N8N_CONNECTOR_NOT_CONFIGURED404Tenant has no active n8n/n8n_api connector and DX_N8N_API_URL is unset
N8N_API_KEY_MISSING400Missing X-N8N-API-KEY on both the Vault connector and environment fallback
N8N_ADMIN_REQUIRED403Caller lacks root, admin, or ldx_admin verified role membership
N8N_API_HTTP_ERROR4xx / 502Upstream n8n returned an error status; secrets are redacted by scrubN8nSecrets
CONNECTOR_URL_UNSAFE400Target URL failed SSRF validation or contained embedded URL credentials
OAUTH_STATE_MISMATCH400stateNonce did not match or was already consumed in TX1
OAUTH_STATE_EXPIRED400Delay between oauthStart and oauthCallback exceeded 15 minutes
OAUTH_REFRESH_TOKEN_MISSING401Access token expired and oauthRefreshTokenEnc is absent on the connector

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)