Skip to content
DigitalVantagePublic

About

Two-way Google Calendar and Microsoft 365 sync so you never get double-booked. Zero dependencies, no database, no webhooks.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

calsync

CI License: MIT Node

Two-way sync between Google Calendar and Microsoft 365. Zero production dependencies, zero database, zero webhooks.

It has exactly one goal: never get double-booked. Copies on the other side are empty busy blocks — no attendees, no meeting links, no title by default.

How it works

Every copy carries a marker in its description: [dvsync1:<source-key>:<content-hash>]. The entire state is rebuilt from those markers on every run — there is no state file and no database. Delete the container, move it to another host, start from scratch; nothing gets duplicated.

The marker also solves the feedback loop: an event carrying a marker is never copied back.

Do not edit or duplicate a copy. The marker lives in a field you can edit, and it is trusted in both directions. Strip it and the copy is orphaned: a replacement gets created, and the leftover — now indistinguishable from a real event — starts syncing back to the other side. Duplicate a copy to turn it into a real meeting and the duplicate inherits the marker, so the next pass adopts it and deletes it as a stray. Both are the price of keeping all state in the copies themselves; moving the marker somewhere the calendar UI cannot reach is on the roadmap in TODO.md.

Recurring series are not mapped one-to-one. Google expands them via singleEvents=true and Graph via calendarView, so both sides hand back ready instances. No RRULE logic anywhere. The source key includes the start date precisely because every instance of a series shares one iCalUID.

src/
  config.js   environment validation (pure function)
  app.js      wiring: tokens -> adapters
  http.js     the one place that knows about retries
  tokens.js   access token cache + refresh token rotation
  store.js    the only on-disk state: rotated tokens
  marker.js   marker, source key, content hash
  google.js   Google Calendar API v3 adapter
  graph.js    Microsoft Graph adapter
  sync.js     the core - knows nothing about HTTP or which side is which
bin/
  calsync.js  entrypoint: loop, signals, exit codes
  auth.js     one-off OAuth bootstrap

Google setup

  1. Google Cloud Console → new project → enable Google Calendar API
  2. OAuth consent screen → User Type: Internal
  3. Credentials → Create OAuth client ID → type Desktop app → the client ID and secret go into GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET
  4. npm run auth:google → open the link → paste GOOGLE_REFRESH_TOKEN into .env

The bootstrap receives Google's redirect on http://localhost:8642. If that port is taken, set AUTH_PORT — a Desktop app client accepts any loopback port, so nothing needs registering on Google's side.

Pick Internal if you possibly can. An External app left in Testing status gets refresh tokens that expire after 7 days — the sync will break every week with invalid_grant. Internal is only available to Workspace accounts and requires no app verification.

If the GCP project belongs to someone else's organization and you cannot create your own, you are stuck with External + Testing and a monthly... make that weekly, token refresh.

Scope: calendar.events — that is all you need to read and write events.

Microsoft setup

  1. Entra ID → App registrations → New registration → Accounts in any organizational directory → the Application (client) ID goes into MS_CLIENT_ID
  2. Authentication → Add platform → Mobile and desktop applications → check https://login.microsoftonline.com/common/oauth2/nativeclient, and set Allow public client flows: Yes
  3. API permissions → Microsoft Graph → Delegated → Calendars.ReadWrite (+ offline_access)
  4. npm run auth:ms → device code → paste MS_REFRESH_TOKEN into .env

If the tenant is yours, put its ID in MS_TENANT instead of common.

Some tenants have user consent for applications disabled. The bootstrap then ends with a message about required administrator approval, and you have to ask an admin to approve the registration.

First run

cp .env.example .env      # fill it in
set -a; source .env; set +a

WINDOW_FUTURE_DAYS=14 npm run dry     # see what it would do
WINDOW_FUTURE_DAYS=14 npm start       # narrow window, for real
npm start                             # full window

Start with npm run dry and a narrow window. Undoing a few hundred duplicated events by hand is miserable.

Deploying on Coolify

docker build -t calsync .
docker run -d --env-file .env -v calsync-data:/app/data --restart unless-stopped calsync

INTERVAL_MINUTES=5 makes the container run in a loop with a healthcheck based on the timestamp of the last pass. Set 0 if you would rather drive it from cron — the container then does a single pass and exits.

The /app/data volume is not optional. Microsoft returns a new refresh token on every refresh; calsync stores it and keeps using it. Without the volume, authorization stops working once the original token's idle period elapses, and you get to repeat the bootstrap.

The volume has to be writable by UID 1000. The container runs as the non-root node user, and a mount placed over /app/data brings its own ownership with it — the chown in the Dockerfile does not apply to it. A host directory created by root produces EACCES and the rotated token is lost on every restart, with a warning in the log as the only sign. Use a named Docker volume, which inherits ownership from the image, or chown -R 1000:1000 the host directory.

