# NextGram Plugin System

Documentation for the plugin platform of NextGram Android. This document set is the
source of truth for the shipped runtime. It describes the `.ngp` package format, the
SDK, the permission model, the security stance, distribution and the remaining
roadmap.

Status: **code and repository paths implemented and device-tested**. The current Android
client is Telegram for Android 13.4.3 with NextGram branding (`app.nextgram.dev`,
Java 17, `minSdk 23`). The v1 path is implemented end to end: signed `.ngp`
verification, atomic install/update/uninstall, DEX loading, declarative settings,
message and chat toolbar actions, the plugin manager and install consent UI, code-plugin
appearance, screen replacement and slots, the signed repository with updates and
revocations, and JVM plus focused on-device tests. The appearance and screen replacement
surfaces added in this release pass JVM and build verification; their on-device checks
remain release gates. Plugin Manager is core and locked; Community is a normal feature
plugin that can be disabled live.

The release feature set is exactly:

- signed `.ngp` code plugins, installed from a file, a chat document, the share sheet
  or the signed GitHub catalog;
- code-plugin appearance through `ui.appearance`: semantic palette tokens, raw upstream
  color keys, plugin-scoped custom colors, apply, reset, persistence and safe mode;
- screen replacement for `CHAT_LIST`, `CHAT`, `SETTINGS`, `PROFILE` and
  `MAIN_NAVIGATION` through `ui.screens`, plus chat list and settings header slots and
  plugin-owned screens;
- repository browsing, update checks with permission diff, changelog and signed
  revocations;
- read API v1 for accounts, chats and messages; lifecycle, account, chat, theme and
  message events; outgoing text interceptor;
- first-frame safe mode, crash attribution, permission revocation and plugin logs.

Theme packages are removed. There is no `kind: "theme"`, no `theme/theme.json`, no theme
preview and no theme catalog. A code plugin with `ui.appearance` is the only theme
provider.

The maximum-capability slice adds the TypeScript/hybrid contract, declarative UI,
resource overrides, message/chat/admin capabilities, automation, HTTP/media/
notifications, the internal-access artifact and the TypeScript SDK/CLI toolchain. See
[typescript.md](/typescript/), [capabilities.md](/capabilities/),
[declarative-ui.md](/declarative-ui/), [resources.md](/resources/),
[automation.md](/automation/) and [internal-api.md](/internal-api/). The QuickJS
runtime is compiled into the app and wired to the host bridge.
On-device runtime checks, the broad instrumentation suite and custom repositories remain
release gates. The GitHub-based repository tooling lives in
[distribution.md](/distribution/) and the separate `nextgram-plugins` repository.

The platform is usable for testing Java/Kotlin plugins with appearance and screen
replacement. `assembleRelease` with R8 passes; the remaining release gates in
[roadmap.md](/roadmap/) are device-specific checks, the first published catalog and an
external security review.

## Trying the current implementation

1. Build the app: `./gradlew :TMessagesProj_App:assembleDebug --offline`.
2. Build the sample plugins:
   `docs/plugins/tools/build-ngp.sh docs/plugins/examples/hello-plugin hello.ngp`, plus
   the `appearance-plugin` and `screen-plugin` demos under `docs/plugins/examples/`.
   The tool compiles the sources, produces DEX at `--min-api 23` and signs the package;
   see [examples/README.md](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/examples/README.md).
3. Install the APK and open the `.ngp` from a file manager, from a chat document or
   through **NextGram Settings → Plugins → Install from file**. The install screen
   lists the publisher key fingerprint, version, permissions and the trusted-code
   warning before anything is written.
4. Enable the plugin in the plugin manager, then open its settings screen from the
   manager or from the contributed row in NextGram Settings. Code plugins ask for a
   restart; contributions appear after the next boot.
5. Disable, re-enable or uninstall from the manager. Three caught failures disable a
   plugin; two interrupted boots enable safe mode, which skips external code.

The repository browser is shipped and uses the signed official catalog. Chat
document, file manager, share sheet and **Install from file** remain supported
fallbacks.

Tests: `./gradlew :TMessagesProj:testDebugUnitTest --offline --tests
'dev.nextgram.plugin.*'` covers manifest validation, archive attacks, parser fuzzing,
signature and path verification, installer rollback, revocation, appearance mapping,
screen registries, repository indexes and performance smoke checks.

## The idea

Everything is a plugin.

- The core kernel provides only what cannot be replaced safely: process lifecycle,
  authentication, MTProto, storage, crypto, calls, media pipeline, navigation shell
  and the plugin runtime.
