# OAuth apps

> Connect your product to accounting firms' Prosaic workspaces with OAuth and PKCE, and the review policy for new apps.

Source: https://developer.prosaic.works/docs/apps/oauth-apps

An OAuth app lets someone connect your product to their Prosaic workspace without handing you an API key. They sign in to Prosaic, approve your app, and your server gets tokens that act as them.

Use one when your product works with workspaces that belong to other people. Usually that's an accounting firm: its staff keep their clients' books in Prosaic, and your practice-management, document-collection or point-of-sale product reads and writes those books on the firm's behalf.

Two other routes don't need an OAuth app:

- **Your own workspace.** For a server-side integration with books you control, use an [API key](/docs/getting-started/authentication).
- **Embedding a ledger in your product.** If you keep books for your own customers, your platform workspace owns one entity per customer. That's the [embedded ledger](/docs/ledger/embedded-ledger), and it runs on your API key.

## What works today

| Endpoint      | URL                                                                |
| ------------- | ------------------------------------------------------------------ |
| Discovery     | `https://app.prosaic.works/.well-known/oauth-authorization-server` |
| Authorisation | `https://app.prosaic.works/api/auth/oauth2/authorize`              |
| Token         | `https://app.prosaic.works/api/auth/oauth2/token`                  |
| Registration  | `https://app.prosaic.works/api/auth/oauth2/register`               |
| Revocation    | `https://app.prosaic.works/api/auth/oauth2/revoke`                 |

Read the endpoints from the discovery document rather than hard-coding them. OpenID Connect clients can use `https://app.prosaic.works/.well-known/openid-configuration`, which lists the same endpoints plus `userinfo`.

- **Grant:** authorisation code with PKCE. The only code challenge method is `S256`, and PKCE is required.
- **Scopes:** `openid`, `profile`, `email` and `offline_access`. The first three identify the user; `offline_access` gets you a refresh token. There are no narrower API scopes: the access token can do what the consenting user can do in Prosaic.
- **Access tokens** last 24 hours.
- **Refresh tokens** last 30 days and rotate. Each refresh returns a new refresh token and retires the old one, so save the new one every time.
- **Registration:** a workspace admin or owner registers an app in Prosaic, under **Settings → Developer**. Dynamic client registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) at the registration endpoint is for tools that register one client per person, such as MCP clients.

## 1. Register your app

In Prosaic, open **Settings → Developer** and choose **Register an app**. You need to be an admin or owner of your workspace; the app belongs to the workspace, not to you. Registering apps is in early access: if your workspace says so, email [hello@prosaic.works](mailto:hello@prosaic.works) and we'll turn it on.

- **Type.** Choose **Web app** if your app has a server that can keep a secret: you get a client ID and a client secret. Choose **Native app** for desktop and mobile apps, or **Single-page app** for code that runs only in the browser: these are public clients with no secret, and PKCE protects the exchange.
- **Redirect URIs.** Where Prosaic sends people back with a code. They must use `https`. Native apps may also use a loopback address such as `http://127.0.0.1:8123/callback`, or a reverse-domain scheme such as `com.example.app:/callback`. No wildcards or fragments.
- **Links.** A homepage, privacy policy and terms (all optional, all `https`). They appear on the consent screen next to your app's name and your workspace's name.

Copy the client secret when it appears: it's shown once. You can rotate it later from the app's page; the old secret stops working straight away.

Register a product integration here rather than through dynamic registration. A client registered dynamically isn't tied to a workspace, so the consent screen can't say who built it, and it can't be reviewed.

## 2. Send the user to Prosaic

The [Node SDK](/docs/sdk/node) has the flow built in. It generates the PKCE verifier and `state` for you:

```ts
import { OAuth } from 'prosaic-node';

const clientId = process.env.PROSAIC_CLIENT_ID;
if (!clientId) throw new Error('Set PROSAIC_CLIENT_ID');

const oauth = new OAuth({
  clientId,
  clientSecret: process.env.PROSAIC_CLIENT_SECRET, // Omit for a public client
});

const authorization = oauth.createAuthorization({
  redirectUri: 'https://acme.example/oauth/callback',
});

// Save `authorization` in this user's server-side session,
// then redirect their browser to authorization.url.
```

By default it asks for `openid profile email offline_access`. The user signs in to Prosaic if they need to, then sees a consent screen listing the scopes, and allows or denies your app. The screen shows your app's name, your workspace's name and your links, and until Prosaic has reviewed your app, it says so.

