<?php
// Aigistry record verifier (rules 2.0). PHP 7.2+ with the sodium extension.
// Usage: php verify.php <record.json | URL> [--key HEX | --keys public-key.json | --keys-url URL]
// Prints VALID or INVALID and why; exit status 0 only when valid. Works on the raw signed text, never a re-encoded copy.
function load_src(string $s): string { $d = @file_get_contents($s); if ($d === false) { fwrite(STDERR, "cannot read $s\n"); exit(2); } return $d; }
$argv2 = array_slice($argv, 1); $rec = null; $key = null; $keysSrc = 'https://aigistry.com/public-key.json';
for ($i = 0; $i < count($argv2); $i++) { if ($argv2[$i] === '--key') $key = $argv2[++$i]; elseif ($argv2[$i] === '--keys' || $argv2[$i] === '--keys-url') $keysSrc = $argv2[++$i]; else $rec = $argv2[$i]; }
if (!$rec) { fwrite(STDERR, "usage: php verify.php <record.json|URL> [--key HEX|--keys FILE|--keys-url URL]\n"); exit(2); }
$t = load_src($rec);
function out(bool $ok, string $why) { echo ($ok ? 'VALID: ' : 'INVALID: ') . $why . "\n"; exit($ok ? 0 : 1); }
if (strncmp($t, '{"signed":', 10) !== 0) out(false, 'not an Aigistry record file');
$p = strpos($t, ',"record_hash":'); if ($p === false) out(false, 'not an Aigistry record file');
$signed = substr($t, 10, $p - 10); $meta = json_decode('{' . substr($t, $p + 1), true);
if (!is_array($meta)) out(false, 'unreadable record file');
$h = hash('sha256', $signed);
if (!hash_equals($h, (string)($meta['record_hash'] ?? ''))) out(false, 'the signed text does not match the record hash');
if (($meta['signature_algorithm'] ?? '') !== 'Ed25519') out(false, 'unexpected signature algorithm');
if ($key === null) { $kj = json_decode(load_src($keysSrc), true); foreach (($kj['keys'] ?? []) as $k) if ($k['key_id'] === ($meta['public_key_id'] ?? null)) $key = $k['public_key']; }
if (!$key || !ctype_xdigit($key) || strlen($key) !== 64) out(false, 'no usable key for key id ' . ($meta['public_key_id'] ?? '?'));
$sig = ctype_xdigit((string)($meta['signature'] ?? '')) ? hex2bin($meta['signature']) : '';
if (strlen($sig) !== SODIUM_CRYPTO_SIGN_BYTES || !sodium_crypto_sign_verify_detached($sig, $h, hex2bin($key))) out(false, 'the signature does not verify');
$r = json_decode($signed, true);
out(true, sprintf('format %s, %s, %s, revision %s, received %s', $r['format'], $r['organization'], $r['domain'], $r['revision'], $r['received_at']));
