refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { verifyMessage, isAddress, type Hex } from 'viem'
|
||||
export function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value)
|
||||
if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']'
|
||||
return (
|
||||
'{' +
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((k) => JSON.stringify(k) + ':' + canonicalJson((value as Record<string, unknown>)[k]))
|
||||
.join(',') +
|
||||
'}'
|
||||
)
|
||||
}
|
||||
export function bodyHash(body: unknown): string {
|
||||
return body == null ? '-' : createHash('sha256').update(canonicalJson(body)).digest('hex')
|
||||
}
|
||||
export function buildMessage(
|
||||
action: string,
|
||||
wallet: string,
|
||||
timestamp: number,
|
||||
body: unknown,
|
||||
): string {
|
||||
return `TrumpSignal · ${action}\nwallet: ${wallet.toLowerCase()}\ntimestamp: ${timestamp}\nbody: ${bodyHash(body)}`
|
||||
}
|
||||
export interface ReplayStore {
|
||||
claim(signature: string, expiresAt: number): Promise<boolean>
|
||||
}
|
||||
export async function verifySignedRequest(
|
||||
input: {
|
||||
action: string
|
||||
wallet: string
|
||||
timestamp: number
|
||||
signature: string
|
||||
body: unknown
|
||||
allowReplay?: boolean
|
||||
},
|
||||
replay: ReplayStore,
|
||||
now = Date.now(),
|
||||
): Promise<void> {
|
||||
if (!isAddress(input.wallet) || !Number.isSafeInteger(input.timestamp))
|
||||
throw new Error('Invalid signed envelope')
|
||||
if (input.timestamp > now + 30_000 || now - input.timestamp > 300_000)
|
||||
throw new Error('Signed request expired or clock skew too large')
|
||||
const valid = await verifyMessage({
|
||||
address: input.wallet,
|
||||
message: buildMessage(input.action, input.wallet, input.timestamp, input.body),
|
||||
signature: input.signature as Hex,
|
||||
})
|
||||
if (!valid) throw new Error('Signature does not match wallet')
|
||||
if (!input.allowReplay && !(await replay.claim(input.signature.toLowerCase(), now + 300_000)))
|
||||
throw new Error('Signature already used (replay blocked)')
|
||||
}
|
||||
Reference in New Issue
Block a user