使用 Starchild 登录

使用 Starchild Auth SDK 为网页应用添加登录、会话恢复、Guest 账号处理和服务端 token 验证。

开始前

iamstarchild.com → More → OAuth Apps → Create App 创建 OAuth 应用。填写名称、第三方网页的完整 Allowed Origin、所需 Scopes,以及可选的 System Prompt。Origin 必须包含 scheme 和端口,不含路径、query、hash 或结尾斜杠。为每个本地端口分别注册,例如 http://localhost:5173。不要注册 http://localhost:6066,这是 Starchild 网页应用自己的本地端口。

Scope 权限 审核
profile 名称、头像、用户 ID、Guest 状态 自动通过
chat 对话、线程、容器、技能、媒体、任务、钱包读取和 WebSocket 管理员审核
credit:read Credit 余额和历史 管理员审核
credit:write 充值、礼品卡、Points 兑换,并包含 credit:read 管理员审核

只选择 profile 会立即获得 Client ID。其他 Scope 需要审核。批准且 active 的应用 Origin 大约每 5 分钟同步到 CORS 白名单。

安装与登录
npm install starchild-auth-sdk
# 或 yarn add starchild-auth-sdk
# 或 pnpm add starchild-auth-sdk
import { StarchildAuth } from 'starchild-auth-sdk'

const auth = new StarchildAuth({
  clientId: 'YOUR-CLIENT-ID',
  scope: 'profile', // 仅在应用获批后添加 chat 或 credit scopes
  onLogin: ({ accessToken, refreshToken, expiresIn, userInfo }) => {
    console.log(userInfo.agentName, userInfo.isGuest)
  },
})

button.addEventListener('click', async () => {
  try { await auth.login() }
  catch (error) {
    if (error?.message?.includes('cancelled')) console.log('用户取消了登录')
    else if (error?.message?.includes('blocked')) console.log('弹窗被浏览器拦截')
    else console.error(error)
  }
})

login() 必须直接从 click 等用户手势调用。onLogin 的 payload 是 { accessToken, refreshToken, expiresIn, userInfo }

Guest 账号与绑定

没有 loginAsGuest()。Guest 与正式账号使用同一个 auth.login() 流程。若 userInfo.isGuest === true,必须在 Starchild 主站绑定 Google、X、Email、Phone 或 Wallet,不要自建绑定页:

const user = await auth.fetchUserInfo()
if (auth.isGuest() || user?.isGuest) {
  const tab = auth.bindAccount()
  if (!tab) window.location.href = auth.getBindAccountUrl()
}

绑定后下次 fetchUserInfo() 或 token refresh 应显示 isGuest: false。请明确 Guest 是否可以付款或执行不可逆操作。

服务端验证

每次请求都读取当前 token,并在服务端验证:

GET https://ai-api.iamstarchild.com/v1/oauth/userinfo
Authorization: Bearer <access-token>

使用 userInfoId 作为稳定的所有权和配额键。验证失败返回 401 并拒绝访问。403 且 detail 为 Insufficient scope 表示 token 缺少已批准的权限,不等同于过期 token。

userinfo 返回结构包括 userInfoIdagentNameagentAvatarisGuest。token refresh/logout 使用 https://go-api.iamstarchild.com/v1/oauth/{refresh,logout}

会话安全

Access token 有效期 15 分钟,默认每 12 分钟并在页面重新可见时刷新。Refresh token 有效期 7 天,保存在 localStoragestarchild_rt_{clientId}。优先使用 SDK 自动刷新;getRefreshToken() 的结果按密码处理,不要记录、外传或放入 URL。支付等敏感操作在验证失败时必须 fail closed。

排查与检查清单
  • Popup 被拦截:从 click handler 调用 login()
  • Origin 错误:检查第三方页面的 scheme 和端口,不要使用 6066。
  • CORS 错误:检查 allowed origins、审核状态,并等待约 5 分钟同步。
  • Guest:使用 auth.bindAccount(),不要自建绑定流程。
  • 401:重新登录。
  • 403 scope 错误:重新授权所需且已批准的 Scope。

  • [ ] 只申请需要的 Scope

  • [ ] 注册生产和所有本地 Origin
  • [ ] 服务端验证每个受保护请求
  • [ ] 处理 isGuest
  • [ ] 不记录或传输 Refresh token

下一步请阅读 Starchild Auth SDK API 参考。示例针对 starchild-auth-sdk 0.4.1。