Solo CRM

Google integration

Connect a Google account so Calendar events become meetings and Gmail syncs a contact timeline and provides a private inbox with reading and sending.

Connects a Google account to a workspace and syncs Calendar events into meetings and Gmail metadata into an email timeline, with a private Inbox for reading conversations, downloading attachments, composing and replying.

Sections 1 and 2 are done once, by you, in the Google Cloud Console. The resulting OAuth client is then pasted into Settings → Integrations, per workspace — it is not an environment variable.


1. What to enable in the Cloud Console

Create the project

  1. Go to https://console.cloud.google.com/ and create a project (or pick one).
  2. Note the project name — you will select it in every step below.

Enable the APIs

APIs & Services → Library, then enable each of:

APINeeded forSkip if
Google Calendar APISyncing events into meetingsYou only want email
Gmail APIThe email timelineYou only want calendar
Google People APIReading the linked account's name and emailNever — always enable

The People API backs the userinfo call that identifies which Google account was linked. Without it the callback cannot tell one account from another and the connection fails.

APIs & Services → OAuth consent screen

  • User type: Internal if everyone using this CRM is in your Google Workspace organisation. Choose it if you can — it skips Google's verification entirely. Otherwise External.

  • App name, support email, developer contact — required.

  • Authorised domains — the domain serving the app.

  • Scopes — add:

    https://www.googleapis.com/auth/userinfo.email
    https://www.googleapis.com/auth/userinfo.profile
    https://www.googleapis.com/auth/calendar.events
    https://www.googleapis.com/auth/gmail.readonly     ← only if you want email
    https://www.googleapis.com/auth/gmail.send         ← composing and replying
  • Test users — while the app is in Testing, only addresses listed here can connect. Add your own.

Create the OAuth client

APIs & Services → Credentials → Create credentials → OAuth client ID

  • Application type: Web application

  • Authorised redirect URIs — add one per environment, exactly:

    http://localhost:3000/api/integrations/google/callback
    http://crm.local:9031/api/integrations/google/callback
    https://your-production-host/api/integrations/google/callback

    These must match character for character, including the scheme and port. A mismatch produces redirect_uri_mismatch and nothing else.

Copy the Client ID and Client secret.


2. Read this before enabling Gmail

gmail.readonly is a restricted scope. For an External app, Google requires a security assessment (an annual third-party audit, with real cost and weeks of lead time) before it can be verified. Until verification, an External app is capped at 100 users and shows an "unverified app" warning.

Internal apps are exempt. If your users are all in one Google Workspace organisation, set the consent screen to Internal and this does not apply.

Calendar (calendar.events) is a sensitive, not restricted, scope — it needs verification for External apps but no security assessment.

If Gmail is not worth that, connect calendar only: the app requests Gmail scopes only when you tick the box, and every Gmail feature degrades to absent rather than broken.


3. Where the credentials go

In Settings → Integrations, not in the environment. Open the workspace, choose Integrations, and fill in the Google OAuth client section:

FieldValue
Client ID...apps.googleusercontent.com
Client secretfrom the same Cloud Console credential — stored encrypted, never sent back to the browser
Redirect base URLthe origin Google redirects back to: the redirect URI above, minus /api/integrations/google/callback. Leave empty to use BETTER_AUTH_URL.

Save takes effect immediately — no restart, and no rebuild of the image.

An OAuth client is a single application to Google: one consent screen, one quota, one publishing status, one set of test users. A server-wide client would therefore put every workspace's calendar and mailbox behind credentials no individual tenant could rotate or revoke, and a quota exhausted by one workspace would stop the others. That is why these are per workspace.

The environment still owns one Google-related value, because it protects the tokens rather than being one:

# Optional. Encrypts stored OAuth tokens at rest; falls back to
# BETTER_AUTH_SECRET. Any length — it is hashed to 32 bytes.
GOOGLE_TOKEN_ENCRYPTION_KEY=

It is not PB_-prefixed, so it never reaches the browser. See src/lib/public-env.ts.

Migrating an existing deployment

Installs that predate this read GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and GOOGLE_REDIRECT_BASE_URL from the environment. Nothing reads them now, so copy them into each workspace's settings once:

npx tsx db/seed-google-settings.ts --check   # report, change nothing
npx tsx db/seed-google-settings.ts           # write

It is idempotent, skips any workspace that already has a client id, and does nothing at all when the two variables are unset. Connected accounts survive the move — their stored grants are untouched — but until the client is present in settings, no token can be refreshed, so run it before or just after deploying. Afterwards the three variables can be deleted.


4. Connecting an account

  1. Open Settings in the workspace.
  2. Under Integrations, choose Connect Google (tick Include Gmail to request mailbox access).
  3. Approve the consent screen. You are returned to Settings.
  4. Press Sync now to pull immediately, rather than waiting for the worker.

Requires the workspace:manage permission — owners only, at present.


5. How the sync behaves

Calendar → meetings. One-way. Events from the primary calendar become meetings, matched on the Google event id so a re-sync updates rather than duplicates. Cancelling in Google deletes the meeting here. The first run pulls 30 days; every run after is incremental via Google's syncToken. If that token expires (410), it falls back to a full window automatically.

Gmail → email timeline. Headers and Google's own snippet only — never the message body. Messages are linked to a contact by matching the counterparty address, and to that contact's primary company. A message from someone not yet in the CRM is still stored, and becomes linked as soon as they are added and the next sync runs.

What triggers a sync

  • Sync now in Settings.
  • The calendar-sync-queue BullMQ worker (npx tsx workers/index.ts), which needs REDIS_URL.
  • A Google push notification, if the app is on public HTTPS.

