# `.ngp` Package Format

`.ngp` stands for **NextGram Plugin**. One file is one plugin. The extension is
short, easy to send in a chat and easy to type. It is also the extension of Neo Geo
Pocket ROMs, so the client never trusts the extension alone: a valid package must be a
ZIP with a valid `plugin.json` and a valid signature. The MIME type is
`application/vnd.nextgram.plugin+zip` with `application/x-nextgram-plugin` accepted as
an alias.

The extension is a hint, not a security boundary. A package renamed to `.zip` still
installs through the plugin manager's file picker. Chat auto-detection uses the
extension, so a renamed file may need the picker instead of a direct tap.

## 1. Container

An `.ngp` file is a ZIP archive:

- UTF-8 entry names, forward slashes only;
- no encryption, no ZIP64 requirement, no multi-volume archives;
- deflate or stored compression only;
- CRC32 present and checked;
- no symlinks, no absolute paths, no `..` segments, no drive letters, no backslashes;
- no duplicate names, including case-insensitive duplicates;
- no directory entries; every entry is a file;
- `META-INF/` is reserved for the signature.

### 1.1 Layout

```
plugin.json                     required, package manifest
LICENSE                         optional, recommended
CHANGELOG.md                    optional, shown on update
README.md                       optional, shown in plugin details

android/
  dex/
    classes.dex                 required for kind=code/java and kind=hybrid

script/
  main.js                       required for kind=script/ts and kind=hybrid

assets/
  icon.png                      required, referenced by manifest
  screenshots/...               optional, referenced by manifest
  ...                           plugin assets (images, fonts, wallpapers)

i18n/
  en.json                       optional localization for declarative UI

META-INF/
  MANIFEST.MF                   JAR manifest with SHA-256 digests
  NGP.SF                        signature file
  NGP.RSA or NGP.EC             PKCS#7 signature block
```

Allowed root entries are exactly: `plugin.json`, `LICENSE`, `CHANGELOG.md`,
`README.md`, `android/`, `script/`, `assets/`, `i18n/`, `META-INF/`.
Anything else is rejected. Future format versions may add entries; a v1 client rejects
unknown entries instead of guessing.

`code`/`java` packages must not contain `script/`; `script`/`ts` packages must not
contain `android/`. Only `hybrid` contains both payloads. This keeps the trust decision
simple: a sandboxed script package cannot hide code, and a hybrid package is explicitly
marked as trusted code with a TypeScript entry point.

### 1.2 Limits

| Item | Limit |
| --- | --- |
| Package file | 64 MB |
| Uncompressed total | 192 MB |
| Entries | 4096 |
| Single entry | 64 MB |
| Compression ratio | 200:1 per entry |
| `plugin.json` | 256 KB |
| `classes.dex` | 32 MB |
| `script/main.js` | 8 MB |
| Icon | 2 MB, max 1024x1024 |
| Screenshot | 4 MB each, max 6 |
| `i18n` file | 128 KB each, max 20 locales |

The verifier checks these limits against the central directory before extracting a
single byte. A package that declares a larger uncompressed size is rejected even if the
compressed file is small.

### 1.3 Prohibited content

- Native libraries: any `*.so`, `*.dylib`, `*.dll`, or `lib/` entry.
- Nested `.ngp`, `.apk`, `.jar`, `.dex` outside the declared payload, and any entry
  whose content starts with a ZIP, GZIP, 7z, RAR, XZ or BZIP2 signature.
- Executable scripts (`.sh`, `.bat`, `.cmd`, `.ps1`).
- XML vector drawables, SVG, HTML and JavaScript outside `script/main.js`.
- Any file under `META-INF/` other than the three signature files.
- DEX files outside `android/dex/classes.dex`.
- Paths that are not NFC-normalized.

Assets are data. The host may decode images and fonts, but never executes an asset.

## 2. Manifest

`plugin.json` is UTF-8 JSON. Unknown fields are ignored in v1 for forward
compatibility, except unknown permissions and unknown payload paths, which are
rejected. The formal schema is
[schema/plugin.schema.json](/schema/plugin.schema.json).

