Viewing file: cookie_utils.php (3.21 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
// cookie_utils.php — Parse Set-Cookie and encrypt JSON storage.
function parse_set_cookie_line(string $line, string $defaultDomain): ?array {
if (stripos($line, 'Set-Cookie:') !== 0) return null;
$cookieStr = trim(substr($line, strlen('Set-Cookie:')));
$parts = array_map('trim', explode(';', $cookieStr));
if (!isset($parts[0])) return null;
$nv = explode('=', $parts[0], 2);
$name = $nv[0] ?? '';
$value = $nv[1] ?? '';
$meta = [
'name' => $name,
'value' => $value,
'domain' => $defaultDomain,
'path' => '/',
'secure' => false,
'httponly' => false,
'expires' => null,
'samesite' => null,
];
for ($i=1; $i<count($parts); $i++) {
$kv = explode('=', $parts[$i], 2);
$k = strtolower(trim($kv[0]));
$v = isset($kv[1]) ? trim($kv[1]) : null;
if ($k === 'domain' && $v) {
$d = ltrim($v, '.');
$meta['domain'] = $d;
} elseif ($k === 'path' && $v) {
$meta['path'] = $v;
} elseif ($k === 'secure') {
$meta['secure'] = true;
} elseif ($k === 'httponly') {
$meta['httponly'] = true;
} elseif ($k === 'expires' && $v) {
$ts = strtotime($v);
if ($ts !== false) $meta['expires'] = $ts;
} elseif ($k === 'samesite' && $v) {
$vv = ucfirst(strtolower($v));
if (in_array($vv, ['Lax','Strict','None'])) $meta['samesite'] = $vv;
}
}
return $meta;
}
function merge_cookie(array &$jar, array $c): void {
$key = $c['name'].'|'.$c['domain'].'|'.$c['path'];
$jar[$key] = $c;
}
function encrypt_json_blob(string $json, string $key): array {
if (function_exists('sodium_crypto_secretbox')) {
if (strlen($key) !== 32) $key = substr(hash('sha256', $key, true),0,32);
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ct = sodium_crypto_secretbox($json, $nonce, $key);
return ['alg'=>'sodium_secretbox','nonce'=>base64_encode($nonce),'ciphertext'=>base64_encode($ct)];
}
// OpenSSL AES-256-GCM fallback
$iv = random_bytes(12);
$tag = '';
$ct = openssl_encrypt($json, 'aes-256-gcm', hash('sha256',$key,true), OPENSSL_RAW_DATA, $iv, $tag);
return ['alg'=>'aes-256-gcm','iv'=>base64_encode($iv),'tag'=>base64_encode($tag),'ciphertext'=>base64_encode($ct)];
}
function save_encrypted_json(string $file, array $payload): void {
$dir = dirname($file);
if (!is_dir($dir)) mkdir($dir, 0700, true);
file_put_contents($file, json_encode($payload, JSON_UNESCAPED_SLASHES));
@chmod($file, 0600);
}
function export_cookies_txt(array $cookies, string $file): void {
$lines = [];
foreach ($cookies as $c) {
$lines[] = sprintf(
'%s=%s; Domain=%s; Path=%s; HttpOnly=%s; Secure=%s; Expires=%s; SameSite=%s',
$c['name'], $c['value'], $c['domain'], $c['path'],
$c['httponly']?'true':'false', $c['secure']?'true':'false',
$c['expires'] ? gmdate('c', $c['expires']) : 'null',
$c['samesite'] ?? 'null'
);
}
file_put_contents($file, implode("\n", $lines));
}
?>
|