<commit_before><?php /** @file */

/**
 * Zot endpoint
 */


require_once('include/zot.php');


function post_init(&$a) {

	// Most access to this endpoint is via the post method.
	// Here we will pick out the magic auth params which arrive
	// as a get request, and the only communications to arrive this way.

	if(argc() > 1) {

		$webbie = argv(1);

		if(array_key_exists('auth',$_REQUEST)) {
			logger('mod_zot: auth request received.');
			$address = $_REQUEST['auth'];
			$dest    = $_REQUEST['dest'];
			$sec     = $_REQUEST['sec'];
			$version = $_REQUEST['version'];

			switch($dest) {
				case 'channel':
					$desturl = z_root() . '/channel/' . $webbie;
					break;
				case 'photos':
					$desturl = z_root() . '/photos/' . $webbie;
					break;
				case 'profile':
					$desturl = z_root() . '/profile/' . $webbie;
					break;
				default:
					$desturl = $dest;
					break;
			}
			$c = q("select * from channel where channel_address = '%s' limit 1",
				dbesc($webbie)
			);
			if(! $c) {
				logger('mod_zot: auth: unable to find channel ' . $webbie);
				// They'll get a notice when they hit the page, we don't need two of them. 
				goaway($desturl);
			}

			// Try and find a hubloc for the person attempting to auth
			$x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash where hubloc_addr = '%s' limit 1",
				dbesc($address)
			);

			if(! $x) {
				// finger them if they can't be found. 
				$ret = zot_finger($addr,null);
				if($ret['success']) {
					$j = json_decode($ret['body'],true);
					if($j)
						import_xchan($j);
					$x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash where hubloc_addr = '%s' limit 1",
						dbesc($address)
					);
				}
			}
			if(! $x) {
				logger('mod_zot: auth: unable to finger ' . $addr);
				goaway($desturl);
			}

			logger('mod_zot: auth request received from ' . $x[0]['xchan_addr'] . ' for ' . $webbie); 

			// check credentials and access

			// If they are already authenticated and haven't changed credentials, 
			// we can save an expensive network round trip and improve performance.

			$remote = remote_user();
			$result = null;

			$already_authed = ((($remote) && ($x[0]['hubloc_hash'] == $remote)) ? true : false); 

			if(! $already_authed) {
				// Auth packets MUST use ultra top-secret hush-hush mode 
				$p = zot_build_packet($c[0],$type = 'auth_check',
					array(array('guid' => $x[0]['hubloc_guid'],'guid_sig' => $x[0]['hubloc_guid_sig'])), 
					$x[0]['hubloc_sitekey'], $sec);
				$result = zot_zot($x[0]['hubloc_callback'],$p);
				if(! $result['success']) {
					logger('mod_zot: auth_check callback failed.');
					goaway($desturl);
				}
				$j = json_decode($result['body'],true);
			}

			if($already_authed || $j['success']) {
				if($j['success']) {
					// legit response, but we do need to check that this wasn't answered by a man-in-middle
					if(! rsa_verify($sec . $x[0]['xchan_hash'],base64url_decode($j['confirm']),$x[0]['xchan_pubkey'])) {
						logger('mod_zot: auth: final confirmation failed.');
						goaway($desturl);
					}
				}
				// everything is good... maybe
				if(local_user()) {

					// tell them to logout if they're logged in locally as anything but the target remote account
					// in which case just shut up because they don't need to be doing this at all.

					if($a->channel['channel_hash'] != $x[0]['xchan_hash']) {
						logger('mod_zot: auth: already authenticated locally as somebody else.');
						notice( t('Remote authentication blocked. You are logged into this site locally. Please logout and retry.') . EOL);
					}
					goaway($desturl);
				}
				// log them in
				$_SESSION['authenticated'] = 1;
				$_SESSION['visitor_id'] = $x[0]['xchan_hash'];
				$_SESSION['my_address'] = $address;
				$arr = array('xchan' => $x[0], 'url' => $desturl, 'channel_address' => $webbie);
				call_hooks('magic_auth_success',$arr);
				$a->set_observer($x[0]);
				require_once('include/security.php');
				$a->set_groups(init_groups_visitor($_SESSION['visitor_id']));
				info(sprintf( t('Welcome %s. Remote authentication successful.'),$x[0]['xchan_name']));
				logger('mod_zot: auth success from ' . $x[0]['xchan_addr'] . ' for ' . $webbie); 

			}

// FIXME - we really want to save the return_url in the session before we visit rmagic.
// This does however prevent a recursion if you visit rmagic directly, as it would otherwise send you back here again. 
// But z_root() probably isn't where you really want to go. 

			if(strstr($desturl,z_root() . '/rmagic'))
				goaway(z_root());

			goaway($desturl);
		}

		logger('mod_zot: invalid args: ' . print_r($a->argv,true));
		killme();
	}

	return;
}




	
function post_post(&$a) {

	logger('mod_zot: ' . print_r($_REQUEST,true), LOGGER_DEBUG);

	$ret = array('success' => false);

	$data = json_decode($_REQUEST['data'],true);

	logger('mod_zot: data: ' . print_r($data,true), LOGGER_DATA);

	/**
	 * Many message packets will arrive encrypted. The existence of an 'iv' element 
	 * tells us we need to unencapsulate the AES-256-CBC content using the site private key
	 */

	if(array_key_exists('iv',$data)) {
		$data = aes_unencapsulate($data,get_config('system','prvkey'));
		logger('mod_zot: decrypt1: ' . $data, LOGGER_DATA);
		$data = json_decode($data,true);
	}

	logger('mod_zot: decoded data: ' . print_r($data,true), LOGGER_DATA);

	$msgtype = ((array_key_exists('type',$data)) ? $data['type'] : '');


	if($msgtype === 'pickup') {

		/**
		 * The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash
		 * First verify that that the returned signatures verify, then check that we have an outbound queue item
		 * with the correct hash.
		 * If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back
		 *
		 */

		if((! $data['secret']) || (! $data['secret_sig'])) {
			$ret['message'] = 'no verification signature';
			logger('mod_zot: pickup: ' . $ret['message'], LOGGER_DEBUG);
			json_return_and_die($ret);
		}
		$r = q("select hubloc_sitekey from hubloc where hubloc_url = '%s' and hubloc_callback = '%s' and hubloc_sitekey != '' ",
			dbesc($data['url']),
			dbesc($data['callback'])
		);
		if(! $r) {
			$ret['message'] = 'site not found';
			logger('mod_zot: pickup: ' . $ret['message']);
			json_return_and_die($ret);
		}

		foreach ($r as $hubsite) {

			// verify the url_sig
			// If the server was re-installed at some point, there could be multiple hubs with the same url and callback.
			// Only one will have a valid key.

			$forgery = true;
			$secret_fail = true;

			$sitekey = $hubsite['hubloc_sitekey'];

			logger('mod_zot: Checking sitekey: ' . $sitekey);

			if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) {
				$forgery = false;
			}
			if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) {
				$secret_fail = false;
			}<commit_msg>we don't need every hubloc for the site, only those that have different keys<commit_after><?php /** @file */

/**
 * Zot endpoint
 */


require_once('include/zot.php');


function post_init(&$a) {

	// Most access to this endpoint is via the post method.
	// Here we will pick out the magic auth params which arrive
	// as a get request, and the only communications to arrive this way.

	if(argc() > 1) {

		$webbie = argv(1);

		if(array_key_exists('auth',$_REQUEST)) {
			logger('mod_zot: auth request received.');
			$address = $_REQUEST['auth'];
			$dest    = $_REQUEST['dest'];
			$sec     = $_REQUEST['sec'];
			$version = $_REQUEST['version'];

			switch($dest) {
				case 'channel':
					$desturl = z_root() . '/channel/' . $webbie;
					break;
				case 'photos':
					$desturl = z_root() . '/photos/' . $webbie;
					break;
				case 'profile':
					$desturl = z_root() . '/profile/' . $webbie;
					break;
				default:
					$desturl = $dest;
					break;
			}
			$c = q("select * from channel where channel_address = '%s' limit 1",
				dbesc($webbie)
			);
			if(! $c) {
				logger('mod_zot: auth: unable to find channel ' . $webbie);
				// They'll get a notice when they hit the page, we don't need two of them. 
				goaway($desturl);
			}

			// Try and find a hubloc for the person attempting to auth
			$x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash where hubloc_addr = '%s' limit 1",
				dbesc($address)
			);

			if(! $x) {
				// finger them if they can't be found. 
				$ret = zot_finger($addr,null);
				if($ret['success']) {
					$j = json_decode($ret['body'],true);
					if($j)
						import_xchan($j);
					$x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash where hubloc_addr = '%s' limit 1",
						dbesc($address)
					);
				}
			}
			if(! $x) {
				logger('mod_zot: auth: unable to finger ' . $addr);
				goaway($desturl);
			}

			logger('mod_zot: auth request received from ' . $x[0]['xchan_addr'] . ' for ' . $webbie); 

			// check credentials and access

			// If they are already authenticated and haven't changed credentials, 
			// we can save an expensive network round trip and improve performance.

			$remote = remote_user();
			$result = null;

			$already_authed = ((($remote) && ($x[0]['hubloc_hash'] == $remote)) ? true : false); 

			if(! $already_authed) {
				// Auth packets MUST use ultra top-secret hush-hush mode 
				$p = zot_build_packet($c[0],$type = 'auth_check',
					array(array('guid' => $x[0]['hubloc_guid'],'guid_sig' => $x[0]['hubloc_guid_sig'])), 
					$x[0]['hubloc_sitekey'], $sec);
				$result = zot_zot($x[0]['hubloc_callback'],$p);
				if(! $result['success']) {
					logger('mod_zot: auth_check callback failed.');
					goaway($desturl);
				}
				$j = json_decode($result['body'],true);
			}

			if($already_authed || $j['success']) {
				if($j['success']) {
					// legit response, but we do need to check that this wasn't answered by a man-in-middle
					if(! rsa_verify($sec . $x[0]['xchan_hash'],base64url_decode($j['confirm']),$x[0]['xchan_pubkey'])) {
						logger('mod_zot: auth: final confirmation failed.');
						goaway($desturl);
					}
				}
				// everything is good... maybe
				if(local_user()) {

					// tell them to logout if they're logged in locally as anything but the target remote account
					// in which case just shut up because they don't need to be doing this at all.

					if($a->channel['channel_hash'] != $x[0]['xchan_hash']) {
						logger('mod_zot: auth: already authenticated locally as somebody else.');
						notice( t('Remote authentication blocked. You are logged into this site locally. Please logout and retry.') . EOL);
					}
					goaway($desturl);
				}
				// log them in
				$_SESSION['authenticated'] = 1;
				$_SESSION['visitor_id'] = $x[0]['xchan_hash'];
				$_SESSION['my_address'] = $address;
				$arr = array('xchan' => $x[0], 'url' => $desturl, 'channel_address' => $webbie);
				call_hooks('magic_auth_success',$arr);
				$a->set_observer($x[0]);
				require_once('include/security.php');
				$a->set_groups(init_groups_visitor($_SESSION['visitor_id']));
				info(sprintf( t('Welcome %s. Remote authentication successful.'),$x[0]['xchan_name']));
				logger('mod_zot: auth success from ' . $x[0]['xchan_addr'] . ' for ' . $webbie); 

			}

// FIXME - we really want to save the return_url in the session before we visit rmagic.
// This does however prevent a recursion if you visit rmagic directly, as it would otherwise send you back here again. 
// But z_root() probably isn't where you really want to go. 

			if(strstr($desturl,z_root() . '/rmagic'))
				goaway(z_root());

			goaway($desturl);
		}

		logger('mod_zot: invalid args: ' . print_r($a->argv,true));
		killme();
	}

	return;
}




	
function post_post(&$a) {

	logger('mod_zot: ' . print_r($_REQUEST,true), LOGGER_DEBUG);

	$ret = array('success' => false);

	$data = json_decode($_REQUEST['data'],true);

	logger('mod_zot: data: ' . print_r($data,true), LOGGER_DATA);

	/**
	 * Many message packets will arrive encrypted. The existence of an 'iv' element 
	 * tells us we need to unencapsulate the AES-256-CBC content using the site private key
	 */

	if(array_key_exists('iv',$data)) {
		$data = aes_unencapsulate($data,get_config('system','prvkey'));
		logger('mod_zot: decrypt1: ' . $data, LOGGER_DATA);
		$data = json_decode($data,true);
	}

	logger('mod_zot: decoded data: ' . print_r($data,true), LOGGER_DATA);

	$msgtype = ((array_key_exists('type',$data)) ? $data['type'] : '');


	if($msgtype === 'pickup') {

		/**
		 * The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash
		 * First verify that that the returned signatures verify, then check that we have an outbound queue item
		 * with the correct hash.
		 * If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back
		 *
		 */

		if((! $data['secret']) || (! $data['secret_sig'])) {
			$ret['message'] = 'no verification signature';
			logger('mod_zot: pickup: ' . $ret['message'], LOGGER_DEBUG);
			json_return_and_die($ret);
		}
		$r = q("select distinct hubloc_sitekey from hubloc where hubloc_url = '%s' and hubloc_callback = '%s' and hubloc_sitekey != '' group by hubloc_sitekey ",
			dbesc($data['url']),
			dbesc($data['callback'])
		);
		if(! $r) {
			$ret['message'] = 'site not found';
			logger('mod_zot: pickup: ' . $ret['message']);
			json_return_and_die($ret);
		}

		foreach ($r as $hubsite) {

			// verify the url_sig
			// If the server was re-installed at some point, there could be multiple hubs with the same url and callback.
			// Only one will have a valid key.

			$forgery = true;
			$secret_fail = true;

			$sitekey = $hubsite['hubloc_sitekey'];

			logger('mod_zot: Checking sitekey: ' . $sitekey);

			if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) {
				$forgery = false;
			}
			if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) {
				$secret_fail = false;
			}
{'fraction_non_alphanumeric': 0.16423670668953688, 'fraction_numerical': 0.004431103487707261, 'mean_word_length': 3.4535327816677275, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6833081', 'n_tokens_mistral': 5578, 'n_tokens_neox': 4685, 'n_words': 1285}