# Google OAuth Runbook

This runbook describes how Flynn acquires, stores, refreshes, and rotates Google OAuth tokens for Gmail, Calendar, Docs, Drive, and Tasks.

## Scope Policy (Least Privilege)

| Service | Command | Scope(s) |
|---|---|---|
| Gmail | `flynn gmail-auth` | `https://www.googleapis.com/auth/gmail.settings.basic`, `https://www.googleapis.com/auth/gmail.readonly` |
| Calendar | `flynn gcal-auth` | `https://www.googleapis.com/auth/calendar.readonly` |
| Docs | `flynn gdocs-auth` | `https://www.googleapis.com/auth/documents.readonly`, `https://www.googleapis.com/auth/drive.metadata.readonly` |
| Drive | `flynn gdrive-auth` | `https://www.googleapis.com/auth/drive.readonly` |
| Tasks | `flynn gtasks-auth` | `https://www.googleapis.com/auth/tasks.readonly` |

Unified entrypoint:

```bash
flynn google-auth --service gmail
flynn google-auth --service gcal
flynn google-auth --service gdocs
flynn google-auth --service gdrive
flynn google-auth --service gtasks
```

Add `--manual` for copy/paste flow, or `--config <path>` for non-default config.

## Storage Model

- Canonical token store: `~/.config/flynn/auth.json`
  - Path: `google.services.<service>.token`
  - Metadata: scopes, token file path, credentials file path, `updated_at`
- Compatibility token files remain supported:
  - `~/.config/flynn/gmail-token.json`
  - `~/.config/flynn/gcal-token.json`
  - `~/.config/flynn/gdocs-token.json`
  - `~/.config/flynn/gdrive-token.json`
  - `~/.config/flynn/gtasks-token.json`

Runtime behavior:

1. Flynn checks auth store first.
2. If missing, Flynn loads legacy token file and migrates it into auth store.
3. If both are missing, tools/watchers fail with a service-specific re-auth command hint.

## Refresh and Rotation Behavior

- OAuth client refresh events write back to:
  - auth store (`auth.json`)
  - service token file (compatibility)
- If auth store write is blocked (for example `EACCES`), Flynn keeps operating from token files.
- Re-auth is required when Google returns insufficient-scope errors for a service.

## Local Operation Checklist

1. Configure `automation.<service>.credentials_file` in Flynn config.
2. Run service auth command (or `flynn google-auth --service <service>`).
3. Run `flynn doctor` and verify service checks:
   - `Gmail configured`
   - `Google Calendar configured`
   - `Google Docs configured`
   - `Google Drive configured`
   - `Google Tasks configured`

## Failure and Renewal Signals

- Missing credentials file: hard failure with path.
- Missing tokens (store + file): doctor warning + runtime auth error with command hint.
- Scope mismatch: runtime error includes explicit re-auth command for the affected service.