### 2.1 Required fields

| Field | Type | Rules |
| --- | --- | --- |
| `format` | string | Exactly `"ngp"` |
| `formatVersion` | integer | `1` in this spec |
| `id` | string | Reverse-DNS, lowercase, 3–128 chars, immutable |
| `name` | string | 1–64 chars, English/default name |
| `version` | string | Semver, for example `1.2.0` |
| `versionCode` | integer | Positive, monotonic per plugin ID |
| `kind` | string | `code`, `script`, `java`, `ts` or `hybrid`; `java` is an alias of `code`, `ts` is an alias of `script` |
| `api` | integer | Public SDK major version, `1` in this spec |
| `platforms` | array | `["android"]`, `["desktop"]` or `["*"]` for script |
| `description` | string | 1–2000 chars |
| `author` | object | `name` required, `telegram` and `url` optional |
| `license` | string | SPDX identifier or `LicenseRef-Proprietary` |
| `icon` | string | Path under `assets/` |
| `permissions` | array | Known permission names, may be empty |

Kind-specific fields:

| Kind | Field | Rules |
| --- | --- | --- |
| `code` / `java` | `entrypoints.android` | Class that implements `NextGramPlugin` |
| `script` / `ts` | `script` | Exactly `script/main.js` |
| `hybrid` | `script`, `entrypoints.android` | `script/main.js` is the primary entry point; the class implements `NextGramNativeModule` |
| `hybrid` | `nativeMethods` | Optional method allowlist; each name matches `^[a-zA-Z][a-zA-Z0-9_]{0,63}$`. Missing entries make `ctx.native.call` fail closed |
| all | `resources` | Optional declared resource kinds for consent and validation: `font`, `sound`, `wallpaper`, `icon`, `strings`, `haptics`, `motion`, `chrome` |

### 2.2 Optional fields

| Field | Type | Purpose |
| --- | --- | --- |
| `minHost` | string | Semver range, for example `">=13.4.0"`. Required for `script`/`ts`/`hybrid` and for any capability added after API 1 (resources, automation, chat admin, internal access) |
| `maxHost` | string | Semver range, for example `"<14.0.0"` |
| `homepage` | string | HTTPS URL |
| `source` | string | HTTPS URL to source code |
| `support` | string | HTTPS URL or `https://t.me/...` |
| `changelog` | string | Path to a changelog file, default `CHANGELOG.md` |
| `screenshots` | array | Up to 6 asset paths |
| `dependencies` | array | Plugin dependencies with semver ranges |
| `conflicts` | array | Plugin IDs that cannot be enabled together |
| `provides` | array | Service keys for documentation and dependency checks |
| `update` | object | Reserved and ignored in v1. The repository index is the update source |
| `localization` | object | Locale overrides for `name` and `description` |
| `experimental` | boolean | Show an "experimental" badge |
| `deprecated` | boolean | Show a deprecation warning |

### 2.3 Example: code plugin

```json
{
  "format": "ngp",
  "formatVersion": 1,
  "id": "dev.example.hello",
  "name": "Hello NextGram",
  "version": "1.0.0",
  "versionCode": 1,
  "kind": "code",
  "api": 1,
  "minHost": ">=13.4.0",
  "platforms": ["android"],
  "entrypoints": {
    "android": "dev.example.hello.HelloPlugin"
  },
  "description": "A minimal plugin that adds a settings screen and a message action.",
  "author": {
    "name": "Example Author",
    "telegram": "@example"
  },
  "license": "GPL-3.0-or-later",
  "icon": "assets/icon.png",
  "screenshots": ["assets/screenshots/settings.webp"],
  "permissions": ["ui.settings", "ui.chat", "messages.read"],
  "dependencies": [],
  "localization": {
    "ru": {
      "name": "Hello NextGram",
      "description": "Минимальный плагин с экраном настроек и действием в меню сообщения."
    }
  }
}
```

### 2.4 Example: script plugin

