@hivemagnus/magnus 1.1.4 → 1.1.7

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/dist/health.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Io } from './io.js';
2
+ import type { ProbeOptions } from './probe.js';
2
3
  import type { Project } from './project.js';
3
4
  export interface RuntimeInfo {
4
5
  version: string;
@@ -19,6 +20,11 @@ export declare function runtimeFiles(project: Project): string[];
19
20
  export declare function readRuntime(project: Project): RuntimeInfo | null;
20
21
  /** Loopback for wildcard binds, otherwise the address the server listens on. */
21
22
  export declare function probeHost(host: string | undefined): string;
23
+ /**
24
+ * The certificate a component serves, from its env file. Absent when the file
25
+ * or setting is missing or unreadable, which Io.probe handles.
26
+ */
27
+ export declare function probeOptions(project: Project, component: 'server' | 'ui'): ProbeOptions;
22
28
  export interface WaitOptions {
23
29
  version: string;
24
30
  /** The runtime file must name a process started after this instant. */
package/dist/health.js CHANGED
@@ -41,6 +41,22 @@ export function probeHost(host) {
41
41
  return '127.0.0.1';
42
42
  return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
43
43
  }
44
+ /**
45
+ * The certificate a component serves, from its env file. Absent when the file
46
+ * or setting is missing or unreadable, which Io.probe handles.
47
+ */
48
+ export function probeOptions(project, component) {
49
+ try {
50
+ const configured = readEnvFile(project.envFile(component))['TLS_CERT_PATH'];
51
+ if (!configured)
52
+ return {};
53
+ const pem = readFileSync(isAbsolute(configured) ? configured : project.path(configured), 'utf8');
54
+ return pem.includes('BEGIN CERTIFICATE') ? { ca: pem } : {};
55
+ }
56
+ catch {
57
+ return {};
58
+ }
59
+ }
44
60
  /**
45
61
  * Healthy means: the runtime file reports the expected version from a process
46
62
  * started after the restart, /api/v1/health answers 200, and the console (if
@@ -81,13 +97,13 @@ export async function waitForHealthy(io, project, options) {
81
97
  else if (runtime.version !== options.version)
82
98
  last = `serving ${runtime.version}, expected ${options.version}`;
83
99
  else {
84
- const server = await io.probe(`https://${probeHost(runtime.host)}:${runtime.port || project.state.ports.server}/api/v1/health`);
100
+ const server = await io.probe(`https://${probeHost(runtime.host)}:${runtime.port || project.state.ports.server}/api/v1/health`, probeOptions(project, 'server'));
85
101
  if (server !== 200)
86
102
  last = `/api/v1/health answered ${server ?? 'nothing'}`;
87
103
  else if (!project.state.components.includes('ui'))
88
104
  return { ok: true, detail: `server ${runtime.version} healthy` };
89
105
  else {
90
- const ui = await io.probe(`https://127.0.0.1:${project.state.ports.ui}/login`);
106
+ const ui = await io.probe(`https://127.0.0.1:${project.state.ports.ui}/login`, probeOptions(project, 'ui'));
91
107
  if (ui !== null && ui < 500)
92
108
  return { ok: true, detail: `server ${runtime.version} and console healthy` };
93
109
  last = `the console answered ${ui ?? 'nothing'}`;
package/dist/io.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type ProbeOptions } from './probe.js';
1
2
  export interface RunOptions {
2
3
  cwd?: string;
3
4
  env?: NodeJS.ProcessEnv;
@@ -33,7 +34,7 @@ export interface Io {
33
34
  * answers. Certificates are not verified: this only asks whether the local
34
35
  * process is up; the runtime file confirms which version it is.
35
36
  */
36
- probe(url: string): Promise<number | null>;
37
+ probe(url: string, options?: ProbeOptions): Promise<number | null>;
37
38
  /** Free bytes for an unprivileged writer on the file system holding `path`, or null when unknown. */
38
39
  freeBytes(path: string): number | null;
39
40
  env: NodeJS.ProcessEnv;
package/dist/io.js CHANGED
@@ -4,9 +4,8 @@
4
4
  */
5
5
  import { spawn } from 'node:child_process';
6
6
  import { statfsSync } from 'node:fs';
7
- import { request as httpRequest } from 'node:http';
8
- import { request as httpsRequest } from 'node:https';
9
7
  import { createInterface } from 'node:readline/promises';
8
+ import { probeStatus } from './probe.js';
10
9
  export class CommandError extends Error {
11
10
  result;
12
11
  constructor(message, result) {
@@ -46,17 +45,7 @@ export function systemIo() {
46
45
  rl.close();
47
46
  }
48
47
  },
49
- probe: (url) => new Promise((resolve) => {
50
- const target = new URL(url);
51
- const send = target.protocol === 'https:' ? httpsRequest : httpRequest;
52
- const req = send(target, { method: 'GET', timeout: 5_000, rejectUnauthorized: false }, (res) => {
53
- res.resume();
54
- resolve(res.statusCode ?? null);
55
- });
56
- req.on('timeout', () => req.destroy());
57
- req.on('error', () => resolve(null));
58
- req.end();
59
- }),
48
+ probe: (url, options) => probeStatus(url, options),
60
49
  freeBytes: (path) => {
61
50
  try {
62
51
  const stats = statfsSync(path);
@@ -0,0 +1,11 @@
1
+ export interface ProbeOptions {
2
+ /** PEM of the certificate the project's server or console is configured with. */
3
+ ca?: string;
4
+ }
5
+ export interface ProbeEnvironment {
6
+ isLocalAddress?: (host: string) => Promise<boolean>;
7
+ warn?: (line: string) => void;
8
+ }
9
+ export declare function isLoopbackAddress(address: string): boolean;
10
+ export declare function isLocalAddress(host: string): Promise<boolean>;
11
+ export declare function probeStatus(url: string, options?: ProbeOptions, environment?: ProbeEnvironment): Promise<number | null>;
package/dist/probe.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The health probe behind Io.probe. It only reads a status code and sends no
3
+ * credentials. Each project's server and console run on this machine, usually
4
+ * behind a self-signed certificate that does not name the address probed.
5
+ *
6
+ * With the project's certificate, the served certificate must chain to it. That
7
+ * pins the identity, so the hostname check is skipped: the certificate names the
8
+ * public host while the probe connects to a bind address.
9
+ *
10
+ * Verification is switched off only for an address that belongs to this machine
11
+ * (loopback or a local interface), where traffic stays in the kernel, and only
12
+ * when no certificate is known or the known one does not verify (say it renewed
13
+ * and the running server still serves the old one). Answering null there would
14
+ * read as "the port is closed" while waiting for a stop, and as "unhealthy" after
15
+ * a restart, rolling back a working upgrade. Any other address is always verified.
16
+ */
17
+ import { lookup } from 'node:dns/promises';
18
+ import { request as httpRequest } from 'node:http';
19
+ import { request as httpsRequest } from 'node:https';
20
+ import { isIP } from 'node:net';
21
+ import { networkInterfaces } from 'node:os';
22
+ export function isLoopbackAddress(address) {
23
+ const bare = address.replace(/^\[|\]$/g, '').toLowerCase();
24
+ const mapped = bare.startsWith('::ffff:') ? bare.slice(7) : bare;
25
+ return mapped === '::1' || mapped === 'localhost' || (isIP(mapped) === 4 && mapped.startsWith('127.'));
26
+ }
27
+ export async function isLocalAddress(host) {
28
+ const bare = host.replace(/^\[|\]$/g, '');
29
+ if (isLoopbackAddress(bare))
30
+ return true;
31
+ const local = new Set(Object.values(networkInterfaces()).flatMap((rows) => (rows ?? []).map((row) => row.address.toLowerCase())));
32
+ if (isIP(bare))
33
+ return local.has(bare.toLowerCase());
34
+ try {
35
+ const resolved = await lookup(bare, { all: true });
36
+ return resolved.length > 0 && resolved.every((row) => isLoopbackAddress(row.address) || local.has(row.address.toLowerCase()));
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ function isCertificateError(error) {
43
+ return /CERT|SELF_SIGNED|UNABLE_TO_(?:GET_ISSUER|VERIFY|DECRYPT)|INVALID_CA|INVALID_PURPOSE|PATH_LENGTH/.test(error.code ?? '');
44
+ }
45
+ function attempt(target, tls) {
46
+ return new Promise((resolve) => {
47
+ const send = target.protocol === 'https:' ? httpsRequest : httpRequest;
48
+ const failed = (error) => resolve({ status: null, certificateRejected: isCertificateError(error) });
49
+ try {
50
+ const req = send(target, { method: 'GET', timeout: 5_000, ...tls }, (res) => {
51
+ res.resume();
52
+ resolve(res.statusCode === undefined ? { status: null, certificateRejected: false } : { status: res.statusCode });
53
+ });
54
+ req.on('timeout', () => req.destroy());
55
+ req.on('error', failed);
56
+ req.end();
57
+ }
58
+ catch (error) {
59
+ // An unusable PEM throws while the request is created.
60
+ failed(Object.assign(error instanceof Error ? error : new Error(String(error)), { code: 'CERT_UNUSABLE' }));
61
+ }
62
+ });
63
+ }
64
+ let warned = false;
65
+ export async function probeStatus(url, options = {}, environment = {}) {
66
+ const target = new URL(url);
67
+ const verified = { rejectUnauthorized: true };
68
+ if (target.protocol === 'https:' && options.ca) {
69
+ Object.assign(verified, { ca: options.ca, allowPartialTrustChain: true, checkServerIdentity: () => undefined });
70
+ }
71
+ const first = await attempt(target, verified);
72
+ if (first.status !== null || !first.certificateRejected)
73
+ return first.status;
74
+ const local = await (environment.isLocalAddress ?? isLocalAddress)(target.hostname);
75
+ if (!local)
76
+ return null;
77
+ if (options.ca && !warned) {
78
+ warned = true;
79
+ (environment.warn ?? console.error)(`The certificate at ${target.host} does not match the project's TLS certificate; continuing with an unverified local status probe.`);
80
+ }
81
+ // Deliberately unverified, and only for an address on this machine: a credential-free liveness probe of the
82
+ // local service, of which only the HTTP status is read. Treating a rejected certificate as "down" would make
83
+ // a working install roll back or look stopped.
84
+ return (await attempt(target, { rejectUnauthorized: false })).status;
85
+ }
package/dist/release.d.ts CHANGED
@@ -39,6 +39,9 @@ export declare const TOO_OLD_HINT = "this engine is too old to read it; run the
39
39
  * configuration (.npmrc), then the public registry.
40
40
  */
41
41
  export declare function resolveRegistry(io: Io, explicit: string | undefined, npm?: () => Promise<string | null>): Promise<string>;
42
+ export declare function trimTrailingSlashes(url: string): string;
43
+ /** Encodes the scope's slash; the leading @ stays literal, as npm itself sends it and every registry proxy accepts it. */
44
+ export declare function registryPackagePath(name: string): string;
42
45
  export declare function fetchRegistryCatalog(io: Io, registry: string, packageName?: string): Promise<ReleaseCatalog>;
43
46
  /** npm pack names files `<scope>-<name>-<version>.tgz`. */
44
47
  export declare function tarballName(packageName: string, version: string): string;
package/dist/release.js CHANGED
@@ -47,8 +47,18 @@ async function npmConfigRegistry(io) {
47
47
  const value = result.code === 0 ? result.stdout.trim() : '';
48
48
  return /^https?:\/\//.test(value) ? value : null;
49
49
  }
50
+ export function trimTrailingSlashes(url) {
51
+ let end = url.length;
52
+ while (end > 0 && url[end - 1] === '/')
53
+ end -= 1;
54
+ return url.slice(0, end);
55
+ }
56
+ /** Encodes the scope's slash; the leading @ stays literal, as npm itself sends it and every registry proxy accepts it. */
57
+ export function registryPackagePath(name) {
58
+ return name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
59
+ }
50
60
  export async function fetchRegistryCatalog(io, registry, packageName = META_PACKAGE) {
51
- const url = `${registry.replace(/\/+$/, '')}/${packageName.replace('/', '%2f')}`;
61
+ const url = `${trimTrailingSlashes(registry)}/${registryPackagePath(packageName)}`;
52
62
  let response;
53
63
  try {
54
64
  // The full document: the abbreviated install format drops custom fields.
@@ -2,6 +2,7 @@
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { probeOptions } from './health.js';
5
6
  import { mustRun } from './io.js';
6
7
  import { writeAtomic } from './project.js';
7
8
  import { refreshUnit, UNIT_MARKER } from './templates.js';
@@ -103,7 +104,7 @@ export async function stopServices(io, project, options = {}) {
103
104
  io.log(`Stop the Magnus server and console now (the processes started from ${project.path('units')}/*.service). Waiting for port ${project.state.ports.server} to close…`);
104
105
  const deadline = io.now().getTime() + (options.timeoutMs ?? 300_000);
105
106
  for (;;) {
106
- const answer = await io.probe(`https://127.0.0.1:${project.state.ports.server}/api/v1/health`);
107
+ const answer = await io.probe(`https://127.0.0.1:${project.state.ports.server}/api/v1/health`, probeOptions(project, 'server'));
107
108
  if (answer === null)
108
109
  break;
109
110
  if (io.now().getTime() >= deadline)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/magnus",
3
- "version": "1.1.4",
3
+ "version": "1.1.7",
4
4
  "description": "Install, upgrade and roll back a Magnus server and console with one command: `npx @hivemagnus/magnus init`, then `magnus upgrade`. Pins exact, tested component versions, backs up PostgreSQL before every migration and reverts automatically when the new version fails its health check.",
5
5
  "keywords": [
6
6
  "magnus",
@@ -47,7 +47,7 @@
47
47
  "clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('tsconfig.tsbuildinfo',{force:true})\""
48
48
  },
49
49
  "dependencies": {
50
- "@hivemagnus/magnus-contracts": "1.1.4"
50
+ "@hivemagnus/magnus-contracts": "1.1.7"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^24.19.2",
@@ -56,15 +56,15 @@
56
56
  },
57
57
  "magnusRelease": {
58
58
  "schema": 1,
59
- "version": "1.1.4",
59
+ "version": "1.1.7",
60
60
  "engines": {
61
61
  "node": "^24.22.1 || ^26.13.0"
62
62
  },
63
63
  "components": {
64
- "@hivemagnus/magnus-server": "1.1.4",
65
- "@hivemagnus/magnus-ui": "1.1.4",
66
- "@hivemagnus/magnus-contracts": "1.1.4",
67
- "@hivemagnus/magnus-agent": "1.1.4"
64
+ "@hivemagnus/magnus-server": "1.1.7",
65
+ "@hivemagnus/magnus-ui": "1.1.7",
66
+ "@hivemagnus/magnus-contracts": "1.1.7",
67
+ "@hivemagnus/magnus-agent": "1.1.7"
68
68
  },
69
69
  "breaking": false,
70
70
  "minUpgradeFrom": "1.0.0",
@@ -77,8 +77,8 @@
77
77
  "selfUpgradeProtocol": 1,
78
78
  "minLauncher": 1
79
79
  },
80
- "summary": "Restore safety: the original schema is put back when pg_restore cannot be started after the swap, a schema left aside by an interrupted restore blocks a new restore, and a committed restore is not reported as failed when only the cleanup fails. No migrations and no new settings.",
81
- "notesUrl": "https://github.com/ChefTaco/magnus/releases/tag/v1.1.4",
80
+ "summary": "Hermes gateway status and install counts no longer over-report. Security hardening: no stored digest of password-bearing requests, rate limits and a per-peer task cap on the Ardent A2A surface, verified magnus health probes, no credential fingerprints in browser storage. No migrations and no new environment variables; behind a reverse proxy, set a2a.rate_limit.trusted_proxies in Ardent.",
81
+ "notesUrl": "https://github.com/ChefTaco/magnus/releases/tag/v1.1.7",
82
82
  "allowScripts": {
83
83
  "@prisma/engines": true,
84
84
  "argon2": true,