@nylorun/admin 0.13.0-beta → 0.14.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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - 7780b2f: **One client and connection layer.** The Project link and credentials are read one way, and every Runtime client shares one `/health` probe.
8
+
9
+ - `@nylorun/core`: `@nylorun/core/project` (Node only, the one Core subpath that imports Node modules) reads the Nylorun home, a local Tenant's Host root (`tenantHostRoot`), the Project root (`findProjectRoot`) and the Project link and credentials (`findLinkedProject`, `readProjectLink`, `readCredentialsFile`), validated with `ProjectLinkFileSchema` and `ProjectCredentialsFileSchema`; a broken or newer file throws `ProjectFileError`. `@nylorun/core/transport` (browser-safe) holds the `/health` compatibility probe (`checkHealth`), `parseProtocolRange` (on `ProtocolRangeSchema`, ignoring fields a newer Host adds), `describeIncompatibility`, `requestHeaders` and `readBody`.
10
+ - `@nylorun/agents`: `resolveConnection` and `createClient()` find the Project as every reader does: the nearest directory with `.nylorun/` from `cwd` upwards, never the home directory or above it (they used to walk to the filesystem root, and past a `.nylorun/` without a link). A link without `credentials.json`, or a link or credentials file that does not validate, is now `connection_missing` naming the file and `npx nylorun start`, instead of a raw file-system or parse error. `@nylorun/agents/client` loads the link reader only when `createClient()` resolves a connection, so it imports no Node module. The root entry re-exports `checkHealth`, `describeIncompatibility` and `parseProtocolRange`.
11
+ - `@nylorun/admin`: `createAdmin` reads the Project link with the same reader. A link that does not validate is now refused like one from an older nylorun (when nothing else names the Host root), and a linked Project's `credentials.json` that does not validate is `connection_missing` instead of being skipped. `@nylorun/admin/project` re-exports `@nylorun/core/project` for tools that depend on this package. The `/health` check and request headers come from `@nylorun/core/transport`.
12
+ - `nylorun`: reads the Project link and credentials with `@nylorun/core/project`; a credentials file whose keys are not 64 hex characters is replaced by `start`, as an unreadable one was. No command changes.
13
+ - `@nylorun/cli`: `nylo` reads the Project root, link and credentials through `@nylorun/admin/project` instead of its own copies, with the same messages. No command changes.
14
+ - `@nylorun/studio`: the server's Runtime compatibility probe is `checkHealth` from `@nylorun/agents`.
15
+
16
+ ### Patch Changes
17
+
18
+ - Pin core to the tested release.
19
+ - Updated dependencies [7780b2f]
20
+ - Updated dependencies [070674d]
21
+ - @nylorun/core@0.18.0-beta
22
+
3
23
  ## 0.13.0-beta
4
24
 
5
25
  ### Major Changes
