You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { forbidden, unauthorized } from "@/modules/auth/errors";
import {
isKnownCustomer,
listEnvCustomerIds,
resetServiceTokenEnvCache,
resolveEnvServiceToken,
type VerifiedServiceToken,
} from "@/modules/auth/service-token-env";
export type { VerifiedServiceToken } from "@/modules/auth/service-token-env";
export {
isKnownCustomer,
listEnvCustomerIds,
listRegisteredCustomerIds,
parseServiceToken,
parseServiceTokenFromEnv,
verifyServiceToken,
verifyServiceTokenFromEnv,
} from "@/modules/auth/service-token-env";
/** 测试专用:重置 env 缓存 */
export function resetServiceTokenCache(): void {
resetServiceTokenEnvCache();
}
/** 异步env + 数据库活跃客户 */
export async function listAllCustomerIds(): Promise<string[]> {
const { listActiveDbCustomerIds } = await import(
"@/modules/customer/customer-service"
);
const dbIds = await listActiveDbCustomerIds();
return [...new Set([...listEnvCustomerIds(), ...dbIds])].sort();
}
export async function isKnownCustomerAsync(
customerId: string,
): Promise<boolean> {
if (isKnownCustomer(customerId)) {
return true;
}
const { isDbCustomerActive } = await import(
"@/modules/customer/customer-service"
);
return isDbCustomerActive(customerId);
}
/** env + DB 完整校验API 路由用,勿在 middleware 引用本文件) */
export async function verifyServiceTokenAsync(
token: string,
customerId?: string,
): Promise<VerifiedServiceToken> {
const fromEnv = resolveEnvServiceToken(token, customerId);
if (fromEnv) {
return fromEnv;
}
const { resolveDbServiceToken } = await import(
"@/modules/customer/customer-service"
);
const fromDb = await resolveDbServiceToken(token);
if (!fromDb) {
throw unauthorized("Service Token 无效");
}
if (customerId && fromDb.customerId !== customerId) {
throw forbidden("customer_id 与令牌租户不匹配");
}
return fromDb;
}