- Every feature that can be isolated safely is a plugin. Built-in features are
  compiled into the APK and use the same contracts as external plugins. Most of them
  can be disabled.
- External plugins are distributed as `.ngp` files. A plugin can be sent to a chat,
  downloaded from a catalog or opened from a file manager, then installed after an
  explicit confirmation.
- Plugins are written in Kotlin or Java, compiled to DEX and loaded at runtime.
  Simpler plugins can be written in TypeScript and run inside a sandboxed JavaScript
  engine. Appearance and screen replacement are code-plugin capabilities, not separate
  package kinds.

This is a platform, not a bag of Xposed hooks. The public API is typed, versioned and
does not expose `org.telegram.*` internals. Upstream Telegram code is touched only at
a small number of reviewed seams.

## Plugin kinds

| Kind | Author writes | Payload | Runtime | UI | Status |
| --- | --- | --- | --- | --- | --- |
| `java` (`code`) | Kotlin or Java | `android/dex/classes.dex` | Isolated `DexClassLoader` | Native `View`, declarative tree, appearance, screens, slots | Implemented |
| `ts` (`script`) | TypeScript | `script/main.js` | QuickJS context, host bridge | Declarative UI, Canvas, screens, slots | Shipped: SDK, CLI, verifier, QuickJS runtime and bridge; on-device checks are a release gate |
| `hybrid` | TypeScript + Java | both payloads | QuickJS plus `DexClassLoader` native module | TypeScript is primary; Java supplies native methods | Shipped: SDK, CLI, verifier, QuickJS runtime and native-module loader; on-device checks are a release gate |

`java` is an alias of `code`; `ts` is an alias of `script`. New packages and docs use
the new names, and the old names remain accepted forever in v1.

Both use the same `.ngp` container and the same manifest. The `kind` field selects the
payload. A code plugin declares `ui.appearance` to apply a theme and `ui.screens` to
replace a screen. There is no theme kind and no theme payload. A future desktop client
can add a platform payload without changing the container format.

TypeScript is a source language, not a runtime format. A script plugin is compiled to
`script/main.js` at build time; the `.ngp` file contains JavaScript, not `.ts` sources.
The client does not ship a TypeScript compiler.

## Baseline decisions

| Topic | Decision |
| --- | --- |
| Runtime loading | External code is loaded at runtime from `.ngp`; no rebuild required |
| Built-in features | Compiled into the APK, registered through the same plugin contracts |
| Code format | DEX, one `classes.dex` per plugin in v1, no native libraries |
| Script format | TypeScript compiled to a single JavaScript bundle, executed by QuickJS with a JSON host bridge |
| Appearance | Code plugin with `ui.appearance`; semantic tokens, raw keys and custom colors; no theme kind |
| Screen replacement | Code plugin with `ui.screens`; host-owned overlay on five screens; protected surfaces stay stock |
| API style | Typed extension points, events, contributions and services; no reflection hooks |
| API versioning | Versioned package `dev.nextgram.plugin.v1`, semver, binary compatibility |
| Package format | ZIP container, `.ngp`, MIME `application/vnd.nextgram.plugin+zip` |
| Signing | Mandatory for normal installs, self-signed identity, key pinned per plugin ID |
| Permissions | Declared in the manifest, granted by the user, enforced by the host API |
| Sandbox | Script plugins are sandboxed; DEX plugins are trusted code, not sandboxed |
| DEX default | Code plugins are allowed by default with an explicit trusted-code warning |
| Secret chats | API-filtered and excluded from screen providers; a malicious DEX plugin can still reflect |
| SDK license | GPL-3.0 with a plugin-linking exception; exact legal wording under review |
| Install/update | Restart required for code plugins; appearance and screen providers apply at runtime |
| Distribution | GitHub repository with a signed index; chat and file install remain supported |
| Updates | Opt-in manual or daily check against the index; never silent |
| Artifacts | `.ngp` files in GitHub Releases; the repository keeps source, metadata and icons |
| Desktop | Android first; container and manifest are platform-neutral |
| Upstream | Thin seams only; feature logic lives in `dev.nextgram.*` packages |

## Why DEX plugins are not sandboxed

On Android, an in-process `DexClassLoader` plugin has the same access as the host app.
It can use reflection, open sockets, read app-private files and call hidden APIs.
Permissions can only gate the host SDK calls; they cannot stop malicious code.

The design is honest about this:

- Installing a DEX plugin is equivalent to installing a trusted modification. The
  install screen says so.