Without the SDK, redirect to the authorisation endpoint with `response_type=code`, `client_id`, `redirect_uri`, `scope`, `state`, `code_challenge` and `code_challenge_method=S256`.

## 3. Exchange the code

On your callback route, finish the flow with the authorisation you saved. `completeAuthorization` checks the callback's address and `state` before it exchanges the code:

```ts
const tokens = await oauth.completeAuthorization(callbackUrl, authorization);
// { access_token, refresh_token, expires_at, scope, id_token, ... }
```

Use the saved authorisation once, then delete it. Store the tokens encrypted, including `expires_at` and the refresh token.

Without the SDK, POST a form to the token endpoint:

```bash
curl -X POST https://app.prosaic.works/api/auth/oauth2/token \
  -u "$PROSAIC_CLIENT_ID:$PROSAIC_CLIENT_SECRET" \
  -d grant_type=authorization_code \
  -d code="$CODE" \
  -d redirect_uri=https://acme.example/oauth/callback \
  -d code_verifier="$CODE_VERIFIER"
```

A public client sends `client_id` in the form instead of the `-u` credentials. To refresh, send `grant_type=refresh_token` with the `refresh_token`.

## 4. Call the API

Send the access token as a Bearer token. Each request acts as the user who approved your app, with the role they hold in the workspace you select:

```ts
import Prosaic from 'prosaic-node';

const prosaic = new Prosaic({
  // Refreshes before expiry and hands you the rotated tokens to save.
  accessToken: oauth.createTokenProvider(tokens, (updated) =>
    saveTokens(userId, updated),
  ),
});

// Which workspaces can this user reach?
const { data: me } = await prosaic.me.retrieve();
for (const workspace of me.workspaces) {
  console.log(workspace.id, workspace.name, workspace.role);
}

// Work in one of them.
const entities = await prosaic.entities
  .list({}, { workspaceId: me.workspaces[0].id })
  .autoPagingToArray({ limit: 100 });
```

`saveTokens` is your own function, and it must save atomically. Pass `workspaceId` in a method's last argument, as above, or once to `new Prosaic({ accessToken, workspaceId })`. If your app runs in several processes, make sure only one refreshes a given grant at a time.

Over plain HTTP:

```bash
curl https://app.prosaic.works/api/public/v1/entities \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "x-workspace-id: $WORKSPACE_ID"
```

- **`x-workspace-id`** picks the workspace. Without it, the request uses the user's active workspace in Prosaic, which can change under you, so always send it. A workspace the user doesn't belong to returns `403 Not a member of requested workspace`.
- **Firm accounts only.** People who reach Prosaic through a client portal (the `client` and `standard_user` roles) can't use the API through third-party apps. Their requests return `403` with the code `CLIENT_API_ACCESS_DISABLED`.
- **Expired trials.** A workspace whose trial has ended returns `403` with the code `TRIAL_EXPIRED`.
- **`invalid_grant` on refresh** means the grant can't be refreshed. Ask the user to connect again rather than retrying.

When a user disconnects your app, revoke the refresh token with `oauth.revokeToken(refreshToken, 'refresh_token')` or the revocation endpoint.

## Review

New apps start unreviewed, and an unreviewed app can connect to **5 workspaces besides your own**. That's enough to build, test and pilot with a few firms; ask for a review when you need more.

- **What counts.** A workspace counts once anyone in it approves your app. Approving connects every workspace that person belongs to, because your token can reach each of them, so a person in two firms' workspaces uses two places. Several people in the same workspace count once.
- **Your own workspace never counts**, so test there as much as you like.
- **Disconnecting doesn't free a place.** The count is every workspace your app has reached.
- **At the limit,** Prosaic refuses the consent for a new workspace and tells the person to ask you to request a review. People in workspaces you already reach can still connect.
- **Request a review** from your app's page in Settings → Developer. Prosaic approves or rejects it, with a note you'll see on the same page.
- **Once approved** there's no limit. An approved app's redirect URIs are locked so they can't be swapped after review; contact Prosaic to change them.
- **If it's rejected,** your existing connections keep working and the limit stays at 5. Fix what the note says and request a review again.
- **Turning an app off** in Settings signs everyone out of it: their tokens stop working, and they reconnect once you turn it back on.

Apps Prosaic registers, and clients registered dynamically, aren't limited. The [embedded ledger](/docs/ledger/embedded-ledger) isn't affected either: it runs in your own workspace on your API key, with no OAuth app involved.

Questions about reviews: [support@prosaic.works](mailto:support@prosaic.works).
