@dofe/sso-nestjs

中文文档
0.1.86发布于 2026/11/11MITTypeScriptCommonJS近 30 天下载 3080

NestJS integration for sso.dofe.ai internal service APIs.

原始使用文档
文档目录7 节
  1. Install
  2. Usage
  3. AuthGuard base
  4. OIDC Relying Party
  5. Boundary
  6. 固定浏览器双入口
  7. Optional session timing

@dofe/sso-nestjs

NestJS integration for sso.dofe.ai internal service APIs.

Install

pnpm add @dofe/sso-nestjs @dofe/sso-node @nestjs/axios

Usage

import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SsoClientModule } from '@dofe/sso-nestjs';

@Module({
  imports: [
    SsoClientModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        baseUrl: config.getOrThrow('SSO_INTERNAL_API_URL'),
        internalSecret: config.getOrThrow('INTERNAL_API_SECRET'),
        serviceName: 'agents.dofe.ai',
      }),
    }),
  ],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { SsoClientService } from '@dofe/sso-nestjs';

@Injectable()
export class ExampleService {
  constructor(private readonly sso: SsoClientService) {}

  async loadUser(userId: string) {
    return this.sso.getUser(userId);
  }
}

For low-level access, use the underlying @dofe/sso-node client:

await this.sso.client.users.get(userId);
await this.sso.client.teams.getMembers(teamId);
await this.sso.client.permissions.check({ userId, teamId, permission });

For migration from existing local SSO clients, SsoClientService also exposes flat helper methods:

await this.sso.getUser(userId);
await this.sso.getUserTeams(userId);
await this.sso.checkPermission(userId, permission, teamId);
await this.sso.getTeamMembers(teamId);
await this.sso.getUserTeamRole(teamId, userId);
await this.sso.getTenantMembers(tenantId);
await this.sso.getUserTenantRole(tenantId, userId);

For permission checks, prefer SsoPermissionService over hand-written HTTP clients in consuming projects:

import { Injectable } from '@nestjs/common';
import { SsoPermissionService } from '@dofe/sso-nestjs';

@Injectable()
export class PermissionService {
  constructor(private readonly ssoPermissions: SsoPermissionService) {}

  checkLoopPermission(userId: string, action: string, teamId?: string) {
    return this.ssoPermissions.checkModulePermission(userId, 'vibecoding', 'loops', action, teamId);
  }
}

AuthGuard base

Consumer AuthGuards extend DofeSsoAuthGuardBase, delegating the standard SSO token-verify / blacklist / local-user / admin flow to the SDK and keeping only project-specific logic in SsoAuthGuardHooks + a subclass.

import { Injectable } from '@nestjs/common';
import {
  DofeSsoAuthGuardBase,
  type SsoAuthGuardHooks,
  type SsoAuthenticatedRequest,
} from '@dofe/sso-nestjs';

@Injectable()
export class MyAuthHooks implements SsoAuthGuardHooks {
  async resolveLocalUser(ssoSub, claims) {
    /* find/create local user */
  }
  resolveIsAdmin(localUser, claims) {
    return localUser.isAdmin;
  }
  async isBlacklisted?(token) {
    /* optional token blacklist */
  }
  async shouldBypass?(req, ctx) {
    /* optional: health/internal bypass */
  }
}

@Injectable()
export class AuthGuard extends DofeSsoAuthGuardBase {
  /* project-specific checks only */
}

Dev-only bypass (e.g. MODE_USER_ID) is intentionally NOT in the base — implement it in your subclass or shouldBypass hook.

OIDC Relying Party

SsoOidcRelyingPartyModule + SsoOidcRelyingPartyService own the PKCE authorize / callback / exchange / refresh / logout flow. Production must inject a Redis-backed state store (the default InMemoryStateStore loses state on restart and does not share across instances):

import {
  SsoOidcRelyingPartyModule,
  OIDC_RP_STATE_STORE,
  createRedisOidcStateStore,
} from '@dofe/sso-nestjs';

SsoOidcRelyingPartyModule.forRootAsync({
  inject: [ConfigService, RedisService],
  useFactory: (config, redis) => ({
    clientId: config.getOrThrow('SSO_CLIENT_ID'),
    clientSecret: config.getOrThrow('SSO_CLIENT_SECRET'),
    issuerUrl: config.getOrThrow('SSO_ISSUER'),
    internalIssuerUrl: config.get('SSO_INTERNAL_API_URL'),
    redirectPath: '/auth/oidc/callback',
    successPath: '/auth/oidc/success',
    serviceName: 'agents.dofe.ai',
  }),
  stateStore: {
    provide: OIDC_RP_STATE_STORE,
    inject: [RedisService],
    useFactory: (redis) => createRedisOidcStateStore(redis, { keyPrefix: 'dofe:oidc:' }),
  },
});