package/README.md CHANGED
@@ -34,15 +34,21 @@ order, and `admin.source` says which one it used (`options`, `environment` or
34
34
  3. The local Host. The URL comes from `host.json` in the Host root:
35
35
  `options.home`, else `NYLORUN_HOME`, else `~/.nylorun/tenants/<tenant>/` for
36
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
37
+ link (`.nylorun/link.json`, format 3, in the nearest directory with
38
+ `.nylorun/` from `options.cwd` upwards, below the home directory). The
38
39
  key is the `managementKey` of the linked Project's `.nylorun/credentials.json`,
39
40
  else of the Host root's `project-credentials.json`, else of its
40
41
  `cli-credentials.json`. `nylorun start` writes them (the keys
41
42
  `project-management` and `cli-management`). On POSIX a credentials file must
42
43
  be the user's and not group- or world-readable.
43
44
 
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
45
+ When none resolves, or the Project link is from an older nylorun or does not
46
+ validate (and nothing else names the Host root), or the linked Project's
47
+ `credentials.json` does not validate, it throws `connection_missing` and lists
48
+ what it tried. Only this local-Host step reads the Host root: `@nylorun/agents`
49
+ takes the Runtime API's key from the Project or the environment only.
50
+ `@nylorun/admin/project` re-exports `@nylorun/core/project`, the reader of the
51
+ Project files, for tools that depend on this package (`nylo`). The first request checks the
46
52
  Host's `/health` and throws `incompatible_host` unless the Host serves protocol
47
53
  8 with the feature `management-api`.
48
54
 
package/dist/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { tenantHostRoot } from "@nylorun/core/project";
1
2
  import { ManagementClient } from "./management.js";
2
3
  export type AdminSource = "options" | "environment" | "local-host";
3
4
  export interface ResolvedAdmin {
@@ -20,8 +21,7 @@ export interface AdminConnectionOptions {
20
21
  /** Where to look for a Project link naming the Tenant; defaults to the working directory. */
21
22
  cwd?: string;
22
23
  }
23
- /** A local Tenant's Host root: `~/.nylorun/tenants/<name>/`. */
24
- export declare function tenantHostRoot(name: string): string;
24
+ export { tenantHostRoot };
25
25
  /** Resolve the Management API connection once: options → environment → local Host. */
26
26
  export declare function resolveAdminConnection(options?: AdminConnectionOptions): ResolvedAdmin;
27
27
  /** What `createAdmin` returns: the Management API client, and where its connection came from. */
package/dist/client.js CHANGED
@@ -1,65 +1,43 @@
1
- import { readFileSync, realpathSync, statSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { dirname, join, parse, resolve } from "node:path";
4
- import { ProjectLinkFileSchema, RejectedResponseSchema } from "@nylorun/core/contracts";
5
- import { PROTOCOL_FEATURES, PROTOCOL_VERSION, checkCompatibility, } from "@nylorun/core/compatibility";
6
- import { AdminError } from "./errors.js";
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { ProjectFileError, findLinkedProjectRoot, projectCredentialsPath, projectLinkPath, readCredentialsFile, readProjectLink, tenantHostRoot, } from "@nylorun/core/project";
4
+ import { checkHealth, describeIncompatibility } from "@nylorun/core/transport";
5
+ import { AdminError, rejection } from "./errors.js";
7
6
  import { ManagementClient } from "./management.js";
8
7
  function env(name) {
9
8
  const value = process.env[name];
10
9
  return value === undefined || value.trim() === "" ? undefined : value;
11
10
  }
12
- /** A local Tenant's Host root: `~/.nylorun/tenants/<name>/`. */
13
- export function tenantHostRoot(name) {
14
- return resolve(join(homedir(), ".nylorun", "tenants", name));
15
- }
11
+ export { tenantHostRoot };
16
12
  /**
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.
13
+ * The Project link (`.nylorun/link.json`, format 3) from `cwd` upwards (`@nylorun/core/project`):
14
+ * the Tenant it names and the Project's root, or why it cannot be used (`unusable`: a link from
15
+ * an older nylorun or a broken file), which only matters when nothing else names the Host root.
20
16
  */
21
17
  function projectLink(cwd) {
22
- const real = (path) => {
23
- try {
24
- return realpathSync(path);
25
- }
26
- catch {
27
- return path;
28
- }
29
- };
30
- const stop = real(homedir());
31
- let directory = real(resolve(cwd));
32
- const root = parse(directory).root;
33
- while (directory !== stop) {
34
- const path = join(directory, ".nylorun", "link.json");
35
- let raw;
36
- try {
37
- raw = readFileSync(path, "utf8");
38
- }
39
- catch {
40
- /* no link here */
41
- }
42
- if (raw !== undefined) {
43
- try {
44
- const link = ProjectLinkFileSchema.parse(JSON.parse(raw));
45
- if (link.format < 3)
46
- return { olderLink: path };
47
- return { ...(link.tenant ? { tenant: link.tenant } : {}), directory: dirname(path) };
48
- }
49
- catch {
50
- return {};
51
- }
52
- }
53
- if (directory === root)
18
+ const project = findLinkedProjectRoot(cwd);
19
+ if (project === undefined)
20
+ return {};
21
+ try {
22
+ const link = readProjectLink(project);
23
+ if (link === undefined)
54
24
  return {};
55
- directory = dirname(directory);
25
+ if (link.format < 3)
26
+ return {
27
+ unusable: `The Project link at ${projectLinkPath(project)} is from an older nylorun. Run "npx nylorun start" in this project to link it again.`,
28
+ };
29
+ return { ...(link.tenant ? { tenant: link.tenant } : {}), project };
30
+ }
31
+ catch (error) {
32
+ if (error instanceof ProjectFileError)
33
+ return { unusable: error.message };
34
+ throw error;
56
35
  }
57
- return {};
58
36
  }
59
37
  /**
60
38
  * The Host root of the local Host: `options.home`, `NYLORUN_HOME`, or the Host root of the
61
39
  * 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.
40
+ * linked Project's root when the link names this Host root's Tenant.
63
41
  */
64
42
  function resolveHome(options) {
65
43
  const link = projectLink(options?.cwd ?? process.cwd());
@@ -75,8 +53,8 @@ function resolveHome(options) {
75
53
  : linked;
76
54
  return {
77
55
  ...(home ? { home } : {}),
78
- ...(home && home === linked ? { project: link.directory } : {}),
79
- ...(link.olderLink ? { olderLink: link.olderLink } : {}),
56
+ ...(home && home === linked ? { project: link.project } : {}),
57
+ ...(link.unusable ? { unusableLink: link.unusable } : {}),
80
58
  };
81
59
  }
82
60
  function connectionMissing(message) {
@@ -119,6 +97,23 @@ function readJson(path) {
119
97
  return undefined;
120
98
  }
121
99
  }
100
+ /**
101
+ * The management key of a credentials file. The linked Project's must read (a broken one is
102
+ * `connection_missing`, as for every reader of the Project's files); a Host root's key file that
103
+ * does not read holds no key.
104
+ */
105
+ function managementKeyOf(path, project) {
106
+ try {
107
+ return readCredentialsFile(path)?.managementKey;
108
+ }
109
+ catch (error) {
110
+ if (!(error instanceof ProjectFileError))
111
+ throw error;
112
+ if (project)
113
+ connectionMissing(error.message);
114
+ return undefined;
115
+ }
116
+ }
122
117
  /**
123
118
  * The local Host's URL (`host.json`) and a management key: from the linked Project's
124
119
  * `.nylorun/credentials.json`, else the Host root's `project-credentials.json`, else its
@@ -129,13 +124,13 @@ function readLocalHost(home, project) {
129
124
  if (typeof config?.host !== "string" || typeof config.port !== "number")
130
125
  return undefined;
131
126
  const files = [
132
- ...(project ? [join(project, "credentials.json")] : []),
133
- join(home, "project-credentials.json"),
134
- join(home, "cli-credentials.json"),
127
+ ...(project ? [{ path: projectCredentialsPath(project), project: true }] : []),
128
+ { path: join(home, "project-credentials.json"), project: false },
129
+ { path: join(home, "cli-credentials.json"), project: false },
135
130
  ];
136
- for (const path of files) {
137
- const key = readJson(path)?.managementKey;
138
- if (typeof key !== "string" || !/^[0-9a-f]{64}$/.test(key))
131
+ for (const { path, project: own } of files) {
132
+ const key = managementKeyOf(path, own);
133
+ if (key === undefined)
139
134
  continue;
140
135
  assertCredentialsSafe(path, home);
141
136
  return { url: `http://${config.host}:${config.port}`, key };
@@ -144,7 +139,7 @@ function readLocalHost(home, project) {
144
139
  }
145
140
  /** Resolve the Management API connection once: options → environment → local Host. */
146
141
  export function resolveAdminConnection(options) {
147
- const { home, project, olderLink } = resolveHome(options);
142
+ const { home, project, unusableLink } = resolveHome(options);
148
143
  const optionUrl = options?.url?.trim() || undefined;
149
144
  const optionKey = options?.key?.trim() || undefined;
150
145
  if (optionUrl || optionKey) {
@@ -160,47 +155,22 @@ export function resolveAdminConnection(options) {
160
155
  connectionMissing(`Incomplete environment: NYLORUN_MANAGEMENT_KEY needs NYLORUN_RUNTIME_URL. ${sourcesTriedMessage(home)}`);
161
156
  return { url: envUrl.replace(/\/$/, ""), key: envKey, source: "environment", ...(home ? { home } : {}) };
162
157
  }
163
- if (olderLink && !home)
164
- connectionMissing(`The Project link at ${olderLink} is from an older nylorun. Run "npx nylorun start" in this project to link it again.`);
158
+ if (unusableLink && !home)
159
+ connectionMissing(unusableLink);
165
160
  const local = home === undefined ? undefined : readLocalHost(home, project);
166
161
  if (local)
167
162
  return { url: local.url, key: local.key, source: "local-host", home };
168
163
  connectionMissing(`Could not resolve the Management API connection. ${sourcesTriedMessage(home)}`);
169
164
  }
170
- function parseProtocolRange(value) {
171
- if (!value || typeof value !== "object" || Array.isArray(value))
172
- return undefined;
173
- const record = value;
174
- if (typeof record.min !== "number" ||
175
- typeof record.max !== "number" ||
176
- !Array.isArray(record.features) ||
177
- !record.features.every((f) => typeof f === "string"))
178
- return undefined;
179
- return { min: record.min, max: record.max, features: record.features };
180
- }
181
165
  /** 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)
166
+ async function requireCompatibleHost(url) {
167
+ const health = await checkHealth(url);
168
+ if (health.result === "failed")
169
+ throw rejection(health.status, health.body, "Host /health failed");
170
+ if (health.result === "unadvertised")
196
171
  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 });
203
- }
172
+ if (health.result === "incompatible")
173
+ throw new AdminError("incompatible_host", `Incompatible Host: ${describeIncompatibility(health.compatibility)}`, { details: health.compatibility });
204
174
  }
205
175
  /**
206
176
  * `fetch` that checks the Host's `/health` before the first request, and again after a `426`,
@@ -208,7 +178,7 @@ async function checkHealth(url) {
208
178
  */
209
179
  function compatibleFetch(url) {
210
180
  let checked;
211
- const check = () => (checked ??= checkHealth(url).catch((error) => {
181
+ const check = () => (checked ??= requireCompatibleHost(url).catch((error) => {
212
182
  checked = undefined;
213
183
  throw error;
214
184
  }));
package/dist/errors.d.ts CHANGED
@@ -8,3 +8,8 @@ export declare class AdminError extends Error {
8
8
  details?: unknown;
9
9
  });
10
10
  }
11
+ /**
12
+ * The `AdminError` of a refused request: the Runtime's rejection (`{ status: "rejected", code,
13
+ * message }`), else `not_found` naming `what` and the status.
14
+ */
15
+ export declare function rejection(status: number, body: unknown, what: string): AdminError;
package/dist/errors.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { RejectedResponseSchema } from "@nylorun/core/contracts";
1
2
  export class AdminError extends Error {
2
3
  code;
3
4
  status;
@@ -10,3 +11,16 @@ export class AdminError extends Error {
10
11
  this.details = options?.details;
11
12
  }
12
13
  }
14
+ /**
15
+ * The `AdminError` of a refused request: the Runtime's rejection (`{ status: "rejected", code,
16
+ * message }`), else `not_found` naming `what` and the status.
17
+ */
18
+ export function rejection(status, body, what) {
19
+ const rejected = RejectedResponseSchema.safeParse(body);
20
+ return rejected.success
21
+ ? new AdminError(rejected.data.code, rejected.data.message, {
22
+ status,
23
+ details: rejected.data.details,
24
+ })
25
+ : new AdminError("not_found", `${what} (${status})`, { status, details: body });
26
+ }
@@ -4,9 +4,9 @@
4
4
  * Node, so a browser app that reaches the Runtime through its own proxy (Studio) uses it too:
5
5
  * `@nylorun/admin/client`. `createAdmin()` in the package's main entry finds the URL and key.
6
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";
7
+ import { parseBody, requestHeaders } from "@nylorun/core/transport";
8
+ import { ModelCallExportPageSchema, } from "@nylorun/core/contracts";
9
+ import { AdminError, rejection } from "./errors.js";
10
10
  const segment = (value) => encodeURIComponent(value);
11
11
  const withId = (body) => ({
12
12
  requestId: crypto.randomUUID(),
@@ -121,9 +121,8 @@ export class ManagementClient {
121
121
  }
122
122
  async request(method, path, body) {
123
123
  const headers = {
124
- [PROTOCOL_HEADER]: String(PROTOCOL_VERSION),
124
+ ...requestHeaders(this.#key),
125
125
  accept: "application/json",
126
- ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
127
126
  ...(body === undefined ? {} : { "content-type": "application/json" }),
128
127
  ...this.#headers,
129
128
  };
@@ -134,27 +133,9 @@ export class ManagementClient {
134
133
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
135
134
  });
136
135
  const text = await response.text();
137
- let parsed = undefined;
138
- if (text) {
139
- try {
140
- parsed = JSON.parse(text);
141
- }
142
- catch {
143
- parsed = text;
144
- }
145
- }
146
- if (!response.ok) {
147
- const rejected = RejectedResponseSchema.safeParse(parsed);
148
- if (rejected.success)
149
- throw new AdminError(rejected.data.code, rejected.data.message, {
150
- status: response.status,
151
- details: rejected.data.details,
152
- });
153
- throw new AdminError("not_found", `${method} ${path} failed (${response.status})`, {
154
- status: response.status,
155
- details: parsed,
156
- });
157
- }
136
+ const parsed = text ? parseBody(text) : undefined;
137
+ if (!response.ok)
138
+ throw rejection(response.status, parsed, `${method} ${path} failed`);
158
139
  return parsed;
159
140
  }
160
141
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The local machine's Nylorun files (`@nylorun/admin/project`, Node only): the Nylorun home, a
3
+ * local Tenant's Host root, the Project root, and the Project link and credentials, validated
4
+ * with Core's schemas. It is `@nylorun/core/project`, for operator tools that depend on this
5
+ * package and not on Core (`nylo`); `createAdmin` resolves the Project link with it.
6
+ */
7
+ export * from "@nylorun/core/project";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The local machine's Nylorun files (`@nylorun/admin/project`, Node only): the Nylorun home, a
3
+ * local Tenant's Host root, the Project root, and the Project link and credentials, validated
4
+ * with Core's schemas. It is `@nylorun/core/project`, for operator tools that depend on this
5
+ * package and not on Core (`nylo`); `createAdmin` resolves the Project link with it.
6
+ */
7
+ export * from "@nylorun/core/project";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/admin",
3
- "version": "0.13.0-beta",
3
+ "version": "0.14.0-beta",
4
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",
@@ -19,6 +19,10 @@
19
19
  "./client": {
20
20
  "types": "./dist/management.d.ts",
21
21
  "import": "./dist/management.js"
22
+ },
23
+ "./project": {
24
+ "types": "./dist/project.d.ts",
25
+ "import": "./dist/project.js"
22
26
  }
23
27
  },
24
28
  "scripts": {
@@ -28,7 +32,7 @@
28
32
  "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\""
29
33
  },
30
34
  "dependencies": {
31
- "@nylorun/core": "0.17.0-beta"
35
+ "@nylorun/core": "0.18.0-beta"
32
36
  },
33
37
  "peerDependencies": {
34
38
  "zod": "^4.6.5"