Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sdk): user api key support in sdk (#6292)
Will Hutchinson0171cf92ce75
diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex f5e0f3c780..6d6f774938 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -18,27 +18,69 @@ const macro = new Macro({ }); // uses MACRO_API_KEY env var### Authenticating-The SDK can authenticate as a **user** (a Macro API token, sent as an-`Authorization` bearer) or as a **bot** (an `mbot_` API key, created under-Settings → Bots in the web app). With no explicit `auth`, the SDK falls back-to the `MACRO_API_KEY` (user) or `MACRO_BOT_TOKEN` (bot) env var.+Every request the SDK sends carries exactly one Macro credential. There are three kinds.++| Credential | Minted in | Prefix | Acts as |+| --- | --- | --- | --- |+| API key | Settings → API Keys | `mak_` | the user who minted it |+| Bot token | Settings → Bots | `mbot_` | the bot, optionally on behalf of a user |+| Bearer token | a signed-in session | none (JWT) | the signed-in user |++#### API key++The default for scripts and integrations. Put the key in `MACRO_API_KEY` and construct with no options.```ts-const asUser = new Macro({ auth: { type: 'user', token: myApiToken } });-const asBot = new Macro({ auth: { type: 'bot', token: myBotKey } });+import { Macro } from '@macro/sdk';++const macro = new Macro({});+const me = await macro.users.me();```-A bot can act on behalf of a user it's authorized for (its owner, or a member-of its owning team):+Or pass it in code. `token` accepts an API key or a bearer token. The SDK picks the header from the prefix.```ts+const macro = new Macro({ token: process.env.MACRO_API_KEY });+```++The explicit form names the credential kind. Use it when the key is not from an env var, or when it predates the `mak_` prefix.++```ts+const macro = new Macro({+ auth: { type: 'user', apiKey: process.env.MACRO_API_KEY },+});+```++An API key always acts as the user who minted it. `requestedAs` is bot-only.++#### Bot token++```ts+const asBot = new Macro({ auth: { type: 'bot', token: process.env.MACRO_BOT_TOKEN } });const asWolf = asBot.requestedAs('macro|[email protected]');```-Bot requests carry an access scope: `user` (the requested-as user's access —-the default whenever `requestedAs` is used) or `team` (the owning team's-access, for team-owned bots — the default otherwise). Pass-`auth: { type: 'bot', token, scope: ... }` to override.+Bot requests carry an access scope. `user` uses the requested-as user's access, and is the default when `requestedAs` is set. `team` uses the owning team's access, for team-owned bots, and is the default otherwise. Pass `auth: { type: 'bot', token, scope: ... }` to override.++#### Bearer token++A session token, for code running with a signed-in user. Sent as `Authorization: Bearer`. The function form refreshes it.++```ts+const macro = new Macro({ auth: { type: 'user', token: () => session.accessToken() } });+```++#### Which header goes out++The backend rejects a request carrying two credentials with `400 ambiguous credentials`. The SDK sets exactly one.++| You passed | Header sent |+| --- | --- |+| `apiKey: '…'` | `x-macro-user-api-key: …` |+| `token: 'mak_…'` or `MACRO_API_KEY=mak_…` | `x-macro-user-api-key: mak_…` |+| `token: '<jwt>'` or `MACRO_API_KEY=<jwt>` | `Authorization: Bearer <jwt>` |+| `token: 'mbot_…'` | throws. Use `auth: { type: 'bot', token }` or `MACRO_BOT_TOKEN`. |+| `type: 'bot'` | `x-macro-bot-token` plus `x-macro-bot-scope` |### Accessing our APIdiff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.tsindex 7a8b9e7272..d1437d9ca4 100644--- a/packages/sdk/src/config.ts+++ b/packages/sdk/src/config.ts@@ -71,8 +71,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {},};-/** A bearer token, or a (possibly async) function that returns one — the- * function form lets you refresh tokens without reconfiguring. */+/** A credential string, or a (possibly async) function that returns one. */export type TokenSource = string | (() => string | Promise<string>);/** Access scope for bot-authenticated requests. `user` acts with the@@ -80,24 +79,34 @@ export type TokenSource = string | (() => string | Promise<string>);* bot's owning team's access (team-owned bots only). */export type BotScope = 'user' | 'team';-/** How the SDK authenticates with Macro.+/**+ * How the SDK authenticates with Macro.*- * - `user`: a human's Macro API token, sent as `Authorization: Bearer`.- * - `bot`: an `mbot_` API key, sent as `x-macro-bot-token` together with- * `x-macro-bot-scope`. When `scope` is omitted it defaults to `user` when- * `requestedAs` is set (user scope requires an acting user) and `team`- * otherwise.+ * A user has exactly one of two credential fields.+ *+ * - `token`: a bearer token, or a `mak_` API key. The SDK picks the header+ * from the prefix at send time.+ * - `apiKey`: a Settings → API Keys key, always sent as+ * `x-macro-user-api-key`. Not prefix-checked, so keys that predate the+ * `mak_` prefix work here.+ *+ * A bot uses an `mbot_` token as `x-macro-bot-token` plus+ * `x-macro-bot-scope`, defaulting to `user` when `requestedAs` is set and+ * `team` otherwise.*/export type MacroAuth =- | { type: 'user'; token: TokenSource }+ | { type: 'user'; token: TokenSource; apiKey?: never }+ | { type: 'user'; apiKey: string; token?: never }| { type: 'bot'; token: TokenSource; scope?: BotScope };/** Options passed to `new Macro(opts)` and stored on `MacroClient`. */export interface MacroOpts {- /** How to authenticate. Takes precedence over `token`. Falls back to the- * MACRO_API_KEY (user auth) or MACRO_BOT_TOKEN (bot auth) env var. */+ /** How to authenticate. Takes precedence over `token`. Falls back to+ * `MACRO_API_KEY` (a user API key or bearer token) or `MACRO_BOT_TOKEN`+ * (bot). */auth?: MacroAuth;- /** Shorthand for `auth: { type: 'user', token }`. */+ /** Shorthand for `auth: { type: 'user', token }`. Accepts a Settings API+ * key (`mak_…`) or a bearer token. */token?: TokenSource;/** Which Macro environment to talk to. Falls back to the MACRO_ENV env* var, then `'dev'`. */diff --git a/packages/sdk/src/utils/client.ts b/packages/sdk/src/utils/client.tsindex 9b9aefb5c4..7f8f75bbb0 100644--- a/packages/sdk/src/utils/client.ts+++ b/packages/sdk/src/utils/client.ts@@ -1,3 +1,4 @@+import { match, P } from 'ts-pattern';import { Sdk as AgentHarnessSdk } from '../../generated/agent-harness/sdk.gen';import { Sdk as AuthSdk } from '../../generated/auth/sdk.gen';import { Sdk as CognitionSdk } from '../../generated/cognition/sdk.gen';@@ -15,6 +16,7 @@ import {type MacroAuth,type MacroOpts,type ServiceName,+ type TokenSource,WEB_APP_URLS,} from '../config';import { BotsNamespace } from '../entities/bots/namespace';@@ -22,6 +24,74 @@ import { User } from '../entities/users/user';import { MacroEvents } from '../events/receiver';import { type LocalPortmap, resolveLocalPortmap } from '../local-portmap';+const USER_API_KEY_HEADER = 'x-macro-user-api-key';+const USER_API_KEY_PREFIX = 'mak_';+const BOT_TOKEN_PREFIX = 'mbot_';++type CredentialHeader = readonly [name: string, value: string];++function userCredentialHeader(secret: string): CredentialHeader {+ return match(secret)+ .with(P.string.startsWith(BOT_TOKEN_PREFIX), () => {+ throw new Error(+ "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",+ );+ })+ .with(+ P.string.startsWith(USER_API_KEY_PREFIX),+ (key): CredentialHeader => [USER_API_KEY_HEADER, key],+ )+ .otherwise(+ (token): CredentialHeader => ['Authorization', `Bearer ${token}`],+ );+}++async function resolveToken(source: TokenSource): Promise<string> {+ return typeof source === 'function' ? await source() : source;+}++export async function requestAuthHeaders(+ auth: MacroAuth,+ requestedAs?: string,+ existing?: { hasBotScope?: boolean },+): Promise<ReadonlyArray<readonly [string, string]>> {+ return match(auth)+ .with({ type: 'bot' }, async (botAuth) => {+ const tok = await resolveToken(botAuth.token);+ if (!tok.startsWith(BOT_TOKEN_PREFIX)) {+ throw new Error(+ "user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.",+ );+ }+ const headers: Array<readonly [string, string]> = [+ ['x-macro-bot-token', tok],+ ];+ if (!existing?.hasBotScope) {+ headers.push([+ 'x-macro-bot-scope',+ botAuth.scope ?? (requestedAs ? 'user' : 'team'),+ ]);+ }+ if (requestedAs) {+ headers.push(['x-macro-bot-for-macro-user-id', requestedAs]);+ }+ return headers;+ })+ .with({ type: 'user', apiKey: P.string }, ({ apiKey }) => {+ if (apiKey.startsWith(BOT_TOKEN_PREFIX)) {+ throw new Error(+ "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",+ );+ }+ return [[USER_API_KEY_HEADER, apiKey] as const];+ })+ .with({ type: 'user' }, async ({ token }) => {+ const pair = userCredentialHeader(await resolveToken(token));+ return [pair];+ })+ .exhaustive();+}+export class MacroClient {readonly agentHarness: AgentHarnessSdk;readonly auth: AuthSdk;@@ -133,32 +203,13 @@ export class MacroClient {private makeClient(baseUrl: string) {const c = createClient({ baseUrl });c.interceptors.request.use(async (request) => {- const source = this.authConfig.token;- const tok = typeof source === 'function' ? await source() : source;- if (this.authConfig.type === 'bot') {- request.headers.set('x-macro-bot-token', tok);- // A per-call scope wins: the channel webhook fallback pins `user`,- // the only scope a user-owned bot can present (a team scope with no- // owning team is rejected outright).- if (!request.headers.has('x-macro-bot-scope')) {- request.headers.set(- 'x-macro-bot-scope',- this.authConfig.scope ?? (this.requestedAs ? 'user' : 'team'),- );- }- if (this.requestedAs) {- request.headers.set(- 'x-macro-bot-for-macro-user-id',- this.requestedAs,- );- }- } else {- if (tok.startsWith('mbot_')) {- throw new Error(- "bot API key passed as a user token — use auth: { type: 'bot', token } (or MACRO_BOT_TOKEN)",- );- }- request.headers.set('Authorization', `Bearer ${tok}`);+ const headers = await requestAuthHeaders(+ this.authConfig,+ this.requestedAs,+ { hasBotScope: request.headers.has('x-macro-bot-scope') },+ );+ for (const [name, value] of headers) {+ request.headers.set(name, value);}return request;});@@ -198,7 +249,7 @@ function resolveAuth(opts: MacroOpts): MacroAuth {envApiKey ??(() => {throw new Error(- 'no Macro API token — set MACRO_API_KEY / MACRO_BOT_TOKEN or pass token/auth to new Macro()',+ 'no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().',);}),};diff --git a/packages/sdk/tests/auth-headers.test.ts b/packages/sdk/tests/auth-headers.test.tsnew file mode 100644index 0000000000..05013bfb3b--- /dev/null+++ b/packages/sdk/tests/auth-headers.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from 'bun:test';+import { Macro } from '../src/macro';+import { requestAuthHeaders } from '../src/utils/client';++describe('requestAuthHeaders', () => {+ test('token: mak_abc sends the user API key header', async () => {+ expect(+ await requestAuthHeaders({ type: 'user', token: 'mak_abc' }),+ ).toEqual([['x-macro-user-api-key', 'mak_abc']]);+ });++ test('auth.apiKey sends a legacy unprefixed key', async () => {+ expect(+ await requestAuthHeaders({ type: 'user', apiKey: 'legacy0123' }),+ ).toEqual([['x-macro-user-api-key', 'legacy0123']]);+ });++ test('auth.apiKey rejects an mbot_ token', async () => {+ await expect(+ requestAuthHeaders({ type: 'user', apiKey: 'mbot_x' }),+ ).rejects.toThrow(+ "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",+ );+ });++ test('token JWT sends Authorization Bearer', async () => {+ expect(+ await requestAuthHeaders({ type: 'user', token: 'eyJhbGciOi.jwt' }),+ ).toEqual([['Authorization', 'Bearer eyJhbGciOi.jwt']]);+ });++ test('token: mbot_x rejects', async () => {+ await expect(+ requestAuthHeaders({ type: 'user', token: 'mbot_x' }),+ ).rejects.toThrow(+ "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",+ );+ });++ test('bot auth with a mak_ token rejects', async () => {+ await expect(+ requestAuthHeaders({ type: 'bot', token: 'mak_abc' }),+ ).rejects.toThrow(+ "user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.",+ );+ });++ test('bot auth with a legacy API key rejects', async () => {+ await expect(+ requestAuthHeaders({ type: 'bot', token: 'legacy0123' }),+ ).rejects.toThrow(+ "user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.",+ );+ });+});++describe('requestedAs', () => {+ test('throws at construction for a user apiKey', () => {+ expect(+ () =>+ new Macro({+ auth: { type: 'user', apiKey: 'mak_abc' },+ requestedAs: 'macro|[email protected]',+ }),+ ).toThrow(+ 'requestedAs() requires bot auth — a user token always acts as its own user',+ );+ });+});