/**
 * SSH algorithm allowlists.
 *
 * Modern, strong algorithms only. Excludes:
 *   - DSA, RSA-SHA1, MD5, SHA1 — weak / deprecated
 *   - CBC ciphers — vulnerable to plaintext-recovery on MAC failure
 *   - RC4 / arcfour, blowfish, 3DES — broken or weak
 *   - SHA1 HMAC variants — collision-prone
 *   - Compression — leak channel (CRIME-style); kept at 'none'
 *
 * Used by ssh2 Client.connect({ algorithms }) in Phase 3 session core.
 * Order is preference (most favored first per ssh2 docs).
 *
 * Plan: docs/superpowers/plans/2026-05-12-ssh-tool-integration.md (Phase 2).
 */
import type {
  KexAlgorithm,
  CipherAlgorithm,
  ServerHostKeyAlgorithm,
  MacAlgorithm,
  CompressionAlgorithm,
  Algorithms,
} from 'ssh2';

export const ALLOWED_KEX: readonly KexAlgorithm[] = [
  'curve25519-sha256',
  'curve25519-sha256@libssh.org',
  'ecdh-sha2-nistp256',
  'ecdh-sha2-nistp384',
  'ecdh-sha2-nistp521',
  'diffie-hellman-group16-sha512',
  'diffie-hellman-group18-sha512',
  'diffie-hellman-group-exchange-sha256',
];

export const ALLOWED_CIPHER: readonly CipherAlgorithm[] = [
  'chacha20-poly1305@openssh.com',
  'aes256-gcm@openssh.com',
  'aes128-gcm@openssh.com',
  'aes256-ctr',
  'aes192-ctr',
  'aes128-ctr',
];

export const ALLOWED_HOST_KEY: readonly ServerHostKeyAlgorithm[] = [
  'ssh-ed25519',
  'ecdsa-sha2-nistp256',
  'ecdsa-sha2-nistp384',
  'ecdsa-sha2-nistp521',
  'rsa-sha2-512',
  'rsa-sha2-256',
];

export const ALLOWED_HMAC: readonly MacAlgorithm[] = [
  'hmac-sha2-256-etm@openssh.com',
  'hmac-sha2-512-etm@openssh.com',
  'hmac-sha2-256',
  'hmac-sha2-512',
];

export const ALLOWED_COMPRESSION: readonly CompressionAlgorithm[] = ['none'];

export function buildAlgorithmsOption(): Algorithms {
  return {
    kex: [...ALLOWED_KEX],
    cipher: [...ALLOWED_CIPHER],
    serverHostKey: [...ALLOWED_HOST_KEY],
    hmac: [...ALLOWED_HMAC],
    compress: [...ALLOWED_COMPRESSION],
  };
}

/** True if `name` matches an allowed algorithm in any category. */
export function isAllowedAlgorithm(name: string): boolean {
  return (
    (ALLOWED_KEX as readonly string[]).includes(name) ||
    (ALLOWED_CIPHER as readonly string[]).includes(name) ||
    (ALLOWED_HOST_KEY as readonly string[]).includes(name) ||
    (ALLOWED_HMAC as readonly string[]).includes(name) ||
    (ALLOWED_COMPRESSION as readonly string[]).includes(name)
  );
}

/** True if `name` is one of the host-key types we accept from a server. */
export function isAllowedHostKeyType(name: string): boolean {
  return (ALLOWED_HOST_KEY as readonly string[]).includes(name);
}
