@nylorun/admin 0.5.0-beta → 0.7.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 +75 -0
- package/README.md +36 -39
- package/dist/client.d.ts +27 -22
- package/dist/client.js +82 -124
- package/dist/derived-credentials.d.ts +7 -6
- package/dist/derived-credentials.js +7 -6
- package/dist/index.d.ts +18 -24
- package/dist/index.js +8 -2
- package/dist/studio-login.d.ts +20 -0
- package/dist/studio-login.js +56 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,80 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0-beta
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 5ca1923: **Clients for one Tenant per installation: a stack per project, nothing selects a Tenant.** Upgrade these with the Runtime; they speak protocol 5. Existing stacks are left as they are: see MIGRATION.md.
|
|
8
|
+
|
|
9
|
+
- **Breaking (`nylorun`): one stack per project.** `nylorun start` in a project creates the project's stack (named after the project directory, or `--name`; Host root `~/.nylorun/stacks/<name>/`, Compose project `nylorun-<name>`, its own free ports and volumes), waits for its Runtime to create the stack's Tenant, writes the Project link (`.nylorun/link.json` format 2: `stack`, `hostUrl`, `hostId`, `tenantId`) and `.nylorun/credentials.json` (the key of the derived principal `project`, derived from the stack's admin key), and seeds the model provider from the project's `.env`. `nylorun ls` lists the machine's stacks and `nylorun delete <name>` removes one with its volumes and Host root. `nylorun status` shows the stack's Tenant; `nylorun studio` opens it. The old single stack under `~/.nylorun` is never touched: `start` notes it, and `nylorun legacy stop|delete` handles it. Every stack command takes `--name <stack>` (or `NYLORUN_STACK`, or the Project link's stack); `start --no-link` starts a stack without linking the directory; `nylorun reset` resets the selected stack only. The runtime container's healthcheck is now `/health`, so a Tenant that cannot open is reported by `start` from the Admin status at once instead of after a 300 s wait. `NYLORUN_HOME` still overrides the Host root. Stacks start and stop only when you say so.
|
|
10
|
+
- **Breaking (`@nylorun/cli`): no Tenant commands.** `nylo tenant create|use|list|current|delete` are removed; `nylo status`, `nylo reset` and `nylo endpoints` replace `nylo tenant status|reset|endpoints` on the linked installation. `nylo env` prints `NYLORUN_RUNTIME_URL` and `NYLORUN_SERVER_KEY` only. `nylo` no longer writes Project links.
|
|
11
|
+
- **Breaking (`@nylorun/agents`): no Tenant to name.** The `tenant` option (`createClient`, `Transport`, `resolveConnection`, `createActionHandler({ runtime })`, `JwksCache`) and `NYLORUN_TENANT` are gone, and no request sends `Nylorun-Tenant`; a connection is a URL and a key. A Project link of format 0 or 1 is refused with `connection_missing`, naming `npx nylorun start`. `verifyDeliveryToken`'s `tenantId` is optional: without it any Tenant issuer is accepted, since the installation's keys bind it. `TENANT_HEADER` is no longer re-exported.
|
|
12
|
+
- **Breaking (`@nylorun/admin`): status only.** `createTenant`, `listTenants`, `getTenant` and `deleteTenant` are removed; `status().tenant` names the Host's Tenant, and `deriveTenantKey` / `deriveStudioToken` derive its keys. Local Host resolution reads the stack's Host root (`stack` option, `NYLORUN_STACK`, or the Project link's `stack`); `NYLORUN_HOME` and `home` still override it. `stackHostRoot(name)` is exported.
|
|
13
|
+
- **Breaking (`@nylorun/studio`): Studio serves its installation's Tenant.** The Tenant picker, list and create are gone, with `/_studio/tenants`; `/` opens `/tenants/<id>`. The `/tenants/:tenant` routes and the login token's `tenant` claim stay for embedders and must name that Tenant. The proxy sends no `Nylorun-Tenant`.
|
|
14
|
+
- **`@nylorun/create-agent`:** the next steps are `npx nylorun start`, then `npm run dev`.
|
|
15
|
+
- `@nylorun/core`: `ProjectLinkFileSchema` accepts format 2 with `stack`, and `tenantId` is optional; `ERROR_CODES` loses `tenant_conflict` and `active_work`.
|
|
16
|
+
|
|
17
|
+
- 5ca1923: **One Tenant per installation: a database per Tenant, protocol 5.** A Runtime serves exactly one Tenant, the one its Postgres database holds. Two Tenants are two installations.
|
|
18
|
+
|
|
19
|
+
- **Breaking: fresh start.** The Tenant's state is in the fixed schema `nylorun` of its own database and its record in `nylorun_streams`, keyed by session (no `tenant_id`). A database written by an earlier Runtime (`tenant_<id>` schemas, or a record keyed by Tenant) is refused: the Host stays up but not ready, and `/v1/admin/status` names the cause `database-layout-old`. Point the Runtime at a new database (with the local stack, a new stack); the old one is never changed.
|
|
20
|
+
- **The Host creates its Tenant** on first start, in the migration transaction: `NYLORUN_TENANT_ID` (default a new id), `NYLORUN_TENANT_NAME` (default `default`), the Studio principal and the derived principals of `NYLORUN_DERIVED_PRINCIPALS` (comma-separated, default `project`), whose keys the admin key derives (`deriveTenantKey`). Later starts open the same Tenant and add derived principals configured since.
|
|
21
|
+
- **Breaking: no Tenant catalog.** `/v1/admin/tenants` and `/v1/admin/tenants/{tenantId}` are gone (404). `AdminStatus.tenants[]` is replaced by `AdminStatus.tenant` (`id`, `name`, `state: open | unavailable`, `envelope`, and `cause` when it could not be opened). `CreateTenantRequestSchema`, `AdminTenantSchema`, `AdminTenantStatusSchema`, `AdminTenantListSchema` and `QuarantineSchema` leave `@nylorun/core`; `HostTenantSchema` and `TenantCauseSchema` replace them. `@nylorun/admin`'s `listTenants`, `getTenant`, `deleteTenant` and `createTenant` are removed (see below).
|
|
22
|
+
- **Readiness instead of quarantine.** A Tenant that cannot be opened (`schema-too-new`, `kek-missing`, `migration-failed`, `envelope-invalid`, `database-layout-old`, …) fails `/ready` (check `tenant`, which replaces `discovery`) and is reported with its repair in `/v1/admin/status` and the log; every Tenant request gets the opaque 404. A failure outside it (Postgres unreachable) is retried.
|
|
23
|
+
- **Protocol 5.** `PROTOCOL_VERSION = 5`; the Host serves protocols 4 and 5 for one release. Clients no longer require `runtime-tenants`; the Host still advertises it. No request needs `Nylorun-Tenant`: a request without it reaches the Host's Tenant, and one naming another Tenant (or a malformed one), or a publishable key of another Tenant, gets the opaque 404. The OpenAPI documents drop the header parameter and the Admin Tenant routes.
|
|
24
|
+
- **Paths.** The Tenant directory is `<Host root>/tenant/` (was `tenants/<id>/`); `trash/` and the SQLite move to it are gone. The gates service serves its database's Tenant, and its `Nylorun-Tenant` header is optional (when sent, it must name that Tenant).
|
|
25
|
+
- **Breaking: `startEphemeralRuntime` needs a database; the in-memory Session Store is removed.** `StartEphemeralRuntimeOptions.database` is required: a Postgres URL, for which the Runtime opens a pool and ends it on `close()`, or a pool the caller ends. It creates its Tenant in that database through the same bootstrap as a Host, or serves the Tenant the database already holds; the data stays after `close()`, so give each test Tenant a database of its own. Durable Streams and scheduling stay in process. See `MIGRATION.md`.
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- Pin core to the tested release.
|
|
30
|
+
- Updated dependencies [fed780d]
|
|
31
|
+
- Updated dependencies [fed780d]
|
|
32
|
+
- Updated dependencies [7f4c3f1]
|
|
33
|
+
- Updated dependencies [5ca1923]
|
|
34
|
+
- Updated dependencies [5ca1923]
|
|
35
|
+
- @nylorun/core@0.10.0-beta
|
|
36
|
+
|
|
37
|
+
## 0.6.0-beta
|
|
38
|
+
|
|
39
|
+
### Minor Changes
|
|
40
|
+
|
|
41
|
+
- 50d0fb5: **The Admin API on its own listener.** A Runtime can serve the Admin API on an operator listener, so the port that faces browsers and reverse proxies serves the Tenant API alone. The stack does this by default.
|
|
42
|
+
|
|
43
|
+
- **Runtime.** With an operator listener (`adminPort` in `host.json`, or `NYLORUN_ADMIN_LISTEN_PORT`, `NYLORUN_ADMIN_LISTEN_HOST` and `NYLORUN_ADMIN_ALLOWED_HOSTS` in a container), the public listener answers `/v1/admin/**` with the opaque `404` and the operator listener serves the Admin API, Host shutdown and the Tenant API, never to browsers. Each checks `Host` against its own port. `/ready` needs both listening; a taken port on either exits with code 98. Without one, a single listener serves everything as before.
|
|
44
|
+
- **Stack.** `nylorun start` publishes the operator port on loopback (`NYLORUN_ADMIN_PORT`, default 8788), writes it to `host.json` as `adminPort`, and points Studio at `runtime:4001`. `nylorun status` prints it.
|
|
45
|
+
- **Admin client.** Reads `adminPort` from `host.json` and sends Admin API requests there (`admin.adminUrl`); `admin.url` stays the Tenant API URL. A `host.json` without `adminPort` keeps working.
|
|
46
|
+
|
|
47
|
+
- 9d52189: **Embedding Studio in a desktop app.** Studio can be shown inside a desktop app such as Babai Desktop, in an iframe loaded from its URL and signed in by `postMessage` with a token limited to one Tenant.
|
|
48
|
+
|
|
49
|
+
- **`nylorun`.** The local stack lets Babai's origins frame Studio: `NYLORUN_STUDIO_FRAME_ANCESTORS` in `stack/.env` defaults to `nylorun://localhost http://nylorun.localhost` and is passed to the Studio container. `nylorun start --studio-embed-origin <origin>` (repeatable) adds an exact origin, such as a desktop app's dev server, and keeps it across starts until `--studio-embed-origin-reset`. Wildcards are refused. `nylorun status` lists the origins under `Embeds`, and `status --json` as `studio.embedOrigins`.
|
|
50
|
+
- **`@nylorun/admin`.** `mintStudioLoginToken({ studioUrl, adminKey, tenant?, subject? })` mints a single-use Studio login token from an app's backend. With `tenant`, the session it leads to reaches only that Tenant.
|
|
51
|
+
- **Studio.** `POST /_studio/sessions` exchanges such a token for a one-hour bearer session kept in the frame's memory; dashboard pages send `frame-ancestors` from the allowlist instead of `X-Frame-Options: DENY`; `?embed=1` hides Studio's branding, follows the app's theme and routes, and reports its own; `/tenants/:tenant/sessions/:session` opens a session by id. The cookie login of `nylorun studio` is unchanged.
|
|
52
|
+
|
|
53
|
+
The dashboard routes `/tenants/:tenant`, `/tenants/:tenant/agents/:agent`, `/tenants/:tenant/agents/:agent/sessions/:session`, `/tenants/:tenant/sessions/:session`, `/tenants/:tenant/vault` and `/tenants/:tenant/settings` are now a public contract for embedders: removing or changing one is a breaking change.
|
|
54
|
+
|
|
55
|
+
### Patch Changes
|
|
56
|
+
|
|
57
|
+
- Pin core to the tested release.
|
|
58
|
+
- Updated dependencies [c7614a4]
|
|
59
|
+
- Updated dependencies [679c488]
|
|
60
|
+
- Updated dependencies [c85cd9e]
|
|
61
|
+
- Updated dependencies [4282d5f]
|
|
62
|
+
- Updated dependencies [82d95ef]
|
|
63
|
+
- Updated dependencies [f48f12f]
|
|
64
|
+
- Updated dependencies [50d0fb5]
|
|
65
|
+
- Updated dependencies [50d0fb5]
|
|
66
|
+
- Updated dependencies [c121144]
|
|
67
|
+
- Updated dependencies [6ab4c59]
|
|
68
|
+
- Updated dependencies [6ab4c59]
|
|
69
|
+
- Updated dependencies [2ab8ed1]
|
|
70
|
+
- Updated dependencies [c121144]
|
|
71
|
+
- Updated dependencies [9546ac7]
|
|
72
|
+
- Updated dependencies [9546ac7]
|
|
73
|
+
- Updated dependencies [9d52189]
|
|
74
|
+
- Updated dependencies [50d0fb5]
|
|
75
|
+
- Updated dependencies [18468d9]
|
|
76
|
+
- @nylorun/core@0.9.0-beta
|
|
77
|
+
|
|
3
78
|
## 0.5.0-beta
|
|
4
79
|
|
|
5
80
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,61 +1,58 @@
|
|
|
1
1
|
# @nylorun/admin
|
|
2
2
|
|
|
3
|
-
Admin API client for
|
|
4
|
-
|
|
5
|
-
24+. Vocabulary: [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
|
|
3
|
+
Admin API client for a Runtime installation: its status, with the one Tenant it
|
|
4
|
+
serves, and the keys the admin key derives. Depends only on `@nylorun/core`.
|
|
5
|
+
Requires Node 24+. Vocabulary: [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
|
|
6
6
|
|
|
7
7
|
```ts
|
|
8
8
|
import { createAdmin } from "@nylorun/admin";
|
|
9
9
|
|
|
10
10
|
// Resolution: explicit options → NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY → local Host
|
|
11
11
|
const admin = createAdmin();
|
|
12
|
-
// or: createAdmin({ url, key }) / createAdmin({
|
|
12
|
+
// or: createAdmin({ url, key }) / createAdmin({ stack: "my-app" }) / createAdmin({ home })
|
|
13
13
|
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
await admin.listTenants();
|
|
17
|
-
await admin.getTenant(tenant.id);
|
|
18
|
-
await admin.deleteTenant(tenant.id, { activeWork: "refuse" });
|
|
14
|
+
const { tenant } = await admin.status();
|
|
15
|
+
// tenant: { id, name, state: "open" | "unavailable", envelope, cause? }
|
|
19
16
|
```
|
|
20
17
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
`
|
|
24
|
-
|
|
18
|
+
An installation serves one Tenant, which its Host creates on first start. There
|
|
19
|
+
are no Tenant routes: `createTenant`, `listTenants`, `getTenant` and
|
|
20
|
+
`deleteTenant` are gone, and a Host answers `/v1/admin/tenants*` with `404`.
|
|
21
|
+
When the Tenant cannot be opened, `status.tenant.state` is `unavailable` and
|
|
22
|
+
`cause` names why (`schema-too-new`, `kek-missing`, `database-layout-old`, …).
|
|
25
23
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
same key from the admin key to call that Tenant's API, so whoever holds the
|
|
29
|
-
admin key can reach every Tenant created this way.
|
|
30
|
-
|
|
31
|
-
A client on the Host's machine or server that holds the admin key can avoid
|
|
32
|
-
storing an application key too. Name it as a **derived principal** when the
|
|
33
|
-
Tenant is created, then recompute its key whenever it needs one:
|
|
24
|
+
Whoever holds the admin key can derive the keys of the Tenant's derived
|
|
25
|
+
principals and of its Studio principal, so those clients store no key:
|
|
34
26
|
|
|
35
27
|
```ts
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
});
|
|
40
|
-
// Later, in any process that holds the admin key:
|
|
41
|
-
const key = admin.deriveTenantKey(tenant.id, "babai");
|
|
28
|
+
const key = admin.deriveTenantKey(tenant.id!, "project");
|
|
29
|
+
// deriveTenantKey(adminKey, tenantId, principalId) and
|
|
30
|
+
// deriveStudioToken(adminKey, tenantId) are exported too.
|
|
42
31
|
```
|
|
43
32
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Local Host resolution reads `host.json` and `host-credentials.json`
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
33
|
+
The Host registers the derived principals it is configured with
|
|
34
|
+
(`NYLORUN_DERIVED_PRINCIPALS`, default `project`; Babai uses `project,babai`)
|
|
35
|
+
when it creates its Tenant, and `studio` always. Ids match
|
|
36
|
+
`^[a-z][a-z0-9-]{0,31}$`; `studio` is reserved. Only each key's hash is stored,
|
|
37
|
+
so rotating the admin key rotates every derived key. `nylorun start` writes the
|
|
38
|
+
`project` key into a Project's `.nylorun/credentials.json`.
|
|
39
|
+
|
|
40
|
+
Local Host resolution reads `host.json` and `host-credentials.json` from the
|
|
41
|
+
Host root: `options.home`, else `NYLORUN_HOME`, else the stack's Host root
|
|
42
|
+
`~/.nylorun/stacks/<stack>/` for the stack named by `options.stack`,
|
|
43
|
+
`NYLORUN_STACK` or the Project link (`stack` in `.nylorun/link.json`, found
|
|
44
|
+
from `options.cwd` upwards). On POSIX the credentials file must be owned by the
|
|
45
|
+
user and not group- or world-readable. First use checks `/health`
|
|
46
|
+
compatibility and throws `incompatible_host` on mismatch.
|
|
47
|
+
|
|
48
|
+
`mintStudioLoginToken({ studioUrl, adminKey })` mints a single-use Studio login
|
|
49
|
+
token for an app that embeds Studio; its optional `tenant` must name the Host's
|
|
50
|
+
Tenant.
|
|
55
51
|
|
|
56
52
|
Errors are `AdminError` with a registry `code` from `@nylorun/core`
|
|
57
53
|
(`ERROR_CODES`). Re-exports: `PROTOCOL_FEATURES`, `ERROR_CODES`,
|
|
58
|
-
`compareVersions`, `deriveStudioToken`, `deriveTenantKey
|
|
54
|
+
`compareVersions`, `deriveStudioToken`, `deriveTenantKey`, `stackHostRoot`,
|
|
55
|
+
`PROJECT_PRINCIPAL_ID`.
|
|
59
56
|
|
|
60
57
|
Developer applications do **not** depend on this package — only managing
|
|
61
58
|
clients (CLI, desktop Runtime panel, CI) do.
|
package/dist/client.d.ts
CHANGED
|
@@ -1,26 +1,42 @@
|
|
|
1
|
-
import { type AdminStatus
|
|
1
|
+
import { type AdminStatus } from "@nylorun/core/contracts";
|
|
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
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;
|
|
5
11
|
key: string;
|
|
6
12
|
source: AdminSource;
|
|
7
|
-
|
|
13
|
+
/** The Host root read for local Host settings, when one was found. */
|
|
14
|
+
home?: string;
|
|
8
15
|
}
|
|
9
|
-
|
|
10
|
-
* Resolve Admin API connection once: options → environment → local Host.
|
|
11
|
-
*/
|
|
12
|
-
export declare function resolveAdminConnection(options?: {
|
|
16
|
+
export interface AdminConnectionOptions {
|
|
13
17
|
url?: string;
|
|
14
18
|
key?: string;
|
|
19
|
+
/** The Host root itself (overrides `NYLORUN_HOME` and the stack). */
|
|
15
20
|
home?: string;
|
|
16
|
-
|
|
21
|
+
/** The local stack whose Host root (`~/.nylorun/stacks/<stack>/`) to read. */
|
|
22
|
+
stack?: string;
|
|
23
|
+
/** Where to look for a Project link naming the stack; defaults to the working directory. */
|
|
24
|
+
cwd?: string;
|
|
25
|
+
}
|
|
26
|
+
/** A local stack's Host root: `~/.nylorun/stacks/<name>/`. */
|
|
27
|
+
export declare function stackHostRoot(name: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* Resolve Admin API connection once: options → environment → local Host.
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveAdminConnection(options?: AdminConnectionOptions): ResolvedAdmin;
|
|
17
32
|
export declare class AdminClient {
|
|
33
|
+
/** The Host's Tenant API URL. */
|
|
18
34
|
readonly url: string;
|
|
35
|
+
/** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
|
|
36
|
+
readonly adminUrl: string;
|
|
19
37
|
readonly source: AdminSource;
|
|
20
38
|
private readonly key;
|
|
21
39
|
private compatible;
|
|
22
|
-
/** Features the Host advertised at the last compatibility check. */
|
|
23
|
-
private features;
|
|
24
40
|
constructor(resolved: ResolvedAdmin);
|
|
25
41
|
private clearCompatibilityCache;
|
|
26
42
|
private adminHeaders;
|
|
@@ -28,21 +44,10 @@ export declare class AdminClient {
|
|
|
28
44
|
private request;
|
|
29
45
|
private json;
|
|
30
46
|
status(): Promise<AdminStatus>;
|
|
31
|
-
listTenants(): Promise<AdminTenant[]>;
|
|
32
|
-
getTenant(id: string): Promise<AdminTenantStatus>;
|
|
33
|
-
deleteTenant(id: string, options?: {
|
|
34
|
-
activeWork?: "refuse" | "drain" | "cancel";
|
|
35
|
-
}): Promise<void>;
|
|
36
47
|
/**
|
|
37
48
|
* The key of derived principal `principalId` on `tenantId`, from this client's admin key.
|
|
38
|
-
* Valid
|
|
49
|
+
* Valid when the Host registered that principal (`NYLORUN_DERIVED_PRINCIPALS`, default
|
|
50
|
+
* `project`) on its Tenant.
|
|
39
51
|
*/
|
|
40
52
|
deriveTenantKey(tenantId: string, principalId: string): string;
|
|
41
|
-
createTenant(options: {
|
|
42
|
-
name: string;
|
|
43
|
-
principals?: readonly string[];
|
|
44
|
-
}): Promise<{
|
|
45
|
-
tenant: TenantEnvelope;
|
|
46
|
-
applicationKey: string;
|
|
47
|
-
}>;
|
|
48
53
|
}
|
package/dist/client.js
CHANGED
|
@@ -1,29 +1,80 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { readFileSync, statSync } from "node:fs";
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
2
|
import { homedir } from "node:os";
|
|
4
|
-
import { join, resolve } from "node:path";
|
|
5
|
-
import { AdminStatusSchema,
|
|
6
|
-
import { PROTOCOL_FEATURES, PROTOCOL_HEADER, PROTOCOL_VERSION, checkCompatibility,
|
|
7
|
-
import {
|
|
3
|
+
import { dirname, join, parse, resolve } from "node:path";
|
|
4
|
+
import { AdminStatusSchema, ProjectLinkFileSchema, RejectedResponseSchema, } from "@nylorun/core/contracts";
|
|
5
|
+
import { PROTOCOL_FEATURES, PROTOCOL_HEADER, PROTOCOL_VERSION, checkCompatibility, } from "@nylorun/core/compatibility";
|
|
6
|
+
import { deriveTenantKey } from "./derived-credentials.js";
|
|
8
7
|
import { AdminError } from "./errors.js";
|
|
9
8
|
function env(name) {
|
|
10
9
|
const value = process.env[name];
|
|
11
10
|
return value === undefined || value.trim() === "" ? undefined : value;
|
|
12
11
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
/** A local stack's Host root: `~/.nylorun/stacks/<name>/`. */
|
|
13
|
+
export function stackHostRoot(name) {
|
|
14
|
+
return resolve(join(homedir(), ".nylorun", "stacks", name));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The stack a Project link names (`.nylorun/link.json`, format 2), from `cwd` upwards. The walk
|
|
18
|
+
* stops at the home directory, which holds the stacks and is never a Project.
|
|
19
|
+
*/
|
|
20
|
+
function linkedStack(cwd) {
|
|
21
|
+
const real = (path) => {
|
|
22
|
+
try {
|
|
23
|
+
return realpathSync(path);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return path;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const stop = real(homedir());
|
|
30
|
+
let directory = real(resolve(cwd));
|
|
31
|
+
const root = parse(directory).root;
|
|
32
|
+
while (directory !== stop) {
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = readFileSync(join(directory, ".nylorun", "link.json"), "utf8");
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
/* no link here */
|
|
39
|
+
}
|
|
40
|
+
if (raw !== undefined) {
|
|
41
|
+
try {
|
|
42
|
+
return ProjectLinkFileSchema.parse(JSON.parse(raw)).stack;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (directory === root)
|
|
49
|
+
return undefined;
|
|
50
|
+
directory = dirname(directory);
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The Host root of the local Host: `options.home`, `NYLORUN_HOME`, or the Host root of the stack
|
|
56
|
+
* named by `options.stack`, `NYLORUN_STACK` or the Project link. Undefined when none names one.
|
|
57
|
+
*/
|
|
58
|
+
function resolveHome(options) {
|
|
59
|
+
if (options?.home !== undefined && options.home.trim() !== "")
|
|
60
|
+
return resolve(options.home);
|
|
16
61
|
const fromEnv = env("NYLORUN_HOME");
|
|
17
62
|
if (fromEnv)
|
|
18
63
|
return resolve(fromEnv);
|
|
19
|
-
|
|
64
|
+
const stack = options?.stack?.trim() ||
|
|
65
|
+
env("NYLORUN_STACK")?.trim() ||
|
|
66
|
+
linkedStack(options?.cwd ?? process.cwd());
|
|
67
|
+
return stack ? stackHostRoot(stack) : undefined;
|
|
20
68
|
}
|
|
21
69
|
function connectionMissing(message) {
|
|
22
70
|
throw new AdminError("connection_missing", message);
|
|
23
71
|
}
|
|
24
72
|
function sourcesTriedMessage(home) {
|
|
25
73
|
return (`Tried options (url + key), environment (NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY), ` +
|
|
26
|
-
|
|
74
|
+
(home
|
|
75
|
+
? `and local Host settings (host.json + host-credentials.json under ${home}).`
|
|
76
|
+
: "and local Host settings (no stack named: pass `stack`, set NYLORUN_STACK or " +
|
|
77
|
+
"NYLORUN_HOME, or run in a Project that `npx nylorun start` linked)."));
|
|
27
78
|
}
|
|
28
79
|
function assertCredentialsSafe(path) {
|
|
29
80
|
if (process.platform === "win32")
|
|
@@ -73,19 +124,25 @@ function readLocalHost(home) {
|
|
|
73
124
|
}
|
|
74
125
|
const host = config.host;
|
|
75
126
|
const port = config.port;
|
|
127
|
+
const adminPort = config.adminPort;
|
|
76
128
|
const adminKey = credentials.adminKey;
|
|
77
129
|
if (typeof host !== "string" || typeof port !== "number")
|
|
78
130
|
return undefined;
|
|
79
131
|
if (typeof adminKey !== "string" || !/^[0-9a-f]{64}$/.test(adminKey)) {
|
|
80
132
|
return undefined;
|
|
81
133
|
}
|
|
82
|
-
return {
|
|
134
|
+
return {
|
|
135
|
+
url: `http://${host}:${port}`,
|
|
136
|
+
// An older Host serves the Admin API on its only port.
|
|
137
|
+
adminUrl: `http://${host}:${typeof adminPort === "number" ? adminPort : port}`,
|
|
138
|
+
key: adminKey,
|
|
139
|
+
};
|
|
83
140
|
}
|
|
84
141
|
/**
|
|
85
142
|
* Resolve Admin API connection once: options → environment → local Host.
|
|
86
143
|
*/
|
|
87
144
|
export function resolveAdminConnection(options) {
|
|
88
|
-
const home = resolveHome(options
|
|
145
|
+
const home = resolveHome(options);
|
|
89
146
|
const optionUrl = options?.url?.trim() || undefined;
|
|
90
147
|
const optionKey = options?.key?.trim() || undefined;
|
|
91
148
|
if (optionUrl || optionKey) {
|
|
@@ -96,7 +153,7 @@ export function resolveAdminConnection(options) {
|
|
|
96
153
|
url: optionUrl.replace(/\/$/, ""),
|
|
97
154
|
key: optionKey,
|
|
98
155
|
source: "options",
|
|
99
|
-
home,
|
|
156
|
+
...(home ? { home } : {}),
|
|
100
157
|
};
|
|
101
158
|
}
|
|
102
159
|
const envUrl = env("NYLORUN_ADMIN_URL");
|
|
@@ -109,13 +166,14 @@ export function resolveAdminConnection(options) {
|
|
|
109
166
|
url: envUrl.replace(/\/$/, ""),
|
|
110
167
|
key: envKey,
|
|
111
168
|
source: "environment",
|
|
112
|
-
home,
|
|
169
|
+
...(home ? { home } : {}),
|
|
113
170
|
};
|
|
114
171
|
}
|
|
115
|
-
const local = readLocalHost(home);
|
|
172
|
+
const local = home === undefined ? undefined : readLocalHost(home);
|
|
116
173
|
if (local) {
|
|
117
174
|
return {
|
|
118
175
|
url: local.url.replace(/\/$/, ""),
|
|
176
|
+
adminUrl: local.adminUrl.replace(/\/$/, ""),
|
|
119
177
|
key: local.key,
|
|
120
178
|
source: "local-host",
|
|
121
179
|
home,
|
|
@@ -140,12 +198,6 @@ function parseProtocolRange(value) {
|
|
|
140
198
|
features: record.features,
|
|
141
199
|
};
|
|
142
200
|
}
|
|
143
|
-
function hashCredential(token) {
|
|
144
|
-
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
145
|
-
}
|
|
146
|
-
function mintApplicationKey() {
|
|
147
|
-
return randomBytes(32).toString("hex");
|
|
148
|
-
}
|
|
149
201
|
function throwFromResponse(status, body) {
|
|
150
202
|
const parsed = RejectedResponseSchema.safeParse(body);
|
|
151
203
|
if (parsed.success) {
|
|
@@ -154,9 +206,6 @@ function throwFromResponse(status, body) {
|
|
|
154
206
|
details: parsed.data.details,
|
|
155
207
|
});
|
|
156
208
|
}
|
|
157
|
-
if (status === 409) {
|
|
158
|
-
throw new AdminError("tenant_conflict", `Admin request conflict (${status})`, { status, details: body });
|
|
159
|
-
}
|
|
160
209
|
if (status === 404) {
|
|
161
210
|
throw new AdminError("not_found", `Admin request not found (${status})`, {
|
|
162
211
|
status,
|
|
@@ -180,14 +229,16 @@ async function readBody(response) {
|
|
|
180
229
|
}
|
|
181
230
|
}
|
|
182
231
|
export class AdminClient {
|
|
232
|
+
/** The Host's Tenant API URL. */
|
|
183
233
|
url;
|
|
234
|
+
/** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
|
|
235
|
+
adminUrl;
|
|
184
236
|
source;
|
|
185
237
|
key;
|
|
186
238
|
compatible = false;
|
|
187
|
-
/** Features the Host advertised at the last compatibility check. */
|
|
188
|
-
features = [];
|
|
189
239
|
constructor(resolved) {
|
|
190
240
|
this.url = resolved.url;
|
|
241
|
+
this.adminUrl = resolved.adminUrl ?? resolved.url;
|
|
191
242
|
this.source = resolved.source;
|
|
192
243
|
this.key = resolved.key;
|
|
193
244
|
}
|
|
@@ -206,7 +257,7 @@ export class AdminClient {
|
|
|
206
257
|
async ensureCompatible(signal) {
|
|
207
258
|
if (this.compatible)
|
|
208
259
|
return;
|
|
209
|
-
const response = await fetch(`${this.
|
|
260
|
+
const response = await fetch(`${this.adminUrl}/health`, {
|
|
210
261
|
method: "GET",
|
|
211
262
|
redirect: "error",
|
|
212
263
|
signal,
|
|
@@ -228,12 +279,11 @@ export class AdminClient {
|
|
|
228
279
|
: `Host is missing required features: ${result.missing.join(", ")}`;
|
|
229
280
|
throw new AdminError("incompatible_host", `Incompatible Host: ${detail}`, { details: result });
|
|
230
281
|
}
|
|
231
|
-
this.features = [...protocol.features];
|
|
232
282
|
this.compatible = true;
|
|
233
283
|
}
|
|
234
284
|
async request(path, init = {}, options = {}) {
|
|
235
285
|
await this.ensureCompatible(init.signal === null ? undefined : init.signal);
|
|
236
|
-
const response = await fetch(this.
|
|
286
|
+
const response = await fetch(this.adminUrl + path, {
|
|
237
287
|
...init,
|
|
238
288
|
headers: this.adminHeaders(init),
|
|
239
289
|
redirect: "error",
|
|
@@ -275,104 +325,12 @@ export class AdminClient {
|
|
|
275
325
|
const body = await this.json("/v1/admin/status");
|
|
276
326
|
return AdminStatusSchema.parse(body);
|
|
277
327
|
}
|
|
278
|
-
async listTenants() {
|
|
279
|
-
const body = await this.json("/v1/admin/tenants");
|
|
280
|
-
if (!Array.isArray(body)) {
|
|
281
|
-
throw new AdminError("not_found", "Admin list tenants response was not an array.", { details: body });
|
|
282
|
-
}
|
|
283
|
-
return body.map((item) => AdminTenantSchema.parse(item));
|
|
284
|
-
}
|
|
285
|
-
async getTenant(id) {
|
|
286
|
-
const body = await this.json(`/v1/admin/tenants/${encodeURIComponent(id)}`);
|
|
287
|
-
return AdminTenantStatusSchema.parse(body);
|
|
288
|
-
}
|
|
289
|
-
async deleteTenant(id, options) {
|
|
290
|
-
const activeWork = options?.activeWork ?? "refuse";
|
|
291
|
-
await this.json(`/v1/admin/tenants/${encodeURIComponent(id)}?activeWork=${activeWork}`, "DELETE");
|
|
292
|
-
}
|
|
293
328
|
/**
|
|
294
329
|
* The key of derived principal `principalId` on `tenantId`, from this client's admin key.
|
|
295
|
-
* Valid
|
|
330
|
+
* Valid when the Host registered that principal (`NYLORUN_DERIVED_PRINCIPALS`, default
|
|
331
|
+
* `project`) on its Tenant.
|
|
296
332
|
*/
|
|
297
333
|
deriveTenantKey(tenantId, principalId) {
|
|
298
334
|
return deriveTenantKey(this.key, tenantId, principalId);
|
|
299
335
|
}
|
|
300
|
-
async createTenant(options) {
|
|
301
|
-
const principals = options.principals ?? [];
|
|
302
|
-
for (const id of principals)
|
|
303
|
-
if (!DERIVED_PRINCIPAL_ID_PATTERN.test(id) || id === "studio")
|
|
304
|
-
throw new TypeError(`Principal id '${id}' must match ${DERIVED_PRINCIPAL_ID_PATTERN} and not be 'studio'.`);
|
|
305
|
-
if (new Set(principals).size !== principals.length)
|
|
306
|
-
throw new TypeError("Principal ids must be unique.");
|
|
307
|
-
if (principals.length) {
|
|
308
|
-
await this.ensureCompatible();
|
|
309
|
-
if (!this.features.includes("derived-principals"))
|
|
310
|
-
throw new AdminError("incompatible_host", "Host does not support derived principals (feature derived-principals); upgrade it with `nylorun up`.");
|
|
311
|
-
}
|
|
312
|
-
const applicationKey = mintApplicationKey();
|
|
313
|
-
const tenantId = newTenantId();
|
|
314
|
-
const body = {
|
|
315
|
-
tenantId,
|
|
316
|
-
name: options.name,
|
|
317
|
-
principalId: newPrincipalId(),
|
|
318
|
-
credentialHash: hashCredential(applicationKey),
|
|
319
|
-
idempotencyKey: randomUUID(),
|
|
320
|
-
studioCredentialHash: hashCredential(deriveStudioToken(this.key, tenantId)),
|
|
321
|
-
...(principals.length
|
|
322
|
-
? {
|
|
323
|
-
derivedPrincipals: principals.map((id) => ({
|
|
324
|
-
id,
|
|
325
|
-
credentialHash: hashCredential(deriveTenantKey(this.key, tenantId, id)),
|
|
326
|
-
})),
|
|
327
|
-
}
|
|
328
|
-
: {}),
|
|
329
|
-
};
|
|
330
|
-
let lastError;
|
|
331
|
-
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
332
|
-
let response;
|
|
333
|
-
try {
|
|
334
|
-
response = await this.request("/v1/admin/tenants", {
|
|
335
|
-
method: "POST",
|
|
336
|
-
body: JSON.stringify(body),
|
|
337
|
-
signal: AbortSignal.timeout(15_000),
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
catch (error) {
|
|
341
|
-
if (error instanceof AdminError)
|
|
342
|
-
throw error;
|
|
343
|
-
lastError = error;
|
|
344
|
-
if (attempt === 2) {
|
|
345
|
-
throw new AdminError("not_found", `Could not create Tenant after network errors: ${error instanceof Error ? error.message : String(error)}`, { details: error });
|
|
346
|
-
}
|
|
347
|
-
continue;
|
|
348
|
-
}
|
|
349
|
-
if (response.status === 409) {
|
|
350
|
-
const parsed = await readBody(response);
|
|
351
|
-
throw new AdminError("tenant_conflict", "Tenant id conflict.", {
|
|
352
|
-
status: 409,
|
|
353
|
-
details: parsed,
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
if (response.status >= 500) {
|
|
357
|
-
lastError = await readBody(response);
|
|
358
|
-
if (attempt === 2) {
|
|
359
|
-
throwFromResponse(response.status, lastError);
|
|
360
|
-
}
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
const parsed = await readBody(response);
|
|
364
|
-
if (response.status !== 201 && response.status !== 200) {
|
|
365
|
-
throwFromResponse(response.status, parsed);
|
|
366
|
-
}
|
|
367
|
-
return {
|
|
368
|
-
tenant: TenantEnvelopeSchema.parse(parsed),
|
|
369
|
-
applicationKey,
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
throw lastError instanceof AdminError
|
|
373
|
-
? lastError
|
|
374
|
-
: new AdminError("not_found", "Could not create Tenant after retries.", {
|
|
375
|
-
details: lastError,
|
|
376
|
-
});
|
|
377
|
-
}
|
|
378
336
|
}
|
|
@@ -5,15 +5,16 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export declare function deriveStudioToken(adminKey: string, tenantId: string): string;
|
|
7
7
|
/**
|
|
8
|
-
* The derived principal that Projects
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* The derived principal that Projects use. The Host registers it on its Tenant by default
|
|
9
|
+
* (`NYLORUN_DERIVED_PRINCIPALS`), and `nylorun start` derives its key from the stack's admin
|
|
10
|
+
* key into the Project's `.nylorun/credentials.json`.
|
|
11
11
|
*/
|
|
12
12
|
export declare const PROJECT_PRINCIPAL_ID = "project";
|
|
13
13
|
/**
|
|
14
14
|
* Deterministic key of a derived principal (`principalId`, e.g. `babai`) on one Tenant,
|
|
15
|
-
* derived from the admin key. The Tenant stores only its hash, registered when the
|
|
16
|
-
*
|
|
17
|
-
* key when it needs it and stores nothing.
|
|
15
|
+
* derived from the admin key. The Tenant stores only its hash, registered when the Host creates
|
|
16
|
+
* its Tenant with the principals it is configured with (`NYLORUN_DERIVED_PRINCIPALS`, feature
|
|
17
|
+
* `derived-principals`); the client recomputes the key when it needs it and stores nothing.
|
|
18
|
+
* Rotating the admin key rotates every derived key.
|
|
18
19
|
*/
|
|
19
20
|
export declare function deriveTenantKey(adminKey: string, tenantId: string, principalId: string): string;
|
|
@@ -15,16 +15,17 @@ export function deriveStudioToken(adminKey, tenantId) {
|
|
|
15
15
|
.digest("hex");
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* The derived principal that Projects
|
|
19
|
-
*
|
|
20
|
-
*
|
|
18
|
+
* The derived principal that Projects use. The Host registers it on its Tenant by default
|
|
19
|
+
* (`NYLORUN_DERIVED_PRINCIPALS`), and `nylorun start` derives its key from the stack's admin
|
|
20
|
+
* key into the Project's `.nylorun/credentials.json`.
|
|
21
21
|
*/
|
|
22
22
|
export const PROJECT_PRINCIPAL_ID = "project";
|
|
23
23
|
/**
|
|
24
24
|
* Deterministic key of a derived principal (`principalId`, e.g. `babai`) on one Tenant,
|
|
25
|
-
* derived from the admin key. The Tenant stores only its hash, registered when the
|
|
26
|
-
*
|
|
27
|
-
* key when it needs it and stores nothing.
|
|
25
|
+
* derived from the admin key. The Tenant stores only its hash, registered when the Host creates
|
|
26
|
+
* its Tenant with the principals it is configured with (`NYLORUN_DERIVED_PRINCIPALS`, feature
|
|
27
|
+
* `derived-principals`); the client recomputes the key when it needs it and stores nothing.
|
|
28
|
+
* Rotating the admin key rotates every derived key.
|
|
28
29
|
*/
|
|
29
30
|
export function deriveTenantKey(adminKey, tenantId, principalId) {
|
|
30
31
|
const message = Buffer.concat([
|
package/dist/index.d.ts
CHANGED
|
@@ -1,38 +1,32 @@
|
|
|
1
|
-
import type { AdminStatus,
|
|
1
|
+
import type { AdminStatus, HostTenant, TenantEnvelope } from "@nylorun/core/contracts";
|
|
2
2
|
import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, type ErrorCode } from "@nylorun/core/compatibility";
|
|
3
|
+
import { stackHostRoot, type AdminConnectionOptions } from "./client.js";
|
|
3
4
|
import { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey } from "./derived-credentials.js";
|
|
4
5
|
import { AdminError } from "./errors.js";
|
|
5
6
|
export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
|
|
6
7
|
export type { ErrorCode };
|
|
7
8
|
export { AdminError };
|
|
8
|
-
export { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey };
|
|
9
|
+
export { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey, stackHostRoot };
|
|
10
|
+
export { mintStudioLoginToken } from "./studio-login.js";
|
|
9
11
|
export interface Admin {
|
|
12
|
+
/** The Host's Tenant API URL. */
|
|
10
13
|
readonly url: string;
|
|
14
|
+
/** Where Admin API requests go: the operator listener, or `url` on a single-port Host. */
|
|
15
|
+
readonly adminUrl: string;
|
|
11
16
|
readonly source: "options" | "environment" | "local-host";
|
|
17
|
+
/** The Host's status, with the one Tenant it serves (`status.tenant`). */
|
|
12
18
|
status(): Promise<AdminStatus>;
|
|
13
|
-
listTenants(): Promise<AdminTenant[]>;
|
|
14
|
-
getTenant(id: string): Promise<AdminTenantStatus>;
|
|
15
|
-
deleteTenant(id: string, options?: {
|
|
16
|
-
activeWork?: "refuse" | "drain" | "cancel";
|
|
17
|
-
}): Promise<void>;
|
|
18
19
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* `
|
|
20
|
+
* The key of a derived principal on the Host's Tenant, from this client's admin key. The
|
|
21
|
+
* Host registers the principals it is configured with (`NYLORUN_DERIVED_PRINCIPALS`, default
|
|
22
|
+
* `project`) when it creates its Tenant.
|
|
22
23
|
*/
|
|
23
|
-
createTenant(options: {
|
|
24
|
-
name: string;
|
|
25
|
-
principals?: readonly string[];
|
|
26
|
-
}): Promise<{
|
|
27
|
-
tenant: TenantEnvelope;
|
|
28
|
-
applicationKey: string;
|
|
29
|
-
}>;
|
|
30
|
-
/** The key of a derived principal on a Tenant, from this client's admin key. */
|
|
31
24
|
deriveTenantKey(tenantId: string, principalId: string): string;
|
|
32
25
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
export
|
|
26
|
+
/**
|
|
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 stack named by `stack`,
|
|
29
|
+
* `NYLORUN_STACK` or the Project link under `cwd`: `~/.nylorun/stacks/<stack>/`).
|
|
30
|
+
*/
|
|
31
|
+
export declare function createAdmin(options?: AdminConnectionOptions): Admin;
|
|
32
|
+
export type { AdminConnectionOptions, AdminStatus, HostTenant, TenantEnvelope };
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, } from "@nylorun/core/compatibility";
|
|
2
|
-
import { AdminClient, resolveAdminConnection } from "./client.js";
|
|
2
|
+
import { AdminClient, resolveAdminConnection, stackHostRoot, } from "./client.js";
|
|
3
3
|
import { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey, } from "./derived-credentials.js";
|
|
4
4
|
import { AdminError } from "./errors.js";
|
|
5
5
|
export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
|
|
6
6
|
export { AdminError };
|
|
7
|
-
export { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey };
|
|
7
|
+
export { PROJECT_PRINCIPAL_ID, deriveStudioToken, deriveTenantKey, stackHostRoot };
|
|
8
|
+
export { mintStudioLoginToken } from "./studio-login.js";
|
|
9
|
+
/**
|
|
10
|
+
* Resolution: explicit `url` + `key` → `NYLORUN_ADMIN_URL` + `NYLORUN_ADMIN_KEY` → the local
|
|
11
|
+
* Host's settings in its Host root (`home`, `NYLORUN_HOME`, or the stack named by `stack`,
|
|
12
|
+
* `NYLORUN_STACK` or the Project link under `cwd`: `~/.nylorun/stacks/<stack>/`).
|
|
13
|
+
*/
|
|
8
14
|
export function createAdmin(options) {
|
|
9
15
|
return new AdminClient(resolveAdminConnection(options));
|
|
10
16
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type StudioLoginTokenResponse } from "@nylorun/core/contracts";
|
|
2
|
+
/**
|
|
3
|
+
* Mints a single-use Studio login token with the admin key (`POST
|
|
4
|
+
* /_studio/login-tokens`, Studio §8.4). An app that embeds Studio, such as
|
|
5
|
+
* Babai, calls this from its backend and hands only the token to its page,
|
|
6
|
+
* which passes it to the framed Studio in `init`.
|
|
7
|
+
*
|
|
8
|
+
* - `tenant` names the Host's one Tenant, for embedders that pass it (the embed
|
|
9
|
+
* contract keeps it); Studio refuses any other. Omit it, as `nylorun studio` does.
|
|
10
|
+
* - `subject` names the person, for Studio's logs.
|
|
11
|
+
*/
|
|
12
|
+
export declare function mintStudioLoginToken(options: {
|
|
13
|
+
/** Studio's URL, e.g. `studio.url` from `nylorun status --json`. */
|
|
14
|
+
studioUrl: string;
|
|
15
|
+
adminKey: string;
|
|
16
|
+
tenant?: string;
|
|
17
|
+
subject?: string;
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}): Promise<StudioLoginTokenResponse>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { StudioLoginTokenRequestSchema, StudioLoginTokenResponseSchema, } from "@nylorun/core/contracts";
|
|
2
|
+
import { AdminError } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Mints a single-use Studio login token with the admin key (`POST
|
|
5
|
+
* /_studio/login-tokens`, Studio §8.4). An app that embeds Studio, such as
|
|
6
|
+
* Babai, calls this from its backend and hands only the token to its page,
|
|
7
|
+
* which passes it to the framed Studio in `init`.
|
|
8
|
+
*
|
|
9
|
+
* - `tenant` names the Host's one Tenant, for embedders that pass it (the embed
|
|
10
|
+
* contract keeps it); Studio refuses any other. Omit it, as `nylorun studio` does.
|
|
11
|
+
* - `subject` names the person, for Studio's logs.
|
|
12
|
+
*/
|
|
13
|
+
export async function mintStudioLoginToken(options) {
|
|
14
|
+
const body = StudioLoginTokenRequestSchema.safeParse({
|
|
15
|
+
...(options.tenant !== undefined ? { tenant: options.tenant } : {}),
|
|
16
|
+
...(options.subject !== undefined ? { subject: options.subject } : {}),
|
|
17
|
+
});
|
|
18
|
+
if (!body.success)
|
|
19
|
+
throw new AdminError("invalid_request", `Invalid Studio login token request: ${body.error.issues[0]?.message ?? "invalid"}`);
|
|
20
|
+
const fetcher = options.fetch ?? fetch;
|
|
21
|
+
const url = new URL("/_studio/login-tokens", options.studioUrl);
|
|
22
|
+
let response;
|
|
23
|
+
try {
|
|
24
|
+
response = await fetcher(url, {
|
|
25
|
+
method: "POST",
|
|
26
|
+
headers: {
|
|
27
|
+
authorization: `Bearer ${options.adminKey}`,
|
|
28
|
+
"content-type": "application/json",
|
|
29
|
+
accept: "application/json",
|
|
30
|
+
},
|
|
31
|
+
body: JSON.stringify(body.data),
|
|
32
|
+
redirect: "error",
|
|
33
|
+
signal: options.signal ?? AbortSignal.timeout(5000),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
throw new AdminError("connection_missing", `Studio is unavailable at ${url.origin}: ${error instanceof Error ? error.message : String(error)}`);
|
|
38
|
+
}
|
|
39
|
+
const text = await response.text();
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
let message = `Studio refused a login token (HTTP ${response.status}).`;
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(text);
|
|
44
|
+
if (typeof parsed.message === "string")
|
|
45
|
+
message = parsed.message;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
/* keep the status message */
|
|
49
|
+
}
|
|
50
|
+
throw new AdminError(response.status === 401 ? "host_rejected" : "request_rejected", message, { status: response.status });
|
|
51
|
+
}
|
|
52
|
+
const parsed = StudioLoginTokenResponseSchema.safeParse(JSON.parse(text));
|
|
53
|
+
if (!parsed.success)
|
|
54
|
+
throw new AdminError("incompatible_host", "This Studio does not support login tokens limited to a Tenant; update the stack.");
|
|
55
|
+
return parsed.data;
|
|
56
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/admin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0-beta",
|
|
4
4
|
"description": "Nylorun Admin API client for Tenants and Host status",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\""
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@nylorun/core": "0.
|
|
27
|
+
"@nylorun/core": "0.10.0-beta"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
30
|
"zod": "^4.6.5"
|