From 2a8dba481818fefb4a77de752c9c554124c187cc Mon Sep 17 00:00:00 2001 From: ryan-wong-coder Date: Fri, 17 Jul 2026 13:31:36 +0800 Subject: [PATCH] feat(plugins): add plugin contract and SDK --- docs/plugin-platform/contract-and-sdk.md | 162 +++ docs/plugin-platform/threat-model.md | 146 +++ .../generated/plugin-contract.schema.json | 1100 +++++++++++++++++ eslint.config.js | 2 +- examples/plugins/hello-netcatty/README.md | 12 + .../hello-netcatty/netcatty.plugin.json | 58 + examples/plugins/hello-netcatty/package.json | 12 + examples/plugins/hello-netcatty/src/index.ts | 9 + examples/plugins/hello-netcatty/tsconfig.json | 13 + package-lock.json | 164 ++- package.json | 12 +- packages/plugin-cli/package.json | 29 + packages/plugin-cli/src/archive.ts | 535 ++++++++ packages/plugin-cli/src/cli.test.ts | 173 +++ packages/plugin-cli/src/cli.ts | 64 + packages/plugin-cli/src/commands.ts | 136 ++ packages/plugin-cli/src/constants.ts | 14 + packages/plugin-cli/src/index.ts | 22 + packages/plugin-cli/src/manifest.ts | 144 +++ packages/plugin-cli/src/packagePath.ts | 52 + packages/plugin-cli/tsconfig.build.json | 17 + packages/plugin-contract/package.json | 25 + .../schema/plugin-contract.schema.json | 553 +++++++++ packages/plugin-contract/src/contract.test.ts | 92 ++ .../src/generated/plugin-contract.ts | 247 ++++ packages/plugin-contract/src/index.ts | 5 + packages/plugin-contract/tsconfig.build.json | 16 + packages/plugin-sdk/package.json | 20 + packages/plugin-sdk/src/index.test.ts | 56 + packages/plugin-sdk/src/index.ts | 183 +++ packages/plugin-sdk/tsconfig.build.json | 16 + scripts/generate-plugin-contract.mjs | 144 +++ 32 files changed, 4200 insertions(+), 33 deletions(-) create mode 100644 docs/plugin-platform/contract-and-sdk.md create mode 100644 docs/plugin-platform/threat-model.md create mode 100644 electron/plugins/generated/plugin-contract.schema.json create mode 100644 examples/plugins/hello-netcatty/README.md create mode 100644 examples/plugins/hello-netcatty/netcatty.plugin.json create mode 100644 examples/plugins/hello-netcatty/package.json create mode 100644 examples/plugins/hello-netcatty/src/index.ts create mode 100644 examples/plugins/hello-netcatty/tsconfig.json create mode 100644 packages/plugin-cli/package.json create mode 100644 packages/plugin-cli/src/archive.ts create mode 100644 packages/plugin-cli/src/cli.test.ts create mode 100644 packages/plugin-cli/src/cli.ts create mode 100644 packages/plugin-cli/src/commands.ts create mode 100644 packages/plugin-cli/src/constants.ts create mode 100644 packages/plugin-cli/src/index.ts create mode 100644 packages/plugin-cli/src/manifest.ts create mode 100644 packages/plugin-cli/src/packagePath.ts create mode 100644 packages/plugin-cli/tsconfig.build.json create mode 100644 packages/plugin-contract/package.json create mode 100644 packages/plugin-contract/schema/plugin-contract.schema.json create mode 100644 packages/plugin-contract/src/contract.test.ts create mode 100644 packages/plugin-contract/src/generated/plugin-contract.ts create mode 100644 packages/plugin-contract/src/index.ts create mode 100644 packages/plugin-contract/tsconfig.build.json create mode 100644 packages/plugin-sdk/package.json create mode 100644 packages/plugin-sdk/src/index.test.ts create mode 100644 packages/plugin-sdk/src/index.ts create mode 100644 packages/plugin-sdk/tsconfig.build.json create mode 100644 scripts/generate-plugin-contract.mjs diff --git a/docs/plugin-platform/contract-and-sdk.md b/docs/plugin-platform/contract-and-sdk.md new file mode 100644 index 000000000..5170c7256 --- /dev/null +++ b/docs/plugin-platform/contract-and-sdk.md @@ -0,0 +1,162 @@ +# Netcatty plugin contract and SDK + +Status: internal preview (`0.1.0-internal`) +Tracking issue: [#2269](https://github.com/binaricat/Netcatty/issues/2269) + +This document describes the contract delivered by phase 1 of the plugin +platform. It deliberately does not expose a plugin loader. Package installation, +runtime isolation, permissions, UI contributions, terminal providers, connection +providers, synchronization, and distribution are introduced by later phases. + +## Contract ownership + +`packages/plugin-contract/schema/plugin-contract.schema.json` is the canonical +public protocol. It uses JSON Schema 2020-12 and defines: + +- package manifests and entrypoints; +- permission declarations; +- setting, command, menu, view, and provider contributions; +- JSON-RPC requests, notifications, results, cancellation, and errors; +- stream frames and flow-control windows; +- permission requests and decisions; +- provider requests and results. + +`npm run generate:plugin-contract` derives two committed artifacts from that +file: + +1. TypeScript types exported by `@netcatty/plugin-contract`; +2. a self-contained schema bundle under `electron/plugins/generated/` for the + future host runtime. + +`npm run check:plugin-contract` compares both outputs byte-for-byte. CI can +therefore reject a schema edit whose SDK or Electron representation was not +regenerated. + +The contract is intentionally marked internal. Compatibility is not promised +until the final rollout PR freezes API 1.0. During the internal period, every +breaking change must update the schema identifier and generated artifacts in +the same commit. + +## Package layout + +A plugin is a directory with `netcatty.plugin.json` at its root. The manifest +declares one or both execution entrypoints: + +```json +{ + "manifestVersion": 1, + "id": "com.example.my-plugin", + "name": "my-plugin", + "version": "0.1.0", + "publisher": "example", + "engines": { + "netcatty": ">=0.0.0", + "api": "0.1.0-internal" + }, + "main": { + "browser": "dist/browser.js", + "node": "dist/node.js" + } +} +``` + +Paths use relative POSIX syntax. Absolute paths, drive-letter paths, +backslashes, `.` and `..` segments, Unicode normalization ambiguity, Windows +reserved names, and platform-specific trailing dots or spaces are rejected. +Every entrypoint, view document, and companion executable must exist in the +package. + +Browser and Node entrypoints express placement, not permission. The future +runtime still evaluates the manifest permissions, trust level, and user grants +before activating either entrypoint. + +## TypeScript SDK + +`@netcatty/plugin-sdk` exports the generated contract types and a small set of +lifecycle primitives: + +- `definePlugin` keeps exact plugin types while checking the activation shape; +- `DisposableStore` gives activation code one cleanup owner; +- `CancellationTokenSource` provides cooperative cancellation without exposing + host abort controllers; +- `PluginError` carries a stable machine-readable error code and JSON details; +- `PluginContext` defines storage, secret storage, logging, and subscriptions. + +The context interfaces are contracts only in phase 1. The isolated host in +phase 2 and capability brokers in phase 3 provide their implementations. + +Plugin entrypoints should return or register every acquired resource: + +```ts +import { definePlugin } from "@netcatty/plugin-sdk"; + +export default definePlugin({ + activate(context) { + context.subscriptions.add(registerSomething()); + }, +}); +``` + +Activation code must treat cancellation and deadlines as normal outcomes. +Host-side cancellation can stop waiting for a plugin but cannot forcibly unwind +arbitrary JavaScript without terminating the isolated runtime. + +## CLI + +`@netcatty/plugin-cli` supplies four commands: + +- `init` creates a minimal TypeScript plugin; +- `validate` checks a source directory or packaged archive; +- `build` validates the manifest and runs the plugin's npm build script without + a shell; +- `pack` emits a deterministic `.ncpkg` archive. + +The packer sorts UTF-8 package paths, stores fixed ZIP timestamps and file +modes, and writes entries without platform-dependent compression output. The +same files and manifest therefore produce the same archive bytes. + +Package validation rejects: + +- path traversal, absolute paths, backslashes, and case-colliding names; +- symbolic links and non-regular files; +- executable files not declared as companion executables; +- companion binaries whose SHA-256 does not match the manifest; +- duplicate entries, encrypted entries, and unsupported compression methods; +- missing entrypoints and views; +- excessive path, file, archive, or expanded-package sizes. + +These checks are repeated when reading `.ncpkg` files. Installation in phase 2 +must not trust a package merely because the publisher previously ran the CLI. + +## Compatibility rules for later phases + +The following rules are already fixed even though their implementations arrive +later: + +1. JSON Schema is the wire authority. TypeScript types alone never justify + accepting an unvalidated message. +2. Unknown manifest properties are rejected within API 0.1. This prevents a + misspelled security declaration from silently becoming ineffective. +3. Runtime RPC payloads are JSON values. Native objects, functions, Electron + handles, DOM nodes, and cyclic values cannot cross the boundary. +4. Permission declarations do not grant access. They only make a future user + grant possible. +5. Required and optional permission sets cannot overlap. +6. Secret settings cannot contain defaults in the manifest. +7. Companion executables are content-addressed and explicitly declared. +8. Cancellation identifiers and deadlines are part of the RPC contract so a + slow plugin cannot retain an unbounded host request. +9. Stream sequence numbers and receive windows are part of the public protocol; + producers must stop when the receiver's advertised capacity is exhausted. + +## Repository commands + +```bash +npm run generate:plugin-contract +npm run check:plugin-contract +npm run test:plugin-contract +npm run build:plugin-packages +``` + +The complete application checks remain mandatory because workspace and root +dependency changes affect installation and release builds. diff --git a/docs/plugin-platform/threat-model.md b/docs/plugin-platform/threat-model.md new file mode 100644 index 000000000..7731d5063 --- /dev/null +++ b/docs/plugin-platform/threat-model.md @@ -0,0 +1,146 @@ +# Plugin platform threat model + +Status: phase 1 contract baseline + +Plugins are untrusted code. A useful plugin may parse terminal output, display +content, call remote services, or ship a native companion; none of those needs +imply trust in the author's code, update server, dependencies, or account. + +This threat model records the security properties that the nine-stage platform +must preserve. Phase 1 enforces package-format properties and defines the wire +types. Later phases implement process isolation and capability mediation. + +## Protected assets + +- passwords, private keys, API keys, OTP values, and secret-setting plaintext; +- terminal input while echo is disabled or authentication is in progress; +- host addresses, usernames, notes, command history, and terminal output; +- local files and filesystem metadata outside a plugin's data directory; +- Netcatty renderer and main-process authority, Electron IPC, and Node APIs; +- other plugins' packages, storage, logs, settings, and runtime messages; +- cloud synchronization keys and provider credentials; +- the integrity and availability of terminal sessions and the Netcatty process. + +## Adversaries + +The design assumes any of the following may be hostile: + +- a locally installed plugin package; +- a plugin dependency compromised after publication; +- a publisher account or distribution server; +- a companion executable; +- remote content rendered or parsed by a plugin; +- a malformed or intentionally expensive RPC peer; +- an old package crafted to exploit a newer installer; +- an update that requests broader permissions than the installed version. + +The operating system, Electron sandbox, Netcatty application package, and user +account are trusted. A machine already controlled by malware is outside the +platform's protection boundary. + +## Package attacks + +### Archive traversal and aliasing + +ZIP entries can target an absolute path, contain `..`, use backslashes on +Windows, differ only by case, or exploit reserved device names. Extractors may +then write outside staging or overwrite a different entry. + +The contract CLI accepts one normalized POSIX spelling for each path and +rejects exact and case-folded duplicates. The phase 2 installer must run the +same validation before extraction and must extract only under a newly created +staging directory. + +### Symbolic links and executable smuggling + +A symbolic link can make an apparently safe relative path resolve outside the +package. An executable bit can also hide an undeclared native program among +ordinary assets. + +Packages cannot contain symbolic links. Executable files must appear in +`companionExecutables`; their content SHA-256 is part of the manifest. A later +signature covers both the manifest and deterministic archive. + +### Resource exhaustion + +Small compressed inputs can expand into very large outputs, or contain huge +file counts and path names. Both source packing and archive validation impose +limits on archive bytes, expanded bytes, individual files, entry count, +manifest bytes, and path bytes. The installer must enforce limits while +streaming, before committing package metadata. + +## Runtime attacks reserved for later phases + +### Renderer escape + +Normal plugins will run in a sandboxed Chromium context without Node, +`contextIsolation` bypasses, arbitrary Electron IPC, or direct access to the +application React tree and xterm instance. Plugin documents use a dedicated +protocol with a restrictive Content Security Policy. Privileged plugins run in +separate utility processes rather than the Netcatty main process. + +### Confused deputy + +A plugin may ask the host to act on another plugin, terminal, host, file, or +network origin. Every request must carry runtime identity assigned by the host; +the host must ignore plugin-supplied identity fields. Capability handlers check +the sender, active operation, declared permission, user grant, and resource +scope before using application authority. + +### Permission laundering + +A plugin could call a broadly capable built-in command or another plugin to +avoid its own permission check. Public commands therefore retain caller +identity, and capability checks occur at the final privileged boundary rather +than only in UI or command registration. + +### Secret exfiltration + +Secret values are never ordinary settings or JSON-RPC results. The credential +broker uses operation-bound, single-use leases. Terminal sensitive-input mode +bypasses third-party hooks unconditionally. Logs, diagnostics, synchronization, +and crash reports redact secret fields before persistence. + +### Denial of service + +RPC requests have deadlines and cancellation IDs. Streams have explicit byte +windows. The runtime supervisor will enforce activation and shutdown deadlines, +message-rate and memory quotas, crash quarantine, and terminal interceptor +circuit breakers. A failed plugin must not stop unrelated plugins or terminal +sessions. + +### Update substitution and rollback + +The final distribution stage uses signed repository metadata, publisher +signatures, staged health checks, atomic version switching, and rollback to the +last healthy version. Permission, API, or trust-level increases require a new +user decision; an existing grant is not silently widened. + +## Security invariants + +The platform is not ready for public enablement unless all of these hold: + +1. Ordinary plugins have no ambient Node, Electron, filesystem, network, React, + or xterm authority. +2. A declaration is not a grant, and a grant is limited to its declared + resource and lifetime. +3. No renderer means interactive permission requests fail closed. +4. Password and no-echo input never reaches plugin hooks. +5. The package installed is the package validated and, later, signed. +6. A plugin cannot address another plugin's storage or runtime by changing an + identifier in its request. +7. Plugin failure is contained and the terminal data path fails open only where + disclosure is impossible. +8. Secrets never enter manifests, package defaults, logs, diagnostics, or cloud + synchronization sidecars. +9. Unknown newer protocol versions fail closed at privileged boundaries. +10. Disabling every plugin restores the unextended Netcatty behavior and does + not impose more than the agreed terminal throughput budget. + +## Phase 1 limitations + +No plugin code is loaded by this PR. The SDK context has interfaces but no host +implementation. The schema bundle is committed for drift checking but is not +wired into Electron. This limits phase 1's attack surface to developer tooling +and package validation while allowing the runtime work to be reviewed +separately. diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json new file mode 100644 index 000000000..caf9de6bd --- /dev/null +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -0,0 +1,1100 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://netcatty.com/schemas/plugins/0.1.0-internal/plugin-contract.schema.json", + "title": "Netcatty Plugin Contract", + "description": "Canonical public contract for Netcatty plugin manifests and host RPC messages.", + "$ref": "#/$defs/PluginManifest", + "$defs": { + "JsonPrimitive": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "JsonValue": { + "oneOf": [ + { + "$ref": "#/$defs/JsonPrimitive" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/JsonValue" + } + }, + { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + } + } + ] + }, + "RelativePackagePath": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^(?!/)(?![A-Za-z]:)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*(?:^|/)\\.(?:/|$)).+$" + }, + "Identifier": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$" + }, + "PluginId": { + "type": "string", + "minLength": 3, + "maxLength": 128, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$" + }, + "LocalizedText": { + "oneOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + { + "type": "object", + "minProperties": 1, + "propertyNames": { + "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$" + }, + "additionalProperties": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + } + ] + }, + "PluginPermission": { + "type": "string", + "enum": [ + "storage", + "settings", + "commands", + "menus", + "views", + "terminal.read", + "terminal.decorate", + "terminal.complete", + "terminal.transform", + "connection", + "authentication", + "sync", + "import", + "network", + "filesystem", + "secrets", + "companion.execute" + ] + }, + "PermissionDeclaration": { + "oneOf": [ + { + "$ref": "#/$defs/PluginPermission" + }, + { + "type": "object", + "required": [ + "permission", + "resources" + ], + "properties": { + "permission": { + "$ref": "#/$defs/PluginPermission" + }, + "resources": { + "type": "array", + "minItems": 1, + "maxItems": 128, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } + }, + "reason": { + "type": "string", + "maxLength": 1024 + } + }, + "additionalProperties": false + } + ] + }, + "PermissionSet": { + "type": "object", + "properties": { + "required": { + "type": "array", + "maxItems": 64, + "items": { + "$ref": "#/$defs/PermissionDeclaration" + } + }, + "optional": { + "type": "array", + "maxItems": 64, + "items": { + "$ref": "#/$defs/PermissionDeclaration" + } + } + }, + "additionalProperties": false + }, + "PluginEntrypoints": { + "type": "object", + "properties": { + "browser": { + "$ref": "#/$defs/RelativePackagePath" + }, + "node": { + "$ref": "#/$defs/RelativePackagePath" + } + }, + "minProperties": 1, + "additionalProperties": false + }, + "PluginEngines": { + "type": "object", + "required": [ + "netcatty", + "api" + ], + "properties": { + "netcatty": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "api": { + "const": "0.1.0-internal" + } + }, + "additionalProperties": false + }, + "SettingScope": { + "type": "string", + "enum": [ + "application", + "workspace", + "host", + "session", + "device" + ] + }, + "SettingControl": { + "type": "string", + "enum": [ + "switch", + "select", + "multiselect", + "text", + "textarea", + "number", + "password", + "color", + "keybinding", + "path" + ] + }, + "SettingOption": { + "type": "object", + "required": [ + "value", + "label" + ], + "properties": { + "value": { + "type": "string", + "maxLength": 256 + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + } + }, + "additionalProperties": false + }, + "SettingContribution": { + "type": "object", + "required": [ + "id", + "label", + "control", + "scope" + ], + "properties": { + "id": { + "$ref": "#/$defs/Identifier" + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "control": { + "$ref": "#/$defs/SettingControl" + }, + "scope": { + "$ref": "#/$defs/SettingScope" + }, + "default": { + "$ref": "#/$defs/JsonValue" + }, + "secret": { + "type": "boolean", + "default": false + }, + "required": { + "type": "boolean", + "default": false + }, + "options": { + "type": "array", + "maxItems": 256, + "items": { + "$ref": "#/$defs/SettingOption" + } + }, + "minimum": { + "type": "number" + }, + "maximum": { + "type": "number" + }, + "pattern": { + "type": "string", + "maxLength": 512 + }, + "placeholder": { + "$ref": "#/$defs/LocalizedText" + }, + "when": { + "type": "string", + "maxLength": 1024 + } + }, + "additionalProperties": false + }, + "CommandContribution": { + "type": "object", + "required": [ + "id", + "title" + ], + "properties": { + "id": { + "$ref": "#/$defs/Identifier" + }, + "title": { + "$ref": "#/$defs/LocalizedText" + }, + "category": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "enablement": { + "type": "string", + "maxLength": 1024 + }, + "defaultKeybinding": { + "type": "string", + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "MenuLocation": { + "type": "string", + "enum": [ + "commandPalette", + "application", + "host/context", + "terminal/context", + "terminal/toolbar", + "statusBar" + ] + }, + "MenuContribution": { + "type": "object", + "required": [ + "command", + "location" + ], + "properties": { + "command": { + "$ref": "#/$defs/Identifier" + }, + "location": { + "$ref": "#/$defs/MenuLocation" + }, + "group": { + "type": "string", + "maxLength": 128 + }, + "order": { + "type": "number" + }, + "when": { + "type": "string", + "maxLength": 1024 + } + }, + "additionalProperties": false + }, + "ViewLocation": { + "type": "string", + "enum": [ + "aside", + "panel", + "tab", + "modal", + "settings" + ] + }, + "ViewContribution": { + "type": "object", + "required": [ + "id", + "title", + "location", + "entry" + ], + "properties": { + "id": { + "$ref": "#/$defs/Identifier" + }, + "title": { + "$ref": "#/$defs/LocalizedText" + }, + "location": { + "$ref": "#/$defs/ViewLocation" + }, + "entry": { + "$ref": "#/$defs/RelativePackagePath" + }, + "when": { + "type": "string", + "maxLength": 1024 + }, + "retainContextWhenHidden": { + "type": "boolean", + "default": false + } + }, + "additionalProperties": false + }, + "ProviderKind": { + "type": "string", + "enum": [ + "terminal.completion", + "terminal.decoration", + "terminal.link", + "terminal.hover", + "terminal.matcher", + "terminal.semantic", + "terminal.prompt", + "terminal.background", + "terminal.interceptor", + "connection", + "authentication", + "sync", + "importer" + ] + }, + "ProviderContribution": { + "type": "object", + "required": [ + "id", + "label", + "kind" + ], + "properties": { + "id": { + "$ref": "#/$defs/Identifier" + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "kind": { + "$ref": "#/$defs/ProviderKind" + }, + "activationEvent": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "capabilities": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "configuration": { + "$ref": "#/$defs/JsonValue" + } + }, + "additionalProperties": false + }, + "CompanionExecutable": { + "type": "object", + "required": [ + "id", + "path", + "platforms", + "sha256" + ], + "properties": { + "id": { + "$ref": "#/$defs/Identifier" + }, + "path": { + "$ref": "#/$defs/RelativePackagePath" + }, + "platforms": { + "type": "array", + "minItems": 1, + "maxItems": 12, + "uniqueItems": true, + "items": { + "enum": [ + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64", + "win32-arm64", + "win32-x64" + ] + } + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "permissions": { + "type": "array", + "maxItems": 32, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + } + }, + "additionalProperties": false + }, + "PluginContributions": { + "type": "object", + "properties": { + "settings": { + "type": "array", + "maxItems": 512, + "items": { + "$ref": "#/$defs/SettingContribution" + } + }, + "commands": { + "type": "array", + "maxItems": 512, + "items": { + "$ref": "#/$defs/CommandContribution" + } + }, + "menus": { + "type": "array", + "maxItems": 1024, + "items": { + "$ref": "#/$defs/MenuContribution" + } + }, + "views": { + "type": "array", + "maxItems": 128, + "items": { + "$ref": "#/$defs/ViewContribution" + } + }, + "providers": { + "type": "array", + "maxItems": 256, + "items": { + "$ref": "#/$defs/ProviderContribution" + } + } + }, + "additionalProperties": false + }, + "PluginManifest": { + "type": "object", + "required": [ + "manifestVersion", + "id", + "name", + "version", + "publisher", + "engines", + "main" + ], + "properties": { + "$schema": { + "type": "string", + "format": "uri-reference" + }, + "manifestVersion": { + "const": 1 + }, + "id": { + "$ref": "#/$defs/PluginId" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "displayName": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "version": { + "type": "string", + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" + }, + "publisher": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "license": { + "type": "string", + "maxLength": 128 + }, + "homepage": { + "type": "string", + "format": "uri" + }, + "repository": { + "type": "string", + "format": "uri" + }, + "engines": { + "$ref": "#/$defs/PluginEngines" + }, + "main": { + "$ref": "#/$defs/PluginEntrypoints" + }, + "activationEvents": { + "type": "array", + "maxItems": 256, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } + }, + "permissions": { + "$ref": "#/$defs/PermissionSet" + }, + "contributes": { + "$ref": "#/$defs/PluginContributions" + }, + "companionExecutables": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/CompanionExecutable" + } + } + }, + "additionalProperties": false + }, + "RpcId": { + "oneOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + { + "type": "integer", + "minimum": 0 + } + ] + }, + "RpcRequest": { + "type": "object", + "required": [ + "jsonrpc", + "id", + "method" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "method": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "params": { + "$ref": "#/$defs/JsonValue" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "RpcNotification": { + "type": "object", + "required": [ + "jsonrpc", + "method" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "method": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "params": { + "$ref": "#/$defs/JsonValue" + } + }, + "additionalProperties": false + }, + "RpcSuccess": { + "type": "object", + "required": [ + "jsonrpc", + "id", + "result" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "result": { + "$ref": "#/$defs/JsonValue" + } + }, + "additionalProperties": false + }, + "RpcErrorObject": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer" + }, + "message": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "data": { + "$ref": "#/$defs/JsonValue" + } + }, + "additionalProperties": false + }, + "RpcFailure": { + "type": "object", + "required": [ + "jsonrpc", + "id", + "error" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } + }, + "additionalProperties": false + }, + "RpcCancel": { + "type": "object", + "required": [ + "jsonrpc", + "method", + "params" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "method": { + "const": "$/cancelRequest" + }, + "params": { + "type": "object", + "required": [ + "cancellationId" + ], + "properties": { + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "StreamFrame": { + "oneOf": [ + { + "type": "object", + "required": [ + "streamId", + "sequence", + "kind" + ], + "properties": { + "streamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "const": "open" + }, + "windowBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 16777216 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "streamId", + "sequence", + "kind", + "data" + ], + "properties": { + "streamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "const": "chunk" + }, + "data": { + "$ref": "#/$defs/JsonValue" + }, + "byteLength": { + "type": "integer", + "minimum": 0, + "maximum": 16777216 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "streamId", + "sequence", + "kind" + ], + "properties": { + "streamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "enum": [ + "end", + "cancel" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "streamId", + "sequence", + "kind", + "error" + ], + "properties": { + "streamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "streamId", + "sequence", + "kind", + "windowBytes" + ], + "properties": { + "streamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "const": "windowUpdate" + }, + "windowBytes": { + "type": "integer", + "minimum": 1, + "maximum": 16777216 + } + }, + "additionalProperties": false + } + ] + }, + "PermissionGrantScope": { + "type": "string", + "enum": [ + "once", + "session", + "application", + "always" + ] + }, + "PermissionRequest": { + "type": "object", + "required": [ + "requestId", + "pluginId", + "permission", + "reason" + ], + "properties": { + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "pluginId": { + "$ref": "#/$defs/PluginId" + }, + "permission": { + "$ref": "#/$defs/PluginPermission" + }, + "resources": { + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "operationId": { + "type": "string", + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "PermissionDecision": { + "type": "object", + "required": [ + "requestId", + "decision" + ], + "properties": { + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "decision": { + "enum": [ + "allow", + "deny", + "cancel" + ] + }, + "scope": { + "$ref": "#/$defs/PermissionGrantScope" + }, + "resources": { + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } + } + }, + "additionalProperties": false + }, + "ProviderRequest": { + "type": "object", + "required": [ + "providerId", + "operation", + "requestId" + ], + "properties": { + "providerId": { + "$ref": "#/$defs/Identifier" + }, + "operation": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "payload": { + "$ref": "#/$defs/JsonValue" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "ProviderResult": { + "type": "object", + "required": [ + "requestId", + "status" + ], + "properties": { + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "status": { + "enum": [ + "ok", + "cancelled", + "failed" + ] + }, + "result": { + "$ref": "#/$defs/JsonValue" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } + }, + "additionalProperties": false + } + } +} diff --git a/eslint.config.js b/eslint.config.js index 2f75ec4b3..fe5d6e841 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -12,7 +12,7 @@ export default [ // every other electron/ file matches no config and stays unlinted as before. { ...js.configs.recommended, ignores: ["electron/**"] }, { - ignores: ["node_modules/**", "dist/**", "scripts/**", "public/monaco/**", ".github/**", ".claude/**", "release/**", "release-build/**", ".worktrees/**"], + ignores: ["node_modules/**", "**/dist/**", "scripts/**", "public/monaco/**", ".github/**", ".claude/**", "release/**", "release-build/**", ".worktrees/**"], }, { files: ["**/*.{ts,tsx}"], diff --git a/examples/plugins/hello-netcatty/README.md b/examples/plugins/hello-netcatty/README.md new file mode 100644 index 000000000..b5813d193 --- /dev/null +++ b/examples/plugins/hello-netcatty/README.md @@ -0,0 +1,12 @@ +# Hello Netcatty + +This package is a compile-time example for the internal plugin API. PR 1 does +not load or execute it inside Netcatty; the isolated host runtime arrives in PR +2 of the plugin platform series. + +From the repository root: + +```bash +npm run build --workspace @netcatty/example-hello-plugin +npm exec --workspace @netcatty/plugin-cli -- netcatty-plugin validate examples/plugins/hello-netcatty +``` diff --git a/examples/plugins/hello-netcatty/netcatty.plugin.json b/examples/plugins/hello-netcatty/netcatty.plugin.json new file mode 100644 index 000000000..c93168e34 --- /dev/null +++ b/examples/plugins/hello-netcatty/netcatty.plugin.json @@ -0,0 +1,58 @@ +{ + "$schema": "../../../packages/plugin-contract/schema/plugin-contract.schema.json", + "manifestVersion": 1, + "id": "com.netcatty.hello", + "name": "hello-netcatty", + "displayName": { + "en": "Hello Netcatty", + "zh-CN": "你好,Netcatty" + }, + "description": "Minimal plugin contract and SDK example.", + "version": "0.1.0", + "publisher": "netcatty", + "license": "GPL-3.0-or-later", + "engines": { + "netcatty": ">=0.0.0", + "api": "0.1.0-internal" + }, + "main": { + "browser": "dist/index.js" + }, + "activationEvents": [ + "onCommand:hello.sayHello" + ], + "permissions": { + "required": [ + "commands", + "settings" + ], + "optional": [] + }, + "contributes": { + "settings": [ + { + "id": "hello.greeting", + "label": "Greeting", + "description": "Text used by the example command.", + "control": "text", + "scope": "application", + "default": "Hello from Netcatty" + } + ], + "commands": [ + { + "id": "hello.sayHello", + "title": "Say Hello", + "category": "Examples" + } + ], + "menus": [ + { + "command": "hello.sayHello", + "location": "commandPalette", + "group": "examples", + "order": 10 + } + ] + } +} diff --git a/examples/plugins/hello-netcatty/package.json b/examples/plugins/hello-netcatty/package.json new file mode 100644 index 000000000..7d6233462 --- /dev/null +++ b/examples/plugins/hello-netcatty/package.json @@ -0,0 +1,12 @@ +{ + "name": "@netcatty/example-hello-plugin", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc -p tsconfig.json" + }, + "dependencies": { + "@netcatty/plugin-sdk": "0.1.0-internal" + } +} diff --git a/examples/plugins/hello-netcatty/src/index.ts b/examples/plugins/hello-netcatty/src/index.ts new file mode 100644 index 000000000..cf7a42c4f --- /dev/null +++ b/examples/plugins/hello-netcatty/src/index.ts @@ -0,0 +1,9 @@ +import { definePlugin } from "@netcatty/plugin-sdk"; + +export default definePlugin({ + activate(context) { + context.logger.info("Hello Netcatty example activated", { + pluginId: context.pluginId, + }); + }, +}); diff --git a/examples/plugins/hello-netcatty/tsconfig.json b/examples/plugins/hello-netcatty/tsconfig.json new file mode 100644 index 000000000..e9b5ed724 --- /dev/null +++ b/examples/plugins/hello-netcatty/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"] +} diff --git a/package-lock.json b/package-lock.json index 714535bac..b4bf39137 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,10 @@ "version": "0.0.0", "hasInstallScript": true, "license": "GPL-3.0-or-later", + "workspaces": [ + "packages/*", + "examples/plugins/*" + ], "dependencies": { "@ai-sdk/anthropic": "^4.0.0", "@ai-sdk/google": "^4.0.0", @@ -104,6 +108,13 @@ "@vscode/windows-process-tree": "^0.7.0" } }, + "examples/plugins/hello-netcatty": { + "name": "@netcatty/example-hello-plugin", + "version": "0.1.0", + "dependencies": { + "@netcatty/plugin-sdk": "0.1.0-internal" + } + }, "node_modules/@agentclientprotocol/sdk": { "version": "0.18.2", "resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-0.18.2.tgz", @@ -343,7 +354,6 @@ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.111.0.tgz", "integrity": "sha512-1hUqKi+uJQoS5X90+InwHbFAXMvgq0DnsC5hVLEeSRaODiU5WvmqDAcVCmGS2wC0pN9Z8jtWCbWw7JLzeDdm/Q==", "license": "MIT", - "peer": true, "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" @@ -1289,7 +1299,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1895,7 +1904,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1985,7 +1993,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", - "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1995,7 +2002,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -2008,7 +2014,6 @@ "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", "license": "Apache-2.0", - "peer": true, "peerDependencies": { "@bufbuild/protobuf": "^1.10.0" } @@ -2460,6 +2465,7 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, + "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2481,6 +2487,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3899,7 +3906,6 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", - "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4182,7 +4188,6 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", - "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -4263,6 +4268,22 @@ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/@netcatty/example-hello-plugin": { + "resolved": "examples/plugins/hello-netcatty", + "link": true + }, + "node_modules/@netcatty/plugin-cli": { + "resolved": "packages/plugin-cli", + "link": true + }, + "node_modules/@netcatty/plugin-contract": { + "resolved": "packages/plugin-contract", + "link": true + }, + "node_modules/@netcatty/plugin-sdk": { + "resolved": "packages/plugin-sdk", + "link": true + }, "node_modules/@noble/hashes": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz", @@ -8194,7 +8215,6 @@ "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", "dev": true, "license": "MIT", - "optional": true, "dependencies": { "@types/node": "*" } @@ -8205,7 +8225,6 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8235,7 +8254,6 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8595,7 +8613,6 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", - "peer": true, "workspaces": [ "addons/*" ] @@ -8660,7 +8677,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9360,7 +9376,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10186,7 +10201,8 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10483,7 +10499,6 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10765,6 +10780,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10785,6 +10801,7 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10800,6 +10817,7 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10810,6 +10828,7 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11034,7 +11053,6 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -12447,7 +12465,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -12902,6 +12919,7 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", + "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -13179,6 +13197,7 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", + "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14139,7 +14158,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15260,6 +15278,7 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15279,7 +15298,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15891,7 +15909,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", - "dev": true, "license": "MIT" }, "node_modules/picocolors": { @@ -16030,6 +16047,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -16047,6 +16065,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16368,7 +16387,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -16378,7 +16396,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -18003,6 +18020,7 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -18029,6 +18047,7 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18103,7 +18122,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -18224,7 +18242,6 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18336,7 +18353,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18377,7 +18393,6 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", - "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18753,7 +18768,6 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18847,7 +18861,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -19135,7 +19148,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } @@ -19171,6 +19183,98 @@ "type": "github", "url": "https://github.com/sponsors/wooorm" } + }, + "packages/plugin-cli": { + "name": "@netcatty/plugin-cli", + "version": "0.1.0-internal", + "license": "GPL-3.0-or-later", + "dependencies": { + "@netcatty/plugin-contract": "0.1.0-internal", + "ajv": "8.18.0", + "ajv-formats": "3.0.1", + "yauzl": "^3.2.0" + }, + "bin": { + "netcatty-plugin": "dist/cli.js" + }, + "devDependencies": { + "@types/yauzl": "^2.10.3" + } + }, + "packages/plugin-cli/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "packages/plugin-cli/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "packages/plugin-cli/node_modules/yauzl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz", + "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "packages/plugin-contract": { + "name": "@netcatty/plugin-contract", + "version": "0.1.0-internal", + "license": "GPL-3.0-or-later", + "devDependencies": { + "ajv": "8.18.0", + "ajv-formats": "3.0.1" + } + }, + "packages/plugin-contract/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "packages/plugin-contract/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "packages/plugin-sdk": { + "name": "@netcatty/plugin-sdk", + "version": "0.1.0-internal", + "license": "GPL-3.0-or-later", + "dependencies": { + "@netcatty/plugin-contract": "0.1.0-internal" + } } } } diff --git a/package.json b/package.json index cd38e369f..6b03a116e 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,10 @@ "private": true, "version": "0.0.0", "type": "module", + "workspaces": [ + "packages/*", + "examples/plugins/*" + ], "author": "binaricat ", "license": "GPL-3.0-or-later", "engines": { @@ -24,7 +28,8 @@ "fetch:mosh:dev": "node scripts/fetch-mosh-binaries.cjs --host --resolve-release", "fetch:et": "node scripts/fetch-et-binaries.cjs", "fetch:et:dev": "node scripts/fetch-et-binaries.cjs --host --resolve-release", - "build": "vite build", + "build": "npm run build:plugin-packages && vite build", + "build:plugin-packages": "npm run generate:plugin-contract && npm run build --workspace @netcatty/plugin-contract && npm run build --workspace @netcatty/plugin-sdk && npm run build --workspace @netcatty/plugin-cli && npm run build --workspace @netcatty/example-hello-plugin", "preview": "vite preview", "start": "node electron/launch.cjs", "pack": "npm run build && cross-env NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --publish=never", @@ -41,9 +46,12 @@ "generate:capability-tools": "node scripts/generate-capability-tools.cjs", "generate:codex-app-server-schema": "node scripts/generate-codex-app-server-schema.cjs", "check:codex-app-server-schema": "node scripts/generate-codex-app-server-schema.cjs --check", + "generate:plugin-contract": "node scripts/generate-plugin-contract.mjs", + "check:plugin-contract": "node scripts/generate-plugin-contract.mjs --check", "lint": "eslint .", "lint:fix": "eslint . --fix", - "test": "node --test --import tsx electron/*.test.cjs electron/scripts/*.test.cjs electron/terminalWorker/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/codexAppServer/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.tsx components/port-forwarding/*.test.ts components/scripts/*.test.tsx components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai/toolArtifacts/*.test.ts components/ai/toolArtifacts/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts", + "test": "node --test --import tsx electron/*.test.cjs electron/scripts/*.test.cjs electron/terminalWorker/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/codexAppServer/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.tsx components/port-forwarding/*.test.ts components/scripts/*.test.tsx components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai/toolArtifacts/*.test.ts components/ai/toolArtifacts/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts packages/*/src/*.test.ts", + "test:plugin-contract": "node --test --import tsx packages/*/src/*.test.ts", "test:sync-crdt": "node --test --import tsx domain/convergentSync/*.test.ts", "bench:sync-crdt": "tsx scripts/bench-sync-crdt.ts", "test:ssh-mfa-models": "node --test electron/bridges/sshMfaModels.live.test.cjs", diff --git a/packages/plugin-cli/package.json b/packages/plugin-cli/package.json new file mode 100644 index 000000000..3b40443e1 --- /dev/null +++ b/packages/plugin-cli/package.json @@ -0,0 +1,29 @@ +{ + "name": "@netcatty/plugin-cli", + "version": "0.1.0-internal", + "private": true, + "type": "module", + "license": "GPL-3.0-or-later", + "files": ["dist"], + "bin": { + "netcatty-plugin": "./dist/cli.js" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + }, + "dependencies": { + "@netcatty/plugin-contract": "0.1.0-internal", + "ajv": "8.18.0", + "ajv-formats": "3.0.1", + "yauzl": "^3.2.0" + }, + "devDependencies": { + "@types/yauzl": "^2.10.3" + } +} diff --git a/packages/plugin-cli/src/archive.ts b/packages/plugin-cli/src/archive.ts new file mode 100644 index 000000000..8fbcb5e82 --- /dev/null +++ b/packages/plugin-cli/src/archive.ts @@ -0,0 +1,535 @@ +import { createHash, randomUUID } from "node:crypto"; +import { constants, createReadStream, createWriteStream } from "node:fs"; +import { + lstat, + mkdir, + open, + opendir, + rename, + rm, + stat, +} from "node:fs/promises"; +import path from "node:path"; +import { once } from "node:events"; + +import type { PluginManifest } from "@netcatty/plugin-contract"; +import yauzl, { type Entry, type ZipFile } from "yauzl"; + +import { IGNORED_ROOT_ENTRIES, PACKAGE_LIMITS } from "./constants.js"; +import { readAndValidateManifest, validateManifestValue } from "./manifest.js"; +import { assertSafePackagePath, PackagePathRegistry } from "./packagePath.js"; + +const CRC32_TABLE = new Uint32Array(256); +const EXECUTABLE_EXTENSIONS = new Set([".bat", ".cmd", ".com", ".exe", ".ps1"]); +for (let index = 0; index < CRC32_TABLE.length; index += 1) { + let value = index; + for (let bit = 0; bit < 8; bit += 1) { + value = (value & 1) === 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1; + } + CRC32_TABLE[index] = value >>> 0; +} + +interface ScannedFile { + readonly absolutePath: string; + readonly packagePath: string; + readonly size: number; + readonly crc32: number; + readonly sha256: string; + readonly executable: boolean; +} + +export interface PackageBuildResult { + readonly outputPath: string; + readonly fileCount: number; + readonly uncompressedBytes: number; + readonly archiveBytes: number; + readonly sha256: string; +} + +export interface PackageValidationResult { + readonly manifest: PluginManifest; + readonly fileCount: number; + readonly uncompressedBytes: number; +} + +export type PluginDirectoryValidationResult = PackageValidationResult; + +function updateCrc32(current: number, chunk: Buffer): number { + let crc = current; + for (const byte of chunk) crc = CRC32_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8); + return crc >>> 0; +} + +async function readRegularFile( + filePath: string, + onChunk: (chunk: Buffer) => void, +): Promise<{ size: number; mode: number }> { + const noFollow = "O_NOFOLLOW" in constants + ? constants.O_NOFOLLOW + : 0; + const handle = await open(filePath, constants.O_RDONLY | noFollow); + try { + const fileStats = await handle.stat(); + if (!fileStats.isFile()) throw new Error(`Package source is not a regular file: ${filePath}`); + let size = 0; + const stream = createReadStream(filePath, { fd: handle.fd, autoClose: false }); + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + size += buffer.byteLength; + onChunk(buffer); + } + return { size, mode: fileStats.mode }; + } finally { + await handle.close(); + } +} + +async function hashFile( + filePath: string, +): Promise<{ crc32: number; sha256: string; size: number; mode: number }> { + const sha256 = createHash("sha256"); + let crc = 0xffffffff; + const file = await readRegularFile(filePath, (buffer) => { + sha256.update(buffer); + crc = updateCrc32(crc, buffer); + }); + return { + crc32: (crc ^ 0xffffffff) >>> 0, + sha256: sha256.digest("hex"), + size: file.size, + mode: file.mode, + }; +} + +function sortPackagePaths(left: ScannedFile, right: ScannedFile): number { + return Buffer.compare(Buffer.from(left.packagePath), Buffer.from(right.packagePath)); +} + +function isExecutablePackageFile(packagePath: string, mode: number): boolean { + return (mode & 0o111) !== 0 + || EXECUTABLE_EXTENSIONS.has(path.posix.extname(packagePath).toLowerCase()); +} + +async function scanPackageDirectory( + pluginDirectory: string, + manifest: PluginManifest, +): Promise { + const registry = new PackagePathRegistry(); + const companionPaths = new Map( + (manifest.companionExecutables ?? []).map((companion) => [companion.path, companion]), + ); + const files: ScannedFile[] = []; + let totalBytes = 0; + + async function visit(directory: string, relativeDirectory: string): Promise { + const entries = []; + for await (const entry of await opendir(directory)) entries.push(entry); + entries.sort((left, right) => Buffer.compare(Buffer.from(left.name), Buffer.from(right.name))); + for (const entry of entries) { + if (IGNORED_ROOT_ENTRIES.has(entry.name) || entry.name.endsWith(".ncpkg")) continue; + const relativePath = relativeDirectory + ? `${relativeDirectory}/${entry.name}` + : entry.name; + const packagePath = assertSafePackagePath(relativePath); + const absolutePath = path.join(directory, entry.name); + const fileStats = await lstat(absolutePath); + if (fileStats.isSymbolicLink()) { + throw new Error(`Symbolic links are not allowed in plugin packages: ${packagePath}`); + } + if (fileStats.isDirectory()) { + await visit(absolutePath, packagePath); + continue; + } + if (!fileStats.isFile()) { + throw new Error(`Only regular files are allowed in plugin packages: ${packagePath}`); + } + registry.add(packagePath); + if (files.length + 1 > PACKAGE_LIMITS.fileCount) { + throw new Error(`Plugin package exceeds ${PACKAGE_LIMITS.fileCount} files`); + } + if (fileStats.size > PACKAGE_LIMITS.singleFileBytes) { + throw new Error(`Plugin file exceeds ${PACKAGE_LIMITS.singleFileBytes} bytes: ${packagePath}`); + } + totalBytes += fileStats.size; + if (totalBytes > PACKAGE_LIMITS.uncompressedBytes) { + throw new Error( + `Plugin package exceeds ${PACKAGE_LIMITS.uncompressedBytes} uncompressed bytes`, + ); + } + const hashes = await hashFile(absolutePath); + if (hashes.size !== fileStats.size || hashes.mode !== fileStats.mode) { + throw new Error(`Package source changed while it was being scanned: ${packagePath}`); + } + const isExecutable = isExecutablePackageFile(packagePath, hashes.mode); + if (isExecutable && !companionPaths.has(packagePath)) { + throw new Error(`Executable file is not declared as a companion: ${packagePath}`); + } + const companion = companionPaths.get(packagePath); + if (companion && companion.sha256 !== hashes.sha256) { + throw new Error(`Companion SHA-256 mismatch: ${packagePath}`); + } + files.push({ + absolutePath, + packagePath, + size: fileStats.size, + executable: Boolean(companion), + crc32: hashes.crc32, + sha256: hashes.sha256, + }); + } + } + + await visit(pluginDirectory, ""); + const packagedPaths = new Set(files.map(({ packagePath }) => packagePath)); + const requiredPaths = [ + "netcatty.plugin.json", + manifest.main.browser, + manifest.main.node, + ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), + ...companionPaths.keys(), + ].filter((entryPath): entryPath is string => Boolean(entryPath)); + for (const requiredPath of requiredPaths) { + if (!packagedPaths.has(requiredPath)) { + throw new Error(`Manifest references a missing package file: ${requiredPath}`); + } + } + return files.sort(sortPackagePaths); +} + +function makeLocalHeader(file: ScannedFile): Buffer { + const name = Buffer.from(file.packagePath, "utf8"); + const header = Buffer.alloc(30 + name.byteLength); + header.writeUInt32LE(0x04034b50, 0); + header.writeUInt16LE(20, 4); + header.writeUInt16LE(0x0800, 6); + header.writeUInt16LE(0, 8); + header.writeUInt16LE(0, 10); + header.writeUInt16LE(33, 12); + header.writeUInt32LE(file.crc32, 14); + header.writeUInt32LE(file.size, 18); + header.writeUInt32LE(file.size, 22); + header.writeUInt16LE(name.byteLength, 26); + header.writeUInt16LE(0, 28); + name.copy(header, 30); + return header; +} + +function makeCentralHeader(file: ScannedFile, localOffset: number): Buffer { + const name = Buffer.from(file.packagePath, "utf8"); + const header = Buffer.alloc(46 + name.byteLength); + header.writeUInt32LE(0x02014b50, 0); + header.writeUInt16LE(0x0314, 4); + header.writeUInt16LE(20, 6); + header.writeUInt16LE(0x0800, 8); + header.writeUInt16LE(0, 10); + header.writeUInt16LE(0, 12); + header.writeUInt16LE(33, 14); + header.writeUInt32LE(file.crc32, 16); + header.writeUInt32LE(file.size, 20); + header.writeUInt32LE(file.size, 24); + header.writeUInt16LE(name.byteLength, 28); + header.writeUInt16LE(0, 30); + header.writeUInt16LE(0, 32); + header.writeUInt16LE(0, 34); + header.writeUInt16LE(0, 36); + const mode = file.executable ? 0o100755 : 0o100644; + header.writeUInt32LE((mode << 16) >>> 0, 38); + header.writeUInt32LE(localOffset, 42); + name.copy(header, 46); + return header; +} + +function makeEndOfCentralDirectory( + entryCount: number, + centralSize: number, + centralOffset: number, +): Buffer { + const footer = Buffer.alloc(22); + footer.writeUInt32LE(0x06054b50, 0); + footer.writeUInt16LE(0, 4); + footer.writeUInt16LE(0, 6); + footer.writeUInt16LE(entryCount, 8); + footer.writeUInt16LE(entryCount, 10); + footer.writeUInt32LE(centralSize, 12); + footer.writeUInt32LE(centralOffset, 16); + footer.writeUInt16LE(0, 20); + return footer; +} + +async function writeBuffer(output: ReturnType, buffer: Buffer) { + if (!output.write(buffer)) await once(output, "drain"); +} + +async function writeArchive(files: readonly ScannedFile[], outputPath: string): Promise { + await mkdir(path.dirname(outputPath), { recursive: true }); + const temporaryPath = `${outputPath}.tmp-${process.pid}-${randomUUID()}`; + const output = createWriteStream(temporaryPath, { flags: "wx", mode: 0o600 }); + const centralHeaders: Buffer[] = []; + let offset = 0; + try { + await once(output, "open"); + for (const file of files) { + const localHeader = makeLocalHeader(file); + centralHeaders.push(makeCentralHeader(file, offset)); + await writeBuffer(output, localHeader); + offset += localHeader.byteLength; + const sha256 = createHash("sha256"); + let crc = 0xffffffff; + let writtenBytes = 0; + const input = await open( + file.absolutePath, + constants.O_RDONLY | ("O_NOFOLLOW" in constants ? constants.O_NOFOLLOW : 0), + ); + try { + const inputStats = await input.stat(); + if (!inputStats.isFile() || inputStats.size !== file.size) { + throw new Error(`Package source changed before archive write: ${file.packagePath}`); + } + const stream = createReadStream(file.absolutePath, { fd: input.fd, autoClose: false }); + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + writtenBytes += buffer.byteLength; + sha256.update(buffer); + crc = updateCrc32(crc, buffer); + await writeBuffer(output, buffer); + offset += buffer.byteLength; + } + } finally { + await input.close(); + } + if ( + writtenBytes !== file.size + || ((crc ^ 0xffffffff) >>> 0) !== file.crc32 + || sha256.digest("hex") !== file.sha256 + ) { + throw new Error(`Package source changed while it was being written: ${file.packagePath}`); + } + } + const centralOffset = offset; + for (const centralHeader of centralHeaders) { + await writeBuffer(output, centralHeader); + offset += centralHeader.byteLength; + } + await writeBuffer( + output, + makeEndOfCentralDirectory(files.length, offset - centralOffset, centralOffset), + ); + output.end(); + await once(output, "close"); + const archiveStats = await stat(temporaryPath); + if (archiveStats.size > PACKAGE_LIMITS.archiveBytes) { + throw new Error(`Plugin archive exceeds ${PACKAGE_LIMITS.archiveBytes} bytes`); + } + await rename(temporaryPath, outputPath); + } catch (error) { + output.destroy(); + await rm(temporaryPath, { force: true }); + throw error; + } +} + +export async function buildPluginPackage( + pluginDirectory: string, + outputPath: string, +): Promise { + const sourceDirectory = path.resolve(pluginDirectory); + const resolvedOutputPath = path.resolve(outputPath); + if (!resolvedOutputPath.endsWith(".ncpkg")) { + throw new Error("Plugin package output must use the .ncpkg extension"); + } + const manifest = await readAndValidateManifest(sourceDirectory); + const files = await scanPackageDirectory(sourceDirectory, manifest); + await writeArchive(files, resolvedOutputPath); + const outputStats = await stat(resolvedOutputPath); + const archiveHash = await hashFile(resolvedOutputPath); + return { + outputPath: resolvedOutputPath, + fileCount: files.length, + uncompressedBytes: files.reduce((sum, file) => sum + file.size, 0), + archiveBytes: outputStats.size, + sha256: archiveHash.sha256, + }; +} + +export async function validatePluginDirectory( + pluginDirectory: string, +): Promise { + const sourceDirectory = path.resolve(pluginDirectory); + const manifest = await readAndValidateManifest(sourceDirectory); + const files = await scanPackageDirectory(sourceDirectory, manifest); + return { + manifest, + fileCount: files.length, + uncompressedBytes: files.reduce((sum, file) => sum + file.size, 0), + }; +} + +function openZip(filePath: string): Promise { + return new Promise((resolve, reject) => { + yauzl.open( + filePath, + { lazyEntries: true, decodeStrings: true, strictFileNames: true, validateEntrySizes: true }, + (error, zipFile) => { + if (error || !zipFile) reject(error ?? new Error("Unable to open plugin archive")); + else resolve(zipFile); + }, + ); + }); +} + +interface ReadArchiveEntryResult { + readonly bytes: number; + readonly crc32: number; + readonly sha256: string; + readonly contents?: Buffer; +} + +function readEntry( + zipFile: ZipFile, + entry: Entry, + captureContents: boolean, +): Promise { + return new Promise((resolve, reject) => { + zipFile.openReadStream(entry, (error, stream) => { + if (error || !stream) { + reject(error ?? new Error(`Unable to read archive entry: ${entry.fileName}`)); + return; + } + const chunks: Buffer[] = []; + const sha256 = createHash("sha256"); + let crc = 0xffffffff; + let bytes = 0; + stream.on("data", (chunk: Buffer) => { + const buffer = Buffer.from(chunk); + bytes += chunk.byteLength; + if (bytes > PACKAGE_LIMITS.singleFileBytes) { + stream.destroy(new Error(`Plugin file exceeds size limit: ${entry.fileName}`)); + return; + } + sha256.update(buffer); + crc = updateCrc32(crc, buffer); + if (captureContents) chunks.push(buffer); + }); + stream.once("error", reject); + stream.once("end", () => resolve({ + bytes, + crc32: (crc ^ 0xffffffff) >>> 0, + sha256: sha256.digest("hex"), + contents: captureContents ? Buffer.concat(chunks) : undefined, + })); + }); + }); +} + +export async function validatePluginPackage( + archivePath: string, +): Promise { + const archiveStats = await stat(archivePath); + if (archiveStats.size > PACKAGE_LIMITS.archiveBytes) { + throw new Error(`Plugin archive exceeds ${PACKAGE_LIMITS.archiveBytes} bytes`); + } + const zipFile = await openZip(archivePath); + const registry = new PackagePathRegistry(); + const entries = new Map(); + let totalBytes = 0; + + await new Promise((resolve, reject) => { + const fail = (error: unknown) => { + zipFile.close(); + reject(error); + }; + zipFile.once("error", fail); + zipFile.once("end", resolve); + zipFile.on("entry", (entry: Entry) => { + void (async () => { + try { + const packagePath = registry.add(entry.fileName); + if (entries.size + 1 > PACKAGE_LIMITS.fileCount) { + throw new Error(`Plugin package exceeds ${PACKAGE_LIMITS.fileCount} files`); + } + if ((entry.generalPurposeBitFlag & 1) !== 0) { + throw new Error(`Encrypted ZIP entries are not allowed: ${packagePath}`); + } + if (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) { + throw new Error(`Unsupported ZIP compression method: ${packagePath}`); + } + const mode = (entry.externalFileAttributes >>> 16) & 0xffff; + const fileType = mode & 0o170000; + if (fileType !== 0 && fileType !== 0o100000) { + throw new Error(`Only regular files are allowed: ${packagePath}`); + } + if (entry.uncompressedSize > PACKAGE_LIMITS.singleFileBytes) { + throw new Error(`Plugin file exceeds size limit: ${packagePath}`); + } + totalBytes += entry.uncompressedSize; + if (totalBytes > PACKAGE_LIMITS.uncompressedBytes) { + throw new Error("Plugin package exceeds the uncompressed size limit"); + } + const result = await readEntry( + zipFile, + entry, + packagePath === "netcatty.plugin.json", + ); + if (result.bytes !== entry.uncompressedSize || result.crc32 !== entry.crc32) { + throw new Error(`ZIP entry integrity check failed: ${packagePath}`); + } + entries.set(packagePath, { + contents: result.contents, + mode, + sha256: result.sha256, + }); + zipFile.readEntry(); + } catch (error) { + fail(error); + } + })(); + }); + zipFile.readEntry(); + }); + + const manifestEntry = entries.get("netcatty.plugin.json"); + if (!manifestEntry?.contents) throw new Error("Plugin package is missing netcatty.plugin.json"); + if (manifestEntry.contents.byteLength > PACKAGE_LIMITS.manifestBytes) { + throw new Error("Plugin manifest exceeds the size limit"); + } + let manifestValue: unknown; + try { + manifestValue = JSON.parse(manifestEntry.contents.toString("utf8")); + } catch (error) { + throw new Error( + `Plugin manifest is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + ); + } + const validation = validateManifestValue(manifestValue); + if (!validation.valid || !validation.manifest) { + throw new Error(`Plugin manifest is invalid:\n- ${validation.errors.join("\n- ")}`); + } + const manifest = validation.manifest; + const declaredCompanions = new Map( + (manifest.companionExecutables ?? []).map((companion) => [companion.path, companion]), + ); + for (const [packagePath, entry] of entries) { + const isExecutable = isExecutablePackageFile(packagePath, entry.mode); + if (isExecutable && !declaredCompanions.has(packagePath)) { + throw new Error(`Executable file is not declared as a companion: ${packagePath}`); + } + } + const requiredPaths = [ + manifest.main.browser, + manifest.main.node, + ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), + ].filter((entryPath): entryPath is string => Boolean(entryPath)); + for (const requiredPath of requiredPaths) { + if (!entries.has(requiredPath)) { + throw new Error(`Manifest references a missing package file: ${requiredPath}`); + } + } + for (const [companionPath, companion] of declaredCompanions) { + const entry = entries.get(companionPath); + if (!entry) throw new Error(`Manifest references a missing companion: ${companionPath}`); + if (entry.sha256 !== companion.sha256) { + throw new Error(`Companion SHA-256 mismatch: ${companionPath}`); + } + } + return { manifest, fileCount: entries.size, uncompressedBytes: totalBytes }; +} diff --git a/packages/plugin-cli/src/cli.test.ts b/packages/plugin-cli/src/cli.test.ts new file mode 100644 index 000000000..0274dd081 --- /dev/null +++ b/packages/plugin-cli/src/cli.test.ts @@ -0,0 +1,173 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { + mkdir, + mkdtemp, + readFile, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { buildPluginPackage, validatePluginPackage } from "./archive.ts"; +import { PACKAGE_LIMITS } from "./constants.ts"; +import { initPlugin } from "./commands.ts"; +import { readAndValidateManifest, validateManifestValue } from "./manifest.ts"; +import { assertSafePackagePath, PackagePathRegistry } from "./packagePath.ts"; + +function manifest(overrides: Record = {}) { + return { + manifestVersion: 1, + id: "com.example.package-test", + name: "package-test", + version: "1.0.0", + publisher: "example", + engines: { netcatty: ">=1.0.0", api: "0.1.0-internal" }, + main: { browser: "dist/index.js" }, + ...overrides, + }; +} + +async function createPlugin(root: string): Promise { + const directory = path.join(root, "plugin"); + await mkdir(path.join(directory, "dist"), { recursive: true }); + await Promise.all([ + writeFile( + path.join(directory, "netcatty.plugin.json"), + `${JSON.stringify(manifest(), null, 2)}\n`, + ), + writeFile(path.join(directory, "dist/index.js"), "export default {};\n"), + writeFile(path.join(directory, "README.md"), "# Package test\n"), + ]); + return directory; +} + +test("path validation rejects traversal, platform aliases, and duplicates", () => { + for (const unsafe of ["../escape", "/absolute", "C:/drive", "a\\b", "a/../b", "CON", "a//b"]) { + assert.throws(() => assertSafePackagePath(unsafe)); + } + const registry = new PackagePathRegistry(); + registry.add("dist/Plugin.js"); + assert.throws(() => registry.add("dist/plugin.js"), /case-colliding/); +}); + +test("manifest validation reports permission and contribution mistakes", () => { + const result = validateManifestValue(manifest({ + permissions: { required: ["network"], optional: ["network"] }, + contributes: { + commands: [{ id: "package.run", title: "Run" }], + menus: [{ command: "package.missing", location: "commandPalette" }], + }, + })); + assert.equal(result.valid, false); + assert.match(result.errors.join("\n"), /both required and optional/); + assert.match(result.errors.join("\n"), /undeclared command/); +}); + +test("init creates a valid TypeScript plugin skeleton", async (context) => { + const root = await mkdtemp(path.join(tmpdir(), "netcatty-plugin-init-")); + context.after(() => rm(root, { recursive: true, force: true })); + const directory = path.join(root, "created"); + + await initPlugin(directory, { id: "com.example.created", name: "Created" }); + + const createdManifest = await readAndValidateManifest(directory); + assert.equal(createdManifest.id, "com.example.created"); + assert.match(await readFile(path.join(directory, "src/index.ts"), "utf8"), /definePlugin/); +}); + +test("packing is deterministic and the archive validates", async (context) => { + const root = await mkdtemp(path.join(tmpdir(), "netcatty-plugin-pack-")); + context.after(() => rm(root, { recursive: true, force: true })); + const directory = await createPlugin(root); + const first = path.join(root, "first.ncpkg"); + const second = path.join(root, "second.ncpkg"); + + const firstResult = await buildPluginPackage(directory, first); + await buildPluginPackage(directory, second); + const firstBytes = await readFile(first); + const secondBytes = await readFile(second); + + assert.deepEqual(firstBytes, secondBytes); + assert.equal( + firstResult.sha256, + createHash("sha256").update(firstBytes).digest("hex"), + ); + const validation = await validatePluginPackage(first); + assert.equal(validation.manifest.id, "com.example.package-test"); + assert.equal(validation.fileCount, 3); +}); + +test("archive validation rejects duplicate names and CRC corruption", async (context) => { + const root = await mkdtemp(path.join(tmpdir(), "netcatty-plugin-archive-safety-")); + context.after(() => rm(root, { recursive: true, force: true })); + const directory = await createPlugin(root); + await Promise.all([ + writeFile(path.join(directory, "a.txt"), "first\n"), + writeFile(path.join(directory, "b.txt"), "second\n"), + ]); + const validPath = path.join(root, "valid.ncpkg"); + await buildPluginPackage(directory, validPath); + const validBytes = await readFile(validPath); + + const duplicateBytes = Buffer.from(validBytes); + const originalName = Buffer.from("b.txt"); + const duplicateName = Buffer.from("a.txt"); + let replacements = 0; + for (let offset = duplicateBytes.indexOf(originalName); offset !== -1;) { + duplicateName.copy(duplicateBytes, offset); + replacements += 1; + offset = duplicateBytes.indexOf(originalName, offset + originalName.byteLength); + } + assert.equal(replacements, 2, "ZIP should contain the local and central entry names"); + const duplicatePath = path.join(root, "duplicate.ncpkg"); + await writeFile(duplicatePath, duplicateBytes); + await assert.rejects(validatePluginPackage(duplicatePath), /Duplicate or case-colliding/); + + const corruptedBytes = Buffer.from(validBytes); + const content = Buffer.from("# Package test\n"); + const contentOffset = corruptedBytes.indexOf(content); + assert.notEqual(contentOffset, -1); + corruptedBytes[contentOffset] ^= 0x01; + const corruptedPath = path.join(root, "corrupted.ncpkg"); + await writeFile(corruptedPath, corruptedBytes); + await assert.rejects(validatePluginPackage(corruptedPath), /integrity check failed/); +}); + +test("packer rejects symbolic links and undeclared executables", async (context) => { + const root = await mkdtemp(path.join(tmpdir(), "netcatty-plugin-safety-")); + context.after(() => rm(root, { recursive: true, force: true })); + const directory = await createPlugin(root); + await assert.rejects( + buildPluginPackage(directory, path.join(root, "wrong-extension.zip")), + /\.ncpkg extension/, + ); + if (process.platform !== "win32") { + await symlink("README.md", path.join(directory, "linked-readme")); + await assert.rejects( + buildPluginPackage(directory, path.join(root, "symlink.ncpkg")), + /Symbolic links/, + ); + await rm(path.join(directory, "linked-readme")); + } + await mkdir(path.join(directory, "bin")); + const executablePath = path.join(directory, "bin/tool.exe"); + await writeFile(executablePath, "not-a-real-executable\n"); + await assert.rejects( + buildPluginPackage(directory, path.join(root, "executable.ncpkg")), + /not declared as a companion/, + ); +}); + +test("manifest byte limit is enforced before JSON parsing", async (context) => { + const root = await mkdtemp(path.join(tmpdir(), "netcatty-plugin-limit-")); + context.after(() => rm(root, { recursive: true, force: true })); + await writeFile( + path.join(root, "netcatty.plugin.json"), + `{"padding":"${"x".repeat(PACKAGE_LIMITS.manifestBytes)}"}`, + ); + await assert.rejects(readAndValidateManifest(root), /manifest exceeds/); +}); diff --git a/packages/plugin-cli/src/cli.ts b/packages/plugin-cli/src/cli.ts new file mode 100644 index 000000000..5d5ae5e54 --- /dev/null +++ b/packages/plugin-cli/src/cli.ts @@ -0,0 +1,64 @@ +#!/usr/bin/env node + +import process from "node:process"; + +import { buildPlugin, initPlugin, packPlugin, validateTarget } from "./commands.js"; + +const USAGE = `Netcatty plugin CLI (API 0.1.0-internal) + +Usage: + netcatty-plugin init --id [--name ] + netcatty-plugin validate + netcatty-plugin build + netcatty-plugin pack [--out ] +`; + +function optionValue(args: readonly string[], name: string): string | undefined { + const index = args.indexOf(name); + if (index === -1) return undefined; + const value = args[index + 1]; + if (!value || value.startsWith("--")) throw new Error(`Missing value for ${name}`); + return value; +} + +async function main(args: readonly string[]): Promise { + const [command, target] = args; + if (!command || command === "help" || command === "--help" || command === "-h") { + process.stdout.write(USAGE); + return; + } + if (!target) throw new Error(`Missing target for ${command}`); + + if (command === "init") { + const id = optionValue(args, "--id"); + if (!id) throw new Error("init requires --id "); + const directory = await initPlugin(target, { id, name: optionValue(args, "--name") }); + process.stdout.write(`Initialized plugin in ${directory}\n`); + return; + } + if (command === "validate") { + const result = await validateTarget(target); + process.stdout.write( + `Valid ${result.kind}: ${result.manifest.id}@${result.manifest.version}\n`, + ); + return; + } + if (command === "build") { + await buildPlugin(target); + process.stdout.write("Plugin build completed.\n"); + return; + } + if (command === "pack") { + const result = await packPlugin(target, optionValue(args, "--out")); + process.stdout.write( + `Packed ${result.fileCount} files to ${result.outputPath}\nSHA-256 ${result.sha256}\n`, + ); + return; + } + throw new Error(`Unknown command: ${command}`); +} + +main(process.argv.slice(2)).catch((error: unknown) => { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; +}); diff --git a/packages/plugin-cli/src/commands.ts b/packages/plugin-cli/src/commands.ts new file mode 100644 index 000000000..f51916da0 --- /dev/null +++ b/packages/plugin-cli/src/commands.ts @@ -0,0 +1,136 @@ +import { spawn } from "node:child_process"; +import { mkdir, readdir, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import type { PluginManifest } from "@netcatty/plugin-contract"; + +import { + buildPluginPackage, + validatePluginDirectory, + validatePluginPackage, +} from "./archive.js"; +import { readAndValidateManifest } from "./manifest.js"; + +export interface InitPluginOptions { + readonly id: string; + readonly name?: string; +} + +export async function initPlugin( + targetDirectory: string, + options: InitPluginOptions, +): Promise { + const directory = path.resolve(targetDirectory); + await mkdir(directory, { recursive: true }); + const existingEntries = await readdir(directory); + if (existingEntries.length > 0) { + throw new Error(`Target directory is not empty: ${directory}`); + } + const displayName = options.name?.trim() || options.id.split(".").at(-1) || options.id; + const packageName = options.id.replaceAll(".", "-"); + const manifest: PluginManifest = { + $schema: "https://netcatty.com/schemas/plugins/0.1.0-internal/plugin-contract.schema.json", + manifestVersion: 1, + id: options.id, + name: displayName, + displayName, + description: "A Netcatty plugin", + version: "0.1.0", + publisher: options.id.split(".")[0] || "local", + engines: { + netcatty: ">=0.0.0", + api: "0.1.0-internal", + }, + main: { browser: "dist/index.js" }, + activationEvents: ["onStartupFinished"], + permissions: { required: [], optional: [] }, + }; + await mkdir(path.join(directory, "src"), { recursive: true }); + await Promise.all([ + writeFile( + path.join(directory, "netcatty.plugin.json"), + `${JSON.stringify(manifest, null, 2)}\n`, + "utf8", + ), + writeFile( + path.join(directory, "package.json"), + `${JSON.stringify({ + name: packageName, + version: "0.1.0", + private: true, + type: "module", + scripts: { build: "tsc -p tsconfig.json" }, + dependencies: { "@netcatty/plugin-sdk": "0.1.0-internal" }, + devDependencies: { typescript: "^5.9.0" }, + }, null, 2)}\n`, + "utf8", + ), + writeFile( + path.join(directory, "tsconfig.json"), + `${JSON.stringify({ + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "Bundler", + strict: true, + declaration: true, + rootDir: "src", + outDir: "dist", + }, + include: ["src/**/*.ts"], + }, null, 2)}\n`, + "utf8", + ), + writeFile( + path.join(directory, "src/index.ts"), + `import { definePlugin } from "@netcatty/plugin-sdk";\n\nexport default definePlugin({\n activate(context) {\n context.logger.info("${displayName} activated");\n },\n});\n`, + "utf8", + ), + ]); + await readAndValidateManifest(directory); + return directory; +} + +export async function validateTarget(target: string) { + const resolved = path.resolve(target); + const targetStats = await stat(resolved); + if (targetStats.isDirectory()) { + const result = await validatePluginDirectory(resolved); + return { kind: "directory" as const, ...result }; + } + if (targetStats.isFile() && resolved.endsWith(".ncpkg")) { + const result = await validatePluginPackage(resolved); + return { kind: "package" as const, ...result }; + } + throw new Error("Validation target must be a plugin directory or .ncpkg file"); +} + +export async function buildPlugin(pluginDirectory: string): Promise { + const directory = path.resolve(pluginDirectory); + await readAndValidateManifest(directory); + const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + await new Promise((resolve, reject) => { + const child = spawn(npmCommand, ["run", "build", "--if-present"], { + cwd: directory, + env: process.env, + shell: false, + stdio: "inherit", + windowsHide: true, + }); + child.once("error", reject); + child.once("exit", (code, signal) => { + if (code === 0) resolve(); + else reject(new Error(`Plugin build failed (${signal ?? `exit ${String(code)}`})`)); + }); + }); + await validatePluginDirectory(directory); +} + +export async function packPlugin(pluginDirectory: string, outputPath?: string) { + const directory = path.resolve(pluginDirectory); + const manifest = await readAndValidateManifest(directory); + const resolvedOutput = outputPath + ? path.resolve(outputPath) + : path.join(path.dirname(directory), `${manifest.id}-${manifest.version}.ncpkg`); + return buildPluginPackage(directory, resolvedOutput); +} diff --git a/packages/plugin-cli/src/constants.ts b/packages/plugin-cli/src/constants.ts new file mode 100644 index 000000000..4c28457c9 --- /dev/null +++ b/packages/plugin-cli/src/constants.ts @@ -0,0 +1,14 @@ +export const PACKAGE_LIMITS = Object.freeze({ + archiveBytes: 100 * 1024 * 1024, + uncompressedBytes: 250 * 1024 * 1024, + singleFileBytes: 50 * 1024 * 1024, + manifestBytes: 1024 * 1024, + fileCount: 5_000, + pathBytes: 512, +}); + +export const IGNORED_ROOT_ENTRIES = new Set([ + ".DS_Store", + ".git", + "node_modules", +]); diff --git a/packages/plugin-cli/src/index.ts b/packages/plugin-cli/src/index.ts new file mode 100644 index 000000000..99f287663 --- /dev/null +++ b/packages/plugin-cli/src/index.ts @@ -0,0 +1,22 @@ +export { PACKAGE_LIMITS } from "./constants.js"; +export { + buildPluginPackage, + validatePluginDirectory, + validatePluginPackage, + type PackageBuildResult, + type PackageValidationResult, + type PluginDirectoryValidationResult, +} from "./archive.js"; +export { + buildPlugin, + initPlugin, + packPlugin, + validateTarget, + type InitPluginOptions, +} from "./commands.js"; +export { + readAndValidateManifest, + validateManifestValue, + type ManifestValidationResult, +} from "./manifest.js"; +export { assertSafePackagePath, PackagePathRegistry } from "./packagePath.js"; diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts new file mode 100644 index 000000000..6569ce886 --- /dev/null +++ b/packages/plugin-cli/src/manifest.ts @@ -0,0 +1,144 @@ +import { createRequire } from "node:module"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +import type { + PermissionDeclaration, + PluginManifest, + PluginPermission, +} from "@netcatty/plugin-contract"; +import Ajv2020, { type ErrorObject } from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; + +import { PACKAGE_LIMITS } from "./constants.js"; +import { assertSafePackagePath } from "./packagePath.js"; + +const require = createRequire(import.meta.url); +const schemaPath = require.resolve( + "@netcatty/plugin-contract/schema/plugin-contract.schema.json", +); +const contractSchema = JSON.parse(await readFile(schemaPath, "utf8")) as object; +const ajv = new Ajv2020({ allErrors: true, strict: true }); +addFormats(ajv); +const validateSchema = ajv.compile(contractSchema); + +export interface ManifestValidationResult { + readonly valid: boolean; + readonly manifest?: PluginManifest; + readonly errors: readonly string[]; +} + +function formatAjvError(error: ErrorObject): string { + const location = error.instancePath || "/"; + return `${location} ${error.message ?? "is invalid"}`; +} + +function permissionName(declaration: PermissionDeclaration): PluginPermission { + return typeof declaration === "string" ? declaration : declaration.permission; +} + +function findDuplicateIds(manifest: PluginManifest): string[] { + const errors: string[] = []; + const groups = [ + ["settings", manifest.contributes?.settings], + ["commands", manifest.contributes?.commands], + ["views", manifest.contributes?.views], + ["providers", manifest.contributes?.providers], + ["companionExecutables", manifest.companionExecutables], + ] as const; + for (const [groupName, contributions] of groups) { + const ids = new Set(); + for (const contribution of contributions ?? []) { + if (ids.has(contribution.id)) { + errors.push(`Duplicate ${groupName} id: ${contribution.id}`); + } + ids.add(contribution.id); + } + } + return errors; +} + +function validateSemantics(manifest: PluginManifest): string[] { + const errors = findDuplicateIds(manifest); + const requiredPermissions = new Set( + (manifest.permissions?.required ?? []).map(permissionName), + ); + for (const declaration of manifest.permissions?.optional ?? []) { + const permission = permissionName(declaration); + if (requiredPermissions.has(permission)) { + errors.push(`Permission cannot be both required and optional: ${permission}`); + } + } + + const commandIds = new Set((manifest.contributes?.commands ?? []).map(({ id }) => id)); + for (const menu of manifest.contributes?.menus ?? []) { + if (!commandIds.has(menu.command)) { + errors.push(`Menu references an undeclared command: ${menu.command}`); + } + } + + for (const setting of manifest.contributes?.settings ?? []) { + if (setting.secret && setting.default !== undefined) { + errors.push(`Secret setting must not declare a default value: ${setting.id}`); + } + if (["select", "multiselect"].includes(setting.control) && !setting.options?.length) { + errors.push(`${setting.control} setting requires options: ${setting.id}`); + } + if (setting.control === "number" && setting.minimum !== undefined + && setting.maximum !== undefined && setting.minimum > setting.maximum) { + errors.push(`Number setting minimum exceeds maximum: ${setting.id}`); + } + } + + for (const entryPath of [ + manifest.main.browser, + manifest.main.node, + ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), + ...(manifest.companionExecutables ?? []).map(({ path: companionPath }) => companionPath), + ]) { + if (entryPath) { + try { + assertSafePackagePath(entryPath); + } catch (error) { + errors.push(error instanceof Error ? error.message : String(error)); + } + } + } + return errors; +} + +export function validateManifestValue(value: unknown): ManifestValidationResult { + if (!validateSchema(value)) { + return { + valid: false, + errors: (validateSchema.errors ?? []).map(formatAjvError), + }; + } + const semanticErrors = validateSemantics(value); + return semanticErrors.length === 0 + ? { valid: true, manifest: value, errors: [] } + : { valid: false, errors: semanticErrors }; +} + +export async function readAndValidateManifest( + pluginDirectory: string, +): Promise { + const manifestPath = path.join(pluginDirectory, "netcatty.plugin.json"); + const contents = await readFile(manifestPath); + if (contents.byteLength > PACKAGE_LIMITS.manifestBytes) { + throw new Error(`Plugin manifest exceeds ${PACKAGE_LIMITS.manifestBytes} bytes`); + } + let value: unknown; + try { + value = JSON.parse(contents.toString("utf8")); + } catch (error) { + throw new Error( + `Plugin manifest is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + ); + } + const result = validateManifestValue(value); + if (!result.valid || !result.manifest) { + throw new Error(`Plugin manifest is invalid:\n- ${result.errors.join("\n- ")}`); + } + return result.manifest; +} diff --git a/packages/plugin-cli/src/packagePath.ts b/packages/plugin-cli/src/packagePath.ts new file mode 100644 index 000000000..41eaf31d1 --- /dev/null +++ b/packages/plugin-cli/src/packagePath.ts @@ -0,0 +1,52 @@ +import { PACKAGE_LIMITS } from "./constants.js"; + +const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i; +const WINDOWS_SPECIAL = /[<>:"|?*]/; + +function containsControlCharacter(value: string): boolean { + return [...value].some((character) => character.charCodeAt(0) <= 0x1f); +} + +export function assertSafePackagePath(input: string): string { + if (!input || input !== input.normalize("NFC")) { + throw new Error(`Package path must be non-empty NFC text: ${JSON.stringify(input)}`); + } + if (Buffer.byteLength(input, "utf8") > PACKAGE_LIMITS.pathBytes) { + throw new Error(`Package path exceeds ${PACKAGE_LIMITS.pathBytes} UTF-8 bytes: ${input}`); + } + if (input.startsWith("/") || /^[A-Za-z]:/.test(input) || input.includes("\\")) { + throw new Error(`Package path must be relative POSIX syntax: ${input}`); + } + const segments = input.split("/"); + if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) { + throw new Error(`Package path contains an unsafe segment: ${input}`); + } + for (const segment of segments) { + if ( + segment.endsWith(".") + || segment.endsWith(" ") + || WINDOWS_RESERVED_NAME.test(segment) + || WINDOWS_SPECIAL.test(segment) + || containsControlCharacter(segment) + ) { + throw new Error(`Package path is not portable across supported platforms: ${input}`); + } + } + return input; +} + +export class PackagePathRegistry { + readonly #exact = new Set(); + readonly #portable = new Set(); + + add(input: string): string { + const safePath = assertSafePackagePath(input); + const portableKey = safePath.toLowerCase(); + if (this.#exact.has(safePath) || this.#portable.has(portableKey)) { + throw new Error(`Duplicate or case-colliding package path: ${safePath}`); + } + this.#exact.add(safePath); + this.#portable.add(portableKey); + return safePath; + } +} diff --git a/packages/plugin-cli/tsconfig.build.json b/packages/plugin-cli/tsconfig.build.json new file mode 100644 index 000000000..d77c9e9df --- /dev/null +++ b/packages/plugin-cli/tsconfig.build.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist", + "skipLibCheck": true, + "esModuleInterop": true + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/plugin-contract/package.json b/packages/plugin-contract/package.json new file mode 100644 index 000000000..439d0d7af --- /dev/null +++ b/packages/plugin-contract/package.json @@ -0,0 +1,25 @@ +{ + "name": "@netcatty/plugin-contract", + "version": "0.1.0-internal", + "private": true, + "type": "module", + "license": "GPL-3.0-or-later", + "files": [ + "dist", + "schema" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./schema/plugin-contract.schema.json": "./schema/plugin-contract.schema.json" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + }, + "devDependencies": { + "ajv": "8.18.0", + "ajv-formats": "3.0.1" + } +} diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json new file mode 100644 index 000000000..bb5f6b936 --- /dev/null +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -0,0 +1,553 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://netcatty.com/schemas/plugins/0.1.0-internal/plugin-contract.schema.json", + "title": "Netcatty Plugin Contract", + "description": "Canonical public contract for Netcatty plugin manifests and host RPC messages.", + "$ref": "#/$defs/PluginManifest", + "$defs": { + "JsonPrimitive": { + "oneOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "type": "null" } + ] + }, + "JsonValue": { + "oneOf": [ + { "$ref": "#/$defs/JsonPrimitive" }, + { "type": "array", "items": { "$ref": "#/$defs/JsonValue" } }, + { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/JsonValue" } + } + ] + }, + "RelativePackagePath": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^(?!/)(?![A-Za-z]:)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*(?:^|/)\\.(?:/|$)).+$" + }, + "Identifier": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$" + }, + "PluginId": { + "type": "string", + "minLength": 3, + "maxLength": 128, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$" + }, + "LocalizedText": { + "oneOf": [ + { "type": "string", "minLength": 1, "maxLength": 512 }, + { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$" }, + "additionalProperties": { "type": "string", "minLength": 1, "maxLength": 512 } + } + ] + }, + "PluginPermission": { + "type": "string", + "enum": [ + "storage", + "settings", + "commands", + "menus", + "views", + "terminal.read", + "terminal.decorate", + "terminal.complete", + "terminal.transform", + "connection", + "authentication", + "sync", + "import", + "network", + "filesystem", + "secrets", + "companion.execute" + ] + }, + "PermissionDeclaration": { + "oneOf": [ + { "$ref": "#/$defs/PluginPermission" }, + { + "type": "object", + "required": ["permission", "resources"], + "properties": { + "permission": { "$ref": "#/$defs/PluginPermission" }, + "resources": { + "type": "array", + "minItems": 1, + "maxItems": 128, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 2048 } + }, + "reason": { "type": "string", "maxLength": 1024 } + }, + "additionalProperties": false + } + ] + }, + "PermissionSet": { + "type": "object", + "properties": { + "required": { + "type": "array", + "maxItems": 64, + "items": { "$ref": "#/$defs/PermissionDeclaration" } + }, + "optional": { + "type": "array", + "maxItems": 64, + "items": { "$ref": "#/$defs/PermissionDeclaration" } + } + }, + "additionalProperties": false + }, + "PluginEntrypoints": { + "type": "object", + "properties": { + "browser": { "$ref": "#/$defs/RelativePackagePath" }, + "node": { "$ref": "#/$defs/RelativePackagePath" } + }, + "minProperties": 1, + "additionalProperties": false + }, + "PluginEngines": { + "type": "object", + "required": ["netcatty", "api"], + "properties": { + "netcatty": { "type": "string", "minLength": 1, "maxLength": 128 }, + "api": { "const": "0.1.0-internal" } + }, + "additionalProperties": false + }, + "SettingScope": { + "type": "string", + "enum": ["application", "workspace", "host", "session", "device"] + }, + "SettingControl": { + "type": "string", + "enum": [ + "switch", + "select", + "multiselect", + "text", + "textarea", + "number", + "password", + "color", + "keybinding", + "path" + ] + }, + "SettingOption": { + "type": "object", + "required": ["value", "label"], + "properties": { + "value": { "type": "string", "maxLength": 256 }, + "label": { "$ref": "#/$defs/LocalizedText" }, + "description": { "$ref": "#/$defs/LocalizedText" } + }, + "additionalProperties": false + }, + "SettingContribution": { + "type": "object", + "required": ["id", "label", "control", "scope"], + "properties": { + "id": { "$ref": "#/$defs/Identifier" }, + "label": { "$ref": "#/$defs/LocalizedText" }, + "description": { "$ref": "#/$defs/LocalizedText" }, + "control": { "$ref": "#/$defs/SettingControl" }, + "scope": { "$ref": "#/$defs/SettingScope" }, + "default": { "$ref": "#/$defs/JsonValue" }, + "secret": { "type": "boolean", "default": false }, + "required": { "type": "boolean", "default": false }, + "options": { + "type": "array", + "maxItems": 256, + "items": { "$ref": "#/$defs/SettingOption" } + }, + "minimum": { "type": "number" }, + "maximum": { "type": "number" }, + "pattern": { "type": "string", "maxLength": 512 }, + "placeholder": { "$ref": "#/$defs/LocalizedText" }, + "when": { "type": "string", "maxLength": 1024 } + }, + "additionalProperties": false + }, + "CommandContribution": { + "type": "object", + "required": ["id", "title"], + "properties": { + "id": { "$ref": "#/$defs/Identifier" }, + "title": { "$ref": "#/$defs/LocalizedText" }, + "category": { "$ref": "#/$defs/LocalizedText" }, + "description": { "$ref": "#/$defs/LocalizedText" }, + "enablement": { "type": "string", "maxLength": 1024 }, + "defaultKeybinding": { "type": "string", "maxLength": 128 } + }, + "additionalProperties": false + }, + "MenuLocation": { + "type": "string", + "enum": [ + "commandPalette", + "application", + "host/context", + "terminal/context", + "terminal/toolbar", + "statusBar" + ] + }, + "MenuContribution": { + "type": "object", + "required": ["command", "location"], + "properties": { + "command": { "$ref": "#/$defs/Identifier" }, + "location": { "$ref": "#/$defs/MenuLocation" }, + "group": { "type": "string", "maxLength": 128 }, + "order": { "type": "number" }, + "when": { "type": "string", "maxLength": 1024 } + }, + "additionalProperties": false + }, + "ViewLocation": { + "type": "string", + "enum": ["aside", "panel", "tab", "modal", "settings"] + }, + "ViewContribution": { + "type": "object", + "required": ["id", "title", "location", "entry"], + "properties": { + "id": { "$ref": "#/$defs/Identifier" }, + "title": { "$ref": "#/$defs/LocalizedText" }, + "location": { "$ref": "#/$defs/ViewLocation" }, + "entry": { "$ref": "#/$defs/RelativePackagePath" }, + "when": { "type": "string", "maxLength": 1024 }, + "retainContextWhenHidden": { "type": "boolean", "default": false } + }, + "additionalProperties": false + }, + "ProviderKind": { + "type": "string", + "enum": [ + "terminal.completion", + "terminal.decoration", + "terminal.link", + "terminal.hover", + "terminal.matcher", + "terminal.semantic", + "terminal.prompt", + "terminal.background", + "terminal.interceptor", + "connection", + "authentication", + "sync", + "importer" + ] + }, + "ProviderContribution": { + "type": "object", + "required": ["id", "label", "kind"], + "properties": { + "id": { "$ref": "#/$defs/Identifier" }, + "label": { "$ref": "#/$defs/LocalizedText" }, + "description": { "$ref": "#/$defs/LocalizedText" }, + "kind": { "$ref": "#/$defs/ProviderKind" }, + "activationEvent": { "type": "string", "minLength": 1, "maxLength": 256 }, + "capabilities": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "configuration": { "$ref": "#/$defs/JsonValue" } + }, + "additionalProperties": false + }, + "CompanionExecutable": { + "type": "object", + "required": ["id", "path", "platforms", "sha256"], + "properties": { + "id": { "$ref": "#/$defs/Identifier" }, + "path": { "$ref": "#/$defs/RelativePackagePath" }, + "platforms": { + "type": "array", + "minItems": 1, + "maxItems": 12, + "uniqueItems": true, + "items": { + "enum": [ + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64", + "win32-arm64", + "win32-x64" + ] + } + }, + "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "permissions": { + "type": "array", + "maxItems": 32, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 128 } + } + }, + "additionalProperties": false + }, + "PluginContributions": { + "type": "object", + "properties": { + "settings": { "type": "array", "maxItems": 512, "items": { "$ref": "#/$defs/SettingContribution" } }, + "commands": { "type": "array", "maxItems": 512, "items": { "$ref": "#/$defs/CommandContribution" } }, + "menus": { "type": "array", "maxItems": 1024, "items": { "$ref": "#/$defs/MenuContribution" } }, + "views": { "type": "array", "maxItems": 128, "items": { "$ref": "#/$defs/ViewContribution" } }, + "providers": { "type": "array", "maxItems": 256, "items": { "$ref": "#/$defs/ProviderContribution" } } + }, + "additionalProperties": false + }, + "PluginManifest": { + "type": "object", + "required": ["manifestVersion", "id", "name", "version", "publisher", "engines", "main"], + "properties": { + "$schema": { "type": "string", "format": "uri-reference" }, + "manifestVersion": { "const": 1 }, + "id": { "$ref": "#/$defs/PluginId" }, + "name": { "type": "string", "minLength": 1, "maxLength": 128 }, + "displayName": { "$ref": "#/$defs/LocalizedText" }, + "description": { "$ref": "#/$defs/LocalizedText" }, + "version": { + "type": "string", + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" + }, + "publisher": { "type": "string", "minLength": 1, "maxLength": 128 }, + "license": { "type": "string", "maxLength": 128 }, + "homepage": { "type": "string", "format": "uri" }, + "repository": { "type": "string", "format": "uri" }, + "engines": { "$ref": "#/$defs/PluginEngines" }, + "main": { "$ref": "#/$defs/PluginEntrypoints" }, + "activationEvents": { + "type": "array", + "maxItems": 256, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 256 } + }, + "permissions": { "$ref": "#/$defs/PermissionSet" }, + "contributes": { "$ref": "#/$defs/PluginContributions" }, + "companionExecutables": { + "type": "array", + "maxItems": 32, + "items": { "$ref": "#/$defs/CompanionExecutable" } + } + }, + "additionalProperties": false + }, + "RpcId": { + "oneOf": [ + { "type": "string", "minLength": 1, "maxLength": 128 }, + { "type": "integer", "minimum": 0 } + ] + }, + "RpcRequest": { + "type": "object", + "required": ["jsonrpc", "id", "method"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "id": { "$ref": "#/$defs/RpcId" }, + "method": { "type": "string", "minLength": 1, "maxLength": 256 }, + "params": { "$ref": "#/$defs/JsonValue" }, + "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, + "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + }, + "RpcNotification": { + "type": "object", + "required": ["jsonrpc", "method"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "method": { "type": "string", "minLength": 1, "maxLength": 256 }, + "params": { "$ref": "#/$defs/JsonValue" } + }, + "additionalProperties": false + }, + "RpcSuccess": { + "type": "object", + "required": ["jsonrpc", "id", "result"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "id": { "$ref": "#/$defs/RpcId" }, + "result": { "$ref": "#/$defs/JsonValue" } + }, + "additionalProperties": false + }, + "RpcErrorObject": { + "type": "object", + "required": ["code", "message"], + "properties": { + "code": { "type": "integer" }, + "message": { "type": "string", "minLength": 1, "maxLength": 2048 }, + "data": { "$ref": "#/$defs/JsonValue" } + }, + "additionalProperties": false + }, + "RpcFailure": { + "type": "object", + "required": ["jsonrpc", "id", "error"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "id": { "$ref": "#/$defs/RpcId" }, + "error": { "$ref": "#/$defs/RpcErrorObject" } + }, + "additionalProperties": false + }, + "RpcCancel": { + "type": "object", + "required": ["jsonrpc", "method", "params"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "method": { "const": "$/cancelRequest" }, + "params": { + "type": "object", + "required": ["cancellationId"], + "properties": { + "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "StreamFrame": { + "oneOf": [ + { + "type": "object", + "required": ["streamId", "sequence", "kind"], + "properties": { + "streamId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "sequence": { "type": "integer", "minimum": 0 }, + "kind": { "const": "open" }, + "windowBytes": { "type": "integer", "minimum": 1024, "maximum": 16777216 } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["streamId", "sequence", "kind", "data"], + "properties": { + "streamId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "sequence": { "type": "integer", "minimum": 0 }, + "kind": { "const": "chunk" }, + "data": { "$ref": "#/$defs/JsonValue" }, + "byteLength": { "type": "integer", "minimum": 0, "maximum": 16777216 } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["streamId", "sequence", "kind"], + "properties": { + "streamId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "sequence": { "type": "integer", "minimum": 0 }, + "kind": { "enum": ["end", "cancel"] } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["streamId", "sequence", "kind", "error"], + "properties": { + "streamId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "sequence": { "type": "integer", "minimum": 0 }, + "kind": { "const": "error" }, + "error": { "$ref": "#/$defs/RpcErrorObject" } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["streamId", "sequence", "kind", "windowBytes"], + "properties": { + "streamId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "sequence": { "type": "integer", "minimum": 0 }, + "kind": { "const": "windowUpdate" }, + "windowBytes": { "type": "integer", "minimum": 1, "maximum": 16777216 } + }, + "additionalProperties": false + } + ] + }, + "PermissionGrantScope": { + "type": "string", + "enum": ["once", "session", "application", "always"] + }, + "PermissionRequest": { + "type": "object", + "required": ["requestId", "pluginId", "permission", "reason"], + "properties": { + "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "pluginId": { "$ref": "#/$defs/PluginId" }, + "permission": { "$ref": "#/$defs/PluginPermission" }, + "resources": { + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 2048 } + }, + "reason": { "type": "string", "minLength": 1, "maxLength": 1024 }, + "operationId": { "type": "string", "maxLength": 128 } + }, + "additionalProperties": false + }, + "PermissionDecision": { + "type": "object", + "required": ["requestId", "decision"], + "properties": { + "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "decision": { "enum": ["allow", "deny", "cancel"] }, + "scope": { "$ref": "#/$defs/PermissionGrantScope" }, + "resources": { + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 2048 } + } + }, + "additionalProperties": false + }, + "ProviderRequest": { + "type": "object", + "required": ["providerId", "operation", "requestId"], + "properties": { + "providerId": { "$ref": "#/$defs/Identifier" }, + "operation": { "type": "string", "minLength": 1, "maxLength": 128 }, + "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "payload": { "$ref": "#/$defs/JsonValue" }, + "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, + "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + }, + "ProviderResult": { + "type": "object", + "required": ["requestId", "status"], + "properties": { + "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "status": { "enum": ["ok", "cancelled", "failed"] }, + "result": { "$ref": "#/$defs/JsonValue" }, + "error": { "$ref": "#/$defs/RpcErrorObject" } + }, + "additionalProperties": false + } + } +} diff --git a/packages/plugin-contract/src/contract.test.ts b/packages/plugin-contract/src/contract.test.ts new file mode 100644 index 000000000..2841dcb56 --- /dev/null +++ b/packages/plugin-contract/src/contract.test.ts @@ -0,0 +1,92 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; + +import Ajv2020 from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; + +const schema = JSON.parse( + await readFile( + new URL("../schema/plugin-contract.schema.json", import.meta.url), + "utf8", + ), +); +const ajv = new Ajv2020({ allErrors: true, strict: true }); +addFormats(ajv); +ajv.addSchema(schema); + +function validator(definition: string) { + return ajv.compile({ $ref: `${schema.$id}#/$defs/${definition}` }); +} + +const validManifest = { + manifestVersion: 1, + id: "com.example.contract-test", + name: "contract-test", + version: "1.2.3-beta.1", + publisher: "example", + engines: { netcatty: ">=1.0.0", api: "0.1.0-internal" }, + main: { browser: "dist/browser.js" }, + permissions: { required: ["commands"], optional: ["network"] }, + contributes: { + commands: [{ id: "contract.run", title: "Run" }], + menus: [{ command: "contract.run", location: "commandPalette" }], + providers: [{ id: "contract.completion", label: "Completion", kind: "terminal.completion" }], + }, +}; + +test("plugin manifest schema accepts the internal contract", () => { + const validate = validator("PluginManifest"); + assert.equal(validate(validManifest), true, JSON.stringify(validate.errors)); +}); + +test("plugin manifest schema rejects unknown properties and traversal", () => { + const validate = validator("PluginManifest"); + assert.equal(validate({ ...validManifest, unexpected: true }), false); + assert.equal( + validate({ ...validManifest, main: { browser: "../outside.js" } }), + false, + ); +}); + +test("RPC, stream, permission, and provider schemas validate independently", () => { + const rpc = validator("RpcRequest"); + const stream = validator("StreamFrame"); + const permission = validator("PermissionRequest"); + const provider = validator("ProviderRequest"); + + assert.equal(rpc({ jsonrpc: "2.0", id: "1", method: "settings.get", deadlineMs: 1000 }), true); + assert.equal(stream({ streamId: "s1", sequence: 0, kind: "open", windowBytes: 65536 }), true); + assert.equal(permission({ + requestId: "p1", + pluginId: "com.example.contract-test", + permission: "network", + reason: "Fetch completion metadata", + resources: ["https://api.example.com"], + }), true); + assert.equal(provider({ + providerId: "contract.completion", + operation: "provideCompletions", + requestId: "r1", + deadlineMs: 500, + }), true); +}); + +test("secret setting defaults are excluded by the semantic CLI validator", async () => { + const { validateManifestValue } = await import("../../plugin-cli/src/manifest.ts"); + const result = validateManifestValue({ + ...validManifest, + contributes: { + settings: [{ + id: "contract.token", + label: "Token", + control: "password", + scope: "application", + secret: true, + default: "must-not-ship", + }], + }, + }); + assert.equal(result.valid, false); + assert.match(result.errors.join("\n"), /must not declare a default/); +}); diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts new file mode 100644 index 000000000..2361de5d0 --- /dev/null +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -0,0 +1,247 @@ +// This file is generated from schema/plugin-contract.schema.json. +// Run `npm run generate:plugin-contract` after changing the contract. +// Do not edit this file directly. + +export type CommandContribution = { + id: Identifier; + title: LocalizedText; + category?: LocalizedText; + description?: LocalizedText; + enablement?: string; + defaultKeybinding?: string; +}; + +export type CompanionExecutable = { + id: Identifier; + path: RelativePackagePath; + platforms: Array<"darwin-arm64" | "darwin-x64" | "linux-arm64" | "linux-x64" | "win32-arm64" | "win32-x64">; + sha256: string; + permissions?: Array; +}; + +export type Identifier = string; + +export type JsonPrimitive = (string) | (number) | (boolean) | (null); + +export type JsonValue = (JsonPrimitive) | (Array) | ({ [key: string]: JsonValue }); + +export type LocalizedText = (string) | ({ [key: string]: string }); + +export type MenuContribution = { + command: Identifier; + location: MenuLocation; + group?: string; + order?: number; + when?: string; +}; + +export type MenuLocation = "commandPalette" | "application" | "host/context" | "terminal/context" | "terminal/toolbar" | "statusBar"; + +export type PermissionDecision = { + requestId: string; + decision: "allow" | "deny" | "cancel"; + scope?: PermissionGrantScope; + resources?: Array; +}; + +export type PermissionDeclaration = (PluginPermission) | ({ + permission: PluginPermission; + resources: Array; + reason?: string; +}); + +export type PermissionGrantScope = "once" | "session" | "application" | "always"; + +export type PermissionRequest = { + requestId: string; + pluginId: PluginId; + permission: PluginPermission; + resources?: Array; + reason: string; + operationId?: string; +}; + +export type PermissionSet = { + required?: Array; + optional?: Array; +}; + +export type PluginContributions = { + settings?: Array; + commands?: Array; + menus?: Array; + views?: Array; + providers?: Array; +}; + +export type PluginEngines = { + netcatty: string; + api: "0.1.0-internal"; +}; + +export type PluginEntrypoints = { + browser?: RelativePackagePath; + node?: RelativePackagePath; +}; + +export type PluginId = string; + +export type PluginManifest = { + $schema?: string; + manifestVersion: 1; + id: PluginId; + name: string; + displayName?: LocalizedText; + description?: LocalizedText; + version: string; + publisher: string; + license?: string; + homepage?: string; + repository?: string; + engines: PluginEngines; + main: PluginEntrypoints; + activationEvents?: Array; + permissions?: PermissionSet; + contributes?: PluginContributions; + companionExecutables?: Array; +}; + +export type PluginPermission = "storage" | "settings" | "commands" | "menus" | "views" | "terminal.read" | "terminal.decorate" | "terminal.complete" | "terminal.transform" | "connection" | "authentication" | "sync" | "import" | "network" | "filesystem" | "secrets" | "companion.execute"; + +export type ProviderContribution = { + id: Identifier; + label: LocalizedText; + description?: LocalizedText; + kind: ProviderKind; + activationEvent?: string; + capabilities?: Array; + configuration?: JsonValue; +}; + +export type ProviderKind = "terminal.completion" | "terminal.decoration" | "terminal.link" | "terminal.hover" | "terminal.matcher" | "terminal.semantic" | "terminal.prompt" | "terminal.background" | "terminal.interceptor" | "connection" | "authentication" | "sync" | "importer"; + +export type ProviderRequest = { + providerId: Identifier; + operation: string; + requestId: string; + payload?: JsonValue; + deadlineMs?: number; + cancellationId?: string; +}; + +export type ProviderResult = { + requestId: string; + status: "ok" | "cancelled" | "failed"; + result?: JsonValue; + error?: RpcErrorObject; +}; + +export type RelativePackagePath = string; + +export type RpcCancel = { + jsonrpc: "2.0"; + method: "$/cancelRequest"; + params: { + cancellationId: string; + }; +}; + +export type RpcErrorObject = { + code: number; + message: string; + data?: JsonValue; +}; + +export type RpcFailure = { + jsonrpc: "2.0"; + id: RpcId; + error: RpcErrorObject; +}; + +export type RpcId = (string) | (number); + +export type RpcNotification = { + jsonrpc: "2.0"; + method: string; + params?: JsonValue; +}; + +export type RpcRequest = { + jsonrpc: "2.0"; + id: RpcId; + method: string; + params?: JsonValue; + deadlineMs?: number; + cancellationId?: string; +}; + +export type RpcSuccess = { + jsonrpc: "2.0"; + id: RpcId; + result: JsonValue; +}; + +export type SettingContribution = { + id: Identifier; + label: LocalizedText; + description?: LocalizedText; + control: SettingControl; + scope: SettingScope; + default?: JsonValue; + secret?: boolean; + required?: boolean; + options?: Array; + minimum?: number; + maximum?: number; + pattern?: string; + placeholder?: LocalizedText; + when?: string; +}; + +export type SettingControl = "switch" | "select" | "multiselect" | "text" | "textarea" | "number" | "password" | "color" | "keybinding" | "path"; + +export type SettingOption = { + value: string; + label: LocalizedText; + description?: LocalizedText; +}; + +export type SettingScope = "application" | "workspace" | "host" | "session" | "device"; + +export type StreamFrame = ({ + streamId: string; + sequence: number; + kind: "open"; + windowBytes?: number; +}) | ({ + streamId: string; + sequence: number; + kind: "chunk"; + data: JsonValue; + byteLength?: number; +}) | ({ + streamId: string; + sequence: number; + kind: "end" | "cancel"; +}) | ({ + streamId: string; + sequence: number; + kind: "error"; + error: RpcErrorObject; +}) | ({ + streamId: string; + sequence: number; + kind: "windowUpdate"; + windowBytes: number; +}); + +export type ViewContribution = { + id: Identifier; + title: LocalizedText; + location: ViewLocation; + entry: RelativePackagePath; + when?: string; + retainContextWhenHidden?: boolean; +}; + +export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "settings"; diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts new file mode 100644 index 000000000..8b811a8c3 --- /dev/null +++ b/packages/plugin-contract/src/index.ts @@ -0,0 +1,5 @@ +export const PLUGIN_API_VERSION = "0.1.0-internal" as const; +export const PLUGIN_MANIFEST_FILE = "netcatty.plugin.json" as const; +export const PLUGIN_PACKAGE_EXTENSION = ".ncpkg" as const; + +export type * from "./generated/plugin-contract.js"; diff --git a/packages/plugin-contract/tsconfig.build.json b/packages/plugin-contract/tsconfig.build.json new file mode 100644 index 000000000..a6820658e --- /dev/null +++ b/packages/plugin-contract/tsconfig.build.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json new file mode 100644 index 000000000..d9cad9795 --- /dev/null +++ b/packages/plugin-sdk/package.json @@ -0,0 +1,20 @@ +{ + "name": "@netcatty/plugin-sdk", + "version": "0.1.0-internal", + "private": true, + "type": "module", + "license": "GPL-3.0-or-later", + "files": ["dist"], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + }, + "dependencies": { + "@netcatty/plugin-contract": "0.1.0-internal" + } +} diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts new file mode 100644 index 000000000..eb7cf785a --- /dev/null +++ b/packages/plugin-sdk/src/index.test.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + CancellationError, + CancellationTokenSource, + definePlugin, + DisposableStore, + PluginError, + throwIfCancellationRequested, +} from "./index.ts"; + +test("definePlugin preserves the exact plugin object", () => { + const plugin = definePlugin({ activate() {} }); + assert.equal(typeof plugin.activate, "function"); +}); + +test("DisposableStore disposes every item once", () => { + const store = new DisposableStore(); + const calls: string[] = []; + store.add({ dispose: () => calls.push("first") }); + store.add({ dispose: () => calls.push("second") }); + + store.dispose(); + store.dispose(); + + assert.deepEqual(calls, ["first", "second"]); +}); + +test("DisposableStore disposes rejected late additions", () => { + const store = new DisposableStore(); + store.dispose(); + let disposed = false; + + assert.throws( + () => store.add({ dispose: () => { disposed = true; } }), + (error) => error instanceof PluginError && error.code === "unavailable", + ); + assert.equal(disposed, true); +}); + +test("CancellationTokenSource notifies listeners once", () => { + const source = new CancellationTokenSource(); + let count = 0; + source.token.onCancellationRequested(() => count += 1); + + source.cancel(); + source.cancel(); + + assert.equal(count, 1); + assert.equal(source.token.isCancellationRequested, true); + assert.throws( + () => throwIfCancellationRequested(source.token), + CancellationError, + ); +}); diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts new file mode 100644 index 000000000..ec64ac8d3 --- /dev/null +++ b/packages/plugin-sdk/src/index.ts @@ -0,0 +1,183 @@ +import type { JsonValue } from "@netcatty/plugin-contract"; + +export type * from "@netcatty/plugin-contract"; + +export interface Disposable { + dispose(): void; +} + +export type CancellationListener = () => void; + +export interface CancellationToken { + readonly isCancellationRequested: boolean; + onCancellationRequested(listener: CancellationListener): Disposable; +} + +export interface PluginLogger { + debug(message: string, fields?: Readonly>): void; + info(message: string, fields?: Readonly>): void; + warn(message: string, fields?: Readonly>): void; + error(message: string, fields?: Readonly>): void; +} + +export interface PluginKeyValueStore { + get(key: string): Promise; + set(key: string, value: JsonValue): Promise; + delete(key: string): Promise; + keys(): Promise; +} + +export interface PluginSecretStore { + get(key: string): Promise; + set(key: string, value: string): Promise; + delete(key: string): Promise; +} + +export interface PluginContext { + readonly pluginId: string; + readonly subscriptions: DisposableStore; + readonly storage: PluginKeyValueStore; + readonly secrets: PluginSecretStore; + readonly logger: PluginLogger; +} + +export interface NetcattyPlugin { + activate(context: PluginContext): void | Disposable | Promise; + deactivate?(): void | Promise; +} + +export type PluginErrorCode = + | "cancelled" + | "deadline_exceeded" + | "invalid_argument" + | "not_found" + | "permission_denied" + | "resource_exhausted" + | "unavailable" + | "unsupported" + | "internal"; + +export class PluginError extends Error { + readonly code: PluginErrorCode; + readonly details?: JsonValue; + + constructor(code: PluginErrorCode, message: string, details?: JsonValue) { + super(message); + this.name = "PluginError"; + this.code = code; + this.details = details; + } +} + +export class CancellationError extends PluginError { + constructor(message = "The operation was cancelled") { + super("cancelled", message); + this.name = "CancellationError"; + } +} + +export class DisposableStore implements Disposable { + readonly #items = new Set(); + #isDisposed = false; + + get isDisposed(): boolean { + return this.#isDisposed; + } + + add(disposable: T): T { + if (this.#isDisposed) { + disposable.dispose(); + throw new PluginError("unavailable", "Cannot add to a disposed DisposableStore"); + } + this.#items.add(disposable); + return disposable; + } + + delete(disposable: Disposable): boolean { + return this.#items.delete(disposable); + } + + clear(): void { + const items = [...this.#items]; + this.#items.clear(); + const errors: unknown[] = []; + for (const item of items) { + try { + item.dispose(); + } catch (error) { + errors.push(error); + } + } + if (errors.length > 0) { + throw new AggregateError(errors, "One or more plugin disposables failed"); + } + } + + dispose(): void { + if (this.#isDisposed) return; + this.#isDisposed = true; + this.clear(); + } +} + +class MutableCancellationToken implements CancellationToken { + readonly #listeners = new Set(); + #isCancellationRequested = false; + + get isCancellationRequested(): boolean { + return this.#isCancellationRequested; + } + + onCancellationRequested(listener: CancellationListener): Disposable { + if (this.#isCancellationRequested) { + queueMicrotask(listener); + return { dispose() {} }; + } + this.#listeners.add(listener); + return { + dispose: () => { + this.#listeners.delete(listener); + }, + }; + } + + cancel(): void { + if (this.#isCancellationRequested) return; + this.#isCancellationRequested = true; + const listeners = [...this.#listeners]; + this.#listeners.clear(); + for (const listener of listeners) listener(); + } + + dispose(): void { + this.#listeners.clear(); + } +} + +export class CancellationTokenSource implements Disposable { + readonly #token = new MutableCancellationToken(); + #isDisposed = false; + + get token(): CancellationToken { + return this.#token; + } + + cancel(): void { + if (!this.#isDisposed) this.#token.cancel(); + } + + dispose(cancel = false): void { + if (this.#isDisposed) return; + if (cancel) this.#token.cancel(); + this.#token.dispose(); + this.#isDisposed = true; + } +} + +export function definePlugin(plugin: T): T { + return plugin; +} + +export function throwIfCancellationRequested(token: CancellationToken): void { + if (token.isCancellationRequested) throw new CancellationError(); +} diff --git a/packages/plugin-sdk/tsconfig.build.json b/packages/plugin-sdk/tsconfig.build.json new file mode 100644 index 000000000..a6820658e --- /dev/null +++ b/packages/plugin-sdk/tsconfig.build.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/scripts/generate-plugin-contract.mjs b/scripts/generate-plugin-contract.mjs new file mode 100644 index 000000000..cceadc303 --- /dev/null +++ b/scripts/generate-plugin-contract.mjs @@ -0,0 +1,144 @@ +import { readFile, mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const schemaPath = path.join( + rootDir, + "packages/plugin-contract/schema/plugin-contract.schema.json", +); +const generatedTypesPath = path.join( + rootDir, + "packages/plugin-contract/src/generated/plugin-contract.ts", +); +const electronBundlePath = path.join( + rootDir, + "electron/plugins/generated/plugin-contract.schema.json", +); +const checkOnly = process.argv.includes("--check"); + +const schemaText = await readFile(schemaPath, "utf8"); +const schema = JSON.parse(schemaText); + +if (schema.$schema !== "https://json-schema.org/draft/2020-12/schema") { + throw new Error("Plugin contract must use JSON Schema 2020-12"); +} +if (!schema.$id?.includes("/0.1.0-internal/")) { + throw new Error("Plugin contract $id must include the internal API version"); +} +if (!schema.$defs || typeof schema.$defs !== "object") { + throw new Error("Plugin contract must define $defs"); +} + +function quoteProperty(name) { + return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name); +} + +function literal(value) { + return JSON.stringify(value); +} + +function referenceName(reference) { + const prefix = "#/$defs/"; + if (typeof reference !== "string" || !reference.startsWith(prefix)) { + throw new Error(`Unsupported schema reference: ${String(reference)}`); + } + return decodeURIComponent(reference.slice(prefix.length)); +} + +function schemaTypeToTs(node, level = 0) { + if (node === true) return "unknown"; + if (node === false) return "never"; + if (!node || typeof node !== "object") return "unknown"; + if ("$ref" in node) return referenceName(node.$ref); + if ("const" in node) return literal(node.const); + if (Array.isArray(node.enum)) return node.enum.map(literal).join(" | ") || "never"; + + for (const keyword of ["oneOf", "anyOf"]) { + if (Array.isArray(node[keyword])) { + return node[keyword].map((entry) => `(${schemaTypeToTs(entry, level)})`).join(" | "); + } + } + if (Array.isArray(node.allOf)) { + return node.allOf.map((entry) => `(${schemaTypeToTs(entry, level)})`).join(" & "); + } + if (Array.isArray(node.type)) { + return node.type.map((entry) => schemaTypeToTs({ ...node, type: entry }, level)).join(" | "); + } + + if (node.type === "null") return "null"; + if (node.type === "string") return "string"; + if (node.type === "number" || node.type === "integer") return "number"; + if (node.type === "boolean") return "boolean"; + if (node.type === "array") { + return `Array<${schemaTypeToTs(node.items ?? true, level)}>`; + } + if (node.type === "object" || node.properties || node.additionalProperties) { + const properties = node.properties ?? {}; + const entries = Object.entries(properties); + const required = new Set(node.required ?? []); + const additional = node.additionalProperties; + + if (entries.length === 0) { + if (additional && typeof additional === "object") { + return `{ [key: string]: ${schemaTypeToTs(additional, level)} }`; + } + return additional === false ? "Record" : "Record"; + } + + const indent = " ".repeat(level + 1); + const closingIndent = " ".repeat(level); + const body = entries.map(([name, propertySchema]) => { + const optional = required.has(name) ? "" : "?"; + return `${indent}${quoteProperty(name)}${optional}: ${schemaTypeToTs(propertySchema, level + 1)};`; + }); + let objectType = `{\n${body.join("\n")}\n${closingIndent}}`; + if (additional && typeof additional === "object") { + objectType = `(${objectType} & Record)`; + } + return objectType; + } + return "unknown"; +} + +const definitionNames = Object.keys(schema.$defs).sort((left, right) => + left.localeCompare(right, "en"), +); +const generatedTypes = [ + "// This file is generated from schema/plugin-contract.schema.json.", + "// Run `npm run generate:plugin-contract` after changing the contract.", + "// Do not edit this file directly.", + "", + ...definitionNames.flatMap((name) => [ + `export type ${name} = ${schemaTypeToTs(schema.$defs[name])};`, + "", + ]), +].join("\n"); +const normalizedSchema = `${JSON.stringify(schema, null, 2)}\n`; + +async function assertCurrent(filePath, expected, label) { + let actual; + try { + actual = await readFile(filePath, "utf8"); + } catch { + throw new Error(`${label} is missing. Run npm run generate:plugin-contract.`); + } + if (actual !== expected) { + throw new Error(`${label} is out of date. Run npm run generate:plugin-contract.`); + } +} + +if (checkOnly) { + await assertCurrent(generatedTypesPath, generatedTypes, "Generated plugin TypeScript contract"); + await assertCurrent(electronBundlePath, normalizedSchema, "Electron plugin schema bundle"); + console.log("Plugin contract generated artifacts are current."); +} else { + await mkdir(path.dirname(generatedTypesPath), { recursive: true }); + await mkdir(path.dirname(electronBundlePath), { recursive: true }); + await Promise.all([ + writeFile(generatedTypesPath, generatedTypes, "utf8"), + writeFile(electronBundlePath, normalizedSchema, "utf8"), + ]); + console.log("Generated plugin TypeScript contract and Electron schema bundle."); +}