@apifuse/provider-sdk 2.2.0-beta.14 → 2.2.0-beta.16

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.
@@ -0,0 +1,91 @@
1
+ // This set suppresses the unregistered-provider-error-code signal for codes
2
+ // intentionally emitted by SDK paths. It is not the complete authority for
3
+ // runtime error resolution: branded errors and additional canonical SDK codes
4
+ // must also remain immune to provider-declared status/retryability overrides.
5
+ export const SDK_OWNED_PROVIDER_ERROR_CODES = new Set([
6
+ "MISSING_SECRET",
7
+ "AUTH_PROMPT_UNAVAILABLE",
8
+ "BROWSER_CDP_POOL_REQUIRED",
9
+ "BROWSER_RUNTIME_UNSUPPORTED",
10
+ "STEALTH_RUNTIME_UNSUPPORTED",
11
+ "SSE_EVENT_UNDECLARED",
12
+ "STREAM_EVENT_TOO_LARGE",
13
+ "STREAM_CHUNK_TOO_LARGE",
14
+ "SSE_RESULT_UNSUPPORTED",
15
+ "STREAM_RESULT_UNSUPPORTED",
16
+ "AUTH_FLOW_NOT_CONFIGURED",
17
+ "refresh_not_supported",
18
+ "RUNTIME_UNSUPPORTED",
19
+ "PROVIDER_STATE_UNSUPPORTED",
20
+ "CHOICE_TOKEN_MASTER_SECRET_NOT_CONFIGURED",
21
+ "CHOICE_STATE_PAYLOAD_TOO_LARGE",
22
+ "CHOICE_STATE_UNAVAILABLE",
23
+ "CHOICE_CONTEXT_REQUIRED",
24
+ "unsupported_stealth_cookie_store_version",
25
+ "provider_secret_error",
26
+ "credential_key_error",
27
+ "credential_mode_error",
28
+ "flow_expired",
29
+ "turn_validation_error",
30
+ "context_access_error",
31
+ "UNSUPPORTED_STT_OPTION",
32
+ "INVALID_STT_AUDIO",
33
+ "STT_AUDIO_TOO_LARGE",
34
+ "STT_UPSTREAM_FAILED",
35
+ "INVALID_STT_VERIFICATION_CODE_OPTIONS",
36
+ "NO_CODE_FOUND",
37
+ "AMBIGUOUS_CODE",
38
+ "retry_invalid_policy",
39
+ "retry_unsafe_method",
40
+ "stealth_cookie_store_serialize_failed",
41
+ "response_too_large",
42
+ "transport_stream_unavailable",
43
+ "transport_invalid_method",
44
+ "http_transport_override_unsupported",
45
+ "http_redirect_policy_invalid",
46
+ "http_redirect_stopped",
47
+ "http_redirect_max_hops",
48
+ "http_redirect_missing_location",
49
+ "http_redirect_loop",
50
+ "transport_invalid_url",
51
+ "retry_exhausted",
52
+ "auth_abort_unsafe_data",
53
+ "credentials_auth_missing_credential_keys",
54
+ "credentials_auth_missing_credential",
55
+ "credentials_auth_invalid_login_result",
56
+ "credentials_auth_unknown_challenge",
57
+ "credentials_auth_unknown_pending_challenge",
58
+ "STATEFUL_FORWARDING_NOT_CONFIGURED",
59
+ "STATEFUL_FORWARDING_SIGNATURE_MISSING",
60
+ "STATEFUL_FORWARDING_NONCE_INVALID",
61
+ "STATEFUL_FORWARDING_TIMESTAMP_INVALID",
62
+ "STATEFUL_FORWARDING_SIGNATURE_INVALID",
63
+ "STATEFUL_FORWARDING_REPLAY_DETECTED",
64
+ "STATEFUL_FORWARDING_REPLAY_CACHE_FULL",
65
+ "STATEFUL_FORWARDING_ENVELOPE_INVALID",
66
+ "STATEFUL_FORWARDING_PROVIDER_MISMATCH",
67
+ "STATEFUL_FORWARDING_SOURCE_POD_MISMATCH",
68
+ "STATEFUL_FORWARDING_OWNER_FENCE_INVALID",
69
+ "STATEFUL_FORWARDING_REQUEST_FAILED",
70
+ "STATEFUL_FORWARDING_CONTEXT_MISSING",
71
+ "STATEFUL_FORWARDING_BAD_RESPONSE",
72
+ "STATEFUL_INTERNAL_EXECUTOR_NOT_CONFIGURED",
73
+ "STATEFUL_FILE_FORWARDING_UNSUPPORTED",
74
+ "STATEFUL_CONTROL_PLANE_OPERATION_AMBIGUOUS",
75
+ "STATEFUL_CONTROL_PLANE_REQUEST_FAILED",
76
+ "STATEFUL_CONTROL_PLANE_HTTP_ERROR",
77
+ "STATEFUL_CONTROL_PLANE_INVALID_RESPONSE",
78
+ ]);
79
+
80
+ // Complete code authority for provider-declared runtime resolution. Keep this
81
+ // separate from signal suppression: declarations may document these codes, but
82
+ // their status and retryability can never override the SDK's canonical result.
83
+ export const SDK_RUNTIME_OWNED_ERROR_CODES = new Set([
84
+ ...SDK_OWNED_PROVIDER_ERROR_CODES,
85
+ "reauth_required",
86
+ "STT_UNAVAILABLE",
87
+ "UNSUPPORTED_STT_BACKEND",
88
+ "OUTPUT_VALIDATION_FAILED",
89
+ "NOT_FOUND",
90
+ "not_found",
91
+ ]);
package/src/errors.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ProviderErrorCategory } from "./observability.js";
2
+ import type { HttpRedirectFailureReason } from "./types.js";
2
3
 
