@effect/chat-teams 0.0.0 → 4.1.5
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.
- package/AGENTS.md +434 -0
- package/CLAUDE.md +434 -0
- package/LICENSE +21 -0
- package/README.md +116 -0
- package/ai-docs/README.md +44 -0
- package/ai-docs/package.json +36 -0
- package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
- package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
- package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
- package/ai-docs/src/01_effect/01_basics/index.md +7 -0
- package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
- package/ai-docs/src/01_effect/02_schema/index.md +7 -0
- package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
- package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
- package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
- package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
- package/ai-docs/src/01_effect/03_services/index.md +5 -0
- package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
- package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
- package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
- package/ai-docs/src/01_effect/04_errors/index.md +1 -0
- package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
- package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
- package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
- package/ai-docs/src/01_effect/05_resources/index.md +3 -0
- package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
- package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
- package/ai-docs/src/01_effect/06_running/index.md +1 -0
- package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
- package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
- package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
- package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
- package/ai-docs/src/03_stream/30_encoding.ts +163 -0
- package/ai-docs/src/03_stream/index.md +4 -0
- package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
- package/ai-docs/src/04_integration/index.md +5 -0
- package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
- package/ai-docs/src/05_batching/index.md +3 -0
- package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
- package/ai-docs/src/06_schedule/index.md +3 -0
- package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
- package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
- package/ai-docs/src/07_datetime/index.md +5 -0
- package/ai-docs/src/08_observability/10_logging.ts +66 -0
- package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
- package/ai-docs/src/08_observability/index.md +7 -0
- package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
- package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
- package/ai-docs/src/09_testing/index.md +1 -0
- package/ai-docs/src/10_predicate/01_basics.ts +14 -0
- package/ai-docs/src/10_predicate/index.md +9 -0
- package/ai-docs/src/40_sql/10_basics.ts +175 -0
- package/ai-docs/src/40_sql/index.md +6 -0
- package/ai-docs/src/50_http-client/10_basics.ts +102 -0
- package/ai-docs/src/50_http-client/index.md +3 -0
- package/ai-docs/src/51_http-server/10_basics.ts +118 -0
- package/ai-docs/src/51_http-server/20_testing.ts +100 -0
- package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
- package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
- package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
- package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
- package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
- package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
- package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
- package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
- package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
- package/ai-docs/src/51_http-server/index.md +3 -0
- package/ai-docs/src/52_graphql/10_basics.ts +117 -0
- package/ai-docs/src/52_graphql/20_testing.ts +45 -0
- package/ai-docs/src/52_graphql/30_batching.ts +118 -0
- package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
- package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
- package/ai-docs/src/52_graphql/index.md +6 -0
- package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
- package/ai-docs/src/60_child-process/index.md +3 -0
- package/ai-docs/src/70_cli/10_basics.ts +162 -0
- package/ai-docs/src/70_cli/index.md +5 -0
- package/ai-docs/src/71_ai/10_language-model.ts +156 -0
- package/ai-docs/src/71_ai/20_tools.ts +226 -0
- package/ai-docs/src/71_ai/30_chat.ts +158 -0
- package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
- package/ai-docs/src/71_ai/index.md +5 -0
- package/ai-docs/src/80_cluster/10_entities.ts +97 -0
- package/ai-docs/src/80_cluster/index.md +4 -0
- package/ai-docs/src/index.md +10 -0
- package/ai-docs/tsconfig.json +28 -0
- package/dist/TeamsChat.d.ts +318 -0
- package/dist/TeamsChat.d.ts.map +1 -0
- package/dist/TeamsChat.js +316 -0
- package/dist/TeamsChat.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/adapter.d.ts +2 -0
- package/dist/internal/adapter.d.ts.map +1 -0
- package/dist/internal/adapter.js +300 -0
- package/dist/internal/adapter.js.map +1 -0
- package/dist/internal/address.d.ts +2 -0
- package/dist/internal/address.d.ts.map +1 -0
- package/dist/internal/address.js +52 -0
- package/dist/internal/address.js.map +1 -0
- package/dist/internal/auth.d.ts +2 -0
- package/dist/internal/auth.d.ts.map +1 -0
- package/dist/internal/auth.js +142 -0
- package/dist/internal/auth.js.map +1 -0
- package/dist/internal/connector.d.ts +2 -0
- package/dist/internal/connector.d.ts.map +1 -0
- package/dist/internal/connector.js +173 -0
- package/dist/internal/connector.js.map +1 -0
- package/dist/internal/download.d.ts +5 -0
- package/dist/internal/download.d.ts.map +1 -0
- package/dist/internal/download.js +183 -0
- package/dist/internal/download.js.map +1 -0
- package/dist/internal/envelope.d.ts +2 -0
- package/dist/internal/envelope.d.ts.map +1 -0
- package/dist/internal/envelope.js +337 -0
- package/dist/internal/envelope.js.map +1 -0
- package/dist/internal/errors.d.ts +2 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/errors.js +113 -0
- package/dist/internal/errors.js.map +1 -0
- package/dist/internal/interactions.d.ts +2 -0
- package/dist/internal/interactions.d.ts.map +1 -0
- package/dist/internal/interactions.js +288 -0
- package/dist/internal/interactions.js.map +1 -0
- package/dist/internal/length.d.ts +2 -0
- package/dist/internal/length.d.ts.map +1 -0
- package/dist/internal/length.js +147 -0
- package/dist/internal/length.js.map +1 -0
- package/dist/internal/normalize.d.ts +2 -0
- package/dist/internal/normalize.d.ts.map +1 -0
- package/dist/internal/normalize.js +224 -0
- package/dist/internal/normalize.js.map +1 -0
- package/dist/internal/parse.d.ts +2 -0
- package/dist/internal/parse.d.ts.map +1 -0
- package/dist/internal/parse.js +33 -0
- package/dist/internal/parse.js.map +1 -0
- package/dist/internal/render.d.ts +2 -0
- package/dist/internal/render.d.ts.map +1 -0
- package/dist/internal/render.js +316 -0
- package/dist/internal/render.js.map +1 -0
- package/dist/internal/webhook.d.ts +2 -0
- package/dist/internal/webhook.d.ts.map +1 -0
- package/dist/internal/webhook.js +88 -0
- package/dist/internal/webhook.js.map +1 -0
- package/package.json +61 -1
- package/src/TeamsChat.ts +470 -0
- package/src/index.ts +12 -0
- package/src/internal/adapter.ts +351 -0
- package/src/internal/address.ts +67 -0
- package/src/internal/auth.ts +192 -0
- package/src/internal/connector.ts +253 -0
- package/src/internal/download.ts +277 -0
- package/src/internal/envelope.ts +427 -0
- package/src/internal/errors.ts +94 -0
- package/src/internal/interactions.ts +294 -0
- package/src/internal/length.ts +170 -0
- package/src/internal/normalize.ts +232 -0
- package/src/internal/parse.ts +41 -0
- package/src/internal/render.ts +318 -0
- package/src/internal/webhook.ts +117 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { retrySafe } from "effect/chat/ChatAdapter"
|
|
2
|
+
import type { ChatError, ChatErrorReason } from "effect/chat/ChatError"
|
|
3
|
+
import * as Clock from "effect/Clock"
|
|
4
|
+
import * as DateTime from "effect/DateTime"
|
|
5
|
+
import * as Duration from "effect/Duration"
|
|
6
|
+
import * as Effect from "effect/Effect"
|
|
7
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient"
|
|
8
|
+
import * as HttpClient from "effect/http/HttpClient"
|
|
9
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest"
|
|
10
|
+
import type * as HttpClientResponse from "effect/http/HttpClientResponse"
|
|
11
|
+
import * as Option from "effect/Option"
|
|
12
|
+
import * as Predicate from "effect/Predicate"
|
|
13
|
+
import * as Redacted from "effect/Redacted"
|
|
14
|
+
import type * as Schema from "effect/Schema"
|
|
15
|
+
import * as Semaphore from "effect/Semaphore"
|
|
16
|
+
import type { Cloud, Credentials } from "../TeamsChat.ts"
|
|
17
|
+
import * as Errors from "./errors.ts"
|
|
18
|
+
import { parseUrl } from "./parse.ts"
|
|
19
|
+
|
|
20
|
+
/** A cloud is privileged configuration: nothing in it is ever read from an activity. @internal */
|
|
21
|
+
export const publicCloud: Cloud = {
|
|
22
|
+
connectorUrl: "https://smba.trafficmanager.net/teams",
|
|
23
|
+
connectorHosts: ["smba.trafficmanager.net"],
|
|
24
|
+
openIdMetadataUrl: "https://login.botframework.com/v1/.well-known/openidconfiguration",
|
|
25
|
+
issuer: "https://api.botframework.com",
|
|
26
|
+
loginUrl: "https://login.microsoftonline.com",
|
|
27
|
+
connectorScope: "https://api.botframework.com/.default",
|
|
28
|
+
fileHostSuffixes: ["sharepoint.com"],
|
|
29
|
+
redirectHosts: []
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** How long before `expiresAt` a cached token is dropped. */
|
|
33
|
+
const refreshMargin = Duration.minutes(5)
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The trust step for a Connector base URL: `https:`, the default port, no
|
|
37
|
+
* userinfo and an exact host in the allowlist. Gives the URL without a
|
|
38
|
+
* trailing slash, or `undefined`.
|
|
39
|
+
*
|
|
40
|
+
* @internal
|
|
41
|
+
*/
|
|
42
|
+
export const trustedServiceUrl = (url: string, hosts: ReadonlyArray<string>): string | undefined => {
|
|
43
|
+
const parsed = parseUrl(url)
|
|
44
|
+
if (
|
|
45
|
+
parsed === undefined || parsed.protocol !== "https:" || parsed.port !== "" || parsed.username !== "" ||
|
|
46
|
+
parsed.password !== "" ||
|
|
47
|
+
parsed.search !== "" || parsed.hash !== "" || !hosts.includes(parsed.hostname)
|
|
48
|
+
) {
|
|
49
|
+
return undefined
|
|
50
|
+
}
|
|
51
|
+
return parsed.origin + parsed.pathname.replace(/\/+$/, "")
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Gets a token by client credentials, or from the consumer's provider, and
|
|
56
|
+
* caches it until five minutes before it expires. A token with no expiry is
|
|
57
|
+
* not cached.
|
|
58
|
+
*
|
|
59
|
+
* @internal
|
|
60
|
+
*/
|
|
61
|
+
export const makeTokens = (options: {
|
|
62
|
+
readonly http: HttpClient.HttpClient
|
|
63
|
+
readonly cloud: Cloud
|
|
64
|
+
readonly appId: string
|
|
65
|
+
readonly tenantId: string
|
|
66
|
+
readonly credentials: Credentials
|
|
67
|
+
}) => {
|
|
68
|
+
const cache = new Map<string, { readonly token: Redacted.Redacted<string>; readonly until: number }>()
|
|
69
|
+
const lock = Semaphore.makeUnsafe(1)
|
|
70
|
+
const fail = (reason: ChatErrorReason) => Effect.fail(Errors.chatError("token", reason))
|
|
71
|
+
|
|
72
|
+
const clientCredentials = (secret: Redacted.Redacted<string>) => (scope: string) =>
|
|
73
|
+
Effect.gen(function*() {
|
|
74
|
+
const url = `${options.cloud.loginUrl}/${encodeURIComponent(options.tenantId)}/oauth2/v2.0/token`
|
|
75
|
+
const request = HttpClientRequest.post(url).pipe(
|
|
76
|
+
HttpClientRequest.bodyUrlParams({
|
|
77
|
+
grant_type: "client_credentials",
|
|
78
|
+
client_id: options.appId,
|
|
79
|
+
client_secret: Redacted.value(secret),
|
|
80
|
+
scope
|
|
81
|
+
})
|
|
82
|
+
)
|
|
83
|
+
const response = yield* send(options.http, request, false, "token")
|
|
84
|
+
if (response.status !== 200) {
|
|
85
|
+
return yield* fail(Errors.reasonForStatus(response.status, { write: false }))
|
|
86
|
+
}
|
|
87
|
+
const json = yield* response.json.pipe(
|
|
88
|
+
Effect.catch((cause) => fail(Errors.invalidResponse(false, "invalid_json", cause)))
|
|
89
|
+
)
|
|
90
|
+
if (!Predicate.isObject(json) || typeof json.access_token !== "string" || json.access_token === "") {
|
|
91
|
+
return yield* fail(Errors.invalidResponse(false, "missing_access_token"))
|
|
92
|
+
}
|
|
93
|
+
const now = yield* Clock.currentTimeMillis
|
|
94
|
+
const expiresIn = typeof json.expires_in === "number" ? json.expires_in : Number(json.expires_in)
|
|
95
|
+
return {
|
|
96
|
+
token: Redacted.make(json.access_token),
|
|
97
|
+
...(Number.isFinite(expiresIn) && expiresIn > 0
|
|
98
|
+
? { expiresAt: DateTime.makeUnsafe(now + expiresIn * 1000) }
|
|
99
|
+
: {})
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
const provider = Redacted.isRedacted(options.credentials)
|
|
104
|
+
? clientCredentials(options.credentials)
|
|
105
|
+
: options.credentials
|
|
106
|
+
|
|
107
|
+
return (scope: string): Effect.Effect<Redacted.Redacted<string>, ChatError> =>
|
|
108
|
+
lock.withPermit(Effect.gen(function*() {
|
|
109
|
+
const now = yield* Clock.currentTimeMillis
|
|
110
|
+
const cached = cache.get(scope)
|
|
111
|
+
if (cached !== undefined && cached.until > now) return cached.token
|
|
112
|
+
cache.delete(scope)
|
|
113
|
+
const token = yield* retrySafe(provider(scope))
|
|
114
|
+
if (token.expiresAt !== undefined) {
|
|
115
|
+
const until = DateTime.toEpochMillis(token.expiresAt) - Duration.toMillis(refreshMargin)
|
|
116
|
+
if (until > now) cache.set(scope, { token: token.token, until })
|
|
117
|
+
}
|
|
118
|
+
return token.token
|
|
119
|
+
}))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The client with Fetch's redirects off, for every request it sends,
|
|
124
|
+
* including those made by code the adapter hands it to, such as the key set.
|
|
125
|
+
*
|
|
126
|
+
* @internal
|
|
127
|
+
*/
|
|
128
|
+
export const noRedirects = (http: HttpClient.HttpClient): HttpClient.HttpClient =>
|
|
129
|
+
HttpClient.transform(
|
|
130
|
+
http,
|
|
131
|
+
(effect) => Effect.provideService(effect, FetchHttpClient.RequestInit, { redirect: "manual" })
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The URL a request goes to, with its query parameters and without a hash.
|
|
136
|
+
*
|
|
137
|
+
* @internal
|
|
138
|
+
*/
|
|
139
|
+
export const effectiveUrl = (request: HttpClientRequest.HttpClientRequest): string | undefined => {
|
|
140
|
+
const url = Option.getOrUndefined(HttpClientRequest.toUrl(request))
|
|
141
|
+
if (url === undefined) return undefined
|
|
142
|
+
url.hash = ""
|
|
143
|
+
return url.href
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Sends one request with redirects off. A response from another URL than
|
|
148
|
+
* the request's, query included, means something followed a redirect, and
|
|
149
|
+
* is refused.
|
|
150
|
+
*
|
|
151
|
+
* @internal
|
|
152
|
+
*/
|
|
153
|
+
export const send = (
|
|
154
|
+
http: HttpClient.HttpClient,
|
|
155
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
156
|
+
write: boolean,
|
|
157
|
+
op: string
|
|
158
|
+
): Effect.Effect<HttpClientResponse.HttpClientResponse, ChatError> =>
|
|
159
|
+
noRedirects(http).execute(request).pipe(
|
|
160
|
+
Effect.catch((error) => Effect.fail(Errors.chatError(op, Errors.transport(write, error.reason._tag, error)))),
|
|
161
|
+
Effect.flatMap((response) =>
|
|
162
|
+
response.url !== effectiveUrl(request)
|
|
163
|
+
? Effect.fail(Errors.chatError(op, Errors.untrustedUrl()))
|
|
164
|
+
: Effect.succeed(response)
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
/** @internal */
|
|
169
|
+
export interface CallOptions {
|
|
170
|
+
readonly write?: boolean | undefined
|
|
171
|
+
readonly retry?: boolean | undefined
|
|
172
|
+
/**
|
|
173
|
+
* The activity's own `serviceUrl`, for an op tied to an inbound activity.
|
|
174
|
+
* It is checked against the allowlist before a token is attached. Absent,
|
|
175
|
+
* the cloud's global Connector URL is used.
|
|
176
|
+
*/
|
|
177
|
+
readonly serviceUrl?: string | undefined
|
|
178
|
+
readonly query?: Readonly<Record<string, string>> | undefined
|
|
179
|
+
/** The op for the error. Default: the method and path. */
|
|
180
|
+
readonly op?: string | undefined
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** @internal */
|
|
184
|
+
export interface Connector {
|
|
185
|
+
readonly call: (
|
|
186
|
+
method: "GET" | "POST" | "PUT" | "DELETE",
|
|
187
|
+
path: string,
|
|
188
|
+
body: unknown,
|
|
189
|
+
options?: CallOptions | undefined
|
|
190
|
+
) => Effect.Effect<Schema.Json | undefined, ChatError>
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The Connector client. `path` starts with `/v3/` and has its segments
|
|
195
|
+
* encoded by the caller.
|
|
196
|
+
*
|
|
197
|
+
* @internal
|
|
198
|
+
*/
|
|
199
|
+
export const make = (options: {
|
|
200
|
+
readonly http: HttpClient.HttpClient
|
|
201
|
+
readonly cloud: Cloud
|
|
202
|
+
readonly token: (scope: string) => Effect.Effect<Redacted.Redacted<string>, ChatError>
|
|
203
|
+
}): Connector => {
|
|
204
|
+
const once = (
|
|
205
|
+
method: "GET" | "POST" | "PUT" | "DELETE",
|
|
206
|
+
path: string,
|
|
207
|
+
body: unknown,
|
|
208
|
+
callOptions: CallOptions | undefined
|
|
209
|
+
): Effect.Effect<Schema.Json | undefined, ChatError> => {
|
|
210
|
+
const write = callOptions?.write === true
|
|
211
|
+
const op = callOptions?.op ?? `${method} ${path.split("/").slice(0, 3).join("/")}`
|
|
212
|
+
const fail = (reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
|
|
213
|
+
return Effect.gen(function*() {
|
|
214
|
+
const base = callOptions?.serviceUrl === undefined
|
|
215
|
+
? options.cloud.connectorUrl
|
|
216
|
+
: trustedServiceUrl(callOptions.serviceUrl, options.cloud.connectorHosts)
|
|
217
|
+
if (base === undefined) return yield* fail(Errors.untrustedUrl())
|
|
218
|
+
const token = yield* Effect.mapError(options.token(options.cloud.connectorScope), Errors.withOp(op))
|
|
219
|
+
let request = HttpClientRequest.make(method)(base + path).pipe(
|
|
220
|
+
HttpClientRequest.bearerToken(Redacted.value(token)),
|
|
221
|
+
HttpClientRequest.setHeader("accept", "application/json")
|
|
222
|
+
)
|
|
223
|
+
if (callOptions?.query !== undefined) request = HttpClientRequest.setUrlParams(request, callOptions.query)
|
|
224
|
+
if (body !== undefined) request = HttpClientRequest.bodyJsonUnsafe(request, body)
|
|
225
|
+
const response = yield* send(options.http, request, write, op)
|
|
226
|
+
const retryAfter = Errors.parseRetryAfter(response.headers["retry-after"])
|
|
227
|
+
if (response.status < 200 || response.status >= 300) {
|
|
228
|
+
const json = yield* Effect.orElseSucceed(response.json, () => undefined)
|
|
229
|
+
const error = Predicate.isObject(json) && Predicate.isObject(json.error) ? json.error : undefined
|
|
230
|
+
const code = typeof error?.code === "string" ? error.code : undefined
|
|
231
|
+
return yield* fail(Errors.reasonForStatus(response.status, { write, retryAfter, code }))
|
|
232
|
+
}
|
|
233
|
+
const text = yield* response.text.pipe(
|
|
234
|
+
Effect.catch((cause) => fail(Errors.invalidResponse(write, "invalid_body", cause)))
|
|
235
|
+
)
|
|
236
|
+
if (text.trim() === "") return undefined
|
|
237
|
+
try {
|
|
238
|
+
return JSON.parse(text) as Schema.Json
|
|
239
|
+
} catch (cause) {
|
|
240
|
+
return yield* fail(Errors.invalidResponse(write, "invalid_json", cause))
|
|
241
|
+
}
|
|
242
|
+
}).pipe(Effect.scoped)
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
call: (method, path, body, callOptions) => {
|
|
246
|
+
const call = once(method, path, body, callOptions)
|
|
247
|
+
return callOptions?.retry === false ? call : retrySafe(call)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Encodes one path segment. @internal */
|
|
253
|
+
export const segment = (value: string): string => encodeURIComponent(value)
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import type { ChatError, ChatErrorReason } from "effect/chat/ChatError"
|
|
2
|
+
import type * as ChatMessage from "effect/chat/ChatMessage"
|
|
3
|
+
import * as Effect from "effect/Effect"
|
|
4
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient"
|
|
5
|
+
import * as HttpClient from "effect/http/HttpClient"
|
|
6
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest"
|
|
7
|
+
import type * as HttpClientResponse from "effect/http/HttpClientResponse"
|
|
8
|
+
import * as Option from "effect/Option"
|
|
9
|
+
import * as Redacted from "effect/Redacted"
|
|
10
|
+
import * as Stream from "effect/Stream"
|
|
11
|
+
import * as Errors from "./errors.ts"
|
|
12
|
+
import { isObject, object, parseUrl, string } from "./parse.ts"
|
|
13
|
+
|
|
14
|
+
const op = "download"
|
|
15
|
+
|
|
16
|
+
/** The content type of a personal chat file the bot may fetch without credentials. @internal */
|
|
17
|
+
export const fileDownloadInfo = "application/vnd.microsoft.teams.file.download.info"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* An attachment id is one of:
|
|
21
|
+
*
|
|
22
|
+
* - `connector:{url}`: a Connector attachment view, fetched with the bot token.
|
|
23
|
+
* - `preauth:{url}`: a pre-authenticated file URL, fetched with no credentials.
|
|
24
|
+
* The URL itself grants access, so it is never logged.
|
|
25
|
+
* - `url:{url}`: any other URL. It is kept so the message shows the file,
|
|
26
|
+
* but `download` refuses it.
|
|
27
|
+
*
|
|
28
|
+
* @internal
|
|
29
|
+
*/
|
|
30
|
+
export type Kind = "connector" | "preauth" | "url"
|
|
31
|
+
|
|
32
|
+
const kinds: ReadonlyArray<Kind> = ["connector", "preauth", "url"]
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The path of a Connector attachment view:
|
|
36
|
+
* `/{region}/v3/attachments/{id}/views/{view}`, where the region segment may be
|
|
37
|
+
* absent. Each segment is letters, digits, `_` or `-`, and the URL has no
|
|
38
|
+
* query.
|
|
39
|
+
*
|
|
40
|
+
* @internal
|
|
41
|
+
*/
|
|
42
|
+
export const connectorPath = /^(?:\/[A-Za-z0-9_-]+)?\/v3\/attachments\/[A-Za-z0-9_-]+\/views\/[A-Za-z0-9_-]+$/
|
|
43
|
+
|
|
44
|
+
/** Whether `host` is `suffix` or ends with `.{suffix}`. @internal */
|
|
45
|
+
export const underSuffix = (host: string, suffixes: ReadonlyArray<string>): boolean =>
|
|
46
|
+
suffixes.some((raw) => {
|
|
47
|
+
const suffix = raw.toLowerCase().replace(/^\./, "")
|
|
48
|
+
return suffix.length > 0 && (host === suffix || host.endsWith(`.${suffix}`))
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
const isIpLiteral = (host: string): boolean => host.startsWith("[") || /^\d+\.\d+\.\d+\.\d+$/.test(host)
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Parses `input` and checks the parts every hop needs: `https:`, no userinfo,
|
|
55
|
+
* the default port and a host name rather than an IP literal. The fragment is
|
|
56
|
+
* dropped, since it is never sent.
|
|
57
|
+
*
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
export const safeUrl = (input: string, base?: string): URL | undefined => {
|
|
61
|
+
const url = parseUrl(input, base)
|
|
62
|
+
if (
|
|
63
|
+
url === undefined || url.protocol !== "https:" || url.username !== "" || url.password !== "" ||
|
|
64
|
+
url.port !== "" || url.hostname.length === 0 || isIpLiteral(url.hostname)
|
|
65
|
+
) {
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
url.hash = ""
|
|
69
|
+
return url
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const size = (record: { readonly [key: string]: unknown }): number | undefined => {
|
|
73
|
+
const value = record.size
|
|
74
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Turns a Bot Framework activity attachment into a chat attachment.
|
|
79
|
+
*
|
|
80
|
+
* - `connector:` when `contentUrl` has the origin of the activity's
|
|
81
|
+
* `serviceUrl`, its host is in `connectorHosts` and its path is
|
|
82
|
+
* {@link connectorPath}.
|
|
83
|
+
* - `preauth:` for a file download info attachment in a personal chat whose
|
|
84
|
+
* `content.downloadUrl` is under one of `fileHostSuffixes`. Its
|
|
85
|
+
* `contentType` is Teams' own, so it is left out.
|
|
86
|
+
* - `url:` for any other `https:` or `http:` `contentUrl`.
|
|
87
|
+
*
|
|
88
|
+
* An attachment with no usable URL, such as a card or the HTML copy of the
|
|
89
|
+
* message, is `undefined`.
|
|
90
|
+
*
|
|
91
|
+
* @internal
|
|
92
|
+
*/
|
|
93
|
+
export const classify = (attachment: unknown, context: {
|
|
94
|
+
readonly serviceUrl: string
|
|
95
|
+
readonly conversationType?: string | undefined
|
|
96
|
+
readonly connectorHosts: ReadonlySet<string>
|
|
97
|
+
readonly fileHostSuffixes: ReadonlyArray<string>
|
|
98
|
+
}): ChatMessage.Attachment | undefined => {
|
|
99
|
+
if (!isObject(attachment)) return undefined
|
|
100
|
+
const contentType = string(attachment, "contentType")
|
|
101
|
+
const name = string(attachment, "name")
|
|
102
|
+
const content = object(attachment, "content")
|
|
103
|
+
const make = (id: string, type: string | undefined, bytes: number | undefined): ChatMessage.Attachment => ({
|
|
104
|
+
id,
|
|
105
|
+
...(name === undefined ? {} : { name }),
|
|
106
|
+
...(type === undefined ? {} : { contentType: type }),
|
|
107
|
+
...(bytes === undefined ? {} : { size: bytes })
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
if (contentType === fileDownloadInfo && context.conversationType === "personal" && content !== undefined) {
|
|
111
|
+
const raw = string(content, "downloadUrl")
|
|
112
|
+
const url = raw === undefined ? undefined : safeUrl(raw)
|
|
113
|
+
if (url !== undefined && underSuffix(url.hostname, context.fileHostSuffixes)) {
|
|
114
|
+
return make(`preauth:${url.href}`, undefined, size(content) ?? size(attachment))
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const raw = string(attachment, "contentUrl")
|
|
119
|
+
if (raw === undefined) return undefined
|
|
120
|
+
const type = contentType === fileDownloadInfo ? undefined : contentType
|
|
121
|
+
const url = safeUrl(raw)
|
|
122
|
+
const service = parseUrl(context.serviceUrl)
|
|
123
|
+
if (
|
|
124
|
+
url !== undefined && service !== undefined && url.origin === service.origin &&
|
|
125
|
+
context.connectorHosts.has(url.hostname) && url.search === "" && connectorPath.test(url.pathname)
|
|
126
|
+
) {
|
|
127
|
+
return make(`connector:${url.href}`, type, size(attachment))
|
|
128
|
+
}
|
|
129
|
+
const other = parseUrl(raw)
|
|
130
|
+
if (other === undefined || (other.protocol !== "https:" && other.protocol !== "http:")) return undefined
|
|
131
|
+
return make(`url:${other.href}`, type, size(attachment))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Splits an attachment id into its kind and URL.
|
|
136
|
+
*
|
|
137
|
+
* @internal
|
|
138
|
+
*/
|
|
139
|
+
export const parseId = (id: string): { readonly kind: Kind; readonly url: string } | undefined => {
|
|
140
|
+
const at = id.indexOf(":")
|
|
141
|
+
if (at === -1) return undefined
|
|
142
|
+
const kind = kinds.find((kind) => kind === id.slice(0, at))
|
|
143
|
+
return kind === undefined ? undefined : { kind, url: id.slice(at + 1) }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @internal */
|
|
147
|
+
export interface DownloadOptions {
|
|
148
|
+
readonly maxBytes: number
|
|
149
|
+
/** The bot token. It is read only for a `connector:` id, and sent on its first request only. */
|
|
150
|
+
readonly token: Effect.Effect<Redacted.Redacted<string>, ChatError>
|
|
151
|
+
/** Exact Connector hosts. */
|
|
152
|
+
readonly connectorHosts: ReadonlySet<string>
|
|
153
|
+
/** Host suffixes for pre-authenticated file URLs, matched at a label boundary. */
|
|
154
|
+
readonly fileHostSuffixes: ReadonlyArray<string>
|
|
155
|
+
/** Exact hosts a redirect may also go to. Empty by default. */
|
|
156
|
+
readonly redirectHosts?: ReadonlySet<string> | undefined
|
|
157
|
+
readonly http?: HttpClient.HttpClient | undefined
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The most redirects one download follows. @internal */
|
|
161
|
+
export const maxRedirects = 3
|
|
162
|
+
|
|
163
|
+
const redirects: ReadonlySet<number> = new Set([301, 302, 303, 307, 308])
|
|
164
|
+
|
|
165
|
+
const fail = (reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Streams the file behind an attachment id.
|
|
169
|
+
*
|
|
170
|
+
* Every hop must pass {@link safeUrl}. The first must have a host in the id's
|
|
171
|
+
* own allowlist (exact `connectorHosts` for `connector:`, `fileHostSuffixes`
|
|
172
|
+
* for `preauth:`), and a redirect a host there or in `redirectHosts`. A
|
|
173
|
+
* redirect host never receives the token. The first hop of a
|
|
174
|
+
* `connector:` id must also have the {@link connectorPath} shape. A URL that
|
|
175
|
+
* fails fails `Forbidden` with detail `untrusted_url`.
|
|
176
|
+
*
|
|
177
|
+
* Requests carry only the headers set here: the bearer token, on the first
|
|
178
|
+
* hop of a `connector:` id. Redirects are read by hand, at most
|
|
179
|
+
* {@link maxRedirects} of them, and only 301, 302, 303, 307 and 308, each sent
|
|
180
|
+
* again as a GET. Fetch runs with `redirect: "manual"`, and a response from
|
|
181
|
+
* another URL than the request's is refused, since a client followed a
|
|
182
|
+
* redirect without the checks.
|
|
183
|
+
*
|
|
184
|
+
* Errors and spans hold the host only: a `preauth:` URL is a credential.
|
|
185
|
+
* The client's own span is turned off for the same reason, as it records the
|
|
186
|
+
* whole URL.
|
|
187
|
+
*
|
|
188
|
+
* @internal
|
|
189
|
+
*/
|
|
190
|
+
export function download(
|
|
191
|
+
id: string,
|
|
192
|
+
options: DownloadOptions & { readonly http: HttpClient.HttpClient }
|
|
193
|
+
): Stream.Stream<Uint8Array, ChatError>
|
|
194
|
+
export function download(
|
|
195
|
+
id: string,
|
|
196
|
+
options: DownloadOptions
|
|
197
|
+
): Stream.Stream<Uint8Array, ChatError, HttpClient.HttpClient>
|
|
198
|
+
export function download(
|
|
199
|
+
id: string,
|
|
200
|
+
options: DownloadOptions
|
|
201
|
+
): Stream.Stream<Uint8Array, ChatError, HttpClient.HttpClient> {
|
|
202
|
+
return Stream.unwrap(Effect.gen(function*() {
|
|
203
|
+
const parsed = parseId(id)
|
|
204
|
+
if (parsed === undefined) return yield* fail(Errors.invalidRequest("attachment_id"))
|
|
205
|
+
if (parsed.kind === "url") return yield* fail(Errors.unsupported("download", "url_attachment"))
|
|
206
|
+
const { kind } = parsed
|
|
207
|
+
const redirectHosts = options.redirectHosts ?? new Set<string>()
|
|
208
|
+
// The id's own allowlist. `redirectHosts` never vouches for the first
|
|
209
|
+
// hop, since the first hop of a `connector:` id is the one with the token.
|
|
210
|
+
const own = (url: URL): boolean =>
|
|
211
|
+
kind === "connector"
|
|
212
|
+
? options.connectorHosts.has(url.hostname)
|
|
213
|
+
: underSuffix(url.hostname, options.fileHostSuffixes)
|
|
214
|
+
const allowed = (url: URL): boolean => own(url) || redirectHosts.has(url.hostname)
|
|
215
|
+
|
|
216
|
+
const first = safeUrl(parsed.url)
|
|
217
|
+
if (
|
|
218
|
+
first === undefined || !own(first) ||
|
|
219
|
+
(kind === "connector" && (first.search !== "" || !connectorPath.test(first.pathname)))
|
|
220
|
+
) {
|
|
221
|
+
return yield* fail(Errors.untrustedUrl())
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const http = HttpClient.withScope(options.http ?? (yield* HttpClient.HttpClient))
|
|
225
|
+
const tooLarge = Errors.chatError(op, Errors.tooLarge("files", "max_bytes"))
|
|
226
|
+
|
|
227
|
+
const send = (url: URL, hop: number) =>
|
|
228
|
+
Effect.gen(function*() {
|
|
229
|
+
let request = HttpClientRequest.get(url.href)
|
|
230
|
+
if (kind === "connector" && hop === 0) {
|
|
231
|
+
const token = yield* Effect.mapError(options.token, Errors.withOp(op))
|
|
232
|
+
request = HttpClientRequest.bearerToken(request, Redacted.value(token))
|
|
233
|
+
}
|
|
234
|
+
const sent = Option.getOrUndefined(HttpClientRequest.toUrl(request))?.href
|
|
235
|
+
const response = yield* http.execute(request).pipe(
|
|
236
|
+
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
|
|
237
|
+
Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
|
|
238
|
+
Effect.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag)))
|
|
239
|
+
)
|
|
240
|
+
yield* Effect.annotateCurrentSpan("http.response.status_code", response.status)
|
|
241
|
+
if (response.url !== sent) return yield* fail(Errors.untrustedUrl())
|
|
242
|
+
return response
|
|
243
|
+
}).pipe(
|
|
244
|
+
Effect.withSpan("TeamsChat.download.request", {
|
|
245
|
+
kind: "client",
|
|
246
|
+
attributes: { "server.address": url.hostname, "teams.download.hop": hop }
|
|
247
|
+
})
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
let url = first
|
|
251
|
+
let response: HttpClientResponse.HttpClientResponse
|
|
252
|
+
for (let hop = 0;; hop++) {
|
|
253
|
+
response = yield* send(url, hop)
|
|
254
|
+
if (!redirects.has(response.status)) break
|
|
255
|
+
if (hop === maxRedirects) return yield* fail(Errors.invalidResponse(false, "too_many_redirects"))
|
|
256
|
+
const location = response.headers.location
|
|
257
|
+
if (location === undefined) return yield* fail(Errors.invalidResponse(false, "missing_location"))
|
|
258
|
+
const next = safeUrl(location, url.href)
|
|
259
|
+
if (next === undefined || !allowed(next)) return yield* fail(Errors.untrustedUrl())
|
|
260
|
+
url = next
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (response.status < 200 || response.status >= 300) {
|
|
264
|
+
return yield* fail(Errors.reasonForStatus(response.status, { write: false }))
|
|
265
|
+
}
|
|
266
|
+
const length = Number(response.headers["content-length"])
|
|
267
|
+
if (Number.isFinite(length) && length > options.maxBytes) return yield* Effect.fail(tooLarge)
|
|
268
|
+
let received = 0
|
|
269
|
+
return response.stream.pipe(
|
|
270
|
+
Stream.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag))),
|
|
271
|
+
Stream.mapEffect((chunk) => {
|
|
272
|
+
received += chunk.length
|
|
273
|
+
return received > options.maxBytes ? Effect.fail(tooLarge) : Effect.succeed(chunk)
|
|
274
|
+
})
|
|
275
|
+
)
|
|
276
|
+
}))
|
|
277
|
+
}
|