platform.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /**
  2. * 平台网关调用(总则§16.1:登录页归 SEOH 平台,本系统不自建登录校验)。
  3. *
  4. * 三步式真实登录:图形验证码 → 凭证校验拿 challenge_token → 密码登录拿 access_token。
  5. * 本地 otp-service 开了 OTP_SERVICE_BYPASS_CAPTCHA_VERIFY,故 code 可固定 "0000";
  6. * 生产环境必须把图片渲染出来让用户输入(见 LoginPage 的验证码图)。
  7. */
  8. import { GATEWAY_BASE, newRequestId } from "./gateway";
  9. /** 网关规定的平台服务前缀=`/api/system`,调用处再拼 `/{service_name}/{operation_id}`。 */
  10. const GW = `${GATEWAY_BASE}/api/system`;
  11. /** 由 vite.config.ts `define` 注入的项目空间标识(见该文件 seoCtx 注释)。 */
  12. declare const __SEO_CTX__:
  13. | { tenant_id: string; project_id: string; env: string; stage: string }
  14. | undefined;
  15. export const SEO_CTX = __SEO_CTX__ ?? { tenant_id: "", project_id: "", env: "nonprod", stage: "dev" };
  16. /**
  17. * 登录档位:
  18. * · `end_user`=项目空间账号(本系统全部业务角色账号属此档,业主 2026-11-07 裁定,
  19. * 见 18 册 §18.3),必须带 `scope_id/project_id/tenant_id/env/stage`;
  20. * · `platform`=平台身份服务账号(本机仅 `root`,用于对照),⛔ 带空间字段。
  21. * 两步(`challenge/verify` 与 `auth/password`)必须用**同一份**上下文:`challenge_token`
  22. * 一次性且与上下文绑定,第二步换上下文即 12006。
  23. */
  24. export type LoginScope = "end_user" | "platform";
  25. export function loginContext(scope: LoginScope): Record<string, string> {
  26. return scope === "end_user"
  27. ? {
  28. scope_type: "end_user",
  29. scope_id: SEO_CTX.project_id,
  30. project_id: SEO_CTX.project_id,
  31. tenant_id: SEO_CTX.tenant_id,
  32. env: SEO_CTX.env,
  33. stage: SEO_CTX.stage,
  34. }
  35. : { scope_type: "platform" };
  36. }
  37. /** 空间标识缺失时给用户的显式原因(⛔ 让请求带着空 scope_id 发出去)。 */
  38. export function ctxMissing(scope: LoginScope): boolean {
  39. return scope === "end_user" && (!SEO_CTX.project_id || !SEO_CTX.tenant_id);
  40. }
  41. export class GatewayError extends Error {
  42. constructor(
  43. public code: number | null,
  44. message: string,
  45. public status?: number,
  46. ) {
  47. super(message);
  48. }
  49. }
  50. async function post<T>(path: string, data: unknown, headers?: Record<string, string>): Promise<T> {
  51. const r = await fetch(`${GW}${path}`, {
  52. method: "POST",
  53. headers: { "Content-Type": "application/json", "X-Request-Id": newRequestId(), ...headers },
  54. body: JSON.stringify({ data }),
  55. });
  56. const body = await r.json().catch(() => ({}));
  57. const code = (body as { code?: number }).code ?? null;
  58. if (!r.ok || (code !== null && code !== 10000)) {
  59. throw new GatewayError(code, (body as { message?: string }).message ?? `HTTP ${r.status}`, r.status);
  60. }
  61. return (body as { data: T }).data;
  62. }
  63. export type Captcha = { captcha_id: string; image_base64?: string; image?: string };
  64. export async function createCaptcha(scene = "playground"): Promise<Captcha> {
  65. return post<Captcha>("/seoh-identity-provider/otp/captcha/create@v1", {
  66. channel: "captcha",
  67. scene,
  68. });
  69. }
  70. export async function verifyChallenge(input: {
  71. username: string;
  72. captchaId: string;
  73. code: string;
  74. scene?: string;
  75. scope: LoginScope;
  76. }): Promise<string> {
  77. const d = await post<{ challenge_token?: string }>("/seoh-identity-provider/auth/challenge/verify@v1", {
  78. username: input.username,
  79. channel: "captcha",
  80. code: input.code,
  81. captcha_id: input.captchaId,
  82. scene: input.scene ?? "playground",
  83. ...loginContext(input.scope),
  84. });
  85. if (!d?.challenge_token) throw new GatewayError(null, "凭证校验未返回 challenge_token");
  86. return d.challenge_token;
  87. }
  88. export type LoginResult = {
  89. access_token: string;
  90. user_id?: string;
  91. identity_id?: string;
  92. user_type?: string;
  93. scope_type?: string;
  94. scope_id?: string;
  95. expires_in?: number;
  96. };
  97. export async function loginWithPassword(input: {
  98. username: string;
  99. password: string;
  100. challengeToken: string;
  101. scope: LoginScope;
  102. }): Promise<LoginResult> {
  103. return post<LoginResult>(
  104. "/seoh-identity-provider/auth/password@v1",
  105. { username: input.username, password: input.password, ...loginContext(input.scope) },
  106. { "X-Login-Challenge-Token": input.challengeToken },
  107. );
  108. }
  109. /**
  110. * 免登录「激活码换密码」(D-12,手册 P2 客户自助激活)。
  111. *
  112. * 真源=`POST /auth/bootstrap/consume@v1`(openapi:1684,`x-require-auth:false`):校验一次性
  113. * 引导凭证 → 写入新密码 → 旧密码与未消费凭证作废 → 按普通登录**直接签发令牌**。
  114. * 与 `loginWithPassword` 同构:未携带 `X-Internal-Token` 时必须带第一步拿到的
  115. * `X-Login-Challenge-Token`,且 `data` 的 scope 上下文须与 `verifyChallenge` **同一份**,否则 12006。
  116. * ⚠️ 凭证字段名=`token`(openapi:1716 `data.required`=`token`/`new_password`/`username`),⛔ `code`/
  117. * `bootstrap_code`;凭证不存在/已过期/已使用/次数耗尽统一 12007,平台不细分原因。
  118. */
  119. export async function consumeBootstrap(input: {
  120. /** 线上字段名三必填项,由 `activationPayload()` 产出(⛔ 在这里改字段名)。 */
  121. payload: { username: string; token: string; new_password: string };
  122. challengeToken: string;
  123. scope: LoginScope;
  124. }): Promise<LoginResult> {
  125. return post<LoginResult>(
  126. "/seoh-identity-provider/auth/bootstrap/consume@v1",
  127. { ...input.payload, ...loginContext(input.scope) },
  128. { "X-Login-Challenge-Token": input.challengeToken },
  129. );
  130. }
  131. export async function logout(accessToken: string): Promise<void> {
  132. try {
  133. await fetch(`${GW}/seoh-identity-provider/auth/logout@v1`, {
  134. method: "POST",
  135. headers: {
  136. "Content-Type": "application/json",
  137. "X-Request-Id": newRequestId(),
  138. Authorization: `Bearer ${accessToken}`,
  139. },
  140. body: JSON.stringify({ data: {} }),
  141. });
  142. } catch {
  143. /* 会话已由前端销毁,登出失败不阻塞 */
  144. }
  145. }