2026-09-26 18:00:08 +08:00

81 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* JWT(token)解析工具 —— **仅供排障 / 诊断使用**
*
* ⚠️ 只做 base64url 解码,**不校验签名**。用途是把 token 里的 `platform_code` /
* `current_role_id` 打出来与服务端返回对账(例如排查「切换身份后重进小程序又变回旧身份」),
* **不能**用于任何鉴权判断 —— 鉴权一律以后端为准。
*
* ⚠️ 不做完整 UTF-8 解码:本项目的 token payload 全是 ASCII(id / username /
* platform_code / 时间戳)。若以后出现中文(如 real_name),解析会失败并返回 null
* (调用方按「拿不到」处理即可)。
*/
export interface TokenPayload {
/** 账号 ID */
id?: number
username?: string
/** 签发时的平台编码(后端按 (账号, platform_code) 记当前身份) */
platform_code?: string
/** 签发时的当前身份 ID(= 用户身份列表里的 employees[].id) */
current_role_id?: number
/** 签发时的当前组织 ID */
current_store_id?: number
/** 微信登录态才有 */
oauth_id?: number
iat?: number
exp?: number
[key: string]: any
}
/** 解析 JWT 的 payload 段;格式不对 / 解不出 JSON 时返回 null */
export function parseTokenPayload(token?: string): TokenPayload | null {
const parts = (token || '').split('.')
if (parts.length < 2) return null
const base64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const normalized = parts[1].replace(/-/g, '+').replace(/_/g, '/')
try {
let binary = ''
let buffer = 0
let bits = 0
for (const char of normalized) {
const index = base64Table.indexOf(char)
if (index === -1) continue
buffer = (buffer << 6) | index
bits += 6
if (bits >= 8) {
bits -= 8
binary += String.fromCharCode((buffer >> bits) & 0xff)
}
}
return JSON.parse(binary) as TokenPayload
} catch {
return null
}
}
/**
* token 指纹:只取前 12 位
*
* 为什么不全量展示:完整 token 是凭证,不能进日志 / 截图 / bug 报告;
* 前 12 位足够区分「内存里的 token」和「存储里的 token」是不是同一个。
*/
export function tokenFingerprint(token?: string): string {
if (!token) return '(空)'
return `${token.slice(0, 12)}…(共 ${token.length} 字符)`
}
/** 秒级时间戳 → `YYYY-MM-DD HH:mm:ss`(本地时区);空值返回「-」 */
export function formatTokenTime(seconds?: number): string {
if (!seconds) return '-'
const date = new Date(seconds * 1000)
if (Number.isNaN(date.getTime())) return '-'
const pad = (n: number): string => (n < 10 ? `0${n}` : String(n))
return (
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
)
}