import {
  constants,
  createCipheriv,
  createDecipheriv,
  createHmac,
  generateKeyPairSync,
  publicEncrypt,
  randomBytes,
} from 'crypto';
import { decryptFlow, encryptFlow, validFlowSignature } from './flow-crypto';

describe('native Flow encryption', () => {
  const keys = generateKeyPairSync('rsa', { modulusLength: 2048 });
  it('validates the signature over the exact raw bytes and fails closed', () => {
    const raw = Buffer.from('{"action":"ping"}');
    const signature =
      'sha256=' + createHmac('sha256', 'secret').update(raw).digest('hex');
    expect(validFlowSignature(raw, signature, 'secret')).toBe(true);
    expect(validFlowSignature(Buffer.from('{}'), signature, 'secret')).toBe(
      false,
    );
    expect(validFlowSignature(raw, 'sha256=wrong', 'secret')).toBe(false);
    expect(validFlowSignature(raw, signature, '')).toBe(false);
    expect(validFlowSignature(undefined, signature, 'secret')).toBe(false);
  });
  it('decrypts a client request and encrypts the response using the inverted IV', () => {
    const aes = randomBytes(16),
      iv = randomBytes(16);
    const cipher = createCipheriv('aes-128-gcm', aes, iv);
    const body = { action: 'INIT', flow_token: 'opaque' };
    const encrypted = Buffer.concat([
      cipher.update(JSON.stringify(body)),
      cipher.final(),
      cipher.getAuthTag(),
    ]);
    const envelope = {
      encrypted_aes_key: publicEncrypt(
        {
          key: keys.publicKey,
          padding: constants.RSA_PKCS1_OAEP_PADDING,
          oaepHash: 'sha256',
        },
        aes,
      ).toString('base64'),
      encrypted_flow_data: encrypted.toString('base64'),
      initial_vector: iv.toString('base64'),
    };
    const result = decryptFlow(
      envelope,
      keys.privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
    );
    expect(result.data).toEqual(body);
    const response = Buffer.from(
      encryptFlow({ screen: 'SEARCH' }, result.aes, result.iv),
      'base64',
    );
    const decipher = createDecipheriv(
      'aes-128-gcm',
      aes,
      Buffer.from(iv.map((byte) => byte ^ 255)),
    );
    decipher.setAuthTag(response.subarray(-16));
    expect(
      JSON.parse(
        Buffer.concat([
          decipher.update(response.subarray(0, -16)),
          decipher.final(),
        ]).toString(),
      ),
    ).toEqual({ screen: 'SEARCH' });
    envelope.encrypted_flow_data = Buffer.alloc(encrypted.length).toString(
      'base64',
    );
    expect(() =>
      decryptFlow(
        envelope,
        keys.privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
      ),
    ).toThrow();
  });
});
