Security Model
Threat model, trust boundaries, protected surfaces and plugin policy.
This document is deliberately blunt. A plugin system that can change a Telegram client is a security-critical feature. The design must not promise sandboxing that Android cannot provide for in-process code.
1. Security stance#
There are two trust tiers in the shipped runtime:
| Tier | Example | Isolation | What it can access |
|---|---|---|---|
| Sandboxed code | TypeScript plugin | QuickJS context with a host bridge | Only the bridge APIs and granted permissions |
| Trusted code | Kotlin/Java DEX plugin | None beyond the Android app sandbox | Everything the NextGram process can access |
The second tier is the important one. A DEX plugin runs in the NextGram process, under the same Android UID. It can use reflection, open files, create sockets and inspect memory. Permissions gate the official API; they do not stop malicious code.
Therefore:
- Installing a DEX plugin is equivalent to installing a trusted modification of NextGram. The installer says this in plain language.
- The signing key identifies the publisher and prevents silent updates from another key. It does not make the publisher trustworthy.
- The catalog "verified" badge means the package was reviewed by the maintainers. It is not a security audit and not a guarantee.
- Users who do not trust third-party code can keep the stock theme, avoid screen replacement plugins and disable code plugins entirely. There is no data-only theme tier any more.
2. Assets to protect#
- Telegram sessions and MTProto authorization keys.
- Message history, media, contacts, phone numbers and account metadata.
- Secret chat content and encryption state.
- Passcode, biometric unlock and screen lock state.
- Payment data, Premium purchases, gifts and Telegram Passport.
- The user's Telegram account reputation and API access.
- The integrity of the NextGram installation and the plugin catalog.
- Plugin signing keys and update channels.
- User trust in the client.
3. Adversaries#
| Adversary | Capability |
|---|---|
| Malicious plugin author | Ships a signed .ngp with hidden behavior or misleading permissions |
| Compromised plugin author | Has the real signing key and can publish a malicious update |
| Malicious chat participant | Sends a plugin file and social-engineers the user to install it |
| Compromised catalog | Can serve arbitrary index entries or downloads |
| Network attacker | Intercepts update checks or downloads |
| Malicious screen plugin | Draws an imitation of Telegram UI or the plugin manager |
| Malicious script author | Tries to escape QuickJS or abuse bridge APIs |
| Local attacker | Has physical access to an unlocked or rooted device |
| Supply-chain attacker | Compromises the SDK, Gradle plugin, repository index key or build pipeline |
| Upstream attacker | Exploits a Telegram or Android vulnerability outside the plugin system |
4. Trust boundaries#
4.1 Android app sandbox#
The app sandbox protects NextGram from other apps. It does not isolate plugins from NextGram. All DEX plugins share the app UID, the process, the heap and app-private storage.
Consequences:
- A DEX plugin can read Telegram databases and preference files directly, including data the plugin API never exposes.
- A DEX plugin can read another plugin's storage.
- A DEX plugin can inspect decrypted secret chat messages while they are in memory, and can attempt to read encrypted secret chat records.
- Permissions cannot prevent this. They are a contract and an audit mechanism.
This is the main residual risk of the design. It is not fixable with a better permission check; it requires a separate process or a different plugin model.
4.2 Script sandbox#
QuickJS runs in the app process but has no Java/Android bindings. The only bridge is the nextgram object:
- values are JSON-serializable;
- every host call goes through a permission check;
- there is no filesystem, socket, class loader or reflection access;
- memory and execution time are limited;
- the engine is kept up to date because a QuickJS escape is a sandbox escape.
A script can still exfiltrate data that the bridge returns. Permissions and review matter.
The script runtime ships in this tree. Script packages install, enable, disable and update through the same signed-package flow and consent screen as code packages. The QuickJS context is created per plugin with a 32 MB heap and a 6 MB stack, callbacks run with a bounded deadline, and a plugin that exceeds a limit is interrupted and disabled.
4.3 Screen replacement#
ui.screens is a high-risk trust surface. A plugin view is attached as an opaque overlay over a stock screen and can imitate the Telegram interface, including menus, dialogs and permission prompts. The host keeps the real fragment, lifecycle, navigation, insets and back handling, but the user sees the plugin's drawing.
Boundaries:
- Protected surfaces never resolve a screen provider: login, passcode, payments, secret chats, installer, consent, safe mode, plugin manager, calls and inactive accounts.
SharedConfig.appLockeddisables screen providers entirely.- The Allow screen replacement plugins switch defaults on and can remove every overlay and slot without uninstalling plugins.
- Safe mode unloads external plugins and clears appearance and screen state.
- A plugin view cannot change the navigation stack, the action bar or another plugin's registration.
- A factory or view exception falls back to the stock screen and counts toward the plugin failure budget.
This is an API and UI boundary, not a process boundary. A malicious DEX plugin can still draw its own window or use reflection; the contract is not a sandbox. The consent copy says that the plugin can imitate the interface and should only be installed from a trusted author.
4.4 Appearance#
ui.appearance is a low-risk permission, but the effect is global. A code plugin can apply semantic colors, arbitrary upstream Theme.key_* values and plugin-scoped custom colors. The host validates keys, warns about unknown raw keys and low-contrast pairs, and keeps one active provider.
The kernel-owned Reset appearance action restores the previous theme without loading the plugin. Disable, uninstall, revocation, safe mode and a failed apply also restore the previous theme. Appearance cannot execute code by itself; it is applied by a trusted code plugin.
4.5 Repository and catalog#
The GitHub repository is a signed index and a transport, not a package authority. A package must have its own valid signature. The index can mark a package verified and provide a hash, but it cannot make a package signed by a different key trusted for an update. A compromised repository can mislead users with entries and badges; it cannot forge a package update without the publisher key. The index signing key is separate from the plugin signing keys and is stored in CI secrets, never in a pull request job.
5. Threat model#
| Threat | Mitigation | Residual risk |
|---|---|---|
| Malicious plugin from a chat | No auto-install; source shown; signature and permissions shown; explicit warning for code | User installs anyway; social engineering |
| Plugin update changes behavior | New permissions re-consent; changelog; same key required; audit log | Same permissions can hide new behavior |
| Update signed by another key | Key pinned per plugin ID; update rejected | Compromised original key |
| Downgrade to vulnerable version | Strictly increasing versionCode; previous version kept for manual rollback | Developer mode allows downgrade |
| ZIP path traversal | Canonical path checks; reject .., absolute paths, backslashes, symlinks | None known |
| ZIP bomb | Size, entry count, compression ratio and uncompressed size limits before extraction | CPU/disk pressure within limits |
| Duplicate entry ambiguity | Reject duplicate and case-insensitive duplicate names; reject unsigned entries | None known |
| Signature stripping | Every non-signature entry must be signed; exactly one signer | JAR signing does not cover ZIP metadata, handled separately |
| Malicious DEX | Android ART verification; no native libs; trusted-code warning | Full app access by design |
| Malicious script | QuickJS sandbox; bridge validation; time/memory limits; no Android bindings | Engine vulnerability; permitted data exfiltration |
| Screen replacement imitates UI | ui.screens high risk and off by default; protected resolver; kill switch; safe mode; trusted-author warning | Plugin can draw a convincing fake of an unprotected screen |
| Broken appearance | Previous theme restore, kernel Reset appearance, safe mode, contrast warnings | Unreadable colors until reset |
| Global theme tints protected surfaces | Appearance is documented as global; protected surfaces receive no plugin views, contexts or data | Login, passcode and payment screens change color with the rest of the app |
| Parser exploit | Bounded inputs; strict validation; fuzzing; keep parsers updated | Unknown parser bugs |
| Repository/catalog compromise | Pinned official key; package signature independent; local cache; branch protection | Attacker with official key can mark bad plugins verified |
| Malicious pull request or CI compromise | Required review; read-only PR workflow; signing key only in release job; least-privilege tokens | Compromised release job or maintainer account |
| GitHub outage or tampering | Signed index; cached copy; immutable artifact URLs; chat/file fallback | Denial of service; stale catalog |
| Update MITM | HTTPS; package signature; hash from signed index | Compromised author endpoint |
| Account ban from automation | No raw MTProto; rate limits; background send confirmation; audit; plugin policy | Malicious code can still use reflection |
| Spam or bulk messaging | Per-plugin rate limits; background confirmation; policy and revocation | Reflection bypass; user grants |
| Secret chat leak | API filters secret chats; CHAT screen provider never resolves for a secret dialog; no events or actions; blocked permission | Malicious DEX can reflect; see 4.1 |
| Passcode/payment leak | Protected resolver for screen providers; no API access; app-lock and login checks | Malicious DEX can reflect; see 4.1 |
| Plugin data theft by another plugin | None at the process level | Same UID; documented |
| Clipboard abuse | Host API permission; Android 13+ clipboard restrictions | Malicious DEX can use Android APIs directly |
| Overlay/phishing UI | Host-owned overlay; protected surfaces never receive plugin views; install consent shows the screen warning; kill switch | DEX can draw its own overlays or fake unprotected content |
| Plugin reads logs | Logs are app-private | Same UID |
| SDK supply-chain attack | Signed artifacts, checksums, pinned dependencies, reproducible builds | Build infrastructure compromise |
| Malicious plugin downloads new code | Policy forbids it; no official API | DEX can load code itself; not enforceable |
6. Permissions are a contract, not a sandbox#
The permission system exists to:
- tell the user what a plugin intends to do;
- gate the official API;
- produce an audit trail;
- let the user revoke capabilities;
- give plugin authors a clear capability model.
It does not:
- stop a DEX plugin from reading files;
- stop a DEX plugin from opening a socket;
- stop reflection into
org.telegram.*; - isolate one plugin from another;
- protect secret chats from a determined malicious DEX plugin.
The install screen must say this. The following sentence is part of the UX copy:
Code plugins run inside NextGram and have the same access as the app itself. Only install plugins from authors you trust. Permissions describe what the plugin uses, but they cannot sandbox its code.
For script plugins, the same sentence is not shown; instead the screen says the plugin runs in a restricted JavaScript sandbox.
ui.screens is a high-risk permission because the host cannot inspect what a plugin draws. A plugin with that permission can imitate unprotected Telegram content. The permission starts off at install, the consent copy warns that the plugin can replace screens and imitate the interface, and the kernel switch Allow screen replacement plugins can disable all overlays. The permission still gates an API, not the process.
7. Protected surfaces#
Third-party plugins cannot contribute UI, receive events or call APIs for these areas:
- login, registration, phone confirmation, QR login and two-step password;
- passcode, biometric unlock and screen lock;
- payment forms, checkout, Premium purchase, gifts and Telegram Passport;
- secret chats;
- the plugin installer, consent screen, permission editor and update prompt;
- safe mode and crash recovery;
- the plugin manager and plugin details;
- catalog trust UI and signature details;
- calls, group calls, call media and screen sharing.
For these surfaces:
- no plugin contributions are rendered;
- no plugin screen provider or slot is attached;
- no
ScreenContextorSlotContextis created; - no plugin events are emitted;
- no plugin API returns data;
- the kernel UI does not call plugin code.
This is an API and UI boundary, not a process boundary. A malicious DEX plugin can still attempt reflection. See 4.1. The design does not claim otherwise.
Appearance is global: an applied .attheme also tints login, passcode and payment screens. Those surfaces receive no plugin views, contexts or data, but their colors are not isolated. Per-screen theme isolation is a follow-up; the Reset appearance action and safe mode are the recovery paths. This residual is accepted and documented.
Secret chats deserve a separate note: the API filters them, the CHAT screen provider never resolves for a secret dialog, and third-party plugins cannot request them. But because DEX plugins share the process, the only hard guarantee is not installing untrusted code. Users who need secret chat isolation should disable code plugins. Themes are no longer a data-only safe tier; they are applied by code plugins too.
A plugin file received in a secret chat is also not offered for in-place installation. The user must save it and install it through the file picker. The installer never stores the secret chat id or title. This keeps the secret chat surface out of the plugin trust flow.
8. Signing and publisher identity#
8.1 Plugin keys#
- Each publisher generates a key pair and a self-signed certificate.
- The certificate is not issued by a CA. Identity is the SHA-256 fingerprint.
- RSA 2048+ or EC P-256+ only. SHA-256 digests. No MD5 or SHA-1.
- The key is stored outside the repository and the build output.
- CI signing uses a secret store with narrow access and audit logs.
- The plugin ID and key fingerprint are shown on the install screen.
- Updates must use the same key.
- Key rotation is not supported in v1. A future rotation statement must be signed by the old key.
8.2 Repository index keys#
- The official index key is pinned in the app.
- It is kept offline or in an HSM-backed signing service.
- The index signing key is separate from any plugin key.
- Custom repositories are not part of v1; the app trusts only the pinned official index key.
- A compromised index key can mark bad plugins as verified, but cannot sign packages. The package signature remains the install gate.
- The index key lives only in the release workflow. Pull request workflows run untrusted code without access to it.
- The index is built from reviewed entries and artifacts; workflow permissions are read-only except for the release job.
- Artifacts are referenced by immutable URL (GitHub Release asset or commit-pinned raw path) and checked against the SHA-256 from the signed index.
- Branch protection is recommended for changes to
catalog/,.github/and signing configuration.
8.3 Revocation#
The catalog can publish a signed revocation list:
{
"format": "ngp-revocations",
"formatVersion": 1,
"issuedAt": "2026-12-02T00:00:00Z",
"entries": [
{
"id": "dev.example.bad",
"fingerprint": "hex...",
"maxVersionCode": 12,
"reason": "malware",
"severity": "critical"
}
]
}- Critical revocations disable the plugin as soon as a verified list is applied and again at the next start. Enabling, reloading or updating a package whose
versionCodeis at or belowmaxVersionCodeis refused; a newer version outside the range may be installed normally. - Non-critical revocations show a warning and recommend uninstalling. The user can override a warning only within the revoked version range; the override is pruned when a newer revocation entry widens that range.
- Critical malware revocation is never overridable, and a critical entry wins over a warning entry that matches the same plugin, fingerprint and version.
- Revocation feeds and catalog indexes require a valid pinned ECDSA P-256 signature. Unsigned indexes are accepted only in developer mode, which is compiled out of release builds; revocation feeds never accept unsigned input.
- Cached feeds are re-verified on load. A network failure falls back to the last signed cache and does not clear an existing critical revocation.
- Revocation lists are checked on catalog refresh and on update checks, not silently in the background by default.
9. Install-time hardening#
- The source file is copied with a size limit before parsing.
- ZIP structure is validated before extraction: duplicate and case-insensitive duplicate names, directory entries, absolute paths, backslash paths, drive letters,
..segments, non-NFC names and control characters are rejected. - Entry count, per-entry size, total uncompressed size and compression ratio are checked against the central directory before any payload is read.
- ZIP, GZIP, 7z, RAR, XZ and BZIP2 signatures are rejected under any file name, so renaming a nested archive does not bypass the extension check.
- The signature is verified before
plugin.jsonis parsed; every non-META-INFentry must carry a SHA-256 digest and exactly one signer is allowed. - JSON parsing has depth, string, number, array and object-size limits. Duplicate keys and oversized structures are rejected; unknown fields are ignored, while unknown permissions and payload paths are rejected.
- Assets are not decoded until after install; icons are bounds-checked, including a minimum PNG header length, before dimensions are read.
script/main.jsis limited to 8 MB; script and hybrid packages install and enable.- DEX is extracted to a private directory and marked read-only before loading.
- The installer copies the verified package into staging, re-checks its size and SHA-256, and extracts only from that staged copy, so a source file swapped after preview cannot change what is installed.
- No native libraries, no nested archives, no executables.
- Package paths are canonicalized and checked against the staging root.
- The installer runs in the main process but does not call plugin code.
- The install is atomic; a failed update leaves the previous version installed, enabled and loadable, and a failed registry write restores the previous entry.
10. Runtime hardening#
- Every plugin callback is wrapped by
PluginGuard. - Exceptions are caught and attributed; repeated failures disable the plugin.
- Main-thread callbacks have a budget; repeated blocking disables the plugin.
- Script callbacks have CPU, memory and queue limits.
- Service calls can fall back to the default provider.
- Interceptors have a measured 50 ms budget. A slow interceptor can delay one operation; repeated violations disable it.
- API rate limits prevent accidental or malicious floods.
- Plugin-initiated sends, edits and deletes are written to an audit log visible in the plugin details.
- Each plugin keeps at most 300 log lines and each line is truncated to 8 KB in both logcat and the in-app log. Host code never logs message text, captions, phone numbers or other account data.
- Safe mode disables external plugins after a boot crash loop and skips code and script plugin loading. It resets the active appearance and removes screen and slot providers. The boot counter resets only after the first frame, not at activity start.
- Developer mode, unsigned packages and unsigned catalog indexes are available only in debug builds; the release build hides the switch and ignores a previously stored preference.
- The plugin manager can disable all external plugins, one plugin, or only code plugins.
11. Account safety#
Telegram accounts are valuable and easy to lose. The plugin API is designed to reduce ban risk:
- No raw MTProto access in v1.
- No direct access to authorization keys.
- Rate limits per plugin for reads, sends, edits and deletes.
- Background sends require a dangerous permission and a confirmation.
- No bulk messaging, mass inviting, scraping or automated account actions.
- Flood-wait errors are returned to the plugin; the host does not retry in a loop.
- Plugins cannot change privacy settings, transfer ownership, delete accounts or manage sessions.
- The plugin policy forbids automation that violates Telegram's terms.
None of this is enforceable against a malicious DEX plugin. It reduces accidental harm and gives the catalog a reason to remove abusive plugins.
12. Privacy#
- NextGram adds no analytics or telemetry. The plugin system does not change that.
- Plugin logs stay on the device. They are exported only by an explicit user action.
- Update checks are off by default and run at most once per day when enabled.
- Catalog requests carry no account identifier. The server sees an IP address like any HTTPS request.
- Plugin data is stored in the no-backup directory and is excluded from Android auto-backup.
- Permission prompts explain data access in plain language.
- Snapshots omit phone numbers, auth keys, raw file paths and secret chat content unless a permission explicitly allows the field.
- Plugins must not log message contents, phone numbers or tokens.
- A plugin that wants network access declares
network. For DEX plugins this is declarative; for scripts it is enforced by the bridge.
13. Supply chain#
- SDK artifacts will be published with checksums and signatures at the first public SDK release.
- The Gradle plugin and CLI pin their dependencies and verify downloads.
- Plugin templates lock the SDK version and use a dependency verification file.
- Release builds use a clean environment and a documented toolchain.
- Reproducible builds are recommended for plugins; the catalog can show a "reproducible" badge when the source and build instructions are available.
- The repository review checks the source link, license, permissions and behavior.
- The official repository index key, plugin signing keys and CI secrets are separate.
- Pull request validation runs without secrets and cannot publish an index or release.
- Release artifacts are uploaded to GitHub Releases and referenced by immutable URLs.
- Branch protection covers
catalog/,.github/and signing configuration. - A compromised SDK or repository release is handled like a security incident: advisory, revocation, new version and user notification.
14. Incident response#
- Confirm the report and identify affected plugin IDs, versions and fingerprints.
- Publish a revocation entry with severity and reason.
- Remove the plugin from the catalog and disable downloads.
- Notify users in the NextGram channel and in the plugin manager.
- Provide removal instructions and, if needed, a safe-mode path.
- If the signing key is compromised, publish an advisory; v1 cannot rotate keys, so the plugin ID is retired.
- If the SDK or repository index key is compromised, rotate the key, ship an app update and revoke affected artifacts.
- Publish a post-mortem without user-identifying data.
15. Plugin policy#
A plugin is removed from the catalog and may be revoked if it:
- steals credentials, sessions, messages, contacts or payment data;
- hides its behavior or requests permissions it does not need;
- sends spam, scrapes data, automates account actions or evades Telegram limits;
- accesses secret chats, passcode, payments or Telegram Passport;
- downloads and executes code not contained in its signed package;
- ships native code, exploits, malware or a backdoor;
- impersonates NextGram, Telegram or another publisher;
- uses the catalog to distribute illegal content or fraud;
- violates the license of NextGram or its dependencies.
The policy applies to the catalog. Chat distribution cannot be policed by the maintainers, which is another reason the install screen is explicit.
16. Security review checklist#
Before a plugin is marked verified:
- [ ] The source link matches the package and builds reproducibly, or the author provides a build attestation.
- [ ] The signing key is controlled by the publisher and not shared.
- [ ] The manifest permissions match the behavior.
- [ ] No native libraries, dynamic code loading or hidden network endpoints.
- [ ] No access to protected surfaces.
- [ ] No automated messaging, scraping or rate-limit evasion.
- [ ] Logs do not contain sensitive data.
- [ ] The plugin handles permission denial and empty states.
- [ ] The plugin does not block the main thread.
- [ ] The package passes the verifier and the SDK contract tests.
- [ ] The license is compatible with the plugin's distribution model.
17. Residual risks#
These risks are accepted for v1 and must be communicated:
- DEX plugins are trusted code. They can read Telegram data directly, including secret chats, and can exfiltrate it. Permissions do not prevent this.
- The catalog review is not a formal security audit.
- Self-signed publisher keys can be stolen; key rotation is not available in v1.
- QuickJS or Android parser vulnerabilities can break the script sandbox.
- A malicious plugin can draw deceptive UI inside its own screens or imitate an unprotected screen with
ui.screens. - An applied appearance is global and also tints protected surfaces; it does not give a plugin access to their data.
- A malicious plugin can abuse network access;
networkis declarative for DEX code. - Users can grant dangerous permissions or install unsigned developer packages.
- Upstream Telegram or Android vulnerabilities are outside this design.
18. Future hardening#
- A separate process with a narrow Binder API for non-UI code plugins.
- A fully declarative remote-UI model for untrusted code plugins.
- Per-plugin storage encryption and Keystore-backed secrets.
- Key rotation with old-key-signed statements.
- Whole-file signature scheme in addition to JAR signing.
- Reproducible builds and build attestations in the catalog.
- Revocation feed with automatic critical response.
- Security audit and bug bounty before a 1.0 plugin release.
Until then, the product must be honest: code plugins are modifications, not sandboxed extensions. The rest of the system is designed around that fact.