> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiveth.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node

> Verify Aiveth tokens and webhooks and call the admin API from a Node server with @gooclaim/aiveth.

`@gooclaim/aiveth` is the Aiveth by Gooclaim SDK for Node servers. Use it to check ID tokens, access tokens, machine tokens and AI agent tokens, to verify webhooks, and to call the admin API.

## Install

Requires Node 18.17 or later. CommonJS (`require`) and ES modules (`import`) both work.

```bash theme={null}
npm install @gooclaim/aiveth
```

## Configure

```ts theme={null}
import { Aiveth } from '@gooclaim/aiveth';

const aiveth = new Aiveth({
  baseUrl: 'https://accounts.aiveth.com',
  apiKey: process.env.AIVETH_API_KEY, // only for the admin API and events
});
```

| Option | Type | Description |
| - | - | - |
| `baseUrl` | `string` | Your Aiveth address. Required. |
| `apiKey` | `string` | An [API key](https://docs.aiveth.com/account/api-keys.md) (`aiveth_sk_...`). Needed only for the admin API and events. Token and webhook checks need none. |
| `fetch` | `typeof fetch` | Your own `fetch`, for tests or a runtime without a global one. |

Each environment has its own keys: `aiveth_sk_test_...` for Development and `aiveth_sk_live_...` for production.

## Tokens

### `tokens.verifyIdToken(token, { clientId })`

Checks an app's ID token offline, against Aiveth's published keys: signed by Aiveth, for this app, and not expired. Returns the claims.

```ts theme={null}
const user = await aiveth.tokens.verifyIdToken(idToken, { clientId: 'your-app-client-id' });
user.sub;        // the person
user.org_id;     // the organization
user.email;
user.role;
user.permissions;
```

### `tokens.userFromAccessToken(accessToken)`

An app's access token is opaque. Aiveth says who it stands for. Returns the claims, or `null` when the token has ended.

```ts theme={null}
const user = await aiveth.tokens.userFromAccessToken(accessToken);
if (!user) return res.status(401).end();
```

### `tokens.verifyMachineToken(token, { orgId })`

Checks a [machine app's](https://docs.aiveth.com/apps/machine-to-machine.md) token meant for your organization's services.

```ts theme={null}
const machine = await aiveth.tokens.verifyMachineToken(token, { orgId: 'your-organization-id' });
machine.client_id; // the machine app
machine.scope;
```

### `tokens.verifyMcpToken(token, { resource, scopes? })`

Checks an AI agent's token for your MCP server. `resource` is the server's address as registered in Aiveth. A token for any other server is refused. Missing `scopes` throw `InsufficientScopeError`.

```ts theme={null}
const who = await aiveth.tokens.verifyMcpToken(bearer, {
  resource: 'https://mcp.example.com/mcp',
  scopes: ['files:read'],
});
who.sub;       // the person the agent acts for
who.client_id; // the agent
```

See [Protect an MCP server](#protect-an-mcp-server).

### `tokens.connectedToken({ accessToken, connection, clientId, clientSecret })`

Gets the Google, Microsoft or GitHub token a person connected for your organization's apps. Server only: it needs your app's secret, and the app must have Connected accounts turned on.

```ts theme={null}
const google = await aiveth.tokens.connectedToken({
  accessToken,
  connection: 'google', // 'google' | 'microsoft' | 'github'
  clientId: process.env.AIVETH_CLIENT_ID!,
  clientSecret: process.env.AIVETH_CLIENT_SECRET!,
});
google.accessToken; // call Google as the person
google.expiresIn;   // seconds left, absent when it doesn't end
```

### `tokens.discover()`

Returns Aiveth's OpenID Connect discovery document. The other token methods call it for you.

### `hasFlag(claims, key)`

Is a feature flag on for this person? Aiveth puts the flags that are on for the person in the ID token as `feature_flags`.

```ts theme={null}
import { hasFlag } from '@gooclaim/aiveth';

if (hasFlag(user, 'new-billing')) {
  // show the new billing page
}
```

## Webhooks

### `verifyWebhook(rawBody, headers, secret, options?)`

Checks that Aiveth signed exactly these bytes, recently, and returns the parsed message. Throws `WebhookVerificationError` otherwise. `secret` is the `whsec_...` secret the console showed once.

Pass the **raw** body. Parsing and re-serialising JSON changes the bytes.

```ts theme={null}
import express from 'express';
import { verifyWebhook } from '@gooclaim/aiveth';

app.post('/webhooks/aiveth', express.raw({ type: 'application/json' }), (req, res) => {
  const event = verifyWebhook(req.body, req.headers, process.env.AIVETH_WEBHOOK_SECRET!);
  // handle event
  res.status(204).end();
});
```

Messages use the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers (Standard Webhooks). The timestamp may be up to 5 minutes (`TOLERANCE_SECONDS`) from now, or set `{ toleranceSeconds }`. A message may arrive twice: keep the `webhook-id`s you have handled and skip repeats. See [Webhooks](https://docs.aiveth.com/events/webhooks.md).

## Admin API

These need an API key with the right power. Every refusal throws `AivethError` with Aiveth's message and `status`.

### People

| Method | Does | Power |
| - | - | - |
| `people.list(email?)` | List people, or find one by email. | `people:read` |
| `people.get(id)` | One person. | `people:read` |
| `people.setRole(id, role)` | Change a role (never Owner). | `people:roles` |
| `people.setActive(id, active)` | Suspend or reactivate. | `people:manage` |
| `people.signOut(id)` | Sign the person out everywhere. | `people:manage` |
| `people.fields(id)` | Read custom fields. | `people:manage` |
| `people.setFields(id, fields)` | Change custom fields. `public` also needs `organization:fields`. | `people:manage` |
| `people.import(people)` | Import up to 500 people. | `people:manage` |
| `people.importAll(people)` | Import any number, 500 at a time. | `people:manage` |
| `people.sendResetEmails()` | Send a reset link to everyone still waiting for your old system's password check. Once a day. | `people:manage` |

```ts theme={null}
const [asha] = await aiveth.people.list('asha@example.com');
await aiveth.people.setActive(asha.id, false);

const report = await aiveth.people.importAll([
  { email: 'ravi@example.com', first_name: 'Ravi', password_hash: '$2b$12$...', password_hasher: 'bcrypt' },
]);
report.created;
report.skipped; // [{ email, why }]
```

See [Import users](https://docs.aiveth.com/access/import-users.md).

### Invitations and roles

| Method | Does | Power |
| - | - | - |
| `invitations.list()` | List invitations. | `people:manage` |
| `invitations.send(email, role?)` | Invite someone. They get an email. | `people:manage` |
| `invitations.withdraw(id)` | Withdraw an invitation. | `people:manage` |
| `roles.list()` | List your organization's roles. | `roles:read` |

```ts theme={null}
await aiveth.invitations.send('new.person@example.com');
```

### Organization fields

| Method | Does | Power |
| - | - | - |
| `organization.fields()` | Read the organization's custom fields. | `organization:fields` |
| `organization.setFields(fields)` | Change them. | `organization:fields` |

### Fine-grained permissions

Make types of part and their roles in the console first. See [Fine-grained authorization](https://docs.aiveth.com/access/fine-grained-authorization.md).

| Method | Does | Power |
| - | - | - |
| `authorization.check(personId, permission, type, externalId)` | May this person do this on this part? Returns `{ allowed, via }`. | `authorization:read` |
| `authorization.resourcesFor(personId, permission, type?)` | The parts this person may do it on. | `authorization:read` |
| `authorization.accessOf(personId)` | A person's roles on parts. | `authorization:read` |
| `authorization.register(part)` | Register a part when your app makes it. | `resources:write` |
| `authorization.find(type, externalId)` | Find a part, or `null`. | `authorization:read` |
| `authorization.get(partId)` | One part and its access. | `authorization:read` |
| `authorization.peopleWith(partId, permission)` | Who may do this on a part. | `authorization:read` |
| `authorization.change(partId, change)` | Rename it, or give it a new parent of the same type. | `resources:write` |
| `authorization.remove(partId, everythingBelow?)` | Remove a part. Refused while parts sit under it, unless `everythingBelow` is `true`. | `resources:write` |
| `authorization.give(type, externalId, role, holder)` | Give a role on a part to `{ person_id }` or `{ group_id }`. Never to the key's maker. | `authorization:write` |
| `authorization.take(accessId)` | Take it back. | `authorization:write` |

```ts theme={null}
await aiveth.authorization.register({
  type: 'branch', external_id: 'mumbai', name: 'Mumbai',
  parent_type: 'region', parent_external_id: 'west',
});
await aiveth.authorization.give('branch', 'mumbai', 'branch_approver', { person_id: raviId });
const { allowed } = await aiveth.authorization.check(raviId, 'claim:approve', 'branch', 'mumbai');
```

### Consent

For apps that ask for consent on their own screen. See [Consent](https://docs.aiveth.com/privacy/consent.md).

| Method | Does | Power |
| - | - | - |
| `consents.record(personId, noticeVersion, choices, language?)` | Record answers. `409` when the version isn't current. | `consent:write` |
| `consents.check(personId, purpose)` | `{ granted, notice_version, current, at, expires_at }` | `consent:read` |
| `consents.allows(personId, purpose)` | `check`, as `true` or `false`. | `consent:read` |
| `consents.get(personId)` | `{ person_id, consents }` for the current notice. | `consent:read` |
| `consents.withdraw(personId, purpose)` | Withdraw one purpose. | `consent:write` |
| `consents.receipt(personId)` | The signed receipt: `{ receipt, claims }`. | `consent:read` |
| `consents.import(noticeVersion, people)` | Import up to 500 earlier answers. | `consent:write` |
| `consents.importAll(noticeVersion, people)` | Import any number, 500 at a time. | `consent:write` |

```ts theme={null}
await aiveth.consents.record(personId, 3, { account: true, newsletter: false });

if (await aiveth.consents.allows(personId, 'newsletter')) {
  sendNewsletter();
}

await aiveth.consents.withdraw(personId, 'newsletter');
```

A time-bound yes stops counting on its end date, so ask `allows` each time rather than storing the answer.

### Events

### `events.list({ types?, after?, limit?, rangeStart? })`

Reads your organization's events, oldest first. Page on with `list_metadata.after`. Needs `events:read`.

```ts theme={null}
let after: string | undefined;
do {
  const page = await aiveth.events.list({ types: ['user.created'], after });
  for (const event of page.data) handle(event);
  after = page.list_metadata.after ?? undefined;
} while (after);
```

See [Event types](https://docs.aiveth.com/events/event-types.md).

## Protect an MCP server

Register your MCP server in the console under **AI agents** with its address and permissions. Then serve the protected resource metadata and check each request's token:

```ts theme={null}
import { Aiveth, protectedResourceMetadata, challenge, InsufficientScopeError } from '@gooclaim/aiveth';

const MCP = 'https://mcp.example.com/mcp';
const aiveth = new Aiveth({ baseUrl: 'https://accounts.aiveth.com' });

// GET /.well-known/oauth-protected-resource/mcp
res.json(protectedResourceMetadata({ resource: MCP, baseUrl: 'https://accounts.aiveth.com', scopes: ['files:read'] }));

// on every MCP request
try {
  const who = await aiveth.tokens.verifyMcpToken(bearer, { resource: MCP, scopes: ['files:read'] });
} catch (e) {
  const missing = e instanceof InsufficientScopeError;
  res.status(missing ? 403 : 401)
    .set('WWW-Authenticate', challenge({
      resource: MCP,
      scope: ['files:read'],
      ...(missing ? { error: 'insufficient_scope' } : {}),
    }))
    .end();
}
```

| Function | Returns |
| - | - |
| `protectedResourceMetadata({ resource, baseUrl, scopes, name? })` | The RFC 9728 document that tells agents to sign in with Aiveth. |
| `metadataUrl(resource)` | Where that document lives for your server. |
| `challenge({ resource, scope?, error?, description? })` | The `WWW-Authenticate` value for a `401` or `403`. |

An agent token is for one MCP server (its `aud`). It lasts 10 minutes, and the agent renews it. See [MCP servers](https://docs.aiveth.com/agents/mcp-server.md).

## Errors

| Error | When |
| - | - |
| `AivethError` | Aiveth refused a call, or couldn't be reached. Has `status` (or `null`). |
| `TokenVerificationError` | A token isn't valid. |
| `InsufficientScopeError` | An agent token lacks permissions. Has `missing`. |
| `WebhookVerificationError` | A webhook's signature, timestamp or secret doesn't check out. |

All of them extend `AivethError`. An outage while checking a token throws `AivethError`, never `TokenVerificationError`, so you can tell a bad token from a network problem.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.