Connecting accounts with OAuth2
A calendar, bookkeeping or mail module often works on someone's account at another service: their Google calendar, their Exact or Moneybird administration. Those services hand out access with OAuth2. SHADE runs the whole flow for your module: an admin connects the account, SHADE keeps the tokens sealed, refreshes them before they end, seals them again when the instance's secret is rotated and revokes them when your module is uninstalled. Your module only calls the service's API.
The OAuth2 client is experimental in 0.1 (see Experimental manifest parts): the manifest
part oauth, oauthFetch, oauthAccessToken, oauthAccounts, ModuleOAuthProvider and OAuthAccount may change
in a minor version until a second, different module uses them. It is for trusted modules only.
Naming the provider
Declare each provider under its own name in oauth, with the client id and secret as settings (the secret as a
secret setting, so it is sealed), and give the hosts SHADE calls in your network capability:
import { defineModule } from '@shadestack/module-sdk/server'
export default defineModule({
name: 'calendars-google',
// …
capabilities: {
network: { hosts: ['oauth2.googleapis.com', 'www.googleapis.com'] }
},
settings: {
fields: [
{ kind: 'text', name: 'clientId', label: 'Client id' },
{ kind: 'text', name: 'clientSecret', label: 'Client secret' }
],
secrets: ['clientSecret']
},
oauth: {
google: {
authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenUrl: 'https://oauth2.googleapis.com/token',
revokeUrl: 'https://oauth2.googleapis.com/revoke',
scopes: ['https://www.googleapis.com/auth/calendar.readonly'],
clientId: 'clientId',
clientSecret: 'clientSecret',
// Google gives a refresh token only for offline access, and only when the person agrees again.
authorizeParams: { access_type: 'offline', prompt: 'consent' }
}
}
})
SHADE refuses the module when it loads if:
- an endpoint is not https, or holds a user name, password or fragment;
- the token or revocation endpoint is on a host your
networkcapability does not name (the authorization endpoint is only visited by the admin's browser, so it needs no host); clientIdis not one of your settings, orclientSecretis not a secret setting;authorizeParamsnames a parameter SHADE sets itself (response_type,client_id,redirect_uri,scope,state,code_challenge,code_challenge_method).
Ask for the fewest scopes that do the job, read-only where the service has them.
The redirect address
Every instance has one redirect address, made from its configuration, never from a request:
<SHADE_ADMIN_URL, or SHADE_API_URL>/api/packages/oauth/callback
Register exactly that address with the provider, for every module and provider on the instance. Tell the instance's operator in your module's README: the client id and secret come from the client's own account at the provider, so their data never passes through anyone else's app.
Connecting an account
An admin (anyone who may manage modules) connects an account from your module's settings section or page: a button that asks SHADE for the provider's address and sends the browser there.
const { url } = await $fetch('/api/packages/oauth/calendars-google/google/start', {
method: 'POST',
body: { account: 'default', returnTo: '/module-settings/calendars-google' }
})
window.location.href = url
account names the account when your module keeps more than one (lower-case letters, digits and dashes;
default when left out). returnTo is the admin path the browser comes back to, with ?oauth=connected added; only
a path on the admin is taken.
SHADE uses the authorization code flow with PKCE (S256). The state it sends is bound to the admin's session and
taken once, within ten minutes: a callback that comes back in another browser, too late, twice or with a state SHADE
never gave is refused with 403, without saying why. Why is in the audit log as protection.oauth-refused, once per
module a minute. The admin starts again from your module's page.
GET /api/packages/oauth/<plugin> lists the module's connected accounts for admins, and
DELETE /api/packages/oauth/<plugin>/<provider>/<account> disconnects one (revoked at the provider, audited).
Calling the provider's API
oauthFetch is moduleFetch with the account's access token as Authorization: Bearer. SHADE refreshes the token
first when it ends within a minute:
import { oauthFetch } from '@shadestack/module-sdk/server'
const response = await oauthFetch(ctx, 'google', 'https://www.googleapis.com/calendar/v3/users/me/calendarList', { account: 'default' })
const calendars = await response.json()
The same rules as moduleFetch apply: only hosts your network capability names, over https, never into the
server's own network, and the token never follows a redirect to another origin. oauthAccessToken(ctx, provider, account?) gives the token itself, for a client library that wants one; use it at once and never store it.
oauthAccounts(ctx) lists your module's accounts (OAuthAccount: provider, account, status, scope, when the token
ends), never their tokens.
What can go wrong:
| Error | When | What to do |
|---|---|---|
| NOT_FOUND | No such account is connected | Ask an admin to connect it |
| CONFLICT | The provider refused the refresh token (the person revoked access, or it expired): the account is broken, audited once as packages.oauth.refresh-failed | Show it on your page; an admin connects it again, which mends it |
| UNAVAILABLE | The provider did not answer a refresh (audited once a minute) | Try again later; the account is kept |
What SHADE does for you
- Sealed tokens. The tokens are kept by SHADE, not in your tables, sealed with the instance's vault. They are never in your module's settings, its backup on uninstall, an instance's export or any answer.
- Rotating
APP_SECRET.rotate-secretsseals them again with the new key. YouronSecretsRotatedneeds to do nothing for them. - Uninstalling. The accounts go with the uninstall, and once it has committed SHADE revokes each refresh token at
the provider's revocation endpoint. Your
onUninstallneeds to do nothing for them. A provider without a revocation endpoint, or one that does not answer, is noted in the audit log aspackages.oauth.revoke-failed. - One refresh at a time. Containers refresh an account one at a time, under a lease, and claim its refresh token in the database before they call the provider; nothing waits on a database transaction while the provider answers. A call that finds another container refreshing waits for the new token (up to about 12 seconds, else UNAVAILABLE). So a provider that hands out a new refresh token on every refresh never sees the same one twice, even when a container loses its lease mid-call.
- Outside a transaction. Call
oauthFetchandoauthAccessTokenoutside your own transactions: a refresh within one is refused, since the transaction would stay open while the provider answers.
Testing
Core's fixture oauth-probe (in SHADE's repository, shade/test/testing/fixtures/modules/oauth-probe) connects
accounts against a mock authorization server in the API's tests (apps/api/test/testing/oauth-server.ts): it answers
behind the modules' network stand-ins (stubModuleNetwork({ resolve, send }) from @shadestack/core/services) and
holds the flow to the rules a real provider does.