# Continue with Google

Signing in with a Google account, beside email and password or in place of
it. An [extension](../extensions/README.md): ordinary Mote in a package,
taken with one `use`. Whoever comes back from Google is signed in to the
same accounts and sessions as [`auth.signIn`](back-end.md#signing-in)
gives, so nothing else in the program changes: `auth.me()`, `me`, rules,
`requires signedIn`, [shared accounts](back-end.md#accounts-several-apps-share),
`auth.signOut`. Back to the [map](README.md).

```mote
use "pkg:google/google.mote"

state who = "nobody"
task whoAmI
  who = (auth.me() else none)?.email ?? "nobody"

column gap=8 padding=16
  text `Signed in: ${who}`
  GoogleButton
```

```toml
# mote.toml, beside the entry
[packages]
google = "../mote/extensions/google"
```

```sh
GOOGLE_CLIENT_ID=1234-abc.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=… bun dist/server/main.js
```

A package line, a `use`, two settings and a button. The page is loaded
again when the person comes back, so a `task` that asks `auth.me()` (as any
page that signs people in has) finds them.

## At Google

Once, in the [Google Cloud console](https://console.cloud.google.com/),
under "APIs & Services":

1. Make a project for the app, or choose one.
2. "OAuth consent screen": say what the app is called and who may use it
   (anyone with a Google account, or only people of your own Workspace).
   The scopes asked for are `openid`, `email` and `profile`: who the person
   is, and nothing of theirs.
3. "Credentials", "Create credentials", "OAuth client ID", of the type
   **Web application**.
4. Under "Authorized redirect URIs" enter the site's address followed by
   `/auth/google/callback`, exactly as people reach it:
   `https://shop.example/auth/google/callback`. For `mote dev`, also
   `http://localhost:4870/auth/google/callback`. Nothing need be entered
   under "Authorized JavaScript origins": the page never talks to Google.
5. It shows a client ID and a client secret. They are the two settings.

## Settings

| | |
|---|---|
| `GOOGLE_CLIENT_ID` | The client's id. Unset, the button leads to a page that says signing in with Google is not set up. |
| `GOOGLE_CLIENT_SECRET` | Its secret. Read with [`secret`](back-end.md#secrets): the back end does not start without it, and its log never shows it. |
| `GOOGLE_REDIRECT` | The whole address Google sends people back to, as entered at Google: `https://shop.example/auth/google/callback`. Unset, it is the address the request came to ([`route.origin`](back-end.md#what-a-server-fn-can-use)) with `/auth/google/callback`. **Set it in production**: see [behind a proxy](#behind-a-proxy). |
| `GOOGLE_DOMAIN` | Only people of this Google Workspace domain (`shop.example`; several with commas between). [Below](#who-may-come-in). |
| `GOOGLE_LINK` | `ask`: an account that is already there, with an address nothing ever verified, is not taken on Google's word. [Below](#whose-account-it-is). |
| `GOOGLE_PROMPT` | `select_account`: Google asks which account each time, also of someone signed in to one only. |
| `GOOGLE_DISCOVERY` | An address to read Google's endpoints from: `https://accounts.google.com/.well-known/openid-configuration`. [Below](#to-confirm-against-google). |
| `GOOGLE_AUTH_URL` `GOOGLE_TOKEN_URL` `GOOGLE_KEYS_URL` `GOOGLE_ISSUER` | Each endpoint by itself, in place of the one written in the extension. |

`mote build` lists them in `dist/.env.example`, the secret first.

## In the page

| | |
|---|---|
| `GoogleButton` | A link, drawn as a button, that says "Continue with Google". It works before the page's script has run. `to="/orders"`: the route to come back to (unsaid: where the page is). `label="Sign in with Google"`: other words. `hint=email`: an address to offer Google. It takes styles as any component does. |
| `button "Continue with Google" press=googleSignIn` | The same as an action, for a button of your own; `press=googleSignInTo("/orders")` to come back to a route. |
| `button "Connect Google" press=googleConnect` | For someone signed in already: Google becomes another way in to their account. |
| `googleProfile()` | A `server fn`: what Google said of whoever is signed in, `{email, name, picture}`, or `none` for someone who did not come by Google. `picture` is an address at Google. |

The mark on the button is a letter in a ring, drawn in the extension: it is
not Google's logo, and no file of Google's is in the package. Google asks
apps that show its logo to follow its branding guidelines; a program that
wants the logo adds it itself.

Signing out is [`auth.signOut`](back-end.md#signing-in), as ever. It ends
the session here and does nothing at Google.

Two addresses are the extension's, and a program may link to the first
itself: `GET /auth/google/start?to=/path&hint=address` and
`GET /auth/google/callback`. A program cannot have routes of its own at
those two.

## What happens

The OAuth 2.0 authorization-code flow with OpenID Connect, for a web client
that keeps a secret, with PKCE:

1. **`/auth/google/start`** makes a `state`, a PKCE verifier and a `nonce`
   (each random), keeps them in a row with where to come back to, and sends
   the browser to Google with `response_type=code`, `scope=openid email
   profile`, the `state`, the `nonce` and the verifier's SHA-256 (`S256`).
   The row is named by the hash of a random handle; the handle itself goes
   to this browser in a cookie (`mote_oidc_google`: `HttpOnly`,
   `SameSite=Lax`, only for `/auth/google`, `Secure` over https, ten
   minutes). No `access_type=offline` is asked for: there is no refresh
   token.
2. The person signs in at Google and agrees. Google sends the browser to
   **`/auth/google/callback`** with a code and the `state`.
3. The callback finds the row by the cookie and **spends it** (it is good
   once, for ten minutes, whatever comes next), then compares the `state`.
   A callback in a browser that did not begin it has no cookie, or another
   sign-in's: nobody can be signed in as somebody else by being sent a link.
4. The back end **exchanges the code** at Google's token endpoint, with the
   client's secret and the verifier (ten seconds at most). A code stolen
   on the way is no use without both.
5. The **id token** in the answer is checked: its signature against
   Google's published keys (never `alg: none` or an HMAC:
   [`crypto.jwt.verify`](data.md#crypto)), that it has not ended, that it
   is from Google (`iss`: `https://accounts.google.com` or
   `accounts.google.com`), for this client (`aud`, and `azp` when there is
   one), carries this sign-in's `nonce`, names a person (`sub`) and an
   address, and that **Google has verified the address** (`email_verified`
   is `true`; anything else is refused).
6. Then [who may come in](#who-may-come-in), [whose account it is](#whose-account-it-is),
   `auth.signInAs`, and a `303` to where the person was. That address is
   a path of this site or it is `/`: `//evil.example`, `https://…` and
   `/\evil.example` are not followed.

A sign-in that is refused answers a plain page that says why in a sentence
("You are not signed in", and a link back), sets no session, and is one
line of the [log](back-end.md#logs) at `warn` with a short `why`. The log
never has a code, a token, a `state` or the secret in it.

Google's keys are kept for as long as Google's answer says (`cache-control:
max-age`; five minutes at least, a day at most), and read again, at most
once a minute, when a token names a key that is not among them.

## What is kept

In the app's own database, in models no page can reach (they have no rules):

| | |
|---|---|
| `OidcLink` | For each person who came by Google: Google's id for them (`sub`), which account that is, and their address, name and picture's address as Google last said them. |
| `OidcPending` | A sign-in that was begun: `state`, verifier, `nonce`, where to come back to. Spent when it comes back; gone a quarter of an hour or so after its ten minutes. |
| `OidcCache` | Google's keys (public), and its discovery document when `GOOGLE_DISCOVERY` is set. |

No access token, no refresh token and no id token is kept: they are let go
of when the callback has answered. The account itself is a row of
[the accounts](back-end.md#signing-in), with no password: nobody signs in
to it with one until one is set (`auth.setPassword`, by a reset link of
the program's own).

## Whose account it is

A person is known by **Google's `sub`**, never by their address: an address
can change hands, a `sub` does not. So:

1. **Someone who came before** (there is a link for the `sub`) is that
   account. If Google's address for them has changed, the account's
   follows, unless another account has that address.
2. **Nobody here has that address**: a new account is made, and linked.
   (Accounts and links are kept in two databases. The link is written
   first, as nobody's yet, then the account is made and the link given it:
   if the back end stops between the two, the next sign-in by the same
   `sub` goes on from there, and nobody else is let in by what was left.)
3. **An account with that address is there already**, made with a password
   say. Google says, verified, that this person holds the address; the
   account's address may never have been shown to be its maker's (signing
   up proves nothing). What is done depends on that:

| The account's address | `GOOGLE_LINK` unset | `GOOGLE_LINK=ask` |
|---|---|---|
| was verified ([`auth.verified`](back-end.md#accounts-made-by-the-programs-own-code): the program said so, or an earlier Google sign-in did) | linked, and signed in | linked, and signed in |
| was never verified | linked and signed in; **its password is replaced by one nobody has, and its other sessions end** | refused: "sign in the way you did before, then connect Google" |

The reasoning. Somebody can sign up with *your* address and a password of
their own before you ever come, and wait. If your Google sign-in were then
simply joined to that account, they would be inside your account with their
password. So when an account whose address nobody verified becomes yours
by Google's word, whoever else held it is put out: the password stops
working and every session of it ends. The cost falls on the honest case
too: someone who signed up with a password, never had their address
verified, and one day presses the Google button, finds their old password
gone (they are signed in, and a reset link of the program's sets a new
one). A program that would rather ask says `GOOGLE_LINK=ask`: such a
person is told to sign in with their password and press "Connect Google"
(`googleConnect`), which proves both at once. A program that already
verifies addresses (a link it mails at sign-up, an invitation) says so with
`auth.setVerified(userId)` when the link is opened, and its people keep
their passwords.

Three more rules:

- **Only where Google is the address's mail service.** An account that is
  already there is taken on Google's word only for a `gmail.com` or
  `googlemail.com` address, or one in a domain Google hosts (the token
  says `hd`). A Google account can carry an address of any mail service,
  verified once and perhaps long ago; for those, a new account is made if
  the address is free, and an account that is there is "sign in the way
  you did before, then connect".
- **One Google person for an account, one account for a Google person.**
  A second `sub` that shows the address of an account already linked to
  another is refused, not joined: the account's holder signs in with the
  Google account they used before.
- **Connecting** (`googleConnect`) is for someone signed in: the handle it
  goes with is asked for by the app's own page (a `server fn`), is good
  once, and only in the session that asked.

## Who may come in

Unsaid, everyone Google vouches for. Two ways to say otherwise:

**`GOOGLE_DOMAIN=shop.example`**: only people of that Google Workspace
domain. What is checked is the token's `hd` claim, which Google sets for
accounts a Workspace domain manages. How the address ends is not looked at:
anyone can make a personal Google account with an address in any domain.
(The domain is also offered to Google as a hint, so its page shows the
right accounts; the hint is not the check.)

**A fn of the program's own**, for anything else: the extension says `wants
fn googleMay(who: OidcWho): bool = true` ([what a package
wants](language.md#what-a-package-wants-of-its-taker)), and the program may
declare it:

```text
fn googleMay(who: OidcWho): bool
  if !who.email.endsWith("@shop.example") fail("Only people of the shop sign in here.")?
  return Invited.has({email: who.email})?
```

It is asked before anyone is let in, and before any account is made for
them. False is a no in the extension's words (`You may not sign in here.`);
a failure is a no in the program's, which are what the person reads. `who`
is `{provider: "google", sub, email, domain, name, fresh}`: `domain` is the
`hd` claim (`""` for a personal account), `fresh` is true for someone no
link is kept for yet. It may read the program's own rows (an `Invited`
model, say). Unsaid, everyone Google vouches for may come in.

**The way this was said before** still works, for this release: a [`server
before` hook](models.md#hooks) on the extension's model `OidcSignIn`
(`server before OidcSignIn.add(who)` + `fail("…")?`). After `googleMay`
says yes, the extension adds a row there and takes it away again in the
same turn (nothing is kept), and a hook that fails is a no. A program that
has one moves its lines into `googleMay`; the row and the hook will go.

## Several apps at the same accounts

With [`MOTE_ACCOUNTS`](back-end.md#accounts-several-apps-share) the accounts
and sessions are shared and each app's rows are its own; the links are each
app's own rows. Give every app the extension, the same client id and
secret, and at Google one redirect address for each app.

- Someone who signs in with Google at one app **is signed in at all of
  them**, as with a password: the session is the shared one.
- At the second app there is no link yet, and the account is found by its
  address (case 3 above). The first app's sign-in marked the address as
  verified, in the shared accounts, so the second **links it and leaves the
  password alone**. From then on each app knows the person by `sub`.
- A link is one app's knowledge. An app that never saw a person sign in
  with Google does not know their `sub`: there, a *different* Google person
  showing the same verified address would be linked, where the first app
  would refuse them. That takes Google itself vouching for one address to
  two people, which it does not do for the addresses that are linked at all
  (`gmail.com`, and domains it hosts).

## Behind a proxy

Google sends people back to exactly the address it was given, and only to
one entered in the console. Behind a proxy or a tunnel the back end may not
know its own public address: it sees what the proxy passes on (`Forwarded`,
or `X-Forwarded-Proto` and `X-Forwarded-Host`, else `Host`).

- **Set `GOOGLE_REDIRECT`** to the public address,
  `https://shop.example/auth/google/callback`. Then nothing a request says
  decides it, and the sign-in's cookie is `Secure`.
- **Set [`MOTE_PROXY`](back-end.md#limits)** (`1`, or how many proxies
  stand in front), so that the two routes' limits count each visitor's own
  address and not the proxy's.
- The cookie that ties a sign-in to its browser is the host's that
  `GOOGLE_REDIRECT` names. Someone who reached the site under another name
  of it (`www.shop.example`) is sent to that host to begin, and comes back
  there. Unless the session's cookie covers both names
  ([`MOTE_COOKIE_DOMAIN`](back-end.md#accounts-several-apps-share)), that
  is where they are signed in.

## To confirm against Google

The extension has Google's four values written in it:

| | |
|---|---|
| Authorization | `https://accounts.google.com/o/oauth2/v2/auth` |
| Token | `https://oauth2.googleapis.com/token` |
| Keys | `https://www.googleapis.com/oauth2/v3/certs` |
| Issuer | `https://accounts.google.com` (and `accounts.google.com`) |

They were written from memory of Google's OpenID discovery document, by
something that could not fetch it. **When first deploying, open
`https://accounts.google.com/.well-known/openid-configuration` and compare**
`authorization_endpoint`, `token_endpoint`, `jwks_uri` and `issuer`. Or do
not trust the constants at all: set `GOOGLE_DISCOVERY` to that address, and
the four are read from it (once a day; the last copy is used while it
cannot be read). With it set, the issuer is the document's `issuer` alone.
A wrong value fails closed: a sign-in is refused, nobody is let in.

## Limits, acting, usage

- The two routes take **30 a minute from one address** each
  ([`limit … by ip`](back-end.md#limits)); `googleConnect`'s handle, 10 a
  minute a person.
- **While [acting as someone](back-end.md#acting-as-someone)**, beginning a
  sign-in, finishing one and connecting are all refused.
- With [usage](usage.md) on, a first sign-in with Google is a `signup`
  event and every later one a `signin`, as with a password.

## Another provider

The flow is `extensions/oauth/oauth.mote`, which every provider shares;
`google.mote` is Google's settings over it: a record (`OauthProvider`), two
routes and a button. GitHub, Microsoft, Apple and the others, any OpenID
provider by its issuer, and Google's tokens kept for its APIs
(`GOOGLE_KEEP=1`, `use "pkg:google/tokens.mote"`, `oauthToken(googleProvider(), user)`)
are [oauth.md](oauth.md). `oauthMay(who)` is asked for every provider,
Google's too, before `googleMay`.

## Tests

Nothing in them reaches Google. `tests/google_fakeidp.mjs` is a pretend
provider (it approves at once, checks the secret, the redirect address, the
PKCE verifier and that a code is used once, and can be told to mint wrong
tokens).

- `tests/expect/real_google_signin.txt`: a browser presses the button and comes
  back signed in; again from another route; an account squatted with a
  password; a verified account that keeps its password; where it comes
  back to; an address Google is not the mail service of; the program's
  hook; an address that changes; acting; a second app at the same
  accounts; a Workspace domain, `ask`, connecting, discovery.
- `tests/expect/real_google_hostile.txt`: every wrong token (another client,
  another issuer, ended, another nonce, no `sub`, unsigned, HS256 under the
  public key, an unpublished key, an address not verified); the state
  missing, wrong, another browser's, used twice; a callback opened in
  another browser; a code used twice and a code brought to another
  sign-in; one Google person for two accounts; what a page cannot ask
  for; the limits; and that the logs hold no code, token, state or secret.
- `extensions/google/tests.mote`: the same flow by the clock, with
  [`mote test`](testing.md#tests-in-the-program): ten minutes and once,
  every claim, the keys' keeping, the linking rules, connecting.

Source: `extensions/google/` (`google.mote`, `tests.mote`), over
`extensions/oauth/oauth.mote`;
`runtime/server/auth.mote` for `auth.create`, `auth.setEmail`,
`auth.verified` and `auth.setVerified`.
