Spaces:
Running

File size: 3,679 Bytes
6529592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
const crypto = require('crypto');

const SCOPES = {
    profile: {
        title: 'Профиль',
        description: 'Имя, аватар и статус верификации'
    }
};

const randomToken = (bytes = 32) => crypto.randomBytes(bytes).toString('base64url');

const randomCode = () => String(crypto.randomInt(100000, 1000000));

const hashToken = (value) => crypto.createHash('sha256').update(String(value)).digest('hex');

const hashCode = (value) => {
    const { JWT_SECRET } = require('../config/env');
    return crypto.createHmac('sha256', JWT_SECRET).update(String(value)).digest('hex');
};

const safeEqual = (left, right) => {
    const a = Buffer.from(String(left));
    const b = Buffer.from(String(right));
    if (a.length !== b.length) return false;
    return crypto.timingSafeEqual(a, b);
};

const parseScopes = (value) => {
    const parts = String(value || 'profile').trim().split(/\s+/).filter(Boolean);
    if (!parts.length) return ['profile'];
    return [...new Set(parts)];
};

const normalizeScope = (value) => parseScopes(value).join(' ');

const maskUsername = (value) => {
    const name = String(value || '');
    if (name.length <= 2) return name;
    return `${name[0]}${'*'.repeat(Math.max(2, name.length - 2))}${name[name.length - 1]}`;
};

const isAllowedRedirectUri = (value) => {
    try {
        const url = new URL(String(value));
        if (url.hash) return false;
        if (['javascript:', 'data:', 'file:', 'vbscript:', 'about:'].includes(url.protocol)) return false;
        if (url.protocol === 'http:') return ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
        if (url.protocol === 'https:') return Boolean(url.hostname);
        return /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) && Boolean(url.host);
    } catch {
        return false;
    }
};

const buildRedirect = (uri, params) => {
    const url = new URL(String(uri));
    for (const [key, value] of Object.entries(params)) {
        if (value === undefined || value === null || value === '') continue;
        url.searchParams.set(key, String(value));
    }
    return url.toString();
};

const baseUrl = (req) => {
    const configured = String(process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '');
    if (configured) return configured;
    return `${req.protocol}://${req.get('host')}`;
};

const parseBasic = (header) => {
    if (!header || typeof header !== 'string' || !header.startsWith('Basic ')) return null;
    try {
        const decoded = Buffer.from(header.slice(6), 'base64').toString('utf8');
        const index = decoded.indexOf(':');
        if (index < 0) return null;
        return {
            clientId: decodeURIComponent(decoded.slice(0, index)),
            clientSecret: decodeURIComponent(decoded.slice(index + 1))
        };
    } catch {
        return null;
    }
};

const verifyPkce = (verifier, challenge) => {
    if (!verifier || !challenge) return false;
    if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(String(verifier))) return false;
    const computed = crypto.createHash('sha256').update(String(verifier)).digest('base64url');
    return safeEqual(computed, challenge);
};

const publicUser = (user) => ({
    sub: user.username,
    username: user.username,
    preferred_username: user.username,
    displayName: user.displayName || '',
    avatar: user.avatar || null,
    isVerified: Boolean(user.isVerified)
});

module.exports = {
    SCOPES,
    randomToken,
    randomCode,
    hashToken,
    hashCode,
    safeEqual,
    parseScopes,
    normalizeScope,
    maskUsername,
    isAllowedRedirectUri,
    buildRedirect,
    baseUrl,
    parseBasic,
    verifyPkce,
    publicUser
};