- DEX plugins are allowed by default, and the plugin manager can disable all external
  code plugins. The warning is not hidden behind a developer setting.
- Plugins are signed, and updates must use the same signing key.
- Secret chats, authentication, passcode, payments and the plugin installer itself are
  protected surfaces. Their data and UI are not exposed through the API, and screen
  providers never resolve for them. A malicious DEX plugin can still attempt reflection;
  that residual risk is documented.
- The official catalog can mark reviewed plugins, but no badge is a guarantee.
- Script plugins are the safer tier for untrusted authors: QuickJS has no Android
  bindings and every capability goes through the host bridge.

See [security.md](/security/) for the full threat model.

## Documents

| Document | Contents |
| --- | --- |
| [architecture.md](/architecture/) | Kernel, lifecycle, class loading, seams, built-in plugins, threading, failure isolation |
| [package-format.md](/package-format/) | `.ngp` container, manifest, signing, validation, install and update flows, chat integration |
| [sdk.md](/sdk/) | Public API, extension points, UI model, events, services, permissions, script API, versioning |
| [themes.md](/appearance/) | Appearance API for code plugins: tokens, raw keys, custom colors, apply/reset, safe mode |
| [typescript.md](/typescript/) | TypeScript as the primary plugin language: SDK, CLI, bundle, sandbox, hybrid packages |
| [declarative-ui.md](/declarative-ui/) | Node model, styling tokens, Canvas, accessibility, screens and slots |
| [capabilities.md](/capabilities/) | Messages, chats, chat admin, HTTP, media, notifications, events and interceptors |
| [resources.md](/resources/) | Fonts, sounds, wallpaper, icons, strings, haptics, motion and chrome |
| [automation.md](/automation/) | Rules, triggers, filters, actions, rate limits, audit and confirmation |
| [internal-api.md](/internal-api/) | Trusted Java/hybrid access to the unstable internal facade |
| [screens.md](/screens/) | Screen replacement, catalogue keys, contexts, slots, protected surfaces, kill switch |
| [security.md](/security/) | Threat model, trust boundaries, protected surfaces, permissions, safe mode, plugin policy |
| [distribution.md](/distribution/) | GitHub plugin repository, catalog index, artifact layout, moderation and updates |
| [roadmap.md](/roadmap/) | Phases, deliverables, acceptance criteria, risks and open questions |
| [release-notes.md](/release-notes/) | Shipped feature set, build, packaging, publishing and verification checklist |
| [schema/plugin.schema.json](/schema/plugin.schema.json) | JSON Schema for `plugin.json` |
| [examples/hello-plugin/plugin.json](/examples/hello-plugin/plugin.json) | Minimal code plugin manifest |

## Vocabulary

- **Kernel** — the always-present host: boot, registry, installer, class loading,
  permissions, hooks, services, storage and recovery.
- **Built-in plugin** — a feature compiled into the APK. It uses the plugin contracts
  and appears in the plugin manager. Some built-ins are critical and locked.
- **External plugin** — a plugin loaded from an `.ngp` package at runtime.
- **Package** — one `.ngp` file.
- **Plugin ID** — immutable reverse-DNS identifier, for example `dev.example.hello`.
- **Contribution** — a declared UI or behavior item: settings screen, menu action,
  toolbar action, decorator.
- **Service** — a replaceable implementation of a host-defined interface.
- **Seam** — a small adapter in upstream Telegram code that calls the kernel. Seams are
  the only places where upstream files are modified.
- **Protected surface** — a screen or data set that third-party plugins cannot access:
  authentication, passcode, payments, secret chats, plugin trust UI, plugin manager,
  safe mode and calls.
- **Screen key** — one of the five host screens a plugin may replace: `CHAT_LIST`,
  `CHAT`, `SETTINGS`, `PROFILE`, `MAIN_NAVIGATION`.
- **Overlay** — the host-owned `FrameLayout` that holds a plugin screen over the stock
  fragment. The stock fragment and navigation stack remain.

## Open questions

- The exact legal wording of the GPL-3.0 plugin-linking exception.
- Catalog governance: who reviews "verified" plugins and how takedowns are handled.
- Custom repositories: trust-on-first-use or an explicit key import flow. Deferred to
  the next release; v1 uses the official catalog only.
- Per-screen theme isolation for protected surfaces. The current `.attheme` is global.
- Whether chat media, calls and payments should ever be exposed to a replaced `CHAT`
  screen. The current default is no.
- Whether a future upstream drawer should add `ScreenKey.DRAWER`. There is no drawer in
  this tree, so no key exists.
