@llm4ts/shell 3.0.0 → 3.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.
@@ -1,301 +1,4 @@
1
- import { readFile, readdir } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import * as Effect from "effect/Effect";
4
- import * as Redacted from "effect/Redacted";
5
- import * as Schema from "effect/Schema";
6
- // The auth profile, `.llm4ts/soap/<service>/auth.json` (gitignored). It holds
7
- // references only — `env:NAME` or `file:path` — never a secret value; a
8
- // literal where a secret belongs is a decode error. References are resolved
9
- // at call time into `Redacted` values that live inside the transport; no
10
- // secret reaches arguments, logs, traces, persisted files, or error
11
- // messages (errors name the reference, never its value).
12
- export const Environment = Schema.Literals(["dev", "test", "uat"]);
13
- /** `env:NAME` or `file:path`. */
14
- export const SecretRef = Schema.String.check(Schema.isPattern(/^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+)$/, {
15
- message: "must be a reference, env:NAME or file:path — never the secret itself"
16
- }));
17
- /** A username may be written literally or referenced. */
18
- export const Principal = Schema.String;
19
- export class BasicAuth extends Schema.Class("BasicAuth")({
20
- scheme: Schema.Literal("basic"),
21
- user: Principal,
22
- password: SecretRef
23
- }) {
24
- }
25
- export class BearerAuth extends Schema.Class("BearerAuth")({
26
- scheme: Schema.Literal("bearer"),
27
- token: SecretRef
28
- }) {
29
- }
30
- export class NoAuth extends Schema.Class("NoAuth")({
31
- scheme: Schema.Literal("none")
32
- }) {
33
- }
34
- export const HttpAuth = Schema.Union([NoAuth, BasicAuth, BearerAuth]);
35
- /** How the profile's CA material combines with Node's system roots. */
36
- export const TlsTrust = Schema.Literals(["system+ca", "ca-only"]);
37
- /**
38
- * Client TLS: PEM cert+key, or a PKCS#12 bundle; CA material as a PEM file
39
- * (`ca`) and/or a directory of PEMs (`caDir`), added to the system roots
40
- * unless `trust` is `ca-only`; `servername` for a host behind a front door.
41
- */
42
- export class TlsConfig extends Schema.Class("TlsConfig")({
43
- cert: Schema.optionalKey(SecretRef),
44
- key: Schema.optionalKey(SecretRef),
45
- pfx: Schema.optionalKey(SecretRef),
46
- passphrase: Schema.optionalKey(SecretRef),
47
- ca: Schema.optionalKey(SecretRef),
48
- caDir: Schema.optionalKey(Schema.String),
49
- trust: Schema.optionalKey(TlsTrust),
50
- servername: Schema.optionalKey(Schema.String)
51
- }) {
52
- }
53
- const ProxyUrl = Schema.String.check(Schema.isPattern(/^https?:\/\/[^/?#@]+\/?$/i, {
54
- message: "an http(s) proxy origin without credentials or path; credentials go in auth"
55
- }));
56
- /**
57
- * An explicit HTTP CONNECT proxy for one side, with the hosts that bypass
58
- * it (`*.suffix` wildcards). Environment proxy variables are never read.
59
- */
60
- export class ProxyConfig extends Schema.Class("ProxyConfig")({
61
- url: ProxyUrl,
62
- noProxy: Schema.optionalKey(Schema.Array(Schema.String)),
63
- auth: Schema.optionalKey(BasicAuth)
64
- }) {
65
- }
66
- export const ProxySetting = Schema.Union([Schema.Literal("none"), ProxyConfig]);
67
- export class HttpSide extends Schema.Class("HttpSide")({
68
- auth: Schema.optionalKey(HttpAuth),
69
- tls: Schema.optionalKey(TlsConfig),
70
- proxy: Schema.optionalKey(ProxySetting)
71
- }) {
72
- }
73
- /** The credential the STS request template is filled with. */
74
- export class StsCredential extends Schema.Class("StsCredential")({
75
- user: Principal,
76
- password: SecretRef
77
- }) {
78
- }
79
- /**
80
- * A SAML bearer token from an STS: the template under the service folder
81
- * is filled and posted to `endpoint` with this side's auth, TLS and proxy;
82
- * the first element named `token.element` in the answer is carried, bytes
83
- * unchanged, in every call's WS-Security header.
84
- */
85
- export class StsConfig extends Schema.Class("StsConfig")({
86
- endpoint: Schema.String.check(Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
87
- message: "an http(s) URL without credentials; secrets go in references"
88
- })),
89
- soapVersion: Schema.optionalKey(Schema.Literals(["1.1", "1.2"])),
90
- /** Relative to the service folder; `sts init` writes the default. */
91
- template: Schema.optionalKey(Schema.String),
92
- auth: StsCredential,
93
- appliesTo: Schema.optionalKey(Schema.String),
94
- token: Schema.optionalKey(Schema.Struct({ element: Schema.optionalKey(Schema.String) })),
95
- renewBeforeSeconds: Schema.optionalKey(Schema.Int),
96
- timestamp: Schema.optionalKey(Schema.Boolean),
97
- tls: Schema.optionalKey(TlsConfig),
98
- proxy: Schema.optionalKey(ProxySetting),
99
- timeoutSeconds: Schema.optionalKey(Schema.Int)
100
- }) {
101
- }
102
- export const defaultStsTemplate = "sts.request.xml";
103
- export const defaultTokenElement = "Assertion";
104
- export class UsernameToken extends Schema.Class("UsernameToken")({
105
- user: Principal,
106
- password: SecretRef,
107
- passwordType: Schema.Literals(["text", "digest"])
108
- }) {
109
- }
110
- export const MutatingPolicy = Schema.Literals(["confirm", "flag", "deny"]);
111
- export class MutatingPolicies extends Schema.Class("MutatingPolicies")({
112
- dev: Schema.optionalKey(MutatingPolicy),
113
- test: Schema.optionalKey(MutatingPolicy),
114
- uat: Schema.optionalKey(MutatingPolicy)
115
- }) {
116
- }
117
- export class AuthProfile extends Schema.Class("AuthProfile")({
118
- environment: Environment,
119
- /** Overrides the WSDL's address for calls (the WSDL often names another environment). */
120
- endpoint: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
121
- message: "an http(s) URL without credentials; secrets go in references"
122
- }))),
123
- /** Fetching the WSDL and its schemas. */
124
- fetch: Schema.optionalKey(HttpSide),
125
- /** Calling operations. */
126
- call: Schema.optionalKey(HttpSide),
127
- wsSecurity: Schema.optionalKey(UsernameToken),
128
- /** A SAML bearer token from an STS, carried by every call. */
129
- sts: Schema.optionalKey(StsConfig),
130
- mutating: Schema.optionalKey(MutatingPolicies),
131
- timeoutSeconds: Schema.optionalKey(Schema.Int)
132
- }) {
133
- }
134
- /** `auth.json`, or `auth.<env>.json` when an environment is selected. */
135
- export const profileFileName = (env) => env === undefined || env.trim() === "" ? "auth.json" : `auth.${env.trim()}.json`;
136
- export const defaultMutatingPolicy = (environment) => environment === "dev" ? "confirm" : "flag";
137
- export const mutatingPolicy = (profile) => profile.mutating?.[profile.environment] ?? defaultMutatingPolicy(profile.environment);
138
- export class AuthProfileError extends Schema.TaggedError()("AuthProfileError", {
139
- /** The reference or field involved; never a secret value. */
140
- subject: Schema.String,
141
- detail: Schema.String
142
- }) {
143
- get message() {
144
- return `auth profile: ${this.subject}: ${this.detail}`;
145
- }
146
- }
147
- export const decodeAuthProfile = (text, file = "auth.json") => Schema.decodeUnknownEffect(Schema.fromJsonString(AuthProfile))(text).pipe(Effect.mapError((error) =>
148
- // Schema issues quote the offending input; a mistyped secret could be
149
- // in it, so only the paths of the issue are kept.
150
- new AuthProfileError({
151
- subject: file,
152
- detail: `invalid profile (${issuePaths(error.message)})`
153
- })));
154
- /** Keep only the `at ["a"]["b"]` locations of a schema message, dropping any quoted value. */
155
- const issuePaths = (message) => {
156
- const paths = [...message.matchAll(/at ((?:\[[^\]]*\])+)/g)].map((match) => [...(match[1] ?? "").matchAll(/\["?([^"\]]*)"?\]/g)].map((part) => part[1] ?? "").join("."));
157
- return paths.length === 0
158
- ? "see the soap-ace README for the profile shape"
159
- : `at ${[...new Set(paths)].join(", ")}; secrets must be env:NAME or file:path references`;
160
- };
161
- export const resolveSecret = (source, reference) => {
162
- if (reference.startsWith("env:")) {
163
- const name = reference.slice(4);
164
- const value = source.environment[name];
165
- return value === undefined || value === ""
166
- ? Effect.fail(new AuthProfileError({ subject: reference, detail: "variable is not set" }))
167
- : Effect.succeed(Redacted.make(new TextEncoder().encode(value)));
168
- }
169
- if (reference.startsWith("file:")) {
170
- return Effect.map(source.readFile(reference.slice(5)), (bytes) => Redacted.make(bytes));
171
- }
172
- return Effect.fail(new AuthProfileError({ subject: "reference", detail: "not env: or file:" }));
173
- };
174
- export const resolveText = (source, reference) => Effect.map(resolveSecret(source, reference), (secret) => Redacted.make(new TextDecoder().decode(Redacted.value(secret)).replace(/\r?\n$/, "")));
175
- /** A principal: resolved when it is a reference, else the literal. */
176
- export const resolvePrincipal = (source, value) => value.startsWith("env:") || value.startsWith("file:")
177
- ? Effect.map(resolveText(source, value), Redacted.value)
178
- : Effect.succeed(value);
179
- const optionalSecret = (source, name, reference) => reference === undefined
180
- ? Effect.succeed({})
181
- : Effect.map(resolveSecret(source, reference), (value) => ({ [name]: value }));
182
- export const resolveTls = (source, tls) => tls === undefined
183
- ? Effect.succeed(undefined)
184
- : Effect.gen(function* () {
185
- if (tls.pfx !== undefined && (tls.cert !== undefined || tls.key !== undefined)) {
186
- return yield* new AuthProfileError({
187
- subject: "tls",
188
- detail: "use either pfx or cert+key, not both"
189
- });
190
- }
191
- if ((tls.cert === undefined) !== (tls.key === undefined)) {
192
- return yield* new AuthProfileError({
193
- subject: "tls",
194
- detail: "cert and key go together"
195
- });
196
- }
197
- const cert = yield* optionalSecret(source, "cert", tls.cert);
198
- const key = yield* optionalSecret(source, "key", tls.key);
199
- const pfx = yield* optionalSecret(source, "pfx", tls.pfx);
200
- const caFile = tls.ca === undefined ? undefined : Redacted.value(yield* resolveSecret(source, tls.ca));
201
- let caDir;
202
- if (tls.caDir !== undefined) {
203
- if (source.readPemDirectory === undefined) {
204
- return yield* new AuthProfileError({
205
- subject: "tls.caDir",
206
- detail: "this source cannot read a directory"
207
- });
208
- }
209
- caDir = yield* source.readPemDirectory(tls.caDir);
210
- }
211
- const ca = caFile === undefined && caDir === undefined
212
- ? {}
213
- : { ca: Redacted.make(concatPem(caFile, caDir)) };
214
- const passphrase = tls.passphrase === undefined
215
- ? {}
216
- : { passphrase: yield* resolveText(source, tls.passphrase) };
217
- return {
218
- ...cert,
219
- ...key,
220
- ...pfx,
221
- ...ca,
222
- ...passphrase,
223
- ...(tls.trust === undefined ? {} : { trust: tls.trust }),
224
- ...(tls.servername === undefined ? {} : { servername: tls.servername })
225
- };
226
- });
227
- const concatPem = (...parts) => {
228
- const present = parts.filter((part) => part !== undefined);
229
- const joined = present.map((part) => new TextDecoder().decode(part).trimEnd()).join("\n");
230
- return new TextEncoder().encode(`${joined}\n`);
231
- };
232
- /** Whether a host bypasses the proxy: exact match, or `*.suffix` / `.suffix`. */
233
- export const bypassesProxy = (host, noProxy) => {
234
- const lower = host.toLowerCase();
235
- return noProxy.some((entry) => {
236
- const pattern = entry.trim().toLowerCase();
237
- if (pattern === "")
238
- return false;
239
- if (pattern === "*")
240
- return true;
241
- if (pattern.startsWith("*.") || pattern.startsWith(".")) {
242
- const suffix = pattern.replace(/^\*/, "");
243
- return lower.endsWith(suffix) && lower.length > suffix.length;
244
- }
245
- return lower === pattern;
246
- });
247
- };
248
- export const resolveProxy = (source, proxy) => proxy === undefined || proxy === "none"
249
- ? Effect.succeed(undefined)
250
- : Effect.gen(function* () {
251
- const authorization = proxy.auth === undefined
252
- ? {}
253
- : {
254
- authorization: basicHeader(yield* resolvePrincipal(source, proxy.auth.user), yield* resolveText(source, proxy.auth.password))
255
- };
256
- return { url: proxy.url, noProxy: proxy.noProxy ?? [], ...authorization };
257
- });
258
- const basicHeader = (user, password) => Redacted.make(`Basic ${Buffer.from(`${user}:${Redacted.value(password)}`, "utf8").toString("base64")}`);
259
- export const resolveSide = (source, side) => Effect.gen(function* () {
260
- const auth = side?.auth;
261
- const tls = yield* resolveTls(source, side?.tls);
262
- const proxy = yield* resolveProxy(source, side?.proxy);
263
- if (auth === undefined || auth.scheme === "none")
264
- return { headers: [], tls, proxy };
265
- if (auth.scheme === "basic") {
266
- const user = yield* resolvePrincipal(source, auth.user);
267
- const password = yield* resolveText(source, auth.password);
268
- return { headers: [["authorization", basicHeader(user, password)]], tls, proxy };
269
- }
270
- const token = yield* resolveText(source, auth.token);
271
- return {
272
- headers: [["authorization", Redacted.make(`Bearer ${Redacted.value(token)}`)]],
273
- tls,
274
- proxy
275
- };
276
- });
277
- export const resolveUsernameToken = (source, token) => token === undefined
278
- ? Effect.succeed(undefined)
279
- : Effect.gen(function* () {
280
- return {
281
- user: yield* resolvePrincipal(source, token.user),
282
- password: yield* resolveText(source, token.password),
283
- passwordType: token.passwordType
284
- };
285
- });
286
- /** Secrets from the process environment and local files. */
287
- export const nodeSecretSource = (environment = process.env) => ({
288
- environment,
289
- readFile: (path) => Effect.tryPromise({
290
- try: async () => new Uint8Array(await readFile(path)),
291
- catch: () => new AuthProfileError({ subject: `file:${path}`, detail: "not readable" })
292
- }),
293
- readPemDirectory: (path) => Effect.tryPromise({
294
- try: async () => {
295
- const names = (await readdir(path)).filter((name) => /\.(pem|crt|cer)$/i.test(name)).sort();
296
- const parts = await Promise.all(names.map((name) => readFile(join(path, name))));
297
- return concatPem(...parts.map((part) => new Uint8Array(part)));
298
- },
299
- catch: () => new AuthProfileError({ subject: `tls.caDir ${path}`, detail: "not readable" })
300
- })
301
- });
1
+ // Promoted to `@llm4ts/flow/endpoint/Auth` in 3.2.0 (ADR 0048): the
2
+ // endpoint profile, secret references, TLS and proxy resolution are no
3
+ // longer SOAP-specific. This module keeps the kit's import paths working.
4
+ export * from "@llm4ts/flow/endpoint/Auth";
@@ -1,309 +1,10 @@
1
- import * as http from "node:http";
2
- import * as https from "node:https";
3
- import * as net from "node:net";
4
- import * as tls from "node:tls";
5
- import * as Context from "effect/Context";
1
+ // Promoted to `@llm4ts/flow/endpoint/Transport` in 3.2.0 (ADR 0048); the
2
+ // discovery document loader stays here because it reads WSDLs.
6
3
  import * as Duration from "effect/Duration";
