# Signing in with other services: oauth

GitHub, Microsoft, Apple, Discord, GitLab, LinkedIn, Slack, any OpenID
Connect provider by its issuer's address, and a single sign-on connection
for each customer of a B2B product: an [extension](../extensions/README.md)
of ordinary Mote, taken one provider at a time, into the program's own
accounts and sessions. [Google](google.md) is the same flow under its own
package. Beside the sign-ins: a provider's tokens kept sealed for calls to
its API in the person's name (`oauthToken`), and the flows with no browser
(client credentials, the device code). Back to the [map](README.md).

```text
use "pkg:oauth/github.mote"
use "pkg:oauth/microsoft.mote"

column gap=8
  GithubButton
  MicrosoftButton label="Sign in with your work account"
```

```toml
# mote.toml
[packages]
oauth = "../mote/extensions/oauth"
```

Each provider is two settings (its client's id and secret), two routes
(`GET /auth/<name>/start`, `GET /auth/<name>/callback`; Apple's callback is
a `POST` too), a button, three actions (`<name>SignIn`, `<name>SignInTo(route)`,
`<name>Connect`) and three `server fn`s (`<name>ConnectHandle`,
`<name>Profile`, `<name>Disconnect`). No SDK, no code of the provider's.

## The providers

| File | Settings | What is particular to it |
|---|---|---|
| `github.mote` | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`; `GITHUB_URL`, `GITHUB_API` for Enterprise Server | Not OpenID Connect: who someone is comes from `/user`, their address from `/user/emails`, **the one GitHub marks primary, only if it is verified**. |
| `microsoft.mote` | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`; `MICROSOFT_TENANT` (`common` unset, `organizations`, `consumers`, an id), `MICROSOFT_TENANTS`, `MICROSOFT_TRUSTED_TENANTS`, `MICROSOFT_AUTHORITY` | [Below](#microsoft-tenants-and-addresses). |
| `apple.mote` | `APPLE_CLIENT_ID` (the Services ID), `APPLE_TEAM_ID`, `APPLE_KEY_ID`, `APPLE_PRIVATE_KEY` (the `.p8`, a secret) | The client secret is an ES256 token made from the key for each sign-in; the browser comes back with a form it posts, so the sign-in's cookie is `SameSite=None; Secure` and **the site must be on https**; the name is in that form the first time only; `email_verified` may be the text `"true"`. No PKCE is sent. |
| `discord.mote` | `DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET` | Not OpenID Connect: `/users/@me`, the address only when `verified`. |
| `gitlab.mote` | `GITLAB_CLIENT_ID`, `GITLAB_CLIENT_SECRET`; `GITLAB_URL` for a GitLab of your own, `GITLAB_HOME` | OpenID Connect at the instance. |
| `linkedin.mote` | `LINKEDIN_CLIENT_ID`, `LINKEDIN_CLIENT_SECRET` | OpenID Connect; no PKCE is sent. |
| `slack.mote` | `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET`; `SLACK_TEAM` (workspaces' ids) | Its token endpoint answers 200 to a code it refused, with `ok: false`: a no. A workspace is checked by the token's `https://slack.com/team_id`. |
| `issuer.mote` | `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`; `OIDC_LABEL`, `OIDC_DOMAINS`, `OIDC_SCOPE` | Any OpenID provider by its issuer (Okta, Auth0, Keycloak, Cognito, Entra for one tenant): everything read from its discovery document. Routes `/auth/oidc/…`, `OidcButton`. |
| `sso.mote` | `OAUTH_TOKEN_KEY` (the connections' secrets are sealed) | [A connection for each customer](#single-sign-on-for-each-customer). |

Every provider also takes `<NAME>_REDIRECT` (the whole callback address, as
registered: **set it in production**, as [google.md](google.md#behind-a-proxy)
explains), `<NAME>_LINK=ask` and, where it has an API worth calling,
`<NAME>_KEEP=1` with `<NAME>_SCOPES` (below). Unset, the button leads to a
page that says the sign-in is not set up.

## Whose account it is

The rules are [Google's](google.md#whose-account-it-is), for every provider,
and they are careful on purpose:

- A person is known by the provider's id for them (`sub`), never by their
  address. Only an address the provider says it **verified** is taken; any
  other is refused, with why.
- An account that is already here is joined on a provider's word **only
  for an address that provider is the mail service of** (Google: gmail.com
  and Workspace domains; Microsoft: outlook.com, hotmail.com, live.com,
  msn.com and trusted tenants; Apple: icloud.com, me.com, mac.com and its
  relay addresses; a connection: its customer's domains). GitHub, Discord,
  LinkedIn, Slack and GitLab are the mail service of nothing: a person
  whose address has an account here signs in the way they did and presses
  "Connect". An account whose address was never verified that is joined
  loses its password and its sessions.
- One person at a provider for an account, one account for a person there.
- `oauthMay(who)` is the program's say for every provider (`who.provider`
  says which), as `googleMay` is for Google:

```text
fn oauthMay(who: OidcWho): bool
  if who.provider == "github" && !Invited.has({email: who.email})? fail("Ask for an invitation first.")?
  return true
```

## Microsoft: tenants and addresses

- **The `common` issuer.** With `common` or `organizations` the discovery
  document's issuer is `https://login.microsoftonline.com/{tenantid}/v2.0`.
  A token's `iss` is taken only when it is that with the token's own `tid`
  in it, and `tid` is a tenant's id: a token of one tenant cannot pass as
  another's. `MICROSOFT_TENANTS` then says which tenants may come in at all.
- **Work addresses are not verified.** The `email` of a work or school
  account is whatever that tenant's admin typed. Taking it on its word would
  let the admin of any tenant into anyone's account here (the attack known
  as "nOAuth"). It is taken as verified only when Microsoft says the tenant
  owns the domain (the optional claim `xms_edov`: add it under the app
  registration's "Token configuration"), for a personal account (the
  consumer tenant `9188040d-6c67-4c5b-b112-36a304b66dad`), or for a tenant
  the program lists in `MICROSOFT_TRUSTED_TENANTS` (its customers'). Anyone
  else is refused and told why.

## Single sign-on for each customer

`sso.mote` keeps a connection for each customer in a model, `OauthIssuer`,
which the program's admins fill through fns of the program's own:

```text
use "pkg:oauth/sso.mote"

rule admin = me.email in setting.list("SHOP_ADMINS")

server fn addSso(given: SsoGiven): SsoConnection requires admin && secondFactor(10)
  return ssoAdd(given)?

// The sign-in page asks the address first, and sends people of a customer's domain to their own provider.
action next(email: string)
  ssoSignIn(email)
```

- `ssoAdd({name, label, issuer, client, secret, domains})` reads the
  issuer's discovery document before it keeps anything, and refuses a
  document whose `issuer` is another; the client's secret is sealed with
  `OAUTH_TOKEN_KEY`. `ssoList()`, `ssoSwitch(name, on)`, `ssoRemove(name)`.
- The routes are `/auth/sso/<name>/start` and `/auth/sso/<name>/callback`
  (register that one at the customer's provider); `ssoFor(email)` and the
  `server fn ssoWhere(email)` find the connection of an address's domain.
- **`domains`** are the mail domains the customer owns. A connection with
  them signs in people of those domains only: the customer's admin can make
  a user with anyone's address at their own provider, and that is not the
  customer's to vouch for. It is also what lets an account here with such an
  address be joined on the provider's word. The program says the customer
  owns them (a DNS record it checked, a contract): this file takes its word.

## Tokens kept for a provider's API

```text
use "pkg:oauth/github.mote"
use "pkg:oauth/tokens.mote"      // GITHUB_KEEP=1 GITHUB_SCOPES=repo OAUTH_TOKEN_KEY=…

server fn repos(): json requires signedIn
  let answer = oauthCall(githubProvider(), auth.me()?.id ?? "", "GET", "https://api.github.com/user/repos", none)?
  return answer.json
```

| | |
|---|---|
| `oauthToken(provider, user)` | An access token good for a minute more at least: the one kept, or a new one by the refresh token. Fails with the kind `"connect"` when there is none, or the provider refused the refresh (the person took the access back): they connect again. `"offline"` when it cannot be reached. |
| `oauthCall(provider, user, method, address, body)` | `net.send` with that token as a bearer; a `401` gets a new token and is asked once more. |
| `oauthUserinfo(provider, user)` | What an OpenID provider's userinfo endpoint says now. |
| `oauthConnected(provider, user)` | `{scope, until, refreshes, at}`, or none. Nothing that is a token. |
| `oauthRevoke(provider, user)` | Takes the access back at the provider (RFC 7009, the refresh token; GitHub's own API) and forgets the tokens. |
| `wants fn oauthRevoked(provider, user, why)` | Told when a grant is gone: `"revoked"`, or `"refused"` (the refresh was). |

- Tokens are kept in `OauthGrant`, **sealed** with `OAUTH_TOKEN_KEY`
  ([`crypto.seal`](data.md#crypto), AES-256-GCM) and bound to their row: a
  sealed token copied into another person's row does not open there.
- **One refresh at a time** for a grant: whoever refreshes takes the row's
  turn first; another call at the same moment waits for what it gets
  instead of spending the same refresh token (providers that turn refresh
  tokens over, Microsoft's and Xero's, would refuse the second and the grant
  would be lost). A refresh token the provider turns over is kept as the new
  one.
- Google gives a refresh token only when asked for offline access and
  consent: `GOOGLE_KEEP=1` asks for both, and the `pkg:google/tokens.mote`
  file is this one by Google's package's name.
- `<name>Disconnect()` takes a provider away from someone signed in: its
  link, and its tokens, taken back. It is refused for an account's only way
  in unless the program's `oauthMayDisconnect(provider, user)` says there is
  another (a password it let them set).

## With no browser: machine.mote

| | |
|---|---|
| `oauthClientToken(provider, scope, audience)` | A token for the back end itself (client credentials, RFC 6749 4.4), kept sealed while it is good: Graph with `https://graph.microsoft.com/.default`, an Auth0 API by its audience. |
| `oauthDeviceBegin(provider, user)` | A device sign-in (RFC 8628) for an account, or `"app"`: `{handle, code, uri, complete, every, until}` to show. |
| `oauthDevicePoll(provider, handle)` | `{state, words}`: `"waiting"` (and asking sooner than the provider's interval is answered so without asking), `"done"` (the tokens are kept, for `oauthToken(provider, user)`), `"denied"`, `"expired"`. `slow_down` is honoured, and GitHub's "pending" that comes with a 200. |

## What is checked, and the hostile cases tested

The flow is [Google's](google.md#what-happens): PKCE (S256), `state` and
`nonce`, a sign-in good for ten minutes and once, tied to the browser that
began it by a cookie only its two addresses see. An id token is checked by
[`crypto.jwt.verify`](data.md#signatures-with-a-key-pair) against the
provider's published keys (kept as long as the provider says, fetched again
at most once a minute for a key not among them: rotation), then claim by
claim. Tested, by `tests/all.sh`:

| Run | |
|---|---|
| `real_google_hostile` | Through the routes and a pretend provider: a token for another audience, another issuer, ended, another nonce, no `sub`, unsigned (`alg: none`), HS256 under the public key, an unpublished key; the state missing, wrong, another browser's, used twice; a code used twice and brought to another sign-in; an unverified address; one person there for two accounts; logs with no code, token, state or secret. |
| `real_oauth_flows` | GitHub (its API, an unverified primary address), Microsoft (a trusted tenant; an untrusted tenant's typed address; a `tid` that is not its issuer's), a callback opened in another browser, a code brought to another sign-in, a wrong state; Google's tokens refreshed, turned over and revoked. |
| `real_oauth` | `mote test` of every provider's quirks, sealing, refreshing, rotation, a refused refresh, revocation, client credentials, the device code, connections and their domains. |
| `real_identity_vectors` | The signatures and tokens themselves, against RFC 7515, RFC 8037 and OpenSSL. |

## Not yet met the real providers

**Nothing here has signed in to GitHub, Microsoft, Apple, Discord, GitLab,
LinkedIn, Slack, Okta, Auth0, Keycloak or Cognito.** Every endpoint is
written from what each provider documented as of 2026, by something that
could not fetch their documents, and every test is against stand-ins. Where
an address was not certain it is a setting. To check one with a real client:

1. Register a client at the provider, with the redirect URI
   `https://<your site>/auth/<name>/callback` (for `mote dev`,
   `http://localhost:4870/auth/<name>/callback`; Apple takes only https:
   use a tunnel).
2. Start the back end with its settings and `<NAME>_REDIRECT` set to that
   address, press the button, sign in, and see `<name>Profile()` give the
   address you have there.
3. Check each in the log (`warn` lines say why a sign-in was refused):
   - **GitHub**: a primary address that is verified signs in; make the
     primary one unverified and it is refused. `GITHUB_KEEP=1
     GITHUB_SCOPES=repo`, then `oauthToken(githubProvider(), user)` lists
     repositories. GitHub's PKCE support was uncertain when this was written:
     if the token endpoint refuses the verifier, say so.
   - **Microsoft**: with `MICROSOFT_TENANT` unset, a personal account and a
     work account; the work one is refused until `xms_edov` is added in
     "Token configuration" or its tenant is in `MICROSOFT_TRUSTED_TENANTS`.
     Compare the discovery document at
     `https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration`.
   - **Apple**: over https only; the first sign-in shows the name, the
     second does not and it stays. Check that the token endpoint takes the
     client secret (an `invalid_client` means the team, key id or Services
     ID is wrong). Whether Apple takes PKCE was not certain: none is sent.
   - **Discord, GitLab, LinkedIn, Slack**: an address that is verified
     there signs in; Slack with `SLACK_TEAM` set refuses another workspace.
     LinkedIn's issuer (`https://www.linkedin.com/oauth`) and its keys'
     address were the least certain: compare its discovery document,
     `https://www.linkedin.com/oauth/.well-known/openid-configuration`.
   - **An issuer** (Okta, Auth0, Keycloak, Cognito): `OIDC_ISSUER` exactly
     as the discovery document's `issuer` says (Auth0's ends in `/`).
   - **Refresh tokens**: set a short access-token lifetime at the provider,
     call `oauthToken` twice across it, and see one refresh in the log.

## In the source

`extensions/oauth/`: `oauth.mote` (the flow, the linking rules, the
models), one file a provider, `tokens.mote`, `machine.mote`, `sso.mote`,
`issuer.mote`, `tests.mote`. The pretend provider is
`tests/google_fakeidp.mjs`; the runs are named above. Not here, on purpose:
SAML and SCIM ([saml.md](saml.md) says why, and what a product loses);
"sign in with" one Mote app to another.
