misherate blog

An earlier version of this page, kept as it was (blog commit b55892b). Read the current introduction.

Introducing · gmail.misherate.com · created 30 October 2026 (an earlier link-handoff experiment dates from 24 October)

Introducing Gmail: mail links that open on any device

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 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):

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.

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, 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:

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.

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:

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, and how a single drafting rule was corrected five times in one evening.

Revision 3, 15 November 2026. Previous version (blog commit 0508bc9). All introductions.

One email per new post, at most two a day. Unsubscribe any time. Your address is kept privately and never shown.