All files / core/blong-gogo/src/adapter/server/viber signature.ts

100% Statements 30/30
100% Branches 4/4
100% Functions 1/1
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 3x 3x 3x 3x 4x 1x 1x  
import {createHmac, timingSafeEqual} from 'node:crypto';
 
import {library} from '@feasibleone/blong/types';
 
/**
 * The Viber request signature.
 *
 * Viber signs the raw body with the bot's auth token and sends the hex digest in
 * `X-Viber-Content-Signature`. There is no timestamp header, so the raw bytes and a constant-time
 * compare are the whole check — and the bytes are exactly why the receiver keeps them.
 */
export interface IViberSignature {
    authToken?: string;
    signature?: string;
    rawBody?: Buffer;
}
 
export const viberSignatureMatches = ({
    authToken,
    signature,
    rawBody,
}: IViberSignature): boolean => {
    if (!authToken || !signature || !rawBody) return false;
    const expected = createHmac('sha256', authToken).update(rawBody).digest('hex');
    const left = Buffer.from(expected);
    const right = Buffer.from(signature);
    return left.length === right.length && timingSafeEqual(left, right);
};
 
export default library(() => ({viberSignatureMatches}));