import { hmac } from '@noble/hashes/hmac'; import { sha256 } from '@noble/hashes/sha2'; import { GuestError, GuestPayload, GuestSigner } from './GuestContracts'; export const GUEST_REGISTRATION_PATH = '/account/v2/guest/login'; /** 协议签名,不负责发送请求或读取配置。 / Protocol signing without transport or configuration access. */ export class HmacGuestSigner implements GuestSigner { constructor(private readonly secret: string, private readonly nonce: () => string, private readonly clock: () => number = Date.now) { if (typeof secret !== 'string' || !secret.trim()) throw new GuestError('configuration', 'Guest signing configuration is unavailable.'); } headers(payload: GuestPayload): Record { const timestamp = String(Math.floor(this.clock() / 1000)); const nonce = this.nonce(); if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp)) || Number(timestamp) <= 0 || !/^[a-zA-Z0-9-]{16,128}$/.test(nonce)) { throw new GuestError('configuration', 'Unable to prepare a secure sign-in request.'); } // 仅签白名单;false 必须参与,空 uid 是第五行。 / Sign only allowed fields; include false and the empty fifth uid line. const fields: Record = { guest_id: payload.guest_id, pkg: payload.pkg, device_type: payload.device_type, register_device: payload.register_device, install_fb: String(payload.install_fb), gyroscope_not_spinning: String(payload.gyroscope_not_spinning), }; const canonical = Object.keys(fields).filter(key => fields[key] !== '').sort().map(key => `${key}=${fields[key]}`).join('&'); const message = ['POST', GUEST_REGISTRATION_PATH, timestamp, nonce, '', canonical].join('\n'); const signature = Array.from(hmac(sha256, this.secret, message), value => value.toString(16).padStart(2, '0')).join(''); return { 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Sign': signature }; } }