7
4
  import * as Effect from "effect/Effect";
8
- import * as Redacted from "effect/Redacted";
9
- import * as Ref from "effect/Ref";
10
- import * as Schema from "effect/Schema";
11
- import { bypassesProxy } from "./Auth.js";
5
+ import { displayUrl } from "@llm4ts/flow/endpoint/Transport";
12
6
  import { DocumentLoadError, makeFileDocumentLoader } from "./Wsdl.js";
13
- export class TransportError extends Schema.TaggedError()("TransportError", {
14
- url: Schema.String,
15
- reason: Schema.Literals(["scheme", "network", "tls", "timeout", "aborted", "proxy"]),
16
- detail: Schema.String
17
- }) {
18
- get message() {
19
- return `${this.url}: ${this.reason}: ${this.detail}`;
20
- }
21
- }
22
- export class SoapTransport extends Context.Service()("@llm4ts/kits/soap-ace/SoapTransport") {
23
- }
24
- /** Strip query string and credentials from a URL before it lands in an error or a file. */
25
- export const displayUrl = (raw) => {
26
- try {
27
- const url = new URL(raw);
28
- return `${url.protocol}//${url.host}${url.pathname}`;
29
- }
30
- catch {
31
- return "(invalid url)";
32
- }
33
- };
34
- const errorCode = (cause) => typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string"
35
- ? cause.code
36
- : "request failed";
37
- const tlsCodes = /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO|DEPTH_ZERO|ERR_OSSL/;
38
- const unknownIssuer = /SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|UNABLE_TO_GET_ISSUER|DEPTH_ZERO|CERT_UNTRUSTED|UNABLE_TO_GET_LOCAL_ISSUER/;
39
- export const trustHint = 'the chain is not trusted; capture it with soap-sample "trust <side>"';
40
- const describeTlsFailure = (code) => unknownIssuer.test(code) ? `${code} (${trustHint})` : code;
41
- class ProxyRefused extends Error {
42
- status;
43
- constructor(status) {
44
- super(`proxy refused the tunnel: HTTP ${status}`);
45
- this.status = status;
46
- }
47
- }
48
- const flatHeaders = (headers) => Object.fromEntries(Object.entries(headers).flatMap(([name, value]) => value === undefined ? [] : [[name, Array.isArray(value) ? value.join(", ") : value]]));
49
- const bufferOf = (secret) => secret === undefined ? undefined : Buffer.from(Redacted.value(secret));
50
- /** The CA list a connection verifies against: system roots plus the profile's, or the profile's alone. */
51
- export const caListFor = (resolved) => {
52
- if (resolved?.ca === undefined) {
53
- return undefined;
54
- }
55
- const own = new TextDecoder().decode(Redacted.value(resolved.ca));
56
- return resolved.trust === "ca-only" ? [own] : [...tls.rootCertificates, own];
57
- };
58
- const tlsOptionsOf = (resolved, host) => {
59
- const ca = caListFor(resolved);
60
- return {
61
- ...(resolved === undefined
62
- ? {}
63
- : {
64
- cert: bufferOf(resolved.cert),
65
- key: bufferOf(resolved.key),
66
- pfx: bufferOf(resolved.pfx),
67
- passphrase: resolved.passphrase === undefined ? undefined : Redacted.value(resolved.passphrase)
68
- }),
69
- // A pinned chain may hold only what the server sent (a leaf signed by a
70
- // CA it never presents): trust it as captured, not only self-signed roots.
71
- ...(ca === undefined ? {} : { ca: [...ca], allowPartialTrustChain: true }),
72
- servername: resolved?.servername ?? (net.isIP(host) === 0 ? host : undefined)
73
- };
74
- };
75
- const portOf = (url) => url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
76
- /** Whether this request goes through the proxy: configured and the host not excluded. */
77
- export const proxyFor = (url, proxy) => proxy === undefined || bypassesProxy(url.hostname, proxy.noProxy) ? undefined : proxy;
78
- /** An HTTP CONNECT tunnel to `target` through `proxy`; the raw socket, not yet TLS. */
79
- const connectTunnel = (proxy, target, signal) => new Promise((resolve, reject) => {
80
- const proxyUrl = new URL(proxy.url);
81
- const headers = { host: `${target.hostname}:${portOf(target)}` };
82
- if (proxy.authorization !== undefined) {
83
- headers["proxy-authorization"] = Redacted.value(proxy.authorization);
84
- }
85
- const request = http.request({
86
- host: proxyUrl.hostname,
87
- port: portOf(proxyUrl),
88
- method: "CONNECT",
89
- path: `${target.hostname}:${portOf(target)}`,
90
- headers,
91
- signal
92
- });
93
- request.on("connect", (response, socket) => {
94
- if (response.statusCode === 200) {
95
- resolve(socket);
96
- }
97
- else {
98
- socket.destroy();
99
- reject(new ProxyRefused(response.statusCode ?? 0));
100
- }
101
- });
102
- request.on("error", reject);
103
- request.end();
104
- });
105
- /** The socket a request runs on: direct, or through the tunnel; TLS-wrapped for https. */
106
- const openSocket = async (url, resolved, proxy, signal) => {
107
- const via = proxyFor(url, proxy);
108
- if (via === undefined) {
109
- return undefined;
110
- }
111
- const tunnel = await connectTunnel(via, url, signal);
112
- if (url.protocol !== "https:") {
113
- return tunnel;
114
- }
115
- return new Promise((resolve, reject) => {
116
- const secure = tls.connect({ ...tlsOptionsOf(resolved, url.hostname), socket: tunnel }, () => resolve(secure));
117
- secure.on("error", reject);
118
- });
119
- };
120
- const transportFailure = (shown, cause) => {
121
- if (cause instanceof ProxyRefused) {
122
- return new TransportError({ url: shown, reason: "proxy", detail: `HTTP ${cause.status}` });
123
- }
124
- const code = errorCode(cause);
125
- return new TransportError({
126
- url: shown,
127
- reason: code === "ABORT_ERR" ? "aborted" : tlsCodes.test(code) ? "tls" : "network",
128
- detail: tlsCodes.test(code) ? describeTlsFailure(code) : code
129
- });
130
- };
131
- const withTimeout = (shown, timeout) => (effect) => effect.pipe(Effect.timeoutOrElse({
132
- duration: timeout,
133
- orElse: () => Effect.fail(new TransportError({
134
- url: shown,
135
- reason: "timeout",
136
- detail: `no response within ${Duration.format(timeout)}`
137
- }))
138
- }));
139
- const parseTarget = (raw, needsTls) => {
140
- const shown = displayUrl(raw);
141
- let url;
142
- try {
143
- url = new URL(raw);
144
- }
145
- catch {
146
- return new TransportError({ url: shown, reason: "scheme", detail: "invalid URL" });
147
- }
148
- if (url.protocol !== "https:" && url.protocol !== "http:") {
149
- return new TransportError({
150
- url: shown,
151
- reason: "scheme",
152
- detail: `${url.protocol} is not http(s)`
153
- });
154
- }
155
- if (url.protocol === "http:" && needsTls) {
156
- return new TransportError({
157
- url: shown,
158
- reason: "scheme",
159
- detail: "client TLS needs an https URL"
160
- });
161
- }
162
- return url;
163
- };
164
- const pemOf = (der) => `-----BEGIN CERTIFICATE-----\n${der
165
- .toString("base64")
166
- .replace(/(.{64})/g, "$1\n")
167
- .trimEnd()}\n-----END CERTIFICATE-----\n`;
168
- const nameOf = (subject) => Object.entries(subject ?? {})
169
- .map(([key, value]) => `${key}=${Array.isArray(value) ? value.join("+") : String(value)}`)
170
- .join(", ");
171
- /** Walk `issuerCertificate` links, leaf first, stopping at the self-signed root. */
172
- const chainOf = (leaf) => {
173
- const out = [];
174
- const seen = new Set();
175
- let current = leaf;
176
- while (current !== undefined && current.raw !== undefined && !seen.has(current.fingerprint256)) {
177
- seen.add(current.fingerprint256);
178
- out.push({
179
- subject: nameOf(current.subject),
180
- issuer: nameOf(current.issuer),
181
- validFrom: current.valid_from,
182
- validTo: current.valid_to,
183
- fingerprint256: current.fingerprint256,
184
- pem: pemOf(current.raw)
185
- });
186
- current = current.issuerCertificate === current ? undefined : current.issuerCertificate;
187
- }
188
- return out;
189
- };
190
- export const makeNodeSoapTransport = () => ({
191
- send: (request) => {
192
- const shown = displayUrl(request.url);
193
- const target = parseTarget(request.url, request.tls !== undefined);
194
- if (target instanceof TransportError) {
195
- return Effect.fail(target);
196
- }
197
- const url = target;
198
- const headers = { ...request.headers };
199
- for (const [name, value] of request.secretHeaders)
200
- headers[name] = Redacted.value(value);
201
- const body = request.body === undefined ? undefined : Buffer.from(Redacted.value(request.body), "utf8");
202
- if (body !== undefined)
203
- headers["content-length"] = String(body.length);
204
- return Effect.tryPromise({
205
- try: (signal) => {
206
- const started = performance.now();
207
- return openSocket(url, request.tls, request.proxy, signal).then((socket) => new Promise((resolve, reject) => {
208
- const options = {
209
- method: request.method,
210
- headers,
211
- signal,
212
- ...(url.protocol === "https:" ? tlsOptionsOf(request.tls, url.hostname) : {}),
213
- ...(socket === undefined ? {} : { createConnection: () => socket })
214
- };
215
- const handler = (response) => {
216
- const chunks = [];
217
- response.on("data", (chunk) => chunks.push(chunk));
218
- response.on("error", reject);
219
- response.on("end", () => resolve({
220
- status: response.statusCode ?? 0,
221
- headers: flatHeaders(response.headers),
222
- body: new Uint8Array(Buffer.concat(chunks)),
223
- elapsedMs: Math.round(performance.now() - started)
224
- }));
225
- };
226
- const outgoing = url.protocol === "https:"
227
- ? https.request(url, options, handler)
228
- : http.request(url, options, handler);
229
- outgoing.on("error", reject);
230
- if (body !== undefined)
231
- outgoing.write(body);
232
- outgoing.end();
233
- }));
234
- },
235
- catch: (cause) => transportFailure(shown, cause)
236
- }).pipe(withTimeout(shown, request.timeout));
237
- },
238
- peerChain: (raw, options) => {
239
- const shown = displayUrl(raw);
240
- const target = parseTarget(raw, false);
241
- if (target instanceof TransportError) {
242
- return Effect.fail(target);
243
- }
244
- const url = target;
245
- if (url.protocol !== "https:") {
246
- return Effect.fail(new TransportError({
247
- url: shown,
248
- reason: "scheme",
249
- detail: "only an https endpoint has a chain"
250
- }));
251
- }
252
- return Effect.tryPromise({
253
- try: (signal) => {
254
- const via = proxyFor(url, options.proxy);
255
- const tunnelled = via === undefined ? Promise.resolve(undefined) : connectTunnel(via, url, signal);
256
- return tunnelled.then((tunnel) => new Promise((resolve, reject) => {
257
- const socket = tls.connect({
258
- ...(tunnel === undefined
259
- ? { host: url.hostname, port: portOf(url) }
260
- : { socket: tunnel }),
261
- servername: options.servername ?? (net.isIP(url.hostname) === 0 ? url.hostname : undefined),
262
- rejectUnauthorized: false
263
- }, () => {
264
- const leaf = socket.getPeerCertificate(true);
265
- const chain = {
266
- host: url.hostname,
267
- certificates: chainOf(leaf),
268
- trustedBySystem: socket.authorized,
269
- authorizationError: socket.authorizationError === undefined || socket.authorizationError === null
270
- ? undefined
271
- : String(socket.authorizationError)
272
- };
273
- socket.end();
274
- resolve(chain);
275
- });
276
- socket.on("error", reject);
277
- signal.addEventListener("abort", () => socket.destroy());
278
- }));
279
- },
280
- catch: (cause) => transportFailure(shown, cause)
281
- }).pipe(withTimeout(shown, options.timeout));
282
- }
283
- });
284
- /**
285
- * A scripted transport for tests: each request goes to `respond`, and every
286
- * request is recorded (secrets still redacted) for assertions. `chain`
287
- * answers `peerChain`; by default an endpoint presents nothing.
288
- */
289
- export const makeFakeSoapTransport = (respond, chain = (url) => Effect.succeed({
290
- host: new URL(url).hostname,
291
- certificates: [],
292
- trustedBySystem: true,
293
- authorizationError: undefined
294
- })) => Effect.map(Ref.make([]), (log) => ({
295
- transport: {
296
- send: (request) => Effect.andThen(Ref.update(log, (all) => [...all, request]), respond(request)),
297
- peerChain: (url) => chain(url)
298
- },
299
- requests: Ref.get(log)
300
- }));
301
- export const xmlResponse = (xml, status = 200) => ({
302
- status,
303
- headers: { "content-type": "text/xml; charset=utf-8" },
304
- body: new TextEncoder().encode(xml),
305
- elapsedMs: 5
306
- });
7
+ export * from "@llm4ts/flow/endpoint/Transport";
307
8
  const isUrl = (location) => /^https?:\/\//i.test(location);
