SOURCE DOWNLOAD

木漏茶室源码下载中心

整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。

发布版本 v6.25.231 升级后自动生成独立源码包,下载中心只发送这份冻结包 已排除 config.php / 用户数据 / 上传文件 / 升级备份
komorebi-forum 183 个节点 · PHP 8.3.37 · 完整源码 ZIP 1.31 MB
下载完整源码 ZIP 源码包大小:1.31 MB 安装教程 作者主页 免费开源 免费下载 ↓
COMMUNITY DEPLOYMENTS

已经跑起来的木漏茶室

从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。

实时检测
2 个站点已部署

已展示全部 2 个站点。

inc/totp.php 7.8 KB · 发布包 v6.25.231
下载
<?php
/**
 * TOTP 动态验证(RFC 6238,SHA1 / 30 秒 / 6 位)
 * 密钥使用站点 config.key 加密后保存,恢复码只保存哈希。
 */

function totp_globally_enabled()
{
    return setting('totp_enabled', '0') === '1';
}

function totp_user_enabled($user)
{
    return is_array($user)
        && (int) ($user['totp_enabled'] ?? 0) === 1
        && trim((string) ($user['totp_secret'] ?? '')) !== '';
}

function totp_login_required_for($user)
{
    // 用户自己绑定的 TOTP 始终生效;后台开关只控制是否展示新绑定入口。
    return totp_user_enabled($user);
}

/** Base32 编码(RFC 4648,去掉填充) */
function totp_base32_encode($bytes)
{
    $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
    $out = '';
    $bits = 0;
    $value = 0;
    $len = strlen($bytes);
    for ($i = 0; $i < $len; $i++) {
        $value = ($value << 8) | ord($bytes[$i]);
        $bits += 8;
        while ($bits >= 5) {
            $bits -= 5;
            $out .= $alphabet[($value >> $bits) & 31];
        }
    }
    if ($bits > 0) {
        $out .= $alphabet[($value << (5 - $bits)) & 31];
    }
    return $out;
}

function totp_base32_decode($secret)
{
    $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
    $secret = strtoupper(preg_replace('/[^A-Za-z2-7]/', '', (string) $secret));
    $bits = 0;
    $value = 0;
    $out = '';
    $len = strlen($secret);
    for ($i = 0; $i < $len; $i++) {
        $pos = strpos($alphabet, $secret[$i]);
        if ($pos === false) {
            continue;
        }
        $value = ($value << 5) | $pos;
        $bits += 5;
        if ($bits >= 8) {
            $bits -= 8;
            $out .= chr(($value >> $bits) & 255);
        }
    }
    return $out;
}

function totp_new_secret($bytes = 20)
{
    return totp_base32_encode(random_bytes(max(10, (int) $bytes)));
}

function totp_code($secret, $timestamp = null, $period = 30, $digits = 6)
{
    $key = totp_base32_decode($secret);
    if ($key === '') {
        return '';
    }
    $timestamp = $timestamp === null ? time() : (int) $timestamp;
    $counter = (int) floor($timestamp / max(1, (int) $period));
    // 64 位计数器拆成两个 32 位整数,兼容 32 位 PHP。
    $counterBytes = pack('N2', (int) floor($counter / 4294967296), $counter & 0xFFFFFFFF);
    $hash = hash_hmac('sha1', $counterBytes, $key, true);
    $offset = ord($hash[19]) & 0x0F;
    $binary = ((ord($hash[$offset]) & 0x7F) << 24)
        | ((ord($hash[$offset + 1]) & 0xFF) << 16)
        | ((ord($hash[$offset + 2]) & 0xFF) << 8)
        | (ord($hash[$offset + 3]) & 0xFF);
    $code = (string) ($binary % (10 ** max(6, min(8, (int) $digits))));
    return str_pad($code, max(6, min(8, (int) $digits)), '0', STR_PAD_LEFT);
}

function totp_verify($secret, $code, $window = 1, $period = 30, $digits = 6)
{
    $code = preg_replace('/\D/', '', (string) $code);
    if (strlen($code) !== (int) $digits) {
        return false;
    }
    $window = max(0, (int) $window);
    $now = time();
    for ($i = -$window; $i <= $window; $i++) {
        $expected = totp_code($secret, $now + ($i * (int) $period), $period, $digits);
        if ($expected !== '' && hash_equals($expected, $code)) {
            return true;
        }
    }
    return false;
}

