|
| 1 | +import { randomStringForEntropy } from '@stablelib/random'; |
| 2 | +import { getPkhfromPk, validateAddress, ValidationResult, verifySignature } from '@taquito/utils'; |
| 3 | +import { NextFunction, Request, Response } from 'express'; |
| 4 | +import { StatusCodes } from 'http-status-codes'; |
| 5 | +import memoizee from 'memoizee'; |
| 6 | +import * as yup from 'yup'; |
| 7 | + |
| 8 | +import { CodedError } from './utils/errors'; |
| 9 | + |
| 10 | +const SIGNING_NONCE_TTL = 5 * 60_000; |
| 11 | + |
| 12 | +/** Result for packing (via `import('@taquito/michel-codec').packDataBytes({ string })`) in bytes for message: |
| 13 | + * `Tezos Signed Message: Confirming my identity as ${Account PKH}.\n\nNonce: ${nonce}` |
| 14 | + */ |
| 15 | +const TEZ_SIG_AUTH_MSG_PATTERN = |
| 16 | + /^0501[a-f0-9]{8}54657a6f73205369676e6564204d6573736167653a20436f6e6669726d696e67206d79206964656e7469747920617320[a-f0-9]{72}2e0a0a4e6f6e63653a20[a-f0-9]{16,40}$/; |
| 17 | + |
| 18 | +export const getSigningNonce = memoizee( |
| 19 | + (pkh: string) => { |
| 20 | + if (validateAddress(pkh) !== ValidationResult.VALID) throw new CodedError(400, 'Invalid address'); |
| 21 | + |
| 22 | + return buildNonce(); |
| 23 | + }, |
| 24 | + { |
| 25 | + max: 1_000_000, |
| 26 | + maxAge: SIGNING_NONCE_TTL |
| 27 | + } |
| 28 | +); |
| 29 | + |
| 30 | +export function removeSigningNonce(pkh: string) { |
| 31 | + getSigningNonce.delete(pkh); |
| 32 | +} |
| 33 | + |
| 34 | +export async function tezosSigAuthMiddleware(req: Request, res: Response, next: NextFunction) { |
| 35 | + const sigHeaders = await sigAuthHeadersSchema.validate(req.headers).catch(() => null); |
| 36 | + |
| 37 | + if (!sigHeaders) { |
| 38 | + logInvalidSigAuthValues('values (empty)', req.headers); |
| 39 | + |
| 40 | + return void res.status(StatusCodes.UNAUTHORIZED).send(); |
| 41 | + } |
| 42 | + |
| 43 | + const { |
| 44 | + 'tw-sig-auth-tez-pk': publicKey, |
| 45 | + 'tw-sig-auth-tez-msg': messageBytes, |
| 46 | + 'tw-sig-auth-tez-sig': signature |
| 47 | + } = sigHeaders; |
| 48 | + |
| 49 | + let pkh: string; |
| 50 | + try { |
| 51 | + pkh = getPkhfromPk(publicKey); |
| 52 | + } catch (err) { |
| 53 | + console.error(err); |
| 54 | + |
| 55 | + return void res.status(StatusCodes.BAD_REQUEST).send({ message: 'Invalid public key' }); |
| 56 | + } |
| 57 | + |
| 58 | + // Nonce |
| 59 | + const { value: nonce } = getSigningNonce(pkh); |
| 60 | + const nonceBytes = Buffer.from(nonce, 'utf-8').toString('hex'); |
| 61 | + |
| 62 | + if (!messageBytes.endsWith(nonceBytes)) { |
| 63 | + logInvalidSigAuthValues('nonce', req.headers); |
| 64 | + |
| 65 | + return void res.status(StatusCodes.UNAUTHORIZED).send({ code: 'INVALID_NONCE', message: 'Invalid nonce' }); |
| 66 | + } |
| 67 | + |
| 68 | + // Message |
| 69 | + if (!TEZ_SIG_AUTH_MSG_PATTERN.test(messageBytes)) { |
| 70 | + logInvalidSigAuthValues('pattern', req.headers); |
| 71 | + |
| 72 | + return void res.status(StatusCodes.UNAUTHORIZED).send({ code: 'INVALID_MSG', message: 'Invalid message' }); |
| 73 | + } |
| 74 | + |
| 75 | + // Signature |
| 76 | + try { |
| 77 | + verifySignature(messageBytes, publicKey, signature); |
| 78 | + } catch (error) { |
| 79 | + logInvalidSigAuthValues('signature', req.headers); |
| 80 | + console.error(error); |
| 81 | + |
| 82 | + return void res |
| 83 | + .status(StatusCodes.UNAUTHORIZED) |
| 84 | + .send({ code: 'INVALID_SIG', message: 'Invalid signature or message' }); |
| 85 | + } |
| 86 | + |
| 87 | + removeSigningNonce(pkh); |
| 88 | + |
| 89 | + next(); |
| 90 | +} |
| 91 | + |
| 92 | +const sigAuthHeadersSchema = yup.object().shape({ |
| 93 | + 'tw-sig-auth-tez-pk': yup.string().required(), |
| 94 | + 'tw-sig-auth-tez-msg': yup.string().required(), |
| 95 | + 'tw-sig-auth-tez-sig': yup.string().required() |
| 96 | +}); |
| 97 | + |
| 98 | +function buildNonce() { |
| 99 | + // Same as in in SIWE.generateNonce() |
| 100 | + const value = randomStringForEntropy(96); |
| 101 | + |
| 102 | + const expiresAt = new Date(Date.now() + SIGNING_NONCE_TTL).toISOString(); |
| 103 | + |
| 104 | + return { value, expiresAt }; |
| 105 | +} |
| 106 | + |
| 107 | +function logInvalidSigAuthValues(title: string, reqHeaders: Record<string, unknown>) { |
| 108 | + console.error(`[SIG-AUTH] Received invalid message ${title}. Request headers:`); |
| 109 | + |
| 110 | + console.info(JSON.stringify(reqHeaders, null, 2)); |
| 111 | +} |
0 commit comments