308
9
  /**
309
10
  * The document loader for discovery: local paths from disk, http(s) URLs
@@ -503,6 +503,37 @@ const operations20 = (discovery, rootLocation) => {
503
503
  * Discover a SOAP service: read the WSDL at `location` (a path or URL) with
504
504
  * every document it imports, and return its typed catalog.
505
505
  */
506
+ /**
507
+ * A catalog from a standalone XSD (imports and includes followed), with no
508
+ * endpoints or operations: what `xml-validate` checks a document against
509
+ * (ADR 0048). The root element's own namespace becomes the target namespace.
510
+ */
511
+ export const readSchemaCatalog = (location) => Effect.gen(function* () {
512
+ const loader = yield* DocumentLoader;
513
+ const rootLocation = isUrl(location) ? location : posix.normalize(location);
514
+ const discovery = new Discovery(loader);
515
+ const root = yield* discovery.load(rootLocation);
516
+ if (!is(root, XsdNamespace, "schema")) {
517
+ return yield* new WsdlError({
518
+ reason: "not-wsdl",
519
+ detail: `root element is {${root.name.namespace}}${root.name.local}, not xs:schema`,
520
+ location: safeLocation(rootLocation)
521
+ });
522
+ }
523
+ yield* discovery.schema(root, rootLocation, undefined);
524
+ const schemas = finishSchemas(discovery.schemas);
525
+ return new WsdlCatalog({
526
+ version: CatalogVersion,
527
+ wsdlVersion: "1.1",
528
+ targetNamespace: attribute(root, "targetNamespace") ?? "",
529
+ documents: discovery.documents,
530
+ endpoints: [],
531
+ operations: [],
532
+ elements: schemas.elements,
533
+ types: schemas.types,
534
+ openQuestions: [...schemas.questions, ...discovery.questions]
535
+ });
536
+ });
506
537
  export const readCatalog = (location) => Effect.gen(function* () {
507
538
  const loader = yield* DocumentLoader;
508
539
  if (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(location)) {