# Packages

> How modules are packaged, versioned, installed, and updated.

URL: https://www.trakhound.com/docs/trakhound-framework/packages

Every module in TrakHound is distributed as a Package. Packages keep projects organized, are versioned, and can be installed on any number of Instances.

Diagram: A project with a trakhound.package.json manifest is built by the CLI into a .thp Package file. The file is published to a Package source and installed on an Instance, either from the source or uploaded, along with its dependencies. Versions are installed side by side, and configurations using the Package load the new version without restarting.

## Package Manifest

Each Package project contains a `trakhound.package.json` manifest:

```
{
  "id": "MyCompany.Example.Api",
  "category": "api",
  "metadata": {
    "publisher": "My Company",
    "description": "Example API",
    ".defaultRoute": "/api/example"
  },
  "dependencies": [
    { "id": "MyCompany.Example.Shared", "version": "1.0.0" },
    { "id": "TrakHound.Memory.Service", "version": "1.*", "minimumVersion": "1.2.0" }
  ]
}
```

| Key | Description |
| --- | --- |
| `id` | Unique ID of the Package. The project's assembly must be named `{id}.dll`. |
| `category` | `api`, `app`, `function`, `worker`, `service`, or `identity`. |
| `metadata` | Information about the Package such as `publisher`, `description`, `project`, and `repository`. Keys starting with `.` are settings used by TrakHound (see below). |
| `dependencies` | Other Packages that are installed along with this Package: `id`, `version`, and an optional `minimumVersion`. |

### Dependencies

A dependency's `version` is an exact version (`1.0.0`) or a wildcard (`1.*` matches any 1.x version). Add `minimumVersion` when your Package needs a feature added in a later version: `"version": "1.*", "minimumVersion": "1.2.0"` accepts 1.2.0 or newer, but not 2.x.

- An installed dependency that matches is kept. Otherwise the latest matching version is downloaded, and the install fails if it is still below the minimum.
- The admin UI shows each dependency's version and minimum (ex. `1.* (>= 1.2.0)`), and flags installed dependencies that don't satisfy it.
- Packing fails if `minimumVersion` isn't a valid version, or is higher than an exact `version`.

### Metadata Settings

| Key | Description |
| --- | --- |
| `.defaultRoute` | Default route for an API or App when it is configured. |
| `.defaultVolumeId` | Default Volume ID used when the Package is configured. |
| `.configurationParameters` | Comma separated parameter names (ex. `"host,port,useSsl"`) shown as fields in the admin UI's configuration form. |
| `.image` | Image shown for the Package in the admin UI. |
| `.licenseRequired` | Set to `"true"` when the Package requires a license. |
| `.licensePublisherId`, `.licenseProductId` | Identify the license the Package checks for. |
| `.licenseRequestUrl` | URL where users can request a license. |

## Publishing

### Versions from Git

A Package's version comes from git. The `version` in `trakhound.package.json` is a two part prefix you set by hand (ex. `"0.3"`), and the CLI adds the **height**: the number of commits since that line last changed. So `"0.3"` four commits later builds `0.3.4`.

