@evomap/evolver-adapter-public 2.0.41 → 2.0.44

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.
@@ -34,7 +34,19 @@ export interface PublicOAuthOptions {
34
34
  maxWaitMs?: number;
35
35
  /** Provider-level refresh bound, including injected transports. */
36
36
  refreshTimeoutMs?: number;
37
+ /** Exact access credential bound to a durable reporting destination. Never use for ordinary reads. */
38
+ expectedTokenBinding?: string;
37
39
  }
40
+ /** A local refusal before the business request enters HubFetch.fetchFn. No credential data is exposed. */
41
+ export declare class OAuthCredentialBindingError extends Error {
42
+ constructor();
43
+ }
44
+ /** Authentication failed before the bound Hub business request began. */
45
+ export declare class OAuthAuthenticationPreflightError extends Error {
46
+ constructor(cause: unknown);
47
+ }
48
+ /** Inspect the trusted credential file without exposing its access token or treating the machine id as an account. */
49
+ export declare function readPublicOAuthCredentialBinding(credPath: string): string | undefined;
38
50
  /**
39
51
  * device token 认证(M6-5, 默认路径 evolver login). device code flow(学 gh auth login):
40
52
  * 显示 user code → 用户在浏览器授权 → 轮询拿 token. 绑机器指纹(CEO: OS machineId+软兜底).
@@ -1,8 +1,34 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { CredentialStore } from './credentialStore.js';
2
3
  import { resolveMachineId, machineFingerprint } from './machineId.js';
3
4
  export const TOKEN_TTL_MS = 24 * 60 * 60_000; // fallback only; the hub supplies expiresInMs (~1h)
4
5
  export const ROTATE_BEFORE_MS = 5 * 60_000; // refresh 5min before expiry (hub access tokens are short-lived ~1h)
5
6
  const DEFAULT_REFRESH_TIMEOUT_MS = 15_000;
7
+ /** A local refusal before the business request enters HubFetch.fetchFn. No credential data is exposed. */
8
+ export class OAuthCredentialBindingError extends Error {
9
+ constructor() {
10
+ super('oauth_credential_binding_changed');
11
+ this.name = 'OAuthCredentialBindingError';
12
+ }
13
+ }
14
+ /** Authentication failed before the bound Hub business request began. */
15
+ export class OAuthAuthenticationPreflightError extends Error {
16
+ constructor(cause) {
17
+ super(cause instanceof Error ? cause.message : 'oauth_authentication_preflight_failed', { cause });
18
+ this.name = 'OAuthAuthenticationPreflightError';
19
+ }
20
+ }
21
+ function tokenBinding(cred) {
22
+ if (!cred || cred.kind !== 'oauth_device_token' || !('token' in cred)
23
+ || typeof cred.token !== 'string' || !cred.token || /\s/u.test(cred.token)
24
+ || [...cred.token].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127))
25
+ return undefined;
26
+ return `sha256:${createHash('sha256').update('evomap-public-oauth-access-token-v1\0').update(cred.token).digest('hex')}`;
27
+ }
28
+ /** Inspect the trusted credential file without exposing its access token or treating the machine id as an account. */
29
+ export function readPublicOAuthCredentialBinding(credPath) {
30
+ return tokenBinding(new CredentialStore(credPath).load());
31
+ }
6
32
  function abortReason(signal) {
7
33
  return signal.reason instanceof Error ? signal.reason : new Error('device_flow_timeout');
8
34
  }
@@ -96,11 +122,54 @@ export class PublicOAuthProvider {
96
122
  }
97
123
  }