```json
{
  "format": "ngp",
  "formatVersion": 1,
  "id": "dev.example.quicktranslate",
  "name": "Quick Translate",
  "version": "0.3.0",
  "versionCode": 3,
  "kind": "script",
  "api": 1,
  "platforms": ["*"],
  "script": "script/main.js",
  "description": "Adds a translate action for selected messages.",
  "author": {"name": "Example Author"},
  "license": "MIT",
  "icon": "assets/icon.png",
  "permissions": ["ui.chat", "messages.read", "network"]
}
```

### 2.5 ID rules

`id` matches:

```text
^[a-z][a-z0-9]*(\.[a-z0-9][a-z0-9_-]*)+$
```

Rules:

- lowercase only;
- at least two segments;
- each segment starts with a letter or digit;
- hyphens and underscores are allowed after the first character;
- 3–128 characters total;
- `app.nextgram.*` is reserved for official built-in plugins; an external package with
  that prefix is rejected;
- the ID is immutable for the lifetime of the plugin;
- changing the ID creates a different plugin with separate storage and permissions.

## 3. Signature

Every normal install requires a valid signature. Unsigned packages are accepted only
in developer mode and carry a permanent warning badge.

### 3.1 Scheme

The package uses standard JAR signing:

- `META-INF/MANIFEST.MF` contains a SHA-256 digest for every entry.
- `META-INF/NGP.SF` contains the digest of the manifest.
- `META-INF/NGP.RSA` or `META-INF/NGP.EC` contains the PKCS#7 signature block.
- The signing certificate is self-signed. Identity is the SHA-256 fingerprint of the
  DER certificate, not a public CA.
- Supported keys: RSA 2048+ with `SHA256withRSA`, or EC P-256+ with
  `SHA256withECDSA`. DSA and MD5/SHA-1 signatures are rejected.
- Exactly one signer. Multiple signatures are rejected.
- Every entry except the signature files must be signed. Unsigned entries are
  rejected.
- The certificate may be expired; expiration does not invalidate the identity, because
  the fingerprint is pinned. The plugin details screen shows the validity dates.
- The certificate subject CN is shown next to the manifest author. A mismatch is a
  visible warning, not a hard block; the signing key is the identity.

JAR signing was chosen over APK Signature Scheme v2 because an `.ngp` is not an APK,
and JAR signing is portable to a future desktop client. JAR signing does not protect
ZIP metadata, so the verifier separately rejects duplicate entries, path tricks,
unknown `META-INF` files and entries that are not covered by the manifest.

### 3.2 Verification order

The installer never parses plugin-provided JSON or DEX before the structure is safe:

1. Copy the source to a private staging file, enforcing the size limit while copying.
2. Open the ZIP, enumerate entries, reject duplicates and unsafe names.
3. Sum uncompressed sizes, check limits and compression ratios.
4. Verify the JAR signature and that every entry is signed.
5. Read the signer certificate; compute the SHA-256 fingerprint.
6. Extract `plugin.json` with a size limit; parse and validate it.
7. Check `format`, `formatVersion`, `kind`, `api`, `platforms`, `minHost`/`maxHost`.
8. Check kind-specific payloads.
9. Check signature identity against an existing installation of the same ID.
10. Check dependencies, conflicts and permissions.
11. Show the consent screen.
12. Install atomically and write the registry.

If any step fails, the staging file is deleted and nothing is registered.

### 3.3 Update identity

- Same `id` + same certificate fingerprint = update.
- Same `id` + different fingerprint = rejected. The user must uninstall the old
  plugin first; its data is wiped unless it was exported.
- `versionCode` must be strictly greater than the installed version. Downgrades are
  rejected outside developer mode.
- A failed update leaves the previous version installed, enabled and loadable. A
  successful update replaces the previous payload; manual downgrade is not offered.
- New permissions require a new consent. If the user declines, the update is canceled.
- A package with the same `versionCode` but different content is rejected.

### 3.4 Key rotation

Not supported in v1. A future version will allow a manifest statement signed by the old
key that authorizes a new key. Until then, key rotation means a new plugin ID or a
reinstall with data loss.

## 4. Validation details

### 4.1 Manifest

- JSON depth is limited; the parser rejects deeply nested input.
- Duplicate keys are rejected.
- `formatVersion` greater than the supported version produces "Update NextGram to
  install this plugin".
