sneakoscope 8.0.2 → 8.0.3
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.
- package/README.md +47 -23
- package/config/skills-hash-ledger.v1.json +1 -1
- package/crates/sks-core/Cargo.lock +1 -1
- package/crates/sks-core/Cargo.toml +1 -1
- package/dist/bin/fast-inline.js +55 -13
- package/dist/bin/sks-dispatch.js +1 -1
- package/dist/cli/command-manifest-lite.js +4 -0
- package/dist/cli/command-registry.js +4 -0
- package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
- package/dist/cli/install-helpers-codex-lb-config.js +74 -8
- package/dist/cli/install-helpers.js +89 -44
- package/dist/commands/codex-lb.js +117 -19
- package/dist/commands/doctor.js +697 -37
- package/dist/config/skills-manifest.json +3 -2
- package/dist/core/agents/agent-runner-codex-exec.js +5 -3
- package/dist/core/codex/codex-config-guard.js +238 -52
- package/dist/core/codex-adapter.js +5 -3
- package/dist/core/codex-app/menubar/constants.js +10 -1
- package/dist/core/codex-app/menubar/global-install.js +288 -0
- package/dist/core/codex-app/menubar/installer.js +79 -14
- package/dist/core/codex-app/menubar/launch-agent.js +267 -45
- package/dist/core/codex-app/menubar/paths.js +3 -0
- package/dist/core/codex-app/menubar/rollback.js +55 -7
- package/dist/core/codex-app/menubar/status.js +75 -4
- package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
- package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
- package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
- package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
- package/dist/core/codex-exec-output-schema.js +4 -1
- package/dist/core/codex-lb/codex-lb-env.js +63 -72
- package/dist/core/codex-lb/codex-lb-setup.js +15 -2
- package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
- package/dist/core/codex-lb/desktop-controller.js +153 -24
- package/dist/core/codex-lb/routing-truth.js +327 -0
- package/dist/core/codex-native/core-skill-manifest.js +1 -1
- package/dist/core/commands/basic-cli.js +7 -1
- package/dist/core/commands/qa-loop-command.js +3 -1
- package/dist/core/commands/telegram-command.js +241 -0
- package/dist/core/config-adopt/config-adopt-command.js +35 -0
- package/dist/core/config-adopt/config-adopt.js +346 -0
- package/dist/core/config-adopt/index.js +3 -0
- package/dist/core/doctor/command-alias-cleanup.js +4 -1
- package/dist/core/doctor/current-project-guidance-nested.js +37 -6
- package/dist/core/doctor/current-project-guidance.js +11 -6
- package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
- package/dist/core/doctor/retired-managed-residue-private.js +1 -1
- package/dist/core/doctor/sks-menubar-doctor.js +4 -0
- package/dist/core/feature-fixtures.js +8 -0
- package/dist/core/hooks-runtime/hook-context.js +9 -0
- package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
- package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
- package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
- package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
- package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
- package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
- package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
- package/dist/core/hooks-runtime.js +148 -4
- package/dist/core/imagegen/imagegen-capability.js +46 -0
- package/dist/core/imagegen/require-imagegen.js +2 -2
- package/dist/core/init/skills.js +17 -3
- package/dist/core/install/installed-package-smoke.js +8 -2
- package/dist/core/naruto/hardware-capacity-probe.js +9 -3
- package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
- package/dist/core/perf/import-graph-budget.js +0 -1
- package/dist/core/product-design-app-server.js +13 -1
- package/dist/core/release/package-size-budget.js +2 -2
- package/dist/core/release/release-pack-receipt.js +1 -2
- package/dist/core/routes/dollar-manifest-lite.js +1 -1
- package/dist/core/routes.js +1 -1
- package/dist/core/security/private-credential-file.js +209 -0
- package/dist/core/subagents/agent-catalog.js +17 -32
- package/dist/core/subagents/naruto-help-contract.js +5 -5
- package/dist/core/subagents/official-subagent-config.js +16 -6
- package/dist/core/subagents/official-subagent-preparation.js +34 -15
- package/dist/core/subagents/official-subagent-prompt.js +4 -4
- package/dist/core/subagents/official-subagent-runner.js +27 -4
- package/dist/core/subagents/thread-budget.js +19 -12
- package/dist/core/subagents/wave-lifecycle.js +18 -6
- package/dist/core/telegram/access.js +54 -0
- package/dist/core/telegram/client.js +144 -0
- package/dist/core/telegram/confirmation.js +37 -0
- package/dist/core/telegram/doctor.js +151 -0
- package/dist/core/telegram/index.js +9 -0
- package/dist/core/telegram/keychain.js +265 -0
- package/dist/core/telegram/liveness.js +109 -0
- package/dist/core/telegram/poller.js +90 -0
- package/dist/core/telegram/redaction.js +15 -0
- package/dist/core/telegram/types.js +1 -0
- package/dist/core/update/update-diagnostics.js +52 -0
- package/dist/core/update/update-migration-state.js +5 -1
- package/dist/core/update/update-operation.js +2 -1
- package/dist/core/update/update-stage-diagnostics.js +38 -0
- package/dist/core/update/update-status.js +2 -9
- package/dist/core/update-check.js +147 -31
- package/dist/core/version.js +1 -1
- package/dist/core/zellij/zellij-launcher.js +23 -4
- package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
- package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
- package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
- package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
- package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
- package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
- package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
- package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
- package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
- package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
- package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
- package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
- package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
- package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
- package/dist/native/sks-menubar/Sources/main.swift +15 -1
- package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
- package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
- package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
- package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
- package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
- package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
- package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
- package/dist/scripts/current-command-surface-check.js +2 -4
- package/dist/scripts/official-subagent-workflow-check.js +1 -1
- package/dist/scripts/packlist-performance-check.js +1 -2
- package/package.json +1 -1
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { redactTelegramError } from './redaction.js';
|
|
2
|
+
import { readTelegramLivenessReceipt, telegramLivenessPath } from './liveness.js';
|
|
3
|
+
export async function probeTelegram(input) {
|
|
4
|
+
const now = input.now ?? Date.now();
|
|
5
|
+
if (!input.client || !input.tokenProvider) {
|
|
6
|
+
return probeTelegramReceipt(input.receiptPath, now);
|
|
7
|
+
}
|
|
8
|
+
const receiptProbe = !input.access || !input.poller
|
|
9
|
+
? await probeTelegramReceipt(input.receiptPath, now)
|
|
10
|
+
: null;
|
|
11
|
+
const blockers = receiptProbe
|
|
12
|
+
? receiptProbe.blockers.filter((blocker) => ![
|
|
13
|
+
'telegram_token_missing',
|
|
14
|
+
'telegram_getme_not_valid',
|
|
15
|
+
'telegram_getme_stale'
|
|
16
|
+
].includes(blocker))
|
|
17
|
+
: [];
|
|
18
|
+
let tokenConfigured = false;
|
|
19
|
+
try {
|
|
20
|
+
tokenConfigured = Boolean(String(await input.tokenProvider.loadToken() ?? '').trim());
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
blockers.push(`telegram_token_load_failed:${redactTelegramError(error)}`);
|
|
24
|
+
}
|
|
25
|
+
let identityValid = false;
|
|
26
|
+
let getMeCheckedAt = null;
|
|
27
|
+
let getMeLatencyMs = null;
|
|
28
|
+
if (!tokenConfigured)
|
|
29
|
+
blockers.push('telegram_token_missing');
|
|
30
|
+
else {
|
|
31
|
+
const started = Date.now();
|
|
32
|
+
try {
|
|
33
|
+
identityValid = (await input.client.getMe()).is_bot === true;
|
|
34
|
+
if (!identityValid)
|
|
35
|
+
blockers.push('telegram_getme_not_bot');
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
blockers.push(`telegram_getme_failed:${redactTelegramError(error)}`);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
getMeLatencyMs = Date.now() - started;
|
|
42
|
+
getMeCheckedAt = new Date().toISOString();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let pairedChatCount = receiptProbe?.paired_chat_count ?? 0;
|
|
46
|
+
if (input.access) {
|
|
47
|
+
try {
|
|
48
|
+
pairedChatCount = await input.access.authorizedCount();
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
blockers.push(`telegram_access_state_failed:${redactTelegramError(error)}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (pairedChatCount === 0 && !blockers.includes('telegram_private_chat_not_paired')) {
|
|
55
|
+
blockers.push('telegram_private_chat_not_paired');
|
|
56
|
+
}
|
|
57
|
+
let poller = receiptProbe?.poller ?? emptyPoller();
|
|
58
|
+
if (input.poller) {
|
|
59
|
+
try {
|
|
60
|
+
poller = input.poller.snapshot();
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
blockers.push(`telegram_poller_state_failed:${redactTelegramError(error)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!poller.running && !blockers.includes('telegram_poller_not_running')) {
|
|
67
|
+
blockers.push('telegram_poller_not_running');
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
schema: 'sks.telegram-doctor-probe.v1',
|
|
71
|
+
ok: blockers.length === 0,
|
|
72
|
+
status: !tokenConfigured ? 'not_configured' : blockers.length ? 'degraded' : 'ready',
|
|
73
|
+
token_configured: tokenConfigured,
|
|
74
|
+
bot_identity_valid: identityValid,
|
|
75
|
+
getme_checked_at: getMeCheckedAt,
|
|
76
|
+
getme_latency_ms: getMeLatencyMs,
|
|
77
|
+
getme_check_kind: 'live',
|
|
78
|
+
paired_chat_count: pairedChatCount,
|
|
79
|
+
audit_healthy: receiptProbe?.audit_healthy ?? true,
|
|
80
|
+
audit_last_error: receiptProbe?.audit_last_error ?? null,
|
|
81
|
+
poller,
|
|
82
|
+
blockers: [...new Set(blockers)],
|
|
83
|
+
checked_at: new Date().toISOString()
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function probeTelegramReceipt(receiptPath, now) {
|
|
87
|
+
const liveness = await readTelegramLivenessReceipt(receiptPath ?? telegramLivenessPath(), now);
|
|
88
|
+
if (!liveness.ok) {
|
|
89
|
+
return {
|
|
90
|
+
schema: 'sks.telegram-doctor-probe.v1', ok: false, status: 'not_configured',
|
|
91
|
+
token_configured: false, bot_identity_valid: false, paired_chat_count: 0,
|
|
92
|
+
audit_healthy: false, audit_last_error: null,
|
|
93
|
+
getme_checked_at: null, getme_latency_ms: null,
|
|
94
|
+
getme_check_kind: 'receipt',
|
|
95
|
+
poller: emptyPoller(), blockers: [liveness.blocker], checked_at: new Date(now).toISOString()
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const receipt = liveness.receipt;
|
|
99
|
+
const blockers = [];
|
|
100
|
+
if (!receipt.token_configured)
|
|
101
|
+
blockers.push('telegram_token_missing');
|
|
102
|
+
if (receipt.token_configured && !receipt.bot_identity_valid)
|
|
103
|
+
blockers.push('telegram_getme_not_valid');
|
|
104
|
+
const getMeAge = receipt.getme_checked_at ? now - Date.parse(receipt.getme_checked_at) : Number.POSITIVE_INFINITY;
|
|
105
|
+
if (receipt.bot_identity_valid && getMeAge > 10 * 60_000)
|
|
106
|
+
blockers.push('telegram_getme_stale');
|
|
107
|
+
if (receipt.paired_chat_count === 0)
|
|
108
|
+
blockers.push('telegram_private_chat_not_paired');
|
|
109
|
+
if (receipt.audit_healthy === false)
|
|
110
|
+
blockers.push('telegram_audit_unavailable');
|
|
111
|
+
if (!receipt.running || !receipt.poller.running)
|
|
112
|
+
blockers.push('telegram_poller_not_running');
|
|
113
|
+
if (liveness.stale)
|
|
114
|
+
blockers.push('telegram_liveness_stale');
|
|
115
|
+
if (receipt.poller.consecutive_failures > 0)
|
|
116
|
+
blockers.push('telegram_poller_degraded');
|
|
117
|
+
return {
|
|
118
|
+
schema: 'sks.telegram-doctor-probe.v1',
|
|
119
|
+
ok: blockers.length === 0,
|
|
120
|
+
status: !receipt.token_configured ? 'not_configured' : blockers.length ? 'degraded' : 'ready',
|
|
121
|
+
token_configured: receipt.token_configured,
|
|
122
|
+
bot_identity_valid: receipt.bot_identity_valid,
|
|
123
|
+
getme_checked_at: receipt.getme_checked_at,
|
|
124
|
+
getme_latency_ms: receipt.getme_latency_ms,
|
|
125
|
+
getme_check_kind: 'receipt',
|
|
126
|
+
paired_chat_count: receipt.paired_chat_count,
|
|
127
|
+
audit_healthy: receipt.audit_healthy !== false,
|
|
128
|
+
audit_last_error: receipt.audit_last_error ?? null,
|
|
129
|
+
poller: receipt.poller,
|
|
130
|
+
blockers,
|
|
131
|
+
checked_at: new Date(now).toISOString()
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function emptyPoller() {
|
|
135
|
+
return {
|
|
136
|
+
schema: 'sks.telegram-poller-state.v1', running: false, offset: 0,
|
|
137
|
+
consecutive_failures: 0, last_poll_at: null, last_success_at: null,
|
|
138
|
+
last_update_at: null, last_error: null
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export function telegramSelfHealAction(probe) {
|
|
142
|
+
if (!probe.audit_healthy || probe.blockers.includes('telegram_audit_unavailable'))
|
|
143
|
+
return 'operator_repair_audit';
|
|
144
|
+
if (!probe.token_configured || !probe.bot_identity_valid || probe.blockers.includes('telegram_getme_stale'))
|
|
145
|
+
return 'revalidate_token';
|
|
146
|
+
if (/409|webhook/i.test(probe.poller.last_error ?? ''))
|
|
147
|
+
return 'operator_remove_webhook';
|
|
148
|
+
if (probe.blockers.includes('telegram_liveness_stale') || !probe.poller.running || probe.poller.consecutive_failures > 0)
|
|
149
|
+
return 'restart_poll';
|
|
150
|
+
return 'none';
|
|
151
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './access.js';
|
|
2
|
+
export * from './client.js';
|
|
3
|
+
export * from './confirmation.js';
|
|
4
|
+
export * from './doctor.js';
|
|
5
|
+
export * from './liveness.js';
|
|
6
|
+
export * from './keychain.js';
|
|
7
|
+
export * from './poller.js';
|
|
8
|
+
export * from './redaction.js';
|
|
9
|
+
export * from './types.js';
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomInt, randomUUID } from 'node:crypto';
|
|
5
|
+
import { assertTestHomeWriteAllowed } from '../fsx.js';
|
|
6
|
+
import { PrivateCredentialFileError, readPrivateCredentialFile, writePrivateTextAtomic } from '../security/private-credential-file.js';
|
|
7
|
+
export const TELEGRAM_TOKEN_ENV_NAMES = ['TELEGRAM_BOT_TOKEN', 'SKS_TELEGRAM_BOT_TOKEN'];
|
|
8
|
+
export const TELEGRAM_STATE_SCHEMA = 'sks.telegram-state.v1';
|
|
9
|
+
export const TELEGRAM_PAIRING_SCHEMA = 'sks.telegram-pairing.v1';
|
|
10
|
+
export const TELEGRAM_STATE_MAX_BYTES = 1024 * 1024;
|
|
11
|
+
const TELEGRAM_TOKEN_PATTERN = /^\d{5,20}:[A-Za-z0-9_-]{20,128}$/;
|
|
12
|
+
const TELEGRAM_TOKEN_MAX_BYTES = 1024;
|
|
13
|
+
const TELEGRAM_STATE_LOCK_ATTEMPTS = 200;
|
|
14
|
+
const TELEGRAM_STATE_LOCK_RETRY_MS = 25;
|
|
15
|
+
export function telegramPrivatePaths(env = process.env) {
|
|
16
|
+
const sksHome = path.resolve(env.SKS_HOME || path.join(env.HOME || os.homedir(), '.sneakoscope'));
|
|
17
|
+
const secretDir = path.join(sksHome, 'secrets');
|
|
18
|
+
const stateDir = path.join(sksHome, 'state');
|
|
19
|
+
return {
|
|
20
|
+
sksHome,
|
|
21
|
+
secretDir,
|
|
22
|
+
tokenPath: path.join(secretDir, 'telegram-bot-token'),
|
|
23
|
+
stateDir,
|
|
24
|
+
statePath: path.join(stateDir, 'telegram.json'),
|
|
25
|
+
stateLockPath: path.join(stateDir, '.telegram.lock')
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function isValidTelegramBotToken(value) {
|
|
29
|
+
return TELEGRAM_TOKEN_PATTERN.test(String(value ?? '').trim());
|
|
30
|
+
}
|
|
31
|
+
export async function resolveTelegramBotToken(input = {}) {
|
|
32
|
+
const env = input.env || process.env;
|
|
33
|
+
for (const name of TELEGRAM_TOKEN_ENV_NAMES) {
|
|
34
|
+
const token = String(env[name] || '').trim();
|
|
35
|
+
if (token) {
|
|
36
|
+
if (!isValidTelegramBotToken(token))
|
|
37
|
+
throw new Error('telegram_token_invalid');
|
|
38
|
+
return { token, source: 'env', env_var: name };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const token = await readStoredTelegramToken(input.paths || telegramPrivatePaths(env));
|
|
42
|
+
return token ? { token, source: 'user_secret_file' } : { token: null, source: null };
|
|
43
|
+
}
|
|
44
|
+
export async function readStoredTelegramToken(paths = telegramPrivatePaths()) {
|
|
45
|
+
if (!await validateExistingPrivateDirectories(paths, 'token'))
|
|
46
|
+
return null;
|
|
47
|
+
try {
|
|
48
|
+
const token = (await readPrivateCredentialFile(paths.sksHome, paths.tokenPath, 'telegram_bot_token', { maxBytes: TELEGRAM_TOKEN_MAX_BYTES })).bytes.toString('utf8').trim();
|
|
49
|
+
if (!token)
|
|
50
|
+
return null;
|
|
51
|
+
if (!isValidTelegramBotToken(token))
|
|
52
|
+
throw new Error('telegram_token_invalid');
|
|
53
|
+
return token;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error instanceof PrivateCredentialFileError && error.code === 'missing')
|
|
57
|
+
return null;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export async function storeTelegramToken(tokenInput, options = {}) {
|
|
62
|
+
const token = String(tokenInput ?? '').trim();
|
|
63
|
+
if (!isValidTelegramBotToken(token))
|
|
64
|
+
throw new Error('telegram_token_invalid');
|
|
65
|
+
const paths = resolvePrivatePaths(options);
|
|
66
|
+
await ensureTelegramPrivateDirectories(paths, 'token');
|
|
67
|
+
await writePrivateTextAtomic(paths.sksHome, paths.tokenPath, `${token}\n`, 'telegram_bot_token');
|
|
68
|
+
}
|
|
69
|
+
export function emptyTelegramState() {
|
|
70
|
+
return {
|
|
71
|
+
schema: TELEGRAM_STATE_SCHEMA,
|
|
72
|
+
pairing: null,
|
|
73
|
+
chats: [],
|
|
74
|
+
confirmations: []
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export async function readTelegramState(paths = telegramPrivatePaths()) {
|
|
78
|
+
if (!await validateExistingPrivateDirectories(paths, 'state'))
|
|
79
|
+
return emptyTelegramState();
|
|
80
|
+
let bytes;
|
|
81
|
+
try {
|
|
82
|
+
bytes = (await readPrivateCredentialFile(paths.sksHome, paths.statePath, 'telegram_state', { maxBytes: TELEGRAM_STATE_MAX_BYTES })).bytes;
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof PrivateCredentialFileError && error.code === 'missing')
|
|
86
|
+
return emptyTelegramState();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
if (bytes.length > TELEGRAM_STATE_MAX_BYTES)
|
|
90
|
+
throw new Error('telegram_state_too_large');
|
|
91
|
+
let parsed;
|
|
92
|
+
try {
|
|
93
|
+
parsed = JSON.parse(bytes.toString('utf8'));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new Error('telegram_state_invalid');
|
|
97
|
+
}
|
|
98
|
+
if (!isTelegramState(parsed))
|
|
99
|
+
throw new Error('telegram_state_invalid');
|
|
100
|
+
return parsed;
|
|
101
|
+
}
|
|
102
|
+
export async function writeTelegramState(state, paths = telegramPrivatePaths()) {
|
|
103
|
+
if (!isTelegramState(state))
|
|
104
|
+
throw new Error('telegram_state_invalid');
|
|
105
|
+
await ensureTelegramPrivateDirectories(paths, 'state');
|
|
106
|
+
const serialized = `${JSON.stringify(state, null, 2)}\n`;
|
|
107
|
+
if (Buffer.byteLength(serialized, 'utf8') > TELEGRAM_STATE_MAX_BYTES) {
|
|
108
|
+
throw new Error('telegram_state_too_large');
|
|
109
|
+
}
|
|
110
|
+
await writePrivateTextAtomic(paths.sksHome, paths.statePath, serialized, 'telegram_state');
|
|
111
|
+
}
|
|
112
|
+
export async function updateTelegramState(update, paths = telegramPrivatePaths()) {
|
|
113
|
+
await ensureTelegramPrivateDirectories(paths, 'state');
|
|
114
|
+
return withTelegramStateLock(paths, async () => {
|
|
115
|
+
const next = await update(await readTelegramState(paths));
|
|
116
|
+
await writeTelegramState(next, paths);
|
|
117
|
+
return next;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
export async function issueTelegramPairingCode(options = {}) {
|
|
121
|
+
const now = options.now ?? Date.now();
|
|
122
|
+
const ttlMs = Math.max(30_000, Math.min(options.ttlMs ?? 5 * 60_000, 15 * 60_000));
|
|
123
|
+
const result = {
|
|
124
|
+
code: `${randomInt(100_000, 1_000_000)}-${randomUUID().slice(0, 4).toUpperCase()}`,
|
|
125
|
+
expires_at: new Date(now + ttlMs).toISOString()
|
|
126
|
+
};
|
|
127
|
+
await updateTelegramState((state) => ({
|
|
128
|
+
...state,
|
|
129
|
+
pairing: {
|
|
130
|
+
schema: TELEGRAM_PAIRING_SCHEMA,
|
|
131
|
+
...result,
|
|
132
|
+
used: false
|
|
133
|
+
}
|
|
134
|
+
}), resolvePrivatePaths(options));
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
async function withTelegramStateLock(paths, operation) {
|
|
138
|
+
const identity = await acquireTelegramStateLock(paths);
|
|
139
|
+
try {
|
|
140
|
+
return await operation();
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
const current = await fs.lstat(paths.stateLockPath).catch(() => null);
|
|
144
|
+
if (current?.isDirectory() && !current.isSymbolicLink()
|
|
145
|
+
&& current.dev === identity.dev && current.ino === identity.ino) {
|
|
146
|
+
await fs.rmdir(paths.stateLockPath).catch(() => undefined);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async function acquireTelegramStateLock(paths) {
|
|
151
|
+
assertTestHomeWriteAllowed(paths.stateLockPath);
|
|
152
|
+
for (let attempt = 0; attempt < TELEGRAM_STATE_LOCK_ATTEMPTS; attempt += 1) {
|
|
153
|
+
try {
|
|
154
|
+
await fs.mkdir(paths.stateLockPath, { mode: 0o700 });
|
|
155
|
+
const created = await inspectPrivateDirectory(paths.stateLockPath, 'telegram_state_lock');
|
|
156
|
+
return { dev: created.dev, ino: created.ino };
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error?.code !== 'EEXIST')
|
|
160
|
+
throw error;
|
|
161
|
+
const current = await fs.lstat(paths.stateLockPath).catch(() => null);
|
|
162
|
+
if (!current)
|
|
163
|
+
continue;
|
|
164
|
+
if (current.isSymbolicLink() || !current.isDirectory()) {
|
|
165
|
+
throw new Error('telegram_state_lock_unsafe_type');
|
|
166
|
+
}
|
|
167
|
+
const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
168
|
+
if (expectedUid !== null && current.uid !== expectedUid) {
|
|
169
|
+
throw new Error('telegram_state_lock_owner_mismatch');
|
|
170
|
+
}
|
|
171
|
+
if ((current.mode & 0o777) !== 0o700)
|
|
172
|
+
throw new Error('telegram_state_lock_mode_not_0700');
|
|
173
|
+
}
|
|
174
|
+
if (attempt + 1 < TELEGRAM_STATE_LOCK_ATTEMPTS) {
|
|
175
|
+
await new Promise((resolve) => setTimeout(resolve, TELEGRAM_STATE_LOCK_RETRY_MS));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
throw new Error('telegram_state_lock_timeout');
|
|
179
|
+
}
|
|
180
|
+
async function ensureTelegramPrivateDirectories(paths, target) {
|
|
181
|
+
await ensurePrivateDirectory(paths.sksHome, 'telegram_sks_home', false);
|
|
182
|
+
await ensurePrivateDirectory(target === 'token' ? paths.secretDir : paths.stateDir, `telegram_${target}_directory`);
|
|
183
|
+
}
|
|
184
|
+
async function validateExistingPrivateDirectories(paths, target) {
|
|
185
|
+
if (!await pathExists(paths.sksHome))
|
|
186
|
+
return false;
|
|
187
|
+
await inspectPrivateDirectory(paths.sksHome, 'telegram_sks_home', false);
|
|
188
|
+
const child = target === 'token' ? paths.secretDir : paths.stateDir;
|
|
189
|
+
if (!await pathExists(child))
|
|
190
|
+
return false;
|
|
191
|
+
await inspectPrivateDirectory(child, `telegram_${target}_directory`);
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
async function ensurePrivateDirectory(directory, label, requireMode0700 = true) {
|
|
195
|
+
assertTestHomeWriteAllowed(directory);
|
|
196
|
+
try {
|
|
197
|
+
await fs.mkdir(directory, { mode: 0o700 });
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error?.code !== 'EEXIST')
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
await inspectPrivateDirectory(directory, label, requireMode0700);
|
|
204
|
+
}
|
|
205
|
+
async function inspectPrivateDirectory(directory, label, requireMode0700 = true) {
|
|
206
|
+
const stat = await fs.lstat(directory);
|
|
207
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
208
|
+
throw new Error(`${label}_unsafe_type`);
|
|
209
|
+
if (requireMode0700 && (stat.mode & 0o777) !== 0o700)
|
|
210
|
+
throw new Error(`${label}_mode_not_0700`);
|
|
211
|
+
if (!requireMode0700 && (stat.mode & 0o022) !== 0)
|
|
212
|
+
throw new Error(`${label}_group_or_other_writable`);
|
|
213
|
+
const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
214
|
+
if (expectedUid !== null && stat.uid !== expectedUid)
|
|
215
|
+
throw new Error(`${label}_owner_mismatch`);
|
|
216
|
+
return stat;
|
|
217
|
+
}
|
|
218
|
+
async function pathExists(file) {
|
|
219
|
+
try {
|
|
220
|
+
await fs.lstat(file);
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (error?.code === 'ENOENT')
|
|
225
|
+
return false;
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function resolvePrivatePaths(options) {
|
|
230
|
+
if (options.paths)
|
|
231
|
+
return options.paths;
|
|
232
|
+
if (!options.home)
|
|
233
|
+
return telegramPrivatePaths(options.env || process.env);
|
|
234
|
+
return telegramPrivatePaths({ ...(options.env || process.env), SKS_HOME: undefined, HOME: options.home });
|
|
235
|
+
}
|
|
236
|
+
function isTelegramState(value) {
|
|
237
|
+
if (!isRecord(value)
|
|
238
|
+
|| value.schema !== TELEGRAM_STATE_SCHEMA
|
|
239
|
+
|| !Array.isArray(value.chats)
|
|
240
|
+
|| !Array.isArray(value.confirmations))
|
|
241
|
+
return false;
|
|
242
|
+
if (value.pairing !== null && !isPairing(value.pairing))
|
|
243
|
+
return false;
|
|
244
|
+
return value.chats.every((chat) => isRecord(chat)
|
|
245
|
+
&& Number.isSafeInteger(chat.chat_id)
|
|
246
|
+
&& Number.isSafeInteger(chat.sender_id)
|
|
247
|
+
&& typeof chat.paired_at === 'string')
|
|
248
|
+
&& value.confirmations.every((confirmation) => isRecord(confirmation)
|
|
249
|
+
&& typeof confirmation.nonce === 'string'
|
|
250
|
+
&& Number.isSafeInteger(confirmation.chat_id)
|
|
251
|
+
&& Number.isSafeInteger(confirmation.sender_id)
|
|
252
|
+
&& typeof confirmation.command === 'string'
|
|
253
|
+
&& typeof confirmation.input_json === 'string'
|
|
254
|
+
&& typeof confirmation.expires_at === 'string');
|
|
255
|
+
}
|
|
256
|
+
function isPairing(value) {
|
|
257
|
+
return isRecord(value)
|
|
258
|
+
&& value.schema === TELEGRAM_PAIRING_SCHEMA
|
|
259
|
+
&& typeof value.code === 'string'
|
|
260
|
+
&& typeof value.expires_at === 'string'
|
|
261
|
+
&& typeof value.used === 'boolean';
|
|
262
|
+
}
|
|
263
|
+
function isRecord(value) {
|
|
264
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
265
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
const MAX_RECEIPT_BYTES = 64 * 1024;
|
|
6
|
+
export function telegramLivenessPath(home = process.env.HOME || os.homedir()) {
|
|
7
|
+
return path.join(path.resolve(home), '.codex', 'sks-menubar', 'telegram-liveness.json');
|
|
8
|
+
}
|
|
9
|
+
export function createTelegramLivenessReceipt(input) {
|
|
10
|
+
return {
|
|
11
|
+
schema: 'sks.telegram-liveness.v1',
|
|
12
|
+
generation: input.generation,
|
|
13
|
+
pid: input.pid ?? process.pid,
|
|
14
|
+
running: input.running,
|
|
15
|
+
token_configured: input.tokenConfigured,
|
|
16
|
+
bot_identity_valid: input.botIdentityValid,
|
|
17
|
+
getme_checked_at: input.getMeCheckedAt ?? (input.botIdentityValid ? (input.heartbeatAt ?? new Date().toISOString()) : null),
|
|
18
|
+
getme_latency_ms: input.getMeLatencyMs ?? (input.botIdentityValid ? 0 : null),
|
|
19
|
+
paired_chat_count: Math.max(0, Math.floor(input.pairedChatCount)),
|
|
20
|
+
started_at: input.startedAt,
|
|
21
|
+
heartbeat_at: input.heartbeatAt ?? new Date().toISOString(),
|
|
22
|
+
stale_after_seconds: Math.max(15, Math.min(input.staleAfterSeconds ?? 120, 600)),
|
|
23
|
+
audit_healthy: input.auditHealthy ?? true,
|
|
24
|
+
audit_last_error: input.auditLastError ?? null,
|
|
25
|
+
poller: { ...input.poller }
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export async function writeTelegramLivenessReceipt(file, receipt) {
|
|
29
|
+
const target = path.resolve(file);
|
|
30
|
+
const directory = path.dirname(target);
|
|
31
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
32
|
+
const temporary = path.join(directory, `.${path.basename(target)}.${randomUUID()}.tmp`);
|
|
33
|
+
try {
|
|
34
|
+
await fs.writeFile(temporary, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
35
|
+
await fs.rename(temporary, target);
|
|
36
|
+
await fs.chmod(target, 0o600);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export async function readTelegramLivenessReceipt(file = telegramLivenessPath(), now = Date.now()) {
|
|
43
|
+
const target = path.resolve(file);
|
|
44
|
+
const stat = await fs.lstat(target).catch(() => null);
|
|
45
|
+
if (!stat)
|
|
46
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_missing' };
|
|
47
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
48
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_unsafe_type' };
|
|
49
|
+
if (stat.size <= 0 || stat.size > MAX_RECEIPT_BYTES)
|
|
50
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_invalid_size' };
|
|
51
|
+
if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {
|
|
52
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_insecure_mode' };
|
|
53
|
+
}
|
|
54
|
+
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
|
|
55
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_wrong_owner' };
|
|
56
|
+
}
|
|
57
|
+
let parsed;
|
|
58
|
+
try {
|
|
59
|
+
parsed = JSON.parse(await fs.readFile(target, 'utf8'));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_invalid_json' };
|
|
63
|
+
}
|
|
64
|
+
if (!isTelegramLivenessReceipt(parsed)) {
|
|
65
|
+
return { ok: false, receipt: null, blocker: 'telegram_liveness_invalid_schema' };
|
|
66
|
+
}
|
|
67
|
+
const heartbeat = Date.parse(parsed.heartbeat_at);
|
|
68
|
+
const ageMs = Number.isFinite(heartbeat) ? Math.max(0, now - heartbeat) : Number.POSITIVE_INFINITY;
|
|
69
|
+
return {
|
|
70
|
+
ok: true,
|
|
71
|
+
receipt: parsed,
|
|
72
|
+
stale: ageMs > parsed.stale_after_seconds * 1_000,
|
|
73
|
+
age_ms: ageMs
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function isTelegramLivenessReceipt(value) {
|
|
77
|
+
if (!value || typeof value !== 'object')
|
|
78
|
+
return false;
|
|
79
|
+
const row = value;
|
|
80
|
+
return row.schema === 'sks.telegram-liveness.v1'
|
|
81
|
+
&& typeof row.generation === 'string' && row.generation.length >= 8 && row.generation.length <= 128
|
|
82
|
+
&& Number.isSafeInteger(row.pid) && Number(row.pid) > 0
|
|
83
|
+
&& typeof row.running === 'boolean'
|
|
84
|
+
&& typeof row.token_configured === 'boolean'
|
|
85
|
+
&& typeof row.bot_identity_valid === 'boolean'
|
|
86
|
+
&& nullableIso(row.getme_checked_at)
|
|
87
|
+
&& (row.getme_latency_ms === null || (Number.isFinite(row.getme_latency_ms) && Number(row.getme_latency_ms) >= 0))
|
|
88
|
+
&& Number.isSafeInteger(row.paired_chat_count) && Number(row.paired_chat_count) >= 0
|
|
89
|
+
&& typeof row.started_at === 'string' && Number.isFinite(Date.parse(row.started_at))
|
|
90
|
+
&& typeof row.heartbeat_at === 'string' && Number.isFinite(Date.parse(row.heartbeat_at))
|
|
91
|
+
&& Number.isFinite(row.stale_after_seconds) && Number(row.stale_after_seconds) >= 15
|
|
92
|
+
&& (row.audit_healthy === undefined || typeof row.audit_healthy === 'boolean')
|
|
93
|
+
&& (row.audit_last_error === undefined || row.audit_last_error === null || typeof row.audit_last_error === 'string')
|
|
94
|
+
&& isPollSnapshot(row.poller);
|
|
95
|
+
}
|
|
96
|
+
function isPollSnapshot(value) {
|
|
97
|
+
if (!value || typeof value !== 'object')
|
|
98
|
+
return false;
|
|
99
|
+
const row = value;
|
|
100
|
+
return row.schema === 'sks.telegram-poller-state.v1'
|
|
101
|
+
&& typeof row.running === 'boolean'
|
|
102
|
+
&& Number.isSafeInteger(row.offset) && Number(row.offset) >= 0
|
|
103
|
+
&& Number.isSafeInteger(row.consecutive_failures) && Number(row.consecutive_failures) >= 0
|
|
104
|
+
&& nullableIso(row.last_poll_at) && nullableIso(row.last_success_at) && nullableIso(row.last_update_at)
|
|
105
|
+
&& (row.last_error === null || typeof row.last_error === 'string');
|
|
106
|
+
}
|
|
107
|
+
function nullableIso(value) {
|
|
108
|
+
return value === null || (typeof value === 'string' && Number.isFinite(Date.parse(value)));
|
|
109
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { TelegramApiError } from './client.js';
|
|
2
|
+
import { redactTelegramError } from './redaction.js';
|
|
3
|
+
export class TelegramPoller {
|
|
4
|
+
options;
|
|
5
|
+
controller = null;
|
|
6
|
+
state = {
|
|
7
|
+
schema: 'sks.telegram-poller-state.v1', running: false, offset: 0,
|
|
8
|
+
consecutive_failures: 0, last_poll_at: null, last_success_at: null,
|
|
9
|
+
last_update_at: null, last_error: null
|
|
10
|
+
};
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.options = {
|
|
13
|
+
...options,
|
|
14
|
+
timeoutSeconds: Math.max(1, Math.min(options.timeoutSeconds ?? 30, 50)),
|
|
15
|
+
minBackoffMs: Math.max(100, options.minBackoffMs ?? 500),
|
|
16
|
+
maxBackoffMs: Math.max(options.minBackoffMs ?? 500, Math.min(options.maxBackoffMs ?? 30_000, 60_000)),
|
|
17
|
+
initialOffset: Number.isSafeInteger(options.initialOffset) && Number(options.initialOffset) >= 0
|
|
18
|
+
? Number(options.initialOffset)
|
|
19
|
+
: 0,
|
|
20
|
+
sleep: options.sleep ?? abortableSleep
|
|
21
|
+
};
|
|
22
|
+
this.state = { ...this.state, offset: this.options.initialOffset };
|
|
23
|
+
}
|
|
24
|
+
snapshot() { return { ...this.state }; }
|
|
25
|
+
start() {
|
|
26
|
+
if (this.controller)
|
|
27
|
+
throw new Error('telegram_poller_already_running');
|
|
28
|
+
this.controller = new AbortController();
|
|
29
|
+
this.state = { ...this.state, running: true, last_error: null };
|
|
30
|
+
return this.run(this.controller.signal).finally(() => {
|
|
31
|
+
this.controller = null;
|
|
32
|
+
this.state = { ...this.state, running: false };
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
stop() { this.controller?.abort(); }
|
|
36
|
+
async run(signal) {
|
|
37
|
+
while (!signal.aborted) {
|
|
38
|
+
this.state = { ...this.state, last_poll_at: new Date().toISOString() };
|
|
39
|
+
try {
|
|
40
|
+
const updates = await this.options.client.getUpdates({
|
|
41
|
+
offset: this.state.offset,
|
|
42
|
+
timeoutSeconds: this.options.timeoutSeconds,
|
|
43
|
+
allowedUpdates: ['message'],
|
|
44
|
+
signal
|
|
45
|
+
});
|
|
46
|
+
for (const update of [...updates].sort((a, b) => a.update_id - b.update_id)) {
|
|
47
|
+
if (signal.aborted)
|
|
48
|
+
return;
|
|
49
|
+
if (!Number.isSafeInteger(update.update_id) || update.update_id < this.state.offset)
|
|
50
|
+
continue;
|
|
51
|
+
const claimed = {
|
|
52
|
+
...this.state,
|
|
53
|
+
offset: Math.max(this.state.offset, update.update_id + 1),
|
|
54
|
+
last_update_at: new Date().toISOString()
|
|
55
|
+
};
|
|
56
|
+
if (this.options.checkpoint)
|
|
57
|
+
await this.options.checkpoint(claimed);
|
|
58
|
+
this.state = claimed;
|
|
59
|
+
await this.options.handleUpdate(update);
|
|
60
|
+
}
|
|
61
|
+
this.state = {
|
|
62
|
+
...this.state,
|
|
63
|
+
consecutive_failures: 0,
|
|
64
|
+
last_success_at: new Date().toISOString(),
|
|
65
|
+
last_error: null
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (signal.aborted)
|
|
70
|
+
return;
|
|
71
|
+
const failures = this.state.consecutive_failures + 1;
|
|
72
|
+
this.state = { ...this.state, consecutive_failures: failures, last_error: redactTelegramError(error) };
|
|
73
|
+
const retryAfter = error instanceof TelegramApiError ? error.retryAfterSeconds : null;
|
|
74
|
+
const exponential = Math.min(this.options.maxBackoffMs, this.options.minBackoffMs * (2 ** Math.min(failures - 1, 8)));
|
|
75
|
+
const delay = retryAfter == null ? exponential : Math.min(this.options.maxBackoffMs, Math.max(exponential, retryAfter * 1_000));
|
|
76
|
+
await this.options.sleep(delay, signal).catch(() => undefined);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function abortableSleep(ms, signal) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
if (signal.aborted)
|
|
84
|
+
return reject(signal.reason);
|
|
85
|
+
const timer = setTimeout(done, ms);
|
|
86
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
87
|
+
function done() { signal.removeEventListener('abort', aborted); resolve(); }
|
|
88
|
+
function aborted() { clearTimeout(timer); reject(signal.reason); }
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const BOT_URL = /\/bot[^/\s]+\//gi;
|
|
3
|
+
const TOKEN_ASSIGNMENT = /((?:bot[_-]?token|token)\s*[:=]\s*)[^\s,"'}]+/gi;
|
|
4
|
+
export function redactTelegramError(value, token) {
|
|
5
|
+
let text = value instanceof Error ? value.message : String(value ?? 'telegram_error');
|
|
6
|
+
if (token)
|
|
7
|
+
text = text.split(token).join('[redacted]');
|
|
8
|
+
return text
|
|
9
|
+
.replace(BOT_URL, '/bot[redacted]/')
|
|
10
|
+
.replace(TOKEN_ASSIGNMENT, '$1[redacted]')
|
|
11
|
+
.slice(0, 512);
|
|
12
|
+
}
|
|
13
|
+
export function redactedChatActor(chatId, senderId = chatId) {
|
|
14
|
+
return `actor:${createHash('sha256').update(`${chatId}:${senderId}`).digest('hex').slice(0, 12)}`;
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SYSTEM_TELEGRAM_CLOCK = { now: () => Date.now() };
|