98
124
  async authenticate(req) {
99
- let cred = this.store.load();
100
- if (!cred || !('token' in cred))
125
+ if (this.opts.expectedTokenBinding !== undefined
126
+ && (typeof this.opts.expectedTokenBinding !== 'string'
127
+ || !/^sha256:[a-f0-9]{64}$/.test(this.opts.expectedTokenBinding))) {
128
+ throw new OAuthCredentialBindingError();
129
+ }
130
+ let cred;
131
+ try {
132
+ cred = this.store.load();
133
+ }
134
+ catch (error) {
135
+ if (this.opts.expectedTokenBinding)
136
+ throw new OAuthCredentialBindingError();
137
+ throw error;
138
+ }
139
+ if (!cred || !('token' in cred)) {
140
+ if (this.opts.expectedTokenBinding)
141
+ throw new OAuthCredentialBindingError();
101
142
  throw new Error('oauth 未登录, 先 login()');
102
- if ((cred.expiresAt ?? 0) - ROTATE_BEFORE_MS <= this.now())
103
- cred = await this.rotate(req?.signal);
143
+ }
144
+ if (this.opts.expectedTokenBinding && tokenBinding(cred) !== this.opts.expectedTokenBinding) {
145
+ throw new OAuthCredentialBindingError();
146
+ }
147
+ if ((cred.expiresAt ?? 0) - ROTATE_BEFORE_MS <= this.now()) {
148
+ try {
149
+ cred = await this.rotate(req?.signal);
150
+ }
151
+ catch (error) {
152
+ if (this.opts.expectedTokenBinding) {
153
+ // A failed refresh does not prove credential replacement. Re-read the
154
+ // trusted store so a concurrent replacement still receives the strict
155
+ // binding refusal, while transient pre-request failures remain retryable.
156
+ let current;
157
+ try {
158
+ current = this.store.load();
159
+ }
160
+ catch {
161
+ throw new OAuthCredentialBindingError();
162
+ }
163
+ if (tokenBinding(current) !== this.opts.expectedTokenBinding)
164
+ throw new OAuthCredentialBindingError();
165
+ throw new OAuthAuthenticationPreflightError(error);
166
+ }
167
+ throw error;
168
+ }
169
+ }
170
+ if (this.opts.expectedTokenBinding && tokenBinding(cred) !== this.opts.expectedTokenBinding) {
171
+ throw new OAuthCredentialBindingError();
172
+ }
104
173
  return { headers: { authorization: `Bearer ${cred.token}`, 'x-evomap-device': cred.device ?? '' } };
105
174
  }
