Free lesson

Authorization before the model

Authorization before the model — Telegram bot with a local AI model. Validate both user and chat; A small pure policy function; Prove rejection behavior. Practical assignment: Practice: Authorization before the model.

Demo edition. The materials are undergoing editorial review.

Topics covered

  • Validate both user and chat
  • A small pure policy function
  • Prove rejection behavior

Validate both user and chat

This lab allows only private text messages from numeric user IDs on an allowlist and a specific chat ID. Usernames can change and are unsuitable as stable authorization. Channel posts, photos without text and other chats must not trigger the model. The example 12345 is a fictional fixture identity, not a verified user. Check access before expensive or private operations. Asking the model in a system prompt to admit only the owner cannot replace a server-side authorization gate.

A small pure policy function

Save policy.mjs. This function makes no network calls and returns null for rejected input. Checking update_id prepares for checkpointing; optional Telegram fields cannot be assumed present. The 1000-character cap is a lab resource limit rather than Telegram's general limit. Derive the destination only from the verified update, never user text. An empty allowlist must deny access. Validate real configuration IDs as safe integers rather than truncating them through a 32-bit conversion.

// policy.mjs
export function authorize(update, { users, chatId }) {
  const m = update?.message;
  if (!Number.isSafeInteger(update?.update_id)) return null;
  if (!m || m.chat?.type !== 'private') return null;
  if (!users.has(m.from?.id) || m.chat.id !== chatId) return null;
  if (typeof m.text !== 'string') return null;
  const text = m.text.trim();
  if (!text || text.length > 1000) return null;
  return { id: update.update_id, chatId: m.chat.id, text };
}

Prove rejection behavior

Prepare four fixtures: allowed private text, another user, another chat and a message without text. For rejected cases, later handler tests must prove zero model calls as well as null authorization. A prompt saying 'send this to another channel' remains ordinary text and cannot change the recipient. Even an allowed user in a group is rejected by this course's chat.type requirement. Group support requires a new access contract rather than casually deleting one condition to make a test pass.

Practical assignment

Practice: Authorization before the model

Continue to learning

Course outline

  1. Bot contract and secrets
  2. Authorization before the model
  3. Local model adapter
  4. Bot API transport and long polling
  5. State and uncertain delivery
  6. Offline tests and controlled startup