@nylorun/admin 0.10.0-beta → 0.12.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,80 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - cf5eb9c: **Protocol 9: the Runtime API is an OAuth 2.1 resource server for your identity provider's tokens.** Nylorun is still never the authorization server. Upgrade every package together; MIGRATION.md has the details.
8
+
9
+ - **Breaking (`@nylorun/runtime`): a refused credential is `401`, not the opaque `404`.** No `Authorization` is `401 credential_required`; an unknown key, or a token no trusted issuer signed or that fails a check, is `401 credential_invalid`. Each carries `WWW-Authenticate: Bearer` (OAuth 2.1 §5.3), naming the protected resource metadata (`resource_metadata`) on the Runtime API when the Runtime has trusted issuers; the Management API's challenge is a bare `Bearer`. `token_expired` and `issuer_unavailable` gain the challenge too. Another Tenant named, a Tenant that could not open and an unsigned capability link stay the opaque `404`.
10
+ - **Breaking (`@nylorun/runtime`): a request with neither `Nylorun-Protocol` nor `Authorization`** on an API route gets that route's `401` challenge instead of `426`, so a generic OAuth client learns where to sign in.
11
+ - `@nylorun/runtime`: a token without a route's scope still gets `403 scope_required`, now with `WWW-Authenticate: Bearer error="insufficient_scope", scope="…"`. The `Bearer` scheme is matched in any case (RFC 9110).
12
+ - `@nylorun/runtime`: `GET /.well-known/oauth-protected-resource` (RFC 9728) serves the resource (`NYLORUN_PUBLIC_URL`, else the request's origin), the identity file's issuers in order and their scopes, with no key or protocol; `404` without an identity file.
13
+ - **Breaking (`@nylorun/runtime`): the identity file drops `maxLifetime`.** The issuer sets its tokens' lifetimes; `exp` is required, `iat` no longer is. A key the file does not define, `maxLifetime` included, is ignored and logged (`identity_file_key_ignored`) instead of stopping the boot. `subject` defaults to `{sub}`, `scopes` to `{ claim: scope }` and `allowedScopes` to every token scope but `studio`.
14
+ - `@nylorun/core`: `PROTOCOL_VERSION` is 9 and `HOST_PROTOCOL` 4–9, with the required feature `resource-server`; `ERROR_CODES` adds `credential_required` and `credential_invalid`. `@nylorun/agents`, `@nylorun/admin` and `@nylorun/cli` send protocol 9.
15
+
16
+ ### Patch Changes
17
+
18
+ - Pin core to the tested release.
19
+ - Updated dependencies [cf5eb9c]
20
+ - Updated dependencies [2ed5fe0]
21
+ - @nylorun/core@0.16.0-beta
22
+
23
+ ## 0.11.1-beta
24
+
25
+ ### Patch Changes
26
+
27
+ - Pin core to the tested release.
28
+ - Updated dependencies [4bd2a0b]
29
+ - Updated dependencies [a64aaca]
30
+ - Updated dependencies [40b7648]
31
+ - Updated dependencies [713e676]
32
+ - Updated dependencies [c135267]
33
+ - Updated dependencies [d36f0d9]
34
+ - Updated dependencies [107b07d]
35
+ - @nylorun/core@0.15.0-beta
36
+
37
+ ## 0.11.0-beta
38
+
39
+ ### Major Changes
40
+
41
+ - 3b3bdc6: **The clients use management keys (Runtime and Management APIs, step A3).** The protocol stays at 7; every client keeps working against a protocol 7 Runtime's routes.
42
+
43
+ - `nylorun`: `nylorun start` keeps an application key (`project`) and a management key (`project-management`) for a Project, in `<Host root>/project-credentials.json` and the Project's `.nylorun/credentials.json` (still format 1, with new `managementKey` and `managementPrincipalId` fields). A credentials file holding only an application key gains a management key at the next start. Commands outside a project keep `cli` and `cli-management`. Keys are issued through `nylorun-operate` in the runtime container instead of the Admin API, and `nylorun key put <id> --management` puts a management key. Seeding the Tenant and `nylorun mcp connect` use the management key (`/v1/tenant/vaults`). Studio reaches the Runtime's public listener.
44
+ - `@nylorun/cli`: `status`, `reset`, `configure`, `doctor` and `access signing-keys` use the Management API through `@nylorun/admin` with the Project's management key, or `NYLORUN_MANAGEMENT_KEY`.
45
+ - `@nylorun/studio`: local Studio needs no login. A request on the published loopback address (`localhost` or `127.0.0.1` at Studio's port) acts as signed in; hosts behind a sign-in proxy and embedding keep their login, and state-changing requests still need Studio's own `Origin`. Studio learns its Tenant from `GET /v1/tenant` with its key instead of the Admin API, and its Connections page manages vaults through `@nylorun/admin/client` at `/v1/tenant/vaults`.
46
+ - **Breaking (`@nylorun/admin`, `@nylorun/runtime`): Studio's key is derived from the admin key alone.** `deriveStudioToken(adminKey)` takes no Tenant id (HMAC-SHA256 over `nylorun/studio/v2`). The Host registers the new key's hash at its next start, replacing the old one; an app that embeds Studio and derives its key must update.
47
+ - `@nylorun/core`: `ProjectCredentialsFileSchema` gains optional `managementKey` and `managementPrincipalId`.
48
+
49
+ - 7f763c3: **The Admin API and the operator listener are gone (Runtime and Management APIs, step A5).** Host work moves to the machine: `nylorun` runs `nylorun-operate` inside the runtime container, and every remote client uses the Runtime API or the Management API.
50
+
51
+ - **Breaking (`@nylorun/runtime`):** `/v1/admin/*` (status, host, shutdown, keys, openapi.json) is removed; it answers like any unknown route. The operator listener, `NYLORUN_ADMIN_LISTEN_PORT`, `NYLORUN_ADMIN_LISTEN_HOST`, `NYLORUN_ADMIN_ALLOWED_HOSTS` and `host.json`'s `adminPort` are gone, and so is the `admin-openapi.json` package file. Stop the Host with SIGTERM. `nylorun-operate status [--json]` reports the version, protocol and the Tenant's id, name, state and cause, exiting 2 when the Tenant is not open. `/ready` adds `harness: { mode, connected }` while the Tenant is open. `startEphemeralRuntime` loses `operatorListener` and `adminUrl`. The admin key stays: it derives Studio's key.
52
+ - **Breaking (`@nylorun/admin`):** `createAdmin()` is the Management API client (`tenant`, `keys`, `models`, `vaults`, `signingKeys`, `settings`) with a management key: explicit `{ url, key }`, else `NYLORUN_RUNTIME_URL` + `NYLORUN_MANAGEMENT_KEY`, else the Project link's or the local Host root's management key. `status()`, `adminUrl`, the Admin API keys, `NYLORUN_ADMIN_URL`/`NYLORUN_ADMIN_KEY` and `OPERATOR_KEYS_FEATURE` are removed; `deriveStudioToken` and `mintStudioLoginToken` stay.
53
+ - **Breaking (`@nylorun/core`):** `admin-status` leaves `PROTOCOL_FEATURES` (the Host still advertises it for protocol 5–7 clients) and `operator-keys` is removed; `AdminStatusSchema`, `AdminHostStatusSchema`, `HostAggregateSchema` and `HostShutdownResponseSchema` are removed.
54
+ - **Breaking (`nylorun`):** no admin port: `NYLORUN_ADMIN_PORT` is no longer written or published (an existing one is ignored). `nylorun start` waits for `/ready`, and `nylorun status` reads readiness from `/ready` and the Tenant from `nylorun-operate status`.
55
+ - `@nylorun/cli`: `nylo status` no longer falls back to the Admin API; when the Tenant does not answer it points to `npx nylorun status`.
56
+
57
+ ### Minor Changes
58
+
59
+ - a6108f4: **The Management API's routes and client (Runtime and Management APIs, step A2).** Additive; the protocol stays at 7.
60
+
61
+ - `@nylorun/runtime`: `GET /v1/tenant/keys`, `PUT /v1/tenant/keys/{keyId}` and `DELETE /v1/tenant/keys/{keyId}` manage the Tenant's application keys with a management key. A management key's name, `studio` and `bootstrap` are refused, so no API call creates, rotates or deletes a management key. Vaults (`/v1/tenant/vaults…`, including `…/oauth/start`) and signing keys (`/v1/tenant/signing-keys…`) are also served under `/v1/tenant`, for management keys only; the old `/v1/vaults…` and `/v1/access/signing-keys…` paths keep serving application keys until protocol 8. `GET /v1/oauth/callback` and `GET /v1/access/jwks` keep their paths.
62
+ - `@nylorun/admin`: `createManagementClient({ url, key })` is the Management API's client: `tenant` (status, seed, reset), `keys` (application keys), `models` (catalog, providers, get, put, select, usage, budgets), `vaults` (with credentials and `startOAuth`), `signingKeys` and `settings` (sandbox, artifacts). `@nylorun/admin/client` exports it with no Node module, for browser apps behind a proxy that adds the key.
63
+
64
+ - c66d8ed: Add optional session reads and a resumable model-ledger export: pinned manifests, usage totals, model calls, and opt-in session/history/sandbox pages (Host feature `session-reads`), and `GET /v1/tenant/calls/model` on the Management API (Host feature `calls-export`). Usage and model calls take an application key acting as itself; the export takes a management key. Runtime reads use a separate bounded, read-only Drizzle pool. The additive migration `0012_session_reads` preserves unknown legacy creation times and usage quality; the export uses safe transaction order without skipping committed rows. `@nylorun/agents` adds `client.sessions.page()`, `session.manifest()`, `session.usage()`, `session.modelCalls()`, `session.history({ limit })` and `client.sandboxes.page()`; `@nylorun/admin` adds `models.exportCalls()`. Legacy unpaged responses are unchanged.
65
+
66
+ ### Patch Changes
67
+
68
+ - Pin core to the tested release.
69
+ - Updated dependencies [3b3bdc6]
70
+ - Updated dependencies [6576e12]
71
+ - Updated dependencies [b28bdd7]
72
+ - Updated dependencies [cc107b1]
73
+ - Updated dependencies [7f763c3]
74
+ - Updated dependencies [98b0d37]
75
+ - Updated dependencies [c66d8ed]
76
+ - @nylorun/core@0.14.0-beta
77
+
3
78
  ## 0.10.0-beta
4
79
 
5
80
  ### Major Changes
package/README.md CHANGED
@@ -1,64 +1,134 @@
1
1
  # @nylorun/admin
2
2
 
3
- Admin API client for a Runtime installation: its status, with the one Tenant it
4
- serves, its operator keys, and the Studio key the admin key derives. Depends only on
5
- `@nylorun/core`.
3
+ The Management API client (protocol 8): the Tenant's status, seed and reset, its
4
+ models, vaults, signing keys, settings and application keys, through
5
+ `/v1/tenant/*` with a **management key**. It also holds the two helpers over the
6
+ admin key that Studio needs. Depends only on `@nylorun/core`.
6
7
  Requires Node 24+. Vocabulary: [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
7
8
 
9
+ Developer applications do **not** depend on this package: they use the Runtime
10
+ API through `@nylorun/agents`. Operators' clients do: the CLI, Studio, CI and
11
+ your own tools.
12
+
8
13
  ```ts
9
14
  import { createAdmin } from "@nylorun/admin";
10
15
 
11
- // Resolution: explicit options → NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY → local Host
12
16
  const admin = createAdmin();
13
17
  // or: createAdmin({ url, key }) / createAdmin({ tenant: "my-app" }) / createAdmin({ home })
14
18
 
15
- const { tenant } = await admin.status();
16
- // tenant: { id, name, state: "open" | "unavailable", envelope, cause? }
19
+ const status = await admin.tenant.status(); // GET /v1/tenant
20
+ const model = await admin.models.get(); // the Tenant's model, never its secret
21
+ const { key } = await admin.keys.put("backend"); // a new application key, shown once
17
22
  ```
18
23
 
19
- An installation serves one Tenant, which its Host creates on first start. There
20
- are no Tenant routes: `createTenant`, `listTenants`, `getTenant` and
21
- `deleteTenant` are gone, and a Host answers `/v1/admin/tenants*` with `404`.
22
- When the Tenant cannot be opened, `status.tenant.state` is `unavailable` and
23
- `cause` names why (`schema-too-new`, `kek-missing`, `database-layout-old`, …).
24
+ ## Connecting
25
+
26
+ `createAdmin(options?)` resolves the URL and the management key once, in this
27
+ order, and `admin.source` says which one it used (`options`, `environment` or
28
+ `local-host`):
29
+
30
+ 1. `options`: `url` and `key` (a management key), both or neither.
31
+ 2. The environment: `NYLORUN_RUNTIME_URL` and `NYLORUN_MANAGEMENT_KEY`. Only the
32
+ key selects this: `NYLORUN_RUNTIME_URL` alone is an app's, with
33
+ `NYLORUN_SERVER_KEY`.
34
+ 3. The local Host. The URL comes from `host.json` in the Host root:
35
+ `options.home`, else `NYLORUN_HOME`, else `~/.nylorun/tenants/<tenant>/` for
36
+ the local Tenant named by `options.tenant`, `NYLORUN_TENANT` or the Project
37
+ link (`.nylorun/link.json`, format 3, found from `options.cwd` upwards). The
38
+ key is the `managementKey` of the linked Project's `.nylorun/credentials.json`,
39
+ else of the Host root's `project-credentials.json`, else of its
40
+ `cli-credentials.json`. `nylorun start` writes them (the keys
41
+ `project-management` and `cli-management`). On POSIX a credentials file must
42
+ be the user's and not group- or world-readable.
43
+
44
+ When none resolves, or the Project link is from an older nylorun, it throws
45
+ `connection_missing` and lists what it tried. The first request checks the
46
+ Host's `/health` and throws `incompatible_host` unless the Host serves protocol
47
+ 8 with the feature `management-api`.
48
+
49
+ Management keys are issued on the Tenant's machine only:
50
+ `npx nylorun key put <id> --management` on a local Tenant, or
51
+ `nylorun-operate keys put <id> --role management` inside the runtime container
52
+ ([SELF_HOSTING.md](../SELF_HOSTING.md#keys)). No API call creates one.
53
+
54
+ ## The groups
24
55
 
25
- Operator keys (Host feature `operator-keys`) are the Tenant's revocable
26
- application keys, managed by name. `put` creates a key or rotates it and returns
27
- it once; a rotated or deleted key stops authenticating on its next request.
28
- Ids match `^[a-z][a-z0-9-]{0,31}$`; `studio` is refused:
56
+ | Group | Methods | Routes |
57
+ | --- | --- | --- |
58
+ | `admin.tenant` | `status()`, `seed(request)`, `reset(request)` | `GET /v1/tenant`, `PUT /v1/tenant/config/seed`, `POST /v1/tenant/reset` |
59
+ | `admin.keys` | `list()`, `put(id)`, `delete(id)` | `/v1/tenant/keys…` |
60
+ | `admin.models` | `catalog()`, `providers()`, `get()`, `put(request)`, `select(request)`, `usage(query)`, `budgets.get()`, `budgets.put(request)` | `/v1/tenant/models`, `/providers`, `/model`, `/model/selection`, `/usage`, `/budgets` |
61
+ | `admin.vaults` | `create`, `list(ownerUserId?)`, `get`, `delete`, `credentials.create`, `.list`, `.get`, `.rotate`, `.delete`, `startOAuth(vaultId, { url, server, clientId? })` | `/v1/tenant/vaults…` |
62
+ | `admin.signingKeys` | `list()`, `rotate({ force? })`, `revoke(kid)` | `/v1/tenant/signing-keys…` |
63
+ | `admin.settings` | `sandbox.get()`, `sandbox.put(request)`, `artifacts.get()`, `artifacts.put(request)` | `/v1/tenant/sandbox`, `/v1/tenant/artifacts` |
64
+
65
+ A request body's `requestId` is optional: the client makes one.
66
+
67
+ `admin.keys` manages the Tenant's **application keys**, the keys app servers
68
+ use on the Runtime API. `put` creates a key or rotates it and returns it once;
69
+ a rotated or deleted key stops authenticating on its next request. `list`
70
+ shows every key's id, role and when it was issued, never the keys. Ids match
71
+ `^[a-z][a-z0-9-]{0,31}$`. `studio`, `bootstrap` and the id of a management key
72
+ are refused, so a management key can never mint another.
29
73
 
30
74
  ```ts
31
75
  const { key } = await admin.keys.put("backend"); // { id, role, createdAt, key, rotated }
32
- await admin.keys.list(); // [{ id, role, createdAt }], never the keys
76
+ await admin.keys.list(); // [{ id, role, createdAt }]
33
77
  await admin.keys.delete("backend"); // true when it existed
34
78
  ```
35
79
 
36
- `nylorun start` links a Project with the operator key `project`, and
37
- `nylorun key put|list|rm` does the same from a terminal.
38
-
39
- The one key the admin key derives is Studio's (`deriveStudioToken(adminKey,
40
- tenantId)`): the Host registers `studio` by hash when it creates its Tenant, so
41
- Studio, and an app embedding it, stores no key, and rotating the admin key
42
- rotates it. Every other client holds an operator key. Since protocol 7 no other
43
- key is derived; a key an earlier Host derived stays valid as an ordinary key
44
- until you replace it with `admin.keys.put(<its id>)`.
45
-
46
- Local Host resolution reads `host.json` and `host-credentials.json` from the
47
- Host root: `options.home`, else `NYLORUN_HOME`, else the Tenant's Host root
48
- `~/.nylorun/tenants/<tenant>/` for the local Tenant named by `options.tenant`,
49
- `NYLORUN_TENANT` or the Project link (`tenant` in `.nylorun/link.json`, format
50
- 3, found from `options.cwd` upwards; a link from an older nylorun throws
51
- `connection_missing`). On POSIX the credentials file must be owned by the
52
- user and not group- or world-readable. First use checks `/health`
53
- compatibility and throws `incompatible_host` on mismatch.
54
-
55
- `mintStudioLoginToken({ studioUrl, adminKey })` mints a single-use Studio login
56
- token for an app that embeds Studio; its optional `tenant` must name the Host's
57
- Tenant.
80
+ Installation vaults hold the installation's shared credentials. A session
81
+ attaches them by id (`vaultIds`) through the Runtime API:
82
+
83
+ ```ts
84
+ const vault = await admin.vaults.create({ scope: "installation", name: "tools", idempotencyKey: "tools" });
85
+ await admin.vaults.credentials.create(vault.id, {
86
+ name: "linear",
87
+ idempotencyKey: "linear",
88
+ auth: { type: "bearer", url: "https://mcp.linear.app/mcp", token: process.env.LINEAR_TOKEN! },
89
+ });
90
+ ```
91
+
92
+ ## In a browser
93
+
94
+ `@nylorun/admin/client` exports `createManagementClient({ url, key?, fetch?,
95
+ headers? })` and `ManagementClient`, with the same groups and no Node module.
96
+ It is for a browser app behind its own server that adds the management key, as
97
+ Studio's Connections page is: omit `key`, and point `url` at that server. Never
98
+ send a management key from a browser: the Runtime refuses any key sent with an
99
+ `Origin` (`403 origin_rejected`).
100
+
101
+ ```ts
102
+ import { createManagementClient } from "@nylorun/admin/client";
103
+
104
+ const admin = createManagementClient({ url: "/my-proxy" });
105
+ ```
106
+
107
+ The main entry exports `createManagementClient` too, for a server that already
108
+ has its URL and key.
109
+
110
+ ## Studio's key and login tokens
111
+
112
+ The admin key in `host-credentials.json` is the installation's root secret, and
113
+ no request accepts it. Two helpers use it locally:
114
+
115
+ - `deriveStudioToken(adminKey)` returns Studio's key: HMAC-SHA256 with the admin
116
+ key over `nylorun/studio/v2`. It names no Tenant. The Host registers its hash
117
+ as principal `studio` (role `studio`, which reaches both APIs) at every start,
118
+ so Studio stores no key and rotating the admin key rotates it. It is the only
119
+ key derived from the admin key.
120
+ - `mintStudioLoginToken({ studioUrl, adminKey, tenant?, subject? })` asks Studio
121
+ (`POST /_studio/login-tokens`) for a single-use login token, for an app that
122
+ embeds Studio. Its optional `tenant` must name the Host's Tenant; `subject`
123
+ names the person in Studio's log.
124
+
125
+ ## Errors and exports
58
126
 
59
127
  Errors are `AdminError` with a registry `code` from `@nylorun/core`
60
- (`ERROR_CODES`). Re-exports: `PROTOCOL_FEATURES`, `ERROR_CODES`,
61
- `compareVersions`, `deriveStudioToken`, `tenantHostRoot`, `OPERATOR_KEYS_FEATURE`.
128
+ (`ERROR_CODES`) and the HTTP `status`. An application key here is
129
+ `403 key_role_mismatch`; a management key sent with `Nylorun-Subject` or
130
+ `Nylorun-Scopes` is `403 subject_invalid`.
62
131
 
63
- Developer applications do **not** depend on this package — only managing
64
- clients (CLI, desktop Runtime panel, CI) do.
132
+ Exports: `createAdmin`, `createManagementClient`, `ManagementClient`,
133
+ `AdminError`, `deriveStudioToken`, `mintStudioLoginToken`, `tenantHostRoot`,
134
+ `PROTOCOL_FEATURES`, `ERROR_CODES` and `compareVersions`.
package/dist/client.d.ts CHANGED
@@ -1,13 +1,9 @@
1
- import { type AdminStatus, type OperatorKey, type PutOperatorKeyResponse } from "@nylorun/core/contracts";
1
+ import { ManagementClient } from "./management.js";
2
2
  export type AdminSource = "options" | "environment" | "local-host";
3
3
  export interface ResolvedAdmin {
4
- /** The Host's Tenant API URL (what a Project link names). */
4
+ /** The Tenant's URL. */
5
5
  url: string;
6
- /**
7
- * Where the Admin API answers when the Host serves it on its own operator listener
8
- * (`adminPort` in host.json). Defaults to `url`.
9
- */
10
- adminUrl?: string;
6
+ /** A management key. */
11
7
  key: string;
12
8
  source: AdminSource;
13
9
  /** The Host root read for local Host settings, when one was found. */
@@ -15,6 +11,7 @@ export interface ResolvedAdmin {
15
11
  }
16
12
  export interface AdminConnectionOptions {
17
13
  url?: string;
14
+ /** A management key. */
18
15
  key?: string;
19
16
  /** The Host root itself (overrides `NYLORUN_HOME` and the Tenant). */
20
17
  home?: string;
@@ -25,43 +22,10 @@ export interface AdminConnectionOptions {
25
22
  }
26
23
  /** A local Tenant's Host root: `~/.nylorun/tenants/<name>/`. */
27
24
  export declare function tenantHostRoot(name: string): string;
28
- /**
29
- * Resolve Admin API connection once: options → environment → local Host.
30
- */
25
+ /** Resolve the Management API connection once: options → environment → local Host. */
31
26
  export declare function resolveAdminConnection(options?: AdminConnectionOptions): ResolvedAdmin;
32
- /** The Host feature `/v1/admin/keys` needs. */
33
- export declare const OPERATOR_KEYS_FEATURE = "operator-keys";
34
- /** The Tenant's operator keys (Host feature `operator-keys`), managed by name. */
35
- export interface AdminKeys {
36
- /**
37
- * Creates key `id` (`^[a-z][a-z0-9-]{0,31}$`), or rotates it: the old key stops
38
- * authenticating at once. The key is in the answer this once. `studio` is refused.
39
- */
40
- put(id: string): Promise<PutOperatorKeyResponse>;
41
- /** Every key of the Tenant by id, with its role and when it was issued; never the keys. */
42
- list(): Promise<OperatorKey[]>;
43
- /** Deletes key `id`: true when it existed. `studio` is refused. */
44
- delete(id: string): Promise<boolean>;
45
- }
46
- export declare class AdminClient {
47
- /** The Host's Tenant API URL. */
48
- readonly url: string;
49
- /** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
50
- readonly adminUrl: string;
27
+ /** What `createAdmin` returns: the Management API client, and where its connection came from. */
28
+ export declare class AdminClient extends ManagementClient {
51
29
  readonly source: AdminSource;
52
- /** The Tenant's operator keys. */
53
- readonly keys: AdminKeys;
54
- private readonly key;
55
- private compatible;
56
- /** The features the Host's `/health` advertised. */
57
- private features;
58
30
  constructor(resolved: ResolvedAdmin);
59
- /** Throws `incompatible_host` when the Host does not advertise `feature`. */
60
- private requireFeature;
61
- private clearCompatibilityCache;
62
- private adminHeaders;
63
- private ensureCompatible;
64
- private request;
65
- private json;
66
- status(): Promise<AdminStatus>;
67
31
  }
package/dist/client.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { readFileSync, realpathSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join, parse, resolve } from "node:path";
4
- import { AdminStatusSchema, DeleteOperatorKeyResponseSchema, ListOperatorKeysResponseSchema, ProjectLinkFileSchema, PutOperatorKeyResponseSchema, RejectedResponseSchema, } from "@nylorun/core/contracts";
5
- import { PROTOCOL_FEATURES, PROTOCOL_HEADER, PROTOCOL_VERSION, checkCompatibility, } from "@nylorun/core/compatibility";
4
+ import { ProjectLinkFileSchema, RejectedResponseSchema } from "@nylorun/core/contracts";
5
+ import { PROTOCOL_FEATURES, PROTOCOL_VERSION, checkCompatibility, } from "@nylorun/core/compatibility";
6
6
  import { AdminError } from "./errors.js";
7
+ import { ManagementClient } from "./management.js";
7
8
  function env(name) {
8
9
  const value = process.env[name];
9
10
  return value === undefined || value.trim() === "" ? undefined : value;
@@ -13,11 +14,11 @@ export function tenantHostRoot(name) {
13
14
  return resolve(join(homedir(), ".nylorun", "tenants", name));
14
15
  }
15
16
  /**
16
- * The Tenant a Project link names (`.nylorun/link.json`, format 3), from `cwd` upwards, or the
17
- * path of a link from an older nylorun. The walk stops at the home directory, which holds the
18
- * Tenants and is never a Project.
17
+ * The Project link (`.nylorun/link.json`, format 3) from `cwd` upwards: the Tenant it names
18
+ * and the Project's `.nylorun/` directory, or the path of a link from an older nylorun. The
19
+ * walk stops at the home directory, which holds the Tenants and is never a Project.
19
20
  */
20
- function linkedTenant(cwd) {
21
+ function projectLink(cwd) {
21
22
  const real = (path) => {
22
23
  try {
23
24
  return realpathSync(path);
@@ -41,7 +42,9 @@ function linkedTenant(cwd) {
41
42
  if (raw !== undefined) {
42
43
  try {
43
44
  const link = ProjectLinkFileSchema.parse(JSON.parse(raw));
44
- return link.format < 3 ? { olderLink: path } : { tenant: link.tenant };
45
+ if (link.format < 3)
46
+ return { olderLink: path };
47
+ return { ...(link.tenant ? { tenant: link.tenant } : {}), directory: dirname(path) };
45
48
  }
46
49
  catch {
47
50
  return {};
@@ -55,34 +58,41 @@ function linkedTenant(cwd) {
55
58
  }
56
59
  /**
57
60
  * The Host root of the local Host: `options.home`, `NYLORUN_HOME`, or the Host root of the
58
- * Tenant named by `options.tenant`, `NYLORUN_TENANT` or the Project link. No `home` when none
59
- * names one; `olderLink` when the Project link is from an older nylorun.
61
+ * Tenant named by `options.tenant`, `NYLORUN_TENANT` or the Project link. `project` is the
62
+ * linked Project's `.nylorun/` when the link names this Host root's Tenant.
60
63
  */
61
64
  function resolveHome(options) {
62
- if (options?.home !== undefined && options.home.trim() !== "")
63
- return { home: resolve(options.home) };
65
+ const link = projectLink(options?.cwd ?? process.cwd());
66
+ const linked = link.tenant ? tenantHostRoot(link.tenant) : undefined;
64
67
  const fromEnv = env("NYLORUN_HOME");
65
- if (fromEnv)
66
- return { home: resolve(fromEnv) };
67
68
  const named = options?.tenant?.trim() || env("NYLORUN_TENANT")?.trim();
68
- if (named)
69
- return { home: tenantHostRoot(named) };
70
- const linked = linkedTenant(options?.cwd ?? process.cwd());
71
- return linked.tenant
72
- ? { home: tenantHostRoot(linked.tenant) }
73
- : { olderLink: linked.olderLink };
69
+ const home = options?.home !== undefined && options.home.trim() !== ""
70
+ ? resolve(options.home)
71
+ : fromEnv
72
+ ? resolve(fromEnv)
73
+ : named
74
+ ? tenantHostRoot(named)
75
+ : linked;
76
+ return {
77
+ ...(home ? { home } : {}),
78
+ ...(home && home === linked ? { project: link.directory } : {}),
79
+ ...(link.olderLink ? { olderLink: link.olderLink } : {}),
80
+ };
74
81
  }
75
82
  function connectionMissing(message) {
76
83
  throw new AdminError("connection_missing", message);
77
84
  }
78
85
  function sourcesTriedMessage(home) {
79
- return (`Tried options (url + key), environment (NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY), ` +
86
+ return ("Tried options (url + key), environment (NYLORUN_RUNTIME_URL + NYLORUN_MANAGEMENT_KEY), " +
80
87
  (home
81
- ? `and local Host settings (host.json + host-credentials.json under ${home}).`
82
- : "and local Host settings (no Tenant named: pass `tenant`, set NYLORUN_TENANT or " +
88
+ ? `and the local Host (host.json under ${home}, with a managementKey in the linked ` +
89
+ "Project's .nylorun/credentials.json, or the Host root's project-credentials.json or " +
90
+ "cli-credentials.json: `npx nylorun start` writes them)."
91
+ : "and the local Host (no Tenant named: pass `tenant`, set NYLORUN_TENANT or " +
83
92
  "NYLORUN_HOME, or run in a Project that `npx nylorun start` linked)."));
84
93
  }
85
- function assertCredentialsSafe(path) {
94
+ /** A credentials file must be the user's and not group- or world-readable (POSIX). */
95
+ function assertCredentialsSafe(path, home) {
86
96
  if (process.platform === "win32")
87
97
  return;
88
98
  let stats;
@@ -93,283 +103,130 @@ function assertCredentialsSafe(path) {
93
103
  return;
94
104
  }
95
105
  const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
96
- if (uid !== undefined && stats.uid !== uid) {
97
- connectionMissing(`host-credentials.json at ${path} is not owned by the current user. ${sourcesTriedMessage(resolve(join(path, "..")))}`);
98
- }
99
- if ((stats.mode & 0o077) !== 0) {
100
- connectionMissing(`host-credentials.json at ${path} is group- or world-readable; fix permissions (chmod 600). ${sourcesTriedMessage(resolve(join(path, "..")))}`);
101
- }
106
+ if (uid !== undefined && stats.uid !== uid)
107
+ connectionMissing(`${path} is not owned by the current user. ${sourcesTriedMessage(home)}`);
108
+ if ((stats.mode & 0o077) !== 0)
109
+ connectionMissing(`${path} is group- or world-readable; fix permissions (chmod 600). ${sourcesTriedMessage(home)}`);
102
110
  }
103
- function readLocalHost(home) {
104
- const configPath = join(home, "host.json");
105
- const credentialsPath = join(home, "host-credentials.json");
106
- let config;
107
- let credentials;
111
+ function readJson(path) {
108
112
  try {
109
- config = JSON.parse(readFileSync(configPath, "utf8"));
113
+ const value = JSON.parse(readFileSync(path, "utf8"));
114
+ return value && typeof value === "object" && !Array.isArray(value)
115
+ ? value
116
+ : undefined;
110
117
  }
111
118
  catch {
112
119
  return undefined;
113
120
  }
114
- try {
115
- assertCredentialsSafe(credentialsPath);
116
- credentials = JSON.parse(readFileSync(credentialsPath, "utf8"));
117
- }
118
- catch (error) {
119
- if (error instanceof AdminError)
120
- throw error;
121
- return undefined;
122
- }
123
- if (!config || typeof config !== "object" || Array.isArray(config)) {
124
- return undefined;
125
- }
126
- if (!credentials ||
127
- typeof credentials !== "object" ||
128
- Array.isArray(credentials)) {
129
- return undefined;
130
- }
131
- const host = config.host;
132
- const port = config.port;
133
- const adminPort = config.adminPort;
134
- const adminKey = credentials.adminKey;
135
- if (typeof host !== "string" || typeof port !== "number")
136
- return undefined;
137
- if (typeof adminKey !== "string" || !/^[0-9a-f]{64}$/.test(adminKey)) {
138
- return undefined;
139
- }
140
- return {
141
- url: `http://${host}:${port}`,
142
- // An older Host serves the Admin API on its only port.
143
- adminUrl: `http://${host}:${typeof adminPort === "number" ? adminPort : port}`,
144
- key: adminKey,
145
- };
146
121
  }
147
122
  /**
148
- * Resolve Admin API connection once: options → environment → local Host.
123
+ * The local Host's URL (`host.json`) and a management key: from the linked Project's
124
+ * `.nylorun/credentials.json`, else the Host root's `project-credentials.json`, else its
125
+ * `cli-credentials.json`.
149
126
  */
127
+ function readLocalHost(home, project) {
128
+ const config = readJson(join(home, "host.json"));
129
+ if (typeof config?.host !== "string" || typeof config.port !== "number")
130
+ return undefined;
131
+ const files = [
132
+ ...(project ? [join(project, "credentials.json")] : []),
133
+ join(home, "project-credentials.json"),
134
+ join(home, "cli-credentials.json"),
135
+ ];
136
+ for (const path of files) {
137
+ const key = readJson(path)?.managementKey;
138
+ if (typeof key !== "string" || !/^[0-9a-f]{64}$/.test(key))
139
+ continue;
140
+ assertCredentialsSafe(path, home);
141
+ return { url: `http://${config.host}:${config.port}`, key };
142
+ }
143
+ return undefined;
144
+ }
145
+ /** Resolve the Management API connection once: options → environment → local Host. */
150
146
  export function resolveAdminConnection(options) {
151
- const { home, olderLink } = resolveHome(options);
147
+ const { home, project, olderLink } = resolveHome(options);
152
148
  const optionUrl = options?.url?.trim() || undefined;
153
149
  const optionKey = options?.key?.trim() || undefined;
154
150
  if (optionUrl || optionKey) {
155
- if (!optionUrl || !optionKey) {
156
- connectionMissing(`Incomplete Admin API options: both url and key are required. ${sourcesTriedMessage(home)}`);
157
- }
158
- return {
159
- url: optionUrl.replace(/\/$/, ""),
160
- key: optionKey,
161
- source: "options",
162
- ...(home ? { home } : {}),
163
- };
164
- }
165
- const envUrl = env("NYLORUN_ADMIN_URL");
166
- const envKey = env("NYLORUN_ADMIN_KEY");
167
- if (envUrl || envKey) {
168
- if (!envUrl || !envKey) {
169
- connectionMissing(`Incomplete Admin API environment: both NYLORUN_ADMIN_URL and NYLORUN_ADMIN_KEY are required. ${sourcesTriedMessage(home)}`);
170
- }
171
- return {
172
- url: envUrl.replace(/\/$/, ""),
173
- key: envKey,
174
- source: "environment",
175
- ...(home ? { home } : {}),
176
- };
177
- }
178
- if (olderLink) {
151
+ if (!optionUrl || !optionKey)
152
+ connectionMissing(`Incomplete options: both url and key (a management key) are required. ${sourcesTriedMessage(home)}`);
153
+ return { url: optionUrl.replace(/\/$/, ""), key: optionKey, source: "options", ...(home ? { home } : {}) };
154
+ }
155
+ // NYLORUN_RUNTIME_URL alone is an app's (with NYLORUN_SERVER_KEY): only the key selects this.
156
+ const envKey = env("NYLORUN_MANAGEMENT_KEY");
157
+ if (envKey) {
158
+ const envUrl = env("NYLORUN_RUNTIME_URL");
159
+ if (!envUrl)
160
+ connectionMissing(`Incomplete environment: NYLORUN_MANAGEMENT_KEY needs NYLORUN_RUNTIME_URL. ${sourcesTriedMessage(home)}`);
161
+ return { url: envUrl.replace(/\/$/, ""), key: envKey, source: "environment", ...(home ? { home } : {}) };
162
+ }
163
+ if (olderLink && !home)
179
164
  connectionMissing(`The Project link at ${olderLink} is from an older nylorun. Run "npx nylorun start" in this project to link it again.`);
180
- }
181
- const local = home === undefined ? undefined : readLocalHost(home);
182
- if (local) {
183
- return {
184
- url: local.url.replace(/\/$/, ""),
185
- adminUrl: local.adminUrl.replace(/\/$/, ""),
186
- key: local.key,
187
- source: "local-host",
188
- home,
189
- };
190
- }
191
- connectionMissing(`Could not resolve Admin API connection. ${sourcesTriedMessage(home)}`);
165
+ const local = home === undefined ? undefined : readLocalHost(home, project);
166
+ if (local)
167
+ return { url: local.url, key: local.key, source: "local-host", home };
168
+ connectionMissing(`Could not resolve the Management API connection. ${sourcesTriedMessage(home)}`);
192
169
  }
193
170
  function parseProtocolRange(value) {
194
- if (!value || typeof value !== "object" || Array.isArray(value)) {
171
+ if (!value || typeof value !== "object" || Array.isArray(value))
195
172
  return undefined;
196
- }
197
173
  const record = value;
198
174
  if (typeof record.min !== "number" ||
199
175
  typeof record.max !== "number" ||
200
176
  !Array.isArray(record.features) ||
201
- !record.features.every((f) => typeof f === "string")) {
177
+ !record.features.every((f) => typeof f === "string"))
202
178
  return undefined;
203
- }
204
- return {
205
- min: record.min,
206
- max: record.max,
207
- features: record.features,
208
- };
179
+ return { min: record.min, max: record.max, features: record.features };
209
180
  }
210
- function throwFromResponse(status, body) {
211
- const parsed = RejectedResponseSchema.safeParse(body);
212
- if (parsed.success) {
213
- throw new AdminError(parsed.data.code, parsed.data.message, {
214
- status,
215
- details: parsed.data.details,
216
- });
217
- }
218
- if (status === 404) {
219
- throw new AdminError("not_found", `Admin request not found (${status})`, {
220
- status,
221
- details: body,
222
- });
181
+ /** Throws unless the Host's `/health` advertises this client's protocol and features. */
182
+ async function checkHealth(url) {
183
+ const response = await fetch(`${url}/health`, { redirect: "error" });
184
+ const body = await response.json().catch(() => undefined);
185
+ if (!response.ok) {
186
+ const rejected = RejectedResponseSchema.safeParse(body);
187
+ throw rejected.success
188
+ ? new AdminError(rejected.data.code, rejected.data.message, { status: response.status })
189
+ : new AdminError("not_found", `Host /health failed (${response.status})`, {
190
+ status: response.status,
191
+ details: body,
192
+ });
193
+ }
194
+ const protocol = parseProtocolRange(body?.protocol);
195
+ if (!protocol)
196
+ throw new AdminError("incompatible_host", "Host /health did not advertise a protocol range.");
197
+ const result = checkCompatibility({ version: PROTOCOL_VERSION, required: [...PROTOCOL_FEATURES] }, protocol);
198
+ if (!result.ok) {
199
+ const detail = result.reason === "version"
200
+ ? `client protocol ${result.client} is outside Host range ${result.host.min}–${result.host.max}`
201
+ : `Host is missing required features: ${result.missing.join(", ")}`;
202
+ throw new AdminError("incompatible_host", `Incompatible Host: ${detail}`, { details: result });
223
203
  }
224
- throw new AdminError("not_found", `Admin request failed (${status})`, {
225
- status,
226
- details: body,
227
- });
228
204
  }
229
- async function readBody(response) {
230
- const text = await response.text();
231
- if (!text)
232
- return undefined;
233
- try {
234
- return JSON.parse(text);
235
- }
236
- catch {
237
- return text;
238
- }
205
+ /**
206
+ * `fetch` that checks the Host's `/health` before the first request, and again after a `426`,
207
+ * retrying the request once when the Host still serves this client.
208
+ */
209
+ function compatibleFetch(url) {
210
+ let checked;
211
+ const check = () => (checked ??= checkHealth(url).catch((error) => {
212
+ checked = undefined;
213
+ throw error;
214
+ }));
215
+ return async (input, init) => {
216
+ await check();
217
+ const response = await fetch(input, init);
218
+ if (response.status !== 426)
219
+ return response;
220
+ checked = undefined;
221
+ await check();
222
+ return fetch(input, init);
223
+ };
239
224
  }
240
- /** The Host feature `/v1/admin/keys` needs. */
241
- export const OPERATOR_KEYS_FEATURE = "operator-keys";
242
- export class AdminClient {
243
- /** The Host's Tenant API URL. */
244
- url;
245
- /** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
246
- adminUrl;
225
+ /** What `createAdmin` returns: the Management API client, and where its connection came from. */
226
+ export class AdminClient extends ManagementClient {
247
227
  source;
248
- /** The Tenant's operator keys. */
249
- keys;
250
- key;
251
- compatible = false;
252
- /** The features the Host's `/health` advertised. */
253
- features = [];
254
228
  constructor(resolved) {
255
- this.url = resolved.url;
256
- this.adminUrl = resolved.adminUrl ?? resolved.url;
229
+ super({ url: resolved.url, key: resolved.key, fetch: compatibleFetch(resolved.url) });
257
230
  this.source = resolved.source;
258
- this.key = resolved.key;
259
- const path = (id) => `/v1/admin/keys/${encodeURIComponent(id)}`;
260
- this.keys = {
261
- put: async (id) => {
262
- await this.requireFeature(OPERATOR_KEYS_FEATURE);
263
- return PutOperatorKeyResponseSchema.parse(await this.json(path(id), "PUT"));
264
- },
265
- list: async () => {
266
- await this.requireFeature(OPERATOR_KEYS_FEATURE);
267
- return ListOperatorKeysResponseSchema.parse(await this.json("/v1/admin/keys"))
268
- .keys;
269
- },
270
- delete: async (id) => {
271
- await this.requireFeature(OPERATOR_KEYS_FEATURE);
272
- try {
273
- DeleteOperatorKeyResponseSchema.parse(await this.json(path(id), "DELETE"));
274
- return true;
275
- }
276
- catch (error) {
277
- // A missing key; an unknown route is the opaque 404 without this message.
278
- if (error instanceof AdminError && error.status === 404 && error.message === `No key ${id}`)
279
- return false;
280
- throw error;
281
- }
282
- },
283
- };
284
- }
285
- /** Throws `incompatible_host` when the Host does not advertise `feature`. */
286
- async requireFeature(feature) {
287
- await this.ensureCompatible();
288
- if (!this.features.includes(feature))
289
- throw new AdminError("incompatible_host", `The Host does not serve ${feature} (Host feature ${feature}): update it.`);
290
- }
291
- clearCompatibilityCache() {
292
- this.compatible = false;
293
- }
294
- adminHeaders(init = {}) {
295
- const headers = new Headers(init.headers);
296
- headers.set("Authorization", `Bearer ${this.key}`);
297
- headers.set(PROTOCOL_HEADER, String(PROTOCOL_VERSION));
298
- headers.set("Accept", "application/json");
299
- if (init.body)
300
- headers.set("Content-Type", "application/json");
301
- return headers;
302
- }
303
- async ensureCompatible(signal) {
304
- if (this.compatible)
305
- return;
306
- const response = await fetch(`${this.adminUrl}/health`, {
307
- method: "GET",
308
- redirect: "error",
309
- signal,
310
- });
311
- const body = await readBody(response);
312
- if (!response.ok) {
313
- throwFromResponse(response.status, body);
314
- }
315
- const protocol = parseProtocolRange(body && typeof body === "object" && !Array.isArray(body)
316
- ? body.protocol
317
- : undefined);
318
- if (!protocol) {
319
- throw new AdminError("incompatible_host", "Host /health did not advertise a protocol range.");
320
- }
321
- const result = checkCompatibility({ version: PROTOCOL_VERSION, required: [...PROTOCOL_FEATURES] }, protocol);
322
- if (!result.ok) {
323
- const detail = result.reason === "version"
324
- ? `client protocol ${result.client} is outside Host range ${result.host.min}–${result.host.max}`
325
- : `Host is missing required features: ${result.missing.join(", ")}`;
326
- throw new AdminError("incompatible_host", `Incompatible Host: ${detail}`, { details: result });
327
- }
328
- this.features = protocol.features;
329
- this.compatible = true;
330
- }
331
- async request(path, init = {}, options = {}) {
332
- await this.ensureCompatible(init.signal === null ? undefined : init.signal);
333
- const response = await fetch(this.adminUrl + path, {
334
- ...init,
335
- headers: this.adminHeaders(init),
336
- redirect: "error",
337
- });
338
- if (response.status === 426) {
339
- this.clearCompatibilityCache();
340
- if (!options.retried426) {
341
- await this.ensureCompatible(init.signal === null ? undefined : init.signal);
342
- return this.request(path, init, { retried426: true });
343
- }
344
- const body = await readBody(response);
345
- const protocol = parseProtocolRange(body && typeof body === "object" && !Array.isArray(body)
346
- ? body.protocol
347
- : undefined);
348
- if (protocol) {
349
- const result = checkCompatibility({ version: PROTOCOL_VERSION, required: [...PROTOCOL_FEATURES] }, protocol);
350
- if (!result.ok) {
351
- throw new AdminError("incompatible_host", "Incompatible Host after protocol upgrade challenge.", { status: 426, details: result });
352
- }
353
- }
354
- throwFromResponse(426, body);
355
- }
356
- return response;
357
- }
358
- async json(path, method = "GET", body) {
359
- const response = await this.request(path, {
360
- method,
361
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
362
- signal: AbortSignal.timeout(15_000),
363
- });
364
- if (response.status === 204)
365
- return undefined;
366
- const parsed = await readBody(response);
367
- if (!response.ok)
368
- throwFromResponse(response.status, parsed);
369
- return parsed;
370
- }
371
- async status() {
372
- const body = await this.json("/v1/admin/status");
373
- return AdminStatusSchema.parse(body);
374
231
  }
375
232
  }
@@ -1,7 +1,8 @@
1
1
  /**
2
- * Deterministic Studio key for one Tenant, derived from the admin key.
3
- * Same admin key and Tenant always produce the same key. Studio derives it in
4
- * memory; the Tenant stores only its hash, as principal `studio`. It is the only
5
- * derived key: every other application key is an operator key (`admin.keys.put`).
2
+ * Deterministic Studio key, derived from the admin key: HMAC-SHA256 over
3
+ * `nylorun/studio/v2`. The same admin key always produces the same key. It names
4
+ * no Tenant (protocol 8): Studio derives it before it learns the Tenant's id, and
5
+ * an installation has one Tenant. Studio derives it in memory; the Tenant stores
6
+ * only its hash, as principal `studio`. It is the only derived key.
6
7
  */
7
- export declare function deriveStudioToken(adminKey: string, tenantId: string): string;
8
+ export declare function deriveStudioToken(adminKey: string): string;
@@ -1,16 +1,13 @@
1
1
  import { createHmac } from "node:crypto";
2
2
  /**
3
- * Deterministic Studio key for one Tenant, derived from the admin key.
4
- * Same admin key and Tenant always produce the same key. Studio derives it in
5
- * memory; the Tenant stores only its hash, as principal `studio`. It is the only
6
- * derived key: every other application key is an operator key (`admin.keys.put`).
3
+ * Deterministic Studio key, derived from the admin key: HMAC-SHA256 over
4
+ * `nylorun/studio/v2`. The same admin key always produces the same key. It names
5
+ * no Tenant (protocol 8): Studio derives it before it learns the Tenant's id, and
6
+ * an installation has one Tenant. Studio derives it in memory; the Tenant stores
7
+ * only its hash, as principal `studio`. It is the only derived key.
7
8
  */
8
- export function deriveStudioToken(adminKey, tenantId) {
9
- const message = Buffer.concat([
10
- Buffer.from("nylorun/studio/v1", "utf8"),
11
- Buffer.from([0]),
12
- Buffer.from(tenantId, "utf8"),
13
- ]);
9
+ export function deriveStudioToken(adminKey) {
10
+ const message = Buffer.from("nylorun/studio/v2", "utf8");
14
11
  return createHmac("sha256", Buffer.from(adminKey, "utf8"))
15
12
  .update(message)
16
13
  .digest("hex");
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { AdminStatus, HostTenant, OperatorKey, PutOperatorKeyResponse, TenantEnvelope } from "@nylorun/core/contracts";
1
+ import type { HostTenant, OperatorKey, PutOperatorKeyResponse, TenantEnvelope } from "@nylorun/core/contracts";
2
2
  import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, type ErrorCode } from "@nylorun/core/compatibility";
3
- import { OPERATOR_KEYS_FEATURE, tenantHostRoot, type AdminConnectionOptions, type AdminKeys } from "./client.js";
3
+ import { AdminClient, tenantHostRoot, type AdminConnectionOptions, type AdminSource } from "./client.js";
4
4
  import { deriveStudioToken } from "./derived-credentials.js";
5
5
  import { AdminError } from "./errors.js";
6
6
  export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
@@ -8,25 +8,20 @@ export type { ErrorCode };
8
8
  export { AdminError };
9
9
  export { deriveStudioToken, tenantHostRoot };
10
10
  export { mintStudioLoginToken } from "./studio-login.js";
11
- export { OPERATOR_KEYS_FEATURE };
12
- export interface Admin {
13
- /** The Host's Tenant API URL. */
14
- readonly url: string;
15
- /** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
16
- readonly adminUrl: string;
17
- readonly source: "options" | "environment" | "local-host";
18
- /** The Host's status, with the one Tenant it serves (`status.tenant`). */
19
- status(): Promise<AdminStatus>;
20
- /**
21
- * The Tenant's operator keys (Host feature `operator-keys`): revocable application keys by
22
- * name. `keys.put("backend")` creates or rotates a key and returns it once.
23
- */
24
- readonly keys: AdminKeys;
25
- }
11
+ export { ManagementClient, createManagementClient, type ManagementClientOptions, type ManagementKeys, type ManagementModels, type ManagementSettings, type ManagementSigningKeys, type ManagementTenant, type ManagementVaults, } from "./management.js";
26
12
  /**
27
- * Resolution: explicit `url` + `key` → `NYLORUN_ADMIN_URL` + `NYLORUN_ADMIN_KEY` → the local
28
- * Host's settings in its Host root (`home`, `NYLORUN_HOME`, or the Tenant named by `tenant`,
29
- * `NYLORUN_TENANT` or the Project link under `cwd`: `~/.nylorun/tenants/<tenant>/`).
13
+ * The Management API client for the installation (`/v1/tenant/*`): `tenant`, `keys`
14
+ * (application keys), `models`, `vaults`, `signingKeys` and `settings`, with a management key.
15
+ * `source` says where the connection came from.
16
+ */
17
+ export type Admin = AdminClient;
18
+ /**
19
+ * Resolution: explicit `url` + `key` (a management key) → `NYLORUN_RUNTIME_URL` +
20
+ * `NYLORUN_MANAGEMENT_KEY` → the local Host: the URL from `host.json` in its Host root
21
+ * (`home`, `NYLORUN_HOME`, or the Tenant named by `tenant`, `NYLORUN_TENANT` or the Project link
22
+ * under `cwd`: `~/.nylorun/tenants/<tenant>/`), and the management key from the linked
23
+ * Project's `.nylorun/credentials.json`, else the Host root's `project-credentials.json`, else
24
+ * its `cli-credentials.json`. The first request checks the Host's `/health` first.
30
25
  */
31
26
  export declare function createAdmin(options?: AdminConnectionOptions): Admin;
32
- export type { AdminConnectionOptions, AdminKeys, AdminStatus, HostTenant, OperatorKey, PutOperatorKeyResponse, TenantEnvelope, };
27
+ export type { AdminConnectionOptions, AdminSource, HostTenant, OperatorKey, PutOperatorKeyResponse, TenantEnvelope, };
package/dist/index.js CHANGED
@@ -1,16 +1,19 @@
1
1
  import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, } from "@nylorun/core/compatibility";
2
- import { AdminClient, OPERATOR_KEYS_FEATURE, resolveAdminConnection, tenantHostRoot, } from "./client.js";
2
+ import { AdminClient, resolveAdminConnection, tenantHostRoot, } from "./client.js";
3
3
  import { deriveStudioToken } from "./derived-credentials.js";
4
4
  import { AdminError } from "./errors.js";
5
5
  export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
6
6
  export { AdminError };
7
7
  export { deriveStudioToken, tenantHostRoot };
8
8
  export { mintStudioLoginToken } from "./studio-login.js";
9
- export { OPERATOR_KEYS_FEATURE };
9
+ export { ManagementClient, createManagementClient, } from "./management.js";
10
10
  /**
11
- * Resolution: explicit `url` + `key` → `NYLORUN_ADMIN_URL` + `NYLORUN_ADMIN_KEY` → the local
12
- * Host's settings in its Host root (`home`, `NYLORUN_HOME`, or the Tenant named by `tenant`,
13
- * `NYLORUN_TENANT` or the Project link under `cwd`: `~/.nylorun/tenants/<tenant>/`).
11
+ * Resolution: explicit `url` + `key` (a management key) → `NYLORUN_RUNTIME_URL` +
12
+ * `NYLORUN_MANAGEMENT_KEY` → the local Host: the URL from `host.json` in its Host root
13
+ * (`home`, `NYLORUN_HOME`, or the Tenant named by `tenant`, `NYLORUN_TENANT` or the Project link
14
+ * under `cwd`: `~/.nylorun/tenants/<tenant>/`), and the management key from the linked
15
+ * Project's `.nylorun/credentials.json`, else the Host root's `project-credentials.json`, else
16
+ * its `cli-credentials.json`. The first request checks the Host's `/health` first.
14
17
  */
15
18
  export function createAdmin(options) {
16
19
  return new AdminClient(resolveAdminConnection(options));
@@ -0,0 +1,120 @@
1
+ import { type CreateCredentialRequest, type CreateVaultRequest, type CredentialInfo, type HostModelCatalog, type HostModelView, type ListProvidersResponse, type ModelCallExportPage, type ModelBudgets, type ModelUsageQuery, type ModelUsageTotals, type OperatorKey, type PutHostModelRequest, type PutModelBudgetsRequest, type PutOperatorKeyResponse, type PutTenantArtifactsRequest, type PutTenantSandboxRequest, type ResetTenantRequest, type ResetTenantResponse, type RotateCredentialRequest, type SeedTenantConfigRequest, type SeedTenantConfigResponse, type SelectHostModelRequest, type SigningKeyView, type StartOAuthRequest, type StartOAuthResponse, type TenantArtifactsView, type TenantSandboxView, type TenantStatus, type VaultInfo } from "@nylorun/core/contracts";
2
+ export interface ManagementClientOptions {
3
+ /** The Tenant's URL, or a proxy in front of it. */
4
+ url: string;
5
+ /** A management key. Omit it behind a proxy that adds the credential (Studio's). */
6
+ key?: string;
7
+ /** Default: the global `fetch`. */
8
+ fetch?: typeof fetch;
9
+ /** Sent on every request, after the client's own headers. */
10
+ headers?: Record<string, string>;
11
+ }
12
+ /** A request body without its `requestId`: the client makes one when it is not given. */
13
+ type Body<T> = Omit<T, "requestId"> & {
14
+ requestId?: string;
15
+ };
16
+ export interface ManagementTenant {
17
+ /** The Tenant's status: its envelope, schema, streams and harnesses. */
18
+ status(): Promise<TenantStatus>;
19
+ /** Seeds the Tenant's configuration where it is unset (`nylorun start` does this). */
20
+ seed(request: Body<SeedTenantConfigRequest>): Promise<SeedTenantConfigResponse>;
21
+ /** Resets the Tenant's sessions, sandboxes or both. */
22
+ reset(request: Body<ResetTenantRequest>): Promise<ResetTenantResponse>;
23
+ }
24
+ /** The Tenant's keys: application keys are managed here; management keys only on its machine. */
25
+ export interface ManagementKeys {
26
+ /** Every key by name, with its role and when it was issued; never the keys. */
27
+ list(): Promise<OperatorKey[]>;
28
+ /** Creates or rotates application key `id`; the key is in the answer this once. */
29
+ put(id: string): Promise<PutOperatorKeyResponse>;
30
+ /** Deletes application key `id`: true when it existed. */
31
+ delete(id: string): Promise<boolean>;
32
+ }
33
+ export interface ManagementModels {
34
+ /** Every provider and model the Runtime knows. */
35
+ catalog(): Promise<HostModelCatalog>;
36
+ /** The providers the Tenant has credentials for. */
37
+ providers(): Promise<ListProvidersResponse>;
38
+ /** The Tenant's model: provider, model and whether a credential is set. */
39
+ get(): Promise<HostModelView>;
40
+ /** Sets a provider's credential (and, optionally, the model). */
41
+ put(request: Body<PutHostModelRequest>): Promise<HostModelView>;
42
+ /** Chooses the provider and model among those with credentials. */
43
+ select(request: Body<SelectHostModelRequest>): Promise<HostModelView>;
44
+ /** What the Tenant's model calls used, for one scope and period. */
45
+ usage(query: ModelUsageQuery): Promise<ModelUsageTotals>;
46
+ /**
47
+ * Every recorded model call, unfiltered, in safe transaction order (Host feature
48
+ * `calls-export`): pages from `after` until `caughtUp`. Each page's `next` is the position to
49
+ * resume from; call again to follow. Deduplicate by row id.
50
+ */
51
+ exportCalls(options?: {
52
+ after?: string;
53
+ limit?: number;
54
+ }): AsyncIterable<ModelCallExportPage>;
55
+ readonly budgets: {
56
+ get(): Promise<ModelBudgets>;
57
+ /** Replaces every budget; an empty list removes every cap. */
58
+ put(request: Body<PutModelBudgetsRequest>): Promise<ModelBudgets>;
59
+ };
60
+ }
61
+ export interface ManagementVaults {
62
+ create(request: Body<CreateVaultRequest>): Promise<VaultInfo>;
63
+ /** The installation vaults, after `ownerUserId`'s when it is given. */
64
+ list(ownerUserId?: string): Promise<VaultInfo[]>;
65
+ get(vaultId: string): Promise<VaultInfo>;
66
+ delete(vaultId: string): Promise<{
67
+ id: string;
68
+ }>;
69
+ readonly credentials: {
70
+ create(vaultId: string, request: Body<CreateCredentialRequest>): Promise<CredentialInfo>;
71
+ list(vaultId: string): Promise<CredentialInfo[]>;
72
+ get(vaultId: string, credentialId: string): Promise<CredentialInfo>;
73
+ /** Rotates the credential's secret. */
74
+ rotate(vaultId: string, credentialId: string, request: Body<RotateCredentialRequest>): Promise<CredentialInfo>;
75
+ delete(vaultId: string, credentialId: string): Promise<{
76
+ id: string;
77
+ }>;
78
+ };
79
+ /** Starts an MCP OAuth connect into an installation vault: open `authorizeUrl` in a browser. */
80
+ startOAuth(vaultId: string, request: StartOAuthRequest): Promise<StartOAuthResponse>;
81
+ }
82
+ export interface ManagementSigningKeys {
83
+ list(): Promise<SigningKeyView[]>;
84
+ /**
85
+ * standby → current → previous → revoked, and a new standby. Refused while the key it would
86
+ * revoke may still verify a live token; `force` skips that and ends those tokens.
87
+ */
88
+ rotate(options?: {
89
+ force?: boolean;
90
+ }): Promise<SigningKeyView[]>;
91
+ /** Revokes a previous or standby key; rotate before revoking the current one. */
92
+ revoke(keyId: string): Promise<SigningKeyView>;
93
+ }
94
+ export interface ManagementSettings {
95
+ readonly sandbox: {
96
+ get(): Promise<TenantSandboxView>;
97
+ put(request: Body<PutTenantSandboxRequest>): Promise<TenantSandboxView>;
98
+ };
99
+ readonly artifacts: {
100
+ get(): Promise<TenantArtifactsView>;
101
+ put(request: Body<PutTenantArtifactsRequest>): Promise<TenantArtifactsView>;
102
+ };
103
+ }
104
+ /** One client of the Management API. */
105
+ export declare class ManagementClient {
106
+ #private;
107
+ readonly url: string;
108
+ readonly tenant: ManagementTenant;
109
+ readonly keys: ManagementKeys;
110
+ readonly models: ManagementModels;
111
+ readonly vaults: ManagementVaults;
112
+ readonly signingKeys: ManagementSigningKeys;
113
+ readonly settings: ManagementSettings;
114
+ constructor(options: ManagementClientOptions);
115
+ private pageCalls;
116
+ private request;
117
+ }
118
+ /** A Management API client for `url`, with a management key (or behind a proxy that adds one). */
119
+ export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
120
+ export {};
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The Management API client (`/v1/tenant/*`, protocol 8): the Tenant's settings, models,
3
+ * vaults, signing keys and application keys, with a management key. It imports nothing from
4
+ * Node, so a browser app that reaches the Runtime through its own proxy (Studio) uses it too:
5
+ * `@nylorun/admin/client`. `createAdmin()` in the package's main entry finds the URL and key.
6
+ */
7
+ import { PROTOCOL_HEADER, PROTOCOL_VERSION, } from "@nylorun/core/compatibility";
8
+ import { ModelCallExportPageSchema, RejectedResponseSchema, } from "@nylorun/core/contracts";
9
+ import { AdminError } from "./errors.js";
10
+ const segment = (value) => encodeURIComponent(value);
11
+ const withId = (body) => ({
12
+ requestId: crypto.randomUUID(),
13
+ ...body,
14
+ });
15
+ /** One client of the Management API. */
16
+ export class ManagementClient {
17
+ url;
18
+ tenant;
19
+ keys;
20
+ models;
21
+ vaults;
22
+ signingKeys;
23
+ settings;
24
+ #key;
25
+ #fetch;
26
+ #headers;
27
+ constructor(options) {
28
+ this.url = options.url.replace(/\/$/, "");
29
+ this.#key = options.key;
30
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
31
+ this.#headers = options.headers ?? {};
32
+ const call = (method, path, body) => this.request(method, path, body);
33
+ this.tenant = {
34
+ status: () => call("GET", "/v1/tenant"),
35
+ seed: (request) => call("PUT", "/v1/tenant/config/seed", withId(request)),
36
+ reset: (request) => call("POST", "/v1/tenant/reset", withId(request)),
37
+ };
38
+ this.keys = {
39
+ list: async () => (await call("GET", "/v1/tenant/keys")).keys,
40
+ put: (id) => call("PUT", `/v1/tenant/keys/${segment(id)}`),
41
+ delete: async (id) => {
42
+ try {
43
+ await call("DELETE", `/v1/tenant/keys/${segment(id)}`);
44
+ return true;
45
+ }
46
+ catch (error) {
47
+ if (error instanceof AdminError && error.status === 404 && error.message === `No key ${id}`)
48
+ return false;
49
+ throw error;
50
+ }
51
+ },
52
+ };
53
+ this.models = {
54
+ catalog: () => call("GET", "/v1/tenant/models"),
55
+ providers: () => call("GET", "/v1/tenant/providers"),
56
+ get: () => call("GET", "/v1/tenant/model"),
57
+ put: (request) => call("PUT", "/v1/tenant/model", withId(request)),
58
+ select: (request) => call("PUT", "/v1/tenant/model/selection", withId(request)),
59
+ usage: (query) => {
60
+ const search = new URLSearchParams(Object.entries(query).flatMap(([name, value]) => value === undefined ? [] : [[name, String(value)]]));
61
+ return call("GET", `/v1/tenant/usage?${search}`);
62
+ },
63
+ exportCalls: (options = {}) => this.pageCalls(options),
64
+ budgets: {
65
+ get: () => call("GET", "/v1/tenant/budgets"),
66
+ put: (request) => call("PUT", "/v1/tenant/budgets", withId(request)),
67
+ },
68
+ };
69
+ const vault = (vaultId) => `/v1/tenant/vaults/${segment(vaultId)}`;
70
+ const credential = (vaultId, credentialId) => `${vault(vaultId)}/credentials/${segment(credentialId)}`;
71
+ this.vaults = {
72
+ create: (request) => call("POST", "/v1/tenant/vaults", withId(request)),
73
+ list: async (ownerUserId) => (await call("GET", ownerUserId === undefined
74
+ ? "/v1/tenant/vaults"
75
+ : `/v1/tenant/vaults?ownerUserId=${segment(ownerUserId)}`)).vaults,
76
+ get: (vaultId) => call("GET", vault(vaultId)),
77
+ delete: (vaultId) => call("DELETE", vault(vaultId)),
78
+ credentials: {
79
+ create: (vaultId, request) => call("POST", `${vault(vaultId)}/credentials`, withId(request)),
80
+ list: async (vaultId) => (await call("GET", `${vault(vaultId)}/credentials`))
81
+ .credentials,
82
+ get: (vaultId, credentialId) => call("GET", credential(vaultId, credentialId)),
83
+ rotate: (vaultId, credentialId, request) => call("POST", credential(vaultId, credentialId), withId(request)),
84
+ delete: (vaultId, credentialId) => call("DELETE", credential(vaultId, credentialId)),
85
+ },
86
+ startOAuth: (vaultId, request) => call("POST", `${vault(vaultId)}/oauth/start`, request),
87
+ };
88
+ this.signingKeys = {
89
+ list: async () => (await call("GET", "/v1/tenant/signing-keys")).keys,
90
+ rotate: async (options = {}) => (await call("POST", "/v1/tenant/signing-keys/rotate", withId(options.force ? { force: true } : {}))).keys,
91
+ revoke: (keyId) => call("POST", `/v1/tenant/signing-keys/${segment(keyId)}/revoke`, withId({})),
92
+ };
93
+ this.settings = {
94
+ sandbox: {
95
+ get: () => call("GET", "/v1/tenant/sandbox"),
96
+ put: (request) => call("PUT", "/v1/tenant/sandbox", withId(request)),
97
+ },
98
+ artifacts: {
99
+ get: () => call("GET", "/v1/tenant/artifacts"),
100
+ put: (request) => call("PUT", "/v1/tenant/artifacts", withId(request)),
101
+ },
102
+ };
103
+ }
104
+ async *pageCalls(options) {
105
+ let after = options.after;
106
+ while (true) {
107
+ const query = new URLSearchParams({ limit: String(options.limit ?? 200) });
108
+ if (after !== undefined)
109
+ query.set("after", after);
110
+ const page = ModelCallExportPageSchema.parse(await this.request("GET", `/v1/tenant/calls/model?${query}`));
111
+ yield page;
112
+ if (page.caughtUp)
113
+ return;
114
+ if (page.next === null || page.next === after)
115
+ throw new Error("Model export did not advance its cursor");
116
+ after = page.next;
117
+ }
118
+ }
119
+ async request(method, path, body) {
120
+ const headers = {
121
+ [PROTOCOL_HEADER]: String(PROTOCOL_VERSION),
122
+ accept: "application/json",
123
+ ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
124
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
125
+ ...this.#headers,
126
+ };
127
+ const response = await this.#fetch(this.url + path, {
128
+ method,
129
+ headers,
130
+ redirect: "error",
131
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
132
+ });
133
+ const text = await response.text();
134
+ let parsed = undefined;
135
+ if (text) {
136
+ try {
137
+ parsed = JSON.parse(text);
138
+ }
139
+ catch {
140
+ parsed = text;
141
+ }
142
+ }
143
+ if (!response.ok) {
144
+ const rejected = RejectedResponseSchema.safeParse(parsed);
145
+ if (rejected.success)
146
+ throw new AdminError(rejected.data.code, rejected.data.message, {
147
+ status: response.status,
148
+ details: rejected.data.details,
149
+ });
150
+ throw new AdminError("not_found", `${method} ${path} failed (${response.status})`, {
151
+ status: response.status,
152
+ details: parsed,
153
+ });
154
+ }
155
+ return parsed;
156
+ }
157
+ }
158
+ /** A Management API client for `url`, with a management key (or behind a proxy that adds one). */
159
+ export function createManagementClient(options) {
160
+ return new ManagementClient(options);
161
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nylorun/admin",
3
- "version": "0.10.0-beta",
4
- "description": "Nylorun Admin API client for Tenants and Host status",
3
+ "version": "0.12.0-beta",
4
+ "description": "Nylorun Management API client: the Tenant's models, vaults, signing keys, settings and application keys",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "files": [
@@ -15,6 +15,10 @@
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "import": "./dist/index.js"
18
+ },
19
+ "./client": {
20
+ "types": "./dist/management.d.ts",
21
+ "import": "./dist/management.js"
18
22
  }
19
23
  },
20
24
  "scripts": {
@@ -24,7 +28,7 @@
24
28
  "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\""
25
29
  },
26
30
  "dependencies": {
27
- "@nylorun/core": "0.13.0-beta"
31
+ "@nylorun/core": "0.16.0-beta"
28
32
  },
29
33
  "peerDependencies": {
30
34
  "zod": "^4.6.5"