106
175
  async rotate(parentSignal) {
package/dist/connect.d.ts CHANGED
@@ -27,6 +27,8 @@ export interface ConnectPublicOptions {
27
27
  onNodeSecretDiverged?: () => void;
28
28
  /** oauth 模式: device flow 传输(缺省=真 HTTP, 此处需注入或由 hubUrl 推导). */
29
29
  oauthTransport?: OAuthTransport;
30
+ /** Fail a reporting request before HTTP if token.json no longer matches its durable destination. */
31
+ expectedOAuthTokenBinding?: string;
30
32
  /** keypair 模式: 注册公钥到 hub. */
31
33
  registerPublicKey?: (pem: string) => Promise<{
32
34
  credentialId: string;
package/dist/connect.js CHANGED
@@ -34,6 +34,7 @@ export function connectPublicHub(opts) {
34
34
  credPath: join(dir, 'token.json'),
35
35
  machine: { softIdPath: join(dir, 'machine-id') },
36
36
  transport,
37
+ ...(opts.expectedOAuthTokenBinding !== undefined ? { expectedTokenBinding: opts.expectedOAuthTokenBinding } : {}),
37
38
  });
38
39
  break;
39
40
  }
@@ -27,7 +27,7 @@ export interface OutcomeReport {
27
27
  summary?: string;
28
28
  usedAssetIds?: readonly string[];
29
29
  }
30
- /** recordOutcome never throws: failures come back as `recorded:false` + reason. */
30
+ /** Remote failures return recorded:false; a local credential-binding refusal throws before the report POST. */
31
31
  export interface OutcomeReceipt {
32
32
  recorded: boolean;
33
33
  reason?: string;
@@ -167,6 +167,7 @@ export declare class PublicHubCapability implements hub.HubCapability {
167
167
  private recordMalformedPublishReceipt;
168
168
  readonly references: reference.ReferenceCapability;
169
169
  fetch(query: hub.HubQuery): Promise<hub.AssetRecord[]>;
170
+ fetchPage(query: hub.HubQuery): Promise<hub.FetchPage>;
170
171
  /**
171
172
  * Fetch one asset AND say why, when the answer is not an asset. `fetchAssetById` collapses every outcome to
172
173
  * `null`, so a caller could not tell "the hub does not have this" from "the hub delivered something the
@@ -186,12 +187,19 @@ export declare class PublicHubCapability implements hub.HubCapability {
186
187
  * Report a cycle outcome to the hub's memory graph (POST /a2a/memory/record).
187
188
  * Unlike the protocol-message endpoints (publish/fetch), memory/record takes a
188
189
  * FLAT body — no GEP envelope. Reporting is observability for the network's
189
- * attribution loop, never a dependency of the cycle itself, so this method
190
- * NEVER throws: auth/4xx/5xx/network failures all degrade to `recorded:false`.
190
+ * attribution loop, never a dependency of the cycle itself.
191
+ * Remote auth/4xx/5xx/network failures degrade to `recorded:false`.
192
+ * Credential-binding and authentication preflight refusals are rethrown so the
193
+ * durable caller can prove no report POST began.
191
194
  * Costs hub credits per the hub's memory pricing (caller gates on enablement).
192
195
  */
193
196
  recordOutcome(report: OutcomeReport): Promise<OutcomeReceipt>;
194
197
  recordMemoryEvent(report: MemoryGraphEventReport): Promise<MemoryGraphEventReceipt>;
198
+ /**
199
+ * Remote auth, HTTP and transport failures return recorded:false. Exact
200
+ * credential-binding and authentication preflight errors are rethrown so a
201
+ * durable caller can prove that no reuse-result POST began.
202
+ */
195
203
  recordReuseResult(report: hub.ReuseResultReport): Promise<hub.ReuseResultReceipt>;
196
204
  listLearningAssets(options?: hub.LearningAssetListOptions): Promise<hub.LearningAssetListResult>;
197
205
  recordLearningAssetUsage(report: hub.LearningAssetUsageReport): Promise<hub.LearningAssetUsageReceipt>;
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { bootstrap, reference, hub as hubNs, signals, wire } from '@evomap/evolver-core';
3
- import { AuthError, HubFetch, HubClientError, globalFetchLike, referenceFetchLike, isHubUnreachableError } from './hubFetch.js';
3
+ import { AuthError, HubFetch, HubClientError, terminalHubRejection, globalFetchLike, referenceFetchLike, isHubUnreachableError } from './hubFetch.js';
4
4
  import { isNodeSecret, parseNodeSecretVersion } from './auth/legacyShim.js';
5
5
  import { inboundToAgentEvent, agentEventToOutbound, publishRespToReceipt, searchQueryToFetchWire, searchQueryToSearchOnlyWire, } from './wireMap.js';
6
6
  import { antiAbuseTelemetryMode, buildHeartbeatAntiAbuseTelemetry, } from './antiAbuseTelemetry.js';
@@ -8,6 +8,7 @@ import { getWorkspaceKeychainMode } from './auth/workspaceKeychain.js';
8
8
  import { agentDirectoryFailure, parsePublicAgentPage, parsePublicAgentProfile, paginatePublicAgentPage, mergePublicAgentPages, publicAgentSearchQuery, publicTaskDiscoveryQuery, PUBLIC_TASK_DISCOVERY_MAX_CANDIDATES, unsupportedPublicAvailability, unsupportedPublicSort, withDirectoryTimeout, } from './agentDirectory.js';
9
9
  import { createRecipeExecution } from './recipeExecution.js';
10
10
  import { assetMatchesId, stripHubDeliveryMetadataForIntegrity } from './hubReuse.js';
11
+ import { OAuthAuthenticationPreflightError, OAuthCredentialBindingError } from './auth/oauthDeviceToken.js';
11
12
  export const INBOUND_LIMIT = 100;
12
13
  export const OUTBOUND_MAX_BATCH = 50;
13
14
  export const OUTBOUND_MAX_BODY_BYTES = 4 * 1024 * 1024;
@@ -335,12 +336,21 @@ export class PublicHubCapability {
335
336
  },
336
337
  };
337
338
  async fetch(query) {
339
+ const page = await this.fetchPage(query);
340
+ if (page.confirmRequired)
341
+ throw new Error('hub_fetch_confirmation_required');
342
+ return page.assets;
343
+ }
344
+ async fetchPage(query) {
338
345
  reference.assertExecutionEligible(query, this.referenceScope);
339
346
  // #69: map camelCase SearchQuery → hub snake_case wire (signalsAny → signals) before sending.
340
347
  // /a2a/fetch responses are FULL GEP envelopes (buildResponse('fetch', …)); the rows live at payload.results,
341
348
  // NOT at the top level. Reading body.results here always yielded [] — every fetch silently returned nothing.
342
349
  const body = await this.http.call('POST', '/a2a/fetch', gepEnvelope('fetch', searchQueryToFetchWire(query)));
343
- return reference.withReferenceScope(this.referenceScope, () => assetsFromBody(body));
350
+ return reference.withReferenceScope(this.referenceScope, () => {
351
+ reference.assertExecutionEligible(body);
352
+ return newbieFetchConfirmation(body) ?? { assets: assetsFromBody(body), confirmRequired: false };
353
+ });
344
354
  }
345
355
  /**
346
356
  * Fetch one asset AND say why, when the answer is not an asset. `fetchAssetById` collapses every outcome to
@@ -494,8 +504,10 @@ export class PublicHubCapability {
494
504
  * Report a cycle outcome to the hub's memory graph (POST /a2a/memory/record).
495
505
  * Unlike the protocol-message endpoints (publish/fetch), memory/record takes a
496
506
  * FLAT body — no GEP envelope. Reporting is observability for the network's
497
- * attribution loop, never a dependency of the cycle itself, so this method
498
- * NEVER throws: auth/4xx/5xx/network failures all degrade to `recorded:false`.
507
+ * attribution loop, never a dependency of the cycle itself.
508
+ * Remote auth/4xx/5xx/network failures degrade to `recorded:false`.
509
+ * Credential-binding and authentication preflight refusals are rethrown so the
510
+ * durable caller can prove no report POST began.
499
511
  * Costs hub credits per the hub's memory pricing (caller gates on enablement).
500
512
  */
501
513
  async recordOutcome(report) {
@@ -506,7 +518,7 @@ export class PublicHubCapability {
506
518
  return { recorded: false, reason: 'no_signals' }; // hub rejects empty signals; skip the paid call
507
519
  const usedAssetIds = [...new Set((report.usedAssetIds ?? []).filter((x) => typeof x === 'string' && x.length > 0 && x.length <= USED_ASSET_ID_MAX_LEN))].slice(0, USED_ASSET_IDS_MAX);
508
520
  try {
509
- await this.http.call('POST', '/a2a/memory/record', {
521
+ const body = await this.http.call('POST', '/a2a/memory/record', {
510
522
  signals,
511
523
  status: report.status,
512
524
  ...(report.geneId ? { gene_id: report.geneId } : {}),
@@ -514,9 +526,14 @@ export class PublicHubCapability {
514
526
  ...(report.summary ? { summary: report.summary } : {}),
515
527
  ...(usedAssetIds.length > 0 ? { used_asset_ids: usedAssetIds } : {}),
516
528
  });
517
- return { recorded: true };
529
+ const payload = asRecord(body['payload']) ?? body;
530
+ return confirmedFeedbackReceipt(body, payload)
531
+ ? { recorded: true }
532
+ : { recorded: false, reason: feedbackReceiptReason(body, payload) ?? 'outcome_receipt_unconfirmed' };
518
533
  }
519
534
  catch (e) {
535
+ if (e instanceof OAuthCredentialBindingError || e instanceof OAuthAuthenticationPreflightError)
536
+ throw e;
520
537
  return { recorded: false, reason: e instanceof Error ? e.message : String(e) };
521
538
  }
522
539
  }
@@ -540,6 +557,11 @@ export class PublicHubCapability {
540
557
  return { recorded: false, reason: e instanceof Error ? e.message : String(e) };
541
558
  }
542
559
  }
560
+ /**
561
+ * Remote auth, HTTP and transport failures return recorded:false. Exact
562
+ * credential-binding and authentication preflight errors are rethrown so a
563
+ * durable caller can prove that no reuse-result POST began.
564
+ */
543
565
  async recordReuseResult(report) {
544
566
  if (!reference.isExecutionEligible(report, this.referenceScope))
545
567
  return { recorded: false, reason: 'reference_not_execution_evidence' };
@@ -560,16 +582,34 @@ export class PublicHubCapability {
560
582
  ...(report.traceId ? { trace_id: report.traceId } : {}),
561
583
  ...(timeSavedSeconds.value !== undefined ? { time_saved_seconds: timeSavedSeconds.value } : {}),
562
584
  ...(report.reason ? { reason: report.reason } : {}),
585
+ ...(report.evidence ? { evidence: report.evidence } : {}),
563
586
  });
564
- const payload = asRecord(body['payload']) ?? body;
587
+ const payload = body['payload'] === undefined ? body : asRecord(body['payload']) ?? {};
588
+ const terminalDeclared = payload['terminal'] === true || body['terminal'] === true;
589
+ const recorded = confirmedFeedbackReceipt(body, payload) && !terminalDeclared;
590
+ const rawReason = feedbackReceiptReason(body, payload);
591
+ const confirmedDuplicate = payload['reason'] === 'duplicate_report'
592
+ && confirmedFeedbackReceipt(body, payload, false) && !terminalDeclared;
593
+ const reason = rawReason === 'duplicate_report' && !recorded && !confirmedDuplicate
594
+ ? 'reuse_receipt_unconfirmed' : rawReason;
595
+ const reuseStats = recorded ? parseReuseStats(payload['reuse_stats'] ?? body['reuse_stats']) : undefined;
565
596
  return {
566
- recorded: payload['recorded'] !== false && payload['ok'] !== false,
567
- ...(stringField(payload, 'reason') ?? stringField(payload, 'error') ? { reason: stringField(payload, 'reason') ?? stringField(payload, 'error') } : {}),
568
- ...(stringField(payload, 'id') ?? stringField(payload, 'receipt_id') ? { id: stringField(payload, 'id') ?? stringField(payload, 'receipt_id') } : {}),
597
+ recorded,
598
+ ...(!recorded || reason ? { reason: reason ?? 'reuse_receipt_unconfirmed' } : {}),
599
+ ...(recorded && (stringField(payload, 'id') ?? stringField(payload, 'receipt_id'))
600
+ ? { id: stringField(payload, 'id') ?? stringField(payload, 'receipt_id') } : {}),
601
+ ...(reuseStats ? { reuseStats } : {}),
602
+ ...(recorded ? reuseAdmission(payload) : {}),
569
603
  };
570
604
  }
571
605
  catch (e) {
572
- return { recorded: false, reason: e instanceof Error ? e.message : String(e) };
606
+ if (e instanceof OAuthCredentialBindingError || e instanceof OAuthAuthenticationPreflightError)
607
+ throw e;
608
+ const rejection = terminalHubRejection(e);
609
+ if (rejection)
610
+ return { recorded: false, terminal: true, ...rejection };
611
+ const reason = e instanceof Error ? e.message : String(e);
612
+ return { recorded: false, reason: reason === 'duplicate_report' ? 'reuse_receipt_unconfirmed' : reason };
573
613
  }
574
614
  }
575
615
  async listLearningAssets(options = {}) {
@@ -880,6 +920,28 @@ export class PublicHubCapability {
880
920
  function asRecord(value) {
881
921
  return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
882
922
  }
923
+ function reuseAdmission(payload) {
924
+ const weight = payload['weight'];
925
+ return {
926
+ ...(typeof payload['eligible'] === 'boolean' ? { eligible: payload['eligible'] } : {}),
927
+ ...(typeof payload['counted'] === 'boolean' ? { counted: payload['counted'] } : {}),
928
+ ...(typeof weight === 'number' && Number.isFinite(weight) ? { weight } : {}),
929
+ };
930
+ }
931
+ function confirmedFeedbackReceipt(envelope, receipt, recorded = true) {
932
+ const permitsSuccess = (value) => value === undefined || value === true;
933
+ const hasNoError = (value) => value === undefined || value === null;
934
+ return receipt['recorded'] === recorded
935
+ && permitsSuccess(receipt['ok'])
936
+ && permitsSuccess(envelope['ok'])
937
+ && (envelope === receipt || envelope['recorded'] === undefined || envelope['recorded'] === recorded)
938
+ && hasNoError(receipt['error'])
939
+ && hasNoError(envelope['error']);
940
+ }
941
+ function feedbackReceiptReason(envelope, receipt) {
942
+ return stringField(envelope, 'reason') ?? stringField(envelope, 'error')
943
+ ?? stringField(receipt, 'reason') ?? stringField(receipt, 'error');
944
+ }
883
945
  function searchAssets(value, source) {
884
946
  if (!Array.isArray(value))
885
947
  throw new Error(`${source}_results_invalid`);
@@ -899,6 +961,7 @@ function semanticSearchAssets(body) {
899
961
  const status = stringField(body, 'search_status');
900
962
  if (status === 'degraded' || body['retryable'] === true)
901
963
  throw new Error('semantic_search_degraded');
964
+ newbieFetchConfirmation(body);
902
965
  const assets = searchAssets(body['assets'], 'semantic_search');
903
966
  if (status === 'no_match') {
904
967
  if (assets.length !== 0)
@@ -917,6 +980,7 @@ function semanticSearchAssets(body) {
917
980
  }
918
981
  function signalSearchAssets(body) {
919
982
  reference.assertExecutionEligible(body);
983
+ newbieFetchConfirmation(body);
920
984
  const payload = asRecord(body['payload']);
921
985
  return searchAssets(payload?.['results'], 'signal_search');
922
986
  }
@@ -1033,6 +1097,9 @@ function dryRunRecipeReceipt(action, recipeId, extra = {}) {
1033
1097
  }
1034
1098
  function assetCandidatesFromBody(body) {
1035
1099
  reference.assertExecutionEligible(body);
1100
+ const confirmation = newbieFetchConfirmation(body);
1101
+ if (confirmation)
1102
+ throw new Error(confirmation.confirmRequired ? 'hub_fetch_confirmation_required' : 'hub_fetch_confirmation_rejected');
1036
1103
  const payload = asRecord(body['payload']);
1037
1104
  const candidates = [
1038
1105
  body['asset'],
@@ -1045,6 +1112,17 @@ function assetCandidatesFromBody(body) {
1045
1112
  return candidates
1046
1113
  .filter((candidate) => Boolean(candidate && typeof candidate === 'object' && !Array.isArray(candidate)));
1047
1114
  }
1115
+ // The Hub holds a new account's paid fetch behind `status: confirm_required` with an empty result set.
1116
+ function newbieFetchConfirmation(body) {
1117
+ const payload = asRecord(body['payload']) ?? body;
1118
+ const failed = [body, payload].some((part) => part['ok'] === false || (part['error'] !== undefined && part['error'] !== null));
1119
+ if (failed)
1120
+ throw new Error(payload['status'] === 'confirm_required'
1121
+ ? 'hub_fetch_confirmation_rejected' : 'hub_fetch_response_rejected');
1122
+ if (payload['status'] !== 'confirm_required')
1123
+ return undefined;
1124
+ return { assets: [], confirmRequired: true, creditCostPreview: asRecord(payload['credit_cost_preview']) ?? {} };
1125
+ }
1048
1126
  function assetsFromBody(body) {
1049
1127
  return assetCandidatesFromBody(body).map(unwrapFetchDeliveryRow);
1050
1128
  }
@@ -1517,6 +1595,18 @@ function mailboxPushFailureReason(row) {
1517
1595
  }
1518
1596
  return undefined;
1519
1597
  }
1598
+ function parseReuseStats(value) {
1599
+ const stats = asRecord(value);
1600
+ if (!stats)
1601
+ return undefined;
1602
+ const { total, success, success_rate: successRate } = stats;
1603
+ const isCount = (n) => Number.isSafeInteger(n) && n >= 0;
1604
+ if (!isCount(total) || !isCount(success) || success > total)
1605
+ return undefined;
1606
+ if (typeof successRate !== 'number' || !Number.isFinite(successRate) || successRate < 0 || successRate > 1)
1607
+ return undefined;
1608
+ return { total, success, successRate };
1609
+ }
1520
1610
  function optionalReuseMetric(report, camelKey, snakeKey, reason) {
1521
1611
  const rawReport = report;
1522
1612
  let value;
@@ -51,6 +51,15 @@ export declare class HubClientError extends Error {
51
51
  readonly retryAfterMs?: number | undefined;
52
52
  constructor(status: number, body: unknown, retryAfterMs?: number | undefined);
53
53
  }
54
+ export declare function isTerminalHubRejectionStatus(status: unknown): status is number;
55
+ /**
56
+ * A Hub verdict that resending the same request can never change. Auth failures, throttling, 5xx and
57
+ * transport errors are not verdicts on the request and return undefined.
58
+ */
59
+ export declare function terminalHubRejection(error: unknown): {
60
+ reason: string;
61
+ status: number;
62
+ } | undefined;
54
63
  export declare class HubUnreachableError extends Error {
55
64
  readonly details: {
56
65
  status?: number;
package/dist/hubFetch.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Agent, buildConnector, fetch as undiciFetch } from 'undici';
2
2
  import { Buffer } from 'node:buffer';
3
3
  import { TextDecoder } from 'node:util';
4
+ import { OAuthAuthenticationPreflightError } from './auth/oauthDeviceToken.js';
4
5
  export const HUB_ERROR_TEXT_MAX_BYTES = 8 * 1024;
5
6
  export const HUB_JSON_TEXT_MAX_BYTES = 4 * 1024 * 1024;
6
7
  export const HUB_UNREACHABLE_BACKOFF_BASE_MS = 60_000;
@@ -53,6 +54,28 @@ export class HubClientError extends Error {
53
54
  this.name = 'HubClientError';
54
55
  }
55
56
  }
57
+ // Only these statuses say the request itself can never be accepted. Every other 4xx (auth, credit,
58
+ // routing, throttling, cancellation, gateway conditions) describes the moment and stays retryable.
59
+ const TERMINAL_HUB_REJECTION_STATUSES = new Set([400, 409, 410, 413, 422]);
60
+ export function isTerminalHubRejectionStatus(status) {
61
+ return typeof status === 'number' && TERMINAL_HUB_REJECTION_STATUSES.has(status);
62
+ }
63
+ /**
64
+ * A Hub verdict that resending the same request can never change. Auth failures, throttling, 5xx and
65
+ * transport errors are not verdicts on the request and return undefined.
66
+ */
67
+ export function terminalHubRejection(error) {
68
+ if (!(error instanceof HubClientError) || !isTerminalHubRejectionStatus(error.status))
69
+ return undefined;
70
+ const envelope = plainRecord(error.body);
71
+ const payload = plainRecord(envelope['payload']);
72
+ const reason = [envelope['reason'], envelope['error'], payload['reason'], payload['error']]
73
+ .find((value) => typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value));
74
+ return { reason: reason ?? 'hub_rejected', status: error.status };
75
+ }
76
+ function plainRecord(value) {
77
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
78
+ }
56
79
  export class HubUnreachableError extends Error {
57
80
  details;
58
81
  code = 'HUB_UNREACHABLE';
@@ -147,6 +170,10 @@ export async function authenticateHubRequest(deps, method, path, bodyObj) {
147
170
  return await awaitWithAbort(deps.auth.authenticate({ method, path, ...(draft ? { body: draft } : {}), signal: authDeadline.signal }), authDeadline.signal);
148
171
  }
149
172
  catch (error) {
173
+ // Bound feedback needs the proof that its business request never started.
174
+ // Preserve that typed refusal rather than reducing it to a generic timeout.
175
+ if (error instanceof OAuthAuthenticationPreflightError)
176
+ throw error;
150
177
  if (isAuthTransportTimeout(error)) {
151
178
  throw new HubUnreachableError('hub authentication timed out', {
152
179
  context: `${method} ${path}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-adapter-public",
3
- "version": "2.0.41",
3
+ "version": "2.0.44",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@evomap/atp-sdk": "^0.1.0",
20
- "@evomap/evolver-core": "2.0.41",
20
+ "@evomap/evolver-core": "2.0.44",
21
21
  "undici": "^6.28.1"
22
22
  },
23
23
  "optionalDependencies": {