@faable/auth-sdk

中文文档
2.9.25发布于 2026/11/12MITTypeScriptES Module近 30 天下载 1.2万

Faable Auth SDK

Client for the FaableAuth REST API — management from a server, session and login flows from a browser or CLI.

原始使用文档
文档目录24 节
  1. Install
  2. Authentication
  3. Client credentials (recommended)
  4. API key
  5. Bearer token
  6. Session cookie (browser)
  7. No credentials
  8. Identifying your integration
  9. Per-call options
  10. Constructor options
  11. Usage
  12. Users
  13. User metadata
  14. Teams
  15. Team members
  16. Roles and permissions
  17. Connections
  18. Clients
  19. Current account
  20. Pagination
  21. Webhooks
  22. Protecting your API
  23. Types
  24. License

Faable Auth SDK

Client for the FaableAuth REST API — management from a server, session and login flows from a browser or CLI.

Programmatically manage FaableAuth users, teams, connections and clients through the FaableAuth REST API — and, with the right strategy, call the tenant's session and login endpoints from a browser or a CLI.

⚠️ Where it can run depends on the credential, not on the package. The SDK itself has no Node-only dependencies and bundles for the browser. What you must never ship to a browser or any untrusted runtime is a client_secret or an API key — those grant management scopes over the tenant. A user's own bearer token or the browser's session cookie only grant what that user can do, and those are fine client-side.

StrategyCredentialGrantsWhere
authClientCredentialsclient_id + client_secretThe client's Management API scopes (its allow-list; none by default)Server only
authApikeyAPI key (fak_…)The management scopes of the keyServer only
authBearerA token the caller already holdsWhatever that token's scopes and subject allowAnywhere the token itself may live
authCookieThe browser's session cookieThe signed-in user's own session (/me, MFA, passkeys…)Browser, same-origin with the auth host
(none)—Public endpoints only (login, passwordless start, device flow…)Anywhere

Install

npm install @faable/auth-sdk

Authentication

Auth is explicit and pluggable: you pick an authStrategy and pass its config in auth. The SDK never reads credentials from the environment — read them yourself and pass them in. The strategy you choose drives the type of auth, so the editor autocompletes the right fields. The strategies are re-exported from @faable/auth-sdk, so you only ever import from this package.

Breaking change (v2): the old createClientCredentials() / createApikeyAuth() helpers (which read FAABLE_* env vars automatically) were removed. Use the authStrategy + auth pair below. domain is now required — there is no hardcoded default host anymore.

authClientCredentials is the default strategy, so you only pass auth with { client_id, client_secret } — no need to set authStrategy:

import { FaableAuthApi } from "@faable/auth-sdk";

const api = FaableAuthApi.create({
  domain: "https://<your-account>.auth.faable.link",
  auth: {
    client_id: process.env.FAABLEAUTH_CLIENT_ID!,
    client_secret: process.env.FAABLEAUTH_CLIENT_SECRET!,
  },
});

Allow the client its Management API scopes first. The token carries at most the client's allow-list (management_scopes): with no scope in auth, the whole list; with scope, the requested ones that are on it. A new client's list is empty, so until you allow scopes (dashboard → your Auth tenant → Clients → the client → OAuth → Management API scopes) every call fails with a FaableApiError whose message names management_scopes_empty and says where to fix it; asking only for scopes outside the list names management_scope_not_allowed. See Calling the Faable Management API.

By default the token is requested from <domain>/oauth/token. If your API host is not the auth server, override it with auth.domain:

auth: {
  client_id: "...",
  client_secret: "...",
  domain: "https://<your-account>.auth.faable.link", // where /oauth/token lives
}

API key

import { FaableAuthApi, authApikey } from "@faable/auth-sdk";

const api = FaableAuthApi.create({
  domain: "https://<your-account>.auth.faable.link",
  authStrategy: authApikey,
  auth: { apikey: "fak_xxxxxxxxxxxxxxxx" },
});

Bearer token

For a token you already hold — a user's access token in a CLI, a token minted elsewhere. The SDK does not mint or refresh it; whoever owns the token does. token may be a getter (sync or async): it is consulted on every request, so a getter that returns the current token keeps a long-lived client correct when the token rotates.

import { FaableAuthApi, authBearer } from "@faable/auth-sdk";

const api = FaableAuthApi.create({
  domain: "https://<your-account>.auth.faable.link",
  authStrategy: authBearer,
  auth: { token: () => session.accessToken },
});

What the calls may do is whatever the token's subject and scopes allow — a user token reaches the user's own resources, a management token reaches the management API.

For pages served under the tenant's auth host that authenticate with the browser's session cookie (the hosted login pages: /me, MFA, passkeys). No config: the browser attaches the cookie itself; the strategy makes the request withCredentials so it also does cross-origin, where the auth server must allow the page's origin for credentials.