- Unknown permissions are rejected, not ignored. A plugin that requires a permission
  from a newer host cannot install on an older host; `minHost` should prevent this.
- `minHost` and `maxHost` are semver ranges. A malformed range rejects the package.
- URLs must be HTTPS. `http://` and custom schemes are rejected.
- Localization locales are BCP-47 tags. The host falls back to the default name and
  description, then to English.
- Paths are relative, NFC-normalized, use forward slashes, and must exist in the
  package. `icon` must be a PNG or WebP image.

### 4.2 DEX

- Magic: `dex\n` followed by version `035`–`039`.
- File size limit 32 MB.
- One `classes.dex`; no `classes2.dex` in v1.
- DEX is compiled with `--min-api 23`.
- No native libraries.
- No classes in `android.*`, `java.*`, `javax.*`, `dalvik.*`, `org.telegram.*` or
  `dev.nextgram.plugin.v1.*` may be defined by the plugin. The class loader enforces
  parent-first delegation for those packages.
- The entry class exists, is public, has a public no-arg constructor and implements
  `NextGramPlugin`.
- The entry class name must survive plugin minification. The official Gradle plugin adds
  the keep rule automatically; a plugin that minifies without it fails at load time
  with a clear error.

### 4.3 Script and TypeScript

Script packages install, enable, disable and update without a process restart.

- `script/main.js` is checked at install time and parsed by QuickJS when the plugin is
  loaded. A syntax error rejects the install; a runtime parse error disables the plugin
  and is reported in the logs.
- The bundle is a single IIFE. It must not import files, use `fetch`,
  `XMLHttpRequest`, `WebSocket`, `require` or Node APIs. The QuickJS context provides
  only the `__ngp` bridge.
- Top-level code must terminate within 1 s and allocate less than 32 MB. The plugin is
  interrupted and disabled otherwise.
- Source maps are not loaded by the client.
- Every plugin gets its own QuickJS context on a dedicated thread with a 32 MB heap and a 6 MB stack. Values cross
  the bridge as UTF-8 JSON, with a 1 MB request and a 4 MB response limit.
- The declarative tree, Canvas display list and bridge payloads are bounded before they
  reach the host.

### 4.4 Hybrid

A hybrid package contains both `script/main.js` and `android/dex/classes.dex`.

- TypeScript is the primary entry point. The class in `entrypoints.android` implements
  `NextGramNativeModule`, not `NextGramPlugin`.
- `nativeMethods` is the manifest allowlist. `methods()` must register an intersecting
  set; a call to a method present in only one list fails closed.
- Arguments and return values are JSON values. A call is limited to 5 s; a timeout is
  fatal for the hybrid plugin.
- The package is trusted code because of its DEX payload. The install screen shows both
  the TypeScript sandbox badge and the trusted-code warning.
- Changing the DEX needs a restart; a TypeScript-only change can be hot-reloaded in
  developer mode.

### 4.5 Unsupported kinds

`kind: "theme"` is not a package kind in format version 1. The manifest parser and the
verifier reject it with `E_UNSUPPORTED_KIND` and the message:

> Theme packages are no longer supported. Ship a code plugin with the ui.appearance permission.

A code plugin declares `ui.appearance` and applies an `AppearanceTheme` at runtime. There
is no `theme/` payload root and no `theme` manifest field. A code plugin may combine
appearance, screen replacement, settings and actions in one package.

Existing packages with `kind: "code"` or `kind: "script"` keep their layout. A plugin
source that referenced `PluginKind.THEME` must be rebuilt against the current SDK.

### 4.6 Assets

- Images are decoded with bounds-only options first. Dimensions and pixel count are
  capped.
- Animated WebP and GIF are allowed only as icons/screenshots if the decoder supports
  them; otherwise the first frame is used.
- Fonts are copied to the plugin cache and loaded by path. They are never loaded from
  the package file directly.
- No asset is executed, reflected or treated as a class.

## 5. Installation

### 5.1 Sources