createRedisOidcStateStore is driver-agnostic (duck-typed ioredis surface) — the SDK does NOT depend on any redis driver; pass your app's existing client.

OIDC helpers (DOFE_RF_COOKIE, classifyRefreshError, resolveOidcUrls, isSecureCookieRequired, getCookieDomain, getDefaultCookieOptions) are framework-free and can be imported on their own.

Boundary

This package wraps @dofe/sso-node with a Nest module and HttpService fetcher. It does not include Redis event subscribers, Prisma, migrations, seeds, or database connection logic.

固定浏览器双入口

SessionV2BffOptions.browserContexts 与 resolveBrowserContext(request) 必须同时配置。 第一项 id 为 canonical,Cookie 名与路径必须等于原配置,保留已有 vault;其他 登记 id 使用独立 vault 与交换密文。解析器只能依据边缘覆盖的完整固定元数据组合 选择登记 id,不能接受任意 URL、origin、query 或调用者自报 realm。

配置解析器后,登录使用 establishForRequest(request, reply, tokens, user); sealExchange(tokens, user, request) 和 redeemExchange(reply, sealed, request) 必须传真实请求。缺请求或未知 id 均拒绝,不能隐式回到 canonical。 publicApiPath 始终为资源合同的 canonical 路径;浏览器 SDK 单独映射 alias 传输路径。

每项 context 的 browserOrigin、cookieName、cookiePath 为固定服务端配置, __Host- Cookie 必须 Path=/ 且无 Domain。native 跨应用 bootstrap 还需固定 bootstrapRedirectUri(目标 client 精确登记回调);非 canonical 没有该项时拒绝 bootstrap。该 URI 由 BFF 送往 SSO,不接受浏览器 body 中的目标声明。

撤销 SID 的共享索引覆盖全部 context。内部 dispatch proof 保存并校验已选 context, 不根据缺少外部头的 loopback 请求重新选择入口。

Optional session timing

SessionV2ClientOptions.onTiming and SessionV2BffOptions.onTiming accept SessionV2TimingObserver, (event: SessionV2TimingEvent) => void | Promise<void>. All timing types are exported from the package root. The hook is optional; synchronous throws and asynchronous rejections are ignored, and promises are never awaited. Keep observer synchronous work short.

Events contain only phase, operation, nonnegative durationMs, outcome (success or error), and optional numeric HTTP status. No identifiers, request objects, URLs, credentials, or response payloads are emitted.

PhaseOperationBoundary
remoteexchange-code, rotate, introspect, renew-ticket, confirmation, bootstrap-exchange, logout-confirmation, logout, callSSO fetch through JSON body parsing and HTTP error handling. call is the fixed fallback for other paths. Method-level schema checks after the call are outside this span.
active-entryreadVault read, expiry and revocation checks.
admissionbegin-dispatch, begin-window-dispatchVault admission, including its remote introspection and lease acquisition.
completioncompleteVault completion commit.
compat-dispatchdispatchCompatibility upstream fetch through buffered body and completion, or stream handoff; excludes subsequent streaming duration.

Nested spans overlap: do not sum admission/completion and their remote spans. status is the original HTTP response status, even when the SDK normalizes an error to 503. A remote success describes HTTP/JSON completion, not an active session grant. Compatibility HTTP statuses >= 400 produce error outcomes without changing the upstream response. Direct transport remains in-process and emits no compat-dispatch span. Compatibility response forwarding preserves Server-Timing and the existing x-request-id; it does not inject or rewrite proof-bound request headers or forward arbitrary upstream headers. No correlation identifier is added to events; applications may associate events using their own async context.

版本与发布记录

@dofe/sso-nestjs 共发布 83 个版本,首次发布于 2026/06/06;过去 12 个月发布了 83 个版本。

版本发布日期距今
0.1.86latest2026/11/112 天前
0.1.852026/11/0211 天前
0.1.842026/10/2816 天前
0.1.832026/10/2717 天前
0.1.822026/10/2717 天前
0.1.812026/10/2717 天前

关于 @dofe/sso-nestjs 的常见问题

@dofe/sso-nestjs 是什么?

NestJS integration for sso.dofe.ai internal service APIs.

如何安装 @dofe/sso-nestjs?

在项目目录运行 npm install @dofe/sso-nestjs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(^7.8.0)、@nestjs/core(^11.0.0)、@nestjs/axios(^4.0.0)、@nestjs/common(^11.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dofe/sso-nestjs 支持 TypeScript 吗?

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

@dofe/sso-nestjs 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@dofe/sso-nestjs 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dofe/sso-nestjs 可以商用吗?

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

@dofe/sso-nestjs 的下载量有多少?

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

@dofe/sso-nestjs 还在维护吗?

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