@zhin.js/host-http 1.2.1 → 1.2.2

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.
@@ -122,6 +122,23 @@ export type ConsoleHttpDecision = Readonly<{
122
122
  export declare function authorizeConsoleHttp(principal: ConsolePrincipal | undefined, method: string, relativePath: string): ConsoleHttpDecision;
123
123
  /** WebSocket upgrade authorization for non-bootstrap principals. */
124
124
  export declare function authorizeConsoleWebSocket(principal: ConsolePrincipal, pathname: string): boolean;
125
- /** Audit detail for an RPC: type, target and parameter key names only. */
126
- export declare function rpcAuditDetail(message: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>>;
125
+ /**
126
+ * JSON length of the detail of one audit entry. The gateway stores at most 4096 characters of
127
+ * JSON detail; statements are cut so the whole detail stays below this budget once serialised
128
+ * (escapes such as `\n` count twice), so the stored detail always parses.
129
+ */
130
+ export declare const AUDIT_DETAIL_JSON_LIMIT = 3500;
131
+ export interface RpcAuditOptions {
132
+ /**
133
+ * Replaces literal values in SQL text (`'…'`) before it is recorded, with the dialect's own
134
+ * lexing (the database Host's `redactSql`). Without it no statement text is recorded at all.
135
+ */
136
+ readonly redactSql?: (sql: string) => string;
137
+ }
138
+ /**
139
+ * Audit detail for an RPC: type, target and parameter key names only — plus the statement text
140
+ * of Console database writes (pass the reply so the DDL a schema change ran is recorded), with
141
+ * literals redacted by `options.redactSql`.
142
+ */
143
+ export declare function rpcAuditDetail(message: Readonly<Record<string, unknown>>, reply?: Readonly<Record<string, unknown>>, options?: RpcAuditOptions): Readonly<Record<string, unknown>>;
127
144
  export declare function rpcAuditTarget(rule: ConsoleRpcPermissionRule | null): string | undefined;
@@ -128,13 +128,81 @@ export function authorizeConsoleWebSocket(principal, pathname) {
128
128
  return principal.open;
129
129
  return permission !== null && grantsAllow(principal.grants, permission);
130
130
  }
131
- /** Audit detail for an RPC: type, target and parameter key names only. */
132
- export function rpcAuditDetail(message) {
131
+ /**
132
+ * JSON length of the detail of one audit entry. The gateway stores at most 4096 characters of
133
+ * JSON detail; statements are cut so the whole detail stays below this budget once serialised
134
+ * (escapes such as `\n` count twice), so the stored detail always parses.
135
+ */
136
+ export const AUDIT_DETAIL_JSON_LIMIT = 3_500;
137
+ function statementTexts(message, reply) {
138
+ if (message.type === 'db:execute' || message.type === 'db:query')
139
+ return typeof message.sql === 'string' && message.sql ? [message.sql] : [];
140
+ const data = reply?.data && typeof reply.data === 'object' ? reply.data : undefined;
141
+ return (Array.isArray(data?.statements) ? data.statements : []).filter((entry) => typeof entry === 'string' && !!entry);
142
+ }
143
+ /**
144
+ * Statement text of Console SQL (`db:query` / `db:execute`, the DDL `db:schema:apply` ran or
145
+ * would have run), literals redacted; result rows are never recorded.
146
+ */
147
+ function databaseStatementDetail(message, reply, options) {
148
+ if (message.type !== 'db:execute' && message.type !== 'db:query' && message.type !== 'db:schema:apply')
149
+ return {};
150
+ const change = message.type === 'db:schema:apply' && message.change && typeof message.change === 'object' ? message.change : {};
151
+ const texts = statementTexts(message, reply);
152
+ const redact = options?.redactSql;
153
+ return {
154
+ ...(message.type === 'db:execute' && message.dryRun === true ? { dryRun: true } : {}),
155
+ ...(typeof change.kind === 'string' ? { change: change.kind.slice(0, 64) } : {}),
156
+ ...(typeof change.table === 'string' ? { table: change.table.slice(0, 256) } : {}),
157
+ ...(texts.length && redact
158
+ ? { statements: texts.map(text => { try {
159
+ return redact(text);
160
+ }
161
+ catch {
162
+ return '[unavailable]';
163
+ } }) }
164
+ : texts.length ? { statementLength: texts.reduce((total, text) => total + text.length, 0) } : {}),
165
+ };
166
+ }
167
+ /** Cuts the longest statement until the serialised detail fits {@link AUDIT_DETAIL_JSON_LIMIT}. */
168
+ function fitAuditDetail(detail) {
169
+ const statements = Array.isArray(detail.statements) ? [...detail.statements] : undefined;
170
+ if (!statements)
171
+ return detail;
172
+ let truncated = false;
173
+ for (;;) {
174
+ const candidate = { ...detail, statements, ...(truncated ? { truncated: true } : {}) };
175
+ const overflow = JSON.stringify(candidate).length - AUDIT_DETAIL_JSON_LIMIT;
176
+ if (overflow <= 0)
177
+ return { ...candidate, statements: Object.freeze(statements) };
178
+ truncated = true;
179
+ let longest = 0;
180
+ for (let index = 1; index < statements.length; index += 1)
181
+ if (statements[index].length > statements[longest].length)
182
+ longest = index;
183
+ const text = statements[longest];
184
+ if (text.length <= 1) {
185
+ statements.splice(longest, 1);
186
+ continue;
187
+ }
188
+ statements[longest] = `${text.slice(0, Math.max(0, text.length - overflow - 1))}…`;
189
+ }
190
+ }
191
+ /**
192
+ * Audit detail for an RPC: type, target and parameter key names only — plus the statement text
193
+ * of Console database writes (pass the reply so the DDL a schema change ran is recorded), with
194
+ * literals redacted by `options.redactSql`.
195
+ */
196
+ export function rpcAuditDetail(message, reply, options) {
133
197
  const data = message.data && typeof message.data === 'object' && !Array.isArray(message.data)
134
198
  ? Object.keys(message.data).sort()
135
199
  : [];
136
200
  const keys = Object.keys(message).filter(key => key !== 'type' && key !== 'requestId' && key !== 'data').sort();
137
- return Object.freeze({ type: String(message.type ?? ''), keys: Object.freeze([...new Set([...keys, ...data])]) });
201
+ return Object.freeze(fitAuditDetail({
202
+ type: String(message.type ?? '').slice(0, 256),
203
+ keys: Object.freeze([...new Set([...keys, ...data])].slice(0, 64).map(key => key.slice(0, 128))),
204
+ ...databaseStatementDetail(message, reply, options),
205
+ }));
138
206
  }
139
207
  export function rpcAuditTarget(rule) {
140
208
  if (!rule)
@@ -1,3 +1,4 @@
1
+ import type { ConsoleAdapterLoginDeclaration, ConsoleLoginFlow, ConsoleLoginOutcome } from '@zhin.js/console-protocol';
1
2
  interface LoginEndpointIdentity {
2
3
  readonly canonicalId: string;
3
4
  readonly instanceId: string;
@@ -20,27 +21,32 @@ export interface ConsoleRpcExtendedCtx {
20
21
  };
21
22
  /** Narrow generation-bound persistent-job port; null when Assistant is disabled. */
22
23
  resolveScheduleEngine?: () => ConsoleScheduleEngine | null | undefined;
23
- /** LoginAssist list/submit/cancel(刷新后仍可消费扫码/滑块待办)。 */
24
- loginAssist?: {
25
- listPending(): readonly {
26
- id: string;
27
- adapter: string;
28
- endpointKey: string;
29
- endpointIdentity?: LoginEndpointIdentity;
30
- type: string;
31
- payload: Record<string, unknown>;
32
- createdAt: number;
33
- expiresAt?: number;
34
- }[];
35
- submit(id: string, value: string | Record<string, unknown>, endpointIdentity?: LoginEndpointIdentity): boolean;
36
- cancel(id: string, reason?: string, endpointIdentity?: LoginEndpointIdentity): boolean;
37
- };
24
+ /** LoginAssist list/submit/cancel(刷新后仍可消费扫码/滑块待办);ADR 0058 flow methods are optional. */
25
+ loginAssist?: ConsoleLoginAssistPort;
26
+ /** ADR 0058: the Endpoint's login declaration and lease-scoped login control (`null` = unknown Endpoint). */
27
+ withEndpointLogin?: <T>(adapter: string, endpointKey: string, run: (login: ConsoleEndpointLoginAccess) => T | Promise<T>) => Promise<T | null>;
38
28
  /** Authenticated Root adapter; mutation DTOs deliberately contain no principal/decision fields. */
39
29
  workroomProfileControl?: ConsoleWorkroomProfileControlPort;
40
30
  /** Authenticated HTTP principal; never accepted from the RPC body. */
41
31
  authenticatedPrincipal?: Readonly<{
42
32
  principalId: string;
43
33
  }>;
34
+ /**
35
+ * The Endpoint the caller was authorized for when its grant covers this call only at an adapter /
36
+ * endpoint scope (never set for global grants, owners or in-process callers). Handlers that act on
37
+ * login tasks or flows restrict themselves to it; set by the dispatcher, never read from the body.
38
+ */
39
+ authorizedEndpoint?: Readonly<{
40
+ adapter: string;
41
+ endpointKey: string;
42
+ }>;
43
+ /**
44
+ * Whether the caller holds `endpoint.operate` on one Endpoint (set by the dispatcher from the
45
+ * authenticated principal, never read from the body). Login read RPCs return live challenge
46
+ * material (QR image, sensitive blocks, verification links, legacy `payload.image` / `url`) only
47
+ * when it says yes; absent (in-process callers without a principal) = trusted.
48
+ */
49
+ canOperateEndpoint?: (adapter: string, endpointKey: string) => boolean;
44
50
  workroomKnowledgeControl?: ConsoleWorkroomKnowledgeControlPort;
45
51
  }
46
52
  export interface ConsoleWorkroomProfileControlPort {
@@ -118,11 +124,60 @@ export interface ConsoleScheduleEngine {
118
124
  resumeJob(id: string): Promise<boolean>;
119
125
  listJobs(): Promise<Record<string, unknown>[]>;
120
126
  }
127
+ /** `data` next to `error` carries a machine-readable code (e.g. `{ code: 'unsupported' }`). */
121
128
  export type ExtendedRpcResult = {
122
129
  data: unknown;
123
130
  } | {
124
131
  error: string;
132
+ data?: unknown;
125
133
  };
134
+ /** Structural LoginAssist port (host/http must not import `@zhin.js/core`). */
135
+ export interface ConsoleLoginAssistPort {
136
+ listPending(): readonly {
137
+ id: string;
138
+ adapter: string;
139
+ endpointKey: string;
140
+ endpointIdentity?: LoginEndpointIdentity;
141
+ type: string;
142
+ payload: Record<string, unknown>;
143
+ createdAt: number;
144
+ expiresAt?: number;
145
+ flowId?: string;
146
+ challengeId?: string;
147
+ }[];
148
+ submit(id: string, value: string | Record<string, unknown>, endpointIdentity?: LoginEndpointIdentity): boolean;
149
+ cancel(id: string, reason?: string, endpointIdentity?: LoginEndpointIdentity): boolean;
150
+ /** ADR 0058 */
151
+ listFlows?(): readonly ConsoleLoginFlow[];
152
+ getFlow?(adapter: string, endpointKey: string): ConsoleLoginFlow | undefined;
153
+ getFlowById?(id: string): ConsoleLoginFlow | undefined;
154
+ /**
155
+ * Event-safe copy of a flow (core `withoutLoginMedia`): no QR image, sensitive blocks redacted,
156
+ * verification links dropped. Returned to readers without `endpoint.operate` on the flow's
157
+ * Endpoint; without it the host strips every challenge's media and blocks.
158
+ */
159
+ eventSafeFlow?(flow: ConsoleLoginFlow): ConsoleLoginFlow;
160
+ submitAndWait?(id: string, value: string | Record<string, unknown>, options?: {
161
+ endpointIdentity?: LoginEndpointIdentity;
162
+ timeoutMs?: number;
163
+ }): Promise<{
164
+ accepted: boolean;
165
+ outcome?: ConsoleLoginOutcome;
166
+ pending?: boolean;
167
+ flow?: ConsoleLoginFlow;
168
+ }>;
169
+ }
170
+ export interface ConsoleEndpointLoginAccess {
171
+ readonly declaration?: ConsoleAdapterLoginDeclaration;
172
+ readonly control?: {
173
+ relogin?(request: {
174
+ signal?: AbortSignal;
175
+ }): Promise<void>;
176
+ refreshChallenge?(request: {
177
+ signal?: AbortSignal;
178
+ }): Promise<void>;
179
+ };
180
+ }
126
181
  export interface ScheduleJobRow {
127
182
  id: string;
128
183
  cron: string;
@@ -1,6 +1,6 @@
1
1
  import { addCron, listSchedule, mutateCron, validateCron } from './schedule-rpc.js';
2
2
  import { actOnRequest, listInbox, listInboxMessages, listPendingRequests, listRecentInboxMessages, mapNoticeRow, mapRequestRow, markInboxConsumed, TABLE_NOTICE, TABLE_REQUEST, } from './inbox-rpc.js';
3
- import { cancelLogin, listLoginPending, submitLogin } from './login-rpc.js';
3
+ import { cancelLogin, controlLogin, getLoginFlow, listLoginFlows, listLoginPending, submitLogin } from './login-rpc.js';
4
4
  import { deleteFriend, groupWriteOp, listChannels, listFriends, listGroupMembers, listGroups, } from './endpoint-rpc.js';
5
5
  import { mutateWorkroomKnowledge, mutateWorkroomProfile } from './workroom-rpc.js';
6
6
  export async function dispatchExtendedConsoleRpc(type, data, ctx) {
@@ -32,11 +32,18 @@ export async function dispatchExtendedConsoleRpc(type, data, ctx) {
32
32
  case 'request.reject':
33
33
  return actOnRequest(type, d, ctx);
34
34
  case 'login.list':
35
- return listLoginPending(ctx);
35
+ return listLoginPending(d, ctx);
36
36
  case 'login.submit':
37
37
  return submitLogin(d, ctx);
38
38
  case 'login.cancel':
39
39
  return cancelLogin(d, ctx);
40
+ case 'login.flow.list':
41
+ return listLoginFlows(d, ctx);
42
+ case 'login.flow.get':
43
+ return getLoginFlow(d, ctx);
44
+ case 'login.relogin':
45
+ case 'login.refresh':
46
+ return controlLogin(type, d, ctx);
40
47
  case 'request.consumed':
41
48
  return markInboxConsumed(d, ctx, TABLE_REQUEST);
42
49
  case 'notice.consumed':
@@ -1,2 +1,3 @@
1
- export type { ConsoleRpcExtendedCtx, ConsoleScheduleEngine, ConsoleWorkroomKnowledgeControlPort, ConsoleWorkroomProfileControlPort, ExtendedRpcResult, } from './contracts.js';
1
+ export type { ConsoleRpcExtendedCtx, ConsoleScheduleEngine, ConsoleWorkroomKnowledgeControlPort, ConsoleWorkroomProfileControlPort, ExtendedRpcResult, ConsoleLoginAssistPort, ConsoleEndpointLoginAccess, } from './contracts.js';
2
+ export { loginAuditDetail, LOGIN_SUBMIT_WAIT_MS } from './login-rpc.js';
2
3
  export { dispatchExtendedConsoleRpc } from './dispatcher.js';
@@ -1 +1,2 @@
1
+ export { loginAuditDetail, LOGIN_SUBMIT_WAIT_MS } from './login-rpc.js';
1
2
  export { dispatchExtendedConsoleRpc } from './dispatcher.js';
@@ -1,4 +1,27 @@
1
+ import { LOGIN_RPC } from '@zhin.js/console-protocol';
1
2
  import type { ConsoleRpcExtendedCtx, ExtendedRpcResult } from './contracts.js';
2
- export declare function listLoginPending(ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
3
- export declare function submitLogin(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
3
+ /** `login.submit` with `wait: true` waits at most this long for the login result. */
4
+ export declare const LOGIN_SUBMIT_WAIT_MS = 15000;
5
+ export declare function listLoginPending(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
6
+ /**
7
+ * `login.submit { taskId, value, endpointIdentity?, adapter?, endpointKey?, wait? }`.
8
+ * `value` is a string (legacy) or `{ action, values }`. With `wait: true` the reply carries the login
9
+ * result (`{ accepted, outcome, flow }`) or `{ accepted, pending: true }` after 15 s; without it the
10
+ * legacy `{ success: true }` reply is unchanged.
11
+ */
12
+ export declare function submitLogin(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): Promise<ExtendedRpcResult>;
4
13
  export declare function cancelLogin(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
14
+ /**
15
+ * `login.flow.list { adapter?, endpointKey? }`: latest flow per Endpoint. Live challenge material
16
+ * only for Endpoints the caller may operate; the event-safe form otherwise (ADR 0058 §8).
17
+ */
18
+ export declare function listLoginFlows(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
19
+ /** `login.flow.get { flowId } | { adapter, endpointKey }` → `{ flow: … | null }`. */
20
+ export declare function getLoginFlow(d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): ExtendedRpcResult;
21
+ /** `login.relogin` / `login.refresh { adapter, endpointKey }` through the Endpoint's login port. */
22
+ export declare function controlLogin(type: typeof LOGIN_RPC.RELOGIN | typeof LOGIN_RPC.REFRESH, d: Record<string, unknown>, ctx: ConsoleRpcExtendedCtx): Promise<ExtendedRpcResult>;
23
+ /**
24
+ * Audit detail of a login RPC reply: the result category only (never values, never messages).
25
+ * `undefined` for other RPCs.
26
+ */
27
+ export declare function loginAuditDetail(type: unknown, data: unknown): Readonly<Record<string, string>> | undefined;
@@ -1,43 +1,80 @@
1
+ import { CONSOLE_LOGIN_UNSUPPORTED, LOGIN_RPC } from '@zhin.js/console-protocol';
1
2
  import { strField } from './rpc-values.js';
2
- export function listLoginPending(ctx) {
3
+ const NOT_WIRED = '登录辅助未接线(LoginAssist 未挂载)';
4
+ /** `login.submit` with `wait: true` waits at most this long for the login result. */
5
+ export const LOGIN_SUBMIT_WAIT_MS = 15_000;
6
+ export function listLoginPending(d, ctx) {
3
7
  const assist = ctx.loginAssist;
4
8
  if (!assist)
5
- return { error: '登录辅助未接线(LoginAssist 未挂载)' };
6
- const tasks = assist.listPending().map((task) => ({
9
+ return { error: NOT_WIRED };
10
+ const scope = loginScope(d, ctx);
11
+ if ('error' in scope)
12
+ return scope;
13
+ const tasks = assist.listPending().filter((task) => inScope(scope, task)).map((task) => ({
7
14
  id: task.id,
8
15
  adapter: task.adapter,
9
16
  endpointKey: task.endpointKey,
10
17
  ...(task.endpointIdentity ? { endpointIdentity: task.endpointIdentity } : {}),
11
18
  type: task.type,
12
- payload: task.payload,
19
+ payload: canOperate(ctx, task) ? task.payload : eventSafeLoginPayload(task.payload),
13
20
  createdAt: task.createdAt,
14
21
  expiresAt: task.expiresAt,
22
+ ...(task.flowId ? { flowId: task.flowId } : {}),
23
+ ...(task.challengeId ? { challengeId: task.challengeId } : {}),
15
24
  }));
16
25
  return { data: { tasks, count: tasks.length } };
17
26
  }
18
- export function submitLogin(d, ctx) {
27
+ /**
28
+ * `login.submit { taskId, value, endpointIdentity?, adapter?, endpointKey?, wait? }`.
29
+ * `value` is a string (legacy) or `{ action, values }`. With `wait: true` the reply carries the login
30
+ * result (`{ accepted, outcome, flow }`) or `{ accepted, pending: true }` after 15 s; without it the
31
+ * legacy `{ success: true }` reply is unchanged.
32
+ */
33
+ export async function submitLogin(d, ctx) {
19
34
  const assist = ctx.loginAssist;
20
35
  if (!assist)
21
- return { error: '登录辅助未接线(LoginAssist 未挂载)' };
36
+ return { error: NOT_WIRED };
22
37
  const id = strField(d, 'taskId');
23
38
  if (!id)
24
39
  return { error: 'taskId is required' };
25
- const raw = d.value ?? '';
26
- const value = typeof raw === 'string' || (raw && typeof raw === 'object')
27
- ? raw
28
- : String(raw ?? '');
40
+ const value = readSubmitValue(d.value);
41
+ if (value === false)
42
+ return { error: 'value must be a string or { action, values }' };
29
43
  const identity = readEndpointIdentity(d.endpointIdentity);
30
44
  if (identity === false)
31
45
  return { error: 'Invalid login Endpoint identity' };
32
- const ok = identity ? assist.submit(id, value, identity) : assist.submit(id, value);
33
- if (!ok)
34
- return { error: `login task not found: ${id}` };
35
- return { data: { success: true } };
46
+ const target = checkTaskTarget(d, ctx, id);
47
+ if (target)
48
+ return target;
49
+ try {
50
+ if (d.wait === true && assist.submitAndWait) {
51
+ const result = await assist.submitAndWait(id, value, {
52
+ ...(identity ? { endpointIdentity: identity } : {}),
53
+ timeoutMs: LOGIN_SUBMIT_WAIT_MS,
54
+ });
55
+ if (!result.accepted)
56
+ return { error: `login task not found: ${id}` };
57
+ if (result.outcome)
58
+ return { data: { accepted: true, outcome: result.outcome, ...(result.flow ? { flow: result.flow } : {}) } };
59
+ return { data: { accepted: true, pending: true, ...(result.flow ? { flow: result.flow } : {}) } };
60
+ }
61
+ const ok = identity ? assist.submit(id, value, identity) : assist.submit(id, value);
62
+ if (!ok)
63
+ return { error: `login task not found: ${id}` };
64
+ return { data: { success: true } };
65
+ }
66
+ catch (error) {
67
+ // LoginSubmissionError: the challenge stays open; its message never contains the value.
68
+ if (error instanceof Error && error.name === 'LoginSubmissionError') {
69
+ return { error: error.message, data: { code: error.code ?? 'input_invalid' } };
70
+ }
71
+ throw error;
72
+ }
36
73
  }
37
74
  export function cancelLogin(d, ctx) {
38
75
  const assist = ctx.loginAssist;
39
76
  if (!assist)
40
- return { error: '登录辅助未接线(LoginAssist 未挂载)' };
77
+ return { error: NOT_WIRED };
41
78
  const id = strField(d, 'taskId');
42
79
  if (!id)
43
80
  return { error: 'taskId is required' };
@@ -45,12 +82,235 @@ export function cancelLogin(d, ctx) {
45
82
  const identity = readEndpointIdentity(d.endpointIdentity);
46
83
  if (identity === false)
47
84
  return { error: 'Invalid login Endpoint identity' };
85
+ const target = checkTaskTarget(d, ctx, id);
86
+ if (target)
87
+ return target;
48
88
  const ok = identity ? assist.cancel(id, reason, identity) : assist.cancel(id, reason);
49
89
  if (!ok)
50
90
  return { error: `login task not found: ${id}` };
51
91
  return { data: { success: true } };
52
92
  }
53
- // ---------------------------------------------------------------- 社交读取
93
+ /**
94
+ * `login.flow.list { adapter?, endpointKey? }`: latest flow per Endpoint. Live challenge material
95
+ * only for Endpoints the caller may operate; the event-safe form otherwise (ADR 0058 §8).
96
+ */
97
+ export function listLoginFlows(d, ctx) {
98
+ const assist = ctx.loginAssist;
99
+ if (!assist)
100
+ return { error: NOT_WIRED };
101
+ if (!assist.listFlows)
102
+ return unsupported('login flows');
103
+ const scope = loginScope(d, ctx);
104
+ if ('error' in scope)
105
+ return scope;
106
+ const flows = assist.listFlows().filter((flow) => inScope(scope, flow)).map((flow) => visibleFlow(assist, ctx, flow));
107
+ return { data: { flows, count: flows.length } };
108
+ }
109
+ /** `login.flow.get { flowId } | { adapter, endpointKey }` → `{ flow: … | null }`. */
110
+ export function getLoginFlow(d, ctx) {
111
+ const assist = ctx.loginAssist;
112
+ if (!assist)
113
+ return { error: NOT_WIRED };
114
+ if (!assist.getFlow || !assist.getFlowById)
115
+ return unsupported('login flows');
116
+ const flowId = strField(d, 'flowId');
117
+ const scope = loginScope(d, ctx);
118
+ if ('error' in scope)
119
+ return scope;
120
+ if (flowId) {
121
+ const flow = assist.getFlowById(flowId);
122
+ // A flow id names one Endpoint; a scoped caller cannot read another Endpoint's flow by id.
123
+ return { data: { flow: flow && inScope(scope, flow) ? visibleFlow(assist, ctx, flow) : null } };
124
+ }
125
+ if (!scope.adapter || !scope.endpointKey)
126
+ return { error: 'flowId or adapter and endpointKey are required' };
127
+ const flow = assist.getFlow(scope.adapter, scope.endpointKey);
128
+ return { data: { flow: flow ? visibleFlow(assist, ctx, flow) : null } };
129
+ }
130
+ /** `login.relogin` / `login.refresh { adapter, endpointKey }` through the Endpoint's login port. */
131
+ export async function controlLogin(type, d, ctx) {
132
+ const scope = loginScope(d, ctx);
133
+ if ('error' in scope)
134
+ return scope;
135
+ const { adapter, endpointKey } = scope;
136
+ if (!adapter || !endpointKey)
137
+ return { error: 'adapter and endpointKey are required' };
138
+ const relogin = type === LOGIN_RPC.RELOGIN;
139
+ const label = relogin ? 'relogin' : 'refresh challenge';
140
+ if (!ctx.withEndpointLogin)
141
+ return unsupported(label);
142
+ const result = await ctx.withEndpointLogin(adapter, endpointKey, async (login) => {
143
+ const declared = relogin ? login.declaration?.relogin === true : login.declaration?.refreshQr === true;
144
+ const run = relogin ? login.control?.relogin : login.control?.refreshChallenge;
145
+ if (!declared || !run)
146
+ return unsupported(label, adapter);
147
+ await run.call(login.control, {});
148
+ return { data: { accepted: true } };
149
+ });
150
+ return result ?? { error: `Endpoint not found: ${adapter}/${endpointKey}` };
151
+ }
152
+ /**
153
+ * Audit detail of a login RPC reply: the result category only (never values, never messages).
154
+ * `undefined` for other RPCs.
155
+ */
156
+ export function loginAuditDetail(type, data) {
157
+ if (type !== LOGIN_RPC.SUBMIT && type !== LOGIN_RPC.CANCEL && type !== LOGIN_RPC.RELOGIN && type !== LOGIN_RPC.REFRESH)
158
+ return undefined;
159
+ if (!data || typeof data !== 'object')
160
+ return undefined;
161
+ const record = data;
162
+ if (typeof record.code === 'string')
163
+ return Object.freeze({ result: record.code });
164
+ if (record.outcome && typeof record.outcome.result === 'string') {
165
+ return Object.freeze({ result: record.outcome.result, ...(typeof record.outcome.code === 'string' ? { code: record.outcome.code } : {}) });
166
+ }
167
+ if (record.pending === true)
168
+ return Object.freeze({ result: 'pending' });
169
+ if (record.accepted === true || record.success === true)
170
+ return Object.freeze({ result: 'accepted' });
171
+ return undefined;
172
+ }
173
+ // ---------------------------------------------------------------- helpers
174
+ function unsupported(what, adapter) {
175
+ return {
176
+ error: `${CONSOLE_LOGIN_UNSUPPORTED}: ${adapter ? `${adapter} does not support ${what}` : `${what} not available on this host`}`,
177
+ data: { code: CONSOLE_LOGIN_UNSUPPORTED },
178
+ };
179
+ }
180
+ /**
181
+ * The Endpoint a login RPC is about: `adapter` / `endpointKey` read from `data` and the top level,
182
+ * exactly the fields the authorization map reads (ADR 0049). Sources that disagree, or a value that
183
+ * is not a string, are rejected. When the dispatcher admitted the caller only through an adapter /
184
+ * endpoint-scoped grant (`ctx.authorizedEndpoint`), the scope is that Endpoint and any other named
185
+ * target is rejected; global callers may omit it (`''` = no filter).
186
+ */
187
+ function loginScope(d, ctx) {
188
+ const sources = d.data && typeof d.data === 'object' && !Array.isArray(d.data)
189
+ ? [d.data, d]
190
+ : [d];
191
+ const read = (key) => {
192
+ let found = '';
193
+ for (const source of sources) {
194
+ const value = source[key];
195
+ if (value === undefined || value === null || value === '')
196
+ continue;
197
+ if (typeof value !== 'string')
198
+ return false;
199
+ const text = value.trim();
200
+ if (!text)
201
+ continue;
202
+ if (found && found !== text)
203
+ return false;
204
+ found = text;
205
+ }
206
+ return found;
207
+ };
208
+ const adapter = read('adapter');
209
+ const endpointKey = read('endpointKey');
210
+ if (adapter === false || endpointKey === false)
211
+ return { error: 'Conflicting login target (adapter / endpointKey)' };
212
+ const authorized = ctx.authorizedEndpoint;
213
+ if (!authorized)
214
+ return { adapter, endpointKey };
215
+ if ((adapter && adapter !== authorized.adapter) || (endpointKey && endpointKey !== authorized.endpointKey)) {
216
+ return { error: 'Login target outside the authorized Endpoint' };
217
+ }
218
+ return { adapter: authorized.adapter, endpointKey: authorized.endpointKey };
219
+ }
220
+ /** The caller may handle this Endpoint's challenge (`endpoint.operate` there); no principal = trusted. */
221
+ function canOperate(ctx, item) {
222
+ return ctx.canOperateEndpoint ? ctx.canOperateEndpoint(item.adapter, item.endpointKey) : true;
223
+ }
224
+ /**
225
+ * A flow as this caller may see it: live for operators, otherwise the event-safe form (no QR image,
226
+ * sensitive blocks redacted, verification links dropped). A port without `eventSafeFlow` falls back
227
+ * to removing every challenge's media and blocks.
228
+ */
229
+ function visibleFlow(assist, ctx, flow) {
230
+ if (canOperate(ctx, flow))
231
+ return flow;
232
+ return assist.eventSafeFlow ? assist.eventSafeFlow(flow) : withoutChallengeMaterial(flow);
233
+ }
234
+ function withoutChallengeMaterial(flow) {
235
+ if (!flow.steps.some((step) => step.challenge?.media || step.challenge?.blocks))
236
+ return flow;
237
+ return Object.freeze({
238
+ ...flow,
239
+ steps: Object.freeze(flow.steps.map((step) => {
240
+ if (!step.challenge || (!step.challenge.media && !step.challenge.blocks))
241
+ return step;
242
+ const { media, blocks: _blocks, ...challenge } = step.challenge;
243
+ return Object.freeze({
244
+ ...step,
245
+ challenge: Object.freeze({
246
+ ...challenge,
247
+ media: Object.freeze({
248
+ ...(media?.expiresAt !== undefined ? { expiresAt: media.expiresAt } : {}),
249
+ ...(media?.refreshable !== undefined ? { refreshable: media.refreshable } : {}),
250
+ ...(media?.qrImage ? { qrImageOmitted: true } : {}),
251
+ ...(media?.link || media?.captcha ? { linkOmitted: true } : {}),
252
+ }),
253
+ }),
254
+ });
255
+ })),
256
+ });
257
+ }
258
+ /**
259
+ * Legacy task payload without the QR image (`image`) and verification link (`url`, may carry a
260
+ * session id), marked `imageOmitted` / `urlOmitted` like the `endpoint.login.*` events.
261
+ */
262
+ function eventSafeLoginPayload(payload) {
263
+ // Allow-list: only the message survives; legacy adapters may put sid / ticket / device anywhere.
264
+ const safe = {};
265
+ if (typeof payload.message === 'string')
266
+ safe.message = payload.message;
267
+ if (payload.image !== undefined)
268
+ safe.imageOmitted = true;
269
+ if (payload.url !== undefined)
270
+ safe.urlOmitted = true;
271
+ if (Object.keys(payload).some((key) => key !== 'message' && key !== 'image' && key !== 'url'))
272
+ safe.fieldsOmitted = true;
273
+ return safe;
274
+ }
275
+ function inScope(scope, item) {
276
+ return (!scope.adapter || item.adapter === scope.adapter) && (!scope.endpointKey || item.endpointKey === scope.endpointKey);
277
+ }
278
+ /** When the caller names an Endpoint, or was authorized for one, the task must belong to it. */
279
+ function checkTaskTarget(d, ctx, id) {
280
+ const scope = loginScope(d, ctx);
281
+ if ('error' in scope)
282
+ return scope;
283
+ if (!scope.adapter && !scope.endpointKey)
284
+ return undefined;
285
+ const task = ctx.loginAssist?.listPending().find((item) => item.id === id);
286
+ if (!task || !inScope(scope, task))
287
+ return { error: `login task not found: ${id}` };
288
+ return undefined;
289
+ }
290
+ function readSubmitValue(raw) {
291
+ if (raw === undefined || raw === null)
292
+ return '';
293
+ if (typeof raw === 'string')
294
+ return raw;
295
+ if (typeof raw === 'number' || typeof raw === 'boolean')
296
+ return String(raw);
297
+ if (typeof raw !== 'object' || Array.isArray(raw))
298
+ return false;
299
+ const record = raw;
300
+ if (record.action === undefined)
301
+ return record;
302
+ if (typeof record.action !== 'string' || !record.action || record.action.length > 64)
303
+ return false;
304
+ if (record.values !== undefined && (!record.values || typeof record.values !== 'object' || Array.isArray(record.values)))
305
+ return false;
306
+ const values = {};
307
+ for (const [key, item] of Object.entries((record.values ?? {}))) {
308
+ if (typeof item !== 'string' && typeof item !== 'number')
309
+ return false;
310
+ values[key] = String(item);
311
+ }
312
+ return { action: record.action, values };
313
+ }
54
314
  function readEndpointIdentity(value) {
55
315
  if (value === undefined)
56
316
  return undefined;
@@ -8,6 +8,8 @@ export declare function wireConversation(channelType: string, channelId: string,
8
8
  */
9
9
  export declare function invalidProjectPatchOperations(patches: readonly unknown[]): string | undefined;
10
10
  export declare function dispatchHostResourceConsoleRpc(type: string, message: RuntimeConsoleRpcMessage, ctx: RuntimeConsoleRpcContext, requestId: number | string | undefined, payloads: RuntimeConsoleRpcReply[]): Promise<boolean>;
11
+ /** Longest statement text the Console SQL editor sends. */
12
+ export declare const MAX_CONSOLE_SQL_LENGTH = 100000;
11
13
  export declare function stringField(message: RuntimeConsoleRpcMessage, key: string): string;
12
14
  export declare function recordField(value: unknown): Record<string, unknown> | undefined;
13
15
  export declare function positiveInteger(value: unknown, fallback: number): number;