1. **Chat document** — a `.ngp` file sent in a Telegram chat. Tapping it opens the
   installer. If the file is not downloaded yet, the app downloads it first.
2. **File manager** — `ACTION_VIEW` with a `content://` or `file://` URI, matched by
   MIME or `.ngp` path.
3. **Share sheet** — `ACTION_SEND` with a stream or `ClipData` that is clearly a
   plugin package. Implemented.
4. **Plugin manager → Install from file** — a SAF picker that accepts any file and
   sniffs the ZIP and manifest. This is the fallback when another app sends
   `application/octet-stream` and the share sheet does not match.
5. **GitHub repository** — the Repository screen downloads a package from a signed
   index. Implemented.
6. **Update check** — a package downloaded from the repository index. Implemented.

Every source goes through the same verifier and consent screen. There is no
"install silently" path except a developer-mode adb command. Chat documents, file
managers, the share sheet and the file picker are implemented today.

### 5.2 Chat document integration

Upstream has a single document-opening choke point:
`AndroidUtilities.openDocument(MessageObject, Activity, BaseFragment)`. The seam:

1. If the file name ends with `.ngp` (case-insensitive), route to
   `PluginInstallCoordinator`.
2. If the file exists, open the installer.
3. If not, start the normal document download, show progress, and open the installer
   when complete.
4. Keep the message id and source chat in the install request so the consent screen can
   show where the file came from.
5. If the package is invalid, show a specific error instead of a generic "no app found".

`AndroidUtilities.openForView` handles the same detection for files opened from the
downloads screen or shared from another app.

The message context menu gets a core "Install plugin" item for `.ngp` documents. This
is kernel UI, not a plugin contribution. A richer in-bubble plugin card can be added
later without changing the package format.

Files received in secret chats are an exception: the in-chat installer is disabled so
that the secret chat surface does not feed the plugin trust UI. The user can explicitly
save the file and install it through the plugin manager's file picker. The installer
does not store the secret chat id or title.

### 5.3 Consent screen

The installer shows:

- icon, name, version, author and source;
- package size and SHA-256 hash;
- signing key fingerprint, shortened and copyable;
- permissions grouped by risk, with plain-language explanations;
- dependency status;
- changelog for updates;
- for code plugins: a permanent warning that the plugin runs as trusted code and can
  access data outside the permission API;
- for unsigned developer packages: a red "unsigned" warning;
- "Install", "Cancel", and for updates "Update".

Low-risk UI permissions may be pre-selected. Message, contact, media, notification,
account and background permissions are off by default and require an explicit toggle.
Because DEX plugins are not sandboxed, the toggles are a contract and a transparency
mechanism, not a security boundary. The warning says this directly.

### 5.4 Atomic install

```
files/plugins/<id>/
  <versionCode>/
    package.ngp          original package, for sharing and reinstall
    payload/             extracted and read-only payload
  current -> <versionCode>   (logical pointer in the registry, not a symlink)
```

Steps:

1. Extract into `files/plugins/.staging/<uuid>/`.
2. Validate the extracted payload again (DEX magic, assets, paths).
3. Set payload files read-only.
4. Move the staging directory to `files/plugins/<id>/<versionCode>/`.
5. Write a new registry file to a temporary path, `fsync`, then rename it over
   `plugins/index.json`.
6. Mark the plugin "pending restart" for code packages.
7. If any step fails, delete the staging directory and leave the old version active.

The registry is app-private and not signed. It stores the installed hashes, key
fingerprints, grants, enabled state and crash counters. On each boot, the kernel
re-hashes the manifest and DEX payload before loading. A mismatch disables the plugin
and asks the user to reinstall; it is treated as corruption or tampering, not as a
reason to execute the changed code.

### 5.5 Enable, disable, uninstall

- **Enable** requires a restart for code packages. The plugin is marked pending until the
  next boot.
- **Disable** unregisters contributions and services immediately and prevents the
  plugin from loading on the next boot. The class loader stays until the process dies.
- **Uninstall** disables the plugin and removes its package. The user chooses whether to
  keep data. Keeping data is useful for reinstalling the same plugin with the same key.
