<?php
/**
 * DFS Backups HUB endpoint — deployed by root to <account>/public_html/backups/api.php (real directory, no WordPress). Since 2026-09-21 the
 * account is the isolated cPanel user backuphub (https://hub.dreamflightstudios.com/backups/api.php); the legacy copy under
 * dreamflightstudi serves plugins below 1.3.0 until the fleet has moved.
 * Holds the READER HMAC key in <account home>/.dfs-health/site-reader.env (mode 600, written by root).
 * A site authenticates each request with HMAC-SHA256(body, site_secret); the hub verifies against sha256(site_secret) published
 * in that site's hello.json (read with the reader key). The hub mints presigned GET URLs ONLY under <client>/<host>/ of the caller.
 */
header( 'Content-Type: application/json' );
header( 'X-Robots-Tag: noindex, nofollow, noarchive' );
header( 'Cache-Control: no-store' );
// The hub's private state lives in <account home>/.dfs-health, resolved from this file's place (public_html/backups/api.php),
// so the same file serves the legacy home (dreamflightstudi) and the isolated BackupHub account (audit H3, 2026-09-21):
// a hub on its own cPanel account means no other site's code can read the reader key.
$health = dirname( dirname( __DIR__ ) ) . '/.dfs-health';
$env    = $health . '/site-reader.env';
$log    = $health . '/hub-api.log';
/**
 * Diagnostic log (master-plugin-audit Phase 4, 2026-09-21): the same JSON line shape as the plugin's dfs_backup_log()
 * — t, sev (DEBUG 5–8 / INFO 9–12 / WARN 13–16 / ERROR 17–20), lvl, ev, mod "hub", req (8 hex per request), ctx —
 * into the existing hub-api.log, ring-capped at 1 MB (renamed to hub-api.log.1, one kept). Every denial is written by
 * out() itself (code >= 400 → request.denied with the code + reason), so no verdict can go unrecorded; accepted actions
 * write their own line before out(). ctx never carries the signature, the body or the reader key: the request's
 * prefix, client ip (raw — this is the hub's own log on Brad's account), action and counts only.
 */
