@nylorun/admin 0.2.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 ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - c49efed: **New package:** Admin API client for managing clients (CLI, desktop Runtime panel, CI). Exports `createAdmin` with `createTenant`, `listTenants`, `getTenant`, `deleteTenant`, and `status`. Depends only on `@nylorun/core`. Resolves connection from options, then `NYLORUN_ADMIN_URL`/`NYLORUN_ADMIN_KEY`, then local Host settings (`host.json` + `host-credentials.json`). Developer applications do not depend on this package.
8
+
9
+ ### Patch Changes
10
+
11
+ - Pin core to the tested release.
12
+ - Updated dependencies [c49efed]
13
+ - Updated dependencies [c49efed]
14
+ - Updated dependencies [fd9fd87]
15
+ - @nylorun/core@0.5.0-beta
16
+
17
+ ## 0.1.0-beta
18
+
19
+ - Package skeleton (Wave 0).
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 Nylo
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @nylorun/admin
2
+
3
+ Admin API client for creating, listing, inspecting and deleting Tenants, and
4
+ reading Host service status. Depends only on `@nylorun/core`. Requires Node
5
+ 24+. Vocabulary: [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
6
+
7
+ ```ts
8
+ import { createAdmin } from "@nylorun/admin";
9
+
10
+ // Resolution: explicit options → NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY → local Host
11
+ const admin = createAdmin();
12
+ // or: createAdmin({ url, key }) / createAdmin({ home: "/path/to/host-root" })
13
+
14
+ const status = await admin.status();
15
+ const { tenant, applicationKey } = await admin.createTenant({ name: "my-app" });
16
+ await admin.listTenants();
17
+ await admin.getTenant(tenant.id);
18
+ await admin.deleteTenant(tenant.id, { activeWork: "refuse" });
19
+ ```
20
+
21
+ `createTenant` generates the Tenant id, principal, application key and
22
+ idempotency key locally; only the key's hash is sent. On network error or
23
+ `5xx` it retries up to three times with identical values. Persist the returned
24
+ `applicationKey` — the Host never sees it in cleartext again.
25
+
26
+ Local Host resolution reads `host.json` and `host-credentials.json` under
27
+ `NYLORUN_HOME` / `~/.nylorun` (or `options.home`). On POSIX the credentials
28
+ file must be owned by the user and not group- or world-readable. First use
29
+ checks `/health` compatibility and throws `incompatible_host` on mismatch.
30
+
31
+ Errors are `AdminError` with a registry `code` from `@nylorun/core`
32
+ (`ERROR_CODES`). Re-exports: `PROTOCOL_FEATURES`, `ERROR_CODES`,
33
+ `compareVersions`.
34
+
35
+ Developer applications do **not** depend on this package — only managing
36
+ clients (CLI, desktop Runtime panel, CI) do. See
37
+ [building a desktop client](../docs/building-a-desktop-client.md).
@@ -0,0 +1,40 @@
1
+ import { type AdminStatus, type AdminTenant, type AdminTenantStatus, type TenantEnvelope } from "@nylorun/core/contracts";
2
+ export type AdminSource = "options" | "environment" | "local-host";
3
+ export interface ResolvedAdmin {
4
+ url: string;
5
+ key: string;
6
+ source: AdminSource;
7
+ home: string;
8
+ }
9
+ /**
10
+ * Resolve Admin API connection once: options → environment → local Host.
11
+ */
12
+ export declare function resolveAdminConnection(options?: {
13
+ url?: string;
14
+ key?: string;
15
+ home?: string;
16
+ }): ResolvedAdmin;
17
+ export declare class AdminClient {
18
+ readonly url: string;
19
+ readonly source: AdminSource;
20
+ private readonly key;
21
+ private compatible;
22
+ constructor(resolved: ResolvedAdmin);
23
+ private clearCompatibilityCache;
24
+ private adminHeaders;
25
+ private ensureCompatible;
26
+ private request;
27
+ private json;
28
+ status(): Promise<AdminStatus>;
29
+ listTenants(): Promise<AdminTenant[]>;
30
+ getTenant(id: string): Promise<AdminTenantStatus>;
31
+ deleteTenant(id: string, options?: {
32
+ activeWork?: "refuse" | "drain" | "cancel";
33
+ }): Promise<void>;
34
+ createTenant(options: {
35
+ name: string;
36
+ }): Promise<{
37
+ tenant: TenantEnvelope;
38
+ applicationKey: string;
39
+ }>;
40
+ }
package/dist/client.js ADDED
@@ -0,0 +1,346 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { AdminStatusSchema, AdminTenantSchema, AdminTenantStatusSchema, RejectedResponseSchema, TenantEnvelopeSchema, } from "@nylorun/core/contracts";
6
+ import { PROTOCOL_FEATURES, PROTOCOL_HEADER, PROTOCOL_VERSION, checkCompatibility, newPrincipalId, newTenantId, } from "@nylorun/core/compatibility";
7
+ import { AdminError } from "./errors.js";
8
+ function env(name) {
9
+ const value = process.env[name];
10
+ return value === undefined || value.trim() === "" ? undefined : value;
11
+ }
12
+ function resolveHome(home) {
13
+ if (home !== undefined && home.trim() !== "")
14
+ return resolve(home);
15
+ const fromEnv = env("NYLORUN_HOME");
16
+ if (fromEnv)
17
+ return resolve(fromEnv);
18
+ return resolve(join(homedir(), ".nylorun"));
19
+ }
20
+ function connectionMissing(message) {
21
+ throw new AdminError("connection_missing", message);
22
+ }
23
+ function sourcesTriedMessage(home) {
24
+ return (`Tried options (url + key), environment (NYLORUN_ADMIN_URL + NYLORUN_ADMIN_KEY), ` +
25
+ `and local Host settings (host.json + host-credentials.json under ${home}).`);
26
+ }
27
+ function assertCredentialsSafe(path) {
28
+ if (process.platform === "win32")
29
+ return;
30
+ let stats;
31
+ try {
32
+ stats = statSync(path);
33
+ }
34
+ catch {
35
+ return;
36
+ }
37
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
38
+ if (uid !== undefined && stats.uid !== uid) {
39
+ connectionMissing(`host-credentials.json at ${path} is not owned by the current user. ${sourcesTriedMessage(resolve(join(path, "..")))}`);
40
+ }
41
+ if ((stats.mode & 0o077) !== 0) {
42
+ connectionMissing(`host-credentials.json at ${path} is group- or world-readable; fix permissions (chmod 600). ${sourcesTriedMessage(resolve(join(path, "..")))}`);
43
+ }
44
+ }
45
+ function readLocalHost(home) {
46
+ const configPath = join(home, "host.json");
47
+ const credentialsPath = join(home, "host-credentials.json");
48
+ let config;
49
+ let credentials;
50
+ try {
51
+ config = JSON.parse(readFileSync(configPath, "utf8"));
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ try {
57
+ assertCredentialsSafe(credentialsPath);
58
+ credentials = JSON.parse(readFileSync(credentialsPath, "utf8"));
59
+ }
60
+ catch (error) {
61
+ if (error instanceof AdminError)
62
+ throw error;
63
+ return undefined;
64
+ }
65
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
66
+ return undefined;
67
+ }
68
+ if (!credentials ||
69
+ typeof credentials !== "object" ||
70
+ Array.isArray(credentials)) {
71
+ return undefined;
72
+ }
73
+ const host = config.host;
74
+ const port = config.port;
75
+ const adminKey = credentials.adminKey;
76
+ if (typeof host !== "string" || typeof port !== "number")
77
+ return undefined;
78
+ if (typeof adminKey !== "string" || !/^[0-9a-f]{64}$/.test(adminKey)) {
79
+ return undefined;
80
+ }
81
+ return { url: `http://${host}:${port}`, key: adminKey };
82
+ }
83
+ /**
84
+ * Resolve Admin API connection once: options → environment → local Host.
85
+ */
86
+ export function resolveAdminConnection(options) {
87
+ const home = resolveHome(options?.home);
88
+ const optionUrl = options?.url?.trim() || undefined;
89
+ const optionKey = options?.key?.trim() || undefined;
90
+ if (optionUrl || optionKey) {
91
+ if (!optionUrl || !optionKey) {
92
+ connectionMissing(`Incomplete Admin API options: both url and key are required. ${sourcesTriedMessage(home)}`);
93
+ }
94
+ return {
95
+ url: optionUrl.replace(/\/$/, ""),
96
+ key: optionKey,
97
+ source: "options",
98
+ home,
99
+ };
100
+ }
101
+ const envUrl = env("NYLORUN_ADMIN_URL");
102
+ const envKey = env("NYLORUN_ADMIN_KEY");
103
+ if (envUrl || envKey) {
104
+ if (!envUrl || !envKey) {
105
+ connectionMissing(`Incomplete Admin API environment: both NYLORUN_ADMIN_URL and NYLORUN_ADMIN_KEY are required. ${sourcesTriedMessage(home)}`);
106
+ }
107
+ return {
108
+ url: envUrl.replace(/\/$/, ""),
109
+ key: envKey,
110
+ source: "environment",
111
+ home,
112
+ };
113
+ }
114
+ const local = readLocalHost(home);
115
+ if (local) {
116
+ return {
117
+ url: local.url.replace(/\/$/, ""),
118
+ key: local.key,
119
+ source: "local-host",
120
+ home,
121
+ };
122
+ }
123
+ connectionMissing(`Could not resolve Admin API connection. ${sourcesTriedMessage(home)}`);
124
+ }
125
+ function parseProtocolRange(value) {
126
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
127
+ return undefined;
128
+ }
129
+ const record = value;
130
+ if (typeof record.min !== "number" ||
131
+ typeof record.max !== "number" ||
132
+ !Array.isArray(record.features) ||
133
+ !record.features.every((f) => typeof f === "string")) {
134
+ return undefined;
135
+ }
136
+ return {
137
+ min: record.min,
138
+ max: record.max,
139
+ features: record.features,
140
+ };
141
+ }
142
+ function hashCredential(token) {
143
+ return createHash("sha256").update(token, "utf8").digest("hex");
144
+ }
145
+ function mintApplicationKey() {
146
+ return randomBytes(32).toString("hex");
147
+ }
148
+ function throwFromResponse(status, body) {
149
+ const parsed = RejectedResponseSchema.safeParse(body);
150
+ if (parsed.success) {
151
+ throw new AdminError(parsed.data.code, parsed.data.message, {
152
+ status,
153
+ details: parsed.data.details,
154
+ });
155
+ }
156
+ if (status === 409) {
157
+ throw new AdminError("tenant_conflict", `Admin request conflict (${status})`, { status, details: body });
158
+ }
159
+ if (status === 404) {
160
+ throw new AdminError("not_found", `Admin request not found (${status})`, {
161
+ status,
162
+ details: body,
163
+ });
164
+ }
165
+ throw new AdminError("not_found", `Admin request failed (${status})`, {
166
+ status,
167
+ details: body,
168
+ });
169
+ }
170
+ async function readBody(response) {
171
+ const text = await response.text();
172
+ if (!text)
173
+ return undefined;
174
+ try {
175
+ return JSON.parse(text);
176
+ }
177
+ catch {
178
+ return text;
179
+ }
180
+ }
181
+ export class AdminClient {
182
+ url;
183
+ source;
184
+ key;
185
+ compatible = false;
186
+ constructor(resolved) {
187
+ this.url = resolved.url;
188
+ this.source = resolved.source;
189
+ this.key = resolved.key;
190
+ }
191
+ clearCompatibilityCache() {
192
+ this.compatible = false;
193
+ }
194
+ adminHeaders(init = {}) {
195
+ const headers = new Headers(init.headers);
196
+ headers.set("Authorization", `Bearer ${this.key}`);
197
+ headers.set(PROTOCOL_HEADER, String(PROTOCOL_VERSION));
198
+ headers.set("Accept", "application/json");
199
+ if (init.body)
200
+ headers.set("Content-Type", "application/json");
201
+ return headers;
202
+ }
203
+ async ensureCompatible(signal) {
204
+ if (this.compatible)
205
+ return;
206
+ const response = await fetch(`${this.url}/health`, {
207
+ method: "GET",
208
+ redirect: "error",
209
+ signal,
210
+ });
211
+ const body = await readBody(response);
212
+ if (!response.ok) {
213
+ throwFromResponse(response.status, body);
214
+ }
215
+ const protocol = parseProtocolRange(body && typeof body === "object" && !Array.isArray(body)
216
+ ? body.protocol
217
+ : undefined);
218
+ if (!protocol) {
219
+ throw new AdminError("incompatible_host", "Host /health did not advertise a protocol range.");
220
+ }
221
+ const result = checkCompatibility({ version: PROTOCOL_VERSION, required: [...PROTOCOL_FEATURES] }, protocol);
222
+ if (!result.ok) {
223
+ const detail = result.reason === "version"
224
+ ? `client protocol ${result.client} is outside Host range ${result.host.min}–${result.host.max}`
225
+ : `Host is missing required features: ${result.missing.join(", ")}`;
226
+ throw new AdminError("incompatible_host", `Incompatible Host: ${detail}`, { details: result });
227
+ }
228
+ this.compatible = true;
229
+ }
230
+ async request(path, init = {}, options = {}) {
231
+ await this.ensureCompatible(init.signal === null ? undefined : init.signal);
232
+ const response = await fetch(this.url + path, {
233
+ ...init,
234
+ headers: this.adminHeaders(init),
235
+ redirect: "error",
236
+ });
237
+ if (response.status === 426) {
238
+ this.clearCompatibilityCache();
239
+ if (!options.retried426) {
240
+ await this.ensureCompatible(init.signal === null ? undefined : init.signal);
241
+ return this.request(path, init, { retried426: true });
242
+ }
243
+ const body = await readBody(response);
244
+ const protocol = parseProtocolRange(body && typeof body === "object" && !Array.isArray(body)
245
+ ? body.protocol
246
+ : undefined);
247
+ if (protocol) {
248
+ const result = checkCompatibility({ version: PROTOCOL_VERSION, required: [...PROTOCOL_FEATURES] }, protocol);
249
+ if (!result.ok) {
250
+ throw new AdminError("incompatible_host", "Incompatible Host after protocol upgrade challenge.", { status: 426, details: result });
251
+ }
252
+ }
253
+ throwFromResponse(426, body);
254
+ }
255
+ return response;
256
+ }
257
+ async json(path, method = "GET", body) {
258
+ const response = await this.request(path, {
259
+ method,
260
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
261
+ signal: AbortSignal.timeout(15_000),
262
+ });
263
+ if (response.status === 204)
264
+ return undefined;
265
+ const parsed = await readBody(response);
266
+ if (!response.ok)
267
+ throwFromResponse(response.status, parsed);
268
+ return parsed;
269
+ }
270
+ async status() {
271
+ const body = await this.json("/v1/admin/status");
272
+ return AdminStatusSchema.parse(body);
273
+ }
274
+ async listTenants() {
275
+ const body = await this.json("/v1/admin/tenants");
276
+ if (!Array.isArray(body)) {
277
+ throw new AdminError("not_found", "Admin list tenants response was not an array.", { details: body });
278
+ }
279
+ return body.map((item) => AdminTenantSchema.parse(item));
280
+ }
281
+ async getTenant(id) {
282
+ const body = await this.json(`/v1/admin/tenants/${encodeURIComponent(id)}`);
283
+ return AdminTenantStatusSchema.parse(body);
284
+ }
285
+ async deleteTenant(id, options) {
286
+ const activeWork = options?.activeWork ?? "refuse";
287
+ await this.json(`/v1/admin/tenants/${encodeURIComponent(id)}?activeWork=${activeWork}`, "DELETE");
288
+ }
289
+ async createTenant(options) {
290
+ const applicationKey = mintApplicationKey();
291
+ const body = {
292
+ tenantId: newTenantId(),
293
+ name: options.name,
294
+ principalId: newPrincipalId(),
295
+ credentialHash: hashCredential(applicationKey),
296
+ idempotencyKey: randomUUID(),
297
+ };
298
+ let lastError;
299
+ for (let attempt = 0; attempt < 3; attempt += 1) {
300
+ let response;
301
+ try {
302
+ response = await this.request("/v1/admin/tenants", {
303
+ method: "POST",
304
+ body: JSON.stringify(body),
305
+ signal: AbortSignal.timeout(15_000),
306
+ });
307
+ }
308
+ catch (error) {
309
+ if (error instanceof AdminError)
310
+ throw error;
311
+ lastError = error;
312
+ if (attempt === 2) {
313
+ throw new AdminError("not_found", `Could not create Tenant after network errors: ${error instanceof Error ? error.message : String(error)}`, { details: error });
314
+ }
315
+ continue;
316
+ }
317
+ if (response.status === 409) {
318
+ const parsed = await readBody(response);
319
+ throw new AdminError("tenant_conflict", "Tenant id conflict.", {
320
+ status: 409,
321
+ details: parsed,
322
+ });
323
+ }
324
+ if (response.status >= 500) {
325
+ lastError = await readBody(response);
326
+ if (attempt === 2) {
327
+ throwFromResponse(response.status, lastError);
328
+ }
329
+ continue;
330
+ }
331
+ const parsed = await readBody(response);
332
+ if (response.status !== 201 && response.status !== 200) {
333
+ throwFromResponse(response.status, parsed);
334
+ }
335
+ return {
336
+ tenant: TenantEnvelopeSchema.parse(parsed),
337
+ applicationKey,
338
+ };
339
+ }
340
+ throw lastError instanceof AdminError
341
+ ? lastError
342
+ : new AdminError("not_found", "Could not create Tenant after retries.", {
343
+ details: lastError,
344
+ });
345
+ }
346
+ }
@@ -0,0 +1,10 @@
1
+ import type { ErrorCode } from "@nylorun/core/compatibility";
2
+ export declare class AdminError extends Error {
3
+ readonly code: ErrorCode;
4
+ readonly status?: number;
5
+ readonly details?: unknown;
6
+ constructor(code: ErrorCode, message: string, options?: {
7
+ status?: number;
8
+ details?: unknown;
9
+ });
10
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,12 @@
1
+ export class AdminError extends Error {
2
+ code;
3
+ status;
4
+ details;
5
+ constructor(code, message, options) {
6
+ super(message);
7
+ this.name = "AdminError";
8
+ this.code = code;
9
+ this.status = options?.status;
10
+ this.details = options?.details;
11
+ }
12
+ }
@@ -0,0 +1,28 @@
1
+ import type { AdminStatus, AdminTenant, AdminTenantStatus, TenantEnvelope } from "@nylorun/core/contracts";
2
+ import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, type ErrorCode } from "@nylorun/core/compatibility";
3
+ import { AdminError } from "./errors.js";
4
+ export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
5
+ export type { ErrorCode };
6
+ export { AdminError };
7
+ export interface Admin {
8
+ readonly url: string;
9
+ readonly source: "options" | "environment" | "local-host";
10
+ status(): Promise<AdminStatus>;
11
+ listTenants(): Promise<AdminTenant[]>;
12
+ getTenant(id: string): Promise<AdminTenantStatus>;
13
+ deleteTenant(id: string, options?: {
14
+ activeWork?: "refuse" | "drain" | "cancel";
15
+ }): Promise<void>;
16
+ createTenant(options: {
17
+ name: string;
18
+ }): Promise<{
19
+ tenant: TenantEnvelope;
20
+ applicationKey: string;
21
+ }>;
22
+ }
23
+ export declare function createAdmin(options?: {
24
+ url?: string;
25
+ key?: string;
26
+ home?: string;
27
+ }): Admin;
28
+ export type { AdminStatus, AdminTenant, AdminTenantStatus, TenantEnvelope };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import { ERROR_CODES, PROTOCOL_FEATURES, compareVersions, } from "@nylorun/core/compatibility";
2
+ import { AdminClient, resolveAdminConnection } from "./client.js";
3
+ import { AdminError } from "./errors.js";
4
+ export { ERROR_CODES, PROTOCOL_FEATURES, compareVersions };
5
+ export { AdminError };
6
+ export function createAdmin(options) {
7
+ return new AdminClient(resolveAdminConnection(options));
8
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@nylorun/admin",
3
+ "version": "0.2.0-beta",
4
+ "description": "Nylorun Admin API client for Tenants and Host status",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "files": [
8
+ "dist",
9
+ "README.md",
10
+ "LICENSE",
11
+ "CHANGELOG.md"
12
+ ],
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json",
22
+ "check": "npm run build && npm test && node scripts/check-package.mjs",
23
+ "test": "vitest run --passWithNoTests",
24
+ "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\""
25
+ },
26
+ "dependencies": {
27
+ "@nylorun/core": "0.5.0-beta"
28
+ },
29
+ "peerDependencies": {
30
+ "zod": "^4.6.5"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^24.0.0",
34
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
35
+ "vitest": "^5.0.1"
36
+ },
37
+ "engines": {
38
+ "node": ">=24"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/nylorun/harness.git",
43
+ "directory": "admin"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ }
49
+ }