/** 将 TOTP 密钥用站点密钥加密;无 OpenSSL 时退回 base64(仍避免明文直接展示)。 */
function totp_encrypt_secret($secret)
{
    $secret = (string) $secret;
    $key = hash('sha256', 'komorebi-totp|' . (string) cfg('key', ''), true);
    if (function_exists('openssl_encrypt') && function_exists('openssl_decrypt')) {
        $iv = random_bytes(12);
        $tag = '';
        $cipher = openssl_encrypt($secret, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
        if ($cipher !== false && $tag !== '') {
            return 'v1:' . base64_encode($iv . $tag . $cipher);
        }
    }
    return 'b64:' . base64_encode($secret);
}

function totp_decrypt_secret($stored)
{
    $stored = (string) $stored;
    if ($stored === '') {
        return '';
    }
    if (strpos($stored, 'v1:') === 0) {
        $raw = base64_decode(substr($stored, 3), true);
        if ($raw === false || strlen($raw) < 28) {
            return '';
        }
        $iv = substr($raw, 0, 12);
        $tag = substr($raw, 12, 16);
        $cipher = substr($raw, 28);
        $key = hash('sha256', 'komorebi-totp|' . (string) cfg('key', ''), true);
        $plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
        return $plain === false ? '' : (string) $plain;
    }
    if (strpos($stored, 'b64:') === 0) {
        $raw = base64_decode(substr($stored, 4), true);
        return $raw === false ? '' : (string) $raw;
    }
    // 兼容手工写入的旧/明文密钥。
    return preg_replace('/[^A-Za-z2-7]/', '', strtoupper($stored));
}

function totp_user_secret($user)
{
    return totp_decrypt_secret((string) ($user['totp_secret'] ?? ''));
}

function totp_format_secret($secret)
{
    $secret = strtoupper(preg_replace('/[^A-Za-z2-7]/', '', (string) $secret));
    $parts = str_split($secret, 4);
    return implode(' ', $parts);
}

function totp_setup_uri($secret, $account, $issuer = '')
{
    $issuer = trim((string) $issuer);
    if ($issuer === '') {
        $issuer = (string) setting('site_name', '木漏茶室');
    }
    $account = trim((string) $account);
    if ($account === '') {
        $account = 'account';
    }
    $label = rawurlencode($issuer . ':' . $account);
    return 'otpauth://totp/' . $label
        . '?secret=' . rawurlencode(strtoupper(preg_replace('/[^A-Za-z2-7]/', '', (string) $secret)))
        . '&issuer=' . rawurlencode($issuer)
        . '&algorithm=SHA1&digits=6&period=30';
}

function totp_normalize_backup_code($code)
{
    return strtoupper(preg_replace('/[^A-Za-z0-9]/', '', (string) $code));
}

function totp_backup_hash($code)
{
    $normalized = totp_normalize_backup_code($code);
    return hash_hmac('sha256', 'komorebi-totp-backup|' . $normalized, (string) cfg('key', ''));
}

function totp_generate_backup_codes($count = 8)
{
    $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $codes = [];
    for ($i = 0; $i < max(1, (int) $count); $i++) {
        $raw = '';
        for ($j = 0; $j < 8; $j++) {
            $raw .= $alphabet[random_int(0, strlen($alphabet) - 1)];
        }
        $codes[] = substr($raw, 0, 4) . '-' . substr($raw, 4, 4);
    }
    return $codes;
}

function totp_store_backup_codes($codes)
{
    $hashes = [];
    foreach ((array) $codes as $code) {
        $normalized = totp_normalize_backup_code($code);
        if ($normalized !== '') {
            $hashes[] = totp_backup_hash($normalized);
        }
    }
    return json_encode($hashes, JSON_UNESCAPED_UNICODE);
}

function totp_backup_remaining($user)
{
    $hashes = json_decode((string) ($user['totp_backup_codes'] ?? ''), true);
    return is_array($hashes) ? count($hashes) : 0;
}

/** 校验 TOTP 或一次性恢复码;恢复码用过即从数据库删除。 */
function totp_verify_user_code($user, $code)
{
    $secret = totp_user_secret($user);
    if ($secret !== '' && totp_verify($secret, $code, 1)) {
        return [true, 'totp'];
    }
    $normalized = totp_normalize_backup_code($code);
    if ($normalized === '') {
        return [false, ''];
    }
    $hashes = json_decode((string) ($user['totp_backup_codes'] ?? ''), true);
    if (!is_array($hashes)) {
        return [false, ''];
    }
    $needle = totp_backup_hash($normalized);
    $matched = false;
    $remaining = [];
    foreach ($hashes as $hash) {
        if (!$matched && is_string($hash) && hash_equals($hash, $needle)) {
            $matched = true;
            continue;
        }
        $remaining[] = $hash;
    }
    if (!$matched) {
        return [false, ''];
    }
    DB::run('UPDATE ' . DB::table('users') . ' SET totp_backup_codes = ? WHERE id = ?', [
        json_encode($remaining, JSON_UNESCAPED_UNICODE), (int) $user['id'],
    ]);
    return [true, 'backup'];
}
主题