- The same commit always builds the same version, on any machine, and the CLI never writes a version back to a file. Commit before publishing a new version.
- Change the prefix to start a new version line (ex. `"0.4"`, which is `0.4.0` until it's committed). `--version` sets a whole version instead.
- A version is never replaced, so the CLI stops if it's already published. The height needs the full history, so the CLI stops in a shallow clone.

### Publish Targets

A `trakhound.package.publish.json` file sets where Packages are published, as named **Publish Targets**. The CLI uses the nearest one, looking in the project folder and then each parent folder, so one file at the root of a repository covers every Package in it:

```
{
  "defaultTarget": "development",
  "targets": {
    "development": {
      "destinations": [ { "managementServer": "http://packages.mycompany.local:8472", "organization": "MyCompany" } ],
      "versionSuffix": "dev{branch}.{timestamp}",
      "allowDirty": true
    },
    "release": {
      "destinations": [ { "managementServer": "https://packages.mycompany.com", "organization": "MyCompany", "apiTokenVariable": "MYCOMPANY_RELEASE_TOKEN" } ],
      "requireSigning": true
    }
  }
}
```

| Setting | Description |
| --- | --- |
| `destinations` | The package servers and organizations to upload to. `apiTokenVariable` names the environment variable that holds that server's API Token, so the tokens never go in the file. |
| `versionSuffix` | A prerelease label for every version published to the Target. `{timestamp}` is the UTC time of the run, and `{branch}` is empty on `main` and `-[branch]` on other branches, so development builds are `0.3.4-dev.20261114153000`. Without it, the Target publishes stable versions. |
| `allowDirty` | Build uncommitted changes (needs `{timestamp}` in the suffix, so each build has its own version). Other Targets refuse uncommitted changes. |
| `requireSigning` | Packages must be [signed](https://www.trakhound.com/docs/trakhound-framework/packages#verification) and built from a clean commit. |

```
th packages dotnet --publish                    # defaultTarget : 0.3.4-dev.20261114153000
th packages dotnet --publish --target release   # 0.3.4
```

- A Package goes to every destination of the Target or to none: if a destination can't be read (ex. an unreachable server), nothing is uploaded. The Target's tokens, signing key, and uncommitted changes are checked before building.
- `--skip-existing` skips a destination that already has the version when it was published from the same commit, ex. after a `build` that stopped partway.
- Without a `trakhound.package.publish.json`, `--server` and `--organization` set where to publish.

Publish with `th packages dotnet --publish`, or in Visual Studio with the TrakHound extension: **Publish TrakHound Package** publishes one project, and **Publish TrakHound Packages...** publishes the projects in a `trakhound.build.json` together, in dependency order, and only if every one builds. Both are on the project's right-click menu in Solution Explorer and the Tools menu. See the [CLI](https://www.trakhound.com/docs/trakhound-framework/cli).

## Package Files

A packed Package is a single `.thp` file containing:

- `package.json` - The Package information (ID, version, category, the TrakHound version it was built against, build date, hash, metadata, and dependencies)
- `dist/` - The build output that is loaded by the Instance
- `src/` - The source code (optional)
- `Readme` and `License` files (optional)

## Versions

Multiple versions of a Package can be installed side by side. Each configuration chooses the version to load with `packageVersion`. A version of `*` uses the newest stable version, and patterns such as `1.2.*` also work. A prerelease is only selected if no stable version matches, so with `1.9.0` and `2.0.0-beta` installed, `*` selects `1.9.0` and logs that a newer prerelease was skipped. To include prereleases, add `-*` (`*-*` or `1.2.*-*`), or use the exact version. In the admin UI, that's a configuration's **Include Prereleases** switch, and prerelease updates are only offered to those configurations.

> TrakHound's own libraries (`TrakHound.Common` and `TrakHound.Blazor`) are provided by the Instance, so a Package built against a newer TrakHound version than the Instance fails to load. Build against the Instance's TrakHound version or older.

## Hot Loading

Instances watch the package directory for changes. When a new version of a Package is installed, configurations using it are reloaded with the new version without restarting the Instance.

## Installing Packages

Packages are installed in several ways:

- From the **Packages** page in the admin UI
- With the CLI: `th packages install <packageId>`, or `th packages install --file <file.thp>` for a local Package file. `--configure` also adds the default configuration for the Package and its dependencies, as the admin UI does
- As part of a [Deployment](https://www.trakhound.com/docs/trakhound-framework/configuration#deployments)

| Packages Tab | What you can do |
| --- | --- |
| **Installed** | See each Package's Category, Version, the configurations using it, Size, and Latest version. Remove versions, **Revert** to the previous version, install an update, or **Clean Unused** Packages no configuration uses. **Verify All** checks each Package, and expanding one shows who signed each version, the commit and build it came from, and its **SBOM** (see [Signing and Verification](https://www.trakhound.com/docs/trakhound-framework/packages#verification)). |
| **Updates** | The installed Packages that have a newer version on the selected source. Sources are checked every 6 hours by default. |
| **Browse** | Packages on the source, by category, with Install. Badges show who signed each Package, and **Check Package** checks its files without installing it. |
| **Upload** | Drop `.thp` Package files, then Install. |
| **Sources** | Add, edit, copy, remove, and test Package sources. Tick **TrakHound PackageManager** on a source that is a [TrakHound PackageManager](https://www.trakhound.com/docs/trakhound-framework/packages#package-manager) feed. |

Dependencies listed in the manifest are installed automatically. Installing a Package doesn't run it: add a [configuration](https://www.trakhound.com/docs/trakhound-framework/configuration) that uses it.

Instances install from the public TrakHound source by default. To share internal Packages across your organization, host your own source on an Instance. See [Self-Hosting Packages](https://www.trakhound.com/docs/trakhound-framework/self-hosting-packages).

## Signing and Verification

Every Package contains a `package.manifest.json` listing each file with its SHA-256, plus the Package's identity and source, including the git commit it was built from. `th packages dotnet` also adds `sbom.cdx.json`, a CycloneDX list of the NuGet packages it was built with. A signature shows who published a Package, and stops someone from changing its files and rewriting the manifest to match.

Diagram: A publisher builds a Package, which records a manifest of its files, the commit it was built from, and its NuGet packages, and signs it with a private key. An Instance trusts the publisher's public key, and checks each Package's files and signature when it's installed and loaded. In Warn mode, problems are logged and the Package is used. In Require mode, only Packages with matching files and a trusted signature are used.

### Sign a Package

Create a key once, and keep the private key out of your repository. Pass it when you build, or set the `TRAKHOUND_SIGNING_KEY` environment variable for CI:

```
th packages keygen contoso --output ~/.trakhound/keys
th packages dotnet --sign-key ~/.trakhound/keys/contoso.private.pem
```

`--sign-key` also works with `pack`, `publish`, and `build`. A signed build stops if the working tree has uncommitted changes, because the Package wouldn't match the recorded commit, unless you pass `--allow-dirty`, which is recorded. Set `repository` in the Package's metadata so the commit can be traced to its repository.

### Trust a Publisher

Add each publisher's public key under **Security > Trusted Publishers**, or with the CLI. Trust is kept per configuration profile. `--prefix` limits a publisher to Package IDs that start with that text, so it can't sign a Package that claims another publisher's ID. Confirm with the publisher that the key is theirs.

```
th trust add ./contoso.public.pem --name Contoso --prefix Contoso.
```

### Check Packages on an Instance

The Instance checks each Package when it's installed and whenever it loads Packages. `packageVerification` in `instance.config.yaml` decides what happens next:

| Mode | What it does |
| --- | --- |
| `Off` | Packages aren't checked. |
| `Warn` (default) | Every Package is used. One that doesn't match its manifest logs a warning, and an unsigned one logs an information message. |
| `Require` | Only Packages whose files match and that are signed by a trusted publisher are used. Anything else is refused and logs an error. |
| `RequireApproval` | Everything `Require` checks, and the build must be on the signed approval list of a [TrakHound PackageManager](https://www.trakhound.com/docs/trakhound-framework/packages#package-manager) source, so a Package copied onto the Instance by hand is refused. Only offered when a source is a Package Manager. |

To turn on `Require`:

1. Add each publisher under **Security > Trusted Publishers**.
2. Click **Verify All** on **Packages > Installed**. Each Package shows `Verified`, `Unsigned`, `No Manifest`, `Untrusted`, `Modified`, or (under `RequireApproval`) `Not Approved`, and anything other than `Verified` would be refused.
3. Set **Settings > Package Verification** (or run `th instance set packageVerification Require`), then restart the Instance.

- Under `Require`, an install fails with the reason and nothing is written, and a Package whose dependency fails isn't installed either.
- A Package that arrives another way, such as a Deployment or a copied folder, is refused when the Instance loads it. A refused Package can be removed on **Packages > Installed**.
- Packages without a signature are refused, including ones built before signing was added, so rebuild them with a signing key first.
- Unless the mode is `Off`, the Instance reads every file of each Package that has a manifest when it starts, which can add to startup time. Boot records show it as the Load Packages step.
- A changed or refused Package raises a Notification. IT tools can collect the results from `GET /_instances/packages/verification` and `/_instances/packages/verification/{packageId}/{version}` (the `Instance` System Resource), including each build's `uuid`, `contentHash` (which tells two builds of one version apart), `installed` time, and whether it's `inUse`.

### TrakHound PackageManager Sources

If your organization runs a [TrakHound PackageManager](https://www.trakhound.com/trakhound-package-manager), register the Instance there to get a feed URL and access token. Then add a source on **Packages > Sources** with that Base URL and Access Token, and tick **TrakHound PackageManager**. For these sources only, the Instance:

- **Only sees the Packages approved for it** when it browses and installs.
- **Reports its installed Packages** (every version, used or not, with its UUID, content hash, verification state, publisher, and commit), so IT can report on what each Instance runs and find Instances that differ. It reports at startup, about 30 seconds after Packages change, and on a heartbeat (**Settings > Notifications > Package Inventory**, every 6 hours by default). A failed report is logged once, and never delays startup or an install.
- **Trusts the publishers the Package Manager verified**, so their Packages show as `Verified` rather than `Untrusted`. They're read at startup and every hour, kept in `security/package-manager-publishers.json` for when the Package Manager can't be reached, and listed read-only on **Security > Trusted Publishers**. A publisher you add yourself with the same key is used instead.
- **Reads the signed list of approved builds** for `RequireApproval`.

```
# remotes.config.yaml in the configuration profile folder, for scripted installs
remotes:
- id: package-manager
  name: Contoso Package Manager
  baseUrl: https://pm.contoso.com/trakhound/package-manager/api/feed
  organization: Contoso
  accessTokenCode: <token>
  packageManager: true
```

### RequireApproval

Under `Require`, a Package signed by a trusted publisher is used however it reached the Instance. `RequireApproval` also requires its content hash, ID, and version to be on the Package Manager's signed approval list, and anything else shows `Not Approved` and is refused.

- **Server key** - The first key the Instance reads is pinned in `security/package-manager-key.json`. Confirm on **Security > Trusted Publishers** that its Key ID matches the one the Package Manager shows. A different key is refused, logged, and raises a Notification. If the key was replaced on purpose, confirm the new Key ID with the Package Manager's administrator and click **Clear Pinned Key**.
- **Approval list** - Read at startup, every hour, and before an install (at most once a minute), and kept in `security/package-manager-attestations.json`. A list is only used if it's signed by the pinned key and hasn't expired (7 days by default). An older list than the one kept is ignored, so a revoked build can't come back. A new list checks the Packages again, so a revoked build stops and one approved since starts.
- **Cut off from the Package Manager** - The last valid list is used. Once it expires, Packages on it keep working so the site doesn't stop, but nothing new is installed, and a warning is logged every hour until a new list arrives.
- **No valid list** (never read, or the key was cleared) - Every Package is refused, and Trusted Publishers says why.
- `th packages install` uses the list the Instance kept.

### Before Installing

**Packages > Browse** shows who signed each Package without downloading it, if the source provides manifests:

| Badge | Meaning |
| --- | --- |
| `Signed by <publisher>` | A trusted publisher signed the manifest. Its files haven't been checked. |
| `Untrusted signature` | It's signed by a key that isn't in your Trusted Publishers. |
| `Unsigned` | It has a manifest, but nobody signed it. |
| `No Manifest` | It has no manifest. |
| `Invalid` | The manifest or signature is bad, or the manifest doesn't match what the source lists. Hover over the badge to see why. |

A badge doesn't look at the files. To check them, select the Package and click **Check Package**, which downloads that version and shows its status, signer, commit, and SBOM without installing it. Only trust the publisher named in the badge: the rest of what Browse lists comes from the source and isn't proven.

### Check from the CLI

```
# Check a Package file, or the installed Packages when --file isn't set
th packages verify --file ./MyPackage-1.0.0.thp --require-signature

# Build the recorded commit again and compare the files
th packages rebuild ./MyPackage-1.0.0.thp
```

`th packages dotnet` builds so that the same commit gives the same files, whatever folder it's built in. `rebuild` needs the same .NET SDK and operating system as the original, exact NuGet versions, and, for Apps, a build with `--include-debug-symbols false`. Only Windows builds with the same SDK have been compared so far. Building runs the repository's code, so the Package must be signed by a trusted publisher unless you pass `--allow-untrusted`, and the Instance never does this itself.

> A signature shows who published a Package and that it hasn't changed. It doesn't show that the code is safe. Files are checked when Packages install or load, so a file changed while the Instance is running isn't noticed until the next restart or **Verify All**: run `th packages verify` on a schedule to find these sooner. Whoever can write to the configuration folder can change what the Instance trusts, so protect it with file permissions.

## Licensed Packages

Commercial Packages set `.licenseRequired` in their metadata. The Instance shows these Packages as **License Required**, and the Package checks for a license matching its publisher and product IDs. License Codes are signed by the publisher and checked on the Instance's own machine, so nothing contacts the publisher and a server without internet access can be licensed.

### Getting a License

1. Copy the **Device ID** from the **Licenses** page of the Instance's admin UI. The device doesn't need internet access.
2. Request a trial or purchase a license at [licenses.trakhound.com](https://licenses.trakhound.com/), choosing the product and pasting the Device ID.
3. Import the License File you receive on the **Licenses** page. A License File can hold licenses for several devices, and each device adds only its own.

See the [Licensing Guide](https://www.trakhound.com/docs/licensing) for plans, payment options, ordering for several devices, and managing your account.

### Licensing Your Own Package

A Package you publish can require a License too. Licenses are checked offline, so nothing contacts you:

1. **Create a key pair** with `th licenses keygen contoso`. Keep `contoso.license.private.pem` secret and outside your repository: anyone with it can issue Licenses for your products.
2. **Embed the public key** in your Package's code as a constant. Never read it from configuration, or a customer could replace it with their own.
3. **Describe the License** in the Package metadata: `.licenseRequired` (`true`), `.licensePublisherId`, `.licenseProductId`, and `.licenseRequestUrl`, which the Instance links to with the product and Device ID added.
4. **Issue Licenses** for a customer's Device ID with `th licenses sign`, or from your own order system with `TrakHoundLicenseSigner`.
5. **Check the License** in the code paths that need it with `TrakHoundLicenseVerifier.VerifyAssignment`.

```
th licenses sign --key ./contoso.license.private.pem --product contoso.widget --device <device-id> --limit 5 --expires 2027-12-31
```

```
var licenseManager = TrakHoundLicenseManagers.Get("contoso");
var assignment = licenseManager.AddAssignment(ProductId, licenseManager.GetDeviceId(), connectionId, "Line 3 connection");

var result = TrakHoundLicenseVerifier.VerifyAssignment(PublicKey, ProductId, licenseManager, assignment.AssignmentId);
if (!result.IsValid) Log(TrakHoundLogLevel.Warning, $"Not licensed : {result.Message}");
```

- A License Code holds the product, the Device ID, the seat limit, and the expiration, signed with ECDSA P-256, so changing any of them makes it invalid. `--any-device` issues a License that works on any device.
- The License Manager stores the Licenses a customer adds and counts seats, but doesn't check signatures, so always check with `TrakHoundLicenseVerifier`.
- Compile the verifier's source files into your own assembly (with `TRAKHOUND_LICENSE_SOURCES` defined), so a changed `TrakHound.Common.dll` on the Instance can't skip the check.
- To replace a key, list both public keys until the old Licenses expire. `th licenses inspect <code>` shows what a code contains and checks it.
