@walkhi/code-relax 0.1.0-beta.22 → 0.1.0-beta.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,54 +1,54 @@
1
- const MAX_BATCH = 200;
2
-
3
- export function relayDiagnostics(pool, onError = () => {}) {
4
- let tail = Promise.resolve();
5
- function validSource(source) {
6
- if (!/^[a-z-]{1,32}$/.test(source)) throw new Error('Invalid diagnostic source');
7
- return source;
8
- }
9
- function serialize(action) {
10
- const result = tail.then(action);
11
- tail = result.catch(error => { onError(error); });
12
- return result;
13
- }
14
- function record(source, event, detail) {
15
- validSource(source);
16
- if (!/^[a-z-]{1,32}$/.test(event) || !/^[a-z-]{1,64}$/.test(detail)) throw new Error('Invalid diagnostic event');
17
- void serialize(async () => {
18
- await pool.execute('INSERT INTO relay_diagnostics (created_at,source,event,detail) VALUES (UTC_TIMESTAMP(3),?,?,?)', [source, event, detail]);
19
- await pool.execute('DELETE FROM relay_diagnostics WHERE created_at < UTC_TIMESTAMP(3) - INTERVAL 1 DAY');
20
- }).catch(() => {});
21
- }
22
- async function read(source) {
23
- validSource(source);
24
- return serialize(async () => {
25
- const [rows] = await pool.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
26
- WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1}`, [source]);
27
- return { rows: rows.slice(0, MAX_BATCH), hasMore: rows.length > MAX_BATCH };
28
- });
29
- }
30
- async function clear(source) {
31
- validSource(source);
32
- return serialize(async () => {
33
- const [result] = await pool.execute('DELETE FROM relay_diagnostics WHERE source=?', [source]);
34
- return { cleared: result.affectedRows };
35
- });
36
- }
37
- async function drain(source) {
38
- validSource(source);
39
- return serialize(async () => {
40
- const db = await pool.getConnection();
41
- try {
42
- await db.beginTransaction();
43
- const [rows] = await db.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
44
- WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1} FOR UPDATE`, [source]);
45
- const selected = rows.slice(0, MAX_BATCH);
46
- if (selected.length) await db.execute('DELETE FROM relay_diagnostics WHERE source=? AND id <= ?', [source, selected.at(-1).id]);
47
- await db.commit();
48
- return { rows: selected, hasMore: rows.length > MAX_BATCH };
49
- } catch (error) { await db.rollback(); throw error; }
50
- finally { db.release(); }
51
- });
52
- }
53
- return { record, read, clear, drain };
54
- }
1
+ const MAX_BATCH = 200;
2
+
3
+ export function relayDiagnostics(pool, onError = () => {}) {
4
+ let tail = Promise.resolve();
5
+ function validSource(source) {
6
+ if (!/^[a-z-]{1,32}$/.test(source)) throw new Error('Invalid diagnostic source');
7
+ return source;
8
+ }
9
+ function serialize(action) {
10
+ const result = tail.then(action);
11
+ tail = result.catch(error => { onError(error); });
12
+ return result;
13
+ }
14
+ function record(source, event, detail) {
15
+ validSource(source);
16
+ if (!/^[a-z-]{1,32}$/.test(event) || !/^[a-z0-9=;.-]{1,64}$/.test(detail)) throw new Error('Invalid diagnostic event');
17
+ return serialize(async () => {
18
+ await pool.execute('INSERT INTO relay_diagnostics (created_at,source,event,detail) VALUES (UTC_TIMESTAMP(3),?,?,?)', [source, event, detail]);
19
+ await pool.execute('DELETE FROM relay_diagnostics WHERE created_at < UTC_TIMESTAMP(3) - INTERVAL 1 DAY');
20
+ }).catch(() => {});
21
+ }
22
+ async function read(source) {
23
+ validSource(source);
24
+ return serialize(async () => {
25
+ const [rows] = await pool.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
26
+ WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1}`, [source]);
27
+ return { rows: rows.slice(0, MAX_BATCH), hasMore: rows.length > MAX_BATCH };
28
+ });
29
+ }
30
+ async function clear(source) {
31
+ validSource(source);
32
+ return serialize(async () => {
33
+ const [result] = await pool.execute('DELETE FROM relay_diagnostics WHERE source=?', [source]);
34
+ return { cleared: result.affectedRows };
35
+ });
36
+ }
37
+ async function drain(source) {
38
+ validSource(source);
39
+ return serialize(async () => {
40
+ const db = await pool.getConnection();
41
+ try {
42
+ await db.beginTransaction();
43
+ const [rows] = await db.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
44
+ WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1} FOR UPDATE`, [source]);
45
+ const selected = rows.slice(0, MAX_BATCH);
46
+ if (selected.length) await db.execute('DELETE FROM relay_diagnostics WHERE source=? AND id <= ?', [source, selected.at(-1).id]);
47
+ await db.commit();
48
+ return { rows: selected, hasMore: rows.length > MAX_BATCH };
49
+ } catch (error) { await db.rollback(); throw error; }
50
+ finally { db.release(); }
51
+ });
52
+ }
53
+ return { record, read, clear, drain };
54
+ }
@@ -1,141 +1,158 @@
1
- import fs from 'node:fs';
2
- import { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
3
- import { tencentAccountProvider } from '../../relay-admin/tencent-account-provider.mjs';
4
-
5
- const sqlTime = value => value.replace('T', ' ').replace(/Z$/, '');
6
- const isoTime = value => value.replace(' ', 'T') + 'Z';
7
- const error = (status, message) => Object.assign(new Error(message), { status });
8
- const tokenHash = token => createHash('sha256').update(token).digest('hex');
9
- const normalizeEmail = value => {
10
- if (typeof value !== 'string') throw error(400, 'Invalid email address');
11
- const email = value.trim().toLowerCase();
12
- if (email.length > 254 || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(email)) {
13
- throw error(400, 'Invalid email address');
14
- }
15
- return email;
16
- };
17
-
18
- export function openEmailAccounts(pool, configFile, providerOverride) {
19
- const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
20
- if (![config.secretId, config.secretKey, config.captchaAppSecretKey, config.fromEmailAddress, config.sesRegion]
21
- .every(value => typeof value === 'string' && value.length > 0) ||
22
- !Number.isSafeInteger(config.captchaAppId) || config.captchaAppId < 1 ||
23
- !Number.isSafeInteger(config.emailTemplateId) || config.emailTemplateId < 1 ||
24
- typeof config.codePepper !== 'string' || config.codePepper.length < 32) {
25
- throw new Error('Incomplete relay account configuration');
26
- }
27
- const provider = providerOverride || tencentAccountProvider(config);
28
- const codeHash = (email, code) => createHmac('sha256', config.codePepper).update(`${email}\0${code}`).digest('hex');
29
- const scopeHash = value => createHmac('sha256', config.codePepper).update(value).digest('hex');
30
-
31
- async function requestCode({ email: rawEmail, ticket, randstr }, ip) {
32
- const email = normalizeEmail(rawEmail);
33
- if (typeof ticket !== 'string' || !ticket || ticket.length > 2048 ||
34
- typeof randstr !== 'string' || !randstr || randstr.length > 128) throw error(400, 'Invalid human verification');
35
- if (!ip || ip.length > 64) throw error(400, 'Invalid client address');
36
- // A cheap pre-check precedes the billable human verification.
37
- const [recent] = await pool.execute('SELECT sent_at FROM email_login_challenges WHERE email = ? AND sent_at > UTC_TIMESTAMP(3) - INTERVAL 60 SECOND', [email]);
38
- if (recent.length) throw error(429, 'Please wait before requesting another code');
39
- const [ipLimit] = await pool.execute(`SELECT request_count FROM email_send_limits
40
- WHERE scope_hash=? AND window_start>=UTC_TIMESTAMP() - INTERVAL 1 HOUR ORDER BY window_start DESC LIMIT 1`, [scopeHash(`ip:${ip}`)]);
41
- if (ipLimit[0]?.request_count >= 20) throw error(429, 'Too many email requests');
42
- if (!await provider.verifyHuman(ticket, randstr, ip)) throw error(403, 'Human verification failed');
43
- const code = String(randomInt(0, 1000000)).padStart(6, '0');
44
- const hash = codeHash(email, code);
45
- const windowStart = sqlTime(new Date(Math.floor(Date.now() / 3600000) * 3600000).toISOString()).slice(0, 19);
46
- const db = await pool.getConnection();
47
- try {
48
- await db.beginTransaction();
49
- for (const [scope, limit] of [[`email:${email}`, 5], [`ip:${ip}`, 20]]) {
50
- const key = scopeHash(scope);
51
- await db.execute('INSERT INTO email_send_limits (scope_hash,window_start,request_count) VALUES (?,?,1) ON DUPLICATE KEY UPDATE request_count=request_count+1', [key, windowStart]);
52
- const [rows] = await db.execute('SELECT request_count FROM email_send_limits WHERE scope_hash=? AND window_start=? FOR UPDATE', [key, windowStart]);
53
- if (rows[0].request_count > limit) throw error(429, 'Too many email requests');
54
- }
55
- const [existing] = await db.execute('SELECT sent_at FROM email_login_challenges WHERE email=? FOR UPDATE', [email]);
56
- if (existing.length && Date.now() - new Date(`${existing[0].sent_at.replace(' ', 'T')}Z`).getTime() < 60000) {
57
- throw error(429, 'Please wait before requesting another code');
58
- }
59
- await db.execute(`INSERT INTO email_login_challenges (email,code_hash,expires_at,attempts,sent_at)
60
- VALUES (?, ?, UTC_TIMESTAMP(3) + INTERVAL 10 MINUTE, 0, UTC_TIMESTAMP(3))
61
- ON DUPLICATE KEY UPDATE code_hash=VALUES(code_hash),expires_at=VALUES(expires_at),attempts=0,sent_at=VALUES(sent_at)`, [email, hash]);
62
- await db.commit();
63
- } catch (failure) { await db.rollback(); throw failure; }
64
- finally { db.release(); }
65
- try { await provider.sendLoginCode(email, code); }
66
- catch (failure) {
67
- await pool.execute('DELETE FROM email_login_challenges WHERE email=? AND code_hash=?', [email, hash]);
68
- throw error(503, 'Email delivery unavailable');
69
- }
70
- return { sent: true, expiresInSeconds: 600 };
71
- }
72
-
73
- async function verifyCode({ email: rawEmail, code }) {
74
- const email = normalizeEmail(rawEmail);
75
- if (typeof code !== 'string' || !/^\d{6}$/.test(code)) throw error(400, 'Invalid code');
76
- const db = await pool.getConnection();
77
- try {
78
- await db.beginTransaction();
79
- const [challenges] = await db.execute('SELECT code_hash,attempts,expires_at FROM email_login_challenges WHERE email=? FOR UPDATE', [email]);
80
- const challenge = challenges[0];
81
- if (!challenge || new Date(`${challenge.expires_at.replace(' ', 'T')}Z`).getTime() <= Date.now()) throw error(401, 'Code expired or incorrect');
82
- const supplied = Buffer.from(codeHash(email, code), 'hex');
83
- if (!timingSafeEqual(supplied, Buffer.from(challenge.code_hash, 'hex'))) {
84
- if (challenge.attempts >= 4) await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
85
- else await db.execute('UPDATE email_login_challenges SET attempts=attempts+1 WHERE email=?', [email]);
86
- await db.commit();
87
- throw error(401, 'Code expired or incorrect');
88
- }
89
- await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
90
- const [identities] = await db.execute(`SELECT u.id,u.status FROM user_login_identities i
91
- JOIN users u ON u.id=i.user_id WHERE i.kind='email' AND i.normalized_value=?`, [email]);
92
- let userId = identities[0]?.id;
93
- if (identities[0]?.status === 'disabled') throw error(403, 'Account unavailable');
94
- if (!userId) {
95
- userId = randomUUID();
96
- await db.execute('INSERT INTO users (id,status,created_at,updated_at) VALUES (?,\'active\',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))', [userId]);
97
- await db.execute(`INSERT INTO user_login_identities (user_id,kind,normalized_value,verified_at,created_at)
98
- VALUES (?,'email',?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))`, [userId, email]);
99
- }
100
- const token = randomBytes(32).toString('base64url');
101
- await db.execute(`INSERT INTO user_sessions (token_hash,user_id,created_at,expires_at)
102
- VALUES (?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3) + INTERVAL 30 DAY)`, [tokenHash(token), userId]);
103
- await db.commit();
104
- return { token, user: { id: userId, email }, expiresInSeconds: 30 * 86400 };
105
- } catch (failure) { await db.rollback(); throw failure; }
106
- finally { db.release(); }
107
- }
108
-
109
- async function current(token) {
110
- if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw error(401, 'Unauthorized');
111
- const [rows] = await pool.execute(`SELECT u.id,i.normalized_value AS email,s.expires_at FROM user_sessions s
112
- JOIN users u ON u.id=s.user_id JOIN user_login_identities i ON i.user_id=u.id AND i.kind='email'
113
- WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>UTC_TIMESTAMP(3) AND u.status='active'`, [tokenHash(token)]);
114
- if (!rows.length) throw error(401, 'Unauthorized');
115
- return { id: rows[0].id, email: rows[0].email, expiresAt: isoTime(rows[0].expires_at) };
116
- }
117
-
118
- async function usage(userId) {
119
- const [settings] = await pool.query('SELECT mode FROM relay_usage_settings WHERE id=1');
120
- if (settings.length !== 1) throw new Error('Missing relay usage settings');
121
- const [budgets] = await pool.execute(`SELECT period_start,period_end,limit_seconds,used_seconds FROM relay_usage_budgets
122
- WHERE user_id=? AND period_start<=UTC_TIMESTAMP(3) AND period_end>UTC_TIMESTAMP(3)
123
- ORDER BY period_start DESC LIMIT 2`, [userId]);
124
- if (budgets.length > 1) throw new Error('Overlapping relay usage budgets');
125
- const budget = budgets[0];
126
- const [totals] = await pool.execute('SELECT task_seconds FROM relay_usage_totals WHERE user_id=?', [userId]);
127
- return { mode: settings[0].mode, periodStart: budget ? isoTime(budget.period_start) : null,
128
- periodEnd: budget ? isoTime(budget.period_end) : null,
129
- limitSeconds: budget?.limit_seconds == null ? null : Number(budget.limit_seconds),
130
- usedSeconds: budget ? Number(budget.used_seconds) : 0,
131
- taskSeconds: Number(totals[0]?.task_seconds || 0) };
132
- }
133
-
134
- async function logout(token) {
135
- await current(token);
136
- await pool.execute('UPDATE user_sessions SET revoked_at=UTC_TIMESTAMP(3) WHERE token_hash=? AND revoked_at IS NULL', [tokenHash(token)]);
137
- return { ok: true };
138
- }
139
-
140
- return { captchaAppId: config.captchaAppId, requestCode, verifyCode, current, usage, logout };
141
- }
1
+ import fs from 'node:fs';
2
+ import { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
3
+ import { tencentAccountProvider } from '../../relay-admin/tencent-account-provider.mjs';
4
+
5
+ const sqlTime = value => value.replace('T', ' ').replace(/Z$/, '');
6
+ const isoTime = value => value.replace(' ', 'T') + 'Z';
7
+ const error = (status, message) => Object.assign(new Error(message), { status });
8
+ const tokenHash = token => createHash('sha256').update(token).digest('hex');
9
+ const normalizeEmail = value => {
10
+ if (typeof value !== 'string') throw error(400, 'Invalid email address');
11
+ const email = value.trim().toLowerCase();
12
+ if (email.length > 254 || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(email)) {
13
+ throw error(400, 'Invalid email address');
14
+ }
15
+ return email;
16
+ };
17
+
18
+ export function openEmailAccounts(pool, configFile, providerOverride) {
19
+ const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
20
+ if (![config.secretId, config.secretKey, config.captchaAppSecretKey, config.fromEmailAddress, config.sesRegion]
21
+ .every(value => typeof value === 'string' && value.length > 0) ||
22
+ !Number.isSafeInteger(config.captchaAppId) || config.captchaAppId < 1 ||
23
+ !Number.isSafeInteger(config.emailTemplateId) || config.emailTemplateId < 1 ||
24
+ typeof config.codePepper !== 'string' || config.codePepper.length < 32) {
25
+ throw new Error('Incomplete relay account configuration');
26
+ }
27
+ const provider = providerOverride || tencentAccountProvider(config);
28
+ const codeHash = (email, code) => createHmac('sha256', config.codePepper).update(`${email}\0${code}`).digest('hex');
29
+ const scopeHash = value => createHmac('sha256', config.codePepper).update(value).digest('hex');
30
+
31
+ async function requestCode({ email: rawEmail, ticket, randstr }, ip) {
32
+ const email = normalizeEmail(rawEmail);
33
+ if (typeof ticket !== 'string' || !ticket || ticket.length > 2048 ||
34
+ typeof randstr !== 'string' || !randstr || randstr.length > 128) throw error(400, 'Invalid human verification');
35
+ if (!ip || ip.length > 64) throw error(400, 'Invalid client address');
36
+ const [identities] = await pool.execute("SELECT u.status FROM user_login_identities i JOIN users u ON u.id=i.user_id WHERE i.kind='email' AND i.normalized_value=?", [email]);
37
+ if (identities[0]?.status === 'cancelled') throw error(409, '该邮箱关联的账号正在注销清理中,暂时无法注册或登录。相关信息将在注销后7天内删除,清理完成后可重新注册。');
38
+ // A cheap pre-check precedes the billable human verification.
39
+ const [recent] = await pool.execute('SELECT sent_at FROM email_login_challenges WHERE email = ? AND sent_at > UTC_TIMESTAMP(3) - INTERVAL 60 SECOND', [email]);
40
+ if (recent.length) throw error(429, 'Please wait before requesting another code');
41
+ const [ipLimit] = await pool.execute(`SELECT request_count FROM email_send_limits
42
+ WHERE scope_hash=? AND window_start>=UTC_TIMESTAMP() - INTERVAL 1 HOUR ORDER BY window_start DESC LIMIT 1`, [scopeHash(`ip:${ip}`)]);
43
+ if (ipLimit[0]?.request_count >= 20) throw error(429, 'Too many email requests');
44
+ if (!await provider.verifyHuman(ticket, randstr, ip)) throw error(403, 'Human verification failed');
45
+ const code = String(randomInt(0, 1000000)).padStart(6, '0');
46
+ const hash = codeHash(email, code);
47
+ const windowStart = sqlTime(new Date(Math.floor(Date.now() / 3600000) * 3600000).toISOString()).slice(0, 19);
48
+ const db = await pool.getConnection();
49
+ try {
50
+ await db.beginTransaction();
51
+ for (const [scope, limit] of [[`email:${email}`, 5], [`ip:${ip}`, 20]]) {
52
+ const key = scopeHash(scope);
53
+ await db.execute('INSERT INTO email_send_limits (scope_hash,window_start,request_count) VALUES (?,?,1) ON DUPLICATE KEY UPDATE request_count=request_count+1', [key, windowStart]);
54
+ const [rows] = await db.execute('SELECT request_count FROM email_send_limits WHERE scope_hash=? AND window_start=? FOR UPDATE', [key, windowStart]);
55
+ if (rows[0].request_count > limit) throw error(429, 'Too many email requests');
56
+ }
57
+ const [existing] = await db.execute('SELECT sent_at FROM email_login_challenges WHERE email=? FOR UPDATE', [email]);
58
+ if (existing.length && Date.now() - new Date(`${existing[0].sent_at.replace(' ', 'T')}Z`).getTime() < 60000) {
59
+ throw error(429, 'Please wait before requesting another code');
60
+ }
61
+ await db.execute(`INSERT INTO email_login_challenges (email,code_hash,expires_at,attempts,sent_at)
62
+ VALUES (?, ?, UTC_TIMESTAMP(3) + INTERVAL 10 MINUTE, 0, UTC_TIMESTAMP(3))
63
+ ON DUPLICATE KEY UPDATE code_hash=VALUES(code_hash),expires_at=VALUES(expires_at),attempts=0,sent_at=VALUES(sent_at)`, [email, hash]);
64
+ await db.commit();
65
+ } catch (failure) { await db.rollback(); throw failure; }
66
+ finally { db.release(); }
67
+ try { await provider.sendLoginCode(email, code); }
68
+ catch (failure) {
69
+ await pool.execute('DELETE FROM email_login_challenges WHERE email=? AND code_hash=?', [email, hash]);
70
+ throw error(503, 'Email delivery unavailable');
71
+ }
72
+ return { sent: true, expiresInSeconds: 600 };
73
+ }
74
+
75
+ async function verifyCode({ email: rawEmail, code }) {
76
+ const email = normalizeEmail(rawEmail);
77
+ if (typeof code !== 'string' || !/^\d{6}$/.test(code)) throw error(400, 'Invalid code');
78
+ const db = await pool.getConnection();
79
+ try {
80
+ await db.beginTransaction();
81
+ const [challenges] = await db.execute('SELECT code_hash,attempts,expires_at FROM email_login_challenges WHERE email=? FOR UPDATE', [email]);
82
+ const challenge = challenges[0];
83
+ if (!challenge || new Date(`${challenge.expires_at.replace(' ', 'T')}Z`).getTime() <= Date.now()) throw error(401, 'Code expired or incorrect');
84
+ const supplied = Buffer.from(codeHash(email, code), 'hex');
85
+ if (!timingSafeEqual(supplied, Buffer.from(challenge.code_hash, 'hex'))) {
86
+ if (challenge.attempts >= 4) await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
87
+ else await db.execute('UPDATE email_login_challenges SET attempts=attempts+1 WHERE email=?', [email]);
88
+ await db.commit();
89
+ throw error(401, 'Code expired or incorrect');
90
+ }
91
+ await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
92
+ const [identities] = await db.execute(`SELECT u.id,u.status FROM user_login_identities i
93
+ JOIN users u ON u.id=i.user_id WHERE i.kind='email' AND i.normalized_value=?`, [email]);
94
+ let userId = identities[0]?.id;
95
+ if (identities[0]?.status === 'cancelled') throw error(409, '该邮箱关联的账号正在注销清理中,暂时无法注册或登录。相关信息将在注销后7天内删除,清理完成后可重新注册。');
96
+ if (identities[0]?.status === 'disabled') throw error(403, 'Account unavailable');
97
+ if (!userId) {
98
+ userId = randomUUID();
99
+ await db.execute('INSERT INTO users (id,status,created_at,updated_at) VALUES (?,\'active\',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))', [userId]);
100
+ await db.execute(`INSERT INTO user_login_identities (user_id,kind,normalized_value,verified_at,created_at)
101
+ VALUES (?,'email',?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))`, [userId, email]);
102
+ }
103
+ const token = randomBytes(32).toString('base64url');
104
+ await db.execute(`INSERT INTO user_sessions (token_hash,user_id,created_at,expires_at)
105
+ VALUES (?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3) + INTERVAL 30 DAY)`, [tokenHash(token), userId]);
106
+ await db.commit();
107
+ return { token, user: { id: userId, email }, expiresInSeconds: 30 * 86400 };
108
+ } catch (failure) { await db.rollback(); throw failure; }
109
+ finally { db.release(); }
110
+ }
111
+
112
+ async function current(token) {
113
+ if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw error(401, 'Unauthorized');
114
+ const [rows] = await pool.execute(`SELECT u.id,i.normalized_value AS email,s.expires_at FROM user_sessions s
115
+ JOIN users u ON u.id=s.user_id JOIN user_login_identities i ON i.user_id=u.id AND i.kind='email'
116
+ WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>UTC_TIMESTAMP(3) AND u.status='active'`, [tokenHash(token)]);
117
+ if (!rows.length) throw error(401, 'Unauthorized');
118
+ return { id: rows[0].id, email: rows[0].email, expiresAt: isoTime(rows[0].expires_at) };
119
+ }
120
+
121
+ async function usage(userId) {
122
+ const [settings] = await pool.query('SELECT mode FROM relay_usage_settings WHERE id=1');
123
+ if (settings.length !== 1) throw new Error('Missing relay usage settings');
124
+ const [budgets] = await pool.execute(`SELECT period_start,period_end,limit_seconds,used_seconds FROM relay_usage_budgets
125
+ WHERE user_id=? AND period_start<=UTC_TIMESTAMP(3) AND period_end>UTC_TIMESTAMP(3)
126
+ ORDER BY period_start DESC LIMIT 2`, [userId]);
127
+ if (budgets.length > 1) throw new Error('Overlapping relay usage budgets');
128
+ const budget = budgets[0];
129
+ const [totals] = await pool.execute('SELECT task_seconds FROM relay_usage_totals WHERE user_id=?', [userId]);
130
+ return { mode: settings[0].mode, periodStart: budget ? isoTime(budget.period_start) : null,
131
+ periodEnd: budget ? isoTime(budget.period_end) : null,
132
+ limitSeconds: budget?.limit_seconds == null ? null : Number(budget.limit_seconds),
133
+ usedSeconds: budget ? Number(budget.used_seconds) : 0,
134
+ taskSeconds: Number(totals[0]?.task_seconds || 0) };
135
+ }
136
+
137
+ async function logout(token) {
138
+ await current(token);
139
+ await pool.execute('UPDATE user_sessions SET revoked_at=UTC_TIMESTAMP(3) WHERE token_hash=? AND revoked_at IS NULL', [tokenHash(token)]);
140
+ return { ok: true };
141
+ }
142
+
143
+ async function cancelAccount(token) {
144
+ const user = await current(token);
145
+ const db = await pool.getConnection();
146
+ try {
147
+ await db.beginTransaction();
148
+ await db.execute("UPDATE users SET status='cancelled',cancelled_at=UTC_TIMESTAMP(3),updated_at=UTC_TIMESTAMP(3) WHERE id=? AND status='active'", [user.id]);
149
+ await db.execute('UPDATE user_sessions SET revoked_at=COALESCE(revoked_at,UTC_TIMESTAMP(3)) WHERE user_id=?', [user.id]);
150
+ await db.execute('UPDATE relay_usage_sessions SET ended_at=confirmed_until WHERE user_id=? AND ended_at IS NULL', [user.id]);
151
+ await db.commit();
152
+ return { ok: true };
153
+ } catch (failure) { await db.rollback(); throw failure; }
154
+ finally { db.release(); }
155
+ }
156
+
157
+ return { captchaAppId: config.captchaAppId, requestCode, verifyCode, current, usage, logout, cancelAccount };
158
+ }