@llm4ts/flow 2.54.1 → 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.
Files changed (95) hide show
  1. package/dist/Activity.d.ts +1 -1
  2. package/dist/Activity.d.ts.map +1 -1
  3. package/dist/Activity.js +20 -0
  4. package/dist/Activity.js.map +1 -1
  5. package/dist/EstimatedUsage.d.ts.map +1 -1
  6. package/dist/EstimatedUsage.js +0 -1
  7. package/dist/EstimatedUsage.js.map +1 -1
  8. package/dist/Pack.d.ts +11 -0
  9. package/dist/Pack.d.ts.map +1 -1
  10. package/dist/Pack.js +2 -0
  11. package/dist/Pack.js.map +1 -1
  12. package/dist/Replay.d.ts.map +1 -1
  13. package/dist/Replay.js +1 -4
  14. package/dist/Replay.js.map +1 -1
  15. package/dist/RosterSeats.d.ts.map +1 -1
  16. package/dist/RosterSeats.js +0 -1
  17. package/dist/RosterSeats.js.map +1 -1
  18. package/dist/Timing.d.ts.map +1 -1
  19. package/dist/Timing.js +0 -1
  20. package/dist/Timing.js.map +1 -1
  21. package/dist/Transcript.d.ts.map +1 -1
  22. package/dist/Transcript.js +0 -1
  23. package/dist/Transcript.js.map +1 -1
  24. package/dist/TransientRetry.d.ts.map +1 -1
  25. package/dist/TransientRetry.js +0 -1
  26. package/dist/TransientRetry.js.map +1 -1
  27. package/dist/endpoint/Auth.d.ts +194 -0
  28. package/dist/endpoint/Auth.d.ts.map +1 -0
  29. package/dist/endpoint/Auth.js +302 -0
  30. package/dist/endpoint/Auth.js.map +1 -0
  31. package/dist/endpoint/Endpoints.d.ts +21 -0
  32. package/dist/endpoint/Endpoints.d.ts.map +1 -0
  33. package/dist/endpoint/Endpoints.js +34 -0
  34. package/dist/endpoint/Endpoints.js.map +1 -0
  35. package/dist/endpoint/Transport.d.ts +90 -0
  36. package/dist/endpoint/Transport.d.ts.map +1 -0
  37. package/dist/endpoint/Transport.js +306 -0
  38. package/dist/endpoint/Transport.js.map +1 -0
  39. package/dist/tools/Builtin.d.ts +5 -0
  40. package/dist/tools/Builtin.d.ts.map +1 -0
  41. package/dist/tools/Builtin.js +7 -0
  42. package/dist/tools/Builtin.js.map +1 -0
  43. package/dist/tools/Diff.d.ts +8 -0
  44. package/dist/tools/Diff.d.ts.map +1 -0
  45. package/dist/tools/Diff.js +45 -0
  46. package/dist/tools/Diff.js.map +1 -0
  47. package/dist/tools/HttpCall.d.ts +14 -0
  48. package/dist/tools/HttpCall.d.ts.map +1 -0
  49. package/dist/tools/HttpCall.js +101 -0
  50. package/dist/tools/HttpCall.js.map +1 -0
  51. package/dist/tools/JsonSchemaCheck.d.ts +36 -0
  52. package/dist/tools/JsonSchemaCheck.d.ts.map +1 -0
  53. package/dist/tools/JsonSchemaCheck.js +342 -0
  54. package/dist/tools/JsonSchemaCheck.js.map +1 -0
  55. package/dist/tools/JsonValidate.d.ts +11 -0
  56. package/dist/tools/JsonValidate.d.ts.map +1 -0
  57. package/dist/tools/JsonValidate.js +84 -0
  58. package/dist/tools/JsonValidate.js.map +1 -0
  59. package/dist/tools/Tool.d.ts +126 -0
  60. package/dist/tools/Tool.d.ts.map +1 -0
  61. package/dist/tools/Tool.js +218 -0
  62. package/dist/tools/Tool.js.map +1 -0
  63. package/dist/tools/TreeDiff.d.ts +42 -0
  64. package/dist/tools/TreeDiff.d.ts.map +1 -0
  65. package/dist/tools/TreeDiff.js +276 -0
  66. package/dist/tools/TreeDiff.js.map +1 -0
  67. package/package.json +12 -4
  68. package/src/Activity.ts +22 -0
  69. package/src/EstimatedUsage.ts +0 -1
  70. package/src/Pack.ts +16 -0
  71. package/src/Replay.ts +1 -7
  72. package/src/RosterSeats.ts +0 -2
  73. package/src/Timing.ts +0 -10
  74. package/src/Transcript.ts +0 -1
  75. package/src/TransientRetry.ts +0 -2
  76. package/src/endpoint/Auth.ts +446 -0
  77. package/src/endpoint/Endpoints.ts +54 -0
  78. package/src/endpoint/Transport.ts +456 -0
  79. package/src/tools/Builtin.ts +10 -0
  80. package/src/tools/Diff.ts +61 -0
  81. package/src/tools/HttpCall.ts +124 -0
  82. package/src/tools/JsonSchemaCheck.ts +457 -0
  83. package/src/tools/JsonValidate.ts +106 -0
  84. package/src/tools/Tool.ts +351 -0
  85. package/src/tools/TreeDiff.ts +386 -0
  86. package/dist/WorkspaceLayout.d.ts +0 -3
  87. package/dist/WorkspaceLayout.d.ts.map +0 -1
  88. package/dist/WorkspaceLayout.js +0 -19
  89. package/dist/WorkspaceLayout.js.map +0 -1
  90. package/dist/WorkspaceTools.d.ts +0 -4
  91. package/dist/WorkspaceTools.d.ts.map +0 -1
  92. package/dist/WorkspaceTools.js +0 -130
  93. package/dist/WorkspaceTools.js.map +0 -1
  94. package/src/WorkspaceLayout.ts +0 -22
  95. package/src/WorkspaceTools.ts +0 -188
