view signature_decode.mjs @ 49:1bd17c2e5517 default tip

video.py must sign video urls for serve-files.js to serve them
author drewp@bigasterisk.com
date Fri, 06 Dec 2024 17:13:51 -0800
parents
children
line wrap: on
line source

import { createDecipheriv } from 'crypto';
import * as fs from 'fs';

const SIGNATURE_KEY = fs.readFileSync('/secret/signature_key');

function removePKCS7Padding(data) {
    const paddingLength = data.charCodeAt(data.length - 1);
    return data.slice(0, -paddingLength);
}

function decryptData(encryptedData, key) {
    const ivLength = 12; // 12 bytes for GCM
    const tagLength = 16; // 16 bytes for GCM
    const decodedData = Buffer.from(encryptedData, 'base64');

    if (decodedData.length < ivLength + tagLength) {
        throw new Error('Invalid encrypted data length');
    }

    const iv = decodedData.slice(0, ivLength);
    const tag = decodedData.slice(-tagLength);
    const ciphertext = decodedData.slice(ivLength, -tagLength);

    const decipher = createDecipheriv('aes-256-gcm', key, iv);
    decipher.setAuthTag(tag);
    let decryptedData = decipher.update(ciphertext, 'base64', 'utf8');
    decryptedData += decipher.final('utf8');
    return decryptedData;
}

export function decodeSig(sig) {
    const clear = decryptData(sig, SIGNATURE_KEY);
    const json = removePKCS7Padding(clear.toString('utf-8'));
    return JSON.parse(json);
}