The heartbeat deliberately does not live on that volume: the image sets HEARTBEAT_FILE=/tmp/calsync-heartbeat. It is evidence about the loop running right now, and a file surviving a restart would let a fresh container inherit its predecessor's proof of life — reporting healthy before completing a single pass. It also keeps the healthcheck measuring whether the sync is alive rather than whether a mounted volume happens to be writable.

docker run --env-file does not support trailing comments — it takes the rest of the line as the value. That is why comments in .env.example sit on their own lines. Numbers, booleans and enumerations (INTERVAL_MINUTES, DRY_RUN, DIRECTIONS, …) reject the mangled value with a readable error. Free-text settings — BUSY_TITLE, GOOGLE_CALENDAR_ID, MS_TENANT, TOKEN_STORE, HEARTBEAT_FILE — cannot tell a comment from a legitimate value and will take it literally, so keep those comments on their own lines.

Settings

Variable Default Notes
COPY_TITLES false false = copies are titled with BUSY_TITLE. Enable only if you really want the content on both sides
BUSY_TITLE Busy Title used for copies when COPY_TITLES=false. Changing it retitles every existing copy on the next pass
SKIP_ALL_DAY true All-day events are skipped — otherwise one side's vacation blocks whole days on the other
DIRECTIONS both g2o or o2g for one-way sync
WINDOW_PAST_DAYS 7 Nothing outside the window is read, so nothing outside it is ever cleaned up — see below before narrowing it
WINDOW_FUTURE_DAYS 180 Same as above
INTERVAL_MINUTES 0 0 = single pass (cron). The Docker image defaults to 5
MAX_DELETES_PER_RUN 25 Delete guard — see below. 0 disables it
GOOGLE_CALENDAR_ID primary See "Write to the default calendar"
TOKEN_STORE data/tokens.json Empty value disables persisting rotated tokens
HEARTBEAT_FILE data/heartbeat Read by the container healthcheck. The Docker image overrides it to /tmp/calsync-heartbeat, off the persistent volume
LOG_LEVEL info error | warn | info | debug
HTTP_RETRIES 4 Retries on 429/5xx, honoring Retry-After
DRY_RUN false Same as --dry-run

The sync window

Every pass reads both calendars over one window: WINDOW_PAST_DAYS back and WINDOW_FUTURE_DAYS forward. Nothing outside it is read, which means nothing outside it is copied — and, just as importantly, nothing outside it is ever cleaned up. A copy sits at the same time as its source, so the two leave the window together and the copy becomes invisible to every later pass.

Narrowing the window strands copies. Going from 365 days to 180 leaves the copies between day 180 and day 365 behind for good: delete their sources and the busy blocks stay on the calendar forever, with nothing left to remove them. Widen the window back and the next pass picks them up again — that is the way out. Widening is always safe.

Delete guard

A bad token, a typo in GOOGLE_CALENDAR_ID, or an empty API response all look exactly like "the user deleted everything" from the program's point of view. So a run holds back deletions when either:

  • there are more copies to delete than MAX_DELETES_PER_RUN, or
  • the source calendar returned zero events.

Creates and updates proceed normally, deletions are skipped, and the log gets a DELETIONS HELD BACK line with the reason. In single-pass mode the process then exits with code 2.

Side effect: if the source calendar genuinely is empty across the whole window, orphaned copies stay. Raise the limit or set MAX_DELETES_PER_RUN=0.

What it doesn't do

  • All-day events — skipped by default. Support is implemented (SKIP_ALL_DAY=false), but then one side's vacation blocks whole days on the other. Time zones outside UTC−12..+12 are not supported for all-day events.
  • Attachments, attendees, meeting links — deliberately not copied. A copy is an empty busy block; carrying the attendee list over would mean sending a second invitation from a second address.
  • Webhooks — polling every 5 minutes instead of push. Webhooks need a public endpoint and Graph subscription renewal every ~3 days. Not worth it for two calendars.
  • More than two calendars — the structure allows it (the core operates on adapters), but nothing has been written in that direction.

Important: write to the default calendar

GOOGLE_CALENDAR_ID=primary and Graph's default calendar are not an accident. The free/busy status other people see is computed only from the default calendar. Copies parked in a separate "Google (sync)" calendar look tidier but do not protect against double-booking — which is to say, they do not do the one thing this exists for.

Tests

npm test

Built-in node:test, no dependencies. The sync core is tested against fake adapters, and test/integration.test.js runs the whole flow through a fake of both APIs — including the case "a copy created in one pass must be recognized in the next".

Exit codes

Code Meaning
0 Pass completed
1 Configuration, authorization, or API error
2 Pass completed, but the guard held back deletions

Contributing

Issues and PRs welcome.

License

MIT — Digital Vantage. Do whatever you want with it; we'd love to hear if you ship something cool on top.

Maintainer

Digital Vantage — partnerstwo technologiczne dla firm B2B w Polsce.

If you need a partner to build, integrate or maintain systems like this — get in touch.

About

Two-way Google Calendar and Microsoft 365 sync so you never get double-booked. Zero dependencies, no database, no webhooks.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages