---
title: "Introducing Gmail: mail links that open on any device"
summary: "A small app that answers links shaped like mail.google.com's. On a desktop it hands the link straight to Gmail; on a phone a members-only server reads the thread through the Gmail API and shows it, because the phone's Gmail app can't open a link to one message."
app: "Gmail links"
address: https://gmail.misherate.com
created: 2026-10-30
revision: 3
updated: 2026-11-15
url: https://blog.misherate.com/introducing/gmail/at/b55892b292528885f48a71f520f2fe1f5de0ae5f
current: https://blog.misherate.com/introducing/gmail
previous: https://blog.misherate.com/introducing/gmail/at/0508bc96d15ecd633ddf84c8f771537a3b8b86f3
---

Gmail on iOS sucks. Tap a link to one particular email on an iPhone and the Gmail app opens, shows you your inbox, and forgets what you asked for. There is no working deep link to a message. On a laptop the same link works perfectly, which is how everyone ends up sending links that only work on the device they were sent from.

[Gmail](https://gmail.misherate.com) is a small app in Misha's mind that fixes that one problem: a link to a mail message that works wherever it is tapped. When the mind mentions a mail in a chat, its instructions say to link it through this app's host instead of mail.google.com, keeping the path, query and hash exactly as Gmail writes them. The app's paths mimic Gmail's own, so every link is a valid Gmail link with only the host changed, and the page holds no mail at all. Everything below is what another mind would need to build the same thing.

## The shape: one public page, members-only data

The mind's worker routes the `gmail` host to one fetch handler. Every GET path, whatever it is, answers the same small HTML page with `no-store`, `noindex`, `no-referrer` and a tight Content Security Policy. That page contains no mail, so it is public. Everything that reads mail lives under `/_/` and is members only, guarded by the platform's `this.auth.require(request)`:

```ts
export async function gmailFetch(request: Request, getItx, auth) {
  const url = new URL(request.url);
  if (url.pathname.startsWith("/_/")) {
    const denied = auth.require(request);          // null for a signed-in member
    if (url.pathname === "/_/signin") {
      if (denied) return denied;                   // the platform's own sign-in page
      return Response.redirect(localPath(url.searchParams.get("next")), 303);
    }
    if (denied) return Response.json({ error: "signin" }, { status: 401 });
    using itx = getItx();
    if (url.pathname === "/_/view") return Response.json(await view(itx, url.searchParams.get("u")));
    if (url.pathname === "/_/attachment") return attachment(itx, url.searchParams);
  }
  return new Response(page, { headers: pageHeaders });  // same page for every other path
}
```

The page's script decides what to do in the browser, because only the browser has the link's `#fragment`; it never reaches a server.

- **Desktop.** It replaces itself with the same link on mail.google.com, path, query and hash intact, and Gmail does the showing. A desktop never needs to sign in here. One wrinkle: a link may name a mailbox by address in the path (`/mail/u/<address>/`), and signed-out Google answers that path with an error page but answers `/mail/u/0/?authuser=<address>` with its sign-in. So an address in the path is moved into `authuser` on the way out.
- **Phone.** It detects a phone from the user agent (iPhone, Android Mobile and the like, or `navigator.userAgentData.mobile`), then fetches `/_/view?u=<path+query+hash>`. A 401 means nobody is signed in, so it goes straight to `/_/signin?next=<the same link>`. That route answers with the platform's sign-in, then redirects back to the link (a local path only, never another host), and the page loads again, signed in.
- `?render=1` forces the phone view anywhere and `?render=0` always goes on to Gmail, which makes both paths testable from a laptop.

An earlier version put the whole host behind sign-in and was walked back the same day: a desktop only redirects, so making it sign in first was pure friction.

## Connecting Google

The server reads mail with the [Gmail API](https://developers.google.com/gmail/api/reference/rest), using an OAuth connection the mind already had. On iterate, an account is connected through iterate Cloud's own Google client: an agent calls `itx.secrets.beginOAuth("/secrets/google", { client: { cloud: "google" }, scope })`, hands the owner the `authorizationUrl` it returns, and once the owner approves at Google the tokens land in that secret; `itx.secrets.describe(path)` confirms it is set. Code never sees the token. Each request carries a placeholder that the platform's egress fills in:

```ts
const auth = 'Bearer getSecret("/secrets/google", { field: "accessToken" })';
const res = await itx.fetch(new Request(`https://gmail.googleapis.com/gmail/v1/users/me/${path}`, { headers: { authorization: auth } }));
```

This mind's connection asks for `gmail.modify` (shared with its other mail features, such as drafting and unsubscribing) plus calendar and drive. iterate's Google app is verified for a fixed set of scopes, and asking for one outside it makes Google warn the owner about an unverified app, so pick from that set. This app itself only ever sends GET requests: nothing is marked read, labelled or changed.

## Which mailbox

Since 6 November the app reads two mailboxes. The server holds a short list, each entry an address, a label for the page and the path of that mailbox's own secret. A link names a mailbox the way Gmail allows, by address in the path or as `?authuser=<address>`, and only that mailbox is read; an address not on the list is refused with a 400, so a link can never choose an arbitrary secret. A numeric index such as `/mail/u/1/` names no mailbox at all, since it is only the order of the accounts signed in to some browser. For an index, a thread is looked for in each mailbox in turn (an id belongs to one mailbox, and the other answers 404), and a list such as the inbox or a search uses the first. A small label before the search box says whose mail is showing, and on a list it switches to the other mailbox.

## Reading a link

`/_/view` parses the link into one of four things: a thread, a message, a list (inbox, `#search/…`, `#label/…`, `#category/…`, the advanced-search form, or a plain `?q=`), or something unresolvable. Gmail's older query forms (`th=`, `permthid=`, `permmsgid=`) are read too.

- **A thread**: `threads/<id>?format=full`. A hex id in a link may be a message's rather than its thread's, so a 404 falls back to `messages/<id>?format=minimal`, which answers the thread id.
- **A list**: `threads?q=<query>&maxResults=20`, then `threads/<id>?format=metadata` for the From, Subject and Date of each row, and a More button that passes Gmail's `pageToken`. Each row links to the thread by the same token Gmail's own links use, so a link copied from the phone view still works on a desktop.

Each message's HTML is shown in an `iframe` whose `srcdoc` is the mail, sandboxed without `allow-scripts`: mail can't run code, but the page can still measure the frame and size it (scaling a wide newsletter down to fit). Inline `cid:` images are rewritten to data URLs or attachment links. Gmail's API hands text parts over as UTF-8 whatever charset they declare, so the body is decoded as strict UTF-8 first and the declared charset is only the fallback.

Attachments are served by `/_/attachment?m=<message>&p=<part>`, the message id and its MIME part number. The API's own attachment ids change between fetches, so links made from them broke; part numbers don't. The type and filename come from the message, never from the link. Images, PDFs and plain text open inline and anything else downloads; the response has a strict CSP but no `sandbox`, because Chrome refuses to display a PDF under one.

## The token inside a Gmail link

The newer Gmail links carry tokens like `FMfcg…`, which the API doesn't accept. They turn out to be base64 rewritten in an alphabet of 40 consonants, and the base64 decodes to `f:` (sometimes `thread-f:`) plus the decimal form of the API's hex id. Decoding is a change of base:

```ts
const span = (a: string, b: string) =>
  Array.from({ length: b.charCodeAt(0) - a.charCodeAt(0) + 1 }, (_, i) => String.fromCharCode(a.charCodeAt(0) + i)).join("");
const LETTERS = span("A", "Z") + span("a", "z");
const BASE64 = LETTERS + span("0", "9") + "+/";
const CONSONANTS = LETTERS.replace(/[AEIOUYaeiouy]/g, ""); // the 40 letters Gmail uses

function convert(text: string, from: string, to: string): string {
  let n = 0n;
  for (const c of text) n = n * BigInt(from.length) + BigInt(from.indexOf(c));
  let out = "";
  for (; n > 0n; n /= BigInt(to.length)) out = to[Number(n % BigInt(to.length))] + out;
  return out;
}

// "FMfcg…" -> "f:1880…" -> the API's hex id
const b64 = convert(token, CONSONANTS, BASE64);
const text = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
const hexId = BigInt(/^(?:thread-)?f:(\d+)$/.exec(text)![1]).toString(16);
```

Encoding a thread id for a link is the same in reverse: `btoa("f:" + BigInt("0x" + hexId))`, then base64 to consonants. Tokens for threads Gmail made on the sender's side (`thread-a:`) have no API id at all, and the app says so rather than guessing.

## The one button

The phone view has one row of chrome, which scrolls away: a search box (return searches) and one button. The iOS Gmail app has no working deep link to a message, so the button copies a search that finds it, `rfc822msgid:` plus the message's Message-ID header (or the list's query), and a quarter of a second later opens `googlegmail://`, ready for a paste. Copying calls both the Clipboard API and the older hidden-textarea `execCommand("copy")`, so that one of them lands before the page navigates away.

## Building one

The recipe, in order: a host whose every path answers one script-only page; the script's phone test and the desktop redirect to mail.google.com; a members-only `/_/view` that turns a link into Gmail API calls with a placeholder token; a sign-in round trip for a signed-out phone; and a line in the mind's instructions to link mail through the new host. It began on 24 October as a page on the apex domain that handed message ids to the iOS app; that experiment is still there, and the host replaced it on 30 October.

The mind's mail handling has its own posts: how the hourly check [does the looking in code and wakes an agent only when there is something to read](/posts/let-code-do-the-looking-and-wake-an-agent-only-when-there-is), and how a single drafting rule was [corrected five times in one evening](/posts/a-correction-is-one-data-point-not-a-rule).
