@zhin.js/gateway 1.1.2 → 1.2.0

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/lib/iam/rpc.js CHANGED
@@ -18,7 +18,7 @@ export async function dispatchIamRpc(message, service, principal) {
18
18
  const ok = (data) => ({ status: 200, body: { success: true, data, type, requestId } });
19
19
  try {
20
20
  if (!service?.ready)
21
- throw new IamError('unavailable', '当前数据库不能存储账号,或尚未就绪');
21
+ throw new IamError('unavailable', service?.publicUnavailable()?.message ?? 'Console 访问控制尚未就绪');
22
22
  const id = (key = 'id') => {
23
23
  const value = payload[key];
24
24
  if (typeof value !== 'string' || !value)
@@ -83,7 +83,24 @@ export interface ConsoleIamServiceOptions {
83
83
  * Without it, levels are inferred from the permission suffix.
84
84
  */
85
85
  readonly pluginPermissions?: () => readonly ConsolePluginPermissionInfo[];
86
+ /**
87
+ * Why access control is closed right now (gateway.db not open, the import of the old project
88
+ * database tables not finished, ADR 0059 §3), or undefined. While closed the service fails
89
+ * closed: {@link ConsoleIamService.initialized} is true (the bootstrap token is refused),
90
+ * nothing authenticates and `/auth/*` answers 503 — an empty store never reads as "no owner".
91
+ */
92
+ readonly unavailable?: () => string | undefined;
93
+ /**
94
+ * Category of `unavailable` (`starting`, `store`, `migration`, `store_lost`, …). Anonymous HTTP
95
+ * callers only ever see this code and a generic message; the detail (paths, driver messages)
96
+ * goes to the logs and to the local owner (`zhin doctor`, `zhin console migrate`).
97
+ */
98
+ readonly unavailableCode?: () => string | undefined;
99
+ /** Called after the first owner was created (the gateway then makes sure its store marker exists). */
100
+ readonly onOwnerCreated?: () => void;
86
101
  }
102
+ /** What anonymous callers learn while access control is closed (no paths or driver messages). */
103
+ export declare const IAM_UNAVAILABLE_PUBLIC_MESSAGE = "Console \u8BBF\u95EE\u63A7\u5236\u6682\u4E0D\u53EF\u7528\uFF1A\u8BF7\u5728\u670D\u52A1\u5668\u4E0A\u8FD0\u884C zhin doctor \u67E5\u770B\u539F\u56E0";
87
104
  /**
88
105
  * What is wrong with a new account's username / password, or null — the rules
89
106
  * {@link ConsoleIamService.createUser} / `createOwner` enforce, for callers that must check before
@@ -104,6 +121,13 @@ export declare class ConsoleIamService implements ConsoleAccessProvider {
104
121
  #private;
105
122
  constructor(options: ConsoleIamServiceOptions);
106
123
  get ready(): boolean;
124
+ /** See {@link ConsoleIamServiceOptions.unavailable} (detail: logs and the local owner only). */
125
+ unavailableReason(): string | undefined;
126
+ /** `{ code, message }` safe for any HTTP caller while closed, or undefined. */
127
+ publicUnavailable(): {
128
+ readonly code: string;
129
+ readonly message: string;
130
+ } | undefined;
107
131
  /** Seeds built-in roles and loads the owner state; call after the database started. */
108
132
  start(options?: Readonly<{
109
133
  timers?: boolean;
@@ -201,3 +225,10 @@ export declare class ConsoleIamService implements ConsoleAccessProvider {
201
225
  /** Daily: audit older than the retention window and expired sessions. */
202
226
  cleanup(): Promise<void>;
203
227
  }
228
+ /** Longest stored audit `detail` (characters of JSON). */
229
+ export declare const AUDIT_DETAIL_MAX_LENGTH = 4096;
230
+ /**
231
+ * Audit detail as JSON that always parses back: a detail longer than the column budget is
232
+ * replaced by `{ truncated, length, preview }` instead of being cut mid-string.
233
+ */
234
+ export declare function auditDetailJson(detail: unknown): string;
@@ -21,6 +21,8 @@ export class IamError extends Error {
21
21
  this.status = STATUS[code];
22
22
  }
23
23
  }
24
+ /** What anonymous callers learn while access control is closed (no paths or driver messages). */
25
+ export const IAM_UNAVAILABLE_PUBLIC_MESSAGE = 'Console 访问控制暂不可用:请在服务器上运行 zhin doctor 查看原因';
24
26
  const USERNAME = /^[a-z0-9][a-z0-9._-]{1,63}$/u;
25
27
  /**
26
28
  * What is wrong with a new account's username / password, or null — the rules
@@ -48,6 +50,9 @@ export class ConsoleIamService {
48
50
  #limiter;
49
51
  #onError;
50
52
  #pluginPermissions;
53
+ #unavailable;
54
+ #unavailableCode;
55
+ #onOwnerCreated;
51
56
  #ready = false;
52
57
  #initialized;
53
58
  #cleanupTimer;
@@ -64,9 +69,22 @@ export class ConsoleIamService {
64
69
  this.#limiter = options.rateLimiter ?? new LoginRateLimiter({ now: this.#now });
65
70
  this.#onError = options.onError ?? (() => undefined);
66
71
  this.#pluginPermissions = options.pluginPermissions ?? (() => []);
72
+ this.#unavailable = options.unavailable ?? (() => undefined);
73
+ this.#unavailableCode = options.unavailableCode ?? (() => undefined);
74
+ this.#onOwnerCreated = options.onOwnerCreated;
67
75
  }
68
76
  get ready() {
69
- return this.#ready;
77
+ return this.#ready && this.#unavailable() === undefined;
78
+ }
79
+ /** See {@link ConsoleIamServiceOptions.unavailable} (detail: logs and the local owner only). */
80
+ unavailableReason() {
81
+ return this.#unavailable();
82
+ }
83
+ /** `{ code, message }` safe for any HTTP caller while closed, or undefined. */
84
+ publicUnavailable() {
85
+ if (this.#unavailable() === undefined)
86
+ return undefined;
87
+ return Object.freeze({ code: this.#unavailableCode() ?? 'unavailable', message: IAM_UNAVAILABLE_PUBLIC_MESSAGE });
70
88
  }
71
89
  /** Seeds built-in roles and loads the owner state; call after the database started. */
72
90
  async start(options = {}) {
@@ -115,6 +133,8 @@ export class ConsoleIamService {
115
133
  clearInterval(this.#refreshTimer);
116
134
  }
117
135
  initialized() {
136
+ if (this.#unavailable() !== undefined)
137
+ return true;
118
138
  if (this.#initialized === true)
119
139
  return true;
120
140
  // Database not up yet, or another process (`zhin console init` beside a running gateway)
@@ -156,7 +176,7 @@ export class ConsoleIamService {
156
176
  }
157
177
  // ------------------------------------------------------------------ authentication
158
178
  async authenticate(token, meta = {}) {
159
- if (!this.#ready || !token || token.length > 256)
179
+ if (!this.ready || !token || token.length > 256)
160
180
  return null;
161
181
  const hash = sha256(token);
162
182
  const now = this.#now();
@@ -199,7 +219,7 @@ export class ConsoleIamService {
199
219
  action: entry.action.slice(0, 256),
200
220
  target: entry.target?.slice(0, 256) ?? null,
201
221
  outcome: entry.outcome,
202
- detail: entry.detail ? JSON.stringify(entry.detail).slice(0, 4096) : null,
222
+ detail: entry.detail ? auditDetailJson(entry.detail) : null,
203
223
  ip: entry.ip?.slice(0, 64) ?? null,
204
224
  }).catch(this.#onError);
205
225
  }
@@ -312,7 +332,14 @@ export class ConsoleIamService {
312
332
  this.#requireReady();
313
333
  if ((await this.#activeOwnerIds()).size > 0)
314
334
  throw new IamError('conflict', '已初始化:所有者已存在');
315
- return this.#createUser({ ...input, bindings: [{ role: 'owner', scopeKind: 'global' }] });
335
+ const owner = await this.#createUser({ ...input, bindings: [{ role: 'owner', scopeKind: 'global' }] });
336
+ try {
337
+ this.#onOwnerCreated?.();
338
+ }
339
+ catch (error) {
340
+ this.#onError(error);
341
+ }
342
+ return owner;
316
343
  });
317
344
  }
318
345
  /** Issues a session for a user (setup returns one for the new owner). */
@@ -782,3 +809,21 @@ function auditView(row) {
782
809
  ip: row.ip === null || row.ip === undefined ? null : String(row.ip),
783
810
  });
784
811
  }
812
+ /** Longest stored audit `detail` (characters of JSON). */
813
+ export const AUDIT_DETAIL_MAX_LENGTH = 4096;
814
+ /**
815
+ * Audit detail as JSON that always parses back: a detail longer than the column budget is
816
+ * replaced by `{ truncated, length, preview }` instead of being cut mid-string.
817
+ */
818
+ export function auditDetailJson(detail) {
819
+ const json = JSON.stringify(detail) ?? 'null';
820
+ if (json.length <= AUDIT_DETAIL_MAX_LENGTH)
821
+ return json;
822
+ let keep = AUDIT_DETAIL_MAX_LENGTH - 64;
823
+ for (;;) {
824
+ const replacement = JSON.stringify({ truncated: true, length: json.length, preview: json.slice(0, Math.max(0, keep)) });
825
+ if (replacement.length <= AUDIT_DETAIL_MAX_LENGTH || keep <= 0)
826
+ return replacement;
827
+ keep -= replacement.length - AUDIT_DETAIL_MAX_LENGTH;
828
+ }
829
+ }
@@ -55,6 +55,8 @@ export interface ConsoleSetupServiceOptions {
55
55
  readonly driverAvailable?: (dialect: SetupDialect) => Promise<boolean>;
56
56
  }
57
57
  export declare const SETUP_NO_MIGRATION_NOTICE = "\u5207\u6362\u6570\u636E\u5E93\u4E0D\u4F1A\u8FC1\u79FB\u65E7\u5E93\u6570\u636E\uFF1A\u63D2\u4EF6\u6570\u636E\u4ECD\u7559\u5728\u539F\u6570\u636E\u5E93\u3002";
58
+ /** PostgreSQL / MySQL: raw Console SQL needs the restricted account (ADR 0059 §4). */
59
+ export declare const SETUP_CONSOLE_ROLE_NOTICE = "PostgreSQL / MySQL \u4E0A Console \u7684\u539F\u59CB SQL \u53EA\u7528\u53D7\u9650\u8D26\u53F7\u6267\u884C\uFF1A\u8FD0\u884C zhin db console-role \u521B\u5EFA\uFF08\u65E0\u5EFA\u53F7\u6743\u9650\u65F6\u52A0 --print-sql \u4EA4\u7ED9 DBA\uFF09\u3002";
58
60
  /**
59
61
  * The one setup flow (ADR 0049 §7): `/auth/setup*` and `zhin console init` are thin wrappers.
60
62
  * Database changes are written to the config file / `.env`; restarting is the caller's job.
@@ -3,7 +3,6 @@ import { isDatabaseDriverAvailable, probeDatabaseConnection, } from '@zhin.js/da
3
3
  import { expandEnvironmentValue } from '@zhin.js/plugin-runtime';
4
4
  import { DATABASE_DIALECT_DEFINITIONS, validateDatabaseConfig, } from '@zhin.js/scaffold-wizard';
5
5
  import { IamError } from './service.js';
6
- import { IAM_DIALECTS } from './tables.js';
7
6
  const DEFAULT_SQLITE_FILE = '.zhin/data.sqlite';
8
7
  const SECRET_FIELDS = new Set(['password']);
9
8
  const ENV_REFERENCE = /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/u;
@@ -34,7 +33,14 @@ function fieldsOf(definition) {
34
33
  })];
35
34
  }));
36
35
  }
37
- const SETUP_DEFINITIONS = DATABASE_DIALECT_DEFINITIONS.filter(definition => IAM_DIALECTS.has(definition.dialect));
36
+ /**
37
+ * Dialects the wizard can test a connection for. Console accounts no longer depend on it: they
38
+ * live in `.zhin/gateway.db` (ADR 0059); a redis / memory project keeps its database block.
39
+ */
40
+ const SETUP_DIALECTS = new Set(['sqlite', 'mysql', 'pg', 'mongodb']);
41
+ const SETUP_DEFINITIONS = DATABASE_DIALECT_DEFINITIONS.filter(definition => SETUP_DIALECTS.has(definition.dialect));
42
+ /** PostgreSQL / MySQL: raw Console SQL needs the restricted account (ADR 0059 §4). */
43
+ export const SETUP_CONSOLE_ROLE_NOTICE = 'PostgreSQL / MySQL 上 Console 的原始 SQL 只用受限账号执行:运行 zhin db console-role 创建(无建号权限时加 --print-sql 交给 DBA)。';
38
44
  /**
39
45
  * The one setup flow (ADR 0049 §7): `/auth/setup*` and `zhin console init` are thin wrappers.
40
46
  * Database changes are written to the config file / `.env`; restarting is the caller's job.
@@ -96,12 +102,13 @@ export class ConsoleSetupService {
96
102
  await this.#options.envFile.write(upsertDotenv(await this.#options.envFile.read(), envUpdates));
97
103
  }
98
104
  await this.#options.config.setKey('database', block);
99
- return Object.freeze({ restartRequired: true, notice: SETUP_NO_MIGRATION_NOTICE });
105
+ const notice = prepared.dialect === 'pg' || prepared.dialect === 'mysql' ? `${SETUP_NO_MIGRATION_NOTICE}${SETUP_CONSOLE_ROLE_NOTICE}` : SETUP_NO_MIGRATION_NOTICE;
106
+ return Object.freeze({ restartRequired: true, notice });
100
107
  }
101
108
  async createOwner(input) {
102
109
  const iam = this.#options.iam();
103
110
  if (!iam?.ready)
104
- throw new IamError('unavailable', '当前数据库不能存储账号,或尚未就绪');
111
+ throw new IamError('unavailable', iam?.publicUnavailable()?.message ?? 'Console 访问控制尚未就绪');
105
112
  if (iam.initialized())
106
113
  throw new IamError('conflict', '已初始化:请改用 zhin console user 管理用户');
107
114
  return { user: await iam.createOwner(input) };
@@ -1,4 +1,7 @@
1
- /** Console access-control tables (ADR 0049 §2). Defined by the composition root before DB start. */
1
+ /**
2
+ * Console access-control tables (ADR 0049 §2). Since ADR 0059 they live in the gateway's own store
3
+ * `.zhin/gateway.db` (SQLite), whatever the project database is.
4
+ */
2
5
  export declare const IAM_TABLES: Readonly<{
3
6
  readonly users: "console_users";
4
7
  readonly roles: "console_roles";
@@ -8,13 +11,10 @@ export declare const IAM_TABLES: Readonly<{
8
11
  readonly audit: "console_audit_log";
9
12
  }>;
10
13
  export declare const IAM_TABLE_DEFINITIONS: Readonly<Record<string, Record<string, unknown>>>;
11
- /** Dialects that can hold accounts (redis / memory cannot, ADR 0049 §8). */
12
- export declare const IAM_DIALECTS: ReadonlySet<string>;
13
14
  export interface IamTableHost {
14
- readonly dialect: string;
15
15
  readonly started: boolean;
16
16
  define(name: string, definition: Record<string, unknown>): void;
17
17
  tables(): readonly string[];
18
18
  }
19
- /** Idempotent; must run before the database starts. Returns false for unsupported dialects. */
20
- export declare function defineConsoleIamTables(host: IamTableHost): boolean;
19
+ /** Idempotent; must run before the database starts. */
20
+ export declare function defineConsoleIamTables(host: IamTableHost): void;
package/lib/iam/tables.js CHANGED
@@ -1,4 +1,7 @@
1
- /** Console access-control tables (ADR 0049 §2). Defined by the composition root before DB start. */
1
+ /**
2
+ * Console access-control tables (ADR 0049 §2). Since ADR 0059 they live in the gateway's own store
3
+ * `.zhin/gateway.db` (SQLite), whatever the project database is.
4
+ */
2
5
  export const IAM_TABLES = Object.freeze({
3
6
  users: 'console_users',
4
7
  roles: 'console_roles',
@@ -65,18 +68,13 @@ export const IAM_TABLE_DEFINITIONS = Object.freeze({
65
68
  ip: text(true),
66
69
  },
67
70
  });
68
- /** Dialects that can hold accounts (redis / memory cannot, ADR 0049 §8). */
69
- export const IAM_DIALECTS = new Set(['sqlite', 'mysql', 'pg', 'mongodb']);
70
- /** Idempotent; must run before the database starts. Returns false for unsupported dialects. */
71
+ /** Idempotent; must run before the database starts. */
71
72
  export function defineConsoleIamTables(host) {
72
- if (!IAM_DIALECTS.has(host.dialect))
73
- return false;
74
73
  if (host.started)
75
- return true;
74
+ return;
76
75
  const existing = new Set(host.tables());
77
76
  for (const [name, definition] of Object.entries(IAM_TABLE_DEFINITIONS)) {
78
77
  if (!existing.has(name))
79
78
  host.define(name, definition);
80
79
  }
81
- return true;
82
80
  }
@@ -33,6 +33,12 @@ export declare const LOCAL_GATEWAY_RPC: Readonly<{
33
33
  readonly CONSOLE_USER_PASSWD: "gateway.console.user.passwd";
34
34
  /** `{ username, disabled }`. */
35
35
  readonly CONSOLE_USER_DISABLE: "gateway.console.user.disable";
36
+ /**
37
+ * `zhin console migrate` / `zhin doctor` beside a running gateway (ADR 0059 §3): the state of the
38
+ * import of the old `console_*` tables (`{ record, pending?, reappeared?, problem? }`), read by
39
+ * the gateway, the only process that opens `.zhin/gateway.db` while it runs.
40
+ */
41
+ readonly CONSOLE_MIGRATION_STATUS: "gateway.console.migration.status";
36
42
  /**
37
43
  * `{base}/…` request on behalf of the local owner ({@link LocalGatewayHttpRequest}): what
38
44
  * `zhin config` / `schedule` / `send` / `watch` use while a gateway runs, so they need no
@@ -39,6 +39,12 @@ export const LOCAL_GATEWAY_RPC = Object.freeze({
39
39
  CONSOLE_USER_PASSWD: 'gateway.console.user.passwd',
40
40
  /** `{ username, disabled }`. */
41
41
  CONSOLE_USER_DISABLE: 'gateway.console.user.disable',
42
+ /**
43
+ * `zhin console migrate` / `zhin doctor` beside a running gateway (ADR 0059 §3): the state of the
44
+ * import of the old `console_*` tables (`{ record, pending?, reappeared?, problem? }`), read by
45
+ * the gateway, the only process that opens `.zhin/gateway.db` while it runs.
46
+ */
47
+ CONSOLE_MIGRATION_STATUS: 'gateway.console.migration.status',
42
48
  /**
43
49
  * `{base}/…` request on behalf of the local owner ({@link LocalGatewayHttpRequest}): what
44
50
  * `zhin config` / `schedule` / `send` / `watch` use while a gateway runs, so they need no
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/gateway",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "Zhin.js management gateway: Console access control, terminal, project configuration and instance supervision (ADR 0054)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -72,13 +72,13 @@
72
72
  "fs-extra": "^11.4.0",
73
73
  "tsx": "^4.23.1",
74
74
  "yaml": "^2.9.0",
75
- "@zhin.js/console-protocol": "1.2.1",
76
- "@zhin.js/database": "1.1.8",
77
- "@zhin.js/host-http": "1.2.1",
75
+ "@zhin.js/console-protocol": "1.2.2",
76
+ "@zhin.js/database": "1.2.0",
77
+ "@zhin.js/host-http": "1.2.2",
78
78
  "@zhin.js/logger": "1.1.3",
79
- "@zhin.js/plugin-runtime": "1.2.0",
80
- "@zhin.js/runtime": "1.2.1",
81
- "@zhin.js/scaffold-wizard": "1.1.20"
79
+ "@zhin.js/plugin-runtime": "1.2.1",
80
+ "@zhin.js/runtime": "1.2.2",
81
+ "@zhin.js/scaffold-wizard": "1.1.21"
82
82
  },
83
83
  "optionalDependencies": {
84
84
  "node-pty": "^1.0.0",