npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@softure-ai/connections

v0.8.0

Published

SOFTURE AI connections module: the app as an OAuth 2.0 client of third-party APIs and a store for their API keys. Providers from configuration, a connect flow for Next.js (one-time state, PKCE, a callback route) behind an admin-only page with each connect

Readme

@softure-ai/connections

Connected accounts for a Next.js app that acts on behalf of its owner's own accounts at other services (a mailbox, a calendar, a task manager, a time tracker, a code host). The app becomes an OAuth 2.0 client of their APIs, or keeps their API keys, without writing the fragile parts again: the authorization code flow with a one-time state and PKCE, encrypted storage, refresh before expiry without double refreshes, and a clear "needs reconnect" state when a grant dies. It is the opposite direction of @softure-ai/mcp-access, which is an OAuth server for clients that call the app.

1. What it provides

  • Providers from configuration, three kinds: oauth (authorization code flow), api_key and basic (pasted by an admin). Each has one account (default) or several (["work", "personal"]).
  • A connect flow for Next.js: the admin-only page ConnectionsPage lists every provider account with its status, last refresh, granted scopes, expiry and last problem, with connect / reconnect / disconnect buttons and key forms; startConnectionAction sends the browser to the provider; completeConnectionRoute is the callback.
  • Encrypted storage: tokens, keys and the PKCE verifier are sealed with AES-256-GCM under the keyring in SOFTURE_CONNECTIONS_KEYS; each row stores its key id for rotation, and the ciphertext is bound to its row. Plaintext never reaches the database, a log line, an error code or the browser.
  • getAccessToken(ctx, { provider, accountId? }): a Result with a usable token. Close to expiry it refreshes under the row's lease (two workers never spend one refresh token twice; the others wait and read the new token). invalid_grant becomes the terminal connections.reconnect_required; network failures, 429, 5xx and odd answers are the retryable connections.refresh_failed. forceRefresh: true refreshes now, under the same lease, for a token the provider refused before its expiry. A failed refresh says what the token endpoint answered: see "Failed refreshes" below.
  • requestWithConnection(ctx, { provider, accountId? }, options): one API call with the stored credential of any kind, through requestJson. On a 401 with OAuth it refreshes once and retries once; only a second 401 (or the first for a key) reports the credential rejected.
  • downloadWithConnection(ctx, { provider, accountId? }, options): the same for a file (an invoice PDF), through requestBytes: the bytes as a Uint8Array with the content type, under a size cap.
  • getCredential for API keys and Basic, reportCredentialRejected when the app saw a 401, and getAuthorizationHeader for either.
  • onReconnectRequired, a hook that runs once when a connection needs reconnecting, so the app can alert the owner (e.g. by mail through @softure-ai/mailing).
  • onConnectionChanged and one info log line for every connect, reconnect, disconnect and failed OAuth callback, for an audit trail of admin actions.
  • @softure-ai/connections/user-oauth: OAuth 2.0 grants that belong to the app's own users, one per user kept by the app: the one-time state and PKCE, the consent URL, the code exchange, refreshes, revocation (RFC 7009 or a bearer call) and sealing a grant to its user. See "Users' own OAuth grants" in section 4.
  • @softure-ai/connections/github-app: for an app whose own users each connect a GitHub App installation (a repository of theirs): the App's JWT, the installation, installation tokens, and the proof that an installation id belongs to the signed-in user. See "Users' own GitHub App installations" in section 4.
  • A privacy contributor, a health check, the softure-connections command (key, rotate-keys) and a fake OAuth provider for tests (@softure-ai/connections/testing).

Provider-specific API clients are out of scope: the app calls the API with requestWithConnection, or with the token and requestJson of @softure-ai/core.

2. Installation

npm install @softure-ai/connections @softure-ai/auth @softure-ai/security @softure-ai/core @softure-ai/db @softure-ai/ui drizzle-orm

Peer dependencies: next 16, react 19, drizzle-orm, @softure-ai/ui. The module depends on auth (and auth on security): a configuration without them fails at startup, so the page is never mounted without a role check.

3. Configuration

import { connections } from "@softure-ai/connections";