3
4
  // Versioned, cross-realm brands. `Symbol.for` resolves to the same symbol in
4
5
  // any copy/entrypoint of this SDK major version, so an error created by a
@@ -148,6 +149,33 @@ export class TransportError extends ProviderError {
148
149
  }
149
150
  }
150
151
 
152
+ export type HttpRedirectErrorOptions = TransportErrorOptions & {
153
+ reason: HttpRedirectFailureReason;
154
+ /** Redacted redirect target suitable for provider diagnostics. */
155
+ target?: string;
156
+ };
157
+
158
+ /** Raised when an opt-in ctx.http redirect policy refuses or cannot resolve a hop. */
159
+ export class HttpRedirectError extends TransportError {
160
+ readonly reason: HttpRedirectFailureReason;
161
+ readonly target?: string;
162
+
163
+ constructor(message: string, options: HttpRedirectErrorOptions) {
164
+ const { reason, target, ...transportOptions } = options;
165
+ super(message, {
166
+ ...transportOptions,
167
+ code: `http_redirect_${reason}`,
168
+ details: {
169
+ reason,
170
+ ...(target ? { target } : {}),
171
+ },
172
+ });
173
+ this.name = "HttpRedirectError";
174
+ this.reason = reason;
175
+ this.target = target;
176
+ }
177
+ }
178
+
151
179
  // Cross-module type guards. Prefer these over `instanceof` at any boundary that
152
180
  // may receive an error from a different copy/entrypoint of the SDK (see the HTTP
153
181
  // server error boundary). They recognize branded errors regardless of which
