@every-app/sdk 0.2.0 → 0.3.0-rc.10

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 (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -3
  3. package/dist/cloudflare/catalogSettings.generated.d.ts +81 -0
  4. package/dist/cloudflare/catalogSettings.generated.d.ts.map +1 -0
  5. package/dist/cloudflare/catalogSettings.generated.js +174 -0
  6. package/dist/cloudflare/index.d.ts +23 -0
  7. package/dist/cloudflare/index.d.ts.map +1 -0
  8. package/dist/cloudflare/index.js +24 -0
  9. package/dist/cloudflare/sentinel.d.ts +127 -0
  10. package/dist/cloudflare/sentinel.d.ts.map +1 -0
  11. package/dist/cloudflare/sentinel.js +85 -0
  12. package/dist/cloudflare/worker.d.ts +805 -0
  13. package/dist/cloudflare/worker.d.ts.map +1 -0
  14. package/dist/cloudflare/worker.js +997 -0
  15. package/dist/dev/index.d.ts +8 -0
  16. package/dist/dev/index.d.ts.map +1 -0
  17. package/dist/dev/index.js +7 -0
  18. package/dist/dev/keypair.d.ts +26 -0
  19. package/dist/dev/keypair.d.ts.map +1 -0
  20. package/dist/dev/keypair.js +62 -0
  21. package/dist/index.d.ts +6 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +5 -0
  24. package/dist/internal/aiDefault.d.ts +204 -0
  25. package/dist/internal/aiDefault.d.ts.map +1 -0
  26. package/dist/internal/aiDefault.js +334 -0
  27. package/dist/internal/aiProviders.d.ts +72 -0
  28. package/dist/internal/aiProviders.d.ts.map +1 -0
  29. package/dist/internal/aiProviders.js +233 -0
  30. package/dist/internal/appSettings.d.ts +315 -0
  31. package/dist/internal/appSettings.d.ts.map +1 -0
  32. package/dist/internal/appSettings.js +549 -0
  33. package/dist/internal/audit.d.ts +108 -0
  34. package/dist/internal/audit.d.ts.map +1 -0
  35. package/dist/internal/audit.js +235 -0
  36. package/dist/internal/capabilities.d.ts +3174 -0
  37. package/dist/internal/capabilities.d.ts.map +1 -0
  38. package/dist/internal/capabilities.js +1110 -0
  39. package/dist/internal/catalog/commerce.d.ts +394 -0
  40. package/dist/internal/catalog/commerce.d.ts.map +1 -0
  41. package/dist/internal/catalog/commerce.js +477 -0
  42. package/dist/internal/catalog/comms.d.ts +375 -0
  43. package/dist/internal/catalog/comms.d.ts.map +1 -0
  44. package/dist/internal/catalog/comms.js +520 -0
  45. package/dist/internal/catalog/index.d.ts +1973 -0
  46. package/dist/internal/catalog/index.d.ts.map +1 -0
  47. package/dist/internal/catalog/index.js +19 -0
  48. package/dist/internal/catalog/inference.d.ts +393 -0
  49. package/dist/internal/catalog/inference.d.ts.map +1 -0
  50. package/dist/internal/catalog/inference.js +460 -0
  51. package/dist/internal/catalog/infra.d.ts +423 -0
  52. package/dist/internal/catalog/infra.d.ts.map +1 -0
  53. package/dist/internal/catalog/infra.js +543 -0
  54. package/dist/internal/catalog/search.d.ts +400 -0
  55. package/dist/internal/catalog/search.d.ts.map +1 -0
  56. package/dist/internal/catalog/search.js +463 -0
  57. package/dist/internal/devProviders.d.ts +49 -0
  58. package/dist/internal/devProviders.d.ts.map +1 -0
  59. package/dist/internal/devProviders.js +80 -0
  60. package/dist/internal/email.d.ts +280 -0
  61. package/dist/internal/email.d.ts.map +1 -0
  62. package/dist/internal/email.js +613 -0
  63. package/dist/internal/events.d.ts +193 -0
  64. package/dist/internal/events.d.ts.map +1 -0
  65. package/dist/internal/events.js +367 -0
  66. package/dist/internal/gatewaySettings.d.ts +83 -0
  67. package/dist/internal/gatewaySettings.d.ts.map +1 -0
  68. package/dist/internal/gatewaySettings.js +215 -0
  69. package/dist/internal/identity.d.ts +57 -5
  70. package/dist/internal/identity.d.ts.map +1 -1
  71. package/dist/internal/identity.js +99 -22
  72. package/dist/internal/index.d.ts +22 -1
  73. package/dist/internal/index.d.ts.map +1 -1
  74. package/dist/internal/index.js +22 -1
  75. package/dist/internal/members.d.ts +36 -0
  76. package/dist/internal/members.d.ts.map +1 -0
  77. package/dist/internal/members.js +7 -0
  78. package/dist/internal/oauthClient.d.ts +61 -0
  79. package/dist/internal/oauthClient.d.ts.map +1 -0
  80. package/dist/internal/oauthClient.js +133 -0
  81. package/dist/internal/oauthPresets.d.ts +33 -0
  82. package/dist/internal/oauthPresets.d.ts.map +1 -0
  83. package/dist/internal/oauthPresets.js +1064 -0
  84. package/dist/internal/oauthScopes.d.ts +172 -0
  85. package/dist/internal/oauthScopes.d.ts.map +1 -0
  86. package/dist/internal/oauthScopes.js +510 -0
  87. package/dist/internal/oauthSpec.d.ts +102 -0
  88. package/dist/internal/oauthSpec.d.ts.map +1 -0
  89. package/dist/internal/oauthSpec.js +789 -0
  90. package/dist/internal/organizationName.d.ts +18 -0
  91. package/dist/internal/organizationName.d.ts.map +1 -0
  92. package/dist/internal/organizationName.js +24 -0
  93. package/dist/internal/protocol.d.ts +150 -3
  94. package/dist/internal/protocol.d.ts.map +1 -1
  95. package/dist/internal/protocol.js +163 -2
  96. package/dist/internal/providerApps.d.ts +75 -0
  97. package/dist/internal/providerApps.d.ts.map +1 -0
  98. package/dist/internal/providerApps.js +59 -0
  99. package/dist/internal/providerRegistry.d.ts +218 -0
  100. package/dist/internal/providerRegistry.d.ts.map +1 -0
  101. package/dist/internal/providerRegistry.js +432 -0
  102. package/dist/internal/providerSpec.d.ts +66 -0
  103. package/dist/internal/providerSpec.d.ts.map +1 -0
  104. package/dist/internal/providerSpec.js +1154 -0
  105. package/dist/internal/remoteMcp.d.ts +188 -0
  106. package/dist/internal/remoteMcp.d.ts.map +1 -0
  107. package/dist/internal/remoteMcp.js +543 -0
  108. package/dist/internal/signInProviders.d.ts +104 -0
  109. package/dist/internal/signInProviders.d.ts.map +1 -0
  110. package/dist/internal/signInProviders.js +245 -0
  111. package/dist/internal/tools.d.ts +115 -0
  112. package/dist/internal/tools.d.ts.map +1 -0
  113. package/dist/internal/tools.js +80 -0
  114. package/dist/manifest.d.ts +238 -0
  115. package/dist/manifest.d.ts.map +1 -0
  116. package/dist/manifest.js +30 -0
  117. package/dist/server/ai.d.ts +111 -0
  118. package/dist/server/ai.d.ts.map +1 -0
  119. package/dist/server/ai.js +145 -0
  120. package/dist/server/aiBinding.d.ts +68 -0
  121. package/dist/server/aiBinding.d.ts.map +1 -0
  122. package/dist/server/aiBinding.js +294 -0
  123. package/dist/server/attribution.d.ts +43 -0
  124. package/dist/server/attribution.d.ts.map +1 -0
  125. package/dist/server/attribution.js +75 -0
  126. package/dist/server/authorizeUrl.d.ts +43 -0
  127. package/dist/server/authorizeUrl.d.ts.map +1 -0
  128. package/dist/server/authorizeUrl.js +106 -0
  129. package/dist/server/connectUrl.d.ts +21 -0
  130. package/dist/server/connectUrl.d.ts.map +1 -0
  131. package/dist/server/connectUrl.js +37 -0
  132. package/dist/server/context.d.ts +68 -0
  133. package/dist/server/context.d.ts.map +1 -0
  134. package/dist/server/context.js +117 -0
  135. package/dist/server/emailBinding.d.ts +72 -0
  136. package/dist/server/emailBinding.d.ts.map +1 -0
  137. package/dist/server/emailBinding.js +124 -0
  138. package/dist/server/emit.d.ts +63 -0
  139. package/dist/server/emit.d.ts.map +1 -0
  140. package/dist/server/emit.js +101 -0
  141. package/dist/server/env.d.ts +44 -0
  142. package/dist/server/env.d.ts.map +1 -0
  143. package/dist/server/env.js +1 -0
  144. package/dist/server/everyApp.d.ts +65 -19
  145. package/dist/server/everyApp.d.ts.map +1 -1
  146. package/dist/server/everyApp.js +195 -30
  147. package/dist/server/fromMcpTools.d.ts +89 -0
  148. package/dist/server/fromMcpTools.d.ts.map +1 -0
  149. package/dist/server/fromMcpTools.js +192 -0
  150. package/dist/server/gatewayFetch.d.ts +54 -14
  151. package/dist/server/gatewayFetch.d.ts.map +1 -1
  152. package/dist/server/gatewayFetch.js +201 -37
  153. package/dist/server/gatewayUrl.d.ts +13 -0
  154. package/dist/server/gatewayUrl.d.ts.map +1 -0
  155. package/dist/server/gatewayUrl.js +34 -0
  156. package/dist/server/index.d.ts +23 -3
  157. package/dist/server/index.d.ts.map +1 -1
  158. package/dist/server/index.js +19 -2
  159. package/dist/server/integrationFetch.d.ts +162 -0
  160. package/dist/server/integrationFetch.d.ts.map +1 -0
  161. package/dist/server/integrationFetch.js +688 -0
  162. package/dist/server/listMembers.d.ts +32 -0
  163. package/dist/server/listMembers.d.ts.map +1 -0
  164. package/dist/server/listMembers.js +71 -0
  165. package/dist/server/nodeServer.d.ts +48 -0
  166. package/dist/server/nodeServer.d.ts.map +1 -0
  167. package/dist/server/nodeServer.js +45 -0
  168. package/dist/server/refusal.d.ts +55 -0
  169. package/dist/server/refusal.d.ts.map +1 -0
  170. package/dist/server/refusal.js +193 -0
  171. package/dist/server/sendEmail.d.ts +39 -0
  172. package/dist/server/sendEmail.d.ts.map +1 -0
  173. package/dist/server/sendEmail.js +114 -0
  174. package/dist/server/tools.d.ts +184 -0
  175. package/dist/server/tools.d.ts.map +1 -0
  176. package/dist/server/tools.js +347 -0
  177. package/dist/server/toolsEndpoint.d.ts +32 -0
  178. package/dist/server/toolsEndpoint.d.ts.map +1 -0
  179. package/dist/server/toolsEndpoint.js +237 -0
  180. package/dist/tanstack-start/index.d.ts +9 -0
  181. package/dist/tanstack-start/index.d.ts.map +1 -0
  182. package/dist/tanstack-start/index.js +29 -0
  183. package/dist/testing/index.d.ts +93 -0
  184. package/dist/testing/index.d.ts.map +1 -0
  185. package/dist/testing/index.js +156 -0
  186. package/package.json +42 -8
  187. package/dist/server/mcp.d.ts +0 -66
  188. package/dist/server/mcp.d.ts.map +0 -1
  189. package/dist/server/mcp.js +0 -147
@@ -0,0 +1,688 @@
1
+ import { ACCOUNT_HEADER, CATALOG, ConfigurationError, GATEWAY_ERROR_HEADER, INTEGRATION_PROXY_PREFIX, OAUTH_TOKEN_BODY_LIMIT, allowedScopes, apiKeyHosts, authorizationFor, capabilitySettings, carriesToken, declaredScopeSets, describeTokenEndpoints, devProviderFile, grantedScopes, heldTokenCallAllowed, injectClientCredentials, integrationProxyPath, oauthClientCredentials, oauthReadMethods, oauthWriteMethods, providerSettingPrefix, requestedScopes, requestedTokenScopes, resolveDevProvider, rewriteTokenRequestScope, scopeExcess, tokenEndpointFor, tokenGrantType, EMAIL_SENDERS_ENV, chooseEmailProvider, parseEmailList, parseEmailSender, } from "../internal/index.js";
2
+ import { applyAttribution, attributionFor, } from "./attribution.js";
3
+ import { BINDING_ORIGIN, gatewayBinding, streamingRequest, } from "./gatewayFetch.js";
4
+ export function integrationFetch({ env, provider, for: explicitTarget, account, optional = false, }) {
5
+ const catalogEntry = fetchableCapability(provider);
6
+ const what = `integrationFetch("${provider}")`;
7
+ // Checked now, so a call nobody's fails where the fetch is made; and
8
+ // again per call, where an identity may since have neared its expiry.
9
+ attributionFor(env, explicitTarget, what);
10
+ const values = env;
11
+ const binding = gatewayBinding(env);
12
+ if (binding && typeof binding.fetch !== "function") {
13
+ throw new ConfigurationError("EVERY_APP_GATEWAY is configured but is not a valid service binding.");
14
+ }
15
+ // An id outside the catalog: the gateway's to resolve over the binding,
16
+ // or in local dev, the registered row's spec `everyapp dev` hands over.
17
+ const integration = catalogEntry ??
18
+ (binding ? undefined : devRegisteredProvider(provider, values));
19
+ const local = binding || !integration ? null : localCredentials(integration, values);
20
+ // In dev an OAuth provider with a held token in `.dev.vars` serves API
21
+ // calls without the client (the token stands in for a connection).
22
+ const devToken = !binding && integration?.mode === "oauth_client" && integration.flow
23
+ ? stringValue(values[devAccessTokenName(provider)])
24
+ : undefined;
25
+ // An OAuth provider with a Gateway-owned flow answers an API call
26
+ // without the client (`integration_not_connected`, below); a token
27
+ // endpoint call without the client throws when it is made.
28
+ const decidesLater = integration?.mode === "oauth_client" && integration.flow !== undefined;
29
+ if (!binding && !local && !devToken && integration && !decidesLater) {
30
+ if (optional)
31
+ return null;
32
+ const names = [
33
+ ...capabilitySettings(integration),
34
+ ...(integration.mode === "oauth_client" && integration.flow
35
+ ? [devAccessTokenName(provider)]
36
+ : []),
37
+ ];
38
+ throw new ConfigurationError(`${integration.label} is unavailable: deploy with the EVERY_APP_GATEWAY binding, or set ${names.join(", ")} in .dev.vars for local development.`);
39
+ }
40
+ return async (input, init) => {
41
+ const target = attributionFor(env, explicitTarget, what);
42
+ const outbound = new Request(input, init);
43
+ const upstream = new URL(outbound.url);
44
+ const headers = new Headers(outbound.headers);
45
+ headers.delete("authorization");
46
+ headers.delete("cookie");
47
+ if (!integration) {
48
+ // A gateway-registered provider: the gateway holds its spec, so the
49
+ // gateway checks the host; here only that it is https at all.
50
+ if (upstream.protocol !== "https:") {
51
+ throw new TypeError(`integrationFetch("${provider}") reaches https URLs only, not ${upstream.protocol}//${upstream.host}.`);
52
+ }
53
+ applyAttribution(headers, target);
54
+ return binding.fetch(streamingRequest(`${BINDING_ORIGIN}${integrationProxyPath(provider, upstream)}`, outbound, headers));
55
+ }
56
+ if (integration.mode === "oauth_client") {
57
+ // A call to the provider's API with the token the gateway holds
58
+ // (docs/design/2026-10-oauth-providers.md section 7), for an entry
59
+ // that supports the Gateway-owned flow; a token endpoint stays the
60
+ // app-driven call it always was.
61
+ const toApi = integration.flow !== undefined &&
62
+ upstream.protocol === "https:" &&
63
+ integration.api.includes(upstream.host) &&
64
+ !tokenEndpointFor(integration, upstream);
65
+ if (toApi) {
66
+ if (binding) {
67
+ if (account)
68
+ headers.set(ACCOUNT_HEADER, account);
69
+ applyAttribution(headers, target);
70
+ return binding.fetch(streamingRequest(`${BINDING_ORIGIN}${integrationProxyPath(provider, upstream)}`, outbound, headers));
71
+ }
72
+ return devHeldTokenCall({
73
+ provider,
74
+ capability: integration,
75
+ outbound,
76
+ upstream,
77
+ headers,
78
+ values,
79
+ });
80
+ }
81
+ return oauthClientCall({
82
+ provider: provider,
83
+ capability: integration,
84
+ outbound,
85
+ upstream,
86
+ headers,
87
+ values,
88
+ ...(binding
89
+ ? { binding, target }
90
+ : { client: local }),
91
+ });
92
+ }
93
+ // In local dev a provider's host setting (`.dev.vars`) adds its host,
94
+ // as the gateway's setting does there.
95
+ const hosts = binding
96
+ ? [...integration.hosts]
97
+ : apiKeyHosts(integration, values);
98
+ if (upstream.protocol !== "https:" || !hosts.includes(upstream.host)) {
99
+ throw new TypeError(`integrationFetch("${provider}") only reaches ${hosts.join(", ")}, not ${upstream.host}.`);
100
+ }
101
+ if (binding) {
102
+ applyAttribution(headers, target);
103
+ return binding.fetch(streamingRequest(`${BINDING_ORIGIN}${integrationProxyPath(provider, upstream)}`, outbound, headers));
104
+ }
105
+ applyAttribution(headers, undefined);
106
+ // The developer's own key, put where the provider's entry says, as the
107
+ // gateway would put its own.
108
+ const auth = local;
109
+ for (const [name, value] of Object.entries(auth.headers)) {
110
+ headers.set(name, value);
111
+ }
112
+ for (const [name, value] of Object.entries(auth.query)) {
113
+ upstream.searchParams.set(name, value);
114
+ }
115
+ return fetch(streamingRequest(upstream.toString(), outbound, headers));
116
+ };
117
+ }
118
+ /**
119
+ * The `.dev.vars` name of a held token for `provider` in local dev
120
+ * (`GOOGLE_WORKSPACE_ACCESS_TOKEN`, `GITHUB_ACCESS_TOKEN`): a token the
121
+ * developer obtained themselves, standing in for the connection the
122
+ * gateway would hold. Dev-only: the gateway never reads it.
123
+ */
124
+ export function devAccessTokenName(provider) {
125
+ return `${providerSettingPrefix(provider)}ACCESS_TOKEN`;
126
+ }
127
+ /**
128
+ * An app's call to an OAuth provider's API in local dev, with no
129
+ * gateway: the gateway's held-token checks in its order (the app's
130
+ * declared sets, the method, the route), then the developer's own token
131
+ * from `.dev.vars` as the bearer, straight to the provider.
132
+ */
133
+ async function devHeldTokenCall({ provider, capability, outbound, upstream, headers, values, }) {
134
+ const token = stringValue(values[devAccessTokenName(provider)]);
135
+ if (!token) {
136
+ return devRefusal(409, "integration_not_connected", `${capability.label} isn't connected here. In local dev, set ${devAccessTokenName(provider)} in .dev.vars to a token you obtained yourself; deployed, the person connects at /connect/${provider}.`, { connectPath: `/connect/${provider}`, reconnect: false });
137
+ }
138
+ const policy = capability.scopePolicy;
139
+ const grant = policy
140
+ ? devScopeSets(policy, provider, capability.label, values, "any")
141
+ : null;
142
+ if (grant && "problem" in grant) {
143
+ return devRefusal(403, grant.code, grant.problem);
144
+ }
145
+ const method = outbound.method.toUpperCase();
146
+ const reads = oauthReadMethods(capability).includes(method);
147
+ const writes = !reads &&
148
+ capability.access.includes("write") &&
149
+ oauthWriteMethods(capability).includes(method) &&
150
+ devDeclaredAccess(provider, values) === "write";
151
+ if (policy && grant) {
152
+ const allowed = heldTokenCallAllowed({
153
+ policy,
154
+ declaredSets: grant.sets,
155
+ // The developer's token stands for a connection granted every set.
156
+ connectionSets: grant.sets,
157
+ hosts: capability.api,
158
+ method,
159
+ upstream,
160
+ readMethods: oauthReadMethods(capability),
161
+ writes,
162
+ });
163
+ if (!allowed.ok) {
164
+ const status = {
165
+ integration_not_connected: 409,
166
+ integration_method_not_allowed: 405,
167
+ integration_scope_not_allowed: 403,
168
+ }[allowed.code];
169
+ return devRefusal(status, allowed.code, allowed.code === "integration_not_connected"
170
+ ? `${capability.label} is connected without ${allowed.missingSets.join(", ")}.`
171
+ : allowed.message);
172
+ }
173
+ }
174
+ else if (!reads && !writes) {
175
+ return devRefusal(405, "integration_method_not_allowed", `${capability.label} calls may use ${oauthReadMethods(capability).join(" or ")} with access: "read"; ${method} needs access: "write" in the app's capabilities entry, on a provider that offers it.`);
176
+ }
177
+ applyAttribution(headers, undefined);
178
+ headers.set("authorization", `Bearer ${token}`);
179
+ for (const name of ["access_token", "token"]) {
180
+ upstream.searchParams.delete(name);
181
+ }
182
+ headers.delete("x-http-method-override");
183
+ return fetch(new Request(upstream.toString(), {
184
+ method,
185
+ headers,
186
+ body: method === "GET" || method === "HEAD" ? null : outbound.body,
187
+ signal: outbound.signal,
188
+ // As the gateway: the token never follows a redirect.
189
+ redirect: "manual",
190
+ ...(method === "GET" || method === "HEAD" ? {} : { duplex: "half" }),
191
+ }));
192
+ }
193
+ /** The `access` the manifest entry for `provider` declares in dev (EVERYAPP_DEV_CAPABILITIES), or null. */
194
+ function devDeclaredAccess(provider, values) {
195
+ const raw = values["EVERYAPP_DEV_CAPABILITIES"];
196
+ try {
197
+ const capabilities = typeof raw === "string" ? jsonRecord(JSON.parse(raw)) : undefined;
198
+ const entry = jsonRecord(capabilities?.[provider]);
199
+ return typeof entry?.["access"] === "string" ? entry["access"] : null;
200
+ }
201
+ catch {
202
+ return null;
203
+ }
204
+ }
205
+ /**
206
+ * The developer's own key or client from `.dev.vars` (with EVERYAPP_DEV
207
+ * set), under the gateway's names; null until every setting it needs is.
208
+ */
209
+ function localCredentials(integration, values) {
210
+ if (!values["EVERYAPP_DEV"])
211
+ return null;
212
+ if (integration.mode === "oauth_client") {
213
+ return oauthClientCredentials(integration, values);
214
+ }
215
+ return authorizationFor(integration, values);
216
+ }
217
+ /**
218
+ * A call to an OAuth client's token endpoint: over the binding, where the
219
+ * gateway puts its client on it, or in local dev straight to the provider
220
+ * with the developer's client put on it by the gateway's own rule.
221
+ */
222
+ async function oauthClientCall({ provider, capability, outbound, upstream, headers, values, binding, target, client, }) {
223
+ const endpoint = tokenEndpointFor(capability, upstream);
224
+ const method = outbound.method.toUpperCase();
225
+ if (!endpoint || !endpoint.methods.includes(method)) {
226
+ throw new TypeError(`integrationFetch("${provider}") only reaches ${capability.label}'s token endpoints (${describeTokenEndpoints(capability)}), not ${method} ${upstream.origin}${upstream.pathname}. Call its API with the user's token directly.`);
227
+ }
228
+ if (binding) {
229
+ applyAttribution(headers, target);
230
+ return binding.fetch(streamingRequest(`${BINDING_ORIGIN}${integrationProxyPath(provider, upstream)}`, outbound, headers));
231
+ }
232
+ applyAttribution(headers, undefined);
233
+ if (!client) {
234
+ throw new ConfigurationError(`${capability.label}'s token endpoints need the client in .dev.vars for local development: set ${capabilitySettings(capability).join(", ")}.`);
235
+ }
236
+ // The gateway's scope checks, in its order, answering its refusals: an
237
+ // app sees in `everyapp dev` what the gateway will say.
238
+ const policy = capability.scopePolicy;
239
+ const grant = policy
240
+ ? devScopeSets(policy, provider, capability.label, values)
241
+ : null;
242
+ if (grant && "problem" in grant) {
243
+ return devRefusal(403, grant.code, grant.problem);
244
+ }
245
+ const sets = grant?.sets;
246
+ const body = method === "GET" ? null : await outbound.text();
247
+ if (body !== null &&
248
+ new TextEncoder().encode(body).byteLength > OAUTH_TOKEN_BODY_LIMIT) {
249
+ throw new TypeError(`A token request's body is at most ${OAUTH_TOKEN_BODY_LIMIT / 1024} KiB.`);
250
+ }
251
+ if (policy &&
252
+ ["grant_type", "scope", "user_scope"].some((name) => upstream.searchParams.has(name))) {
253
+ return devRefusal(400, "integration_body_invalid", "Put grant_type, scope and user_scope in the token request's body, not its query string; the gateway decides on the body.");
254
+ }
255
+ let injected = injectClientCredentials({ url: upstream, headers, body }, endpoint, client);
256
+ if (!injected.ok)
257
+ throw new TypeError(injected.problem);
258
+ if (policy && sets) {
259
+ const refused = refuseTokenRequest(policy, capability, sets, injected);
260
+ if (refused)
261
+ return refused;
262
+ injected = {
263
+ ok: true,
264
+ ...rewriteTokenRequestScope(policy, sets, injected),
265
+ };
266
+ }
267
+ const response = await fetch(new Request(injected.url, {
268
+ method,
269
+ headers: injected.headers,
270
+ body: injected.body,
271
+ signal: outbound.signal,
272
+ // As the gateway: the client never follows a redirect.
273
+ redirect: "manual",
274
+ }));
275
+ if (!policy || !sets || !response.ok)
276
+ return response;
277
+ return checkTokenResponse(policy, capability, sets, response);
278
+ }
279
+ /**
280
+ * The gateway's refusal shape (`{ error, code, message }`, the code in
281
+ * `x-everyapp-error`) from the local-dev twin, so {@link gatewayRefusal}
282
+ * reads it the same way.
283
+ */
284
+ function devRefusal(status, code, message, extra = {}) {
285
+ const labels = {
286
+ 400: "Bad Request",
287
+ 403: "Forbidden",
288
+ 405: "Method Not Allowed",
289
+ 409: "Conflict",
290
+ 502: "Bad Gateway",
291
+ };
292
+ return Response.json({ error: labels[status] ?? "Error", code, message, ...extra }, { status, headers: { [GATEWAY_ERROR_HEADER]: code } });
293
+ }
294
+ /**
295
+ * The scope sets the manifest declares for `id`, read from
296
+ * EVERYAPP_DEV_CAPABILITIES (the manifest's `capabilities` as JSON, which
297
+ * `everyAppWorker()` writes in dev), or the gateway's refusal, in its
298
+ * order: the client not listed for writing (`capability_not_requested`),
299
+ * then a void grant (`integration_scopes_undeclared`: the variable
300
+ * missing, the entry without usable `scopes`, or a set this registry
301
+ * doesn't offer). Fails closed like the gateway: a hand-rolled dev harness
302
+ * that passes no capabilities gets nothing.
303
+ */
304
+ function devScopeSets(policy, id, label, values,
305
+ /** The grant the entry needs: `write` for a token-endpoint call (the app-driven flow), `any` for a held-token call. */
306
+ grant = "write") {
307
+ const offered = Object.keys(policy.sets).join(", ");
308
+ const raw = values["EVERYAPP_DEV_CAPABILITIES"];
309
+ let capabilities;
310
+ try {
311
+ capabilities =
312
+ typeof raw === "string" ? jsonRecord(JSON.parse(raw)) : undefined;
313
+ }
314
+ catch {
315
+ capabilities = undefined;
316
+ }
317
+ if (!capabilities) {
318
+ return {
319
+ code: "integration_scopes_undeclared",
320
+ problem: `${label}'s scope sets aren't known here: everyapp dev passes the manifest's capabilities to the Worker as EVERYAPP_DEV_CAPABILITIES when everyapp.config.ts builds it with everyAppWorker() from @every-app/sdk/cloudflare.`,
321
+ };
322
+ }
323
+ const entry = Object.hasOwn(capabilities, id)
324
+ ? jsonRecord(capabilities[id])
325
+ : undefined;
326
+ // The gateway's check 2: listing the client for writing is the grant
327
+ // of the app-driven flow; a held-token call takes any listing.
328
+ const access = entry?.["access"];
329
+ if (!entry ||
330
+ (grant === "write"
331
+ ? access !== "write"
332
+ : access !== "read" && access !== "write")) {
333
+ return {
334
+ code: "capability_not_requested",
335
+ problem: `This app doesn't list ${label} in its capabilities. Add capabilities: { ${JSON.stringify(id)}: { access: "${grant === "write" ? "write" : "read"}" } } to everyapp.config.ts and start everyapp dev again.`,
336
+ };
337
+ }
338
+ const sets = declaredScopeSets(policy, entry);
339
+ if (sets)
340
+ return { sets };
341
+ const listed = entry["scopes"];
342
+ const unknown = Array.isArray(listed)
343
+ ? listed.filter((name) => typeof name === "string" && !Object.hasOwn(policy.sets, name))
344
+ : [];
345
+ if (unknown.length > 0) {
346
+ return {
347
+ code: "integration_scopes_undeclared",
348
+ problem: `This app's ${label} entry names scope sets this SDK doesn't offer: ${unknown.join(", ")}. It offers: ${offered}. Fix everyapp.config.ts and start everyapp dev again, or update @every-app/sdk if it is older than the set.`,
349
+ };
350
+ }
351
+ return {
352
+ code: "integration_scopes_undeclared",
353
+ problem: `This app lists ${label} without the scope sets it uses. Add scopes: [...] (one or more of: ${offered}) to its ${JSON.stringify(id)} entry in everyapp.config.ts and start everyapp dev again.`,
354
+ };
355
+ }
356
+ function jsonRecord(value) {
357
+ return value && typeof value === "object" && !Array.isArray(value)
358
+ ? value
359
+ : undefined;
360
+ }
361
+ /**
362
+ * The gateway's checks on a token request before it goes out: the grant
363
+ * type must be one the policy completes, and a `scope` the body names must
364
+ * stay within the sets. Null when the request may go.
365
+ */
366
+ function refuseTokenRequest(policy, capability, sets, request) {
367
+ const grantType = tokenGrantType(request);
368
+ if (!policy.grantTypes.includes(grantType)) {
369
+ const completes = policy.grantTypes.map((type) => type === null ? "a code exchange without grant_type" : type);
370
+ const asked = grantType === null
371
+ ? "a request without grant_type"
372
+ : grantType === "other"
373
+ ? "this request's grant_type"
374
+ : grantType;
375
+ return devRefusal(403, "integration_grant_not_allowed", `Through the gateway, ${capability.label} completes ${completes.join(" and ")} grants only; ${asked} isn't one of them. An app never gets app-level tokens with the operator's client.`);
376
+ }
377
+ const asked = requestedTokenScopes(policy, request);
378
+ const excess = asked ? scopeExcess(asked, allowedScopes(policy, sets)) : [];
379
+ if (excess.length > 0) {
380
+ return devRefusal(403, "integration_scope_not_allowed", `This app may ask ${capability.label} for ${sets.join(", ")} (${requestedScopes(policy, sets).scopes.join(", ")}); the request also asks ${excess.join(", ")}. Build the authorize URL and the token request from integrationStatus().scopes.`);
381
+ }
382
+ return null;
383
+ }
384
+ /**
385
+ * The gateway's check on a provider's 2xx answer: a token it carries must
386
+ * name scopes, and those must stay within the sets; on a refusal the
387
+ * answer is dropped, never forwarded, so no app holds a token outside its
388
+ * grant. An answer without a token (Slack's `ok: false`) is the app's to
389
+ * read. A non-2xx answer never reaches here.
390
+ */
391
+ async function checkTokenResponse(policy, capability, sets, response) {
392
+ const invalid = () => devRefusal(502, "integration_response_invalid", `${capability.label} answered with something that isn't a token response (over ${OAUTH_TOKEN_BODY_LIMIT / 1024} KiB or not a JSON object); nothing was passed on.`);
393
+ const bytes = await response.arrayBuffer();
394
+ if (bytes.byteLength > OAUTH_TOKEN_BODY_LIMIT)
395
+ return invalid();
396
+ const text = new TextDecoder().decode(bytes);
397
+ let json;
398
+ try {
399
+ json = JSON.parse(text);
400
+ }
401
+ catch {
402
+ return invalid();
403
+ }
404
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
405
+ return invalid();
406
+ }
407
+ // The body was decoded on read: its length and encoding headers no
408
+ // longer describe it.
409
+ const headers = new Headers(response.headers);
410
+ for (const name of [
411
+ "set-cookie",
412
+ "content-length",
413
+ "content-encoding",
414
+ "transfer-encoding",
415
+ ]) {
416
+ headers.delete(name);
417
+ }
418
+ const forward = () => new Response(text, {
419
+ status: response.status,
420
+ statusText: response.statusText,
421
+ headers,
422
+ });
423
+ if (!carriesToken(json))
424
+ return forward();
425
+ const granted = grantedScopes(policy, json);
426
+ if (!granted) {
427
+ return devRefusal(502, "integration_scope_unverified", `${capability.label} issued a token without saying which scopes it carries, so the gateway can't hold it to this app's scope sets; nothing was passed on. Ask the person to connect again.`);
428
+ }
429
+ const excess = scopeExcess(granted, allowedScopes(policy, sets));
430
+ if (excess.length > 0) {
431
+ const remedy = {
432
+ google: "Ask for only the scopes integrationStatus() returns, without include_granted_scopes, and connect again; if the app needs more, add the scope set to everyapp.config.ts and deploy.",
433
+ microsoft: "On a shared Microsoft client a token carries everything the person consented to this client: have them remove this app's consent at https://myapplications.microsoft.com and connect again, or add the scope set to everyapp.config.ts and deploy.",
434
+ slack: "Slack scopes add up per workspace installation: reinstall the app in the workspace with only the status's scopes, or add the scope set to everyapp.config.ts and deploy.",
435
+ space: "Ask for only the scopes integrationStatus() returns and connect again, or add the scope set to everyapp.config.ts and deploy.",
436
+ comma: "Ask for only the scopes integrationStatus() returns and connect again, or add the scope set to everyapp.config.ts and deploy.",
437
+ }[policy.dialect];
438
+ return devRefusal(403, "integration_scope_exceeded", `${capability.label} granted scopes this app doesn't declare: ${excess.join(", ")}. It declares ${sets.join(", ")} (${requestedScopes(policy, sets).scopes.join(", ")}). Nothing was passed on. ${remedy}`);
439
+ }
440
+ return forward();
441
+ }
442
+ /**
443
+ * A provider outside the catalog in local dev (no binding): the gateway
444
+ * row's spec from EVERYAPP_DEV_PROVIDERS (`.everyapp/providers/<id>.json`,
445
+ * which `everyAppWorker()` reads in dev), or a ConfigurationError naming
446
+ * the file that doesn't parse, or the command that writes one.
447
+ */
448
+ function devRegisteredProvider(provider, values) {
449
+ if (!values["EVERYAPP_DEV"]) {
450
+ throw new ConfigurationError(`"${provider}" isn't in the built-in provider catalog. A provider registered on the gateway (everyapp provider add) is reached through the EVERY_APP_GATEWAY binding, or in everyapp dev from ${devProviderFile(provider)}.`);
451
+ }
452
+ const resolved = resolveDevProvider(values, provider);
453
+ if (!resolved.found)
454
+ throw new ConfigurationError(resolved.problem);
455
+ if (resolved.capability.mode === "ai") {
456
+ throw new ConfigurationError(`${provider} is an AI provider: list it under providers and call it with createGatewayFetch(), not integrationFetch().`);
457
+ }
458
+ return resolved.capability;
459
+ }
460
+ /**
461
+ * The provider `integrationFetch()` calls: one whose key or OAuth client
462
+ * the gateway holds, or undefined for an id outside the built-in catalog
463
+ * (a provider registered on the gateway, which the binding resolves).
464
+ */
465
+ function fetchableCapability(provider) {
466
+ const found = CATALOG.get(String(provider));
467
+ if (!found)
468
+ return undefined;
469
+ if (found.mode === "service") {
470
+ throw new ConfigurationError(`${String(provider)} is a gateway service: call its helper from @every-app/sdk/server (sendEmail(), listMembers()), not integrationFetch().`);
471
+ }
472
+ if (found.mode === "ai") {
473
+ throw new ConfigurationError(`${String(provider)} is an AI provider: list it under providers and call it with createGatewayFetch(), not integrationFetch().`);
474
+ }
475
+ return found;
476
+ }
477
+ function stringValue(value) {
478
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
479
+ }
480
+ /**
481
+ * Whether the app can use an integration right now, without calling the
482
+ * provider: show "an admin needs to set up DataForSEO" (or "sending isn't
483
+ * set up") up front instead of failing mid-task. An OAuth client's status
484
+ * carries its public `clientId` for the authorize URL.
485
+ */
486
+ export async function integrationStatus({ env, provider, for: explicitTarget, }) {
487
+ const status = await readIntegrationStatus({
488
+ env,
489
+ provider,
490
+ ...(explicitTarget === undefined ? {} : { for: explicitTarget }),
491
+ });
492
+ return withSetup(status, String(provider), env);
493
+ }
494
+ /**
495
+ * `status` with its setup fields: the Gateway's as it sent them, or in
496
+ * local development (no binding) the `.dev.vars` names a status that
497
+ * isn't configured lacks.
498
+ */
499
+ function withSetup(status, provider, values) {
500
+ const binding = gatewayBinding(values);
501
+ if (binding || !status.requested || status.configured) {
502
+ return {
503
+ ...status,
504
+ settings: Array.isArray(status.settings) ? status.settings : [],
505
+ setup: typeof status.setup === "string" ? status.setup : null,
506
+ command: typeof status.command === "string" ? status.command : null,
507
+ };
508
+ }
509
+ const integration = CATALOG.get(provider) ?? devRegisteredProvider(provider, values);
510
+ const settings = provider === "email"
511
+ ? ["EMAIL_FROM"]
512
+ : integration
513
+ ? [...capabilitySettings(integration)]
514
+ : [];
515
+ return {
516
+ ...status,
517
+ settings,
518
+ setup: settings.length
519
+ ? `${integration?.label ?? provider} isn't set up for local development: set ${settings.join(" and ")} in .dev.vars.`
520
+ : `${integration?.label ?? provider} isn't set up for local development.`,
521
+ command: null,
522
+ };
523
+ }
524
+ async function readIntegrationStatus({ env, provider, for: explicitTarget, }) {
525
+ const target = attributionFor(env, explicitTarget, `integrationStatus("${String(provider)}")`);
526
+ const values = env;
527
+ const binding = gatewayBinding(env);
528
+ // A provider registered on the gateway is the gateway's to answer for;
529
+ // without one, the catalog, or in local dev the row's spec from
530
+ // `.everyapp/providers/<id>.json`.
531
+ const integration = binding && typeof binding.fetch === "function"
532
+ ? CATALOG.get(String(provider))
533
+ : (CATALOG.get(String(provider)) ??
534
+ devRegisteredProvider(String(provider), values));
535
+ if (integration?.mode === "ai") {
536
+ throw new ConfigurationError(`${String(provider)} is an AI provider: it has no integration status (createGatewayFetch() answers ai_provider_not_configured when its key is unset).`);
537
+ }
538
+ const unavailable = () => (provider === "email"
539
+ ? {
540
+ requested: false,
541
+ configured: false,
542
+ ready: false,
543
+ sender: null,
544
+ senders: [],
545
+ provider: null,
546
+ }
547
+ : {
548
+ requested: false,
549
+ configured: false,
550
+ ready: false,
551
+ });
552
+ if (binding && typeof binding.fetch === "function") {
553
+ const statusUrl = `${BINDING_ORIGIN}${INTEGRATION_PROXY_PREFIX}/${provider}`;
554
+ let response;
555
+ if (target === undefined) {
556
+ response = await binding.fetch(statusUrl);
557
+ }
558
+ else {
559
+ // Whose status: the person's identity (their OAuth connection) or the
560
+ // organization's, as a call would carry it.
561
+ const headers = new Headers();
562
+ applyAttribution(headers, target);
563
+ response = await binding.fetch(statusUrl, { headers });
564
+ }
565
+ if (!response.ok)
566
+ return unavailable();
567
+ return (await response.json());
568
+ }
569
+ if (!integration)
570
+ return unavailable();
571
+ if (integration.mode === "service") {
572
+ if (provider === "email") {
573
+ return devEmailStatus(values);
574
+ }
575
+ // Members: listMembers() answers from the dev identity, nothing to set.
576
+ const dev = Boolean(values["EVERYAPP_DEV"]);
577
+ return {
578
+ requested: true,
579
+ configured: dev,
580
+ ready: dev,
581
+ };
582
+ }
583
+ if (integration.mode === "oauth_client") {
584
+ return devOAuthClientStatus(provider, integration, values);
585
+ }
586
+ const configured = Boolean(values["EVERYAPP_DEV"] && authorizationFor(integration, values));
587
+ return {
588
+ requested: true,
589
+ configured,
590
+ ready: configured,
591
+ };
592
+ }
593
+ /**
594
+ * An OAuth client in local dev, with no gateway: the developer's own, from
595
+ * `.dev.vars`, and for a client with scope sets the manifest's, from
596
+ * EVERYAPP_DEV_CAPABILITIES, shaped as the gateway's status is: an app
597
+ * that doesn't list the client is told nothing, and a void grant is not
598
+ * ready and hides the client id.
599
+ */
600
+ function devOAuthClientStatus(id, capability, values) {
601
+ const client = values["EVERYAPP_DEV"]
602
+ ? oauthClientCredentials(capability, values)
603
+ : null;
604
+ const policy = capability.scopePolicy;
605
+ // An entry with a Gateway-owned flow is listed for reading or writing;
606
+ // the app-driven flow alone needs the write grant.
607
+ const grant = policy
608
+ ? devScopeSets(policy, id, capability.label, values, capability.flow ? "any" : "write")
609
+ : null;
610
+ // The Gateway-owned flow's fields, in dev: a token in `.dev.vars`
611
+ // stands for a connection granted every declared set.
612
+ const flow = capability.flow ? "both" : "app";
613
+ const devToken = capability.flow
614
+ ? stringValue(values[devAccessTokenName(id)])
615
+ : undefined;
616
+ const gateway = (sets) => capability.flow
617
+ ? {
618
+ flow,
619
+ connectPath: `/connect/${id}`,
620
+ connection: devToken
621
+ ? {
622
+ account: "user",
623
+ label: devAccessTokenName(id),
624
+ scopeSets: sets,
625
+ ready: true,
626
+ }
627
+ : null,
628
+ }
629
+ : { flow };
630
+ if (grant && "problem" in grant) {
631
+ if (grant.code === "capability_not_requested") {
632
+ return { requested: false, configured: false, ready: false };
633
+ }
634
+ return {
635
+ requested: true,
636
+ configured: Boolean(client),
637
+ ready: false,
638
+ scopeSets: [],
639
+ ...gateway([]),
640
+ };
641
+ }
642
+ const asked = policy && grant ? requestedScopes(policy, grant.sets) : null;
643
+ return {
644
+ requested: true,
645
+ configured: Boolean(client),
646
+ ready: Boolean(client) || Boolean(devToken),
647
+ ...(client ? { clientId: client.clientId } : {}),
648
+ ...((client || devToken) && grant && asked
649
+ ? {
650
+ scopeSets: grant.sets,
651
+ scopes: asked.scopes,
652
+ ...(asked.userScopes.length > 0
653
+ ? { userScopes: asked.userScopes }
654
+ : {}),
655
+ }
656
+ : {}),
657
+ ...gateway(grant?.sets ?? []),
658
+ };
659
+ }
660
+ /**
661
+ * Email in local dev, with no gateway: sends are printed unless `.dev.vars`
662
+ * sets EMAIL_FROM (and the REST settings), and the senders are the ones
663
+ * `.dev.vars` sets as EVERYAPP_EMAIL_SENDERS, standing in for the
664
+ * installation's (`everyapp email set --sender`); unset, none. The
665
+ * provider is the one the gateway would pick from the same settings:
666
+ * `cloudflare` for the REST pair, `resend` for RESEND_API_KEY, EMAIL_PROVIDER
667
+ * choosing when both are set.
668
+ */
669
+ function devEmailStatus(values) {
670
+ const dev = Boolean(values["EVERYAPP_DEV"]);
671
+ const configured = dev && Boolean(stringValue(values["EMAIL_FROM"]));
672
+ const choice = chooseEmailProvider(values["EMAIL_PROVIDER"], (provider) => (provider === "cloudflare"
673
+ ? stringValue(values["EMAIL_REST_API_TOKEN"]) &&
674
+ stringValue(values["CLOUDFLARE_ACCOUNT_ID"])
675
+ : stringValue(values["RESEND_API_KEY"]))
676
+ ? "settings"
677
+ : null);
678
+ return {
679
+ requested: true,
680
+ configured,
681
+ ready: configured,
682
+ sender: configured
683
+ ? parseEmailSender(stringValue(values["EMAIL_FROM"]), stringValue(values["EMAIL_FROM_NAME"]))
684
+ : null,
685
+ senders: dev ? parseEmailList(values[EMAIL_SENDERS_ENV]) : [],
686
+ provider: configured && choice.ok ? choice.provider : null,
687
+ };
688
+ }