diff --git a/qy_lty/common/utils.py b/qy_lty/common/utils.py new file mode 100644 index 0000000..66e6bd7 --- /dev/null +++ b/qy_lty/common/utils.py @@ -0,0 +1,32 @@ +"""通用工具函数集合。 + +注:common/ 不是 Django app(无 apps.py、未注册到 INSTALLED_APPS), +仅作为跨 app 的纯函数 utility 命名空间使用。 + +不要在此放 Django Model / Manager / 任何依赖 app registry 的对象。 +""" + + +def mask_token(token: str, visible_tail: int = 4, mask_char: str = '*') -> str: + """脱敏长 token / secret,仅保留末 N 位明文。 + + 设计动机:CredentialSlot.access_token 在 Admin 列表 / 查看态需仅显示末 4 位; + Phase 3 阿里云日志 formatter 也将复用本函数。 + + Args: + token: 待脱敏字符串;空字符串 / None 直接返回 '' + visible_tail: 末尾保留明文的字符数(默认 4) + mask_char: 掩码字符(默认 *) + + Returns: + 脱敏后的字符串。例: + 'sk-abcdef1234' -> '*********1234' + '' -> '' + None -> '' + 'abc' -> '***' # 短于 visible_tail 时全部脱敏,不暴露长度信号 + """ + if not token: + return '' + if len(token) <= visible_tail: + return mask_char * len(token) + return mask_char * (len(token) - visible_tail) + token[-visible_tail:]