package/src/index.ts CHANGED
@@ -73,6 +73,8 @@ export { createHttpClient } from "./runtime/http.js";
73
73
  export {
74
74
  createNativeNetworkClient,
75
75
  deriveNativeCredentialAffinityKey,
76
+ NativeEgressGrantExpiredError,
77
+ NativeEgressNotDeclaredError,
76
78
  NativeIdleTimeoutError,
77
79
  NativeNetworkError,
78
80
  NativeProxyExpiredError,
@@ -189,6 +191,9 @@ export type {
189
191
  HealthJourneyStep,
190
192
  HttpClient,
191
193
  HttpMethod,
194
+ HttpRedirectFailureReason,
195
+ HttpRedirectPolicy,
196
+ HttpRedirectPolicyMode,
192
197
  HttpResponse,
193
198
  HttpRetryOptions,
194
199
  HttpRetrySummary,
@@ -225,6 +230,7 @@ export type {
225
230
  OperationDeprecationMetadata,
226
231
  OperationDocMeta,
227
232
  OperationErrorCode,
233
+ ProviderErrorStatus,
228
234
  OperationHandlerResult,
229
235
  OperationInputExample,
230
236
  OperationLifecycle,
@@ -280,6 +286,7 @@ export type {
280
286
  ProviderSttMode,
281
287
  ProviderSupportLevel,
282
288
  RequestOptions,
289
+ RedirectRunReason,
283
290
  Rfc3339Instant,
284
291
  SchemaLike,
285
292
  SmsOrigin,
@@ -0,0 +1,285 @@
1
+ import type {
2
+ NativeProviderConfig,
3
+ NativeTcpDynamicEgressRule,
4
+ NativeTcpEgressRule,
5
+ NativeTcpPortRange,
6
+ NativeTcpTlsMode,
7
+ } from "./types.js";
8
+
9
+ type NativeNetworkDeclaration = NonNullable<NativeProviderConfig["network"]>;
10
+
11
+ const NATIVE_PROVIDER_FIELD_RECORD = {
12
+ network: true,
13
+ } satisfies { readonly [K in keyof Required<NativeProviderConfig>]: true };
14
+ const NATIVE_NETWORK_FIELD_RECORD = {
15
+ tcp: true,
16
+ dynamicTcp: true,
17
+ } satisfies { readonly [K in keyof Required<NativeNetworkDeclaration>]: true };
18
+ const NATIVE_TCP_RULE_FIELD_RECORD = {
19
+ host: true,
20
+ ports: true,
21
+ tls: true,
22
+ } satisfies { readonly [K in keyof Required<NativeTcpEgressRule>]: true };
23
+ const NATIVE_DYNAMIC_TCP_RULE_FIELD_RECORD = {
24
+ sourceHost: true,
25
+ sourceHostSuffixes: true,
26
+ sourcePorts: true,
27
+ sourcePortRanges: true,
28
+ targetHostSuffixes: true,
29
+ targetPorts: true,
30
+ targetPortRanges: true,
31
+ tls: true,
32
+ ttlMs: true,
33
+ maxGrants: true,
34
+ } satisfies { readonly [K in keyof Required<NativeTcpDynamicEgressRule>]: true };
35
+ const NATIVE_TCP_PORT_RANGE_FIELD_RECORD = {
36
+ start: true,
37
+ end: true,
38
+ } satisfies { readonly [K in keyof Required<NativeTcpPortRange>]: true };
39
+
40
+ const NATIVE_PROVIDER_FIELDS = Object.keys(NATIVE_PROVIDER_FIELD_RECORD);
41
+ const NATIVE_NETWORK_FIELDS = Object.keys(NATIVE_NETWORK_FIELD_RECORD);
42
+ const NATIVE_TCP_RULE_FIELDS = Object.keys(NATIVE_TCP_RULE_FIELD_RECORD);
43
+ const NATIVE_DYNAMIC_TCP_RULE_FIELDS = Object.keys(NATIVE_DYNAMIC_TCP_RULE_FIELD_RECORD);
44
+ const NATIVE_TCP_PORT_RANGE_FIELDS = Object.keys(NATIVE_TCP_PORT_RANGE_FIELD_RECORD);
45
+
46
+ export type StaticEgressRuleSnapshot = {
47
+ readonly host: string;
48
+ readonly ports: readonly number[];
49
+ readonly tls: NativeTcpTlsMode;
50
+ };
51
+
52
+ export type DynamicEgressRuleSnapshot = {
53
+ readonly sourceHost?: string;
54
+ readonly sourceHostSuffixes: readonly string[];
55
+ readonly sourcePorts: readonly number[];
56
+ readonly sourcePortRanges: readonly NativeTcpPortRange[];
57
+ readonly targetHostSuffixes: readonly string[];
58
+ readonly targetPorts: readonly number[];
59
+ readonly targetPortRanges: readonly NativeTcpPortRange[];
60
+ readonly tls: NativeTcpTlsMode;
61
+ readonly ttlMs?: number;
62
+ readonly maxGrants?: number;
63
+ };
64
+
65
+ export type NativeEgressPolicySnapshot = {
66
+ readonly staticRules: readonly StaticEgressRuleSnapshot[];
67
+ readonly dynamicRules: readonly DynamicEgressRuleSnapshot[];
68
+ };
69
+
70
+ export class NativeEgressPolicyValidationError extends Error {
71
+ constructor(message: string) {
72
+ super(message);
73
+ this.name = "NativeEgressPolicyValidationError";
74
+ }
75
+ }
76
+
77
+ function fail(message: string): never {
78
+ throw new NativeEgressPolicyValidationError(message);
79
+ }
80
+
81
+ function dataRecord(
82
+ value: unknown,
83
+ fieldPath: string,
84
+ allowed: readonly string[],
85
+ ): Record<string, unknown> {
86
+ if (!value || typeof value !== "object" || Array.isArray(value))
87
+ fail(`${fieldPath} must be an object`);
88
+ const prototype = Reflect.getPrototypeOf(value);
89
+ if (prototype !== Object.prototype && prototype !== null)
90
+ fail(`${fieldPath} must be a plain object`);
91
+ const record: Record<string, unknown> = {};
92
+ for (const key of Reflect.ownKeys(value)) {
93
+ if (typeof key !== "string") fail(`${fieldPath} must not contain symbol fields`);
94
+ if (!allowed.includes(key)) fail(`Unknown field ${fieldPath}.${key}`);
95
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
96
+ if (!descriptor || !("value" in descriptor)) fail(`${fieldPath}.${key} must be a data field`);
97
+ record[key] = descriptor.value;
98
+ }
99
+ return record;
100
+ }
101
+
102
+ function dataArray(value: unknown, fieldPath: string): readonly unknown[] {
103
+ if (!Array.isArray(value)) fail(`${fieldPath} must be an array`);
104
+ const result: unknown[] = [];
105
+ for (const key of Reflect.ownKeys(value)) {
106
+ if (key === "length") continue;
107
+ if (typeof key !== "string" || !/^(?:0|[1-9]\d*)$/.test(key))
108
+ fail(`${fieldPath} must not contain non-index fields`);
109
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
110
+ if (!descriptor || !("value" in descriptor)) fail(`${fieldPath}[${key}] must be a data field`);
111
+ result[Number(key)] = descriptor.value;
112
+ }
113
+ if (result.length !== value.length) fail(`${fieldPath} must not be sparse`);
114
+ for (let index = 0; index < result.length; index += 1) {
115
+ if (!(index in result)) fail(`${fieldPath} must not be sparse`);
116
+ }
117
+ return result;
118
+ }
119
+
120
+ function hasControlCharacter(value: string): boolean {
121
+ for (let index = 0; index < value.length; index += 1) {
122
+ const code = value.charCodeAt(index);
123
+ if (code <= 31 || code === 127) return true;
124
+ }
125
+ return false;
126
+ }
127
+
128
+ function host(value: unknown, fieldPath: string, suffix = false): string {
129
+ if (
130
+ typeof value !== "string" ||
131
+ !value.trim() ||
132
+ hasControlCharacter(value) ||
133
+ /\s/.test(value) ||
134
+ value.includes("://")
135
+ )
136
+ fail(`${fieldPath} must be a non-empty hostname`);
137
+ if (value.includes("*"))
138
+ fail(`${fieldPath} must be an exact ${suffix ? "DNS suffix" : "hostname"}, not a wildcard`);
139
+ const normalized = value.trim().toLowerCase().replace(/\.$/, "");
140
+ if (!normalized) fail(`${fieldPath} must be a non-empty hostname`);
141
+ return normalized;
142
+ }
143
+
144
+ function port(value: unknown, fieldPath: string): number {
145
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 65_535)
146
+ fail(`${fieldPath} must be an integer from 1 to 65535`);
147
+ return value;
148
+ }
149
+
150
+ function ports(value: unknown, fieldPath: string): readonly number[] {
151
+ return dataArray(value, fieldPath).map((value, index) => port(value, `${fieldPath}[${index}]`));
152
+ }
153
+
154
+ function hostSuffixes(value: unknown, fieldPath: string): readonly string[] {
155
+ return dataArray(value, fieldPath).map((value, index) =>
156
+ host(value, `${fieldPath}[${index}]`, true),
157
+ );
158
+ }
159
+
160
+ function ranges(value: unknown, fieldPath: string): readonly NativeTcpPortRange[] {
161
+ return dataArray(value, fieldPath).map((value, index) => {
162
+ const rangePath = `${fieldPath}[${index}]`;
163
+ const record = dataRecord(value, rangePath, NATIVE_TCP_PORT_RANGE_FIELDS);
164
+ const start = port(record.start, `${rangePath}.start`);
165
+ const end = port(record.end, `${rangePath}.end`);
166
+ if (start > end) fail(`${rangePath}.start must not exceed end`);
167
+ return { start, end };
168
+ });
169
+ }
170
+
171
+ function tls(value: unknown, fieldPath: string): NativeTcpTlsMode {
172
+ if (value !== "required" && value !== "allowed" && value !== "disabled")
173
+ fail(`${fieldPath} must be required, allowed, or disabled`);
174
+ return value;
175
+ }
176
+
177
+ function positiveInteger(value: unknown, fieldPath: string): number {
178
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
179
+ fail(`${fieldPath} must be a positive integer`);
180
+ return value;
181
+ }
182
+
183
+ export function parseNativeEgressPolicy(value: unknown): NativeEgressPolicySnapshot {
184
+ try {
185
+ const policy = dataRecord(value, "native.network", NATIVE_NETWORK_FIELDS);
186
+ const staticRules =
187
+ policy.tcp === undefined
188
+ ? []
189
+ : dataArray(policy.tcp, "native.network.tcp").map((value, index) => {
190
+ const fieldPath = `native.network.tcp[${index}]`;
191
+ const rule = dataRecord(value, fieldPath, NATIVE_TCP_RULE_FIELDS);
192
+ const declaredPorts = ports(rule.ports, `${fieldPath}.ports`);
193
+ if (declaredPorts.length === 0) fail(`${fieldPath}.ports must not be empty`);
194
+ return {
195
+ host: host(rule.host, `${fieldPath}.host`),
196
+ ports: declaredPorts,
197
+ tls: tls(rule.tls, `${fieldPath}.tls`),
198
+ };
199
+ });
200
+ const dynamicRules =
201
+ policy.dynamicTcp === undefined
202
+ ? []
203
+ : dataArray(policy.dynamicTcp, "native.network.dynamicTcp").map((value, index) => {
204
+ const fieldPath = `native.network.dynamicTcp[${index}]`;
205
+ const rule = dataRecord(value, fieldPath, NATIVE_DYNAMIC_TCP_RULE_FIELDS);
206
+ const sourceHost =
207
+ rule.sourceHost === undefined
208
+ ? undefined
209
+ : host(rule.sourceHost, `${fieldPath}.sourceHost`);
210
+ const sourceHostSuffixes =
211
+ rule.sourceHostSuffixes === undefined
212
+ ? []
213
+ : hostSuffixes(rule.sourceHostSuffixes, `${fieldPath}.sourceHostSuffixes`);
214
+ if (sourceHost === undefined && sourceHostSuffixes.length === 0)
215
+ fail(
216
+ `${fieldPath} must declare sourceHost or a non-empty sourceHostSuffixes list`,
217
+ );
218
+ const sourcePorts =
219
+ rule.sourcePorts === undefined
220
+ ? []
221
+ : ports(rule.sourcePorts, `${fieldPath}.sourcePorts`);
222
+ const sourcePortRanges =
223
+ rule.sourcePortRanges === undefined
224
+ ? []
225
+ : ranges(rule.sourcePortRanges, `${fieldPath}.sourcePortRanges`);
226
+ if (sourcePorts.length === 0 && sourcePortRanges.length === 0)
227
+ fail(
228
+ `${fieldPath} must declare a non-empty sourcePorts or sourcePortRanges list`,
229
+ );
230
+ const targetHostSuffixes = hostSuffixes(
231
+ rule.targetHostSuffixes,
232
+ `${fieldPath}.targetHostSuffixes`,
233
+ );
234
+ if (targetHostSuffixes.length === 0)
235
+ fail(`${fieldPath}.targetHostSuffixes must not be empty`);
236
+ const targetPorts =
237
+ rule.targetPorts === undefined
238
+ ? []
239
+ : ports(rule.targetPorts, `${fieldPath}.targetPorts`);
240
+ const targetPortRanges =
241
+ rule.targetPortRanges === undefined
242
+ ? []
243
+ : ranges(rule.targetPortRanges, `${fieldPath}.targetPortRanges`);
244
+ if (targetPorts.length === 0 && targetPortRanges.length === 0)
245
+ fail(
246
+ `${fieldPath} must declare a non-empty targetPorts or targetPortRanges list`,
247
+ );
248
+ return {
249
+ ...(sourceHost === undefined ? {} : { sourceHost }),
250
+ sourceHostSuffixes,
251
+ sourcePorts,
252
+ sourcePortRanges,
253
+ targetHostSuffixes,
254
+ targetPorts,
255
+ targetPortRanges,
256
+ tls: tls(rule.tls, `${fieldPath}.tls`),
257
+ ...(rule.ttlMs === undefined
258
+ ? {}
259
+ : { ttlMs: positiveInteger(rule.ttlMs, `${fieldPath}.ttlMs`) }),
260
+ ...(rule.maxGrants === undefined
261
+ ? {}
262
+ : { maxGrants: positiveInteger(rule.maxGrants, `${fieldPath}.maxGrants`) }),
263
+ };
264
+ });
265
+ return { staticRules, dynamicRules };
266
+ } catch (error) {
267
+ if (error instanceof NativeEgressPolicyValidationError) throw error;
268
+ throw new NativeEgressPolicyValidationError(
269
+ "Native egress policy could not be inspected safely",
270
+ );
271
+ }
272
+ }
273
+
274
+ export function validateNativeProviderConfig(value: unknown): void {
275
+ if (value === undefined) return;
276
+ try {
277
+ const native = dataRecord(value, "native", NATIVE_PROVIDER_FIELDS);
278
+ if (native.network !== undefined) parseNativeEgressPolicy(native.network);
279
+ } catch (error) {
280
+ if (error instanceof NativeEgressPolicyValidationError) throw error;
281
+ throw new NativeEgressPolicyValidationError(
282
+ "Native provider config could not be inspected safely",
283
+ );
284
+ }
285
+ }
package/src/provider.ts CHANGED
@@ -37,6 +37,7 @@ export {
37
37
  } from "./define.js";
38
38
  export {
39
39
  AuthError,
40
+ HttpRedirectError,
40
41
  isProviderError,
41
42
  isSessionExpiredError,
42
43
  isTransportError,
@@ -91,6 +92,9 @@ export type {
91
92
  HealthJourneyRunContext,
92
93
  HealthJourneyRunResult,
93
94
  HealthScheduleRandomization,
95
+ HttpRedirectFailureReason,
96
+ HttpRedirectPolicy,
97
+ HttpRedirectPolicyMode,
94
98
  HttpRetryOptions,
95
99
  HttpRetrySummary,
96
100
  InferSchemaOutput,
@@ -119,6 +123,7 @@ export type {
119
123
  OperationDefinition,
120
124
  OperationDocMeta,
121
125
  OperationErrorCode,
126
+ ProviderErrorStatus,
122
127
  OperationInputExample,
123
128
  OperationLifecycle,
124
129
  OperationObservabilityConfig,
@@ -150,6 +155,7 @@ export type {
150
155
  ProviderStateDurationString,
151
156
  ProviderStateNamespace,
152
157
  ProviderSupportLevel,
158
+ RedirectRunReason,
153
159
  SchemaLike,
154
160
  SmsOtpMatcherDefinition,
155
161
  StandardSchemaV1,
@@ -161,6 +167,8 @@ export type {
161
167
  export {
162
168
  createNativeNetworkClient,
163
169
  deriveNativeCredentialAffinityKey,
170
+ NativeEgressGrantExpiredError,
171
+ NativeEgressNotDeclaredError,
164
172
  NativeIdleTimeoutError,
165
173
  NativeNetworkError,
166
174
  NativeProxyExpiredError,