import { FaableAuthApi, authCookie } from "@faable/auth-sdk";

const api = FaableAuthApi.create({
  domain: "https://<your-account>.auth.faable.link",
  authStrategy: authCookie,
});

No credentials

Omit auth and authStrategy and the client is anonymous — right for the public endpoints (login, /passwordless/start, the device flow, OIDC discovery). Those are not on the generated client; call them through the fetcher:

const api = FaableAuthApi.create({
  domain: "https://<your-account>.auth.faable.link",
});
await api.fetcher.post("/passwordless/start", { email, client_id });

Identifying your integration

Every request carries x-faable-client: auth-sdk/<version>+<sha> so the auth server can attribute traffic. An app that wraps the SDK can report as itself instead — the value you pass replaces the default, on data calls and on the token request alike:

FaableAuthApi.create({
  domain,
  clientInfo: { client: "my-app/1.4.0", name: "my-app" },
});

Per-call options

Every fetcher method takes timeout, responseType and retry for that one call. Retries only ever apply to GET (a replayed write could duplicate a resource), and timeout and retry multiply — a short deadline on a hot path wants retry: false next to it:

await api.fetcher.get(`/user/${id}`, { timeout: 800, retry: false });

Constructor options

OptionTypeDescription
domainstringRequired. The account host to target, e.g. https://<your-account>.auth.faable.link. No default. The protocol is optional — <your-account>.auth.faable.link and https://<your-account>.auth.faable.link are equivalent.
authStrategystrategy builderAuth strategy (authClientCredentials | authApikey | authBearer | authCookie), re-exported from @faable/auth-sdk. Defaults to authClientCredentials when auth is given; anonymous when neither is.
authconfigConfig for the chosen strategy. Its shape is inferred from authStrategy (e.g. { client_id, client_secret }).
debugbooleanEnables verbose logging in the underlying fetcher.
headers{ project_id?; account_id? }Advanced / testing escape hatch — target domain but have the server resolve a different project/account (sent as x-faable-project / x-faableauth-account). team_id is a deprecated alias of project_id: a team_<hex> value is sent as project_<hex>, and passing both with different ids throws. The SDK no longer sends x-faable-team.
clientInfo{ client?; name?; instance? }How this integration identifies itself (x-faable-client / x-faable-instance). client replaces the SDK's own auth-sdk/<version>+<sha>.

Usage

Users

// Get a user
const user = await api.getUser("user_xxx");

// Create a user
const created = await api.createUser({
  email: "[email protected]",
  password: "•••••••••",
});

// Update a user
const updated = await api.updateUser("user_xxx", { phone: "+34XXXXXXXXX" });

// List users (paginated) — first page of 30
const firstPage = await api.listUsers().first();

// Filter by email
const matches = await api.listUsers({ email: "[email protected]" }).first();

// Iterate every page
for await (const page of api.listUsers()) {
  for (const user of page) {
    // ...
  }
}

User metadata

const metadata = await api.getUserMetadata("user_xxx");

await api.setUserMetadata("user_xxx", {
  onboarded: true,
  plan: "pro",
});

Teams

const team = await api.getTeam("team_xxx");

const newTeam = await api.createTeam({ name: "Acme Inc." });

await api.deleteTeam("team_xxx");

const myTeams = await api.listTeams({ user_id: "user_xxx" }).first();

Team members

const members = await api.listTeamMembers({ query: "alice" }).first();

const isMember = await api.isUserMemberOfTeam("user_xxx", "team_xxx");

Roles and permissions

A role grants permissions of your APIs. Assign it to a user at the account level and their tokens for an API with rbac enabled carry those permissions (team roles grant none).

const role = await api.roleCreate({ name: "support" });
await api.roleAddPermissions(role.id, {
  permissions: [{ api: "api_xxx", value: "tickets:write" }],
});

await api.userAssignRoles("user_xxx", { roles: [role.id] });
const roles = await api.userRoles("user_xxx");
const permissions = await api.userPermissions("user_xxx"); // with the role that grants each

await api.userRemoveRoles("user_xxx", { roles: [role.id] });
await api.roleRemovePermissions(role.id, {
  permissions: [{ api: "api_xxx", value: "tickets:write" }],
});

Connections

const connections = await api.listConections().first();
const connection = await api.getConection("conn_xxx");

Clients

const clients = await api.listClients().first();
const client = await api.getClient("client_xxx");

Current account

const account = await api.currentAccount();

Pagination

List methods return a paginator. Use .first() to grab the first page or iterate with for await ... of to walk all pages:

const paginator = api.listUsers();

const firstPage = await paginator.first();

for await (const page of paginator) {
  // each `page` is an array of items
}

