@every-app/sdk 0.3.0-rc.8 → 0.3.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 (146) hide show
  1. package/README.md +75 -74
  2. package/dist/cloudflare/catalogSettings.generated.d.ts +20 -6
  3. package/dist/cloudflare/catalogSettings.generated.d.ts.map +1 -1
  4. package/dist/cloudflare/catalogSettings.generated.js +45 -14
  5. package/dist/cloudflare/index.d.ts +1 -1
  6. package/dist/cloudflare/index.d.ts.map +1 -1
  7. package/dist/cloudflare/sentinel.d.ts +3 -0
  8. package/dist/cloudflare/sentinel.d.ts.map +1 -1
  9. package/dist/cloudflare/sentinel.js +10 -0
  10. package/dist/cloudflare/worker.d.ts +67 -23
  11. package/dist/cloudflare/worker.d.ts.map +1 -1
  12. package/dist/cloudflare/worker.js +68 -32
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/internal/aiDefault.d.ts +36 -79
  16. package/dist/internal/aiDefault.d.ts.map +1 -1
  17. package/dist/internal/aiDefault.js +47 -149
  18. package/dist/internal/aiProviders.d.ts +1 -1
  19. package/dist/internal/aiProviders.d.ts.map +1 -1
  20. package/dist/internal/aiProviders.js +2 -2
  21. package/dist/internal/appSettings.d.ts +140 -89
  22. package/dist/internal/appSettings.d.ts.map +1 -1
  23. package/dist/internal/appSettings.js +264 -156
  24. package/dist/internal/capabilities.d.ts +145 -503
  25. package/dist/internal/capabilities.d.ts.map +1 -1
  26. package/dist/internal/capabilities.js +29 -550
  27. package/dist/internal/catalog/commerce.js +1 -1
  28. package/dist/internal/catalog/comms.d.ts +37 -0
  29. package/dist/internal/catalog/comms.d.ts.map +1 -1
  30. package/dist/internal/catalog/comms.js +43 -0
  31. package/dist/internal/catalog/index.d.ts +72 -0
  32. package/dist/internal/catalog/index.d.ts.map +1 -1
  33. package/dist/internal/catalog/infra.d.ts +35 -0
  34. package/dist/internal/catalog/infra.d.ts.map +1 -1
  35. package/dist/internal/catalog/infra.js +65 -0
  36. package/dist/internal/devProviders.d.ts +1 -19
  37. package/dist/internal/devProviders.d.ts.map +1 -1
  38. package/dist/internal/devProviders.js +7 -1
  39. package/dist/internal/events.d.ts +52 -1
  40. package/dist/internal/events.d.ts.map +1 -1
  41. package/dist/internal/events.js +66 -2
  42. package/dist/internal/gatewaySettings.d.ts +6 -16
  43. package/dist/internal/gatewaySettings.d.ts.map +1 -1
  44. package/dist/internal/gatewaySettings.js +6 -24
  45. package/dist/internal/index.d.ts +1 -0
  46. package/dist/internal/index.d.ts.map +1 -1
  47. package/dist/internal/index.js +1 -0
  48. package/dist/internal/mcpOAuth.d.ts +210 -0
  49. package/dist/internal/mcpOAuth.d.ts.map +1 -0
  50. package/dist/internal/mcpOAuth.js +735 -0
  51. package/dist/internal/oauthClient.d.ts +7 -47
  52. package/dist/internal/oauthClient.d.ts.map +1 -1
  53. package/dist/internal/oauthClient.js +1 -115
  54. package/dist/internal/oauthPresets.d.ts +356 -20
  55. package/dist/internal/oauthPresets.d.ts.map +1 -1
  56. package/dist/internal/oauthPresets.js +183 -861
  57. package/dist/internal/oauthScopes.d.ts +43 -155
  58. package/dist/internal/oauthScopes.d.ts.map +1 -1
  59. package/dist/internal/oauthScopes.js +82 -475
  60. package/dist/internal/oauthSpec.d.ts +28 -71
  61. package/dist/internal/oauthSpec.d.ts.map +1 -1
  62. package/dist/internal/oauthSpec.js +172 -448
  63. package/dist/internal/protocol.d.ts +39 -15
  64. package/dist/internal/protocol.d.ts.map +1 -1
  65. package/dist/internal/protocol.js +40 -7
  66. package/dist/internal/providerApps.d.ts +2 -2
  67. package/dist/internal/providerApps.js +2 -2
  68. package/dist/internal/providerRegistry.d.ts +5 -64
  69. package/dist/internal/providerRegistry.d.ts.map +1 -1
  70. package/dist/internal/providerRegistry.js +19 -118
  71. package/dist/internal/providerSpec.d.ts.map +1 -1
  72. package/dist/internal/providerSpec.js +14 -36
  73. package/dist/internal/remoteMcp.d.ts +191 -47
  74. package/dist/internal/remoteMcp.d.ts.map +1 -1
  75. package/dist/internal/remoteMcp.js +338 -133
  76. package/dist/internal/signInProviders.d.ts +1 -1
  77. package/dist/internal/signInProviders.d.ts.map +1 -1
  78. package/dist/internal/tools.d.ts +15 -8
  79. package/dist/internal/tools.d.ts.map +1 -1
  80. package/dist/internal/tools.js +9 -8
  81. package/dist/manifest.d.ts +96 -28
  82. package/dist/manifest.d.ts.map +1 -1
  83. package/dist/manifest.js +1 -1
  84. package/dist/server/ai.d.ts +1 -93
  85. package/dist/server/ai.d.ts.map +1 -1
  86. package/dist/server/ai.js +17 -111
  87. package/dist/server/attribution.d.ts +10 -1
  88. package/dist/server/attribution.d.ts.map +1 -1
  89. package/dist/server/attribution.js +7 -1
  90. package/dist/server/connectUrl.d.ts +4 -9
  91. package/dist/server/connectUrl.d.ts.map +1 -1
  92. package/dist/server/connectUrl.js +17 -14
  93. package/dist/server/context.d.ts +12 -14
  94. package/dist/server/context.d.ts.map +1 -1
  95. package/dist/server/context.js +23 -25
  96. package/dist/server/emit.d.ts.map +1 -1
  97. package/dist/server/emit.js +2 -2
  98. package/dist/server/env.d.ts +3 -0
  99. package/dist/server/env.d.ts.map +1 -1
  100. package/dist/server/eventsEndpoint.d.ts +48 -0
  101. package/dist/server/eventsEndpoint.d.ts.map +1 -0
  102. package/dist/server/eventsEndpoint.js +145 -0
  103. package/dist/server/everyApp.d.ts +16 -26
  104. package/dist/server/everyApp.d.ts.map +1 -1
  105. package/dist/server/everyApp.js +22 -46
  106. package/dist/server/gatewayFetch.d.ts +19 -1
  107. package/dist/server/gatewayFetch.d.ts.map +1 -1
  108. package/dist/server/gatewayFetch.js +45 -3
  109. package/dist/server/index.d.ts +6 -9
  110. package/dist/server/index.d.ts.map +1 -1
  111. package/dist/server/index.js +4 -8
  112. package/dist/server/integrationFetch.d.ts +60 -72
  113. package/dist/server/integrationFetch.d.ts.map +1 -1
  114. package/dist/server/integrationFetch.js +124 -397
  115. package/dist/server/listMembers.d.ts.map +1 -1
  116. package/dist/server/listMembers.js +2 -2
  117. package/dist/server/refusal.d.ts +0 -9
  118. package/dist/server/refusal.d.ts.map +1 -1
  119. package/dist/server/refusal.js +0 -22
  120. package/dist/server/sendEmail.d.ts.map +1 -1
  121. package/dist/server/sendEmail.js +2 -2
  122. package/dist/server/tools.d.ts +17 -6
  123. package/dist/server/tools.d.ts.map +1 -1
  124. package/dist/server/tools.js +14 -4
  125. package/dist/server/toolsEndpoint.d.ts +2 -1
  126. package/dist/server/toolsEndpoint.d.ts.map +1 -1
  127. package/dist/server/toolsEndpoint.js +4 -3
  128. package/dist/server/webhooks.d.ts +56 -0
  129. package/dist/server/webhooks.d.ts.map +1 -0
  130. package/dist/server/webhooks.js +205 -0
  131. package/dist/testing/index.d.ts +2 -3
  132. package/dist/testing/index.d.ts.map +1 -1
  133. package/dist/testing/index.js +2 -6
  134. package/package.json +6 -1
  135. package/dist/server/aiBinding.d.ts +0 -68
  136. package/dist/server/aiBinding.d.ts.map +0 -1
  137. package/dist/server/aiBinding.js +0 -294
  138. package/dist/server/authorizeUrl.d.ts +0 -43
  139. package/dist/server/authorizeUrl.d.ts.map +0 -1
  140. package/dist/server/authorizeUrl.js +0 -106
  141. package/dist/server/emailBinding.d.ts +0 -72
  142. package/dist/server/emailBinding.d.ts.map +0 -1
  143. package/dist/server/emailBinding.js +0 -124
  144. package/dist/server/fromMcpTools.d.ts +0 -89
  145. package/dist/server/fromMcpTools.d.ts.map +0 -1
  146. package/dist/server/fromMcpTools.js +0 -192
