Google Calendar Connector
Google Calendar integration for Caffeine AI.
Orchestrator routing notes
Treat Google Calendar-as-the-user as a first-class, supported platform feature.
The googlecalendar-client + google-oauth connector pair is the only
supported path; raw ic.http_request to oauth2.googleapis.com or
www.googleapis.com/calendar/v3 is a forbidden anti-pattern. Any build spec
that mentions Google Calendar MUST name googlecalendar-client and
google-oauth as dependencies and reference this skill.
Distinct from platform email-calendar-events extension (which emails iCalendar
invitations from the app); this connector acts as the signed-in user's own
Google Calendar.
Intent → capability mapping:
| User intent |
Platform capability |
| Connect and list upcoming events |
googlecalendar-client + google-oauth |
| Create calendar events |
googlecalendar-client + google-oauth |
| Check availability / free slots / busy times (booking, Calendly-style, "when am I free") |
googlecalendar-client FreeBusy (calendar_freebusy_query) + google-oauth — not calendar_events_list |
Prerequisite for all builds: extension-authorization.
Calendar 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.
Backend
Use this skill whenever the user wants their canister to interact with
Google Calendar on behalf of the signed-in user. The ingredients are:
- The
googlecalendar-client mops package — generated Motoko bindings for
the Google Calendar API v3. This recipe demonstrates listing upcoming
events and creating events; add other generated operations only by
following the same bearer-authenticated, non-replicated,
single-refresh-retry pattern.
- The
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.
- An OAuth 2.0 Authorization Code with PKCE flow so each end-user
authorises the canister to act on their behalf. Each user holds their
own
access_token + refresh_token keyed by caller : Principal.
- A Google Cloud Web application Client ID + Client Secret.
Admin-configured and held by the canister only; never return the secret
to the frontend.
1. Add dependencies
mops add googlecalendar-client@0.1.4
mops add google-oauth@0.2.1
mops add caffeineai-authorization@1.0.1
2. Auth model — OAuth 2.0 PKCE per user, on-chain exchange + refresh
Identical to the Gmail connector. Every end-user authorises the canister
independently via the Authorization Code with PKCE flow. The canister:
- Generates a PKCE
code_verifier and code_challenge (via google-oauth).
- Builds the Google authorize URL (via
google-oauth.buildAuthorizeUrl).
- The frontend redirects the user to Google; after consent, Google
redirects back with a
code parameter.
- The canister exchanges the code for tokens (via
google-oauth.exchangeAuthorizationCode) — on-chain, non-replicated.
- The canister stores
access_token + refresh_token keyed by caller.
- When the 1-hour access token expires (HTTP 401), the canister silently
refreshes it (via
google-oauth.refreshAccessToken) and retries.
Google Cloud Console setup
- Create a Google OAuth 2.0 Web application client.
- The app's Calendar settings page must display this literal callback URI in
a copyable field:
window.location.origin + "/connect/calendar" — for
example, https://my-app.caffeine.xyz/connect/calendar. 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 Calendar (for example, the draft and live app
origins) as separate authorized redirect URIs.
- Enable only the Calendar scopes the app needs on the consent screen.
- Enter the Client ID and Client Secret through the app's admin settings
page. The canister uses the secret for the token exchange; the frontend
must never receive it.
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 startCalendarOAuth must be the exact same value
the settings page displays and the administrator registered.
OAuth scopes
| Scope |
Purpose |
https://www.googleapis.com/auth/calendar |
Full read/write access to calendars |
https://www.googleapis.com/auth/calendar.events |
Read/write access to events only |
https://www.googleapis.com/auth/calendar.readonly |
Read-only access to calendars |
https://www.googleapis.com/auth/calendar.events.readonly |
Read-only access to events |
Request calendar (full read/write) for a typical CRUD app; use
.readonly variants for read-only views.
Storing tokens
The bearer never leaves the canister. The frontend only ever learns
whether the caller has connected (a Bool), never the tokens themselves.
- A
Map<Principal, CalendarConnection> keyed by caller. Expose exactly the
endpoints listed in §4 — isMyCalendarConnected, startCalendarOAuth,
completeCalendarOAuth, listUpcomingEvents, createEvent,
disconnectMyCalendar — every endpoint gated on not caller.isAnonymous().
Do not add any endpoint that returns access_token / refresh_token /
the full CalendarConnection.
- Store one pending OAuth flow per caller: the PKCE
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.
Google refresh tokens do NOT rotate
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.
3. is_replicated = ?false is REQUIRED
- Security. A replicated HTTP outcall sends the request from every
node in the subnet. Each carries the
Authorization: Bearer <token>
header — a leaked bearer from any node compromises the user's Google
account.
- Billing. Replicated outcalls produce N parallel API calls. The IC
charges ~13× the cycles, and Google counts each toward quota.
- Determinism. Calendar write responses are non-deterministic (unique
event
id/etag, per-request timestamps). Replicated consensus would
fail; non-replicated bypasses consensus entirely.
→ Always: is_replicated = ?false on every Config.
4. Canonical layout
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/calendar-config.mo — admin-gated Client ID + Secret.
src/backend/mixins/calendar-messaging.mo — per-user OAuth + event ops.
src/backend/lib/calendar.mo — googlecalendar-client + google-oauth glue.
import Map "mo:core/Map";
import Principal "mo:core/Principal";
import AccessControl "mo:caffeineai-authorization/access-control";
import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization";
import MixinCalendarConfig "mixins/calendar-config";
import MixinCalendarMessaging "mixins/calendar-messaging";
import LibCalendar "lib/calendar";
actor {
let accessControlState : AccessControl.AccessControlState;
include MixinAuthorization(accessControlState, null);
let calendarConfig : {
var clientId : Text;
var clientSecret : Text;
};
include MixinCalendarConfig(accessControlState, calendarConfig);
let calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>;
let pendingCalendarFlows : Map.Map<Principal, LibCalendar.PendingOAuth>;
include MixinCalendarMessaging(calendarConfig, calendarConnections, pendingCalendarFlows);
};
The migration chain head:
import Map "mo:core/Map";
import AccessControl "mo:caffeineai-authorization/access-control";
module {
type CalendarConnection = {
accessToken : Text;
refreshToken : Text;
};
type PendingOAuth = {
codeVerifier : Text;
redirectUri : Text;
state : Text;
};
type NewActor = {
accessControlState : AccessControl.AccessControlState;
calendarConfig : { var clientId : Text; var clientSecret : Text };
calendarConnections : Map.Map<Principal, CalendarConnection>;
pendingCalendarFlows : Map.Map<Principal, PendingOAuth>;
};
public func migration(_old : {}) : NewActor {
{
accessControlState = AccessControl.initState();
calendarConfig = { var clientId = ""; var clientSecret = "" };
calendarConnections = Map.empty<Principal, CalendarConnection>();
pendingCalendarFlows = Map.empty<Principal, PendingOAuth>();
};
};
};
import AccessControl "mo:caffeineai-authorization/access-control";
import Runtime "mo:core/Runtime";
mixin (
accessControlState : AccessControl.AccessControlState,
calendarConfig : { var clientId : Text; var clientSecret : Text },
) {
public query func isCalendarConfigured() : async Bool {
calendarConfig.clientId.size() > 0;
};
public shared ({ caller }) func setCalendarCredentials(clientId : Text, clientSecret : Text) : async () {
if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
Runtime.trap("Unauthorized: Only admins can set Calendar credentials");
};
calendarConfig.clientId := clientId;
calendarConfig.clientSecret := clientSecret;
};
};
import Map "mo:core/Map";
import Principal "mo:core/Principal";
import Runtime "mo:core/Runtime";
import LibCalendar "../lib/calendar";
mixin (
calendarConfig : { var clientId : Text; var clientSecret : Text },
calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>,
pendingCalendarFlows : Map.Map<Principal, LibCalendar.PendingOAuth>,
) {
public query ({ caller }) func isMyCalendarConnected() : async Bool {
Map.containsKey(calendarConnections, Principal.compare, caller);
};
public shared ({ caller }) func startCalendarOAuth(redirectUri : Text) : async Text {
if (caller.isAnonymous()) {
Runtime.trap("Sign in to connect Google Calendar");
};
if (calendarConfig.clientId.size() == 0) {
Runtime.trap("Calendar is not configured (admin must set credentials)");
};
await* LibCalendar.startAuthorize(
calendarConfig.clientId, redirectUri, caller, pendingCalendarFlows,
);
};
public shared ({ caller }) func completeCalendarOAuth(code : Text, state : Text) : async () {
if (caller.isAnonymous()) {
Runtime.trap("Sign in to connect Google Calendar");
};
if (calendarConfig.clientId.size() == 0) {
Runtime.trap("Calendar is not configured");
};
let ?pending = Map.get(pendingCalendarFlows, Principal.compare, caller) else {
Runtime.trap("No pending OAuth flow — call startCalendarOAuth first");
};
if (state != pending.state) {
Runtime.trap("OAuth state did not match the pending Calendar flow");
};
Map.remove(pendingCalendarFlows, Principal.compare, caller);
let connection = await* LibCalendar.exchangeCode(
calendarConfig.clientId, calendarConfig.clientSecret, code,
pending.redirectUri, pending.codeVerifier,
);
Map.add(calendarConnections, Principal.compare, caller, connection);
};
public shared ({ caller }) func listUpcomingEvents(
timeMin : Text, timeMax : Text, maxResults : Nat,
) : async LibCalendar.EventSummaryList {
if (caller.isAnonymous()) {
Runtime.trap("Sign in to list events");
};
let ?connection = Map.get(calendarConnections, Principal.compare, caller) else {
Runtime.trap("Connect your Google Calendar first");
};
await* LibCalendar.listUpcomingEvents(
calendarConfig.clientId, calendarConfig.clientSecret, connection, caller,
calendarConnections, timeMin, timeMax, maxResults,
);
};
public shared ({ caller }) func createEvent(
summary : Text, startDateTime : Text, endDateTime : Text,
) : async Text {
if (caller.isAnonymous()) {
Runtime.trap("Sign in to create events");
};
let ?connection = Map.get(calendarConnections, Principal.compare, caller) else {
Runtime.trap("Connect your Google Calendar first");
};
await* LibCalendar.createEvent(
calendarConfig.clientId, calendarConfig.clientSecret, connection, caller,
calendarConnections, summary, startDateTime, endDateTime,
);
};
public shared ({ caller }) func disconnectMyCalendar() : async () {
if (caller.isAnonymous()) {
Runtime.trap("Sign in to disconnect");
};
Map.remove(calendarConnections, Principal.compare, caller);
};
};
import Array "mo:core/Array";
import Error "mo:core/Error";
import Map "mo:core/Map";
import Nat64 "mo:core/Nat64";
import Principal "mo:core/Principal";
import PureMap "mo:core/pure/Map";
import Runtime "mo:core/Runtime";
import Text "mo:core/Text";
import OAuth "mo:google-oauth/OAuth";
import DateTime "mo:google-oauth/DateTime";
import { calendar_events_list; calendar_events_insert } "mo:googlecalendar-client/Apis/EventsApi";
import { calendar_freebusy_query } "mo:googlecalendar-client/Apis/FreebusyApi";
import { type Event; JSON = Event } "mo:googlecalendar-client/Models/Event";
import { type EventDateTime; JSON = EventDateTime } "mo:googlecalendar-client/Models/EventDateTime";
import { type Events; JSON = Events } "mo:googlecalendar-client/Models/Events";
import { type FreeBusyRequest; JSON = FreeBusyRequest } "mo:googlecalendar-client/Models/FreeBusyRequest";
import { type FreeBusyRequestItem; JSON = FreeBusyRequestItem } "mo:googlecalendar-client/Models/FreeBusyRequestItem";
import { type FreeBusyResponse } "mo:googlecalendar-client/Models/FreeBusyResponse";
import { defaultConfig; type Config } "mo:googlecalendar-client/Config";
module {
public type CalendarConnection = {
accessToken : Text;
refreshToken : Text;
};
public type PendingOAuth = {
codeVerifier : Text;
redirectUri : Text;
state : Text;
};
public type EventSummary = {
id : Text;
summary : Text;
start : Text;
end : Text;
// Signals that let the frontend tell a real meeting from a marker:
// isAllDay = the event has a date but no time (all-day block).
// transparency = "transparent" (shows as free) or "opaque"/"" (busy).
// eventType = "default" | "outOfOffice" | "focusTime" | "workingLocation".
// To count/show only real meetings, keep timed, opaque, default events.
isAllDay : Bool;
transparency : Text;
eventType : Text;
};
public type EventSummaryList = [EventSummary];
let SCOPES : Text = "https://www.googleapis.com/auth/calendar";
func configForToken(token : Text) : Config {
{
defaultConfig with
auth = ?#bearer(token);
is_replicated = ?false;
max_response_bytes = ?Nat64.fromNat(2_000_000);
};
};
func refreshIfNeeded(
clientId : Text, clientSecret : Text, connection : CalendarConnection,
caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
errorMsg : Text,
) : async* ?Text {
if (not (errorMsg.contains(#text("401")) or errorMsg.contains(#text("Unauthorized")))) {
Runtime.trap("Calendar API failed: " # errorMsg);
};
let refreshed = await OAuth.refreshAccessToken(clientId, clientSecret, connection.refreshToken);
let newToken = accessTokenOf(refreshed, "Token refresh");
Map.add(calendarConnections, Principal.compare, caller, {
connection with accessToken = newToken;
});
?newToken;
};
public func startAuthorize(
clientId : Text, redirectUri : Text, caller : Principal,
pendingFlows : Map.Map<Principal, PendingOAuth>,
) : async* Text {
let codeVerifier = await OAuth.generateCodeVerifier();
let state = await OAuth.generateCodeVerifier();
Map.add(pendingFlows, Principal.compare, caller, {
codeVerifier;
redirectUri;
state;
});
OAuth.buildAuthorizeUrl(clientId, redirectUri, SCOPES, state, OAuth.computeCodeChallenge(codeVerifier));
};
public func exchangeCode(
clientId : Text, clientSecret : Text, code : Text,
redirectUri : Text, codeVerifier : Text,
) : async* CalendarConnection {
let tokens = await OAuth.exchangeAuthorizationCode(clientId, clientSecret, code, redirectUri, codeVerifier);
let accessToken = accessTokenOf(tokens, "Token exchange");
let refreshToken = tokens.refreshToken
?? Runtime.trap("Token exchange failed: missing refresh_token");
{ accessToken; refreshToken };
};
func accessTokenOf(tokens : OAuth.TokenResponse, operation : Text) : Text {
switch (tokens.error) {
case (?error) {
let description = switch (tokens.errorDescription) {
case (?value) ": " # value;
case null "";
};
Runtime.trap(operation # " failed: " # error # description);
};
case null {};
};
tokens.accessToken ?? Runtime.trap(operation # " failed: missing access_token");
};
// Lists events in [timeMin, timeMax). Pass timeMax = "" for an open-ended
// "everything from now" list; pass both to bound a single day/week (e.g.
// timeMin = start-of-tomorrow, timeMax = start-of-day-after) so the count is
// exact. Both are RFC 3339 strings; include an offset ("…Z" or "…+02:00").
public func listUpcomingEvents(
clientId : Text, clientSecret : Text, connection : CalendarConnection,
caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
timeMin : Text, timeMax : Text, maxResults : Nat,
) : async* EventSummaryList {
if (timeMin.size() == 0) {
Runtime.trap("timeMin must be an RFC 3339 timestamp");
};
let events : Events = try {
await* calendar_events_list(
configForToken(connection.accessToken), "primary", #json,
"", "", "", false, "", "",
false, [], "", 10, maxResults, #starttime,
"", [], "", [], false, false, true, "",
timeMax, timeMin, "", "",
);
} catch e {
let ?newToken = await* refreshIfNeeded(
clientId, clientSecret, connection, caller, calendarConnections, e.message(),
) else Runtime.trap("Calendar API failed");
await* calendar_events_list(
configForToken(newToken), "primary", #json,
"", "", "", false, "", "",
false, [], "", 10, maxResults, #starttime,
"", [], "", [], false, false, true, "",
timeMax, timeMin, "", "",
);
};
eventSummariesOf(events);
};
// Availability uses FreeBusy (POST + JSON body), NOT events.list: one call
// returns the merged busy intervals across the user's calendars with recurring
// events already expanded server-side — no paging, recurrence expansion, or
// client-side merging. Returns the owner's busy intervals in [timeMin, timeMax]
// as raw RFC 3339 (start, end) pairs; timeMin/timeMax are UTC "…Z" strings.
// Single-refresh-on-401 retry.
public func busyTimes(
clientId : Text, clientSecret : Text, connection : CalendarConnection,
caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
timeMin : Text, timeMax : Text,
) : async* [(Text, Text)] {
let request : FreeBusyRequest = {
FreeBusyRequest.init {} with
timeMin = ?timeMin;
timeMax = ?timeMax;
items = ?[{ FreeBusyRequestItem.init {} with id = ?"primary" }];
};
let response : FreeBusyResponse = try {
await* calendar_freebusy_query(
configForToken(connection.accessToken), #json, "", "", "", false, "", "", request,
);
} catch e {
let ?newToken = await* refreshIfNeeded(
clientId, clientSecret, connection, caller, calendarConnections, e.message(),
) else Runtime.trap("Calendar API failed");
await* calendar_freebusy_query(
configForToken(newToken), #json, "", "", "", false, "", "", request,
);
};
// The response map is keyed by the RESOLVED calendar id (the user's email),
// NOT "primary". Iterate EVERY returned calendar and union its busy periods.
var busy : [(Text, Text)] = [];
switch (response.calendars) {
case (?calendars) {
for ((_id, cal) in calendars.entries()) {
switch (cal.busy) {
case (?periods) {
for (p in periods.values()) {
switch (p.start, p.end) {
case (?s, ?e) busy := Array.concat(busy, [(s, e)]);
case _ {};
};
};
};
case null {};
};
};
};
case null {};
};
busy;
};
// --- Availability math (re-exported from google-oauth's tested DateTime) ---
//
// Do NOT re-implement RFC 3339 parsing — a digit parse that forgets to subtract
// '0' (48) reads "2026" as 55354, so busy intervals land in the wrong year and
// availability breaks silently (compiles, never traps). These thin re-exports
// let callers use `LibCalendar.isSlotFree` / `.rfc3339ToNanos` with no extra
// import; the implementation lives in `mo:google-oauth/DateTime`.
public func rfc3339ToNanos(s : Text) : Int = DateTime.rfc3339ToNanos(s);
public func nanosToRfc3339(ns : Int) : Text = DateTime.nanosToRfc3339(ns);
public func overlaps(aStart : Int, aEnd : Int, bStart : Int, bEnd : Int) : Bool =
DateTime.overlaps(aStart, aEnd, bStart, bEnd);
public func isSlotFree(slotStart : Int, slotEnd : Int, busy : [(Text, Text)]) : Bool =
DateTime.isSlotFree(slotStart, slotEnd, busy);
public func createEvent(
clientId : Text, clientSecret : Text, connection : CalendarConnection,
caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
summary : Text, startDateTime : Text, endDateTime : Text,
) : async* Text {
let start : EventDateTime = { EventDateTime.init {} with dateTime = ?startDateTime };
let end : EventDateTime = { EventDateTime.init {} with dateTime = ?endDateTime };
let event : Event = { Event.init {} with
summary = ?summary;
start = ?start;
end = ?end;
};
let created : Event = try {
await* calendar_events_insert(
configForToken(connection.accessToken), "primary", #json,
"", "", "", false, "", "",
0, 10, true, #all, false, event,
);
} catch e {
let ?newToken = await* refreshIfNeeded(
clientId, clientSecret, connection, caller, calendarConnections, e.message(),
) else Runtime.trap("Calendar API failed");
await* calendar_events_insert(
configForToken(newToken), "primary", #json,
"", "", "", false, "", "",
0, 10, true, #all, false, event,
);
};
created.id ?? "";
};
func eventSummariesOf(events : Events) : EventSummaryList {
let items = events.items ?? [];
Array.map<Event, EventSummary>(items, func(e : Event) : EventSummary = {
id = e.id ?? "";
summary = e.summary ?? "(no title)";
start = switch (e.start) {
case (?dt) dt.dateTime ?? dt.date ?? "";
case null "";
};
end = switch (e.end) {
case (?dt) dt.dateTime ?? dt.date ?? "";
case null "";
};
// All-day events carry `date` but no `dateTime`.
isAllDay = switch (e.start) {
case (?dt) switch (dt.dateTime) { case (?_) false; case null true };
case null false;
};
transparency = e.transparency ?? "";
eventType = e.eventType ?? "";
});
};
};
4b. Availability / busy times — use FreeBusy, NOT events.list
Any "when is this person free / busy", booking, or Calendly-style feature MUST
read availability through FreeBusy (calendar_freebusy_query), not
calendar_events_list. FreeBusy is purpose-built for this: a single POST returns
the merged busy intervals across the user's calendars, with recurring events
already expanded server-side — you never page through events, expand recurrences,
or union overlapping blocks yourself. It also folds in out-of-office and all-day
blocks. Reserve calendar_events_list for showing the app's own event list and
_insert / _delete for event CRUD.
The busyTimes helper in the lib/calendar.mo block above is the reference
implementation: it builds a FreeBusyRequest for items = [{ id = "primary" }]
over [timeMin, timeMax], does the single-refresh-on-401 retry, and — crucially
— iterates every calendar the response returns (the map is keyed by the
resolved calendar id, not "primary") and unions their busy periods.
Before comparing each (start, end) against your candidate slots, parse it
to an absolute instant honoring the trailing offset — Google returns timed
periods with a Z or a numeric offset (2026-07-21T14:00:00+02:00), and
all-day blocks as a bare YYYY-MM-DD date. Truncating at the seconds and
ignoring the offset shifts every busy interval by the offset (e.g. 2h in
Zurich summer), so busy blocks miss the slots they should hide. Use
LibCalendar.rfc3339ToNanos (a tested re-export of mo:google-oauth/DateTime)
— it honors the offset and handles all-day dates — then overlap numerically. Do
not hand-roll a parser that stops at the seconds.
End to end, the whole availability flow lives in nanosecond instants and only
touches text at the edges: anchor the window with LibCalendar.rfc3339ToNanos,
build the candidate grid with plain integer arithmetic, filter with
LibCalendar.isSlotFree, then format the survivors back with
LibCalendar.nanosToRfc3339 so they are ready to display and to pass straight to
createEvent (whose startDateTime / endDateTime are RFC 3339 text). The grid
below is a fixed UTC window; real working-hours / timezone policy is app-specific,
but the parse → integer-math → format shape is the same:
func availableSlots(
clientId : Text, clientSecret : Text, connection : LibCalendar.CalendarConnection,
caller : Principal, calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>,
windowStart : Text, // e.g. "2026-07-21T09:00:00Z"
slotCount : Nat, // number of consecutive slots to consider
slotMinutes : Nat, // slot length, e.g. 30
) : async* [(Text, Text)] {
let slotNs = slotMinutes * 60 * 1_000_000_000;
let start0 = LibCalendar.rfc3339ToNanos(windowStart);
// Candidate grid of [s, s+slot) instants.
let candidates = Array.tabulate<(Int, Int)>(slotCount, func(i) {
let s = start0 + i * slotNs;
(s, s + slotNs);
});
let windowEnd = start0 + slotCount * slotNs;
let busy = await* LibCalendar.busyTimes(
clientId, clientSecret, connection, caller, calendarConnections,
windowStart, LibCalendar.nanosToRfc3339(windowEnd),
);
let free = Array.filter<(Int, Int)>(candidates, func(s) = LibCalendar.isSlotFree(s.0, s.1, busy));
Array.map<(Int, Int), (Text, Text)>(
free, func(s) = (LibCalendar.nanosToRfc3339(s.0), LibCalendar.nanosToRfc3339(s.1)),
);
};
5. Available API surface
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) |
Availability math (LibCalendar re-exports of mo:google-oauth/DateTime)
lib/calendar.mo re-exports these tested helpers, so call them as LibCalendar.*
with no extra import. Times are absolute nanoseconds since the Unix epoch,
matching Time.now().
| Function |
Purpose |
LibCalendar.rfc3339ToNanos(text) |
Offset-aware RFC 3339 -> nanoseconds (honors Z / ±HH:MM, bare dates) |
LibCalendar.nanosToRfc3339(ns) |
Nanoseconds -> UTC RFC 3339 text (…Z), ready for createEvent |
LibCalendar.overlaps(aStart, aEnd, bStart, bEnd) |
Half-open interval overlap test |
LibCalendar.isSlotFree(slotStart, slotEnd, busy) |
Slot is free of every (start, end) RFC 3339 busy pair |
googlecalendar-client (Calendar REST API v3)
The canonical actor above intentionally implements only upcoming-event listing
and event creation; for availability/busy times use the FreeBusy helper in §4b.
For another generated operation, keep bearer authentication and
is_replicated = ?false, then apply the same single-refresh-retry pattern as
refreshIfNeeded.
The generated package also exposes:
| Function |
Module |
Purpose |
calendar_events_list |
EventsApi |
List events on a calendar |
calendar_events_get |
EventsApi |
Get an event by id |
calendar_events_insert |
EventsApi |
Create an event |
calendar_events_update |
EventsApi |
Update an event (PUT) |
calendar_events_patch |
EventsApi |
Patch an event (PATCH) |
calendar_events_delete |
EventsApi |
Delete an event |
calendar_events_move |
EventsApi |
Move an event to another calendar |
calendar_events_quickAdd |
EventsApi |
Create event from text ("Lunch at noon") |
calendar_events_instances |
EventsApi |
List instances of a recurring event |
calendar_freebusy_query |
FreebusyApi |
Check free/busy across calendars |
calendar_calendarList_list |
CalendarListApi |
List user's calendars |
calendar_calendarList_get |
CalendarListApi |
Get a calendar list entry |
calendar_calendars_get |
CalendarsApi |
Get calendar metadata |
calendar_calendars_insert |
CalendarsApi |
Create a secondary calendar |
6. Cycles and response sizes
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 googlecalendar-client calls, defaultConfig.cycles = 30_000_000_000
(30B). A typical list/insert costs ~10–15B cycles. Set
max_response_bytes = ?2_000_000 for event list reads that may include
large payloads.
7. Things that will bite you
is_replicated = ?false — see §3. Non-negotiable.
- Google refresh tokens do NOT rotate. Unlike X/Twitter, Google does
not issue a new
refresh_token on each refresh. Keep the original
refresh_token and only persist the new access_token.
- Access tokens expire in 1 hour. The
refreshIfNeeded helper catches
HTTP 401, silently refreshes via google-oauth.refreshAccessToken, and
retries once. If the refresh also fails, surface "re-connect your account".
- Callback URI exact-match. Every character (trailing slash, query
string, port) must match between the authorize URL and the redirect.
Google returns
redirect_uri_mismatch otherwise. Use the fixed
window.location.origin + "/connect/calendar" for redirectUri — the same
value the settings page displays and the /connect/calendar route owns — and
register that exact URI on the Google Web client. Do not build it from
window.location.pathname, which varies by page.
- Pass the displayed value to
startCalendarOAuth 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/calendar") and use that same
helper both for the copyable field on the settings page and for the value
handed to startCalendarOAuth. If the value sent to Google (via
startCalendarOAuth) 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.
- RFC 3339 timestamps. Calendar uses RFC 3339 strings
(
2026-07-10T15:00:00-07:00). For all-day events set
EventDateTime.date (YYYY-MM-DD) instead of dateTime.
createEvent times need a zone. The dateTime you pass to createEvent
MUST carry a UTC offset (…Z or …+02:00) or you MUST also set
EventDateTime.timeZone (an IANA name like "Europe/Zurich"). A bare
2026-07-10T15:00:00 with neither is rejected by Google. Prefer sending an
offset-qualified string so the event lands at the intended wall-clock time.
calendarId = "primary" refers to the authenticated user's default
calendar. Named/shared calendars use their calendar-ID (an email-like
address).
- Availability = FreeBusy, not
events.list. For "am I free / busy" use
calendar_freebusy_query (§4b): one POST returns merged busy intervals with
recurrences expanded server-side. Rebuilding availability from events.list
means paging, expanding recurring events, and merging overlaps by hand — easy
to get wrong, and the classic cause of "the booking link shows me free when I'm
busy".
maxAttendees and maxResults must be ≥ 1. Google rejects maxAttendees=0
/ maxResults=0 with HTTP 400 (documented minimum is 1). The listUpcomingEvents
and createEvent recipes pass maxAttendees = 10; never pass 0 for these on
any events endpoint.
- FreeBusy responses are keyed by the resolved calendar ID, not the string
you queried. When you call
calendar_freebusy_query for "primary", Google
resolves it and returns the calendars map keyed by the real calendar ID (the
user's email address), not the literal "primary". Do not look up
"primary" in the response — that finds nothing and makes every slot look
free (a common availability bug). Instead, iterate over every calendar the
response returns and union all their busy intervals, then subtract those
from your candidate slots. Parse each interval's start/end as RFC 3339
allowing a trailing Z or a numeric offset (+02:00); compare instants, not
raw strings.
- Parse RFC 3339 with
LibCalendar.rfc3339ToNanos (re-exported from
mo:google-oauth/DateTime) — do NOT re-implement it. A hand-rolled parser
that forgets to subtract '0' (48) per digit reads "2026" as 55354, so
every busy interval lands in the wrong year, overlap checks never match, and
availability is silently wrong — the code still compiles and never traps, so the
bug is invisible until a user is double-booked. Use the tested helper.
- HTTP 429 rate-limit. Surface the error to the caller; never
silently retry a write inside the canister — a retry may create a
duplicate event.
- Don't expose the access token.
calendarConnections is read only by
Map.get(calendarConnections, ..., caller) inside API calls. No
getMyCalendarConnection, no getMyAccessToken, no iterator. A leaked
bearer is a per-user account compromise.
alt = #json for all Calendar API v3 calls. Leave optional string
parameters "" and prettyPrint = false.
- API query parameters are plain positional values, not
?T — never pass
null for one. The client's function parameters are Text / Bool / enum /
Nat (e.g. alt, fields, prettyPrint); pass real values like #json,
"", false, 10 — null will not type-check. (Respect each param's
documented minimum: maxAttendees / maxResults must be ≥ 1, see below.) Only
model values (Event, EventDateTime, FreeBusyRequest) are optional
?T.
- Combined Gmail + Calendar apps: request the scope union, and learn the
address via
OAuth.getUserEmail. The union of openid email + .../calendar
.../gmail.send covers availability, sending, and the connected address (via
OIDC userinfo) — no gmail.readonly needed unless the app actually reads mail.
Never drop a scope when merging recipes — see "Combined Gmail + Calendar apps".
- Build
Event / EventDateTime with init {} then record-update
the fields you need — all fields are optional (?T); leave the rest null.
- PATCH/PUT/DELETE are forced non-replicated in the generated client
(the
googlecalendar-client sets is_replicated = ?false on these
methods automatically). For GET/POST, set it explicitly in your Config.
Frontend
Every build using this skill MUST ship all four items below. (If the app
also uses the Gmail connector, follow "Combined Gmail + Calendar apps" below
instead — it replaces /settings/calendar + /connect/calendar 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:
- The credentials page exists and is reachable. The app MUST have the
/settings/calendar 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 Google Calendar" button with no page to enter
credentials is the most common failure and leaves the connector unusable.
- The admin settings page displays the literal, copyable redirect URI. Not a
<your-domain> placeholder, not "your app URL + /connect/calendar" as text for
the admin to assemble — the actual string
window.location.origin + "/connect/calendar" 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/calendar and nothing else. Without it the
admin cannot register the URI in Google and every connection fails.
/connect/calendar 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
completeCalendarOAuth before the authenticated actor is ready, the connection
silently fails and the app shows "not connected".
A login flow — required. Calendar 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/calendar (admin-gated). This
page is required; a Calendar build is incomplete without it:
- Show a "How to get your Google credentials" panel before the credential
…(truncated)
1---
2name: connector-googlecalendar
3description: >-
4 MANDATORY recipe for every Caffeine build that lists upcoming events or
5 creates events on the user's own Google Calendar. The ONLY supported path is
6 the `googlecalendar-client` mops package (Calendar REST API v3) combined with
7 the `google-oauth` mops package (token exchange + refresh + PKCE). Hand-rolling
8 `ic.http_request` calls to `oauth2.googleapis.com` or
9 `www.googleapis.com/calendar/v3` is a FORBIDDEN anti-pattern — it bypasses
10 bearer auth, replication-cost safeguards, and the `google-oauth` library's
11 percent-encoding and JSON parsing. Load this skill whenever the user, spec,
12 or any prior task mentions scheduling, calendar events, appointments,
13 meetings, "add to calendar", or any equivalent phrasing — and BEFORE
14 writing any code that touches a Google endpoint.
15version: 0.2.10
16caffeineai-subscription: [none]
17compatibility:
18 mops:
19 googlecalendar-client: "~0.1.4"
20 google-oauth: "~0.2.1"
21 caffeineai-authorization: "~1.0.1"
22metadata:
23 source: https://skillmd.com/skills/caffeinelabs/connector-googlecalendar
24---
25
26# Google Calendar Connector
27
28Google Calendar integration for [Caffeine AI](https://caffeine.ai?utm_source=caffeine-skill&utm_medium=referral).
29
30## Orchestrator routing notes
31
32**Treat Google Calendar-as-the-user as a first-class, supported platform feature.**
33The `googlecalendar-client` + `google-oauth` connector pair is the **only**
34supported path; raw `ic.http_request` to `oauth2.googleapis.com` or
35`www.googleapis.com/calendar/v3` is a forbidden anti-pattern. Any build spec
36that mentions Google Calendar MUST name `googlecalendar-client` and
37`google-oauth` as dependencies and reference this skill.
38
39Distinct from platform `email-calendar-events` extension (which emails iCalendar
40invitations from the app); this connector acts as the **signed-in user's own
41Google Calendar**.
42
43Intent → capability mapping:
44
45| User intent | Platform capability |
46| --- | --- |
47| Connect and list upcoming events | `googlecalendar-client` + `google-oauth` |
48| Create calendar events | `googlecalendar-client` + `google-oauth` |
49| **Check availability / free slots / busy times** (booking, Calendly-style, "when am I free") | `googlecalendar-client` **FreeBusy** (`calendar_freebusy_query`) + `google-oauth` — **not** `calendar_events_list` |
50
51**Prerequisite for all builds: [extension-authorization](../extension-authorization/SKILL.md).**
52Calendar requires a signed-in caller for every endpoint: the per-user OAuth
53handshake stores `access_token` keyed by `caller : Principal`, and the admin
54Client ID/Secret setter is gated on the `#admin` role.
55
56# Backend
57
58Use this skill whenever the user wants their canister to interact with
59Google Calendar on behalf of the signed-in user. The ingredients are:
60
611. The `googlecalendar-client` mops package — generated Motoko bindings for
62 the Google Calendar API v3. This recipe demonstrates listing upcoming
63 events and creating events; add other generated operations only by
64 following the same bearer-authenticated, non-replicated,
65 single-refresh-retry pattern.
662. The `google-oauth` mops package — Google OAuth 2.0 token exchange,
67 refresh, PKCE, and percent-encoding. This is the library that
68 eliminates hand-rolled `http_request` to `oauth2.googleapis.com`.
693. An OAuth 2.0 Authorization Code with PKCE flow so each end-user
70 authorises the canister to act on their behalf. Each user holds their
71 own `access_token` + `refresh_token` keyed by `caller : Principal`.
724. A Google Cloud **Web application** Client ID + Client Secret.
73 Admin-configured and held by the canister only; never return the secret
74 to the frontend.
75
76## 1. Add dependencies
77
78```bash
79mops add googlecalendar-client@0.1.4
80mops add google-oauth@0.2.1
81mops add caffeineai-authorization@1.0.1
82```
83
84## 2. Auth model — OAuth 2.0 PKCE per user, on-chain exchange + refresh
85
86Identical to the Gmail connector. Every end-user authorises the canister
87independently via the Authorization Code with PKCE flow. The canister:
88
891. Generates a PKCE `code_verifier` and `code_challenge` (via `google-oauth`).
902. Builds the Google authorize URL (via `google-oauth.buildAuthorizeUrl`).
913. The frontend redirects the user to Google; after consent, Google
92 redirects back with a `code` parameter.
934. The canister exchanges the code for tokens (via
94 `google-oauth.exchangeAuthorizationCode`) — **on-chain**, non-replicated.
955. The canister stores `access_token` + `refresh_token` keyed by `caller`.
966. When the 1-hour access token expires (HTTP 401), the canister silently
97 refreshes it (via `google-oauth.refreshAccessToken`) and retries.
98
99### Google Cloud Console setup
100
1011. Create a Google OAuth 2.0 **Web application** client.
1022. The app's Calendar settings page must display this literal callback URI in
103 a copyable field: `window.location.origin + "/connect/calendar"` — for
104 example, `https://my-app.caffeine.xyz/connect/calendar`. The app
105 administrator must manually copy that displayed value into Google Cloud
106 Console under **Authorized redirect URIs**. Register every deployed origin
107 where users can connect Calendar (for example, the draft and live app
108 origins) as separate authorized redirect URIs.
1093. Enable only the Calendar scopes the app needs on the consent screen.
1104. Enter the Client ID and Client Secret through the app's admin settings
111 page. The canister uses the secret for the token exchange; the frontend
112 must never receive it.
113
114PKCE binds each authorization code to the canister-generated verifier, while
115the Web client registration binds the browser callback to the deployed app.
116The callback URI passed to `startCalendarOAuth` must be the exact same value
117the settings page displays and the administrator registered.
118
119### OAuth scopes
120
121| Scope | Purpose |
122| --- | --- |
123| `https://www.googleapis.com/auth/calendar` | Full read/write access to calendars |
124| `https://www.googleapis.com/auth/calendar.events` | Read/write access to events only |
125| `https://www.googleapis.com/auth/calendar.readonly` | Read-only access to calendars |
126| `https://www.googleapis.com/auth/calendar.events.readonly` | Read-only access to events |
127
128Request `calendar` (full read/write) for a typical CRUD app; use
129`.readonly` variants for read-only views.
130
131### Storing tokens
132
133The bearer **never leaves the canister**. The frontend only ever learns
134whether the caller has connected (a `Bool`), never the tokens themselves.
135
136- A `Map<Principal, CalendarConnection>` keyed by caller. Expose exactly the
137 endpoints listed in §4 — `isMyCalendarConnected`, `startCalendarOAuth`,
138 `completeCalendarOAuth`, `listUpcomingEvents`, `createEvent`,
139 `disconnectMyCalendar` — every endpoint gated on `not caller.isAnonymous()`.
140 **Do not add any endpoint that returns `access_token` / `refresh_token` /
141 the full `CalendarConnection`.**
142- Store one pending OAuth flow per caller: the PKCE `code_verifier`, exact
143 `redirectUri`, and a random `state` nonce. Consume it when the callback is
144 completed; do not accept a replacement redirect URI from the frontend.
145
146### Google refresh tokens do NOT rotate
147
148Unlike X/Twitter, Google does **not** rotate the `refresh_token` on each
149refresh. The same `refresh_token` can be reused until the user revokes
150access or the authorization is re-issued. This simplifies the refresh
151logic: just persist the new `access_token`, keep the old `refresh_token`.
152
153## 3. `is_replicated = ?false` is REQUIRED
154
1551. **Security.** A replicated HTTP outcall sends the request from every
156 node in the subnet. Each carries the `Authorization: Bearer <token>`
157 header — a leaked bearer from any node compromises the user's Google
158 account.
1592. **Billing.** Replicated outcalls produce N parallel API calls. The IC
160 charges ~13× the cycles, and Google counts each toward quota.
1613. **Determinism.** Calendar write responses are non-deterministic (unique
162 event `id`/`etag`, per-request timestamps). Replicated consensus would
163 fail; non-replicated bypasses consensus entirely.
164
165→ Always: `is_replicated = ?false` on every `Config`.
166
167## 4. Canonical layout
168
169The default shape: **admin Client ID/Secret + per-user OAuth**. The
170canister owner registers one Google Cloud Desktop app and pastes its
171Client ID + Secret into canister-level config; every end-user runs the
172OAuth 2.0 PKCE handshake against that one credential and ends up with
173their own `access_token` + `refresh_token`.
174
175The example spans four files:
176
177- `src/backend/main.mo` — the actor: state + `include`s only.
178- `src/backend/mixins/calendar-config.mo` — admin-gated Client ID + Secret.
179- `src/backend/mixins/calendar-messaging.mo` — per-user OAuth + event ops.
180- `src/backend/lib/calendar.mo` — `googlecalendar-client` + `google-oauth` glue.
181
182```motoko filepath=src/backend/main.mo
183import Map "mo:core/Map";
184import Principal "mo:core/Principal";
185import AccessControl "mo:caffeineai-authorization/access-control";
186import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization";
187import MixinCalendarConfig "mixins/calendar-config";
188import MixinCalendarMessaging "mixins/calendar-messaging";
189import LibCalendar "lib/calendar";
190
191actor {
192 let accessControlState : AccessControl.AccessControlState;
193 include MixinAuthorization(accessControlState, null);
194
195 let calendarConfig : {
196 var clientId : Text;
197 var clientSecret : Text;
198 };
199 include MixinCalendarConfig(accessControlState, calendarConfig);
200
201 let calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>;
202 let pendingCalendarFlows : Map.Map<Principal, LibCalendar.PendingOAuth>;
203 include MixinCalendarMessaging(calendarConfig, calendarConnections, pendingCalendarFlows);
204};
205```
206
207The migration chain head:
208
209```motoko filepath=src/backend/migrations/00000000_000000.mo
210import Map "mo:core/Map";
211import AccessControl "mo:caffeineai-authorization/access-control";
212
213module {
214 type CalendarConnection = {
215 accessToken : Text;
216 refreshToken : Text;
217 };
218
219 type PendingOAuth = {
220 codeVerifier : Text;
221 redirectUri : Text;
222 state : Text;
223 };
224
225 type NewActor = {
226 accessControlState : AccessControl.AccessControlState;
227 calendarConfig : { var clientId : Text; var clientSecret : Text };
228 calendarConnections : Map.Map<Principal, CalendarConnection>;
229 pendingCalendarFlows : Map.Map<Principal, PendingOAuth>;
230 };
231
232 public func migration(_old : {}) : NewActor {
233 {
234 accessControlState = AccessControl.initState();
235 calendarConfig = { var clientId = ""; var clientSecret = "" };
236 calendarConnections = Map.empty<Principal, CalendarConnection>();
237 pendingCalendarFlows = Map.empty<Principal, PendingOAuth>();
238 };
239 };
240};
241```
242
243```motoko filepath=src/backend/mixins/calendar-config.mo
244import AccessControl "mo:caffeineai-authorization/access-control";
245import Runtime "mo:core/Runtime";
246
247mixin (
248 accessControlState : AccessControl.AccessControlState,
249 calendarConfig : { var clientId : Text; var clientSecret : Text },
250) {
251 public query func isCalendarConfigured() : async Bool {
252 calendarConfig.clientId.size() > 0;
253 };
254
255 public shared ({ caller }) func setCalendarCredentials(clientId : Text, clientSecret : Text) : async () {
256 if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
257 Runtime.trap("Unauthorized: Only admins can set Calendar credentials");
258 };
259 calendarConfig.clientId := clientId;
260 calendarConfig.clientSecret := clientSecret;
261 };
262};
263```
264
265```motoko filepath=src/backend/mixins/calendar-messaging.mo
266import Map "mo:core/Map";
267import Principal "mo:core/Principal";
268import Runtime "mo:core/Runtime";
269import LibCalendar "../lib/calendar";
270
271mixin (
272 calendarConfig : { var clientId : Text; var clientSecret : Text },
273 calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>,
274 pendingCalendarFlows : Map.Map<Principal, LibCalendar.PendingOAuth>,
275) {
276 public query ({ caller }) func isMyCalendarConnected() : async Bool {
277 Map.containsKey(calendarConnections, Principal.compare, caller);
278 };
279
280 public shared ({ caller }) func startCalendarOAuth(redirectUri : Text) : async Text {
281 if (caller.isAnonymous()) {
282 Runtime.trap("Sign in to connect Google Calendar");
283 };
284 if (calendarConfig.clientId.size() == 0) {
285 Runtime.trap("Calendar is not configured (admin must set credentials)");
286 };
287 await* LibCalendar.startAuthorize(
288 calendarConfig.clientId, redirectUri, caller, pendingCalendarFlows,
289 );
290 };
291
292 public shared ({ caller }) func completeCalendarOAuth(code : Text, state : Text) : async () {
293 if (caller.isAnonymous()) {
294 Runtime.trap("Sign in to connect Google Calendar");
295 };
296 if (calendarConfig.clientId.size() == 0) {
297 Runtime.trap("Calendar is not configured");
298 };
299 let ?pending = Map.get(pendingCalendarFlows, Principal.compare, caller) else {
300 Runtime.trap("No pending OAuth flow — call startCalendarOAuth first");
301 };
302 if (state != pending.state) {
303 Runtime.trap("OAuth state did not match the pending Calendar flow");
304 };
305 Map.remove(pendingCalendarFlows, Principal.compare, caller);
306 let connection = await* LibCalendar.exchangeCode(
307 calendarConfig.clientId, calendarConfig.clientSecret, code,
308 pending.redirectUri, pending.codeVerifier,
309 );
310 Map.add(calendarConnections, Principal.compare, caller, connection);
311 };
312
313 public shared ({ caller }) func listUpcomingEvents(
314 timeMin : Text, timeMax : Text, maxResults : Nat,
315 ) : async LibCalendar.EventSummaryList {
316 if (caller.isAnonymous()) {
317 Runtime.trap("Sign in to list events");
318 };
319 let ?connection = Map.get(calendarConnections, Principal.compare, caller) else {
320 Runtime.trap("Connect your Google Calendar first");
321 };
322 await* LibCalendar.listUpcomingEvents(
323 calendarConfig.clientId, calendarConfig.clientSecret, connection, caller,
324 calendarConnections, timeMin, timeMax, maxResults,
325 );
326 };
327
328 public shared ({ caller }) func createEvent(
329 summary : Text, startDateTime : Text, endDateTime : Text,
330 ) : async Text {
331 if (caller.isAnonymous()) {
332 Runtime.trap("Sign in to create events");
333 };
334 let ?connection = Map.get(calendarConnections, Principal.compare, caller) else {
335 Runtime.trap("Connect your Google Calendar first");
336 };
337 await* LibCalendar.createEvent(
338 calendarConfig.clientId, calendarConfig.clientSecret, connection, caller,
339 calendarConnections, summary, startDateTime, endDateTime,
340 );
341 };
342
343 public shared ({ caller }) func disconnectMyCalendar() : async () {
344 if (caller.isAnonymous()) {
345 Runtime.trap("Sign in to disconnect");
346 };
347 Map.remove(calendarConnections, Principal.compare, caller);
348 };
349};
350```
351
352```motoko filepath=src/backend/lib/calendar.mo
353import Array "mo:core/Array";
354import Error "mo:core/Error";
355import Map "mo:core/Map";
356import Nat64 "mo:core/Nat64";
357import Principal "mo:core/Principal";
358import PureMap "mo:core/pure/Map";
359import Runtime "mo:core/Runtime";
360import Text "mo:core/Text";
361import OAuth "mo:google-oauth/OAuth";
362import DateTime "mo:google-oauth/DateTime";
363import { calendar_events_list; calendar_events_insert } "mo:googlecalendar-client/Apis/EventsApi";
364import { calendar_freebusy_query } "mo:googlecalendar-client/Apis/FreebusyApi";
365import { type Event; JSON = Event } "mo:googlecalendar-client/Models/Event";
366import { type EventDateTime; JSON = EventDateTime } "mo:googlecalendar-client/Models/EventDateTime";
367import { type Events; JSON = Events } "mo:googlecalendar-client/Models/Events";
368import { type FreeBusyRequest; JSON = FreeBusyRequest } "mo:googlecalendar-client/Models/FreeBusyRequest";
369import { type FreeBusyRequestItem; JSON = FreeBusyRequestItem } "mo:googlecalendar-client/Models/FreeBusyRequestItem";
370import { type FreeBusyResponse } "mo:googlecalendar-client/Models/FreeBusyResponse";
371import { defaultConfig; type Config } "mo:googlecalendar-client/Config";
372
373module {
374 public type CalendarConnection = {
375 accessToken : Text;
376 refreshToken : Text;
377 };
378
379 public type PendingOAuth = {
380 codeVerifier : Text;
381 redirectUri : Text;
382 state : Text;
383 };
384
385 public type EventSummary = {
386 id : Text;
387 summary : Text;
388 start : Text;
389 end : Text;
390 // Signals that let the frontend tell a real meeting from a marker:
391 // isAllDay = the event has a date but no time (all-day block).
392 // transparency = "transparent" (shows as free) or "opaque"/"" (busy).
393 // eventType = "default" | "outOfOffice" | "focusTime" | "workingLocation".
394 // To count/show only real meetings, keep timed, opaque, default events.
395 isAllDay : Bool;
396 transparency : Text;
397 eventType : Text;
398 };
399
400 public type EventSummaryList = [EventSummary];
401
402 let SCOPES : Text = "https://www.googleapis.com/auth/calendar";
403
404 func configForToken(token : Text) : Config {
405 {
406 defaultConfig with
407 auth = ?#bearer(token);
408 is_replicated = ?false;
409 max_response_bytes = ?Nat64.fromNat(2_000_000);
410 };
411 };
412
413 func refreshIfNeeded(
414 clientId : Text, clientSecret : Text, connection : CalendarConnection,
415 caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
416 errorMsg : Text,
417 ) : async* ?Text {
418 if (not (errorMsg.contains(#text("401")) or errorMsg.contains(#text("Unauthorized")))) {
419 Runtime.trap("Calendar API failed: " # errorMsg);
420 };
421 let refreshed = await OAuth.refreshAccessToken(clientId, clientSecret, connection.refreshToken);
422 let newToken = accessTokenOf(refreshed, "Token refresh");
423 Map.add(calendarConnections, Principal.compare, caller, {
424 connection with accessToken = newToken;
425 });
426 ?newToken;
427 };
428
429 public func startAuthorize(
430 clientId : Text, redirectUri : Text, caller : Principal,
431 pendingFlows : Map.Map<Principal, PendingOAuth>,
432 ) : async* Text {
433 let codeVerifier = await OAuth.generateCodeVerifier();
434 let state = await OAuth.generateCodeVerifier();
435 Map.add(pendingFlows, Principal.compare, caller, {
436 codeVerifier;
437 redirectUri;
438 state;
439 });
440 OAuth.buildAuthorizeUrl(clientId, redirectUri, SCOPES, state, OAuth.computeCodeChallenge(codeVerifier));
441 };
442
443 public func exchangeCode(
444 clientId : Text, clientSecret : Text, code : Text,
445 redirectUri : Text, codeVerifier : Text,
446 ) : async* CalendarConnection {
447 let tokens = await OAuth.exchangeAuthorizationCode(clientId, clientSecret, code, redirectUri, codeVerifier);
448 let accessToken = accessTokenOf(tokens, "Token exchange");
449 let refreshToken = tokens.refreshToken
450 ?? Runtime.trap("Token exchange failed: missing refresh_token");
451 { accessToken; refreshToken };
452 };
453
454 func accessTokenOf(tokens : OAuth.TokenResponse, operation : Text) : Text {
455 switch (tokens.error) {
456 case (?error) {
457 let description = switch (tokens.errorDescription) {
458 case (?value) ": " # value;
459 case null "";
460 };
461 Runtime.trap(operation # " failed: " # error # description);
462 };
463 case null {};
464 };
465 tokens.accessToken ?? Runtime.trap(operation # " failed: missing access_token");
466 };
467
468 // Lists events in [timeMin, timeMax). Pass timeMax = "" for an open-ended
469 // "everything from now" list; pass both to bound a single day/week (e.g.
470 // timeMin = start-of-tomorrow, timeMax = start-of-day-after) so the count is
471 // exact. Both are RFC 3339 strings; include an offset ("…Z" or "…+02:00").
472 public func listUpcomingEvents(
473 clientId : Text, clientSecret : Text, connection : CalendarConnection,
474 caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
475 timeMin : Text, timeMax : Text, maxResults : Nat,
476 ) : async* EventSummaryList {
477 if (timeMin.size() == 0) {
478 Runtime.trap("timeMin must be an RFC 3339 timestamp");
479 };
480 let events : Events = try {
481 await* calendar_events_list(
482 configForToken(connection.accessToken), "primary", #json,
483 "", "", "", false, "", "",
484 false, [], "", 10, maxResults, #starttime,
485 "", [], "", [], false, false, true, "",
486 timeMax, timeMin, "", "",
487 );
488 } catch e {
489 let ?newToken = await* refreshIfNeeded(
490 clientId, clientSecret, connection, caller, calendarConnections, e.message(),
491 ) else Runtime.trap("Calendar API failed");
492 await* calendar_events_list(
493 configForToken(newToken), "primary", #json,
494 "", "", "", false, "", "",
495 false, [], "", 10, maxResults, #starttime,
496 "", [], "", [], false, false, true, "",
497 timeMax, timeMin, "", "",
498 );
499 };
500 eventSummariesOf(events);
501 };
502
503 // Availability uses FreeBusy (POST + JSON body), NOT events.list: one call
504 // returns the merged busy intervals across the user's calendars with recurring
505 // events already expanded server-side — no paging, recurrence expansion, or
506 // client-side merging. Returns the owner's busy intervals in [timeMin, timeMax]
507 // as raw RFC 3339 (start, end) pairs; timeMin/timeMax are UTC "…Z" strings.
508 // Single-refresh-on-401 retry.
509 public func busyTimes(
510 clientId : Text, clientSecret : Text, connection : CalendarConnection,
511 caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
512 timeMin : Text, timeMax : Text,
513 ) : async* [(Text, Text)] {
514 let request : FreeBusyRequest = {
515 FreeBusyRequest.init {} with
516 timeMin = ?timeMin;
517 timeMax = ?timeMax;
518 items = ?[{ FreeBusyRequestItem.init {} with id = ?"primary" }];
519 };
520 let response : FreeBusyResponse = try {
521 await* calendar_freebusy_query(
522 configForToken(connection.accessToken), #json, "", "", "", false, "", "", request,
523 );
524 } catch e {
525 let ?newToken = await* refreshIfNeeded(
526 clientId, clientSecret, connection, caller, calendarConnections, e.message(),
527 ) else Runtime.trap("Calendar API failed");
528 await* calendar_freebusy_query(
529 configForToken(newToken), #json, "", "", "", false, "", "", request,
530 );
531 };
532 // The response map is keyed by the RESOLVED calendar id (the user's email),
533 // NOT "primary". Iterate EVERY returned calendar and union its busy periods.
534 var busy : [(Text, Text)] = [];
535 switch (response.calendars) {
536 case (?calendars) {
537 for ((_id, cal) in calendars.entries()) {
538 switch (cal.busy) {
539 case (?periods) {
540 for (p in periods.values()) {
541 switch (p.start, p.end) {
542 case (?s, ?e) busy := Array.concat(busy, [(s, e)]);
543 case _ {};
544 };
545 };
546 };
547 case null {};
548 };
549 };
550 };
551 case null {};
552 };
553 busy;
554 };
555
556 // --- Availability math (re-exported from google-oauth's tested DateTime) ---
557 //
558 // Do NOT re-implement RFC 3339 parsing — a digit parse that forgets to subtract
559 // '0' (48) reads "2026" as 55354, so busy intervals land in the wrong year and
560 // availability breaks silently (compiles, never traps). These thin re-exports
561 // let callers use `LibCalendar.isSlotFree` / `.rfc3339ToNanos` with no extra
562 // import; the implementation lives in `mo:google-oauth/DateTime`.
563 public func rfc3339ToNanos(s : Text) : Int = DateTime.rfc3339ToNanos(s);
564 public func nanosToRfc3339(ns : Int) : Text = DateTime.nanosToRfc3339(ns);
565 public func overlaps(aStart : Int, aEnd : Int, bStart : Int, bEnd : Int) : Bool =
566 DateTime.overlaps(aStart, aEnd, bStart, bEnd);
567 public func isSlotFree(slotStart : Int, slotEnd : Int, busy : [(Text, Text)]) : Bool =
568 DateTime.isSlotFree(slotStart, slotEnd, busy);
569
570 public func createEvent(
571 clientId : Text, clientSecret : Text, connection : CalendarConnection,
572 caller : Principal, calendarConnections : Map.Map<Principal, CalendarConnection>,
573 summary : Text, startDateTime : Text, endDateTime : Text,
574 ) : async* Text {
575 let start : EventDateTime = { EventDateTime.init {} with dateTime = ?startDateTime };
576 let end : EventDateTime = { EventDateTime.init {} with dateTime = ?endDateTime };
577 let event : Event = { Event.init {} with
578 summary = ?summary;
579 start = ?start;
580 end = ?end;
581 };
582 let created : Event = try {
583 await* calendar_events_insert(
584 configForToken(connection.accessToken), "primary", #json,
585 "", "", "", false, "", "",
586 0, 10, true, #all, false, event,
587 );
588 } catch e {
589 let ?newToken = await* refreshIfNeeded(
590 clientId, clientSecret, connection, caller, calendarConnections, e.message(),
591 ) else Runtime.trap("Calendar API failed");
592 await* calendar_events_insert(
593 configForToken(newToken), "primary", #json,
594 "", "", "", false, "", "",
595 0, 10, true, #all, false, event,
596 );
597 };
598 created.id ?? "";
599 };
600
601 func eventSummariesOf(events : Events) : EventSummaryList {
602 let items = events.items ?? [];
603 Array.map<Event, EventSummary>(items, func(e : Event) : EventSummary = {
604 id = e.id ?? "";
605 summary = e.summary ?? "(no title)";
606 start = switch (e.start) {
607 case (?dt) dt.dateTime ?? dt.date ?? "";
608 case null "";
609 };
610 end = switch (e.end) {
611 case (?dt) dt.dateTime ?? dt.date ?? "";
612 case null "";
613 };
614 // All-day events carry `date` but no `dateTime`.
615 isAllDay = switch (e.start) {
616 case (?dt) switch (dt.dateTime) { case (?_) false; case null true };
617 case null false;
618 };
619 transparency = e.transparency ?? "";
620 eventType = e.eventType ?? "";
621 });
622 };
623};
624```
625
626## 4b. Availability / busy times — use FreeBusy, NOT events.list
627
628Any "when is this person free / busy", booking, or Calendly-style feature MUST
629read availability through **FreeBusy** (`calendar_freebusy_query`), not
630`calendar_events_list`. FreeBusy is purpose-built for this: a single POST returns
631the **merged busy intervals** across the user's calendars, with recurring events
632already expanded server-side — you never page through events, expand recurrences,
633or union overlapping blocks yourself. It also folds in out-of-office and all-day
634blocks. Reserve `calendar_events_list` for showing the app's own event list and
635`_insert` / `_delete` for event CRUD.
636
637The `busyTimes` helper in the `lib/calendar.mo` block above is the reference
638implementation: it builds a `FreeBusyRequest` for `items = [{ id = "primary" }]`
639over `[timeMin, timeMax]`, does the single-refresh-on-401 retry, and — crucially
640— iterates **every** calendar the response returns (the map is keyed by the
641resolved calendar id, not `"primary"`) and unions their busy periods.
642
643**Before comparing** each `(start, end)` against your candidate slots, parse it
644to an absolute instant honoring the trailing offset — Google returns timed
645periods with a `Z` **or** a numeric offset (`2026-07-21T14:00:00+02:00`), and
646all-day blocks as a bare `YYYY-MM-DD` date. Truncating at the seconds and
647ignoring the offset shifts every busy interval by the offset (e.g. 2h in
648Zurich summer), so busy blocks miss the slots they should hide. Use
649`LibCalendar.rfc3339ToNanos` (a tested re-export of `mo:google-oauth/DateTime`)
650— it honors the offset and handles all-day dates — then overlap numerically. Do
651**not** hand-roll a parser that stops at the seconds.
652
653End to end, the whole availability flow lives in nanosecond instants and only
654touches text at the edges: anchor the window with `LibCalendar.rfc3339ToNanos`,
655build the candidate grid with plain integer arithmetic, filter with
656`LibCalendar.isSlotFree`, then format the survivors back with
657`LibCalendar.nanosToRfc3339` so they are ready to display and to pass straight to
658`createEvent` (whose `startDateTime` / `endDateTime` are RFC 3339 text). The grid
659below is a fixed UTC window; real working-hours / timezone policy is app-specific,
660but the parse → integer-math → format shape is the same:
661
662```motoko
663func availableSlots(
664 clientId : Text, clientSecret : Text, connection : LibCalendar.CalendarConnection,
665 caller : Principal, calendarConnections : Map.Map<Principal, LibCalendar.CalendarConnection>,
666 windowStart : Text, // e.g. "2026-07-21T09:00:00Z"
667 slotCount : Nat, // number of consecutive slots to consider
668 slotMinutes : Nat, // slot length, e.g. 30
669) : async* [(Text, Text)] {
670 let slotNs = slotMinutes * 60 * 1_000_000_000;
671 let start0 = LibCalendar.rfc3339ToNanos(windowStart);
672 // Candidate grid of [s, s+slot) instants.
673 let candidates = Array.tabulate<(Int, Int)>(slotCount, func(i) {
674 let s = start0 + i * slotNs;
675 (s, s + slotNs);
676 });
677 let windowEnd = start0 + slotCount * slotNs;
678 let busy = await* LibCalendar.busyTimes(
679 clientId, clientSecret, connection, caller, calendarConnections,
680 windowStart, LibCalendar.nanosToRfc3339(windowEnd),
681 );
682 let free = Array.filter<(Int, Int)>(candidates, func(s) = LibCalendar.isSlotFree(s.0, s.1, busy));
683 Array.map<(Int, Int), (Text, Text)>(
684 free, func(s) = (LibCalendar.nanosToRfc3339(s.0), LibCalendar.nanosToRfc3339(s.1)),
685 );
686};
687```
688
689## 5. Available API surface
690
691### `google-oauth` (OAuth 2.0 mechanics)
692
693| Function | Purpose |
694| --- | --- |
695| `OAuth.urlEncode(text)` | RFC 3986 percent-encoding for form bodies |
696| `OAuth.parseTokenResponse(text)` | Parse Google token-endpoint JSON |
697| `OAuth.exchangeAuthorizationCode(...)` | Exchange auth code for tokens |
698| `OAuth.refreshAccessToken(...)` | Refresh an expired access token |
699| `OAuth.generateCodeVerifier()` | Generate PKCE `code_verifier` (on-chain randomness) |
700| `OAuth.computeCodeChallenge(verifier)` | Compute PKCE `code_challenge` (S256) |
701| `OAuth.buildAuthorizeUrl(...)` | Build the Google OAuth authorize URL |
702| `OAuth.getUserEmail(accessToken)` | Fetch the connected email via OIDC userinfo (needs only `openid email`) |
703
704### Availability math (`LibCalendar` re-exports of `mo:google-oauth/DateTime`)
705
706`lib/calendar.mo` re-exports these tested helpers, so call them as `LibCalendar.*`
707with no extra import. Times are absolute nanoseconds since the Unix epoch,
708matching `Time.now()`.
709
710| Function | Purpose |
711| --- | --- |
712| `LibCalendar.rfc3339ToNanos(text)` | Offset-aware RFC 3339 -> nanoseconds (honors `Z` / `±HH:MM`, bare dates) |
713| `LibCalendar.nanosToRfc3339(ns)` | Nanoseconds -> UTC RFC 3339 text (`…Z`), ready for `createEvent` |
714| `LibCalendar.overlaps(aStart, aEnd, bStart, bEnd)` | Half-open interval overlap test |
715| `LibCalendar.isSlotFree(slotStart, slotEnd, busy)` | Slot is free of every `(start, end)` RFC 3339 busy pair |
716
717### `googlecalendar-client` (Calendar REST API v3)
718
719The canonical actor above intentionally implements only upcoming-event listing
720and event creation; for availability/busy times use the FreeBusy helper in §4b.
721For another generated operation, keep bearer authentication and
722`is_replicated = ?false`, then apply the same single-refresh-retry pattern as
723`refreshIfNeeded`.
724
725The generated package also exposes:
726
727| Function | Module | Purpose |
728| --- | --- | --- |
729| `calendar_events_list` | EventsApi | List events on a calendar |
730| `calendar_events_get` | EventsApi | Get an event by id |
731| `calendar_events_insert` | EventsApi | Create an event |
732| `calendar_events_update` | EventsApi | Update an event (PUT) |
733| `calendar_events_patch` | EventsApi | Patch an event (PATCH) |
734| `calendar_events_delete` | EventsApi | Delete an event |
735| `calendar_events_move` | EventsApi | Move an event to another calendar |
736| `calendar_events_quickAdd` | EventsApi | Create event from text ("Lunch at noon") |
737| `calendar_events_instances` | EventsApi | List instances of a recurring event |
738| `calendar_freebusy_query` | FreebusyApi | Check free/busy across calendars |
739| `calendar_calendarList_list` | CalendarListApi | List user's calendars |
740| `calendar_calendarList_get` | CalendarListApi | Get a calendar list entry |
741| `calendar_calendars_get` | CalendarsApi | Get calendar metadata |
742| `calendar_calendars_insert` | CalendarsApi | Create a secondary calendar |
743
744## 6. Cycles and response sizes
745
746The `google-oauth` library uses `Call.httpRequest` from `mo:ic/Call`, which
747auto-computes and attaches the exact required cycles via the
748`ic0.cost_http_request` system API. No manual cycle budgeting is needed
749for token exchange or refresh calls.
750
751For `googlecalendar-client` calls, `defaultConfig.cycles = 30_000_000_000`
752(30B). A typical list/insert costs ~10–15B cycles. Set
753`max_response_bytes = ?2_000_000` for event list reads that may include
754large payloads.
755
756## 7. Things that will bite you
757
758- **`is_replicated = ?false`** — see §3. Non-negotiable.
759- **Google refresh tokens do NOT rotate.** Unlike X/Twitter, Google does
760 not issue a new `refresh_token` on each refresh. Keep the original
761 `refresh_token` and only persist the new `access_token`.
762- **Access tokens expire in 1 hour.** The `refreshIfNeeded` helper catches
763 HTTP 401, silently refreshes via `google-oauth.refreshAccessToken`, and
764 retries once. If the refresh also fails, surface "re-connect your account".
765- **Callback URI exact-match.** Every character (trailing slash, query
766 string, port) must match between the authorize URL and the redirect.
767 Google returns `redirect_uri_mismatch` otherwise. Use the fixed
768 `window.location.origin + "/connect/calendar"` for `redirectUri` — the same
769 value the settings page displays and the `/connect/calendar` route owns — and
770 register that exact URI on the Google Web client. Do not build it from
771 `window.location.pathname`, which varies by page.
772- **Pass the displayed value to `startCalendarOAuth` unchanged — never the raw
773 `*.icp0.io` canister URL.** A Caffeine app is served at several origins (the
774 `*-draft.caffeine.xyz` draft, the `*.caffeine.xyz` live domain, and the raw
775 `<canister-id>.icp0.io` URL). Compute the redirect URI in **one** shared
776 helper (`window.location.origin + "/connect/calendar"`) and use that same
777 helper both for the copyable field on the settings page and for the value
778 handed to `startCalendarOAuth`. If the value sent to Google (via
779 `startCalendarOAuth`) differs from what the settings page showed and the admin
780 registered — e.g. a build-time/config value or the `*.icp0.io` canister origin
781 — Google returns `redirect_uri_mismatch`.
782- **RFC 3339 timestamps.** Calendar uses RFC 3339 strings
783 (`2026-07-10T15:00:00-07:00`). For all-day events set
784 `EventDateTime.date` (`YYYY-MM-DD`) instead of `dateTime`.
785- **`createEvent` times need a zone.** The `dateTime` you pass to `createEvent`
786 MUST carry a UTC offset (`…Z` or `…+02:00`) or you MUST also set
787 `EventDateTime.timeZone` (an IANA name like `"Europe/Zurich"`). A bare
788 `2026-07-10T15:00:00` with neither is rejected by Google. Prefer sending an
789 offset-qualified string so the event lands at the intended wall-clock time.
790- **`calendarId = "primary"`** refers to the authenticated user's default
791 calendar. Named/shared calendars use their calendar-ID (an email-like
792 address).
793- **Availability = FreeBusy, not `events.list`.** For "am I free / busy" use
794 `calendar_freebusy_query` (§4b): one POST returns merged busy intervals with
795 recurrences expanded server-side. Rebuilding availability from `events.list`
796 means paging, expanding recurring events, and merging overlaps by hand — easy
797 to get wrong, and the classic cause of "the booking link shows me free when I'm
798 busy".
799- **`maxAttendees` and `maxResults` must be ≥ 1.** Google rejects `maxAttendees=0`
800 / `maxResults=0` with HTTP 400 (documented minimum is 1). The `listUpcomingEvents`
801 and `createEvent` recipes pass `maxAttendees = 10`; never pass `0` for these on
802 any events endpoint.
803- **FreeBusy responses are keyed by the *resolved* calendar ID, not the string
804 you queried.** When you call `calendar_freebusy_query` for `"primary"`, Google
805 resolves it and returns the `calendars` map keyed by the real calendar ID (the
806 user's email address), **not** the literal `"primary"`. Do **not** look up
807 `"primary"` in the response — that finds nothing and makes every slot look
808 free (a common availability bug). Instead, iterate over **every** calendar the
809 response returns and union all their `busy` intervals, then subtract those
810 from your candidate slots. Parse each interval's `start`/`end` as RFC 3339
811 allowing a trailing `Z` or a numeric offset (`+02:00`); compare instants, not
812 raw strings.
813- **Parse RFC 3339 with `LibCalendar.rfc3339ToNanos` (re-exported from
814 `mo:google-oauth/DateTime`) — do NOT re-implement it.** A hand-rolled parser
815 that forgets to subtract `'0'` (48) per digit reads `"2026"` as `55354`, so
816 every busy interval lands in the wrong year, overlap checks never match, and
817 availability is silently wrong — the code still compiles and never traps, so the
818 bug is invisible until a user is double-booked. Use the tested helper.
819- **HTTP 429 rate-limit.** Surface the error to the caller; never
820 silently retry a write inside the canister — a retry may create a
821 duplicate event.
822- **Don't expose the access token.** `calendarConnections` is read only by
823 `Map.get(calendarConnections, ..., caller)` inside API calls. No
824 `getMyCalendarConnection`, no `getMyAccessToken`, no iterator. A leaked
825 bearer is a per-user account compromise.
826- **`alt = #json`** for all Calendar API v3 calls. Leave optional string
827 parameters `""` and `prettyPrint = false`.
828- **API query parameters are plain positional values, not `?T` — never pass
829 `null` for one.** The client's function parameters are `Text` / `Bool` / enum /
830 `Nat` (e.g. `alt`, `fields`, `prettyPrint`); pass real values like `#json`,
831 `""`, `false`, `10` — `null` will not type-check. (Respect each param's
832 documented minimum: `maxAttendees` / `maxResults` must be ≥ 1, see below.) Only
833 **model** values (`Event`, `EventDateTime`, `FreeBusyRequest`) are optional
834 `?T`.
835- **Combined Gmail + Calendar apps: request the scope union, and learn the
836 address via `OAuth.getUserEmail`.** The union of `openid email` + `.../calendar`
837 + `.../gmail.send` covers availability, sending, and the connected address (via
838 OIDC userinfo) — no `gmail.readonly` needed unless the app actually reads mail.
839 Never drop a scope when merging recipes — see "Combined Gmail + Calendar apps".
840- **Build `Event` / `EventDateTime` with `init {}` then record-update**
841 the fields you need — all fields are optional (`?T`); leave the rest null.
842- **PATCH/PUT/DELETE are forced non-replicated** in the generated client
843 (the `googlecalendar-client` sets `is_replicated = ?false` on these
844 methods automatically). For GET/POST, set it explicitly in your `Config`.
845
846# Frontend
847
848Every build using this skill MUST ship all four items below. (If the app
849**also** uses the Gmail connector, follow "Combined Gmail + Calendar apps" below
850instead — it replaces `/settings/calendar` + `/connect/calendar` with one shared
851`/settings/google` + `/connect/google`. The requirements below still apply; only
852the two paths change.) These are **acceptance criteria, not suggestions** —
853verify each before the build is done. These three are the requirements builds
854skip, and any one missing makes the connector **broken, not merely
855incomplete**:
856
857- **The credentials page exists and is reachable.** The app MUST have the
858 `/settings/calendar` page with Client ID/Secret inputs (item 2), and a signed-in
859 admin MUST be able to reach it — via a nav link or the not-configured prompt on
860 the connect page. A "Connect Google Calendar" button with no page to enter
861 credentials is the most common failure and leaves the connector unusable.
862- **The admin settings page displays the literal, copyable redirect URI.** Not a
863 `<your-domain>` placeholder, not "your app URL + /connect/calendar" as text for
864 the admin to assemble — the actual string
865 `window.location.origin + "/connect/calendar"` rendered in a read-only field
866 the admin can copy. Concretely: an app served from `https://my-app.caffeine.xyz`
867 must show a field containing exactly
868 `https://my-app.caffeine.xyz/connect/calendar` and nothing else. Without it the
869 admin cannot register the URI in Google and every connection fails.
870- **`/connect/calendar` is a real route that handles Google's callback** — not a
871 button-only page. If it falls through to a catch-all/home redirect, or calls
872 `completeCalendarOAuth` before the authenticated actor is ready, the connection
873 silently fails and the app shows "not connected".
874
8751. **A login flow — required.** Calendar cannot work without a non-anonymous
876 caller; the per-user OAuth handshake stores tokens keyed by
877 `caller : Principal`, and the admin credential setter gates on
878 `#admin`. The login flow comes from
879 [`extension-authorization`](../extension-authorization/SKILL.md):
880 `useInternetIdentity`, login/logout buttons, the `useActor` plumbing
881 that injects the authenticated identity into every backend call.
882
8832. **An admin settings page** — `/settings/calendar` (admin-gated). This
884 page is required; a Calendar build is incomplete without it:
885 - Show a "How to get your Google credentials" panel before the credential
886 inputs. Reassure the admin it is a one-time, ~5-minute setup, and walk
887 through these numbered steps (the agent's completion message must repeat
888 the same steps):
889 1. open the [Google Cloud Console](https://console.cloud.google.com) and
890 sign in with any Google account;
891 2. create or pick a project;
892 3. enable the **Google Calendar API** (APIs & Services → Library → search
893 "Google Calendar API" → Enable);
894 4. configure the **OAuth consent screen** (APIs & Services → OAuth consent
895 screen → **External**; set app name, support email, developer email;
896 Google's default scopes are fine);
897 5. create an **OAuth client ID** of type **Web application** (APIs &
898 Services → Credentials → Create Credentials → OAuth client ID);
899 6. under **Authorized redirect URIs**, add the exact value from the
900 copyable field on this page;
901 7. copy the resulting **Client ID** and **Client Secret** into the inputs
902 below and save.
903 Include a convenience link that opens the Google Cloud Console.
904 - Render the actual URI in a read-only, copyable field using one shared
905 helper:
906 `const calendarRedirectUri = () => window.location.origin + "/connect/calendar";`.
907 For example, if the app is open at `https://my-app.caffeine.xyz`, the
908 displayed value is `https://my-app.caffeine.xyz/connect/calendar`. Never
909 show only `<app-domain>` or ask the administrator to infer the URI.
910 - Two password-inputs bound to `setCalendarCredentials(clientId, clientSecret)`.
911 Submit on enter; clear inputs on success.
912 - Status indicator driven by `isCalendarConfigured()` (returns `Bool`).
913 Show "Configured" / "Not configured" — never display the credentials.
914 - **Make this page reachable.** The app's main navigation (the shared Layout)
915 MUST link to this page for admins — show the link when `isCallerAdmin` is
916 true, hide it otherwise (via
917 [`extension-authorization`](../extension-authorization/SKILL.md)). Add that
918 link wherever the nav is defined, not inside this page. A `/settings/calendar`
919 route with no way to reach it is a broken build. Do not rely on the nav
920 alone: the not-configured prompt below is the primary way users discover
921 setup is needed.
922
9233. **A "Connect Calendar" and callback page** — `/connect/calendar` (any
924 signed-in user). This dedicated page must catch and handle Google's redirect
925 after consent; it is not only a page with a connect button:
926 - **Handle the not-configured case for everyone.** `isCalendarConfigured()` is
927 a public query (any signed-in user may call it). When it returns `false`, do
928 not show a dead connect button. Admins see a link to `/settings/calendar` to
929 enter credentials. Non-admins must see an explanation, not a dead end — e.g.
930 "Google Calendar isn't set up yet — the app's administrator needs to add
931 Google credentials in Settings." Enable the "Connect Google Calendar" button
932 only once configured.
933 - "Connect Google Calendar" button bound to
934 `startCalendarOAuth(calendarRedirectUri())`. Redirect the browser to the
935 URL returned by the canister. Do not derive the callback from an
936 arbitrary current pathname; the fixed `/connect/calendar` route and the
937 settings-page URI must be identical.
938 - Register `/connect/calendar` as a real application route. It must catch
939 the Google callback and must not fall through to a catch-all redirect,
940 layout default, or home page before processing it.
941 - On the return leg, read `error`, `code`, and `state` from
942 `URLSearchParams`. If `error` is present, show the failed/declined
943 connection state and do not call the canister. Only when both `code`
944 and `state` are present, call and **await**
945 `completeCalendarOAuth(code, state)` before navigating anywhere or
946 clearing the URL. Keep a visible "Connecting Google Calendar…" state
947 while it is pending. Do not replace the route, redirect to the home
948 page, or discard the query parameters first — that loses the one-time
949 code and leaves the user disconnected.
950 - **Wait for actor readiness before the one-time callback call.** The page
951 must wait for `useInternetIdentity().isAuthenticated` and
952 `useActor(createActor)` to provide a non-null, non-fetching actor before
953 calling `completeCalendarOAuth`. Do not set a `startedRef`/one-shot guard
954 until then: on first render the actor is often unavailable, and an
955 "Actor not ready" failure otherwise consumes the only retry while the
956 authorization code is still in the URL.
957 - After either terminal path, call `history.replaceState` to remove the
958 OAuth query parameters. This prevents a page refresh from reusing a
959 one-time authorization code.
960 - Status driven by `isMyCalendarConnected()` (returns `Bool`).
961 - Optional "Disconnect Calendar" button bound to `disconnectMyCalendar()`.
962
9634. **Calendar UI** — the main page shows upcoming events. When
964 `isCalendarConfigured()` is `false` and the caller is an admin, render a
965 "Set up Google Calendar" link to `/settings/calendar` so the credentials
966 page is discoverable, not just reachable. Pass the current
967 time as the RFC 3339 `timeMin` value, `""` for an open-ended `timeMax`:
968 `listUpcomingEvents(new Date().toISOString(), "", 10)`. To bound a single day
969 (e.g. "meetings tomorrow"), pass both — the local start of the day and the
970 start of the next day, each RFC 3339 with an offset — and count only entries
971 whose `isAllDay` is false and `transparency` is not `"transparent"` and
972 `eventType` is `"default"` (that filters out all-day, free, out-of-office,
973 and working-location markers). This is required when
974 using `singleEvents = true` and `orderBy = startTime`. Also include a
975 "create event" form. `datetime-local` values have no offset, so convert
976 each browser-local value to an RFC 3339 instant before calling the actor:
977 `createEvent(summary, new Date(startInput).toISOString(),
978 new Date(endInput).toISOString())`.
979 When `isMyCalendarConnected()` is `false`, render an inline
980 "Connect Google Calendar" link to `/connect/calendar`.
981
982Suggested route layout:
983
984```
985/ → Main UI (upcoming events + create form)
986/settings/calendar → Admin credential config (admin-only)
987/connect/calendar → Per-user OAuth handshake (any signed-in user)
988# If the app ALSO uses Gmail: drop the two routes above and use a single
989# /settings/google + /connect/google — see "Combined Gmail + Calendar apps".
990```
991
992## Combined Gmail + Calendar apps
993
994When an app uses both connectors, build **one** shared Google connection, not
995two (an auth code is single-use, so two flows would force two consent screens).
996Frontend:
997
998- **One admin page `/settings/google`** — a single Client ID / Client Secret
999 form, one `isGoogleConfigured` status, and one copyable redirect-URI field
1000 showing exactly `window.location.origin + "/connect/google"`.
1001- **One connect route `/connect/google`** — the same real callback route the
1002 Frontend section above requires: it renders "Connect Google", catches the
1003 redirect, waits for actor readiness, then calls completion once. No second
1004 callback route.
1005- **Do NOT build** `/settings/gmail`, `/connect/gmail`, `/settings/calendar`, or
1006 `/connect/calendar`. Every other Frontend requirement above still applies —
1007 only these paths change.
1008
1009Backend — write the shared flow **once** (it replaces both per-connector OAuth
1010flows). It is the same shape as the per-connector `startAuthorize` /
1011`exchangeCode` / refresh functions, with these exact differences:
1012
1013- One `#admin`-gated config setter storing a single Client ID/Secret.
1014- `SCOPES` = the union below — both APIs in one consent.
1015- `completeGoogleOAuth(code, state)` learns the connected email via
1016 `OAuth.getUserEmail` (OIDC userinfo — needs only `openid email`, not
1017 `gmail.readonly`) and stores one connection
1018 `{ accessToken; refreshToken; emailAddress }` in a single
1019 `Map<Principal, GoogleConnection>`.
1020- Gmail sends and Calendar calls each build **their own** client `Config` from
1021 that one `accessToken`, each keeping its single-refresh-on-401 retry.
1022- Keep the connection and client config in **one** shared state value and pass it
1023 as a parameter to both the Gmail and Calendar mixins, so both read and write the
1024 same connection (see the `writing-motoko` mixins rule).
1025
1026```motoko filepath=src/backend/google.mo
1027let SCOPES : Text =
1028 "openid email " // learn the address via userinfo
1029 # "https://www.googleapis.com/auth/gmail.send "
1030 # "https://www.googleapis.com/auth/calendar";
1031// Add "https://www.googleapis.com/auth/gmail.readonly " ONLY if the app reads mail.
1032```
1033
1034Wire it as **one** connection shared by both services — declare the config,
1035connection map, and pending-flow map once and pass the **same** bindings to
1036every mixin. The Gmail and Calendar messaging mixins do **not** declare their own
1037config or connection; they receive the shared `googleConfig` and
1038`googleConnections` (config is needed for the refresh-on-401 retry):
1039
1040```motoko filepath=src/backend/main.mo
1041actor {
1042 let accessControlState : AccessControl.AccessControlState;
1043 include MixinAuthorization(accessControlState, null);
1044
1045 // ONE shared credential + connection state for both services.
1046 let googleConfig : { var clientId : Text; var clientSecret : Text };
1047 let googleConnections : Map.Map<Principal, Google.Connection>;
1048 let pendingGoogleFlows : Map.Map<Principal, Google.PendingOAuth>;
1049
1050 include MixinGoogleConfig(accessControlState, googleConfig); // setGoogleCredentials / isGoogleConfigured (#admin-gated setter)
1051 include MixinGoogleOAuth(googleConfig, googleConnections, pendingGoogleFlows); // startGoogleOAuth / completeGoogleOAuth, SCOPES = union above
1052 include MixinGmailMessaging(googleConfig, googleConnections); // sendEmail — refresh-on-401 needs config; reads the shared connection
1053 include MixinCalendarMessaging(googleConfig, googleConnections); // calendar calls — same shared config + connection
1054};
1055```
1056
1057This variant's migration chain head replaces the per-connector one — note the
1058shared connection carries `emailAddress`:
1059
1060<!-- motoko-check:skip -->
1061```motoko
1062import Map "mo:core/Map";
1063import AccessControl "mo:caffeineai-authorization/access-control";
1064
1065module {
1066 type Connection = {
1067 accessToken : Text;
1068 refreshToken : Text;
1069 emailAddress : Text;
1070 };
1071
1072 type PendingOAuth = {
1073 codeVerifier : Text;
1074 redirectUri : Text;
1075 state : Text;
1076 };
1077
1078 type NewActor = {
1079 accessControlState : AccessControl.AccessControlState;
1080 googleConfig : { var clientId : Text; var clientSecret : Text };
1081 googleConnections : Map.Map<Principal, Connection>;
1082 pendingGoogleFlows : Map.Map<Principal, PendingOAuth>;
1083 };
1084
1085 public func migration(_old : {}) : NewActor {
1086 {
1087 accessControlState = AccessControl.initState();
1088 googleConfig = { var clientId = ""; var clientSecret = "" };
1089 googleConnections = Map.empty<Principal, Connection>();
1090 pendingGoogleFlows = Map.empty<Principal, PendingOAuth>();
1091 };
1092 };
1093};
1094```
1095
1096Do not give Gmail and Calendar separate config/connection state or separate
1097OAuth flows — one auth code is single-use, and separate state desyncs (see the
1098`writing-motoko` mixins rule).
1099
1100Enable both APIs on the one OAuth client and register only the single
1101`.../connect/google` redirect URI. Split into two separate panels **only** if
1102the user explicitly asks to connect two different Google accounts.
1103
1104## Common to all variants
1105
1106- **Sign-in is required** for every Calendar-related route. Wire the
1107 `/settings/...` and the connect route (`/connect/calendar`, or
1108 `/connect/google` in a combined app) through
1109 [`extension-authorization`](../extension-authorization/SKILL.md)'s
1110 auth guard (`useInternetIdentity` + redirect when `!isAuthenticated`).
1111- **The frontend never persists tokens.** No `localStorage`, no
1112 `IndexedDB`, no cookies — the canister mediates everything. The browser
1113 only ever sees `Bool` status flags and the OAuth redirect URLs.
1114- **The OAuth `state` parameter is canister-generated and validated.** The
1115 canister stores a random nonce with the pending verifier and callback URI.
1116 The frontend must pass both `code` and `state` to the completion call
1117 (`completeCalendarOAuth`, or `completeGoogleOAuth` in a combined app);
1118 it never creates or modifies either value.
1119- **The calendar UI is trivial:** a list of upcoming events, a create-event
1120 form with summary + start/end datetime inputs. No client-side Google SDK,
1121 no token handling, no JSON serialization — the canister is the Calendar client.
1122
1123## Related
1124
1125- [`mops add googlecalendar-client@0.1.4`](https://mops.one/googlecalendar-client) — Calendar REST API v3 bindings.
1126- [`mops add google-oauth@0.2.1`](https://mops.one/google-oauth) — Google OAuth 2.0 library (token exchange, refresh, PKCE, `getUserEmail` userinfo, `DateTime` RFC 3339 helpers).
1127- [Google OAuth 2.0 for Web Server Applications](https://developers.google.com/identity/protocols/oauth2/web-server) — Web-client redirect URI and authorization-code flow reference.
1128- [Google Calendar API v3 reference](https://developers.google.com/calendar/api/v3/reference) — what `googlecalendar-client` wraps.
1129- [RFC 7636 — Proof Key for Code Exchange](https://datatracker.ietf.org/doc/html/rfc7636) — PKCE spec.
1130- [extension-authorization](../extension-authorization/SKILL.md) — **required prerequisite**. Provides Internet Identity login, `useInternetIdentity` / `useActor` frontend plumbing, and the `#admin` role gate.
1131- [connector-googlemail](../connector-googlemail/SKILL.md) — sister connector using the same `google-oauth` library for Gmail.