@@ -0,0 +1,446 @@
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
+
7
+ // The auth profile, `.llm4ts/soap/<service>/auth.json` (gitignored). It holds
8
+ // references only — `env:NAME` or `file:path` — never a secret value; a
9
+ // literal where a secret belongs is a decode error. References are resolved
10
+ // at call time into `Redacted` values that live inside the transport; no
11
+ // secret reaches arguments, logs, traces, persisted files, or error
12
+ // messages (errors name the reference, never its value).
13
+
14
+ export const Environment = Schema.Literals(["dev", "test", "uat"])
15
+ export type Environment = typeof Environment.Type
16
+
17
+ /** `env:NAME` or `file:path`. */
18
+ export const SecretRef = Schema.String.check(
19
+ Schema.isPattern(/^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+)$/, {
20
+ message: "must be a reference, env:NAME or file:path — never the secret itself"
21
+ })
22
+ )
23
+
24
+ /** A username may be written literally or referenced. */
25
+ export const Principal = Schema.String
26
+
27
+ export class BasicAuth extends Schema.Class<BasicAuth>("BasicAuth")({
28
+ scheme: Schema.Literal("basic"),
29
+ user: Principal,
30
+ password: SecretRef
31
+ }) {}
32
+
33
+ export class BearerAuth extends Schema.Class<BearerAuth>("BearerAuth")({
34
+ scheme: Schema.Literal("bearer"),
35
+ token: SecretRef
36
+ }) {}
37
+
38
+ export class NoAuth extends Schema.Class<NoAuth>("NoAuth")({
39
+ scheme: Schema.Literal("none")
40
+ }) {}
41
+
42
+ export const HttpAuth = Schema.Union([NoAuth, BasicAuth, BearerAuth])
43
+ export type HttpAuth = typeof HttpAuth.Type
44
+
45
+ /** How the profile's CA material combines with Node's system roots. */
46
+ export const TlsTrust = Schema.Literals(["system+ca", "ca-only"])
47
+ export type TlsTrust = typeof TlsTrust.Type
48
+
49
+ /**
50
+ * Client TLS: PEM cert+key, or a PKCS#12 bundle; CA material as a PEM file
51
+ * (`ca`) and/or a directory of PEMs (`caDir`), added to the system roots
52
+ * unless `trust` is `ca-only`; `servername` for a host behind a front door.
53
+ */
54
+ export class TlsConfig extends Schema.Class<TlsConfig>("TlsConfig")({
55
+ cert: Schema.optionalKey(SecretRef),
56
+ key: Schema.optionalKey(SecretRef),
57
+ pfx: Schema.optionalKey(SecretRef),
58
+ passphrase: Schema.optionalKey(SecretRef),
59
+ ca: Schema.optionalKey(SecretRef),
60
+ caDir: Schema.optionalKey(Schema.String),
61
+ trust: Schema.optionalKey(TlsTrust),
62
+ servername: Schema.optionalKey(Schema.String)
63
+ }) {}
64
+
65
+ const ProxyUrl = Schema.String.check(
66
+ Schema.isPattern(/^https?:\/\/[^/?#@]+\/?$/i, {
67
+ message: "an http(s) proxy origin without credentials or path; credentials go in auth"
68
+ })
69
+ )
70
+
71
+ /**
72
+ * An explicit HTTP CONNECT proxy for one side, with the hosts that bypass
73
+ * it (`*.suffix` wildcards). Environment proxy variables are never read.
74
+ */
75
+ export class ProxyConfig extends Schema.Class<ProxyConfig>("ProxyConfig")({
76
+ url: ProxyUrl,
77
+ noProxy: Schema.optionalKey(Schema.Array(Schema.String)),
78
+ auth: Schema.optionalKey(BasicAuth)
79
+ }) {}
80
+
81
+ export const ProxySetting = Schema.Union([Schema.Literal("none"), ProxyConfig])
82
+ export type ProxySetting = typeof ProxySetting.Type
83
+
84
+ export class HttpSide extends Schema.Class<HttpSide>("HttpSide")({
85
+ auth: Schema.optionalKey(HttpAuth),
86
+ tls: Schema.optionalKey(TlsConfig),
87
+ proxy: Schema.optionalKey(ProxySetting)
88
+ }) {}
89
+
90
+ /** The credential the STS request template is filled with. */
91
+ export class StsCredential extends Schema.Class<StsCredential>("StsCredential")({
92
+ user: Principal,
93
+ password: SecretRef
94
+ }) {}
95
+
96
+ /**
97
+ * A SAML bearer token from an STS: the template under the service folder
98
+ * is filled and posted to `endpoint` with this side's auth, TLS and proxy;
99
+ * the first element named `token.element` in the answer is carried, bytes
100
+ * unchanged, in every call's WS-Security header.
101
+ */
102
+ export class StsConfig extends Schema.Class<StsConfig>("StsConfig")({
103
+ endpoint: Schema.String.check(
104
+ Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
105
+ message: "an http(s) URL without credentials; secrets go in references"
106
+ })
107
+ ),
108
+ soapVersion: Schema.optionalKey(Schema.Literals(["1.1", "1.2"])),
109
+ /** Relative to the service folder; `sts init` writes the default. */
110
+ template: Schema.optionalKey(Schema.String),
111
+ auth: StsCredential,
112
+ appliesTo: Schema.optionalKey(Schema.String),
113
+ token: Schema.optionalKey(Schema.Struct({ element: Schema.optionalKey(Schema.String) })),
114
+ renewBeforeSeconds: Schema.optionalKey(Schema.Int),
115
+ timestamp: Schema.optionalKey(Schema.Boolean),
116
+ tls: Schema.optionalKey(TlsConfig),
117
+ proxy: Schema.optionalKey(ProxySetting),
118
+ timeoutSeconds: Schema.optionalKey(Schema.Int)
119
+ }) {}
120
+
121
+ export const defaultStsTemplate = "sts.request.xml"
122
+ export const defaultTokenElement = "Assertion"
123
+
124
+ export class UsernameToken extends Schema.Class<UsernameToken>("UsernameToken")({
125
+ user: Principal,
126
+ password: SecretRef,
127
+ passwordType: Schema.Literals(["text", "digest"])
128
+ }) {}
129
+
130
+ export const MutatingPolicy = Schema.Literals(["confirm", "flag", "deny"])
131
+ export type MutatingPolicy = typeof MutatingPolicy.Type
132
+
133
+ export class MutatingPolicies extends Schema.Class<MutatingPolicies>("MutatingPolicies")({
134
+ dev: Schema.optionalKey(MutatingPolicy),
135
+ test: Schema.optionalKey(MutatingPolicy),
136
+ uat: Schema.optionalKey(MutatingPolicy)
137
+ }) {}
138
+
139
+ export class AuthProfile extends Schema.Class<AuthProfile>("AuthProfile")({
140
+ environment: Environment,
141
+ /** Overrides the WSDL's address for calls (the WSDL often names another environment). */
142
+ endpoint: Schema.optionalKey(
143
+ Schema.String.check(
144
+ Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
145
+ message: "an http(s) URL without credentials; secrets go in references"
146
+ })
147
+ )
148
+ ),
149
+ /** Fetching the WSDL and its schemas. */
150
+ fetch: Schema.optionalKey(HttpSide),
151
+ /** Calling operations. */
152
+ call: Schema.optionalKey(HttpSide),
153
+ wsSecurity: Schema.optionalKey(UsernameToken),
154
+ /** A SAML bearer token from an STS, carried by every call. */
155
+ sts: Schema.optionalKey(StsConfig),
156
+ mutating: Schema.optionalKey(MutatingPolicies),
157
+ timeoutSeconds: Schema.optionalKey(Schema.Int)
158
+ }) {}
159
+
160
+ /** `auth.json`, or `auth.<env>.json` when an environment is selected. */
161
+ export const profileFileName = (env: string | undefined): string =>
162
+ env === undefined || env.trim() === "" ? "auth.json" : `auth.${env.trim()}.json`
163
+
164
+ export const defaultMutatingPolicy = (environment: Environment): MutatingPolicy =>
165
+ environment === "dev" ? "confirm" : "flag"
166
+
167
+ export const mutatingPolicy = (profile: AuthProfile): MutatingPolicy =>
168
+ profile.mutating?.[profile.environment] ?? defaultMutatingPolicy(profile.environment)
169
+
170
+ export class AuthProfileError extends Schema.TaggedError<AuthProfileError>()("AuthProfileError", {
171
+ /** The reference or field involved; never a secret value. */
172
+ subject: Schema.String,
173
+ detail: Schema.String
174
+ }) {
175
+ get message(): string {
176
+ return `auth profile: ${this.subject}: ${this.detail}`
177
+ }
178
+ }
179
+
180
+ export const decodeAuthProfile = (
181
+ text: string,
182
+ file = "auth.json"
183
+ ): Effect.Effect<AuthProfile, AuthProfileError> =>
184
+ Schema.decodeUnknownEffect(Schema.fromJsonString(AuthProfile))(text).pipe(
185
+ Effect.mapError(
186
+ (error) =>
187
+ // Schema issues quote the offending input; a mistyped secret could be
188
+ // in it, so only the paths of the issue are kept.
189
+ new AuthProfileError({
190
+ subject: file,
191
+ detail: `invalid profile (${issuePaths(error.message)})`
192
+ })
193
+ )
194
+ )
195
+
196
+ /** Keep only the `at ["a"]["b"]` locations of a schema message, dropping any quoted value. */
197
+ const issuePaths = (message: string): string => {
198
+ const paths = [...message.matchAll(/at ((?:\[[^\]]*\])+)/g)].map((match) =>
199
+ [...(match[1] ?? "").matchAll(/\["?([^"\]]*)"?\]/g)].map((part) => part[1] ?? "").join(".")
200
+ )
201
+ return paths.length === 0
202
+ ? "see the soap-ace README for the profile shape"
203
+ : `at ${[...new Set(paths)].join(", ")}; secrets must be env:NAME or file:path references`
204
+ }
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // Resolution
208
+
209
+ export interface SecretSource {
210
+ readonly environment: Readonly<Record<string, string | undefined>>
211
+ readonly readFile: (path: string) => Effect.Effect<Uint8Array, AuthProfileError>
212
+ /** The `.pem`/`.crt` files of a directory, concatenated; absent sources cannot use `caDir`. */
213
+ readonly readPemDirectory?: (path: string) => Effect.Effect<Uint8Array, AuthProfileError>
214
+ }
215
+
216
+ export const resolveSecret = (
217
+ source: SecretSource,
218
+ reference: string
219
+ ): Effect.Effect<Redacted.Redacted<Uint8Array>, AuthProfileError> => {
220
+ if (reference.startsWith("env:")) {
221
+ const name = reference.slice(4)
222
+ const value = source.environment[name]
223
+ return value === undefined || value === ""
224
+ ? Effect.fail(new AuthProfileError({ subject: reference, detail: "variable is not set" }))
225
+ : Effect.succeed(Redacted.make(new TextEncoder().encode(value)))
226
+ }
227
+ if (reference.startsWith("file:")) {
228
+ return Effect.map(source.readFile(reference.slice(5)), (bytes) => Redacted.make(bytes))
229
+ }
230
+ return Effect.fail(new AuthProfileError({ subject: "reference", detail: "not env: or file:" }))
231
+ }
232
+
233
+ export const resolveText = (
234
+ source: SecretSource,
235
+ reference: string
236
+ ): Effect.Effect<Redacted.Redacted<string>, AuthProfileError> =>
237
+ Effect.map(resolveSecret(source, reference), (secret) =>
238
+ Redacted.make(new TextDecoder().decode(Redacted.value(secret)).replace(/\r?\n$/, ""))
239
+ )
240
+
241
+ /** A principal: resolved when it is a reference, else the literal. */
242
+ export const resolvePrincipal = (
243
+ source: SecretSource,
244
+ value: string
245
+ ): Effect.Effect<string, AuthProfileError> =>
246
+ value.startsWith("env:") || value.startsWith("file:")
247
+ ? Effect.map(resolveText(source, value), Redacted.value)
248
+ : Effect.succeed(value)
249
+
250
+ export interface ResolvedTls {
251
+ readonly cert?: Redacted.Redacted<Uint8Array>
252
+ readonly key?: Redacted.Redacted<Uint8Array>
253
+ readonly pfx?: Redacted.Redacted<Uint8Array>
254
+ readonly passphrase?: Redacted.Redacted<string>
255
+ /** The profile's CA material, file and directory concatenated. */
256
+ readonly ca?: Redacted.Redacted<Uint8Array>
257
+ readonly trust?: TlsTrust
258
+ readonly servername?: string
259
+ }
260
+
261
+ export interface ResolvedProxy {
262
+ readonly url: string
263
+ readonly noProxy: ReadonlyArray<string>
264
+ /** `proxy-authorization`, when the proxy wants one. */
265
+ readonly authorization?: Redacted.Redacted<string>
266
+ }
267
+
268
+ export interface ResolvedSide {
269
+ /** Header name → value to send; values are secrets. */
270
+ readonly headers: ReadonlyArray<readonly [string, Redacted.Redacted<string>]>
271
+ readonly tls: ResolvedTls | undefined
272
+ readonly proxy: ResolvedProxy | undefined
273
+ }
274
+
275
+ const optionalSecret = <K extends string>(
276
+ source: SecretSource,
277
+ name: K,
278
+ reference: string | undefined
279
+ ) =>
280
+ reference === undefined
281
+ ? Effect.succeed({})
282
+ : Effect.map(resolveSecret(source, reference), (value) => ({ [name]: value }))
283
+
284
+ export const resolveTls = (
285
+ source: SecretSource,
286
+ tls: TlsConfig | undefined
287
+ ): Effect.Effect<ResolvedTls | undefined, AuthProfileError> =>
288
+ tls === undefined
289
+ ? Effect.succeed(undefined)
290
+ : Effect.gen(function* () {
291
+ if (tls.pfx !== undefined && (tls.cert !== undefined || tls.key !== undefined)) {
292
+ return yield* new AuthProfileError({
293
+ subject: "tls",
294
+ detail: "use either pfx or cert+key, not both"
295
+ })
296
+ }
297
+ if ((tls.cert === undefined) !== (tls.key === undefined)) {
298
+ return yield* new AuthProfileError({
299
+ subject: "tls",
300
+ detail: "cert and key go together"
301
+ })
302
+ }
303
+ const cert = yield* optionalSecret(source, "cert", tls.cert)
304
+ const key = yield* optionalSecret(source, "key", tls.key)
305
+ const pfx = yield* optionalSecret(source, "pfx", tls.pfx)
306
+ const caFile =
307
+ tls.ca === undefined ? undefined : Redacted.value(yield* resolveSecret(source, tls.ca))
308
+ let caDir: Uint8Array | undefined
309
+ if (tls.caDir !== undefined) {
310
+ if (source.readPemDirectory === undefined) {
311
+ return yield* new AuthProfileError({
312
+ subject: "tls.caDir",
313
+ detail: "this source cannot read a directory"
314
+ })
315
+ }
316
+ caDir = yield* source.readPemDirectory(tls.caDir)
317
+ }
318
+ const ca =
319
+ caFile === undefined && caDir === undefined
320
+ ? {}
321
+ : { ca: Redacted.make(concatPem(caFile, caDir)) }
322
+ const passphrase =
323
+ tls.passphrase === undefined
324
+ ? {}
325
+ : { passphrase: yield* resolveText(source, tls.passphrase) }
326
+ return {
327
+ ...cert,
328
+ ...key,
329
+ ...pfx,
330
+ ...ca,
331
+ ...passphrase,
332
+ ...(tls.trust === undefined ? {} : { trust: tls.trust }),
333
+ ...(tls.servername === undefined ? {} : { servername: tls.servername })
334
+ }
335
+ })
336
+
337
+ const concatPem = (...parts: ReadonlyArray<Uint8Array | undefined>): Uint8Array => {
338
+ const present = parts.filter((part): part is Uint8Array => part !== undefined)
339
+ const joined = present.map((part) => new TextDecoder().decode(part).trimEnd()).join("\n")
340
+ return new TextEncoder().encode(`${joined}\n`)
341
+ }
342
+
343
+ /** Whether a host bypasses the proxy: exact match, or `*.suffix` / `.suffix`. */
344
+ export const bypassesProxy = (host: string, noProxy: ReadonlyArray<string>): boolean => {
345
+ const lower = host.toLowerCase()
346
+ return noProxy.some((entry) => {
347
+ const pattern = entry.trim().toLowerCase()
348
+ if (pattern === "") return false
349
+ if (pattern === "*") return true
350
+ if (pattern.startsWith("*.") || pattern.startsWith(".")) {
351
+ const suffix = pattern.replace(/^\*/, "")
352
+ return lower.endsWith(suffix) && lower.length > suffix.length
353
+ }
354
+ return lower === pattern
355
+ })
356
+ }
357
+
358
+ export const resolveProxy = (
359
+ source: SecretSource,
360
+ proxy: ProxySetting | undefined
361
+ ): Effect.Effect<ResolvedProxy | undefined, AuthProfileError> =>
362
+ proxy === undefined || proxy === "none"
363
+ ? Effect.succeed(undefined)
364
+ : Effect.gen(function* () {
365
+ const authorization =
366
+ proxy.auth === undefined
367
+ ? {}
368
+ : {
369
+ authorization: basicHeader(
370
+ yield* resolvePrincipal(source, proxy.auth.user),
371
+ yield* resolveText(source, proxy.auth.password)
372
+ )
373
+ }
374
+ return { url: proxy.url, noProxy: proxy.noProxy ?? [], ...authorization }
375
+ })
376
+
377
+ const basicHeader = (
378
+ user: string,
379
+ password: Redacted.Redacted<string>
380
+ ): Redacted.Redacted<string> =>
381
+ Redacted.make(
382
+ `Basic ${Buffer.from(`${user}:${Redacted.value(password)}`, "utf8").toString("base64")}`
383
+ )
384
+
385
+ export const resolveSide = (
386
+ source: SecretSource,
387
+ side: HttpSide | undefined
388
+ ): Effect.Effect<ResolvedSide, AuthProfileError> =>
389
+ Effect.gen(function* () {
390
+ const auth = side?.auth
391
+ const tls = yield* resolveTls(source, side?.tls)
392
+ const proxy = yield* resolveProxy(source, side?.proxy)
393
+ if (auth === undefined || auth.scheme === "none") return { headers: [], tls, proxy }
394
+ if (auth.scheme === "basic") {
395
+ const user = yield* resolvePrincipal(source, auth.user)
396
+ const password = yield* resolveText(source, auth.password)
397
+ return { headers: [["authorization", basicHeader(user, password)]], tls, proxy }
398
+ }
399
+ const token = yield* resolveText(source, auth.token)
400
+ return {
401
+ headers: [["authorization", Redacted.make(`Bearer ${Redacted.value(token)}`)]],
402
+ tls,
403
+ proxy
404
+ }
405
+ })
406
+
407
+ export interface ResolvedUsernameToken {
408
+ readonly user: string
409
+ readonly password: Redacted.Redacted<string>
410
+ readonly passwordType: "text" | "digest"
411
+ }
412
+
413
+ export const resolveUsernameToken = (
414
+ source: SecretSource,
415
+ token: UsernameToken | undefined
416
+ ): Effect.Effect<ResolvedUsernameToken | undefined, AuthProfileError> =>
417
+ token === undefined
418
+ ? Effect.succeed(undefined)
419
+ : Effect.gen(function* () {
420
+ return {
421
+ user: yield* resolvePrincipal(source, token.user),
422
+ password: yield* resolveText(source, token.password),
423
+ passwordType: token.passwordType
424
+ }
425
+ })
426
+
427
+ /** Secrets from the process environment and local files. */
428
+ export const nodeSecretSource = (
429
+ environment: Readonly<Record<string, string | undefined>> = process.env
430
+ ): SecretSource => ({
431
+ environment,
432
+ readFile: (path) =>
433
+ Effect.tryPromise({
434
+ try: async () => new Uint8Array(await readFile(path)),
435
+ catch: () => new AuthProfileError({ subject: `file:${path}`, detail: "not readable" })
436
+ }),
437
+ readPemDirectory: (path) =>
438
+ Effect.tryPromise({
439
+ try: async () => {
440
+ const names = (await readdir(path)).filter((name) => /\.(pem|crt|cer)$/i.test(name)).sort()
441
+ const parts = await Promise.all(names.map((name) => readFile(join(path, name))))
442
+ return concatPem(...parts.map((part) => new Uint8Array(part)))
443
+ },
444
+ catch: () => new AuthProfileError({ subject: `tls.caDir ${path}`, detail: "not readable" })
445
+ })
446
+ })
@@ -0,0 +1,54 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Schema from "effect/Schema"
3
+ import type { PlainFileStoreShape } from "../Persistence.ts"
4
+ import type { AuthProfile, AuthProfileError } from "./Auth.ts"
5
+ import { decodeAuthProfile, profileFileName } from "./Auth.ts"
6
+
7
+ /**
8
+ * Named endpoints (ADR 0048, 3.2): `<project>/.llm4ts/endpoints/<name>/auth.json`,
9
+ * or `auth.<env>.json`, in the same shape as a SOAP service profile — the
10
+ * `endpoint` URL, a `call` side (auth, tls, proxy), optional `fetch`,
11
+ * `mutating`, `timeoutSeconds`. A tool is given a name and an environment,
12
+ * never a token: secrets stay `env:NAME` or `file:path` references.
13
+ */
14
+ export const endpointProfilePath = (
15
+ projectRoot: string,
16
+ name: string,
17
+ env: string | undefined
18
+ ): string => `${projectRoot}/.llm4ts/endpoints/${name}/${profileFileName(env)}`
19
+
20
+ export class EndpointError extends Schema.TaggedError<EndpointError>()("EndpointError", {
21
+ endpoint: Schema.String,
22
+ message: Schema.String
23
+ }) {}
24
+
25
+ const endpointNamePattern = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/iu
26
+
27
+ export const loadEndpointProfile = (
28
+ files: PlainFileStoreShape,
29
+ projectRoot: string,
30
+ name: string,
31
+ env: string | undefined
32
+ ): Effect.Effect<AuthProfile, EndpointError> =>
33
+ Effect.gen(function* () {
34
+ if (!endpointNamePattern.test(name)) {
35
+ return yield* new EndpointError({ endpoint: name, message: "not an endpoint name" })
36
+ }
37
+ const path = endpointProfilePath(projectRoot, name, env)
38
+ const text = yield* files
39
+ .read(path)
40
+ .pipe(
41
+ Effect.mapError((error) => new EndpointError({ endpoint: name, message: error.message }))
42
+ )
43
+ if (text === undefined) {
44
+ return yield* new EndpointError({
45
+ endpoint: name,
46
+ message: `no profile at ${path}; write it with at least {"environment": "dev", "endpoint": "https://…"}`
47
+ })
48
+ }
49
+ return yield* decodeAuthProfile(text, path).pipe(
50
+ Effect.mapError(
51
+ (error: AuthProfileError) => new EndpointError({ endpoint: name, message: error.message })
52
+ )
53
+ )
54
+ })