Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/bot/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copy to .dev.vars for `pnpm --filter @app/bot dev` (wrangler reads it as the
# Worker's secrets). None is required: with no token the Worker serves its
# pages and /health says to connect one.
TELEGRAM_TOKEN=
ADMIN_ID=
ADMIN_PASSWORD=
TELEGRAM_SECRET_TOKEN=
21 changes: 21 additions & 0 deletions apps/bot/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 TBXark

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
29 changes: 29 additions & 0 deletions apps/bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# apps/bot — the Worker

[ChatGPT-Telegram-Workers](https://github.com/TBXark/ChatGPT-Telegram-Workers)
by [TBXark](https://github.com/TBXark) and its contributors, MIT
([LICENSE](LICENSE)): upstream's Cloudflare Workers entry
(`packages/apps/workers`), over upstream's libraries in [`packages/`](../../packages),
with the product's name and repository on its pages and one route in front.

| Route | What answers |
|---|---|
| `POST /telegram/<token>/webhook` (`/safehook`) | Telegram's updates — upstream |
| `GET /`, `/help`, `/init`, `/admin`, `/interpolate` | upstream's single-page app (`@bot/web`); `/admin` is the Telegram Mini-App |
| `POST /rpc` | the page's JSON-RPC — upstream |
| `POST /init/bind` | the deploy's webhook binding: `Authorization: Bearer <bot token>`, then upstream's bind (webhook, commands, menu button) — added |
| `GET /health` | the KV namespace read through `DATABASE`, the environment, whether a token is connected — added |

Bindings: `DATABASE` (Workers KV, from the `cloudflare-kv` root's wiring),
`AI` (Workers AI). Secrets, all optional: `TELEGRAM_TOKEN`, `ADMIN_ID`,
`ADMIN_PASSWORD`, `TELEGRAM_SECRET_TOKEN`.

```bash
pnpm --filter @app/bot dev:local # wrangler dev, no account: local KV, no Workers AI
pnpm --filter @app/bot dev # wrangler dev with Workers AI (needs `wrangler login`)
pnpm --filter @app/bot build # wrangler deploy --dry-run → dist/, then the bundle guard
```

Upstream's documentation — the commands, the configuration, the plugin
system — is at
[`doc/en`](https://github.com/TBXark/ChatGPT-Telegram-Workers/tree/master/doc/en).
118 changes: 118 additions & 0 deletions apps/bot/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: bot
description: The Telegram bot (upstream's Workers entry over its libraries, one plain Cloudflare Worker per environment)
spec:
type: cloudflare-worker-turbo
lifecycle: production
owner: platform
# Its pages, attached to it in the workspace's catalog: what the Docs
# library shows for it, and what the catalog's docs and runbook checks read.
# Generated from what this manifest and its sources declare.
docs:
overview: docs/overview.md
pages:
- { path: docs/architecture.md, role: architecture, title: Architecture }
- { path: docs/runbook.md, role: runbook, title: Runbook }
# `app`, not `bot`: a domain and a component share one name space in the
# catalog, and a domain called `bot` would take this component's place in
# it — the bot missing from its own catalog.
domain: app
path: apps/bot
# The Worker is upstream's libraries as much as this directory: a change to
# any of them (packages/) is a change to what this Worker runs, so it
# re-plans this component. Orun selects by path, and this is the path the
# Worker does not own but bundles.
change:
inputs:
- packages/**
# The KV namespace's wiring document, per environment: the cloudflare-kv
# root lease-publishes it after its apply, and the build renders the
# namespace id into wrangler.jsonc from it.
secretEnv:
WIRING_CLOUDFLARE_KV_STAGE: "secret://telegram-ai-bot/telegram-ai-bot/stage/WIRING_CLOUDFLARE_KV"
WIRING_CLOUDFLARE_KV_PROD: "secret://telegram-ai-bot/telegram-ai-bot/prod/WIRING_CLOUDFLARE_KV"
# The bot's own secrets, stored per environment by its owner (README →
# Connecting a bot): the token from @BotFather, the admin's Telegram user id,
# an optional browser password for /admin and an optional webhook secret.
# BEST-EFFORT, wire-now-seed-later: a key nobody has stored is skipped when
# the job resolves its secrets (no env var, no failure), so a fresh product
# deploys and serves before its owner has created a bot at all. The ones
# that are set reach the Worker as Worker SECRETS — the composition's
# secrets-live step, `wrangler secret bulk`, after the deploy — and never a
# bundle or a log.
optionalSecretEnv:
TELEGRAM_TOKEN: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/TELEGRAM_TOKEN"
ADMIN_ID: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/ADMIN_ID"
ADMIN_PASSWORD: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/ADMIN_PASSWORD"
TELEGRAM_SECRET_TOKEN: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/TELEGRAM_SECRET_TOKEN"
subscribe:
environments:
- name: dev
profile: verify
- name: stage
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
- name: prod
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"

workspaceDir: ../..
appDir: .

turboFilter: "@app/bot"
# The committed wrangler.jsonc is the fixture render of
# wrangler.template.jsonc — what the composition's structure check finds
# before anything is built. The build re-renders it for its environment
# (buildCommand), and the composition deploys and dry-runs it with
# `--env <environment>`: telegram-ai-bot-bot-{dev,stage,prod}.
wranglerConfig: wrangler.jsonc

# Pushed with `wrangler secret bulk` after each deploy, from the
# optionalSecretEnv values above that are stored (none, on a fresh product).
runtimeSecrets: "TELEGRAM_TOKEN,ADMIN_ID,ADMIN_PASSWORD,TELEGRAM_SECRET_TOKEN"

installCommand: pnpm install --frozen-lockfile
# Render this environment's wrangler config, then build. stage and prod
# render from the wiring document their cloudflare-kv apply published
# (secretEnv above, resolved before the job's first step); dev, which no
# root applies to and which only verifies, renders from the committed
# fixture. Then turbo builds the libraries and bundles the Worker
# (wrangler deploy --dry-run), and the bundle guard checks it loads in
# workerd. The bot's secrets never reach the build: the Worker reads them
# at request time.
buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-kv --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && env -u TELEGRAM_TOKEN -u ADMIN_ID -u ADMIN_PASSWORD -u TELEGRAM_SECRET_TOKEN pnpm exec turbo run build --filter=@app/bot
typecheckCommand: pnpm exec turbo run typecheck --filter=@app/bot

preDeployCommand: "echo 'No pre-deploy step configured.'"
migrationCommand: "echo 'No migrations configured.'"
# THE POST-DEPLOY STEP, then the smoke. The smoke is the composition's
# one step after the deploy and the secrets push, so the webhook binding
# runs here: with a stored TELEGRAM_TOKEN, scripts/bind-webhook.mjs posts
# to the Worker's own POST /init/bind (the token as a bearer, never on a
# command line or in a log) and the Worker binds Telegram's webhook to
# itself, publishes the commands and the admin menu button; with none it
# is a named no-op. Then /health must answer `"status":"ok"` and `"kv":"ok"`
# for THIS environment — the reading only this Worker, bound to its KV
# namespace, can make. Not the bot's name, which is the owner's to change.
# The Worker composition exports no deployed URL, so the command names its
# own workers.dev URL; ${DEPLOYED_URL} overrides it (a custom domain, or a
# local `wrangler dev`). The body is buffered before grep so an early match
# cannot SIGPIPE curl. The composition retries the whole command with
# backoff, and both halves are idempotent.
smokeCommand: 'base="${DEPLOYED_URL:-https://telegram-ai-bot-bot-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" && node scripts/bind-webhook.mjs "${base}" && health="$(curl -sf --max-time 20 "${base}/health")" && echo "${health}" | grep -q "\"status\":\"ok\"" && echo "${health}" | grep -q "\"kv\":\"ok\"" && echo "${health}" | grep -q "\"environment\":\"${ORUN_ENVIRONMENT}\""'
labels:
team: platform
layer: runtime
surface: bot
runtime: cloudflare
37 changes: 37 additions & 0 deletions apps/bot/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# bot — architecture

Built by the turbo pipeline from `apps/bot` and deployed with wrangler.

| | |
| ------------------ | ---------------------------------- |
| Worker config | `apps/bot/wrangler.template.jsonc` |
| Entry | `src/index.ts` |
| Compatibility date | `2026-08-04` |

## Bindings

| Binding | Kind | Source |
| ---------- | -------------------- | --------------------------------------- |
| `DATABASE` | Workers KV namespace | `app_kv_id` from `cloudflare-kv` |
| `AI` | Workers AI | account-level; no resource to provision |

Identifiers marked _from_ a component are filled in at deploy time from
that component's published outputs for the environment being deployed.

## Variables

`ENVIRONMENT` — overridden per environment (`__ENV__`).

## Wiring

Resolved at deploy time from secrets the infrastructure lanes publish (names only):

- `WIRING_CLOUDFLARE_KV_PROD`
- `WIRING_CLOUDFLARE_KV_STAGE`

## Secrets resolved by the lane (names only)

- `ADMIN_ID` (optional)
- `ADMIN_PASSWORD` (optional)
- `TELEGRAM_SECRET_TOKEN` (optional)
- `TELEGRAM_TOKEN` (optional)
20 changes: 20 additions & 0 deletions apps/bot/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# bot

The Telegram bot (upstream's Workers entry over its libraries, one plain Cloudflare Worker per environment)

A Cloudflare Worker, deployed per environment by its CI lane.

| | |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| Type | `cloudflare-worker-turbo` |
| Source | `apps/bot` |
| Package | `@app/bot` |
| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` |

## Depends on

- (none)

## Depended on by

- (none)
39 changes: 39 additions & 0 deletions apps/bot/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# bot — runbook

## How it runs

Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`.
CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;
the plan orders a component after everything it depends on.

## Local commands

```bash
pnpm --filter @app/bot dev
pnpm --filter @app/bot build
pnpm --filter @app/bot typecheck
pnpm --filter @app/bot lint
```

## Verify

After a deploy the lane runs this smoke against the environment it
deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:

```bash
base="${DEPLOYED_URL:-https://telegram-ai-bot-bot-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" && node scripts/bind-webhook.mjs "${base}" && health="$(curl -sf --max-time 20 "${base}/health")" && echo "${health}" | grep -q "\"status\":\"ok\"" && echo "${health}" | grep -q "\"kv\":\"ok\"" && echo "${health}" | grep -q "\"environment\":\"${ORUN_ENVIRONMENT}\""
```

## Rollback

Revert the commit on `main`. The next convergence applies the previous desired
state; nothing was changed out of band, so there is nothing else to undo.

## Common failures

- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream
has not applied for this environment yet. Within one convergence the plan
runs it first; on its own, re-run that lane.
- **The smoke fails right after a first deploy**: a new workers.dev route can
answer 4xx for a few seconds and the lane retries. A failure that persists
is a regression in the deployed code.
2 changes: 2 additions & 0 deletions apps/bot/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import config from "../../tooling/eslint/index.js";
export default config;
27 changes: 27 additions & 0 deletions apps/bot/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@app/bot",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"dev:local": "wrangler dev --local",
"build": "wrangler deploy --dry-run --outdir dist && node scripts/check-bundle.mjs dist/index.js",
"typecheck": "tsc --noEmit",
"lint": "eslint src scripts",
"wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage"
},
"dependencies": {
"@bot/config": "workspace:*",
"@bot/core": "workspace:*"
},
"devDependencies": {
"@app/eslint-config": "workspace:*",
"@app/tsconfig": "workspace:*",
"@cloudflare/workers-types": "^5.20261006.1",
"@types/node": "^22.9.0",
"eslint": "^9.27.0",
"typescript": "^5.8.3",
"wrangler": "^4.151.0"
}
}
57 changes: 57 additions & 0 deletions apps/bot/scripts/bind-webhook.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env node
// The deploy's webhook binding — run by the component's smoke, which is the
// step after the deploy and the secrets push.
//
// The bot token is an optional Orun secret (TELEGRAM_TOKEN). The deploy job
// has it in its environment when the owner stored one, and has already pushed
// it to the Worker as a secret. This posts to the Worker's own
// POST /init/bind with the token as a bearer, and the Worker runs upstream's
// bind: setWebhook at its own URL, setMyCommands, the Mini-App menu button.
// With no token it says so and exits 0: a fresh bot deploys and serves
// before its owner has created a bot.
//
// The token is never printed, never on a command line, never in a URL this
// logs: it travels in a header to the Worker, over HTTPS.
//
// node scripts/bind-webhook.mjs <worker-url>
const base = (process.argv[2] ?? "").replace(/\/+$/, "");
if (!/^https?:\/\//.test(base)) {
console.error("usage: bind-webhook.mjs <worker-url>");
process.exit(2);
}
const token = (process.env.TELEGRAM_TOKEN ?? "").trim();
if (!token) {
console.log(
`bind-webhook: no TELEGRAM_TOKEN stored for ${process.env.ORUN_ENVIRONMENT ?? "this environment"} — ` +
"the webhook is not bound (connect a bot token: store it with `orun secrets set TELEGRAM_TOKEN`, then redeploy)",
);
process.exit(0);
}

let response;
try {
response = await fetch(`${base}/init/bind`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(30_000),
});
} catch (e) {
console.error(`bind-webhook: ${base}/init/bind did not answer (${e.name})`);
process.exit(1);
}
let body = {};
try {
body = await response.json();
} catch {
// reported below by status
}
const outcome = body.outcome ?? `HTTP ${response.status}`;
if (response.ok && body.ok) {
console.log(`bind-webhook: the webhook is bound to ${base} (commands and the admin menu button published)`);
process.exit(0);
}
// Telegram's own description, when it gave one, says what is wrong (a revoked
// token, a URL it refused). It never contains the token.
const description = body.result?.webhook?.description ?? body.message ?? "";
console.error(`bind-webhook: binding failed — ${outcome}${description ? `: ${description}` : ""}`);
process.exit(1);
21 changes: 21 additions & 0 deletions apps/bot/scripts/check-bundle.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env node
// Upstream's bundle guard (packages/apps/workers/scripts/check-bundle.ts):
// the Worker is pure ESM, loaded by workerd, which has no `require`. A
// CommonJS dependency bundled into it makes the bundler inject a dynamic
// require shim — the build still succeeds, and the Worker crashes on start
// ("Dynamic require of … is not supported"). This fails the build instead.
//
// node scripts/check-bundle.mjs [dist/index.js]
import * as fs from "node:fs";

const MARKER = "in an environment that doesn't expose the `require` function";
const bundle = process.argv[2] ?? "dist/index.js";
const source = fs.readFileSync(bundle, "utf8");
if (source.includes(MARKER)) {
console.error(
`[check-bundle] ${bundle} contains a CommonJS \`require\` shim: a bundled CJS dependency ` +
"is not loadable by workerd and would crash the Worker at startup. Remove or replace it.",
);
process.exit(1);
}
console.log(`[check-bundle] ${bundle} is dependency-free ESM.`);
Loading
Loading