// in defineSoftureConfig({ modules: [...] }), after security(...) and auth(...):
connections({
  providers: [
    {
      kind: "oauth",
      id: "google",
      label: { en: "Google (Gmail, Calendar)" },
      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/gmail.modify", "https://www.googleapis.com/auth/calendar"],
      clientIdEnv: "GOOGLE_CLIENT_ID",
      clientSecretEnv: "GOOGLE_CLIENT_SECRET",
      // Google issues a refresh token only with these.
      authorizeParams: { access_type: "offline", prompt: "consent" },
      // An app in "testing" mode: Google drops refresh tokens after 7 days.
      refreshTokenMaxAgeDays: 7,
    },
    {
      kind: "oauth",
      id: "github",
      authorizeUrl: "https://github.com/login/oauth/authorize",
      tokenUrl: "https://github.com/login/oauth/access_token",
      scopes: ["repo"],
      scopeSeparator: " ",
      clientIdEnv: "GITHUB_CLIENT_ID",
      clientSecretEnv: "GITHUB_CLIENT_SECRET",
    },
    { kind: "api_key", id: "raindrop", label: { en: "Raindrop" }, hint: { en: "Settings, Integrations, Create test token." } },
    // A key read from its own header (bare), or from Authorization with another scheme:
    { kind: "api_key", id: "vendor", label: { en: "Vendor" }, header: { name: "x-vendor-apikey" } },
    { kind: "api_key", id: "other", label: { en: "Other" }, header: { name: "authorization", scheme: "Token" } },
    { kind: "basic", id: "toggl", accounts: ["work", "personal"] },
  ],
  onReconnectRequired: async (event, ctx) => {
    // e.g. sendMail(ctx, { to: owner, subject: `Reconnect ${event.provider}` ... })
  },
  onConnectionChanged: async (event, ctx) => {
    // e.g. an audit record: who connected, reconnected or disconnected which service, and how it ended
  },
}),

| Option | Type | Default | Meaning | | --- | --- | --- | --- | | providers | ProviderDefinition[] | [] | The services the app connects to. | | providers[].kind | "oauth" | "api_key" | "basic" | required | How the app authenticates there. | | providers[].id | string | required | kebab-case, at most 64 characters; unique. | | providers[].label | { en?, <locale>? } | the id | The page's name for it. | | providers[].accounts | string[] | ["default"] | The accounts the app keeps at this provider ([a-z0-9][a-z0-9_-]*). | | providers[].authorizeUrl, tokenUrl | string | required (oauth) | https, or http on localhost (an emulator). | | providers[].revokeUrl | string | none | RFC 7009 endpoint, called best effort on disconnect. | | providers[].scopes | string[] | [] | Requested scopes. | | providers[].scopeSeparator | " " | "," | " " | How the scopes are joined in the authorize URL. | | providers[].clientId / clientIdEnv | string | one required (oauth) | The client id, or the variable that holds it. | | providers[].clientSecretEnv | string | none | The variable that holds the client secret; omit for a public client (then pkce must stay on). | | providers[].clientAuth | "body" | "basic" | "body" | Client credentials in the token request's form, or as HTTP Basic. | | providers[].authorizeParams | Record<string, string> | {} | Extra authorize parameters; the ones the module sets (state, scope, …) are refused. | | providers[].pkce | boolean | true | PKCE S256. | | providers[].rotatesRefreshToken | boolean | false | The provider spends a refresh token on use; a refresh answer without a new one then ends the grant when its access token expires. | | providers[].refreshTokenMaxAgeDays | number | none | Shows the connection as expiring before a refresh token the provider will drop (when the provider does not send refresh_token_expires_in). | | providers[].owner | "app" | "user" | "app" | (oauth) Who a connection belongs to: the app (one connection per account, connected by an admin) or each signed-in user (one connection per user per account, section 4, "Users' own OAuth connections"). | | providers[].returnPath | string | required when owner: "user" | (oauth) The app path a user lands on after connecting their own account, with ?connected= or ?error=. | | providers[].subjectField | string | none | (oauth) A field of the code exchange's answer that names the user's account at the provider (Dropbox account_id), kept as the connection's subject. | | providers[].hint | { en?, <locale>? } | none | (api_key, basic) Where the admin finds the key. | | providers[].header | { name, scheme? } | Authorization: Bearer | (api_key) Where the key goes: { name: "x-api-key" } sends the bare key in that header; { name: "authorization", scheme: "Token" } sends Token <key>. The name is an HTTP token (stored lowercase); scheme only with authorization, Bearer when omitted. | | panelRole | string | "admin" | The auth role that opens the page, connects and disconnects. | | refreshSkewSeconds | number | 300 | A token this close to expiry is refreshed before it is handed out. | | expiringWithinHours | number | 72 | A grant that dies within this many hours shows as expiring. | | refreshLeaseSeconds | number | 30 | How long one worker holds a connection's refresh; must exceed httpTimeoutMs. | | refreshWait | { attempts, intervalMs } | { 40, 250 } | How a caller waits while another worker refreshes. | | stateTtlMinutes | number | 10 | How long an authorization may take, button to callback. | | httpTimeoutMs | number | 10000 | Timeout of a token, exchange or revoke call. | | keysEnv | string | "SOFTURE_CONNECTIONS_KEYS" | The variable that holds the keyring (section 6), for an app that already keeps one under its own name. | | accountReturnPath | string | "/" | Where the callback sends a signed-in user without the panel role when it cannot tell their provider (an unknown or spent state). | | onReconnectRequired | (event, ctx) => void \| Promise<void> | none | Section 10. | | onConnectionChanged | (event, ctx) => void \| Promise<void> | none | Section 10. | | fetch | FetchFunction | global fetch | The token client's fetch; tests pass the fake provider's. | | routes | { page, callback } | /admin/connections, /api/connections/callback | Where the page and the callback are mounted. | | messages | partial dictionaries per locale | built in | Copy overrides (section 9). |

