@uniquedivine/tg-sai 0.0.4 → 0.1.0
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 +41 -0
- package/RUNBOOK.md +204 -24
- package/actionExecutor.ts +183 -131
- package/adminAudit.ts +60 -60
- package/captureProvisioningGolden.ts +98 -0
- package/cfg.ts +12 -1
- package/custodyWorker.ts +501 -0
- package/custodyWorkerCli.ts +58 -0
- package/health.ts +31 -50
- package/main.ts +860 -214
- package/mtcuteAdapter.ts +266 -10
- package/ops.ts +12 -0
- package/package.json +14 -5
- package/profiles.ts +157 -32
- package/provisioning.ts +805 -0
- package/provisioningCli.ts +147 -0
- package/provisioningCloud.ts +214 -0
- package/provisioningGoldens.ts +70 -0
- package/provisioningRuntime.ts +417 -0
- package/runtimeAssets.d.ts +4 -0
- package/runtimeHealth.ts +132 -0
- package/runtimeHealthCli.ts +48 -0
- package/session_string_generator.py +36 -24
- package/state/cli.ts +641 -0
- package/state/db.ts +72 -0
- package/state/guard.ts +270 -0
- package/state/holds.ts +381 -0
- package/state/migrations/0001-flood-hold.sql +16 -0
- package/telegramRuntime.ts +25 -0
- package/telemetry/cli.ts +698 -0
- package/telemetry/db.ts +471 -0
- package/telemetry/middleware.ts +475 -0
- package/telemetry/migrations/0001-event.sql +33 -0
- package/telemetry/migrations/0002-event-job-index.sql +2 -0
- package/telemetry/migrations/0003-event-log.sql +10 -0
- package/telemetry/queries.ts +475 -0
- package/telemetry/run.ts +491 -0
- package/telemetry/sqlAssets.d.ts +4 -0
- package/telemetry/summarize.ts +219 -0
package/state/cli.ts
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tg-sai holds`: inspect and override the flood holds in `state.db`.
|
|
3
|
+
* Writes are dry runs unless `--run` is given. `set` records a `manual`
|
|
4
|
+
* hold with MAX semantics, so it can extend a hold but never shorten it;
|
|
5
|
+
* `clear` is the only way to end a hold early, and needs `--force` while the
|
|
6
|
+
* hold is active. `--run` refuses a `state.db` owned by another user (the
|
|
7
|
+
* worker's file must stay writable by the worker), and each write leaves a
|
|
8
|
+
* `holds.set` / `holds.clear` row in the telemetry DB.
|
|
9
|
+
*/
|
|
10
|
+
import { Database } from "bun:sqlite"
|
|
11
|
+
import type { Command } from "commander"
|
|
12
|
+
import { existsSync, readFileSync, statSync } from "node:fs"
|
|
13
|
+
import { dirname } from "node:path"
|
|
14
|
+
|
|
15
|
+
import type { ProfileStoreEnv } from "../profiles"
|
|
16
|
+
import { log as telemetryLog } from "../telemetry/run"
|
|
17
|
+
import type { LogFields } from "../telemetry/run"
|
|
18
|
+
import {
|
|
19
|
+
isoTime,
|
|
20
|
+
parseAccountId,
|
|
21
|
+
parsePositiveInt,
|
|
22
|
+
toonObject,
|
|
23
|
+
toonTable,
|
|
24
|
+
type Cell,
|
|
25
|
+
} from "../telemetry/cli"
|
|
26
|
+
import { openStateDb, stateDbPath } from "./db"
|
|
27
|
+
import {
|
|
28
|
+
HoldStore,
|
|
29
|
+
MAX_HOLD_MS,
|
|
30
|
+
holdUntil,
|
|
31
|
+
remainingSeconds,
|
|
32
|
+
type FloodHold,
|
|
33
|
+
type HoldGroup,
|
|
34
|
+
} from "./holds"
|
|
35
|
+
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
// Option parsing
|
|
38
|
+
|
|
39
|
+
const NAMED_GROUPS: readonly HoldGroup[] = [
|
|
40
|
+
"invite",
|
|
41
|
+
"create",
|
|
42
|
+
"resolve",
|
|
43
|
+
"send",
|
|
44
|
+
]
|
|
45
|
+
const METHOD_NAME = /^[A-Za-z][\w]*(?:\.[A-Za-z][\w]*)+$/
|
|
46
|
+
const REASON_CODE = /^[A-Za-z0-9_.:-]{1,64}$/
|
|
47
|
+
|
|
48
|
+
/** Parses `invite|create|resolve|send|method:<tl.method>`. */
|
|
49
|
+
export function parseHoldGroup(value: string): HoldGroup {
|
|
50
|
+
const trimmed = value.trim()
|
|
51
|
+
if ((NAMED_GROUPS as readonly string[]).includes(trimmed)) {
|
|
52
|
+
return trimmed as HoldGroup
|
|
53
|
+
}
|
|
54
|
+
if (trimmed.startsWith("method:")) {
|
|
55
|
+
const method = trimmed.slice("method:".length)
|
|
56
|
+
if (METHOD_NAME.test(method)) return `method:${method}`
|
|
57
|
+
}
|
|
58
|
+
throw new Error(
|
|
59
|
+
`--group must be invite, create, resolve, send, or method:<name> ` +
|
|
60
|
+
`(e.g. method:users.getFullUser), got "${value}"`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Parses an ISO 8601 time with a zone; must be after `nowMs`. */
|
|
65
|
+
export function parseUntil(value: string, nowMs: number): number {
|
|
66
|
+
const hasZone = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value.trim())
|
|
67
|
+
const ms = Date.parse(value)
|
|
68
|
+
if (!hasZone || !Number.isFinite(ms)) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`--until must be an ISO 8601 time with a zone, ` +
|
|
71
|
+
`e.g. 2026-11-07T12:00:00Z, got "${value}"`,
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
if (ms <= nowMs) {
|
|
75
|
+
throw new Error(`--until must be in the future, got "${value}"`)
|
|
76
|
+
}
|
|
77
|
+
return ms
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function parseReasonCode(value: string): string {
|
|
81
|
+
if (!REASON_CODE.test(value)) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`--reason-code must be 1-64 of [A-Za-z0-9_.:-], got "${value}"`,
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
return value
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Default `method` for a manual hold: the group's own method, or `manual`. */
|
|
90
|
+
export function defaultMethod(grp: HoldGroup): string {
|
|
91
|
+
return grp.startsWith("method:") ? grp.slice("method:".length) : "manual"
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `request_id` for a manual hold: `manual:<code>`, or null without one. */
|
|
95
|
+
export function manualRequestId(reasonCode: string | undefined): string | null {
|
|
96
|
+
return reasonCode === undefined ? null : `manual:${reasonCode}`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// Projections
|
|
101
|
+
|
|
102
|
+
export const HOLD_FIELDS = [
|
|
103
|
+
"account",
|
|
104
|
+
"group",
|
|
105
|
+
"until",
|
|
106
|
+
"remaining_s",
|
|
107
|
+
"method",
|
|
108
|
+
"wait_s",
|
|
109
|
+
"source",
|
|
110
|
+
] as const
|
|
111
|
+
|
|
112
|
+
/** One hold as printed by `holds list`; `remaining_s` is 0 once ended. */
|
|
113
|
+
export function holdProjection(
|
|
114
|
+
hold: FloodHold,
|
|
115
|
+
nowMs: number,
|
|
116
|
+
): Record<string, Cell> {
|
|
117
|
+
return {
|
|
118
|
+
account: hold.accountId,
|
|
119
|
+
group: hold.grp,
|
|
120
|
+
until: isoTime(hold.untilMs),
|
|
121
|
+
remaining_s:
|
|
122
|
+
hold.untilMs > nowMs ? remainingSeconds(hold.untilMs, nowMs) : 0,
|
|
123
|
+
method: hold.method,
|
|
124
|
+
wait_s: hold.waitS,
|
|
125
|
+
source: hold.source,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface HoldRow {
|
|
130
|
+
account_id: string
|
|
131
|
+
grp: string
|
|
132
|
+
until_ms: number
|
|
133
|
+
method: string
|
|
134
|
+
wait_s: number | null
|
|
135
|
+
source: string
|
|
136
|
+
request_id: string | null
|
|
137
|
+
created_ms: number
|
|
138
|
+
updated_ms: number
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Every stored hold, ended ones included, latest end first. */
|
|
142
|
+
export function allHolds(db: Database, accountId?: string): FloodHold[] {
|
|
143
|
+
const rows =
|
|
144
|
+
accountId === undefined
|
|
145
|
+
? db
|
|
146
|
+
.query<HoldRow, []>(
|
|
147
|
+
"SELECT * FROM flood_hold ORDER BY until_ms DESC, account_id, grp",
|
|
148
|
+
)
|
|
149
|
+
.all()
|
|
150
|
+
: db
|
|
151
|
+
.query<HoldRow, [string]>(
|
|
152
|
+
"SELECT * FROM flood_hold WHERE account_id = ? " +
|
|
153
|
+
"ORDER BY until_ms DESC, grp",
|
|
154
|
+
)
|
|
155
|
+
.all(accountId)
|
|
156
|
+
return rows.map((row) => ({
|
|
157
|
+
accountId: row.account_id,
|
|
158
|
+
grp: row.grp as HoldGroup,
|
|
159
|
+
untilMs: row.until_ms,
|
|
160
|
+
method: row.method,
|
|
161
|
+
waitS: row.wait_s,
|
|
162
|
+
source: row.source as FloodHold["source"],
|
|
163
|
+
requestId: row.request_id,
|
|
164
|
+
createdMs: row.created_ms,
|
|
165
|
+
updatedMs: row.updated_ms,
|
|
166
|
+
}))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The stored hold on `(accountId, grp)`, ended or not. */
|
|
170
|
+
export function storedHold(
|
|
171
|
+
db: Database,
|
|
172
|
+
accountId: string,
|
|
173
|
+
grp: HoldGroup,
|
|
174
|
+
): FloodHold | null {
|
|
175
|
+
return allHolds(db, accountId).find((hold) => hold.grp === grp) ?? null
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* What `recordHold` would store, given the current row: the later end
|
|
180
|
+
* time wins, capped at one year from `nowMs`.
|
|
181
|
+
*/
|
|
182
|
+
export function plannedUntil(
|
|
183
|
+
requestedUntilMs: number,
|
|
184
|
+
existing: FloodHold | null,
|
|
185
|
+
nowMs: number,
|
|
186
|
+
): { untilMs: number; extends: boolean } {
|
|
187
|
+
const capped = Math.min(Math.round(requestedUntilMs), nowMs + MAX_HOLD_MS)
|
|
188
|
+
if (existing && existing.untilMs >= capped) {
|
|
189
|
+
return { untilMs: existing.untilMs, extends: false }
|
|
190
|
+
}
|
|
191
|
+
return { untilMs: capped, extends: true }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ---------------------------------------------------------------------------
|
|
195
|
+
// Command wiring
|
|
196
|
+
|
|
197
|
+
/** Writes one info row to the telemetry DB; never throws. */
|
|
198
|
+
export type HoldsLogFn = (
|
|
199
|
+
event: "holds.set" | "holds.clear",
|
|
200
|
+
msg: string,
|
|
201
|
+
attrs: Record<string, unknown>,
|
|
202
|
+
fields: LogFields,
|
|
203
|
+
) => void
|
|
204
|
+
|
|
205
|
+
export interface HoldsCliContext {
|
|
206
|
+
env?: ProfileStoreEnv
|
|
207
|
+
/** Overrides `stateDbPath(env)`. */
|
|
208
|
+
dbPath?: string
|
|
209
|
+
now?: () => number
|
|
210
|
+
stdout?: (text: string) => void
|
|
211
|
+
stderr?: (text: string) => void
|
|
212
|
+
/** Current process uid; default `process.getuid()`. */
|
|
213
|
+
getuid?: () => number | undefined
|
|
214
|
+
/** Default: the telemetry `log` API with `env`. */
|
|
215
|
+
log?: HoldsLogFn
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
interface ResolvedContext {
|
|
219
|
+
path: string
|
|
220
|
+
now: () => number
|
|
221
|
+
out: (text: string) => void
|
|
222
|
+
err: (text: string) => void
|
|
223
|
+
getuid: () => number | undefined
|
|
224
|
+
log: HoldsLogFn
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function resolveContext(ctx: HoldsCliContext): ResolvedContext {
|
|
228
|
+
const env = ctx.env ?? process.env
|
|
229
|
+
return {
|
|
230
|
+
path: ctx.dbPath ?? stateDbPath(env),
|
|
231
|
+
now: ctx.now ?? Date.now,
|
|
232
|
+
out: ctx.stdout ?? ((text) => process.stdout.write(`${text}\n`)),
|
|
233
|
+
err: ctx.stderr ?? ((text) => process.stderr.write(`${text}\n`)),
|
|
234
|
+
getuid: ctx.getuid ?? (() => process.getuid?.()),
|
|
235
|
+
log:
|
|
236
|
+
ctx.log ??
|
|
237
|
+
((event, msg, attrs, fields) =>
|
|
238
|
+
telemetryLog("info", event, msg, attrs, fields, { env })),
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Login name of `uid` from `/etc/passwd`; `null` when not listed. */
|
|
243
|
+
export function userNameOf(
|
|
244
|
+
uid: number,
|
|
245
|
+
passwd: () => string = () => readFileSync("/etc/passwd", "utf8"),
|
|
246
|
+
): string | null {
|
|
247
|
+
try {
|
|
248
|
+
for (const line of passwd().split("\n")) {
|
|
249
|
+
const fields = line.split(":")
|
|
250
|
+
if (fields.length > 2 && Number(fields[2]) === uid && fields[0]) {
|
|
251
|
+
return fields[0]
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
} catch {
|
|
255
|
+
// No passwd file; the caller falls back to the uid.
|
|
256
|
+
}
|
|
257
|
+
return null
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Refusal text when `path` exists and is owned by a uid other than
|
|
262
|
+
* `currentUid`: writing as another user would leave holds in a file (and
|
|
263
|
+
* `-wal`/`-shm`) the owner's process may not read. `null` otherwise.
|
|
264
|
+
*/
|
|
265
|
+
export function foreignOwnerRefusal(
|
|
266
|
+
path: string,
|
|
267
|
+
currentUid: number | undefined,
|
|
268
|
+
subcommand: "set" | "clear",
|
|
269
|
+
nameOf: (uid: number) => string | null = (uid) => userNameOf(uid),
|
|
270
|
+
): string | null {
|
|
271
|
+
if (currentUid === undefined || !existsSync(path)) return null
|
|
272
|
+
const ownerUid = statSync(path).uid
|
|
273
|
+
if (ownerUid === currentUid) return null
|
|
274
|
+
const name = nameOf(ownerUid)
|
|
275
|
+
// Quoted: an unquoted # starts a shell comment.
|
|
276
|
+
const owner = name ?? `'#${ownerUid}'`
|
|
277
|
+
const dir = dirname(path)
|
|
278
|
+
return (
|
|
279
|
+
`${path} is owned by uid ${ownerUid}` +
|
|
280
|
+
`${name ? ` (${name})` : ""}, not uid ${currentUid}. ` +
|
|
281
|
+
`Run as the owner, e.g.: sudo -u ${owner} env TG_SAI_DIR=${dir} ` +
|
|
282
|
+
`HOME=${dir} tg-sai holds ${subcommand} ... --run`
|
|
283
|
+
)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Attributes of a `holds.*` row. Telemetry stores strings as their length,
|
|
288
|
+
* so the group is a `{ _ }` name, which is kept, and times are epoch ms.
|
|
289
|
+
*/
|
|
290
|
+
function holdLogAttrs(
|
|
291
|
+
accountId: string,
|
|
292
|
+
grp: HoldGroup,
|
|
293
|
+
untilMs: number | null,
|
|
294
|
+
): Record<string, unknown> {
|
|
295
|
+
return { account: Number(accountId), group: { _: grp }, until: untilMs }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Runs `fn` on a read-only handle, or on `null` when the database does not
|
|
300
|
+
* exist yet (no hold has ever been recorded). Never creates the file.
|
|
301
|
+
*/
|
|
302
|
+
function withReadOnlyDb<T>(
|
|
303
|
+
ctx: ResolvedContext,
|
|
304
|
+
fn: (db: Database | null) => T,
|
|
305
|
+
): T {
|
|
306
|
+
if (!existsSync(ctx.path)) return fn(null)
|
|
307
|
+
const db = new Database(ctx.path, { readonly: true, strict: true })
|
|
308
|
+
try {
|
|
309
|
+
db.run("PRAGMA busy_timeout = 5000")
|
|
310
|
+
return fn(db)
|
|
311
|
+
} finally {
|
|
312
|
+
db.close()
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Opens the database for writing, creating and migrating it if needed. */
|
|
317
|
+
function withWritableStore<T>(
|
|
318
|
+
ctx: ResolvedContext,
|
|
319
|
+
fn: (store: HoldStore, db: Database) => T,
|
|
320
|
+
): T {
|
|
321
|
+
const db = openStateDb(ctx.path)
|
|
322
|
+
const store = HoldStore.fromDb(db)
|
|
323
|
+
try {
|
|
324
|
+
return fn(store, db)
|
|
325
|
+
} finally {
|
|
326
|
+
store.close()
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** True when no option of `command` was given on the command line. */
|
|
331
|
+
function calledBare(command: Command): boolean {
|
|
332
|
+
return command.options.every(
|
|
333
|
+
(option) => command.getOptionValueSource(option.attributeName()) !== "cli",
|
|
334
|
+
)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function printHelp(command: Command): void {
|
|
338
|
+
command.outputHelp()
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Throws a commander usage error so the CLI exits 1 with the message. */
|
|
342
|
+
function usageError(command: Command, error: unknown): never {
|
|
343
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
344
|
+
command.error(`error: ${message}`, { exitCode: 1, code: "tg-sai.holds" })
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function parseOrFail<T>(command: Command, fn: () => T): T {
|
|
348
|
+
try {
|
|
349
|
+
return fn()
|
|
350
|
+
} catch (error) {
|
|
351
|
+
usageError(command, error)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
interface ListCliOptions {
|
|
356
|
+
account?: string
|
|
357
|
+
all?: boolean
|
|
358
|
+
json?: boolean
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
interface SetCliOptions {
|
|
362
|
+
account?: string
|
|
363
|
+
group?: string
|
|
364
|
+
until?: string
|
|
365
|
+
waitS?: string
|
|
366
|
+
method?: string
|
|
367
|
+
reasonCode?: string
|
|
368
|
+
run?: boolean
|
|
369
|
+
json?: boolean
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
interface ClearCliOptions {
|
|
373
|
+
account?: string
|
|
374
|
+
group?: string
|
|
375
|
+
run?: boolean
|
|
376
|
+
force?: boolean
|
|
377
|
+
json?: boolean
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function requireOption(
|
|
381
|
+
command: Command,
|
|
382
|
+
value: string | undefined,
|
|
383
|
+
flag: string,
|
|
384
|
+
): string {
|
|
385
|
+
if (value === undefined) usageError(command, `${flag} is required`)
|
|
386
|
+
return value
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Registers `tg-sai holds` and its subcommands on `program`. `context` is
|
|
391
|
+
* for tests; production uses the environment, clock, and stdio.
|
|
392
|
+
*/
|
|
393
|
+
export function registerHoldsCommand(
|
|
394
|
+
program: Command,
|
|
395
|
+
context: HoldsCliContext = {},
|
|
396
|
+
): Command {
|
|
397
|
+
const ctx = resolveContext(context)
|
|
398
|
+
if (context.stdout || context.stderr) {
|
|
399
|
+
program.configureOutput({
|
|
400
|
+
writeOut: (text) => ctx.out(text.replace(/\n$/, "")),
|
|
401
|
+
writeErr: (text) => ctx.err(text.replace(/\n$/, "")),
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const holds = program
|
|
406
|
+
.command("holds")
|
|
407
|
+
.description("Inspect and override saved Telegram flood holds (state.db)")
|
|
408
|
+
.addHelpText(
|
|
409
|
+
"after",
|
|
410
|
+
`
|
|
411
|
+
Examples:
|
|
412
|
+
tg-sai holds list
|
|
413
|
+
tg-sai holds list --account 8274304175 --all --json
|
|
414
|
+
tg-sai holds set --account 8274304175 --group invite --wait-s 3600
|
|
415
|
+
tg-sai holds set --account 8274304175 --group send \\
|
|
416
|
+
--until 2026-11-07T12:00:00Z --reason-code ops_pause --run
|
|
417
|
+
tg-sai holds clear --account 8274304175 --group invite --run --force
|
|
418
|
+
|
|
419
|
+
set and clear are dry runs without --run. set can only extend a hold.
|
|
420
|
+
clear needs --force while the hold is active. Run as the user that owns
|
|
421
|
+
state.db (on the VM, sudo -u sai-custody-worker; see RUNBOOK.md).
|
|
422
|
+
Groups: invite, create, resolve, send, method:<tl.method>.
|
|
423
|
+
`,
|
|
424
|
+
)
|
|
425
|
+
.action(() => {
|
|
426
|
+
printHelp(holds)
|
|
427
|
+
})
|
|
428
|
+
|
|
429
|
+
holds
|
|
430
|
+
.command("list")
|
|
431
|
+
.description("Active holds, latest end first (all stored with --all)")
|
|
432
|
+
.option("--account <id>", "Only this Telegram account id")
|
|
433
|
+
.option("--all", "Include holds that have already ended")
|
|
434
|
+
.option("--json", "Print JSON")
|
|
435
|
+
.action((options: ListCliOptions, command: Command) => {
|
|
436
|
+
const accountId =
|
|
437
|
+
options.account === undefined
|
|
438
|
+
? undefined
|
|
439
|
+
: String(parseOrFail(command, () => parseAccountId(options.account!)))
|
|
440
|
+
const nowMs = ctx.now()
|
|
441
|
+
const rows = withReadOnlyDb(ctx, (db) => {
|
|
442
|
+
if (!db) return []
|
|
443
|
+
const found = options.all
|
|
444
|
+
? allHolds(db, accountId)
|
|
445
|
+
: HoldStore.fromDb(db).activeHolds(accountId, nowMs)
|
|
446
|
+
return found.map((hold) => holdProjection(hold, nowMs))
|
|
447
|
+
})
|
|
448
|
+
if (options.json) ctx.out(JSON.stringify(rows, null, 2))
|
|
449
|
+
else ctx.out(toonTable("holds", HOLD_FIELDS, rows))
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
holds
|
|
453
|
+
.command("set")
|
|
454
|
+
.description("Record a manual hold; extends a hold, never shortens one")
|
|
455
|
+
.option("--account <id>", "Telegram account id")
|
|
456
|
+
.option(
|
|
457
|
+
"--group <group>",
|
|
458
|
+
"invite, create, resolve, send, or method:<tl.method>",
|
|
459
|
+
)
|
|
460
|
+
.option("--until <iso>", "End time, ISO 8601 with zone (UTC recommended)")
|
|
461
|
+
.option("--wait-s <n>", "Hold for N seconds plus the usual margin")
|
|
462
|
+
.option("--method <name>", "Method to record (default: from the group)")
|
|
463
|
+
.option("--reason-code <code>", "Saved as request_id manual:<code>")
|
|
464
|
+
.option("--run", "Write the hold (default is a dry run)")
|
|
465
|
+
.option("--json", "Print JSON")
|
|
466
|
+
.addHelpText(
|
|
467
|
+
"after",
|
|
468
|
+
`
|
|
469
|
+
Exactly one of --until or --wait-s. Without --run nothing is written.
|
|
470
|
+
`,
|
|
471
|
+
)
|
|
472
|
+
.action((options: SetCliOptions, command: Command) => {
|
|
473
|
+
if (calledBare(command)) {
|
|
474
|
+
printHelp(command)
|
|
475
|
+
return
|
|
476
|
+
}
|
|
477
|
+
const nowMs = ctx.now()
|
|
478
|
+
const account = requireOption(command, options.account, "--account")
|
|
479
|
+
const group = requireOption(command, options.group, "--group")
|
|
480
|
+
const accountId = String(
|
|
481
|
+
parseOrFail(command, () => parseAccountId(account)),
|
|
482
|
+
)
|
|
483
|
+
const grp = parseOrFail(command, () => parseHoldGroup(group))
|
|
484
|
+
if ((options.until === undefined) === (options.waitS === undefined)) {
|
|
485
|
+
usageError(command, "give exactly one of --until or --wait-s")
|
|
486
|
+
}
|
|
487
|
+
const waitS =
|
|
488
|
+
options.waitS === undefined
|
|
489
|
+
? null
|
|
490
|
+
: parseOrFail(command, () =>
|
|
491
|
+
parsePositiveInt(options.waitS!, "--wait-s"),
|
|
492
|
+
)
|
|
493
|
+
const requestedUntilMs =
|
|
494
|
+
options.until === undefined
|
|
495
|
+
? holdUntil(nowMs, waitS ?? 0)
|
|
496
|
+
: parseOrFail(command, () => parseUntil(options.until!, nowMs))
|
|
497
|
+
const method = options.method ?? defaultMethod(grp)
|
|
498
|
+
const requestId = manualRequestId(
|
|
499
|
+
options.reasonCode === undefined
|
|
500
|
+
? undefined
|
|
501
|
+
: parseOrFail(command, () => parseReasonCode(options.reasonCode!)),
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
const write = (store: HoldStore | null, db: Database | null) => {
|
|
505
|
+
const existing = db ? storedHold(db, accountId, grp) : null
|
|
506
|
+
const active = existing && existing.untilMs > nowMs ? existing : null
|
|
507
|
+
const plan = plannedUntil(requestedUntilMs, active, nowMs)
|
|
508
|
+
const stored = store
|
|
509
|
+
? store.recordHold({
|
|
510
|
+
accountId,
|
|
511
|
+
grp,
|
|
512
|
+
method,
|
|
513
|
+
source: "manual",
|
|
514
|
+
waitS,
|
|
515
|
+
untilMs: requestedUntilMs,
|
|
516
|
+
requestId,
|
|
517
|
+
nowMs,
|
|
518
|
+
})
|
|
519
|
+
: null
|
|
520
|
+
const untilMs = stored?.untilMs ?? plan.untilMs
|
|
521
|
+
return {
|
|
522
|
+
mode: store ? "run" : "dry_run",
|
|
523
|
+
path: ctx.path,
|
|
524
|
+
account: accountId,
|
|
525
|
+
group: grp,
|
|
526
|
+
requested_until: isoTime(requestedUntilMs),
|
|
527
|
+
until: isoTime(untilMs),
|
|
528
|
+
remaining_s: remainingSeconds(untilMs, nowMs),
|
|
529
|
+
method: plan.extends ? method : (active?.method ?? method),
|
|
530
|
+
wait_s: plan.extends ? waitS : (active?.waitS ?? null),
|
|
531
|
+
source: plan.extends ? "manual" : (active?.source ?? "manual"),
|
|
532
|
+
request_id: plan.extends ? requestId : (active?.requestId ?? null),
|
|
533
|
+
previous_until: isoTime(active?.untilMs),
|
|
534
|
+
changed: plan.extends,
|
|
535
|
+
} satisfies Record<string, Cell>
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (options.run) {
|
|
539
|
+
const refusal = foreignOwnerRefusal(ctx.path, ctx.getuid(), "set")
|
|
540
|
+
if (refusal) usageError(command, refusal)
|
|
541
|
+
}
|
|
542
|
+
const result = options.run
|
|
543
|
+
? withWritableStore(ctx, (store, db) => write(store, db))
|
|
544
|
+
: withReadOnlyDb(ctx, (db) => write(null, db))
|
|
545
|
+
if (options.run) {
|
|
546
|
+
ctx.log(
|
|
547
|
+
"holds.set",
|
|
548
|
+
"manual hold set",
|
|
549
|
+
holdLogAttrs(accountId, grp, Date.parse(String(result.until))),
|
|
550
|
+
{ accountId: Number(accountId), method },
|
|
551
|
+
)
|
|
552
|
+
}
|
|
553
|
+
if (options.json) ctx.out(JSON.stringify(result, null, 2))
|
|
554
|
+
else ctx.out(toonObject(result))
|
|
555
|
+
if (!result.changed) {
|
|
556
|
+
ctx.err(
|
|
557
|
+
"An existing hold ends later; MAX semantics keep it unchanged.",
|
|
558
|
+
)
|
|
559
|
+
}
|
|
560
|
+
if (!options.run) ctx.err("Dry run: nothing written. Add --run to write.")
|
|
561
|
+
})
|
|
562
|
+
|
|
563
|
+
holds
|
|
564
|
+
.command("clear")
|
|
565
|
+
.description("Remove one hold so the account can retry the group now")
|
|
566
|
+
.option("--account <id>", "Telegram account id")
|
|
567
|
+
.option(
|
|
568
|
+
"--group <group>",
|
|
569
|
+
"invite, create, resolve, send, or method:<tl.method>",
|
|
570
|
+
)
|
|
571
|
+
.option("--run", "Delete the hold (default is a dry run)")
|
|
572
|
+
.option("--force", "Allow --run to clear a hold that is still active")
|
|
573
|
+
.option("--json", "Print JSON")
|
|
574
|
+
.action((options: ClearCliOptions, command: Command) => {
|
|
575
|
+
if (calledBare(command)) {
|
|
576
|
+
printHelp(command)
|
|
577
|
+
return
|
|
578
|
+
}
|
|
579
|
+
const nowMs = ctx.now()
|
|
580
|
+
const account = requireOption(command, options.account, "--account")
|
|
581
|
+
const group = requireOption(command, options.group, "--group")
|
|
582
|
+
const accountId = String(
|
|
583
|
+
parseOrFail(command, () => parseAccountId(account)),
|
|
584
|
+
)
|
|
585
|
+
const grp = parseOrFail(command, () => parseHoldGroup(group))
|
|
586
|
+
const existing = withReadOnlyDb(ctx, (db) =>
|
|
587
|
+
db ? storedHold(db, accountId, grp) : null,
|
|
588
|
+
)
|
|
589
|
+
const active = existing !== null && existing.untilMs > nowMs
|
|
590
|
+
let removed = false
|
|
591
|
+
if (options.run && existing) {
|
|
592
|
+
const refusal = foreignOwnerRefusal(ctx.path, ctx.getuid(), "clear")
|
|
593
|
+
if (refusal) usageError(command, refusal)
|
|
594
|
+
if (active && !options.force) {
|
|
595
|
+
usageError(
|
|
596
|
+
command,
|
|
597
|
+
`the ${grp} hold for ${accountId} is active until ` +
|
|
598
|
+
`${isoTime(existing.untilMs)}; add --force to clear it early`,
|
|
599
|
+
)
|
|
600
|
+
}
|
|
601
|
+
removed = withWritableStore(ctx, (store) =>
|
|
602
|
+
store.clearHold(accountId, grp),
|
|
603
|
+
)
|
|
604
|
+
if (removed) {
|
|
605
|
+
ctx.log(
|
|
606
|
+
"holds.clear",
|
|
607
|
+
"hold cleared",
|
|
608
|
+
holdLogAttrs(accountId, grp, existing.untilMs),
|
|
609
|
+
{ accountId: Number(accountId), method: existing.method },
|
|
610
|
+
)
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const result: Record<string, Cell> = {
|
|
614
|
+
mode: options.run ? "run" : "dry_run",
|
|
615
|
+
path: ctx.path,
|
|
616
|
+
account: accountId,
|
|
617
|
+
group: grp,
|
|
618
|
+
found: existing !== null,
|
|
619
|
+
removed,
|
|
620
|
+
until: isoTime(existing?.untilMs),
|
|
621
|
+
remaining_s:
|
|
622
|
+
existing && existing.untilMs > nowMs
|
|
623
|
+
? remainingSeconds(existing.untilMs, nowMs)
|
|
624
|
+
: 0,
|
|
625
|
+
source: existing?.source ?? null,
|
|
626
|
+
}
|
|
627
|
+
if (options.json) ctx.out(JSON.stringify(result, null, 2))
|
|
628
|
+
else ctx.out(toonObject(result))
|
|
629
|
+
if (!existing) ctx.err(`No hold stored for ${accountId} ${grp}.`)
|
|
630
|
+
else if (!options.run) {
|
|
631
|
+
ctx.err(
|
|
632
|
+
active
|
|
633
|
+
? "Dry run: nothing removed. The hold is active; add --run " +
|
|
634
|
+
"--force to remove it."
|
|
635
|
+
: "Dry run: nothing removed. Add --run to remove.",
|
|
636
|
+
)
|
|
637
|
+
}
|
|
638
|
+
})
|
|
639
|
+
|
|
640
|
+
return holds
|
|
641
|
+
}
|
package/state/db.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite"
|
|
2
|
+
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
|
|
5
|
+
import { configDir, type ProfileStoreEnv } from "../profiles.ts"
|
|
6
|
+
import {
|
|
7
|
+
applyMigrations,
|
|
8
|
+
applyPragmas,
|
|
9
|
+
type Migration,
|
|
10
|
+
} from "../telemetry/db.ts"
|
|
11
|
+
// Embedded at bundle/run time so the published package carries the schema.
|
|
12
|
+
import floodHoldMigrationSql from "./migrations/0001-flood-hold.sql" with {
|
|
13
|
+
type: "text",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const STATE_DB_FILE = "state.db"
|
|
17
|
+
export const STATE_DIR_MODE = 0o700
|
|
18
|
+
export const STATE_FILE_MODE = 0o600
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Migrations for `state.db`. Separate from telemetry: state must work with
|
|
22
|
+
* telemetry off, and its history table lives in its own file.
|
|
23
|
+
*/
|
|
24
|
+
export const STATE_MIGRATIONS: readonly Migration[] = [
|
|
25
|
+
{ filename: "0001-flood-hold.sql", sql: floodHoldMigrationSql },
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
export function stateDbPath(env: ProfileStoreEnv = process.env): string {
|
|
29
|
+
return join(configDir(env), STATE_DB_FILE)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function restrictMode(path: string, mode: number): void {
|
|
33
|
+
try {
|
|
34
|
+
chmodSync(path, mode)
|
|
35
|
+
} catch {
|
|
36
|
+
// Not our directory (or a filesystem without modes); the open decides.
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Creates the parent directory (0700) and the database file (0600) before
|
|
42
|
+
* SQLite opens it, so the file never exists with wider permissions. SQLite
|
|
43
|
+
* gives `-wal` and `-shm` the database file's mode.
|
|
44
|
+
*/
|
|
45
|
+
function prepareFile(path: string): void {
|
|
46
|
+
const dir = dirname(path)
|
|
47
|
+
mkdirSync(dir, { recursive: true, mode: STATE_DIR_MODE })
|
|
48
|
+
restrictMode(dir, STATE_DIR_MODE)
|
|
49
|
+
closeSync(openSync(path, "a", STATE_FILE_MODE))
|
|
50
|
+
restrictMode(path, STATE_FILE_MODE)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Opens (creating if needed) the state database at `path`: WAL,
|
|
55
|
+
* `busy_timeout` 5000 ms, and `STATE_MIGRATIONS`. Throws on failure; use
|
|
56
|
+
* `HoldStore.open` for a store that reports `unavailable` instead.
|
|
57
|
+
*/
|
|
58
|
+
export function openStateDb(
|
|
59
|
+
path: string,
|
|
60
|
+
migrations: readonly Migration[] = STATE_MIGRATIONS,
|
|
61
|
+
): Database {
|
|
62
|
+
if (path !== ":memory:") prepareFile(path)
|
|
63
|
+
const db = new Database(path, { create: true, strict: true })
|
|
64
|
+
try {
|
|
65
|
+
applyPragmas(db)
|
|
66
|
+
applyMigrations(db, migrations)
|
|
67
|
+
return db
|
|
68
|
+
} catch (error) {
|
|
69
|
+
db.close()
|
|
70
|
+
throw error
|
|
71
|
+
}
|
|
72
|
+
}
|