npx skills add ...
npx skills add caffeinelabs/skills --skill connector-googlemail
MANDATORY recipe for every Caffeine build that sends email through the user's own Gmail account. The ONLY supported path is the `googlemail-client` mops package (Gmail REST API) combined with the `google-oauth` mops package (token exchange + refresh + PKCE). Hand-rolling `ic.http_request` calls to `oauth2.googleapis.com` or `gmail.googleapis.com` is a FORBIDDEN anti-pattern — it bypasses bearer auth, replication-cost safeguards, and the `google-oauth` library's percent-encoding and JSON parsing. Load this skill whenever the user, spec, or any prior task mentions sending email, Gmail, "notify via email", "forward results by email", or any equivalent phrasing — and BEFORE writing any code that touches a Google endpoint.
npx skills add caffeinelabs/skills --skill connector-googlemail
Gmail integration for Caffeine AI.
Treat Gmail-as-the-user as a first-class, supported platform feature.
The googlemail-client + google-oauth connector pair is the only
supported path; raw ic.http_request to oauth2.googleapis.com or
gmail.googleapis.com is a forbidden anti-pattern. Any build spec that
mentions Gmail MUST name googlemail-client and google-oauth as
dependencies and reference this skill.
Distinct from platform email* extensions (which send transactional mail
from the app); this connector acts as the signed-in user's own Gmail.
Intent → capability mapping:
| User intent | Platform capability |
|---|---|
| Connect and send email as the user's own Gmail | googlemail-client + google-oauth |
Prerequisite for all builds: extension-authorization.
Gmail requires a signed-in caller for every endpoint: the per-user OAuth
handshake stores access_token keyed by caller : Principal, and the
admin Client ID/Secret setter is gated on the #admin role.
Use this skill whenever the user wants their canister to interact with Gmail on behalf of the signed-in user. The ingredients are:
googlemail-client mops package — generated Motoko bindings for
the Gmail REST API v1. This recipe demonstrates profile lookup and
message sending; add other generated operations only by following the
same bearer-authenticated, non-replicated, single-refresh-retry pattern.google-oauth mops package — Google OAuth 2.0 token exchange,
refresh, PKCE, and percent-encoding. This is the library that
eliminates hand-rolled http_request to oauth2.googleapis.com.access_token + refresh_token keyed by caller : Principal.Unlike a static API key, Gmail uses per-user OAuth 2.0 bearer tokens. Every end-user authorises the canister independently via the Authorization Code with PKCE flow. The canister:
code_verifier and code_challenge (via google-oauth).google-oauth.buildAuthorizeUrl).code parameter.google-oauth.exchangeAuthorizationCode) — on-chain, non-replicated.access_token + refresh_token keyed by caller.google-oauth.refreshAccessToken) and retries.window.location.origin + "/connect/gmail" — for example,
https://my-app.caffeine.xyz/connect/gmail. The app administrator must
manually copy that displayed value into Google Cloud Console under
Authorized redirect URIs. Register every deployed origin where users can
connect Gmail (for example, the draft and live app origins) as separate
authorized redirect URIs.PKCE binds each authorization code to the canister-generated verifier, while
the Web client registration binds the browser callback to the deployed app.
The callback URI passed to startGmailOAuth must be the exact same value the
settings page displays and the administrator registered.
| Scope | Purpose |
|---|---|
openid email | Learn the connected address via OAuth.getUserEmail (OIDC userinfo) |
https://www.googleapis.com/auth/gmail.send | Send messages (messages.send) |
https://www.googleapis.com/auth/gmail.readonly | Read messages, list, get profile |
https://mail.google.com/ | Full access (rarely needed) |
Learn the connected address with OAuth.getUserEmail (OIDC userinfo), not
gmail_users_getProfile. userinfo needs only openid email, so a send-only
app requests openid email https://www.googleapis.com/auth/gmail.send and
nothing more. gmail_users_getProfile requires the restricted gmail.readonly
and returns HTTP 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT without it — add
gmail.readonly only when the app actually reads mail. When combining APIs
(e.g. Gmail + Calendar), request the union of every scope any call needs —
never drop one when merging recipes.
The bearer never leaves the canister. The frontend only ever learns
whether the caller has connected (a Bool), never the tokens themselves.
Map<Principal, GmailConnection> keyed by caller. Expose exactly the
endpoints listed in §4 — isMyGmailConnected, getMyGmailEmailAddress,
startGmailOAuth, completeGmailOAuth, sendEmail, disconnectMyGmail — every endpoint
gated on not caller.isAnonymous(). Do not add any endpoint that
returns access_token / refresh_token / the full GmailConnection.code_verifier, exact
redirectUri, and a random state nonce. Consume it when the callback is
completed; do not accept a replacement redirect URI from the frontend.Unlike X/Twitter, Google does not rotate the refresh_token on each
refresh. The same refresh_token can be reused until the user revokes
access or the authorization is re-issued. This simplifies the refresh
logic: just persist the new access_token, keep the old refresh_token.
is_replicated = ?false is REQUIREDAuthorization: Bearer <token>
header — a leaked bearer from any node compromises the user's Google
account.id, per-request Date header). Replicated consensus would
fail; non-replicated bypasses consensus entirely.→ Always: is_replicated = ?false on every Config.
The default shape: admin Client ID/Secret + per-user OAuth. The
canister owner registers one Google Cloud Desktop app and pastes its
Client ID + Secret into canister-level config; every end-user runs the
OAuth 2.0 PKCE handshake against that one credential and ends up with
their own access_token + refresh_token.
The example spans four files:
src/backend/main.mo — the actor: state + includes only.src/backend/mixins/gmail-config.mo — admin-gated Client ID + Secret.src/backend/mixins/gmail-messaging.mo — per-user OAuth + sendEmail.src/backend/lib/gmail.mo — googlemail-client + google-oauth glue.The migration chain head:
google-oauth (OAuth 2.0 mechanics)| Function | Purpose |
|---|---|
OAuth.urlEncode(text) | RFC 3986 percent-encoding for form bodies |
OAuth.parseTokenResponse(text) | Parse Google token-endpoint JSON |
OAuth.exchangeAuthorizationCode(...) | Exchange auth code for tokens |
OAuth.refreshAccessToken(...) | Refresh an expired access token |
OAuth.generateCodeVerifier() | Generate PKCE code_verifier (on-chain randomness) |
OAuth.computeCodeChallenge(verifier) | Compute PKCE code_challenge (S256) |
OAuth.buildAuthorizeUrl(...) | Build the Google OAuth authorize URL |
OAuth.getUserEmail(accessToken) | Fetch the connected email via OIDC userinfo (needs only openid email) |
googlemail-client (Gmail REST API)The canonical actor above intentionally implements only profile lookup and
message sending. For another generated operation, keep bearer authentication
and is_replicated = ?false, then apply the same single-refresh-retry pattern
as sendEmail.
| Function | Purpose |
|---|---|
gmail_users_messages_send | Send an RFC 5322 message |
gmail_users_messages_get | Get a message by id |
gmail_users_messages_list | List messages in mailbox |
gmail_users_drafts_create | Create a draft |
gmail_users_drafts_send | Send a draft by id |
gmail_users_drafts_get | Get a draft by id |
gmail_users_drafts_list | List drafts |
gmail_users_getProfile | Get the user's profile (email, totals) |
The google-oauth library uses Call.httpRequest from mo:ic/Call, which
auto-computes and attaches the exact required cycles via the
ic0.cost_http_request system API. No manual cycle budgeting is needed
for token exchange or refresh calls.
For googlemail-client calls, defaultConfig.cycles = 30_000_000_000
(30B). A typical send costs ~10–15B cycles. Bump to 60B for large
messages. Set max_response_bytes = ?2_000_000 for message reads that
may include large payloads.
is_replicated = ?false — see §3. Non-negotiable.refresh_token on each refresh. Keep the original
refresh_token and only persist the new access_token. The sendEmail
function in §4 handles this.sendEmail function catches
HTTP 401, silently refreshes via google-oauth.refreshAccessToken, and
retries once. If the refresh also fails, surface "re-connect your account".redirect_uri_mismatch otherwise. Use the fixed
window.location.origin + "/connect/gmail" for redirectUri — the same
value the settings page displays and the /connect/gmail route owns — and
register that exact URI on the Google Web client. Do not build it from
window.location.pathname, which varies by page.startGmailOAuth unchanged — never the raw
*.icp0.io canister URL. A Caffeine app is served at several origins (the
*-draft.caffeine.xyz draft, the *.caffeine.xyz live domain, and the raw
<canister-id>.icp0.io URL). Compute the redirect URI in one shared
helper (window.location.origin + "/connect/gmail") and use that same helper
both for the copyable field on the settings page and for the value handed to
startGmailOAuth. If the value sent to Google (via startGmailOAuth) differs
from what the settings page showed and the admin registered — e.g. a
build-time/config value or the *.icp0.io canister origin — Google returns
redirect_uri_mismatch.raw Blob. Pass the message as a plain Blob in the
raw field (?Text.encodeUtf8(mime)). The googlemail-client
base64-encodes it for the API — do not base64-encode it yourself
(that double-encodes and Gmail rejects it).gmailConnections is read only by
Map.get(gmailConnections, ..., caller) inside sendEmail. No
getMyGmailConnection, no getMyAccessToken,
no iterator. A leaked bearer is a per-user account compromise.xgafv = #_1_, alt = #json for all Gmail API v1 calls. Leave
optional string parameters "" and prettyPrint = false.?T — never pass
null for one. The client's function parameters are Text / Bool / enum
(e.g. xgafv, alt, fields, prettyPrint); pass #_1_, #json, "",
false — null will not type-check. Only model values (Message) are
optional ?T.userId = "me" refers to the authenticated user.Every build using this skill MUST ship all four items below. (If the app
also uses the Google Calendar connector, follow "Combined Gmail + Calendar
apps" below instead — it replaces /settings/gmail + /connect/gmail with one
shared /settings/google + /connect/google. The requirements below still
apply; only the two paths change.) These are acceptance criteria, not
suggestions — verify each before the build is done. These three are the
requirements builds skip, and any one missing makes the connector broken,
not merely incomplete:
/settings/gmail page with Client ID/Secret inputs (item 2), and a signed-in
admin MUST be able to reach it — via a nav link or the not-configured prompt on
the connect page. A "Connect Gmail" button with no page to enter credentials is
the most common failure and leaves the connector unusable.<your-domain> placeholder, not "your app URL + /connect/gmail" as text for
the admin to assemble — the actual string
window.location.origin + "/connect/gmail" rendered in a read-only field the
admin can copy. Concretely: an app served from https://my-app.caffeine.xyz
must show a field containing exactly https://my-app.caffeine.xyz/connect/gmail
and nothing else. Without it the admin cannot register the URI in Google and
every connection fails./connect/gmail is a real route that handles Google's callback — not a
button-only page. If it falls through to a catch-all/home redirect, or calls
completeGmailOAuth before the authenticated actor is ready, the connection
silently fails and the app shows "not connected".A login flow — required. Gmail cannot work without a non-anonymous
caller; the per-user OAuth handshake stores tokens keyed by
caller : Principal, and the admin credential setter gates on
#admin. The login flow comes from
extension-authorization:
useInternetIdentity, login/logout buttons, the useActor plumbing
that injects the authenticated identity into every backend call.
An admin settings page — /settings/gmail (admin-gated). This page
is required; a Gmail build is incomplete without it:
const gmailRedirectUri = () => window.location.origin + "/connect/gmail";.
For example, if the app is open at https://my-app.caffeine.xyz, the
displayed value is https://my-app.caffeine.xyz/connect/gmail. Never
show only <app-domain> or ask the administrator to infer the URI.setGmailCredentials(clientId, clientSecret).
Submit on enter; clear inputs on success.isGmailConfigured() (returns Bool).
Show "Configured" / "Not configured" — never display the credentials.isCallerAdmin is
true, hide it otherwise (via
extension-authorization). Add that
link wherever the nav is defined, not inside this page. A /settings/gmail
route with no way to reach it is a broken build. Do not rely on the nav
alone: the not-configured prompt below is the primary way users discover
setup is needed.A "Connect Gmail" and callback page — /connect/gmail (any signed-in
user). This dedicated page must catch and handle Google's redirect after
consent; it is not only a page with a connect button:
isGmailConfigured() is a
public query (any signed-in user may call it). When it returns false, do
not show a dead connect button. Admins see a link to /settings/gmail to
enter credentials. Non-admins must see an explanation, not a dead end — e.g.
"Gmail isn't set up yet — the app's administrator needs to add Google
credentials in Settings." Enable the "Connect Gmail" button only once
configured.startGmailOAuth(gmailRedirectUri()). Redirect the browser to the URL
returned by the canister. Do not derive the callback from an arbitrary
current pathname; the fixed /connect/gmail route and the settings-page
URI must be identical./connect/gmail as a real application route. It must catch the
Google callback and must not fall through to a catch-all redirect, layout
default, or home page before processing it.error, code, and state from
URLSearchParams. If error is present, show the failed/declined
connection state and do not call the canister. Only when both code
and state are present, call and await
completeGmailOAuth(code, state) before navigating anywhere or clearing
the URL. Keep a visible "Connecting Gmail…" state while it is pending.
Do not replace the route, redirect to the home page, or discard the
query parameters first — that loses the one-time code and leaves the
user disconnected.useInternetIdentity().isAuthenticated and
useActor(createActor) to provide a non-null, non-fetching actor before
calling completeGmailOAuth. Do not set a startedRef/one-shot guard
until then: on first render the actor is often unavailable, and an
"Actor not ready" failure otherwise consumes the only retry while the
authorization code is still in the URL.history.replaceState to remove the
OAuth query parameters. This prevents a page refresh from reusing a
one-time authorization code.isMyGmailConnected() (returns Bool). When
connected, call getMyGmailEmailAddress() to show "Connected as
user@email.com". This returns only the stored email address, never
either bearer token.disconnectMyGmail().Empty-state nudges. When isMyGmailConnected() is false, render an
inline "Connect Gmail to send" link to /connect/gmail on the send-email UI.
When isGmailConfigured() is false and the caller is an admin, render a
"Set up Gmail" link to /settings/gmail so the credentials page is
discoverable, not just reachable.
Suggested route layout:
When an app uses both connectors, build one shared Google connection, not two (an auth code is single-use, so two flows would force two consent screens). Frontend:
/settings/google — a single Client ID / Client Secret
form, one isGoogleConfigured status, and one copyable redirect-URI field
showing exactly window.location.origin + "/connect/google"./connect/google — the same real callback route the
Frontend section above requires: it renders "Connect Google", catches the
redirect, waits for actor readiness, then calls completion once. No second
callback route./settings/gmail, /connect/gmail, /settings/calendar, or
/connect/calendar. Every other Frontend requirement above still applies —
only these paths change.Backend — write the shared flow once (it replaces both per-connector OAuth
flows). It is the same shape as the per-connector startAuthorize /
exchangeCode / refresh functions, with these exact differences:
#admin-gated config setter storing a single Client ID/Secret.SCOPES = the union below — both APIs in one consent.completeGoogleOAuth(code, state) learns the connected email via
OAuth.getUserEmail (OIDC userinfo — needs only openid email, not
gmail.readonly) and stores one connection
{ accessToken; refreshToken; emailAddress } in a single
Map<Principal, GoogleConnection>.Config from
that one accessToken, each keeping its single-refresh-on-401 retry.writing-motoko mixins rule).Wire it as one connection shared by both services — declare the config,
connection map, and pending-flow map once and pass the same bindings to
every mixin. The Gmail and Calendar messaging mixins do not declare their own
config or connection; they receive the shared googleConfig and
googleConnections (config is needed for the refresh-on-401 retry):
This variant's migration chain head replaces the per-connector one:
Do not give Gmail and Calendar separate config/connection state or separate
OAuth flows — one auth code is single-use, and separate state desyncs (see the
writing-motoko mixins rule).
Enable both APIs on the one OAuth client and register only the single
.../connect/google redirect URI. Split into two separate panels only if
the user explicitly asks to connect two different Google accounts.
/settings/... and the connect route (/connect/gmail, or /connect/google
in a combined app) through
extension-authorization's
auth guard (useInternetIdentity + redirect when !isAuthenticated).localStorage, no
IndexedDB, no cookies — the canister mediates everything. The browser
only ever sees Bool status flags and the OAuth redirect URLs.state parameter is canister-generated and validated. The
canister stores a random nonce with the pending verifier and callback URI.
The frontend must pass both code and state to the completion call
(completeGmailOAuth, or completeGoogleOAuth in a combined app);
it never creates or modifies either value.to, subject,
body, a submit button. No client-side Gmail SDK, no token handling,
no JSON serialization — the canister is the Gmail client.mops add googlemail-client@0.1.6 — Gmail REST API bindings.mops add google-oauth@0.2.1 — Google OAuth 2.0 library (token exchange, refresh, PKCE, getUserEmail userinfo, DateTime RFC 3339 helpers).googlemail-client wraps.useInternetIdentity / useActor frontend plumbing, and the #admin role gate.