GoHighLevel (GHL)
Audience: Sales, management, support, engineering · Where in app: Settings → Integrations → GoHighLevel · Plan availability: All plans (verify) · agency white-label supported
Naming: the UI says "LeadConnector". All user-facing copy was renamed GoHighLevel → LeadConnector (frontend commits
48a9f133/0b62b6b6). Code, config keys, and routes remaingo_high_level/ghl/goHighLevel*— internal docs keep GHL as the technical name.
GoHighLevel is the deepest CRM integration and the dominant CRM among Knock Knock's agency customers. It does everything HubSpot does plus pipeline/opportunity sync, in-widget calendar booking, automation-event mirroring, and a Nox "action layer" that can draft and send follow-up SMS/email from inside the agent. Campaign visitors are recognized through ?kk= recognition tokens (see kk_token), not a raw ?contact_id=.
What it does
- Bi-directional contact sync (Knock Knock ↔ GHL Contacts).
- Opportunity & pipeline-stage read/filter.
- In-widget calendar booking via GHL Calendar.
- Form intercept for GHL embedded forms (V1 + V2, white-label domains).
- Visitor recognition via
kk_tokenlinks (?kk={{contact.kk_token}}). - Iframe (custom menu / marketplace Custom Page) login, per-staff via SSO.
- Automation-event mirroring (GHL workflows → Nox audit log).
- Nox-drafted follow-ups (draft → approve → send SMS/email) — see the action layer below.
- Agency white-label support across many tenants.
How it works
Auth model: OAuth (v2 marketplace app), with two flavors.
| Flavor | What | Stored on |
|---|---|---|
| OAuth (location) | Standard tenant connection to a GHL location | companies.go_high_level.* |
| Self-account | Web owner's own GHL agency install, no location (holds their menu links) | companies.ghl_self_account.* |
companies.go_high_level.* fields include: access_token, refresh_token, access_token_expires_at, location_id, company_id (the GHL company), user_type, app_version (only 'v2' works — see below), calendar_id (selected booking calendar), multi_calendar_enabled + multi_calendar_ids (visible-calendar subset) + multi_calendar_purposes (Mixed map { <calendar_id>: purpose text }, mirrored on the ms-comm CompanyModel), kk_field_ids (custom-field id cache), custom_menu_id + custom_menu_held_by ('company'/'agency' — whose GHL agency token created the link, the only one that can delete it), secret_key (per-company menu-link login code / legacy webhook secret), user_map ([{ ghl_user_id, user_id }] or { ghl_user_id, blocked: true }, iframe staff mapping), sidebar_label + sidebar_hidden (Custom Page sidebar item), custom_page_at (first Custom Page login) and granted_scopes (scopes on the current grant).
Tokens never reach the browser (15fda18a9): go_high_level.access_token/refresh_token/secret_key and ghl_self_account + agency go_high_level tokens are select:false. Read them with +go_high_level.access_token; "connected" in the frontend is access_token_expires_at.
One "GHL connected" rule (637e65f8e): isGhlConnected (crm/resolveProvider.js) = the port's go_high_level.location_id test, replacing ad-hoc token/expiry checks in AiCallContactExtractedController, AiOutboundCallController, KnoxStatsController, NoxActionUserController, IdentityGraphService and the jobs. ChatTranscriptEmailJob used to select('+go_high_level'), which never loaded the select:false token, so after-chat tags were skipped for every tenant; AiCallGhlTranscriptSyncJob no longer loads tokens, and a Mongo error on the company load retries instead of marking the room skipped (test/ghl-connected-gate.spec.js).
One marketplace app — v1 retired (135988040, 2026-10-19)
Only the public marketplace app ("Knock Knock App") is configured. app/configs/goHighLevel.js holds client_id/client_secret/sso_key, still read from the GO_HIGH_LEVEL_V2_* env names so a stale GO_HIGH_LEVEL_CLIENT_ID can never bring the v1 creds back. Gone: new_install_app_version (GO_HIGH_LEVEL_NEW_INSTALL_APP_VERSION), the agency go_high_level_install_version override + admin selector, _appCreds, _exchangeDetectingApp, the frontend VITE_GHL_V2_LIVE flag.
- Every install/reconnect stamps
app_version: 'v2'. The schema default is still'v1', so old rows read as retired. GoHighLevelService._assertCurrentAppruns ingetCompanyClient/getAgencyClient/getCompanySelfClientbefore any refresh: a non-v2token throwsGHL_APP_RETIRED("install the new app to reconnect"). Nothing syncs for those tenants until they reinstall.- A native
UNINSTALLfrom the retired app's id (RETIRED_APP_IDinGhlNativeEventHelper) only clears non-v2connections, so a client removing the old app after installing the new one keeps its connection. - OAuth
stateis HMAC-signed and expires in 24h (app/lib/oauthState.js) — unsigned or plain-id state is rejected, and an allowlistedreturn_pathrides inside the signed state. Agency install/uninstall/complete-install require managing that exact agency. - Frontend:
common/helpers/ghlMenuLink.jsusesRetiredApp(company)(eithergo_high_levelorghl_self_accountconnected withapp_version !== 'v2') /agencyUsesRetiredApp.GhlAppUpdateBanner.vueshows a red, non-dismissible "LeadConnector has stopped syncing … Reconnect to install the new app." bar inAppLayoutand (scope="agency")AgencyLayout; the integrations card shows Install the new app + Reconnect; the agency client list shows Old app: stopped.
App update banner (f89a6a43b / frontend f4cce741). GHL exposes no installed-version API, so the first Custom Page login (code === 'sso') stamps go_high_level.custom_page_at — the only proof the install runs app 2.0.0+. A v2 company without it gets a dismissible blue GhlAppUpdateBanner ("update it from your App Marketplace, then open Next Level AI").
Granted scopes. grantedScopes(res) records the token response's scope as go_high_level.granted_scopes on install, reconnect and refresh; /user/me adds go_high_level.missing_scopes (missingScopes: requested client_scope minus granted; [] until a grant with scopes was saved). The LeadConnector card then shows Permissions needed + "Not yet granted:" + Reconnect to upgrade.
Marketplace-directory (stateless) install
The app is public-listed on the GHL marketplace, so installs can start GHL-side with no OAuth state:
- A no-state callback on
GET /ghlinstallation/installredirects to the SPA with?ghl_code=<single-use code>; the code survives login/register/social auth and is bound to the logged-in user via the authenticated complete-install endpoint (GoHighLevelController.completeInstall). - Directory installs are two-step: an agency-level token (no
locationId) lands onghl_self_account/ the agency'sgo_high_leveland the bind returnsneeds_mapping: true; the sub-account step maps a location ontocompany.go_high_leveland creates the custom menu. - Menu link:
_createSubAccountMenu()(best-effort, never breaks the bind) first removes any previous link (it points at the old secret), then creates one only whengoHighLevel.sso_keyis unset — the Custom Page replaces it, and needs the SSO key to log anyone in. See Menu links below.
Requested scopes (client_scope): contacts.*, conversations.*, conversations/message.*, lc-email.readonly (Agent K click events, f89a6a43b), opportunities.*, calendars.readonly, calendars/events.*, locations.readonly, locations/customFields.*, locations/customValues.readonly, locations/tags.*, locations/tasks.readonly, workflows.readonly (Nox funnel workflow picker, f89a6a43b), users.readonly, phonenumbers.read, numberpools.read, medias.*, oauth.*, custom-menu-link.*. Existing grants lacking a new scope surface as missing_scopes.
Direction: bi-directional.
?contact_id= landing removed — use kk_token
The widget loader no longer reads ?contact_id= / ?ghl_contact_id= (5b55a0b55): a raw contact id in a URL is spoofable, and the old _maybeTriggerCrmLanding → /identity-graph/crm-landing-verify call never worked anyway (api-key route → always 401). Campaign recognition is the signed per-contact kk_token (?kk={{contact.kk_token}}, stitched by /user-session/kk-click); the loader's only remaining CRM-landing check is HubSpot's hubspotutk — see HubSpot.
Iframe login: custom menu, marketplace Custom Page, per-staff SSO
POST /login/go-high-level (AuthController.goHighLevelLogin) logs the iframe in. The SPA route is /go-high-level/:code with a /connect/:code alias (9fddac33) — white-label marketplace apps may not mention HighLevel in page URLs.
- Menu link (per company):
code=go_high_level.secret_key; always the owner account. - Marketplace Custom Page (
95abe56b5, sidebar title "Next Level AI"): one URL shared by every install,/connect/sso. API-created custom-menu links never receiveREQUEST_USER_DATA, so codessoresolves the company from the decrypted SSO payload'sactiveLocation(go_high_level.location_id+app_version: 'v2') and stampscustom_page_aton first use. - Per-staff mapping (
631ae9cc2/fcd69bf9, blocks9c2496e11):GoHighLevelAuthViewpostsREQUEST_USER_DATAto the GHL parent (3 s timeout) and sends the encrypted payload assso; the 401 silent re-auth resends it (sessionStorage.ghl_sso) so the session stays on that user.lib/ghlSso.decodeUserDatadecrypts it (CryptoJS AES "Salted__", EVP_BytesToKey-MD5, AES-256-CBC) withGO_HIGH_LEVEL_V2_SSO_KEY(goHighLevel.sso_key, the app's Shared Secret — flux backend + schedular configmaps). With a non-emptyuser_map:- the opener's entry (matched on
userId, only whenactiveLocationmatches) isblocked→ 403ghl_user_blocked("Your account owner has turned off access for your LeadConnector user."); linked → that owner/member. - no entry → owner account only if the opener was identified and every entry is a block; otherwise 403
ghl_user_unmapped. So blocks alone restrict just the blocked users, any link restricts everyone unlisted, and an opener GHL didn't identify (no SSO) is always refused because a block can't be checked. - An empty map keeps owner-for-everyone. A linked member skips owner onboarding (first-login stamping as in
login()), and the user must be the owner or amemberunder them.
- the opener's entry (matched on
- Team access tab (owner only, LeadConnector settings):
GET/PUT /go-high-level/user-map(owner only; 400 when not connected / not v2 / unknown member).GETreturnsghl_users,users,user_map,sso_configured(false when the SSO key is unset — the UI then refuses to link, since mapping would block everyone) andrequires_v2.PUTstores links and blocks, dropping entries that are neither. The frontend (522664e6) renders a "LeadConnector user → Signs in as" list; the select's empty option reads Not linked (owner account) or Not linked (no access) depending on whether anyone is linked, plus No access (blocked).PUT /company/:idcan't writeuser_map.
Menu links
A GHL custom menu link needs an agency token, so it lives in a GHL agency's settings — the company's own (ghl_self_account) or the KK agency's. custom_menu_held_by records which token created it (_menuLinkHeldByCompany falls back to "has ghl_self_account or no agency_id" for older rows); add, remove, reconnect and uninstall all delete with that token, and a 404 from GHL just forgets the id.
POST/DELETE /go-high-level/menu-link(menuLink,66caacabc/3e5de15b9): aweb_ownermanages only a link in their own GHL agency (adding needs a connectedghl_self_account, else 400 "Connect your own LeadConnector agency account first"); a KK agency user passes?company_id=for a client it owns and manages only agency-held links. The wrong side gets a 403 naming the other. GHL failures → 502 "LeadConnector rejected the change".- Frontend: the Menu link tab (
menuLinkAdvice: "Not needed: the app page covers it…" on v2), and the agency portal'sGhlClientModal(below).
Custom Page sidebar name / visibility (b24200971)
The marketplace Custom Page title ("Next Level AI") is fixed per app version and agencies can't rename it. A Custom JS script (frontend/src/components/integrations/ghlSidebarScript.js, shown copyable by GhlSidebarScriptHelp.vue with the white-label API origin filled in) runs in LeadConnector, reads the location id from the URL, calls public GET /go-high-level/sidebar?location_id= (v2 installs only; {} for anything unknown; Cache-Control: public, max-age=300) and renames or hides the a.custom-link whose icon aria-label is "Next Level AI icon". A failed fetch retries after 60 s and shows the defaults meanwhile. label = go_high_level.sidebar_label → agency go_high_level_name → agency name, capped at 40 chars; hidden = sidebar_hidden. Set from the App page tab (go_high_level.sidebar_label, sidebar_hidden via the company update). Interim: an agency admin pastes the script into LeadConnector Settings → Company → White Label → Custom JS until the marketplace app version carrying it is approved (the app's Custom JS module takes the same copy, so script changes ship only with a new app version).
Form intercept
Handles standard GHL forms (V1), new V2 forms, white-label GHL domains (auto-detected via dynamic origin discovery), lc-form-submit postMessage events, and contact-id payloads embedded in form events — capturing email/phone/name to the identity graph regardless of how GHL processes the form server-side.
Outbound sync (Knock Knock → GHL)
CrmSyncQueueService (sync-contact, sync-ghl-messages) upserts the contact (find by email/phone via the advanced search API, then upsertContact/saveContact/updateContact). New contacts are stamped with source next-level-app. Visitor intelligence is written as a note (not custom fields, due to scope limits) via the Conversations/contacts notes API — syncContactIntel() posts intent score, pages viewed, last visit, and source, and applies tags: nox-identified, plus nox-intent-hot (score ≥ 50) or nox-intent-warm (≥ 25). ghl_contact_id is persisted on the PersonProfile.
Contacts are add-only (2026-10/11). Tags never ride on an upsert/update body any more — GHL replaces the whole list when they do, which wiped a tenant's own tags on an AI inbound call (23744b9f5); upsertContact/updateContact route them through addTags, GhlPostCallTagsService.syncTags only adds missing ones, GhlAdapter.setTags is gone, and the funnel stage swap is the only remover (test/ghl-tags-add-only.spec.js). A contact matched from an AI call or booking is never overwritten (906d9a2c1, whatever ghl_contact_update_policy says) — it only gets the call tag, note and conversation; empty fields are filled from the call (d3c5fecb4: AiCallContactExtractedController._fillExistingContact with lib/ghlContactFill rule transcript_ai, retried without the email when GHL refuses it as a duplicate) and the scheduling GhlAdapter writes the invitee's name onto a nameless matched contact. sendMessage marks the conversation unread for every caller (0590b533d, d31280514; SDK @gohighlevel/api-client ^3.1.1 with status: 'delivered'), and chats.ghl_conversation_id is in the schema now (373de1aee), so it persists.
Enrichment-guess links (2026-09-10, 40ad30396/c3bb4713b). Apollo-sourced syncs (apollo, lead_sync) reach GHL only, and a guessed link is flagged user_session.ghl_contact_from_enrichment. VisitorIdentityHelper.knowsVisitor (graph link, shadow match, or a stated name/email/phone — not first_name/last_name, where legacy Apollo lives) is the single "we know who this is" test: CrmSyncHelper drops an apollo sync for a known visitor (skipped_known_person), session create skips enrichment when PersonResolver.hasGraphCandidate (fp or IP candidate), and lib/enrichmentLink.releaseGuessedContact clears the link + crm_links row + cached ghl_context the moment a person is stamped or any first-party field lands in chat (name-only captures included). Guessed links get no transcripts or visit comments and never overwrite a stated link; the CRM contact itself is never touched. Backlog cleanup: POST /migrations/unlink-apollo-contacts (+ /admin/identity/maintenance/unlink-apollo-contacts, dry-run first) — pass 1 reads the ghl_appolo_sync trail, pass 2 scans sessions directly for the pre-2026-08-13 backlog (found_by says which rule caught it). Lead-source note (every company with GHL or HubSpot connected, no toggle — the crm_lead_source_note_enabled company flag + its UI toggle were added and removed the same day, 47014ee19): PersonResolverService._dispatchLeadSourceNote queues sync-lead-source-note on crm-sync (60 s delay so the contact sync links the contact first; jobId per session per 30-min window; 8 attempts, exponential from 60 s). CrmSyncHelper.syncLeadSourceNote writes a "Lead source — <date>" note (formatLeadSourceLines, app/lib/leadSource.js) and the gclid into a gclid contact custom field (resolve-or-create; unlike LinkedIn it overwrites — latest click wins). It never writes onto an enrichment-guess link (waits as if unlinked); done[] on the job prevents duplicate notes across retries. Chat-start-URL note: chat sync adds a "Web Chat — <time> / Chat started from: <url>" contact note (not a conversation message — an inbound message would fire InboundMessage and dismiss Agent K follow-ups) from the widget-reported widget_chat_starting_url, once per chat round (leadconnector_starting_url_note_id). The leadconnector_chat_start_url_enabled super-admin flag was removed 2026-09-25 (f1d39fb38) — it now runs for every GHL-connected company, as do the widget call/chat outcome tags.
Inbound enrichment (GHL → Knock Knock)
CrmEnrichmentQueueService refresh caches lifecycle/pipeline stage, opportunities (stage + value), tags, custom fields, and recent notes on PersonProfile.crm_enrichment (crm_enrichment.ghl), surfaced in the AI prompt. Refresh is event-driven; the cache is roughly hourly-fresh and force-refreshable by admins.
Calendar booking (embed)
With companies.go_high_level.booking_enabled + a calendar_id, the widget's "Book a meeting" CTA opens the GHL calendar embed. selectBookingCalendar() prefers the configured calendar_id, else the first bookable non-personal active calendar. The AI agent's booking goes through ms-ai's calendar router → backend POST /go-high-level/booking-available-dates and POST /go-high-level/book-calendar; GHL returns timezone-aware slot strings that are used as-is for booking. V2 calendars are supported via the new selection UI.
Multi-calendar (2026-07/08): go_high_level.multi_calendar_enabled + multi_calendar_ids expose a subset of calendars to visitors. Public GET /go-high-level/:company_id/booking-calendars lists them (and advertises default_calendar_id, always inside the visible subset); the widget shows a step-1 picker and passes calendar_booking_meta.calendar_id; ms-ai adds a calendar_id tool param only when >1 calendar is visible (one-time POST /elevenlabs/sync-calendar-tools on ms-ai re-syncs existing voice agents). GhlAdapter._visibleCalendars mirrors GoHighLevelController.bookingCalendars: a hidden calendar is reported like an unknown one (a stale tool argument can't book it), and a subset of one books that calendar with no picker even if the company default is hidden.
Calendar purposes (2026-09-30). multi_calendar_purposes holds admin-written "purpose of meeting" text per calendar (Booking tab, one input per offered calendar). Saved wholesale on each save: unknown ids, ids containing ./$ (they become Mongo keys) and blanks are dropped; HTML-stripped and capped at 300 chars since it's interpolated into prompts. A location change resets it. Calendars reach ms-ai as { id, name, description, purpose } (purpose separate so the widget picker keeps GHL's own description). ms-ai prompts (chat meetings.agent.ts + ElevenLabs) list Purpose:/Details: per calendar and tell the agent to ask what the meeting is about and match. Because prompts alone were skipped when the visitor gave date + email in one message, check_calendar_availability and book_meeting take a required meeting_purpose in multi-calendar mode; missingMeetingPurpose() (calendar.tool.ts) refuses an empty/generic one ("a meeting", "book a call") with "Not done yet… ask the user". "demo" is not generic, and any purpose containing a meaningful word of a calendar name (≥3 chars) is accepted (66eafa857).
Appointment description (09038d6ef, a6c00037e): Email:<email>\nName:…\nPhone:… — the Email: line used to print the GHL contact id. Name and phone fall back to the matched contact's own (lib/ghlContactFill.contactName, placeholders ignored; _resolveContact returns { id, name, phone }) before Unknown — voice callers often give no name and the chat book_meeting tool sends no phone. ms-ai phone-booking instructions now collect the caller's full name and send it as participant_name (6d5635287).
Email validated before booking (b43ca644d): GhlAdapter.book refuses an address failing ^[^\s@]+@[^\s@]+\.[^\s@]+$ with INVALID_REQUEST ("That email address doesn't look right. Ask the caller to spell their email again.") before it's written onto the contact — a voice agent once sent the GHL #<id> from the caller context.
Slot duration. GoHighLevelService.calendarDurationMinutes(calendar) reads slotDuration + slotDurationUnit (hours ×60; fallback 30). GHL rejects any other length ("Selected slot duration is not a valid duration option for this calendar"), so the hardcoded 30 broke every 45/60-minute calendar. Book, availability slot_minutes, and reschedule all use it, and the booked length is returned to ms-ai so the agent states it (meetingLengthRule covers ghl-calendar as well as Google, 33c4f8d3b); reschedule prefers the calendar's current duration, then the appointment's own span, then 30, and fetches the appointment once for both the assignee and the length.
Appointment times. GHL stores the wall-clock part of startTime/endTime and applies the location's timezone, ignoring the offset sent. GoHighLevelService.formatAppointmentTime(time, zone) always renders in that zone — a bare moment().format() rendered in the pod's zone and booked the wrong hour or got "slot no longer available". getLocationTimezone caches a failed lookup for 2 min (not the hour a resolved zone gets).
Booking failures (2026-09-29, extended 2026-10-21). A slot GHL lists as free but refuses (buffer, team member, per-day cap race) is BOOKING_REFUSED (422) — the agent hands over the booking link instead of retrying; a per-day cap hit on a taken slot carries day_full: true, which ms-comm turns into DAY_FULL_MESSAGE ("…that day is now fully booked. Please select another day…").
GhlAdapter.book: a SLOT_TAKEN refusal is first checked against the invitee's own appointments — a collision with their own meeting at that exact instant is returned as success withalready_booked: true(the lost-response retry: the appointment was created but the reply never reached ms-ai). A real conflict isSLOT_TAKENeven on slug calendars; other create failures keepNEEDS_LINK. SLOT_TAKEN details carryzone_used/start_sentand, when the calendar has a widget slug,booking_urlas a self-serve fallback.SchedulingServiceskips_notifyBookedon thealready_bookedpath — the booking row,new_bookingwebhook and meeting mirror already dedupe on the provider event id, the push didn't.- ms-ai
calendar-router.service.ts: SLOT_TAKEN reply includes the link (offer another time first); AUTH_EXPIRED / INVALID_REQUEST / MEETING_NOT_FOUND / PROVIDER_ERROR return agent-readable lines instead of an opaque 500 (expired connection = stop retrying, take details).signalOutboundBookingfires only on a "booked successfully" result. - ms-comm
GhlBookingMessageHelper.formatMeetingGHLMessage: the sentence "This time slot is no longer available…" is load-bearing (the widget matches it to reopen the calendar sheet) and is sent only for a genuine conflict (code === 'SLOT_TAKEN'or conflict wording), followed by a "Book Meeting" button whenbooking_urlis present; other failures get a generic line. The v2 slot reply echoes the calendar the service resolved, not the null one requested. - Chat logging:
app/helpers/ChatLogHelper.record()writes "GHL booking requested / created / failed / needs link" rows to the sharedlogscollection in ms-comm'schatLoggingshape (body.from_backend: true), so booking events read in one stream peruser_session_idwith the chat's own rows. Best-effort.
Token warm before booking fan-out: bookCalendar calls goHighLevel.getCompanyClient(company_id) once before its parallel GHL calls — GHL rotates single-use refresh tokens, so two parallel refreshes race and can persist a stale token, breaking all future GHL calls for the company. Contact resolution and calendar listing then run in parallel to fit ms-ai's 20s booking-tool budget.
POST /go-high-level/book-calendar back-fills the contact's phone (mirroring the email back-fill) — only when the CRM field is empty, never overwriting an existing value. Conversational-AI bookings (ms-ai book_meeting) arrive with only email + user_session_id, so phone/name fall back to the identity stamped on the user_session (phone_number/name, ignoring placeholder names like "Guest"). All calendar bookings (GHL/Calendly/Google/generic) now record through the shared BookingRecordService — see CRM & External Integration.
Post-call sync extras
- Recordings as playable Conversations messages —
GoHighLevelService.sendCallRecording()posts an inboundLive_Chatmessage with the recording URL as an attachment; GHL fetches, re-hosts, and renders an inline audio player. Needs onlyconversations/message.write. The play URL carries a deliberate.mp3suffix (/recordings/ai/<id>.mp3) so CRMs sniff it as audio instead of a generic document (AiCallGhlTranscriptSyncJob). - Per-agent summary field — outbound agents can set
post_call_summary_field;OutboundCallGhlSyncJobwrites the call summary into that GHL custom field. - Post-call outcome tags —
GhlPostCallTagsService(shared byOutboundCallGhlSyncJoband the inboundAiCallContactExtractedController) tags the contact peragent_key→post_call_tags: builtin outcomesno_answer/voicemail/booked/qualified(outbound) orbooked/qualified(inbound), plus custom rules. Writes are add-only (addTags), so a tenant's other tags are never touched.
Native webhook queue (2026-09-17)
Native marketplace webhooks (top-level type, no customData.company_id) are Ed25519-verified, replay-guarded (stale timestamp > 48h ignored; webhookId SET NX in Redis for 48h, fails open when Redis is down; the key is deleted again if processing throws so GHL's redelivery gets through), acked 200, and enqueued on GhlWebhookQueueService (global.ghlWebhooks): 8 BullMQ shards ghl-webhook-0…7, one job at a time per shard, contact-keyed so a contact's events stay ordered, ~6 jobs/s per shard. Dedupe on GHL's webhookId (completed jobs retained 1h), retries sleep inside the job (10/20/40/80 s) so the shard stays held, enqueue times out after 5 s so a down Redis 500s and GHL redelivers. AppointmentUpdate/Delete that beat their Create defer once (60 s); a replay is skipped if a newer event applied, but cancels always apply and are final. Only the schedular runs workers (local dev needs SERVICE_CRON=true); with no Redis, events run inline. Handler logic lives in GhlNativeEventHelper. Jobs visible in Bull Board at /admin/queues. Tenant lookup rides the go_high_level.location_id index (c981ea601; the 2026-09-17 ContactTagUpdate flood was collection-scanning companies). UNINSTALL clears every company on the location; one from the retired app's id clears only non-v2 connections.
Automation event mirroring
GHL workflow webhooks fire to the inbound route POST /go-high-level/webhook. Workflow/automation events (workflow_started, sms_sent, email_sent, tag_added, pipeline_stage_changed, …) are normalized into the ms-ai action vocabulary and forwarded to ms-ai, stored as knox_ghl_automation_event and surfaced through Nox's knox-automation-activity tool — useful for "did the automation actually fire on John's contact?". Pipeline-stage changes are also forwarded to ms-ai's stage event endpoint.
Nox action layer (draft → approve → send)
Nox can act in GHL: NoxGhlActionService drafts a follow-up (draftFollowup, status drafted), selects a channel (auto = SMS if a phone is known, else email), and on approval (approveAndSend) sends via GHL. It's honesty-gated — status flips to sent only when GHL returns a messageId/emailMessageId — and idempotent (deterministic hash key; retries never double-send). Autonomous send is off by default (company.knox.actions.autonomous_send). Sends are mirrored back to ms-ai as nox_write events. See Nox Assistant.
Configuration & options
| Action | Route |
|---|---|
| OAuth install callback | GET /ghlinstallation/install |
| Get install URL (tenant / agency) | POST /go-high-level/install-url, /install-url/agency |
| Uninstall (tenant / agency) | POST /go-high-level/uninstall, /uninstall/agency |
| List / select calendars | GET / PUT /go-high-level/calendars |
| Public booking calendars (widget) | GET /go-high-level/:company_id/booking-calendars |
| Contact profile | GET /go-high-level/contacts/:contact_id/profile |
| Booking availability / book | POST /go-high-level/booking-available-dates, /book-calendar |
| Inbound webhook | POST /go-high-level/webhook |
| GHL custom action (agents / outbound call) | POST /go-high-level/action/agents, /action/outbound-call |
| Iframe login (custom menu / Custom Page) | POST /login/go-high-level { code, sso } |
| Staff → account mapping (owner) | GET / PUT /go-high-level/user-map |
| Add / remove menu link (owner or agency) | POST / DELETE /go-high-level/menu-link (?company_id= for agency) |
| Sidebar name/visibility (public, Custom JS) | GET /go-high-level/sidebar?location_id= |
- Custom-field syncing requires explicit per-company mapping.
- Clearbit → GHL enrichment:
companies.clearbit_contact_ghl.enable = trueused to push Clearbit-enriched contacts to GHL — currently disabled globally:LeadContactSyncJob(the job pushing enrichment-guessed contacts into GHL/HubSpot) is commented out ofSchedulerService. - Permissions: team members granted
settings.integrationscan manage all integrations (was owner-only 403s) —GeneralHelpercheck. - Agency / white-label: agencies can configure GHL globally and reuse the connection with per-tenant overrides; white-label GHL domains (e.g.
crm.youragency.com) are recognized by form intercept and the OAuth callback.
Behaviors & edge cases
- Workflow-webhook location pinning: signed-only workflow webhooks must come from the company's own location, but the check is observe-only (
location_mismatchlogged) untilGHL_WEBHOOK_ENFORCE_LOCATION=true— a tenant's custom body may omit the location. Custom actions (/go-high-level/action/*) accept unsigned calls unlessGHL_ACTION_REQUIRE_SIGNATURE=true. - Token refresh is serialised (Redis lock + in-process single-flight,
_lockedRefresh); the unused manual refresh endpoint was removed. GHL responses never include raw SDK/axios errors or_debugoutput. - Recording links posted to GHL use ms-comm's vendor-neutral
/recordings/{ai,call,agent}/…aliases (072ff5a40);AiCallGhlTranscriptSyncJobnow callslib/callRecordingUrlinstead of its byte-identical copy. The vendor-named routes stay live so old links keep playing. - Inbound webhook verification: primary is Ed25519 over the raw request body (
X-GHL-Signatureheader, verified againstgoHighLevel.webhook_public_keyPEM SPKI); a legacy fallback comparescustomData.secret_keyto the storedsecret_key(deprecated). Verification requires the raw body — re-stringified JSON won't match. - Rate limiting / resilience:
ghlResilience.jsenforces a per-location sliding window (~90 req/10s, under GHL's ~100/10s), retries 429/5xx with exponential backoff + jitter (honoringRetry-After), caches custom-field/calendar/pipeline IDs (1h TTL), and uses a Redis-backed idempotency store (24h) to dedupe sends/bookings. - Cron sweepers:
OutboundCallGhlSyncJob(1 min) andAiCallGhlTranscriptSyncJob(5 min) post call transcripts as notes;KnoxGhlSyncJob(nightly 03:00) does pipeline-stage sync + new-visitor backfill;CrmVisitActivityJob(15 min, renamed fromGhlVisitActivityJobwhen HubSpot joined) posts each finished visit as a GHL internal comment whengo_high_level.log_visit_activityis on (enrichment-guess links skipped; per-session backoff 30m→4h, then given up). - Stage queries currently rely on a manual
pipeline_stage_breakdownaggregation; full deal-flow joins are roadmapped (see capabilities status). - Dormant-contact search must filter on
dateUpdated— other field names 422 (probed + cached in prod,GoHighLevelService). - DND is per-channel —
dndSettings.Email/dndSettings.SMSblock just that channel; check the channel, not only the globaldndflag (NoxGhlActionService._channelDnd). - Disconnect now fully uninstalls the app GHL-side:
uninstallApp()removes both the sub-account (location) and company-level (ghl_self_account) installs viamarketplace.uninstallApplication;uninstallAgencyApp()removes the agency-level install, and agency uninstall iterates sub-accounts. Failures are logged, never swallowed. Historical GHL data stays; cached enrichment IDs remain but stop refreshing. GhlTipsEmailJobis stopped (commented out ofSchedulerService) — no more weekday GHL tips emails.
Plan & limits
- Available on all plans (verify exact tier gating).
- High-volume tenants may see sync lag under GHL rate limits — the queue backs off gracefully rather than dropping work.
Technical implementation
- Owning services:
backend—app/services/GoHighLevelService.js(~61 KB),NoxGhlActionService.js,IdentityGhlReconcileService.js; routesapp/routes/goHighLevelRoutes.js; webhook verifyapp/lib/ghlWebhookVerify.js; resilienceapp/lib/ghlResilience.js. Automation/stage mirroring + Nox tools inms-ai. - Sync queues:
CrmSyncQueueService.js(crm-sync),CrmEnrichmentQueueService.js(crm-enrichment). - Subsystem: CRM & External Integration · Identity Graph · Nox Assistant.
What Nox can tell you
- Connection state and pipeline structure (
knox-crm(query=pipelines)). - Hot leads silent (in pipeline but not visited) —
knox-crm(query=hot_leads_silent). - Identified visitors on site right now —
knox-crm(query=presence_identified). - A contact's full session history —
knox-crm(query=contact_sessions, contact_id). - Automation events for a contact —
knox-automation-activity.
Tools: knox-crm, knox-automation-activity, knox-action-feed.