Push notifications need public HTTPS. Google will not deliver to http:// or to a host it cannot reach, so watchCalendar is a deliberate no-op on a local or plain-HTTP deployment and sync falls back to polling. That is why the current :9031 deployment will not receive webhooks.


6. When it does not work

SymptomCause
redirect_uri_mismatchThe URI in the console differs from the request. Check scheme, host, port, path — and the workspace's Redirect base URL, which overrides BETTER_AUTH_URL when set.
"Google is not configured for this workspace"The client ID or secret is missing from Settings → Integrations for that workspace. Each configures its own; a second workspace does not inherit the first's.
access_deniedThe account is not in Test users while the app is in Testing.
Connects, then stops after ~an hourGoogle returned no refresh token. Revoke access at https://myaccount.google.com/permissions and reconnect — the app always asks with prompt=consent, which forces a new one.
"no usable token — reconnect it"GOOGLE_TOKEN_ENCRYPTION_KEY (or BETTER_AUTH_SECRET) changed after the tokens were stored, so they can no longer be decrypted. Reconnect.
Calendar syncs, Gmail does notThe account granted only calendar scopes. Reconnect with Include Gmail ticked.
Webhook never firesExpected on plain HTTP — see above. Polling still works.

7. Security notes

  • Tokens are encrypted at rest (AES-256-GCM) in connected_accounts. A database dump alone does not yield a usable Google grant.
  • So is the client secret, in organization_settings, under the same CREDENTIALS_ENCRYPTION_KEY. It is never sent back to the browser — the settings page shows that it is stored, not what it is.
  • The credentials are read after the membership join, not before, in both OAuth routes: reading a workspace's OAuth client is itself something only a member with workspace:manage may do.
  • The callback is CSRF-protected. A nonce is stored in an httpOnly cookie when the flow starts and must match the one in state, so a callback URL cannot be handed to a signed-in user to attach someone else's Google account to their workspace.
  • The org slug in the OAuth flow is untrusted — membership is re-proved on the callback, as everywhere else.
  • Disconnecting deletes the stored tokens but does not revoke the grant at Google. To fully revoke, use https://myaccount.google.com/permissions.

Gmail inbox

Open Inbox in the workspace sidebar. Connect Gmail there, or select Gmail · read and send when connecting through Settings → Integrations. Existing read-only connections must reconnect once to grant sending access; calendar-only connections keep working without Gmail permissions.

The inbox lists only accounts connected by the signed-in user. Full message bodies and attachments are fetched from Gmail when opened, rather than copied into the CRM database. The existing contact timeline still shares synced headers and snippets within the workspace. HTML messages render in an isolated reader with scripts, forms and remote tracking images blocked.

Inbox, Sent and All mail support Gmail search and pagination. Compose and reply support rich text, To/CC/BCC and Gmail threading. Attachments on received mail can be downloaded. Outgoing messages accept up to ten files, at most 10 MB total. Opening a message does not change its read/unread state in Gmail: the requested scopes are read-only plus sending, without permission to modify the mailbox.

The first metadata sync starts after connection. Sync now runs it on demand. With Gmail push configured, authenticated webhooks trigger incremental sync and private WebSocket refreshes of the connected user’s inbox. Watches renew daily; a six-hour reconciliation checks for dropped notifications. Until push delivery has actually been verified, the existing 15-minute fallback stays enabled (GOOGLE_SYNC_MINUTES controls that fallback and Calendar maintenance). Returning to the inbox also refreshes its live Gmail view. History pagination, expired cursors, duplicate notifications and overlapping syncs are handled without advancing past changes that have not been processed.

Send requests carry an idempotency key. If Gmail's response is lost or times out, the CRM reports uncertain delivery and does not resend automatically. Check Gmail Sent before composing another copy. OAuth tokens remain encrypted using the existing application secret. Tests mock Gmail; no real messages are sent by the verification suite.

Gmail push notifications

Gmail publishes mailbox-change notifications through Google Cloud Pub/Sub. The notification contains an address and history ID, not the message body. The CRM uses the saved history cursor to fetch changes, acknowledges only after durable queueing, and verifies the Google-signed identity, exact audience and subscription. Failed delivery is retried by Pub/Sub; duplicate jobs are idempotent.

  1. Use the same Google Cloud project as the workspace’s Google OAuth client. A topic in another project cannot be used, even if it is otherwise accessible.

  2. Authenticate gcloud with an account that can configure that project.

  3. Copy Gmail push endpoint from Settings → Integrations and run:

    scripts/google/setup-gmail-push.sh PROJECT_ID PROJECT_NUMBER HTTPS_WEBHOOK_URL WORKSPACE_UUID

    The script verifies the project number before changing resources. It creates the shared solo-crm-gmail topic, grants Gmail publishing rights, creates a push authentication service account, and creates/updates an authenticated subscription for this workspace. Multiple workspaces in the same project reuse the topic, with separate subscriptions and audiences.

  4. Save the three printed values in Settings → Integrations: Gmail Pub/Sub topic, Gmail push subscription, and Push authentication service account.

  5. Press Sync now in Inbox. The CRM registers its watch. The initial signed notification confirms push delivery; Inbox then shows Push enabled.

No service account private key is uploaded to the CRM. Watch registration never replaces the stored sync cursor, and watch failures do not disable the fallback. Renewal also produces a notification, allowing the app to detect failed delivery. Disconnecting the last linked mailbox stops its watch when possible; if Google is unreachable, the remote watch expires and notifications for deleted accounts are ignored. A shared watch is retained for other connected workspaces.

Google references: Gmail push notifications and authenticated Pub/Sub delivery.

On this page