Webhooks

Faable Auth sends signed POSTs to your server when something happens in the tenant (user.created, team.member.added…). Create the subscription with faable auth webhooks create --url https://… -e user.created (it prints the signing secret once), then verify every delivery before trusting it:

import {
  constructWebhookEvent,
  readRawBody,
  WebhookVerificationError,
} from "@faable/auth-sdk";

// Next.js pages router: the signature is over the RAW body.
export const config = { api: { bodyParser: false } };

export default async function handler(req, res) {
  let event;
  try {
    event = await constructWebhookEvent(
      await readRawBody(req), // fetch-style handlers: await request.text()
      req.headers,
      process.env.FAABLEAUTH_WEBHOOK_SECRET!,
    );
  } catch (e) {
    if (e instanceof WebhookVerificationError) return res.status(401).end();
    throw e;
  }

  switch (event.type) {
    case "user.created":
      await welcome(event.payload.email); // payload is the User
      break;
    case "team.member.added":
      await sync(event.payload.team_id, event.payload.user_id);
      break;
  }
  res.status(200).end();
}
  • Answer 2xx only when the work is done. Timeouts, network errors, 5xx and 429 are retried at 1 min, 5 min, 30 min, 2 h and 12 h.
  • The same event can arrive twice (a retry after a response that was lost). event.delivery_id (x-faable-delivery) is the same on every retry: deduplicate by it, or make the work idempotent.
  • Rotation: faable auth webhooks rotate-secret keeps the old secret valid for 24 h and deliveries carry both signatures. To switch on your side without downtime, pass both: await constructWebhookEvent(body, headers, [oldSecret, newSecret]).
  • Uses Web Crypto, so it runs on Node ≥ 19, Deno, Bun and edge runtimes; that is why it is async.
  • Deliveries older than 5 minutes are refused as replays (toleranceMs to change it).

WebhookEvent, WebhookEventType, WebhookEventOf<"user.created"> and WebhookPayload<"team.member.added"> are generated from the auth OpenAPI, like every other type.

Protecting your API

Verify the access tokens your API receives and check their permissions:

import {
  AccessTokenError,
  bearerToken,
  requirePermissions,
  verifyAccessToken,
} from "@faable/auth-sdk";

export default async function handler(req, res) {
  try {
    const claims = await verifyAccessToken(bearerToken(req.headers.authorization), {
      domain: process.env.FAABLEAUTH_DOMAIN!, // https://<tenant>.auth.faable.link
      audience: "https://api.example.com", // your Api's identifier
    });
    requirePermissions(claims, "tickets:write");
    // … claims.sub is the user (or the client, for machine tokens)
  } catch (e) {
    if (e instanceof AccessTokenError) return res.status(e.status).json({ error: e.reason });
    throw e;
  }
}
  • verifyAccessToken checks the signature against the tenant JWKS (fetched once and cached), iss, aud and exp. It throws AccessTokenError with status 401.
  • requirePermissions throws AccessTokenError insufficient_scope with status 403 and missing; hasPermissions returns a boolean. Both require all the permissions passed.
  • The permissions claim needs the Api's token_dialect to be access_token_authz. With rbac on, a user token carries the permissions the client requested that the user's roles grant, so request them as scopes.

Types

All response shapes are generated from the OpenAPI spec and re-exported from the package root:

import type {
  User,
  Team,
  TeamMember,
  Connection,
  Client,
} from "@faable/auth-sdk";

License

MIT

版本与发布记录

@faable/auth-sdk 共发布 380 个版本,首次发布于 2024/05/28;过去 12 个月发布了 350 个版本。

版本发布日期距今
2.9.25latest2026/11/121 天前
2.9.242026/11/104 天前
2.9.232026/11/094 天前
2.9.222026/11/094 天前
2.9.212026/11/059 天前
2.9.202026/11/049 天前

关于 @faable/auth-sdk 的常见问题

@faable/auth-sdk 是什么?

Faable Auth SDK Client for the FaableAuth REST API — management from a server, session and login flows from a browser or CLI.

如何安装 @faable/auth-sdk?

在项目目录运行 npm install @faable/auth-sdk,或使用 pnpm add / yarn add / bun add。

@faable/auth-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@faable/auth-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@faable/auth-sdk 可以商用吗?

@faable/auth-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@faable/auth-sdk 的下载量有多少?

根据 npm 官方下载统计,@faable/auth-sdk 在 2026/10/14 – 2026/11/12 这 30 天内被下载 12,117 次,日均约 404 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@faable/auth-sdk 还在维护吗?

最新版本 2.9.25 发布于 2026/11/12(1 天前);至今共发布 380 个版本,其中过去 12 个月发布了 350 个;首次发布于 2024/05/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。