function logl( string $ev, array $ctx = array(), int $sev = 9 ): void {
	global $log, $ip, $prefix;
	static $req_id = null;
	if ( null === $req_id ) {
		$req_id = bin2hex( random_bytes( 4 ) );
	}
	$f     = $log;
	$clean = array();
	foreach ( array(
		'ip'     => $ip ?? '',
		'prefix' => $prefix ?? '',
	) + $ctx as $k => $v ) {
		if ( is_string( $v ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags, WordPressVIPMinimum.Functions.StripTags.StripTagsOneParameter -- no WordPress on the hub
			$clean[ $k ] = substr( strip_tags( $v ), 0, 160 );
		} elseif ( is_scalar( $v ) || null === $v ) {
			$clean[ $k ] = $v;
		}
	}
	// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- no WordPress on the hub
	$line = json_encode(
		array(
			't'   => gmdate( 'Y-m-d\TH:i:s\Z' ),
			'sev' => $sev,
			'lvl' => $sev >= 17 ? 'error' : ( $sev >= 13 ? 'warn' : ( $sev >= 9 ? 'info' : 'debug' ) ),
			'ev'  => $ev,
			'mod' => 'hub',
			'req' => $req_id,
			'ctx' => $clean,
		)
	);
	if ( ! is_string( $line ) ) {
		return;
	}
	clearstatcache( true, $f );
	// Silenced on purpose: a warning here would print into the JSON response body of a hub call. The log is best-effort.
	if ( file_exists( $f ) && filesize( $f ) > 1048576 ) {
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Generic.PHP.NoSilencedErrors.Forbidden, WordPress.WP.AlternativeFunctions.rename_rename, WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_rename -- ring rotation of the hub's own log, no WordPress here
		@rename( $f, $f . '.1' );
	}
	@file_put_contents( $f, $line . "\n", FILE_APPEND | LOCK_EX ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Generic.PHP.NoSilencedErrors.Forbidden, WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_file_put_contents -- append-with-lock to the hub's own log, no WordPress here
}
function out( int $code, array $j ): void {
	if ( $code >= 400 ) {
		logl(
			'request.denied',
			array(
				'code'   => $code,
				'reason' => (string) ( $j['error'] ?? '' ),
			),
			$code >= 500 ? 17 : 13
		);
	}
	http_response_code( $code );
	echo json_encode( $j );
	exit;
}
if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
	out(
		405,
		array(
			'ok'    => false,
			'error' => 'POST only',
		)
	);
}
// Rate limit (audit H1, Brad 2026-09-21): 60 requests per minute per client IP, counted BEFORE any storage read — every
// unauthenticated POST otherwise costs one reader-key GET and reveals whether a client/host prefix exists. The hub sits behind
// Cloudflare, so CF-Connecting-IP names the client; a direct-to-origin caller can only evade the limit, never authenticate.
// The counter files live in the hub's own 0700 state dir; there is no WordPress here (no WP_Filesystem, no VIP page cache), and a
// PHP warning from any of these calls would print into the JSON response, so they stay silenced. The client address is used
// ONLY as a sha256 bucket key (never echoed, never trusted for anything else), so a malformed header just gets its own bucket.
$rl_dir = $health . '/ratelimit';
if ( ! is_dir( $rl_dir ) ) {
	// phpcs:ignore Generic.PHP.NoSilencedErrors.Forbidden, WordPressVIPMinimum.Functions.RestrictedFunctions.directory_mkdir -- see above
	@mkdir( $rl_dir, 0700, true );
}
$ip = (string) ( $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '0' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___SERVER__REMOTE_ADDR__, WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders -- a hash-bucket key only, see above
$rl = $rl_dir . '/' . substr( hash( 'sha256', $ip ), 0, 16 ) . '-' . gmdate( 'YmdHi' );
@file_put_contents( $rl, 'x', FILE_APPEND ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Forbidden, WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_file_put_contents -- see above
// phpcs:ignore Generic.PHP.NoSilencedErrors.Forbidden -- see above
if ( (int) @filesize( $rl ) > 60 ) {
	header( 'Retry-After: 60' );
	out(
		429,
		array(
			'ok'    => false,
			'error' => 'rate limited: 60 requests per minute',
		)
	);
}
if ( random_int( 1, 50 ) === 1 ) {
	foreach ( glob( $rl_dir . '/*' ) ?: array() as $f ) {
		if ( filemtime( $f ) < time() - 180 ) {
			// phpcs:ignore Generic.PHP.NoSilencedErrors.Forbidden, WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink -- see above
			@unlink( $f );
		}
	}
}
$raw = file_get_contents( 'php://input' );
$sig = $_SERVER['HTTP_X_DFS_SIGNATURE'] ?? '';
$req = json_decode( $raw, true );
if ( ! is_array( $req ) || empty( $req['site_id'] ) || empty( $req['host'] ) || empty( $req['client'] ) || empty( $req['ts'] ) ) {
	out(
		400,
		array(
			'ok'    => false,
			'error' => 'bad request',
		)
	);
}
if ( abs( time() - (int) $req['ts'] ) > 300 ) {
	out(
		401,
		array(
			'ok'    => false,
			'error' => 'stale timestamp',
		)
	);
}
$cfg = @parse_ini_file( $env );
if ( ! $cfg || empty( $cfg['DFS_AK'] ) ) {
	out(
		500,
		array(
			'ok'    => false,
			'error' => 'hub not configured',
		)
	);
}
if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}   // the S3 class guards on ABSPATH; define it BEFORE requiring, or the require silently exits
foreach ( array( $health . '/class-dfs-backup-s3.php', __DIR__ . '/../wp-content/plugins/dfs-backup/includes/class-dfs-backup-s3.php' ) as $inc ) {
	if ( ! class_exists( 'DFS_Backup_S3' ) && file_exists( $inc ) ) {
		require_once $inc;
	}
}
if ( ! class_exists( 'DFS_Backup_S3' ) ) {
	out(
		500,
		array(
			'ok'    => false,
			'error' => 'transport class missing on hub',
		)
	);
}
$s3     = new DFS_Backup_S3(
	array(
		'ak'     => $cfg['DFS_AK'],
		'sk'     => $cfg['DFS_SK'],
		'bucket' => $cfg['BUCKET'] ?? 'dfs-site-bk',
		'region' => $cfg['REGION'] ?? 'us-east1',
		'prefix' => $cfg['PREFIX'] ?? '',
	)
);
$safe   = fn( $s ) => trim( preg_replace( '/[\/\\\\\x00-\x1f]+/', '-', (string) $s ) );
$prefix = ( $cfg['PREFIX'] ?? '' ) . $safe( $req['client'] ) . '/' . strtolower( $safe( $req['host'] ) ) . '/';
// one reader-key GET: object key (full, cfg prefix included) → body, or null when absent. hello.json here; manifest.sig + manifest.json.gz at redeem.
$fetch = function ( string $key ) use ( $s3 ): ?string {
	$u = $s3->presign_get( $key, 60 );
	$t = tempnam( sys_get_temp_dir(), 'hub' );
	$b = DFS_Backup_S3::download( $u, $t );
	$c = $b > 0 ? (string) file_get_contents( $t ) : null;
	@unlink( $t );
	return $c;
};
// fetch hello.json with the reader key to learn the site's secret hash
$hello = json_decode( (string) $fetch( $prefix . 'hello.json' ), true );
if ( ! is_array( $hello ) || empty( $hello['secret_hash'] ) ) {
	out(
		404,
		array(
			'ok'    => false,
			'error' => 'site not registered (no hello.json with secret_hash)',
		)
	);
}
if ( ( $hello['site_id'] ?? '' ) !== $req['site_id'] ) {
	out(
		401,
		array(
			'ok'    => false,
			'error' => 'site_id mismatch',
		)
	);
}
// signature: the site signs with K = sha256(site_secret); hello.json carries that same K as secret_hash (only reader-key holders can read it)
$expect = hash_hmac( 'sha256', $raw, $hello['secret_hash'] );
if ( ! hash_equals( $expect, $sig ) ) {
	out(
		401,
		array(
			'ok'    => false,
			'error' => 'bad signature',
		)
	);
}
$action = $req['action'] ?? '';
$params = (array) ( $req['params'] ?? array() );
logl(
	'request.accepted',
	array(
		'action'  => (string) $action,
		'site_id' => substr( (string) $req['site_id'], 0, 8 ),
	)
);   // past ts window, hello.json, site_id and signature
if ( $action === 'presign' ) {
	$exp  = max( 60, min( 604800, (int) ( $params['expires'] ?? 7200 ) ) );
	$urls = array();
	foreach ( (array) ( $params['objects'] ?? array() ) as $obj ) {
		$obj = (string) $obj;
		if ( strpos( $obj, $prefix ) !== 0 || strpos( $obj, '..' ) !== false ) {
			out(
				403,
				array(
					'ok'    => false,
					'error' => "object outside your prefix: $obj",
				)
			);
		}
		$urls[ $obj ] = $s3->presign_get( $obj, $exp );
	}
	logl(
		'presign.done',
		array(
			'objects' => count( $urls ),
			'expires' => $exp,
		)
	);
	out(
		200,
		array(
			'ok'      => true,
			'urls'    => $urls,
			'expires' => $exp,
		)
	);
}
if ( $action === 'sets' ) {
	// Version-history calendar: ListObjectsV2 under the caller's <client>/<host>/ with the reader key, grouped per set.
	$sub = $safe( $req['client'] ) . '/' . strtolower( $safe( $req['host'] ) ) . '/';
	// 5000 keys per page: GCS honours it (probe 2026-09-21: MaxKeys=5000, KeyCount=5000, 453 ms) and the 20-page guard in list_prefix then
	// covers 100,000 objects (staging2 = 10,074). A listing cut by the guard would drop the NEWEST sets (keys sort ascending by date).
	$r = $s3->list_prefix( $sub, '', 5000 );
	if ( empty( $r['ok'] ) ) {
		logl( 'sets.list_failed', array( 'code' => (int) ( $r['code'] ?? 0 ) ), 17 );
		out(
			200,
			array(
				'ok'   => true,
				'sets' => array(),
				'note' => 'list failed',
			)
		);
	}
	$sets = array();
	foreach ( $r['objects'] as $o ) {
		$rel = substr( (string) $o['key'], strlen( $prefix ) );          // <setid>/<file>
		$seg = explode( '/', $rel );
		if ( count( $seg ) < 2 || $seg[1] === '' ) {
			continue;
		}
		$sid = $seg[0];
		if ( $sid === 'snapshots' || $sid === 'blobs' || $sid[0] === '_' || strpos( $sid, '.' ) !== false ) {
			continue;
		} // skip helper/_selftest prefixes + loose files
		if ( ! isset( $sets[ $sid ] ) ) {
			$sets[ $sid ] = array(
				'set'      => $sid,
				'bytes'    => 0,
				'files'    => 0,
				'mtime'    => '',
				'complete' => false,
				'signed'   => false,
			);
		}
		$sets[ $sid ]['bytes'] += (int) $o['size'];
		++$sets[ $sid ]['files'];
		if ( $o['mtime'] > $sets[ $sid ]['mtime'] ) {
			$sets[ $sid ]['mtime'] = $o['mtime'];
		}   // max LastModified: a late write into an old folder moves it forward
		if ( $seg[1] === 'manifest.json.gz' ) {
			$sets[ $sid ]['complete'] = true;
		}
		if ( 'manifest.sig' === $seg[1] ) {
			$sets[ $sid ]['signed'] = true;
		}                    // presence only — the SITE verifies with its own K at restore
	}
	krsort( $sets );
	logl(
		'sets.done',
		array(
			'sets'    => count( $sets ),
			'objects' => count( $r['objects'] ),
		)
	);
	out(
		200,
		array(
			'ok'   => true,
			'sets' => array_values( $sets ),
		)
	);
}
// ---- P14 Send/Receive migration: a SENDER grants a named RECEIVER read access to ONE of the sender's own sets; only the
// real receiver (authenticated by its own secret below) can redeem it. Grants are local coordination records (the reader key
// cannot write the immutable bucket), kept in a 700 dir. Isolation holds: creating a grant requires being the authenticated
// sender; redeeming requires being the authenticated receiver; presigns are clamped to the granted set's prefix. ------------
$grants = $health . '/grants';
if ( $action === 'migrate_grant' ) {
	$rc  = $safe( $params['receiver_client'] ?? '' );
	$rh  = strtolower( $safe( $params['receiver_host'] ?? '' ) );
	$rid = $safe( $params['receiver_site_id'] ?? '' );
	$set = $safe( $params['set_id'] ?? '' );
	if ( $rc === '' || $rh === '' || $rid === '' || $set === '' ) {
		out(
			400,
			array(
				'ok'    => false,
				'error' => 'grant needs receiver_client, receiver_host, receiver_site_id, set_id',
			)
		);
	}
	// the set MUST be one of the caller's own — a site can only ever share what lives under its own prefix
	$chk = $s3->list_prefix( $safe( $req['client'] ) . '/' . strtolower( $safe( $req['host'] ) ) . '/' . $set . '/', '', 1 );
	if ( empty( $chk['ok'] ) || empty( $chk['objects'] ) ) {
		out(
			404,
			array(
				'ok'    => false,
				'error' => 'set not found under your prefix',
			)
		);
	}
	if ( ! is_dir( $grants ) ) {
		@mkdir( $grants, 0700, true );
	}
	$gid = bin2hex( random_bytes( 8 ) );
	$put = @file_put_contents(
		"$grants/$gid.json",
		json_encode(
			array(
				'id'               => $gid,
				'sender_client'    => $req['client'],
				'sender_host'      => $req['host'],
				'set_id'           => $set,
				'receiver_site_id' => $rid,
				'receiver_client'  => $rc,
				'receiver_host'    => $rh,
				'created_at'       => gmdate( 'c' ),
				'expires'          => time() + 7 * 86400,
			)
		)
	);
	// a grant that did not reach disk must not be handed out: the receiver would redeem an id that 404s (audit Phase 6)
	if ( false === $put ) {
		out(
			500,
			array(
				'ok'    => false,
				'error' => 'grant not written',
			)
		);
	}
	logl(
		'grant.done',
		array(
			'grant_id'         => $gid,
			'set_id'           => $set,
			'receiver_host'    => $rh,
			'receiver_site_id' => substr( $rid, 0, 8 ),
		)
	);
	out(
		200,
		array(
			'ok'       => true,
			'grant_id' => $gid,
		)
	);
}
if ( $action === 'migrate_inbox' ) {
	$list = array();
	foreach ( glob( "$grants/*.json" ) ?: array() as $gf ) {
		$g = json_decode( (string) @file_get_contents( $gf ), true );
		if ( is_array( $g ) && ( $g['receiver_site_id'] ?? '' ) === $req['site_id'] && (int) ( $g['expires'] ?? 0 ) > time() ) {
			$list[] = array(
				'grant_id'    => $g['id'],
				'from_client' => $g['sender_client'],
				'from_host'   => $g['sender_host'],
				'set_id'      => $g['set_id'],
				'created_at'  => $g['created_at'],
			);
		}
	}
	logl( 'inbox.done', array( 'grants' => count( $list ) ) );
	out(
		200,
		array(
			'ok'     => true,
			'grants' => $list,
		)
	);
}
if ( $action === 'migrate_redeem' ) {
	$gid = $safe( $params['grant_id'] ?? '' );
	$gf  = "$grants/$gid.json";
	$g   = is_readable( $gf ) ? json_decode( (string) file_get_contents( $gf ), true ) : null;
	if ( ! is_array( $g ) || ( $g['receiver_site_id'] ?? '' ) !== $req['site_id'] || (int) ( $g['expires'] ?? 0 ) <= time() ) {
		out(
			403,
			array(
				'ok'    => false,
				'error' => 'no such grant for you (or expired)',
			)
		);
	}
	$sc  = $safe( $g['sender_client'] );
	$sh  = strtolower( $safe( $g['sender_host'] ) );
	$set = $safe( $g['set_id'] );
	$r   = $s3->list_prefix( "$sc/$sh/$set/", '', 5000 );
	if ( empty( $r['ok'] ) ) {
		logl(
			'redeem.list_failed',
			array(
				'grant_id' => $gid,
				'code'     => (int) ( $r['code'] ?? 0 ),
			),
			17
		);
		out(
			200,
			array(
				'ok'    => false,
				'error' => 'granted set list failed',
			)
		);
	}
	$urls = array();
	foreach ( $r['objects'] as $o ) {
		$urls[ (string) $o['key'] ] = $s3->presign_get( (string) $o['key'], 7200 );
	}
	// E1 (2026-09-21): the receiver cannot check the SENDER's manifest signature (K_sender is the sender's secret). The hub can:
	// read the sender's hello.json for K, fetch manifest.json.gz + manifest.sig, verify. 'signed' = a manifest.sig exists;
	// 'verified' = it matches under K_sender. The receiver refuses anything but verified === true (from_grant).
	$pfx      = (string) ( $cfg['PREFIX'] ?? '' );   // presign_get takes the FULL key (cfg prefix + client/host/...); list_prefix adds the cfg prefix itself
	$sig      = $fetch( $pfx . "$sc/$sh/$set/manifest.sig" );
	$signed   = null !== $sig;
	$verified = false;
	if ( $signed ) {
		$sh_hello = json_decode( (string) $fetch( $pfx . "$sc/$sh/hello.json" ), true );
		$gz       = $fetch( $pfx . "$sc/$sh/$set/manifest.json.gz" );
		$verified = is_array( $sh_hello ) && ! empty( $sh_hello['secret_hash'] ) && null !== $gz && hash_equals( hash_hmac( 'sha256', $gz, (string) $sh_hello['secret_hash'] ), trim( $sig ) );
	}
	logl(
		'redeem.verdict',
		array(
			'grant_id'    => $gid,
			'set_id'      => $set,
			'sender_host' => $sh,
			'objects'     => count( $urls ),
			'signed'      => $signed,
			'verified'    => $verified,
		),
		$verified ? 9 : 13
	);   // signed = manifest.sig exists; verified = it matches under the sender's K
	out(
		200,
		array(
			'ok'        => true,
			'urls'      => $urls,
			'set_id'    => $set,
			'from_host' => $g['sender_host'],
			'from_home' => 'https://' . $g['sender_host'],
			'signed'    => $signed,
			'verified'  => $verified,
		)
	);
}
out(
	400,
	array(
		'ok'    => false,
		'error' => 'unknown action',
	)
);