Register the redirect URI <appOrigin><routes.callback> (by default https://your.app/api/connections/callback) with every OAuth provider. It is built from appOrigin of the config, never from a request header.

4. Mounting

// app/admin/connections/page.tsx: the page. Not found for anyone without panelRole, signed in or not.
export { ConnectionsPage as default } from "@softure-ai/connections/next";
export const dynamic = "force-dynamic";
// app/api/connections/callback/route.ts: the OAuth callback; it answers 303 to the page.
export { completeConnectionRoute as GET } from "@softure-ai/connections/next";

The connect, key and disconnect buttons are server actions, registered when the page imports them: nothing more to mount. An app with its own page shell composes the same parts:

import { requireRole } from "@softure-ai/auth/next";
import { disconnectAction, getConnectionsContext, getConnectionsMessages, saveCredentialAction, startConnectionAction, toConnectionPanelRows } from "@softure-ai/connections/next";
import { listConnections } from "@softure-ai/connections/server";
import { ConnectionsPanel } from "@softure-ai/connections/ui";

const views = await listConnections(await getConnectionsContext(config));
<ConnectionsPanel
  rows={toConnectionPanelRows(views, getConnectionsMessages(config), config)}
  actions={{ start: startConnectionAction, save: saveCredentialAction, disconnect: disconnectAction }}
  messages={getConnectionsMessages(config)}
/>;

Using a connection from server code:

import { requestWithConnection } from "@softure-ai/connections/next"; // or /server with your own ctx (a job, a script)

const inbox = await requestWithConnection(
  { provider: "google" },
  { url: "https://gmail.googleapis.com/gmail/v1/users/me/messages", schema: InboxSchema },
);
if (!inbox.ok) return inbox; // connections.reconnect_required is terminal; refresh_failed and refresh_in_progress retry

requestWithConnection takes every option of requestJson (schema, method, body or form, idempotencyKey, readHeaders, fetch, timeoutMs), sets the Authorization header (it replaces one the caller passes) and returns the requestJson result unchanged, with these exceptions:

  • the credential cannot be read: the connections.* code of getAccessToken or getCredential, nothing is sent;
  • a 401 with OAuth: one refresh (only while the stored token is still the refused one, so overlapping calls spend one refresh) and one retry. A failed refresh answers its code (connections.reconnect_required after invalid_grant, the retryable connections.refresh_failed);
  • a second 401, a 401 with an API key or Basic credential, or a 401 with an OAuth connection without a refresh token: reportCredentialRejected (the hook runs once) and connections.reconnect_required.

Failed refreshes

connections.refresh_failed and connections.client_rejected (a ConnectionsRefreshFailure) carry what the token endpoint answered, never its body, error description or a token:

const token = await getAccessToken(ctx, { provider: "google" });
if (!token.ok && token.error === "connections.refresh_failed") {
  token.httpStatus; // 400, 503, 429…; null when no answer came (network failure, timeout); any 2xx reads as 200
  token.oauthError; // "invalid_request", "temporarily_unavailable"…; null when the answer had none (never read from a 429 or 5xx)
}

requestWithConnection and downloadWithConnection pass the same failure on. The field is httpStatus, not status, so it is never mistaken for the provider API's own status on a core.http_* failure.

Every failed refresh (invalid_grant included) logs one warn line, and the row keeps the same detail in last_error_http_status and last_error_oauth_error (the page shows it beside the last problem; ConnectionView has lastErrorHttpStatus and lastErrorOAuthError):

@softure-ai/connections: token refresh failed provider=google account_id=default http_status=400 oauth_error="invalid_request" code=connections.refresh_failed

A form (a URLSearchParams or a FormData with files) is sent as it is, and sent again on the retry after a refresh. A 403 is a permission problem, not a dead credential: it comes back as core.http_refused and reports nothing.

Downloading a file (an invoice or report PDF) takes the same credential path, through core's requestBytes:

import { downloadWithConnection } from "@softure-ai/connections/next"; // or /server with your own ctx

const pdf = await downloadWithConnection(
  { provider: "invoicing" },
  { url: `https://api.invoicing.example/v3/invoices/${id}/pdf`, accept: "application/pdf", maxBytes: 10 * 1024 * 1024 },
);
if (!pdf.ok) return pdf; // core.http_too_large above maxBytes, the other codes as above
return new Response(pdf.value.bytes, { headers: { "content-type": pdf.value.contentType ?? "application/pdf" } });

It takes method (a GET by default), a JSON body for a write that renders a file, accept (default */*), maxBytes (default 25 MiB), idempotencyKey, headers, fetch and timeoutMs, and follows the same 401 rules as requestWithConnection. The body is read in chunks and dropped as soon as it passes maxBytes.

An app with its own HTTP client reads the token and refreshes it itself:

import { getAccessToken } from "@softure-ai/connections/next";

const token = await getAccessToken({ provider: "google" });
// ...the provider answered 401 before the token's expiry:
const fresh = await getAccessToken({ provider: "google", forceRefresh: true }); // same lease, same invalid_grant handling
// still 401: await reportCredentialRejected(ctx, { provider: "google" });

replaceRejectedToken(ctx, { provider, accountId?, rejectedToken }) of /server is the forced refresh the helper uses: it refreshes only while the stored token is rejectedToken and otherwise answers the token stored since.

getCredential({ provider: "raindrop" }) answers { kind: "api_key", apiKey } or { kind: "basic", username, password }; getAuthorizationHeader(credential) turns either (or { kind: "oauth", accessToken }) into the Authorization value, ignoring a provider's header. For an app with its own HTTP client, getCredentialHeader({ provider }) (/next; getCredentialHeader(ctx, { provider }) in /server) answers { name, value } where the provider reads it ({ name: "x-vendor-apikey", value: "<key>" }), with the failures of getCredential; formatCredentialHeader(credential, getCredentialPlacement(provider)) of /server is the same without the read. requestWithConnection sets that header and replaces the caller's header of the same name.

The server functions in /server take { db, clock, config, env? }; env defaults to process.env (the keyring and the client secrets), so a worker outside Next builds the context the same way as getConnectionsContext does.

Inside a transaction (a jobs processSyncItem callback, the app's own db.transaction), pass the transaction as db: requestWithConnection({ ...ctx, db: tx }, ...). The token state is kept outside that transaction anyway: a refreshed token, the refresh lease, reconnect_required and the onReconnectRequired hook go through the app's configured database (database.handle, or the pool for a postgres:// database.url, the handle the adapters use), because the provider has already spent the old refresh token and a rollback cannot undo that. A failed item therefore keeps the rotated refresh token and a terminal invalid_grant (#935). This applies to getAccessToken, replaceRejectedToken, reportCredentialRejected and the two request helpers; the app's own writes stay in its transaction. Three consequences:

  • such a call takes a second pool connection while the caller holds one for its transaction, so the pool needs at least one connection more than the transactions that call it at the same time (a jobs worker's concurrency);
  • a transaction that itself changed the account's row (saveCredential, disconnect) and then asks for its token waits on its own row lock: commit the change first;
  • PGlite has one connection, so there (pglite://, @softure-ai/db/testing) the state is written in the caller's transaction and rolled back with it. With the outer ctx.db inside an open transaction the one-connection test database rejects the read with PoolInsideTransactionError instead of waiting forever.

Users' own OAuth connections (owner: "user")

A provider with owner: "user" keeps one connection per signed-in user (and per account): a user connects their own Dropbox, say, from a page of the app, never from the admin panel. The same table holds them with the user's id in owner_id; each one is sealed with its owner in the additional data, so a row moved to another user does not open. Every call takes the owner:

// The provider, next to the app's own ones:
{ kind: "oauth", id: "dropbox", owner: "user", returnPath: "/settings/dropbox", subjectField: "account_id",
  authorizeUrl: "https://www.dropbox.com/oauth2/authorize", tokenUrl: "https://api.dropboxapi.com/oauth2/token",
  scopes: ["files.content.read"], clientIdEnv: "DROPBOX_APP_KEY", clientSecretEnv: "DROPBOX_APP_SECRET",
  authorizeParams: { token_access_type: "offline" } }

// The user's page (any signed-in user; the owner is always the session's user):
<form action={startOwnConnectionAction}><input type="hidden" name="provider" value="dropbox" />…</form>
<form action={disconnectOwnAction}>…</form>
const [dropbox] = await listOwnConnections(user.id); // status, scopes, subject (the provider's account id)

// The app's code, for that user:
const token = await getAccessToken({ provider: "dropbox", ownerId: user.id });
await requestWithConnection({ provider: "dropbox", ownerId: user.id }, { url, method: "POST", body });
  • The callback route serves both: an admin completes the app's authorizations, any other signed-in user only their own (completeAuthorization(ctx, { …, ownOnly: true })). A user lands on the provider's returnPath, or on accountReturnPath when the state is unknown; a signed-out one on accountReturnPath?error=auth.forbidden.
  • A call without ownerId for a user provider, or with one for an app provider, answers connections.wrong_owner. startConnectionAction (the admin panel) refuses a user provider the same way, and the panel never lists them.
  • Refreshes, leases, reconnect_required and both hooks work as for the app's connections; their events carry ownerId (null for the app's own).
  • Deleting a user (section 11) deletes their connections without calling the provider's revoke endpoint; an app that must revoke first (Dropbox has its own call) does so from its own account deletion step.

Users' own GitHub App installations (/github-app)

Everything above connects the app's own accounts, as its admin. A product whose users each connect a repository of their own (a GitHub App installed on their account) needs other calls, in @softure-ai/connections/github-app. They are stateless: the app keeps each user's installation id with its own records (an id is no secret) and mints an installation token when it needs one, so nothing here needs the module's tables, its keyring or its configuration, and the entry runs on Node and Workers.

import {
  createGithubInstallationToken,
  exchangeGithubUserCode,
  getGithubAppInstallation,
  listGithubInstallationRepositories,
  listGithubUserInstallationRepositories,
} from "@softure-ai/connections/github-app";

const credentials = { appId: env.GH_APP_ID, privateKey: env.GH_APP_PRIVATE_KEY }; // PKCS#1 as GitHub gives it, or PKCS#8

// 1. The setup redirect (`?installation_id=…&state=…`) carries an id anyone could type: prove the user reaches it.
const userToken = await exchangeGithubUserCode({ clientId, clientSecret, code, redirectUri, codeVerifier });
if (!userToken.ok) return userToken;
const reachable = await listGithubUserInstallationRepositories(userToken.value, installationId);
// connections.github_app_not_found: this user cannot reach that installation. Drop the user token either way.

// 2. Later, as the App: is it still installed, and a token for one repository, read only.
const installation = await getGithubAppInstallation(credentials, installationId); // not_found once uninstalled
const token = await createGithubInstallationToken(credentials, installationId, { repositoryIds: [repoId], permissions: { contents: "read" } });
const repositories = await listGithubInstallationRepositories(token.value.token); // what the token still reaches

| Code | When | | --- | --- | | connections.github_app_key_invalid | the private key is not an RSA key in PEM, or the app id is empty | | connections.github_app_not_found | 404: uninstalled, or this credential cannot see it | | connections.github_app_rejected | 401, 403 (a suspended installation, a JWT GitHub refuses), a spent or wrong user code | | connections.github_app_rate_limited | 429, with retryAfterSeconds | | connections.github_app_unavailable | a network failure, a timeout or a 5xx, with retryAfterSeconds when GitHub sent one | | connections.github_app_unexpected | anything else, a body this client cannot read |

Each failure carries status (null when no answer came); a token, the key or GitHub's message never appears in one. The JWT is RS256, issued a minute back and valid nine minutes; the imported key is cached per process.

Users' own OAuth grants (/user-oauth)

The stateless variant of owner: "user" above, for an app that keeps each user's grant with its own rows instead of the module's tables (or runs where the module's store does not): each user connects their own account at a provider (a cloud drive, a code host, a calendar) and the app reads it on their behalf, one grant per user. @softure-ai/connections/user-oauth gives the protocol and the sealing; the app keeps the state record and the sealed grant with its own rows, keyed by its user, since what a grant is for (a folder, a repository) is the app's own data. Stateless, no table, no configuration; Node and Workers.

import {
  buildUserAuthorizationUrl,
  createUserOAuthState,
  defineUserOAuthProvider,
  exchangeUserCode,
  hashUserOAuthState,
  openUserSecret,
  readKeyring,
  refreshUserAccessToken,
  revokeUserGrant,
  sealUserSecret,
} from "@softure-ai/connections/user-oauth";

const dropbox = defineUserOAuthProvider({
  id: "dropbox",
  authorizeUrl: "https://www.dropbox.com/oauth2/authorize",
  tokenUrl: "https://api.dropboxapi.com/oauth2/token",
  revoke: { style: "bearer", url: "https://api.dropboxapi.com/2/auth/token/revoke" }, // or { style: "rfc7009", url }
  scopes: ["files.metadata.read", "files.content.read"],
  authorizeParams: { token_access_type: "offline" }, // a refresh token
});
const client = { clientId: env.DROPBOX_APP_KEY, clientSecret: env.DROPBOX_APP_SECRET };

// 1. The connect button: store stateHash + codeVerifier for the signed-in user (ten minutes, one use).
const { state, stateHash, codeVerifier } = await createUserOAuthState();
const url = await buildUserAuthorizationUrl(dropbox, client, { redirectUri, state, codeVerifier });

// 2. The callback: consume the record by hashUserOAuthState(params.state) for the same user, then
const grant = await exchangeUserCode(dropbox, client, { code, redirectUri, codeVerifier });
// grant.value: accessToken, refreshToken, expiresAt, scopes (as granted), fields (account_id…, never a token).
// Check what the app needs (scopes, the folder); refuse with revokeUserGrant(dropbox, client, grant.value.accessToken).
const sealed = sealUserSecret(keyring, { userId, provider: "dropbox" }, grant.value.refreshToken);

// 3. Later: open, refresh, use. With rotatesRefreshToken, store fresh.value.refreshToken first.
const refreshToken = openUserSecret(keyring, { userId, provider: "dropbox" }, sealed);
const fresh = await refreshUserAccessToken(dropbox, client, refreshToken.value);

readKeyring(env) reads SOFTURE_CONNECTIONS_KEYS; an app with its own keyring variable passes { SOFTURE_CONNECTIONS_KEYS: env.MY_KEYS }. A sealed value opens only for the same user, provider and optional name (two connections of one user at one provider).

| Code | When | | --- | --- | | connections.user_oauth_rejected | the provider answered an OAuth error to a code exchange (a spent code, a wrong verifier, a wrong client) or to a refresh other than invalid_grant | | connections.user_oauth_reconnect_required | a refresh answered invalid_grant: the user revoked the app, or the grant expired | | connections.user_oauth_unavailable | a network failure, a timeout, 429, 5xx, a redirect or an unreadable answer: retry later |

Each failure carries status and the provider's oauthError code (null when none); never a token or the provider's description. createFakeOAuthProvider serves this flow too: fake.user.definition and fake.user.client, with answerFields for the provider's own identifiers and revokeStyle: "bearer".

5. Migrations and tables

Schema connections, three migrations (0001_create_accounts_and_states.sql, 0002_add_last_error_detail.sql, 0003_add_owner_and_subject.sql):

  • accounts: one row per provider account: kind, status (connected or reconnect_required), key_id, credentials (the sealed payload), token_type, scopes, has_refresh_token, expires_at, refresh_expires_at, connected_at, connected_by (auth user id, no foreign key), refreshed_at, last_error (a code), last_error_at, last_error_http_status and last_error_oauth_error (what the token endpoint answered to the last failed refresh, both nullable), the refresh lease (lease_id, lease_until), owner_id (the user a connection belongs to, null for the app's own) and subject (the provider's account id, from subjectField). Unique on (provider, account_id) among the app's rows and on (owner_id, provider, account_id) among the owned ones; checks on every enum, id shape and pair of columns.
  • oauth_states: authorizations in flight: the state's sha256 (never the state), the sealed PKCE verifier, the user who started it, owner_id (set for a user provider, always that same user) and an expiry. One-time; expired rows go when a new authorization starts.

softure migrate applies it with the other modules (after auth).

6. Environment variables

| Variable | Required | What it does | | --- | --- | --- | | SOFTURE_CONNECTIONS_KEYS | yes, at runtime | The keyring: <id>:<base64 of 32 bytes>[,<id>:<key>…]. The first key seals; every listed key opens. | | the providers' clientIdEnv / clientSecretEnv | for each OAuth provider | Read when a flow or a refresh needs them; a missing one shows on the page as connections.provider_not_configured. |

None of them is read at build time, so next build runs without them.

Make a key: npx softure-connections key 2026q4 prints 2026q4:<key>; store it as a secret.

Rotate a key: put the new entry first (new:<key>,old:<key>), deploy, run npx softure-connections rotate-keys (a dry run that counts) and then rotate-keys --commit, which re-seals every connection under the new key and drops authorizations in flight. When it reports nothing left, remove the old entry. A connection whose key is no longer in the keyring answers connections.key_unknown and needs a reconnect. Apps whose config Node cannot load directly use runConnectionsCli from @softure-ai/connections/cli in a script, like softure-mcp.

7. Switches

None.

8. Appearance

ConnectionsPanel (@softure-ai/connections/ui) takes classNames for the slots root, notice, list, item, header, title, status, details, detail, hint, actions and empty, and unstyled. It is built from @softure-ai/ui (Button, TextField, PasswordField, FormError, and Card on the page) and uses only its --sft-* tokens: the status reads success when connected, warning when expiring, danger when it needs a reconnect. The module ships no CSS of its own; import @softure-ai/ui/styles.css as for every module.

9. Copy

src/messages/en.ts: page (title, lead, empty, connected notice), status (one label per status), details (the lines under each account), actions, fields, and errors per code (errors.connections.*, auth.forbidden, core.*). Override keys per locale with connections({ messages: { en: { page: { title: "Accounts" } } } }), or pass a whole translation under another locale. getConnectionsErrorMessage(messages, code) gives the copy for a code, the generic failure for an unknown one.

10. Hooks

onReconnectRequired(event, ctx) runs after reconnect_required is stored for a connection that was connected, once per transition (the next calls answer the code without running it again). event is { provider, accountId, kind, reason, at } with reason:

  • invalid_grant: the provider refused the refresh token (consent revoked, a testing-mode app's 7-day limit, a rotated token reused);
  • expired: the access token expired and there is no refresh token;
  • rejected: the app called reportCredentialRejected (a 401 from the API).

A hook that throws is logged by error kind and never fails the call; the state is stored either way. Called from inside a transaction, the hook's ctx.db is the configured database, not that transaction (section 4), so what the hook writes (an alert job, a mail) is kept when the caller's transaction rolls back. A new connect (or a new key) brings the connection back to connected.

onConnectionChanged(event, ctx) runs after an admin's change is stored: the OAuth callback (completeAuthorization, completeConnectionRoute), a saved key (saveCredential, saveCredentialAction) and a disconnect (disconnect, disconnectAction). event is { change, provider, accountId, kind, actorId, at } (actorId is the admin's auth user id, null for a script) with change:

  • connected: a new connection;
  • reconnected: a connection that existed (connected or reconnect_required) was replaced;
  • disconnected, with revoked: whether the provider accepted the revocation of the grant;
  • connect_failed, with code: the OAuth callback failed after its authorization was found (consent_denied, exchange_failed, client_rejected, ...), so the provider and account are those the admin started with.

A callback without a valid authorization (connections.state_invalid) and a key the form refuses change nothing and report nothing. The event never carries a credential, a code or a state. A hook that throws is logged by error kind, like onReconnectRequired.

Every change also writes one console.info line, with or without the hook; a non-plain actor id is JSON-quoted:

@softure-ai/connections: connection connected provider=google account_id=default kind=oauth actor_id=<user id>
@softure-ai/connections: connection disconnected provider=raindrop account_id=default kind=api_key actor_id=<user id> revoked=false
@softure-ai/connections: connection connect_failed provider=google account_id=default kind=oauth actor_id=<user id> code=connections.consent_denied

disconnect(ctx, { provider, accountId?, actorId? }) takes the actor for these; without it the event says null.

11. GDPR

An app connection belongs to the app (the owner's account elsewhere), not to the admin who clicked connect. A user's own connection (owner: "user") belongs to that user.

  • Export: the app connections the user made (provider, accountId, connectedAt), their pending authorizations, and their own connections (ownConnections: provider, account, subject, scopes, status, connectedAt). Never a token or a key.
  • Delete: clears the user from connected_by and keeps every app connection; deletes the user's own connections (deletedConnections) and pending authorizations. exportConnectionsUserData and deleteConnectionsUserData take { db } only.

12. Limitations

  • No provider-specific API clients; the app calls the API with the token. The one exception is /github-app: a GitHub App's installation and token calls, which an app cannot make with an OAuth token.
  • /user-oauth keeps no state of its own: the app stores the one-time state, the sealed grant and, if it wants one, a cached access token; it refreshes without a lease, so an app that refreshes one user's grant from several workers at once with a rotating provider serialises those refreshes itself.
  • Only the authorization code flow (with or without PKCE). No device flow, no client credentials grant, no OpenID Connect ID token checks: the module stores what the token endpoint answers.
  • One redirect URI for every provider (appOrigin + routes.callback).
  • getAccessToken waits for another worker's refresh by polling (refreshWait); a caller that cannot wait sets attempts: 0 and handles connections.refresh_in_progress as retryable.
  • Revocation on disconnect is best effort: the connection is deleted even when the provider does not answer.
  • A refresh that outlives its lease (a provider slower than refreshLeaseSeconds) still answers the new token but does not store it; keep httpTimeoutMs well under the lease (startup refuses a lease shorter than the timeout).

Testing an app with it

import { createFakeOAuthProvider, createTestKeyring } from "@softure-ai/connections/testing";

const fake = createFakeOAuthProvider({ rotatesRefreshToken: true });
// connections({ providers: [fake.definition], fetch: fake.fetch }), ctx.env = { ...createTestKeyring(), ...fake.env }
const started = await startAuthorization(ctx, { provider: "fake", actorId });
const callback = fake.consent(started.value.url); // the user clicks "Allow"
await completeAuthorization(ctx, { params: { state: callback.searchParams.get("state"), code: callback.searchParams.get("code"), error: null }, actorId });
fake.revokeGrant(); // the next refresh answers invalid_grant
fake.failNext("unavailable", "rate_limited"); // the next token calls fail
fake.rejectAccessTokens(); // fake.apiUrl answers 401 to every token issued so far; refresh tokens still work
await requestWithConnection(ctx, { provider: "fake" }, { url: fake.apiUrl, fetch: fake.fetch }); // refreshes, retries

A user's own GitHub App installation, with a fake that checks the App's JWT against its own key:

import { createFakeGithubProvider } from "@softure-ai/auth/testing";
import { createFakeGithubApp } from "@softure-ai/connections/testing";

const github = createFakeGithubProvider({ openSignUp: true }); // the user's sign-in and token
const app = createFakeGithubApp({
  slug: "my-app",
  setupUrl: "https://app.test/api/source/setup",
  resolveUserId: async (token) => readUserId(await github.fetch("https://api.github.com/user", { headers: { authorization: `Bearer ${token}` } })),
});
// app.credentials (appId, a PKCS#1 key) and app.fetch go to the github-app calls; `privateKey: process.env.APP_KEY`
// makes the fake use the key an app in another process was started with (an end-to-end stack)
const setup = app.install(installUrl, { account: { login: "octocat" }, userIds: [501], repositories: [{ fullName: "octocat/notes" }] });
app.uninstall(installationId); // every call about it answers 404
app.failNext("rate_limited", "unavailable");
// repository contents for an app that reads them with an installation token (commits, trees, blobs, compare)
app.createInstallation({ account: { login: "octocat" }, userIds: [501], repositories: [{ fullName: "octocat/notes", files: { "Projects/Plan.md": "# Plan" } }] });
const head = app.commitFiles("octocat/notes", { "Projects/Plan.md": "# Plan v2", "Inbox.md": "new" }); // a push
app.rewriteHistory("octocat/notes", { "Inbox.md": "only" }); // a force-push: compare from an old head answers `diverged`

Build

npm run build -w modules/connections runs tsc -p tsconfig.build.json. Releasing: scripts/release/README.md.