@@ -1,510 +1,117 @@
1
1
  /**
2
- * The scope set names a manifest entry declares, or null when the entry
3
- * voids its grant: `scopes` missing, not an array, empty, a non-string
4
- * element, a name listed twice, or any name the policy doesn't offer. An
5
- * unknown name voids the whole grant rather than narrowing it silently, so
6
- * a newer CLI's set name reaching an older gateway is refused outright and
7
- * a message can say so.
8
- */
9
- export function declaredScopeSets(policy, entry) {
10
- const declared = entry?.scopes;
11
- if (!Array.isArray(declared) || declared.length === 0)
12
- return null;
13
- const names = [];
14
- for (const name of declared) {
15
- if (typeof name !== "string" ||
16
- !Object.hasOwn(policy.sets, name) ||
17
- names.includes(name)) {
18
- return null;
19
- }
20
- names.push(name);
21
- }
22
- return names;
23
- }
24
- /**
25
- * What an app with `sets` asks the provider for: the sets' scopes in
26
- * registry order, deduplicated, then `alwaysRequested`. The status hands
27
- * these out and the authorize URL (Microsoft: the token leg too) carries
28
- * them verbatim.
29
- */
30
- export function requestedScopes(policy, sets) {
31
- const scopes = [];
32
- const userScopes = [];
33
- for (const [, set] of setsOf(policy, sets)) {
34
- pushNew(scopes, set.scopes);
35
- pushNew(userScopes, set.userScopes ?? []);
36
- }
37
- pushNew(scopes, policy.alwaysRequested);
38
- return { scopes, userScopes };
39
- }
40
- /**
41
- * What a token an app with `sets` is handed may carry: the requested
42
- * scopes and the tolerated ones, in the dialect's canonical spelling so a
43
- * granted list canonicalised the same way compares exactly.
44
- */
45
- export function allowedScopes(policy, sets) {
46
- const requested = requestedScopes(policy, sets);
47
- return {
48
- scopes: canonical(policy.dialect, [
49
- ...requested.scopes,
50
- ...policy.tolerated,
51
- ]),
52
- userScopes: canonical(policy.dialect, requested.userScopes),
53
- };
54
- }
55
- /**
56
- * Whether a token response body carries a token: an access, refresh or ID
57
- * token, or Slack's user token under `authed_user`. A 2xx without one
58
- * (Slack's `ok: false`) is an error the app must see, not a grant.
59
- */
60
- export function carriesToken(json) {
61
- const body = record(json);
62
- if (!body)
63
- return false;
64
- return (typeof body["access_token"] === "string" ||
65
- typeof body["refresh_token"] === "string" ||
66
- typeof body["id_token"] === "string" ||
67
- typeof record(body["authed_user"])?.["access_token"] === "string");
68
- }
69
- /**
70
- * The scopes a token response says it granted, canonicalised per dialect,
71
- * or null when the answer names none for a token it carries, which fails
72
- * closed: every documented success response of the three providers names
73
- * them (map-providers: Google and Microsoft `scope`, Slack `scope` and
74
- * `authed_user.scope`), so a missing field is an answer the gateway can't
75
- * hold to anything.
76
- */
77
- export function grantedScopes(policy, json) {
78
- const body = record(json);
79
- if (!body)
80
- return null;
81
- switch (policy.dialect) {
82
- case "google": {
83
- // Space-delimited, case-sensitive strings (Google's own words).
84
- const scopes = splitScopes("google", body["scope"]);
85
- return scopes ? { scopes } : null;
2
+ * A scope as the provider is asked for it: an app's short scope joined
3
+ * onto the spec's prefix; a full one (with `://`), one of the spec's own
4
+ * identity or tolerated scopes, or any scope of a provider without a
5
+ * prefix, as written.
6
+ */
7
+ export function expandScope(rules, scope) {
8
+ const prefix = rules.scopePrefix;
9
+ if (!prefix || scope.includes("://"))
10
+ return scope;
11
+ const own = [...rules.identityScopes, ...rules.tolerated];
12
+ return own.includes(scope) ? scope : `${prefix}${scope}`;
13
+ }
14
+ /** A scope in the one spelling comparisons use: decoded, lower case, without the prefix. */
15
+ export function canonicalScope(rules, scope) {
16
+ let text = scope.trim();
17
+ if (text.includes("%")) {
18
+ try {
19
+ text = decodeURIComponent(text);
86
20
  }
87
- case "microsoft": {
88
- // Documented URL-encoded with the Graph prefix
89
- // (`https%3A%2F%2Fgraph.microsoft.com%2Fmail.read`), seen as short
90
- // names in either case; `offline_access` is never echoed, and dropped
91
- // if it ever is.
92
- if (typeof body["scope"] !== "string")
93
- return null;
94
- let decoded;
95
- try {
96
- decoded = decodeURIComponent(body["scope"]);
97
- }
98
- catch {
99
- return null;
100
- }
101
- const scopes = splitScopes("microsoft", decoded)?.filter((scope) => scope !== "offline_access");
102
- return scopes && scopes.length > 0 ? { scopes } : null;
103
- }
104
- case "slack":
105
- return slackGrantedScopes(body);
106
- case "space":
107
- case "comma": {
108
- const scopes = splitScopes(policy.dialect, body["scope"]);
109
- return scopes ? { scopes } : null;
21
+ catch {
22
+ // A malformed escape stays as written, and matches nothing asked.
110
23
  }
111
24
  }
25
+ text = text.toLowerCase();
26
+ const prefix = rules.scopePrefix?.toLowerCase();
27
+ return prefix && text.startsWith(prefix) ? text.slice(prefix.length) : text;
112
28
  }
113
- /**
114
- * What a token response granted, for the Gateway-owned flow: as
115
- * {@link grantedScopes}, except that a `space` or `comma` provider that
116
- * names no `scope` at all is taken at its word (RFC 6749 §5.1: the field
117
- * is optional when the grant matches the request), so `requested` stands.
118
- * The three parsed dialects keep failing closed.
119
- */
120
- export function grantedScopesOrRequested(policy, json, requested) {
121
- const granted = grantedScopes(policy, json);
122
- if (granted)
123
- return granted;
124
- const body = record(json);
125
- if (body &&
126
- body["scope"] === undefined &&
127
- (policy.dialect === "space" || policy.dialect === "comma")) {
128
- return { scopes: canonical(policy.dialect, requested.scopes) };
29
+ /** `scopes` canonical, deduplicated, order kept. */
30
+ export function canonicalScopes(rules, scopes) {
31
+ const out = [];
32
+ for (const scope of scopes) {
33
+ const canonical = canonicalScope(rules, scope);
34
+ if (canonical && !out.includes(canonical))
35
+ out.push(canonical);
129
36
  }
130
- return null;
37
+ return out;
131
38
  }
132
39
  /**
133
- * Whether an app's call with a held token goes through, and under which
134
- * set (docs/design/2026-10-oauth-providers.md section 7). In order: every
135
- * set the app declares must be among the connection's (else the person
136
- * connects again: `integration_not_connected` with the missing sets); the
137
- * host must be one of the provider's `api` hosts; the path passes the
138
- * segment rules (`scopeRouteAllows`'s: no batch tunnels, no dot segments,
139
- * no denied segments); then a declared set with routes must cover the
140
- * call, or a declared set without routes covers its hosts by access: a
141
- * read set unlocks `readMethods` (GET and HEAD by default), a write set
142
- * every method the provider offers. `writes` says whether the method is
143
- * one the grant allows beyond reads, decided by the caller as for an
144
- * API-key provider.
40
+ * What a connect for an app that declares `declared` asks the provider
41
+ * for, in the provider's spelling: the app's scopes, then the spec's
42
+ * identity scopes, each once.
145
43
  */
146
- export function heldTokenCallAllowed({ policy, declaredSets, connectionSets, hosts, method, upstream, readMethods = ["GET", "HEAD"], writes, }) {
147
- const missingSets = declaredSets.filter((name) => !connectionSets.includes(name));
148
- if (missingSets.length > 0) {
149
- return { ok: false, code: "integration_not_connected", missingSets };
150
- }
151
- if (upstream.protocol !== "https:" || !hosts.includes(upstream.host)) {
152
- return {
153
- ok: false,
154
- code: "integration_scope_not_allowed",
155
- message: `${upstream.host} is not a host this provider's token reaches (${hosts.join(", ")}).`,
156
- };
157
- }
158
- if (!safeSegments(policy, upstream.pathname)) {
159
- return {
160
- ok: false,
161
- code: "integration_scope_not_allowed",
162
- message: `${upstream.pathname} is a path no scope set unlocks.`,
163
- };
44
+ export function requestedScopes(rules, declared) {
45
+ const out = [];
46
+ for (const scope of [
47
+ ...declared.map((each) => expandScope(rules, each)),
48
+ ...rules.identityScopes,
49
+ ]) {
50
+ if (!out.includes(scope))
51
+ out.push(scope);
164
52
  }
165
- const verb = method.toUpperCase();
166
- const reads = readMethods.includes(verb);
167
- // A set's routes decide first: a read-shaped POST a read set lists
168
- // under `posts` (a search, a query) is a read whatever the grant.
169
- const routed = scopeRouteAllows(policy, declaredSets, verb, upstream);
170
- if (routed)
171
- return { ok: true, set: routed };
172
- if (!reads && !writes) {
173
- return {
174
- ok: false,
175
- code: "integration_method_not_allowed",
176
- message: `${verb} ${upstream.pathname}: calls may use ${readMethods.join(" or ")} with access: "read"; ${verb} needs access: "write" in the app's capabilities entry, on a provider that offers it, or a scope set whose routes list it.`,
177
- };
178
- }
179
- for (const [name, set] of setsOf(policy, declaredSets)) {
180
- if (set.routes.length > 0)
181
- continue;
182
- if (reads || (writes && set.access === "write")) {
183
- return { ok: true, set: name };
184
- }
185
- }
186
- return {
187
- ok: false,
188
- code: "integration_scope_not_allowed",
189
- message: `${verb} ${upstream.pathname} is outside the scope sets this app declares (${declaredSets.join(", ")}).`,
190
- };
191
- }
192
- /**
193
- * Slack answers with up to two tokens, each with its own scopes: the bot
194
- * token at the top level and the installing person's under `authed_user`.
195
- * Which kind the top-level one is comes from `token_type`, because a
196
- * token-rotation refresh of a user token comes back at the top level with
197
- * `token_type: "user"`; `authed_user` is a user token unless it says so.
198
- */
199
- function slackGrantedScopes(body) {
200
- const granted = {};
201
- const take = (token, kind) => {
202
- if (kind !== "bot" && kind !== "user")
203
- return false;
204
- const scopes = splitScopes("slack", token["scope"]);
205
- if (!scopes)
206
- return false;
207
- const key = kind === "bot" ? "scopes" : "userScopes";
208
- granted[key] = pushNew(granted[key] ?? [], scopes);
209
- return true;
210
- };
211
- if (typeof body["access_token"] === "string") {
212
- if (!take(body, body["token_type"]))
213
- return null;
214
- }
215
- const authedUser = record(body["authed_user"]);
216
- if (authedUser && typeof authedUser["access_token"] === "string") {
217
- if (!take(authedUser, authedUser["token_type"] ?? "user"))
218
- return null;
219
- }
220
- return granted.scopes || granted.userScopes ? granted : null;
221
- }
222
- /**
223
- * What `granted` carries beyond `allowed`, per token kind, for a refusal's
224
- * message and log line: the user token's extras as `user:<scope>`. Both
225
- * lists are in the dialect's canonical spelling already.
226
- */
227
- export function scopeExcess(granted, allowed) {
228
- const extra = (scopes, within) => (scopes ?? []).filter((scope) => !within.includes(scope));
229
- return [
230
- ...extra(granted.scopes, allowed.scopes),
231
- ...extra(granted.userScopes, allowed.userScopes).map((scope) => `user:${scope}`),
232
- ];
233
- }
234
- /**
235
- * The scopes a token request itself asks for (`scope`, and Slack's
236
- * `user_scope`, in any case) in its form or JSON body, canonicalised per
237
- * dialect for comparison with `allowedScopes()`, or null when the body
238
- * names none. The query string is never read: the gateway refuses a
239
- * request that puts these there, so only one place decides.
240
- */
241
- export function requestedTokenScopes(policy, request) {
242
- const fields = bodyFields(request);
243
- if (!fields)
244
- return null;
245
- const requested = {};
246
- const scopes = splitScopes(policy.dialect, fields["scope"]);
247
- if (scopes)
248
- requested.scopes = scopes;
249
- const userScopes = splitScopes(policy.dialect, fields["user_scope"]);
250
- if (userScopes)
251
- requested.userScopes = userScopes;
252
- return requested.scopes || requested.userScopes ? requested : null;
53
+ return out;
253
54
  }
254
- /**
255
- * `request` with its `scope`, in any case, as the policy's `requestScope`
256
- * says: replaced by the requested list of the app's `sets`, dropped, or
257
- * kept as sent. A separate step after `injectClientCredentials()`, whose
258
- * re-serialised form or JSON body this edits the same way; any other body
259
- * is left alone.
260
- */
261
- export function rewriteTokenRequestScope(policy, sets, request) {
262
- if (policy.requestScope === "keep" || !request.body)
263
- return request;
264
- const replacement = policy.requestScope === "replace"
265
- ? requestedScopes(policy, sets).scopes.join(" ")
266
- : null;
267
- const type = mediaType(request.headers.get("content-type"));
268
- // Every spelling goes, as `injectClientCredentials()` strips the client:
269
- // Entra reads a form's names in any case, so a `Scope` left beside the
270
- // gateway's `scope` is refused upstream as a duplicate, or read instead.
271
- const isScope = (name) => name.toLowerCase() === "scope";
272
- let body = request.body;
273
- if (type === FORM) {
274
- const params = new URLSearchParams(body);
275
- for (const name of new Set([...params.keys()].filter(isScope))) {
276
- params.delete(name);
277
- }
278
- if (replacement !== null)
279
- params.set("scope", replacement);
280
- body = params.toString();
281
- }
282
- else if (type === JSON_TYPE) {
283
- const parsed = jsonObject(body);
284
- if (!parsed)
285
- return request;
286
- for (const name of Object.keys(parsed)) {
287
- if (isScope(name))
288
- delete parsed[name];
289
- }
290
- if (replacement !== null)
291
- parsed["scope"] = replacement;
292
- body = JSON.stringify(parsed);
293
- }
294
- else {
295
- return request;
296
- }
297
- return { url: request.url, headers: request.headers, body };
55
+ /** Scopes joined as the provider's `scope` parameter takes them. */
56
+ export function joinScopes(rules, scopes) {
57
+ return scopes.join(rules.scopeSeparator === "comma" ? "," : " ");
298
58
  }
299
59
  /**
300
- * The declared set that unlocks `method upstream`, or null. Not wired to
301
- * any live path yet: it becomes the proxy's boundary once the gateway
302
- * holds tokens, and the outbound Worker's for dispatched apps before that.
303
- *
304
- * In order: https only; the host must be on one of the declared sets'
305
- * routes; the raw pathname is refused when it holds `\`, `//` or `%00`;
306
- * each raw segment, and each percent-decoding of it while a `%` remains
307
- * (a provider's layers may each decode once), is refused when it won't
308
- * decode, holds a control or format character or a backslash, is one of
309
- * the policy's denied segments in any case, or splits on `/` into a dot
310
- * segment: `.` or `..`, with or without a `;` parameter (`..;x`), which
311
- * Google's front end resolves like the bare one. The denied comparison is
312
- * of the whole segment, because an encoded slash is part of one id to the
313
- * provider, never a separator: a Search Console site URL whose own path
314
- * holds `batch` stays matchable, and `2%2FmeasurementProtocolSecrets` is
315
- * a data stream id that doesn't exist, not the secrets. Then the raw
316
- * pathname, case preserved, is matched: GET and HEAD need a `paths` entry
317
- * (exact, or a prefix when it ends in `/`), POST needs a `posts` pattern,
318
- * and no other method goes through. Matching the raw path is what lets
319
- * Search Console's `sites/https%3A%2F%2Fexample.com%2F/searchAnalytics/query`
320
- * match `[^/]+` while `..`, batch tunnels and secrets stay refused however
321
- * encoded. `X-HTTP-Method-Override`, `access_token` and `token` parameters
322
- * are the proxy's to strip before it asks; nothing here reads them. The
323
- * proxy fetches with `redirect: "manual"`: Google answers a dot segment it
324
- * resolves with a 302 to the resolved path, and following one would carry
325
- * the token to a path this never matched.
60
+ * The scopes a token response says it granted, canonical. A response
61
+ * with no `scope` field is taken as granted exactly as `requested` (RFC
62
+ * 6749 §5.1); one whose `scope` isn't a string is null (refused).
326
63
  */
327
- export function scopeRouteAllows(policy, sets, method, upstream) {
328
- if (upstream.protocol !== "https:")
64
+ export function grantedScopes(rules, body, requested) {
65
+ const raw = body["scope"];
66
+ if (raw === undefined)
67
+ return canonicalScopes(rules, requested);
68
+ if (typeof raw !== "string")
329
69
  return null;
330
- const onHost = setsOf(policy, sets).flatMap(([name, set]) => set.routes
331
- .filter((route) => route.host === upstream.host)
332
- .map((route) => [name, route]));
333
- if (onHost.length === 0)
334
- return null;
335
- const pathname = upstream.pathname;
336
- if (!safeSegments(policy, pathname))
337
- return null;
338
- const verb = method.toUpperCase();
339
- for (const [name, route] of onHost) {
340
- if (verb === "GET" || verb === "HEAD") {
341
- const covered = route.paths.some((entry) => entry.endsWith("/") ? pathname.startsWith(entry) : pathname === entry);
342
- if (covered)
343
- return name;
344
- }
345
- else if (verb === "POST") {
346
- if (route.posts?.some((pattern) => pattern.test(pathname)))
347
- return name;
70
+ let text = raw;
71
+ if (text.includes("%")) {
72
+ try {
73
+ text = decodeURIComponent(text);
348
74
  }
349
- }
350
- return null;
351
- }
352
- /** Control and format characters: in no provider's path once decoded. */
353
- const UNPRINTABLE = /[\p{Cc}\p{Cf}]/u;
354
- /** A dot segment, bare or with a path parameter (`..;x`): Google's front end resolves both. */
355
- const DOT_SEGMENT = /^\.{1,2}(;|$)/;
356
- /**
357
- * Whether every segment of the raw `pathname` passes the checks above in
358
- * each form a provider's layers could see it: raw, then decoded again
359
- * while a `%` remains.
360
- */
361
- function safeSegments(policy, pathname) {
362
- if (pathname.includes("\\") ||
363
- pathname.includes("//") ||
364
- pathname.includes("%00")) {
365
- return false;
366
- }
367
- const denied = policy.deniedSegments.map((segment) => segment.toLowerCase());
368
- for (const raw of pathname.split("/")) {
369
- let text = raw;
370
- for (;;) {
371
- if (!safeSegment(text, denied))
372
- return false;
373
- if (!text.includes("%"))
374
- break;
375
- // A `%` left after a decode is a byte the provider may decode again
376
- // (double encoding), so that form is checked too; one that isn't an
377
- // escape (`%2525` ends in a bare `%`) won't decode and refuses, as a
378
- // malformed escape in the raw path does.
379
- try {
380
- text = decodeURIComponent(text);
381
- }
382
- catch {
383
- return false;
384
- }
75
+ catch {
76
+ return null;
385
77
  }
386
78
  }
387
- return true;
79
+ const split = rules.scopeSeparator === "comma" ? text.split(/[,\s]+/) : text.split(/\s+/);
80
+ return canonicalScopes(rules, split.filter(Boolean));
388
81
  }
389
82
  /**
390
- * Whether one form of a segment is safe: no control or format character,
391
- * no backslash (in no provider's grammar), not a denied segment in any
392
- * case, and no dot segment among its `/`-split parts (a traversal the
393
- * provider might resolve). The denied comparison is of the whole: an
394
- * encoded slash is part of one id to the provider, never a separator, so
395
- * a Search Console site URL whose own path holds `batch` stays matchable.
83
+ * The mint check: what `granted` (canonical) carries beyond `requested`,
84
+ * the identity scopes and the tolerated ones. Empty means the token may
85
+ * be kept; anything else and the Gateway drops it.
396
86
  */
397
- function safeSegment(text, denied) {
398
- if (UNPRINTABLE.test(text) || text.includes("\\"))
399
- return false;
400
- if (denied.includes(text.toLowerCase()))
401
- return false;
402
- return !text.split("/").some((part) => DOT_SEGMENT.test(part));
87
+ export function scopeExcess(rules, granted, requested) {
88
+ const allowed = canonicalScopes(rules, [
89
+ ...requested,
90
+ ...rules.identityScopes,
91
+ ...rules.tolerated,
92
+ ]);
93
+ return granted.filter((scope) => !allowed.includes(scope));
403
94
  }
404
- /** The policy's sets in registry order, keeping those `names` declares. */
405
- function setsOf(policy, names) {
406
- return Object.entries(policy.sets).filter(([name]) => names.includes(name));
407
- }
408
- const GOOGLE_ALIASES = new Map([
409
- ["email", "https://www.googleapis.com/auth/userinfo.email"],
410
- ["profile", "https://www.googleapis.com/auth/userinfo.profile"],
411
- ]);
412
- const GRAPH_PREFIX = /^https:\/\/graph\.microsoft\.com\//i;
413
- /** `scopes` in the dialect's one spelling, deduplicated, order kept. */
414
95
  /**
415
- * `scopes` in the dialect's canonical spelling (Google's long names,
416
- * Microsoft's bare lower-case names), for comparing a set's scopes with
417
- * what a token response says it granted.
96
+ * The scopes an app declares that a connection doesn't hold: `held` is
97
+ * the connection's canonical list, `declared` as the app wrote them.
418
98
  */
419
- export function canonicalScopes(dialect, scopes) {
420
- return canonical(dialect, [...scopes]);
421
- }
422
- function canonical(dialect, scopes) {
423
- return pushNew([], scopes.map((scope) => {
424
- switch (dialect) {
425
- case "google":
426
- return GOOGLE_ALIASES.get(scope) ?? scope;
427
- case "microsoft":
428
- return scope.replace(GRAPH_PREFIX, "").toLowerCase();
429
- case "slack":
430
- case "space":
431
- case "comma":
432
- return scope;
433
- }
434
- }));
435
- }
436
- /**
437
- * A provider's scope field split into scopes, canonicalised, or null when
438
- * it isn't a string or names nothing. Google and Microsoft separate with
439
- * spaces; Slack with commas (spaces too, in its legacy form).
440
- */
441
- function splitScopes(dialect, value) {
442
- if (typeof value !== "string")
443
- return null;
444
- const separator = dialect === "slack" || dialect === "comma" ? /[,\s]+/ : /\s+/;
445
- const scopes = canonical(dialect, value.split(separator).filter(Boolean));
446
- return scopes.length > 0 ? scopes : null;
447
- }
448
- /** `into` with each of `more` it doesn't have yet, in order. */
449
- function pushNew(into, more) {
450
- for (const item of more)
451
- if (!into.includes(item))
452
- into.push(item);
453
- return into;
454
- }
455
- const FORM = "application/x-www-form-urlencoded";
456
- const JSON_TYPE = "application/json";
457
- /** A token request's body fields, form or JSON, by lowercased name; null for any other body. */
458
- function bodyFields(request) {
459
- if (!request.body)
460
- return null;
461
- const type = mediaType(request.headers.get("content-type"));
462
- if (type === FORM)
463
- return foldFields(new URLSearchParams(request.body));
464
- if (type === JSON_TYPE) {
465
- const parsed = jsonObject(request.body);
466
- return parsed && foldFields(Object.entries(parsed));
467
- }
468
- return null;
469
- }
470
- /**
471
- * `pairs` by lowercased name, as Entra reads a form's names in any case. A
472
- * name's values are one space-joined list, so a field sent twice, or as
473
- * `scope` and `Scope`, hides nothing in the second copy; a value that
474
- * isn't a string leaves its field not a string, which reads as naming
475
- * none.
476
- */
477
- function foldFields(pairs) {
478
- const fields = new Map();
479
- for (const [name, value] of pairs) {
480
- const key = name.toLowerCase();
481
- const before = fields.get(key);
482
- fields.set(key, !fields.has(key)
483
- ? value
484
- : typeof before === "string" && typeof value === "string"
485
- ? `${before} ${value}`
486
- : [before, value]);
487
- }
488
- return Object.fromEntries(fields);
489
- }
490
- /** A Content-Type's media type, lowercased and without parameters. */
491
- function mediaType(contentType) {
492
- return (contentType ?? "").split(";")[0].trim().toLowerCase();
99
+ export function missingScopes(rules, held, declared) {
100
+ const have = canonicalScopes(rules, held);
101
+ return declared.filter((scope) => !have.includes(canonicalScope(rules, scope)));
493
102
  }
494
103
  /**
495
104
  * `text` as a JSON object, or null for anything else (an array, a scalar,
496
- * not JSON). Shared with the gateway's read of a provider's token answer.
105
+ * not JSON). The gateway's read of a provider's token answer.
497
106
  */
498
107
  export function jsonObject(text) {
499
108
  try {
500
- return record(JSON.parse(text));
109
+ const value = JSON.parse(text);
110
+ return value && typeof value === "object" && !Array.isArray(value)
111
+ ? value
112
+ : null;
501
113
  }
502
114
  catch {
503
115
  return null;
504
116
  }
505
117
  }
506
- function record(value) {
507
- return value && typeof value === "object" && !Array.isArray(value)
508
- ? value
509
- : null;
510
- }