| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- /**
- * 平台网关调用(总则§16.1:登录页归 SEOH 平台,本系统不自建登录校验)。
- *
- * 三步式真实登录:图形验证码 → 凭证校验拿 challenge_token → 密码登录拿 access_token。
- * 本地 otp-service 开了 OTP_SERVICE_BYPASS_CAPTCHA_VERIFY,故 code 可固定 "0000";
- * 生产环境必须把图片渲染出来让用户输入(见 LoginPage 的验证码图)。
- */
- import { GATEWAY_BASE, newRequestId } from "./gateway";
- /** 网关规定的平台服务前缀=`/api/system`,调用处再拼 `/{service_name}/{operation_id}`。 */
- const GW = `${GATEWAY_BASE}/api/system`;
- /** 由 vite.config.ts `define` 注入的项目空间标识(见该文件 seoCtx 注释)。 */
- declare const __SEO_CTX__:
- | { tenant_id: string; project_id: string; env: string; stage: string }
- | undefined;
- export const SEO_CTX = __SEO_CTX__ ?? { tenant_id: "", project_id: "", env: "nonprod", stage: "dev" };
- /**
- * 登录档位:
- * · `end_user`=项目空间账号(本系统全部业务角色账号属此档,业主 2026-11-07 裁定,
- * 见 18 册 §18.3),必须带 `scope_id/project_id/tenant_id/env/stage`;
- * · `platform`=平台身份服务账号(本机仅 `root`,用于对照),⛔ 带空间字段。
- * 两步(`challenge/verify` 与 `auth/password`)必须用**同一份**上下文:`challenge_token`
- * 一次性且与上下文绑定,第二步换上下文即 12006。
- */
- export type LoginScope = "end_user" | "platform";
- export function loginContext(scope: LoginScope): Record<string, string> {
- return scope === "end_user"
- ? {
- scope_type: "end_user",
- scope_id: SEO_CTX.project_id,
- project_id: SEO_CTX.project_id,
- tenant_id: SEO_CTX.tenant_id,
- env: SEO_CTX.env,
- stage: SEO_CTX.stage,
- }
- : { scope_type: "platform" };
- }
- /** 空间标识缺失时给用户的显式原因(⛔ 让请求带着空 scope_id 发出去)。 */
- export function ctxMissing(scope: LoginScope): boolean {
- return scope === "end_user" && (!SEO_CTX.project_id || !SEO_CTX.tenant_id);
- }
- export class GatewayError extends Error {
- constructor(
- public code: number | null,
- message: string,
- public status?: number,
- ) {
- super(message);
- }
- }
- async function post<T>(path: string, data: unknown, headers?: Record<string, string>): Promise<T> {
- const r = await fetch(`${GW}${path}`, {
- method: "POST",
- headers: { "Content-Type": "application/json", "X-Request-Id": newRequestId(), ...headers },
- body: JSON.stringify({ data }),
- });
- const body = await r.json().catch(() => ({}));
- const code = (body as { code?: number }).code ?? null;
- if (!r.ok || (code !== null && code !== 10000)) {
- throw new GatewayError(code, (body as { message?: string }).message ?? `HTTP ${r.status}`, r.status);
- }
- return (body as { data: T }).data;
- }
- export type Captcha = { captcha_id: string; image_base64?: string; image?: string };
- export async function createCaptcha(scene = "playground"): Promise<Captcha> {
- return post<Captcha>("/seoh-identity-provider/otp/captcha/create@v1", {
- channel: "captcha",
- scene,
- });
- }
- export async function verifyChallenge(input: {
- username: string;
- captchaId: string;
- code: string;
- scene?: string;
- scope: LoginScope;
- }): Promise<string> {
- const d = await post<{ challenge_token?: string }>("/seoh-identity-provider/auth/challenge/verify@v1", {
- username: input.username,
- channel: "captcha",
- code: input.code,
- captcha_id: input.captchaId,
- scene: input.scene ?? "playground",
- ...loginContext(input.scope),
- });
- if (!d?.challenge_token) throw new GatewayError(null, "凭证校验未返回 challenge_token");
- return d.challenge_token;
- }
- export type LoginResult = {
- access_token: string;
- user_id?: string;
- identity_id?: string;
- user_type?: string;
- scope_type?: string;
- scope_id?: string;
- expires_in?: number;
- };
- export async function loginWithPassword(input: {
- username: string;
- password: string;
- challengeToken: string;
- scope: LoginScope;
- }): Promise<LoginResult> {
- return post<LoginResult>(
- "/seoh-identity-provider/auth/password@v1",
- { username: input.username, password: input.password, ...loginContext(input.scope) },
- { "X-Login-Challenge-Token": input.challengeToken },
- );
- }
- /**
- * 免登录「激活码换密码」(D-12,手册 P2 客户自助激活)。
- *
- * 真源=`POST /auth/bootstrap/consume@v1`(openapi:1684,`x-require-auth:false`):校验一次性
- * 引导凭证 → 写入新密码 → 旧密码与未消费凭证作废 → 按普通登录**直接签发令牌**。
- * 与 `loginWithPassword` 同构:未携带 `X-Internal-Token` 时必须带第一步拿到的
- * `X-Login-Challenge-Token`,且 `data` 的 scope 上下文须与 `verifyChallenge` **同一份**,否则 12006。
- * ⚠️ 凭证字段名=`token`(openapi:1716 `data.required`=`token`/`new_password`/`username`),⛔ `code`/
- * `bootstrap_code`;凭证不存在/已过期/已使用/次数耗尽统一 12007,平台不细分原因。
- */
- export async function consumeBootstrap(input: {
- /** 线上字段名三必填项,由 `activationPayload()` 产出(⛔ 在这里改字段名)。 */
- payload: { username: string; token: string; new_password: string };
- challengeToken: string;
- scope: LoginScope;
- }): Promise<LoginResult> {
- return post<LoginResult>(
- "/seoh-identity-provider/auth/bootstrap/consume@v1",
- { ...input.payload, ...loginContext(input.scope) },
- { "X-Login-Challenge-Token": input.challengeToken },
- );
- }
- export async function logout(accessToken: string): Promise<void> {
- try {
- await fetch(`${GW}/seoh-identity-provider/auth/logout@v1`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-Request-Id": newRequestId(),
- Authorization: `Bearer ${accessToken}`,
- },
- body: JSON.stringify({ data: {} }),
- });
- } catch {
- /* 会话已由前端销毁,登出失败不阻塞 */
- }
- }
|