- A plugin with a different key cannot reuse data; it is wiped.
- Core system plugins cannot be uninstalled or disabled.

### 5.6 Updates

- Manual check in the plugin manager.
- Optional automatic check, off by default. When enabled, it runs at most once per day
  over HTTPS, with no identifiers beyond the request itself.
- Updates are resolved from the signed repository index. The index entry for the
  installed plugin ID supplies the next `versionCode`, `downloadUrl`, `sha256` and
  package signature fingerprint.
- The host checks `id`, `versionCode`, `api`, `minHost`, `sha256` and the package
  signature, then shows the normal consent screen with a permission diff.
- The update is never installed silently.
- If the package or index check fails, the plugin stays on the current version and the
  error is shown in the plugin details.
- A per-plugin update endpoint is not required in v1. The repository index is the
  update source; see [distribution.md](/distribution/).

## 6. Catalog and repository

Distribution uses a GitHub repository with a signed catalog index. GitHub is a
transport, not a trust anchor. The full layout, index schema, moderation flow and
update flow are in [distribution.md](/distribution/).

Package-level invariants:

- `index.json` is accompanied by `index.sig`, an ECDSA P-256 signature over the exact
  bytes of `index.json`.
- The official repository key is pinned in the app. Custom repositories are not part
  of v1; the app uses the official catalog only.
- Only the official index can mark a plugin `verified`. The badge means "reviewed by
  the NextGram maintainers", not "safe".
- The app refreshes the index on user action or on an opt-in schedule. It sends no
  analytics and no account identifier.
- Download URLs must be HTTPS and immutable, either a GitHub Release asset or a
  commit-pinned raw path. The SHA-256 in the index must match the downloaded bytes.
- The package signature is checked as usual. The index cannot grant trust to a package
  signed by a different key than the installed one.
- A missing or invalid index signature fails closed: no package from that index is
  offered.

## 7. Versioning and evolution

- `formatVersion` describes the container. The v1 client supports exactly `1`.
- `api` describes the public SDK. A v1 client supports exactly API major `1`.
- The appearance and screen API is a pre-release hard break: `formatVersion` and `api`
  remain `1`, `PluginKind.THEME` and `kind: "theme"` are removed, and a source that
  referenced them must be rebuilt. Existing code packages remain installable.
- `minHost`/`maxHost` describe the NextGram app version. They are optional but
  recommended.
- Additive manifest fields are ignored by older clients.
- New permissions are rejected by older clients, because silently dropping a permission
  would change plugin behavior.
- New payload kinds are rejected by older clients.
- The client supports the current and previous format version for at least one release
  after a bump.

## 8. Error catalogue

| Code | User-facing meaning |
| --- | --- |
| `E_NOT_ZIP` | The file is not a valid plugin package |
| `E_FORMAT` | Unsupported package format |
| `E_MANIFEST` | The manifest is missing or invalid |
| `E_SIGNATURE` | The signature is missing, invalid or not trusted for this update |
| `E_UNSIGNED` | Unsigned packages are disabled outside developer mode |
| `E_TOO_LARGE` | The package exceeds the size limits |
| `E_UNSAFE_PATH` | The package contains an unsafe path |
| `E_DUPLICATE_ENTRY` | The package contains duplicate entries |
| `E_UNSUPPORTED_API` | The plugin requires a newer NextGram |
| `E_PLATFORM` | The plugin does not support Android |
| `E_PAYLOAD` | The payload is missing or invalid |
| `E_DEX` | The code payload is not valid DEX |
| `E_SCRIPT` | The script failed to compile or initialize |
| `E_UNSUPPORTED_KIND` | `kind: "theme"` was removed; the message says `Theme packages are no longer supported. Ship a code plugin with the ui.appearance permission.` |
| `E_DEPENDENCY` | A required plugin is missing or has the wrong version |
| `E_CONFLICT` | The plugin conflicts with an installed plugin |
| `E_PERMISSION` | The plugin requests an unknown permission |
| `E_KEY_MISMATCH` | The update is signed by a different key |
| `E_DOWNGRADE` | The update is older than the installed version |
| `E_IO` | The package could not be stored |
