@browserstack/mcp-server 1.5.0-beta.21 → 1.5.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +32 -48
  2. package/capability/loadtesting.capability-index.json +1876 -0
  3. package/capability/tm.capability-index.json +50104 -0
  4. package/dist/config.d.ts +1 -4
  5. package/dist/config.js +2 -23
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +3 -7
  8. package/dist/lib/constants.d.ts +0 -3
  9. package/dist/lib/constants.js +0 -3
  10. package/dist/lib/instrumentation.d.ts +2 -14
  11. package/dist/lib/instrumentation.js +29 -104
  12. package/dist/lib/upload-validator.d.ts +2 -3
  13. package/dist/lib/upload-validator.js +15 -18
  14. package/dist/lib/utils.js +3 -10
  15. package/dist/lib/version-resolver.d.ts +5 -0
  16. package/dist/lib/version-resolver.js +2 -8
  17. package/dist/logger.js +10 -1
  18. package/dist/server-factory.js +6 -10
  19. package/dist/tools/accessibility.js +5 -9
  20. package/dist/tools/accessiblity-utils/accessibility-rag.js +1 -3
  21. package/dist/tools/appautomate-utils/native-execution/constants.js +2 -4
  22. package/dist/tools/appautomate.js +1 -3
  23. package/dist/tools/applive.js +1 -1
  24. package/dist/tools/automate.d.ts +0 -7
  25. package/dist/tools/automate.js +1 -104
  26. package/dist/tools/bstack-sdk.js +2 -2
  27. package/dist/tools/build-insights.js +2 -41
  28. package/dist/tools/capability-registry/bind.d.ts +29 -0
  29. package/dist/tools/capability-registry/bind.js +329 -0
  30. package/dist/tools/capability-registry/config.d.ts +62 -0
  31. package/dist/tools/capability-registry/config.js +218 -0
  32. package/dist/tools/capability-registry/discovery.d.ts +44 -0
  33. package/dist/tools/capability-registry/discovery.js +99 -0
  34. package/dist/tools/capability-registry/egress.d.ts +44 -0
  35. package/dist/tools/capability-registry/egress.js +174 -0
  36. package/dist/tools/capability-registry/index-loader.d.ts +133 -0
  37. package/dist/tools/capability-registry/index-loader.js +404 -0
  38. package/dist/tools/capability-registry/register.d.ts +48 -0
  39. package/dist/tools/capability-registry/register.js +604 -0
  40. package/dist/tools/capability-registry/resolve.d.ts +38 -0
  41. package/dist/tools/capability-registry/resolve.js +45 -0
  42. package/dist/tools/capability-registry/search.d.ts +170 -0
  43. package/dist/tools/capability-registry/search.js +709 -0
  44. package/dist/tools/capability-registry/types.d.ts +282 -0
  45. package/dist/tools/capability-registry/types.js +33 -0
  46. package/dist/tools/failurelogs-utils/app-automate.js +3 -4
  47. package/dist/tools/failurelogs-utils/automate.js +4 -5
  48. package/dist/tools/get-failure-logs.js +11 -30
  49. package/dist/tools/observability.js +1 -3
  50. package/dist/tools/percy-sdk.js +9 -9
  51. package/dist/tools/rca-agent-utils/format-rca.js +4 -5
  52. package/dist/tools/rca-agent-utils/get-failed-test-id.js +0 -12
  53. package/dist/tools/rca-agent-utils/types.d.ts +0 -1
  54. package/dist/tools/rca-agent.js +2 -5
  55. package/dist/tools/review-agent.js +1 -2
  56. package/dist/tools/sdk-utils/common/constants.d.ts +1 -1
  57. package/dist/tools/sdk-utils/common/constants.js +1 -2
  58. package/dist/tools/selfheal.js +3 -6
  59. package/dist/tools/testmanagement-utils/TCG-utils/api.js +7 -26
  60. package/dist/tools/testmanagement-utils/TCG-utils/config.d.ts +0 -2
  61. package/dist/tools/testmanagement-utils/TCG-utils/config.js +0 -5
  62. package/dist/tools/testmanagement-utils/testcase-from-file.js +1 -2
  63. package/dist/tools/testmanagement-utils/upload-file.js +2 -16
  64. package/dist/tools/testmanagement.js +17 -39
  65. package/package.json +11 -5
  66. package/dist/lib/node-version-notice.d.ts +0 -1
  67. package/dist/lib/node-version-notice.js +0 -9
  68. package/dist/lib/tool-latency.d.ts +0 -4
  69. package/dist/lib/tool-latency.js +0 -16
  70. package/dist/lib/untrusted-content.d.ts +0 -15
  71. package/dist/lib/untrusted-content.js +0 -24
  72. package/dist/tools/ask-browserstack/central-oauth.d.ts +0 -120
  73. package/dist/tools/ask-browserstack/central-oauth.js +0 -277
  74. package/dist/tools/ask-browserstack/config.d.ts +0 -102
  75. package/dist/tools/ask-browserstack/config.js +0 -140
  76. package/dist/tools/ask-browserstack/egress.d.ts +0 -34
  77. package/dist/tools/ask-browserstack/egress.js +0 -31
  78. package/dist/tools/ask-browserstack/register.d.ts +0 -61
  79. package/dist/tools/ask-browserstack/register.js +0 -416
  80. package/dist/tools/ask-browserstack/relay.d.ts +0 -201
  81. package/dist/tools/ask-browserstack/relay.js +0 -577
  82. package/dist/tools/ask-browserstack/stream.d.ts +0 -116
  83. package/dist/tools/ask-browserstack/stream.js +0 -236
  84. package/dist/tools/ask-browserstack/types.d.ts +0 -196
  85. package/dist/tools/ask-browserstack/types.js +0 -14
  86. package/dist/tools/automate-utils/list-session-ids.d.ts +0 -28
  87. package/dist/tools/automate-utils/list-session-ids.js +0 -87
  88. package/dist/tools/automate-utils/resolve-hashed-build-id.d.ts +0 -30
  89. package/dist/tools/automate-utils/resolve-hashed-build-id.js +0 -124
  90. package/dist/tools/failurelogs-utils/resolve-app-build-id.d.ts +0 -2
  91. package/dist/tools/failurelogs-utils/resolve-app-build-id.js +0 -5
  92. package/dist/tools/failurelogs-utils/video.d.ts +0 -3
  93. package/dist/tools/failurelogs-utils/video.js +0 -25
  94. package/dist/tools/tool-handoff.d.ts +0 -66
  95. package/dist/tools/tool-handoff.js +0 -78
@@ -1,120 +0,0 @@
1
- /**
2
- * Mint a BrowserStack central-OAuth JWT from the caller's username and access key.
3
- *
4
- * This replaces a shared delegation token, and the upgrade is not cosmetic.
5
- * `validate_delegation_token` refuses any token without `user.user_id`/`user.group_id`, so
6
- * what we mint here is USER-ATTESTED: Atlas sets `principal_verified=True`, takes the acting
7
- * user from signed claims rather than from anything we put in the request body, and reuses
8
- * this same JWT as its `egress_token` — so the product call a human approves runs as that
9
- * human, not as a shared service account.
10
- *
11
- * SECRET HYGIENE IS THE WHOLE POINT OF THIS MODULE, and Atlas's `central_oauth.py` learned
12
- * it the hard way: "The body can echo the credential back on some errors, so it is NOT
13
- * logged or raised — only the status." Neither the access key nor the minted token is ever
14
- * logged, returned, or put in an error message. Only a status code is.
15
- */
16
- import { Credentials } from "./egress.js";
17
- /**
18
- * BOTH PARTS ARE REQUIRED, AND THERE IS NO FALLBACK TO ANOTHER SCOPE.
19
- *
20
- * `oauth_user_profile` stays because it is what makes the pair obtainable through the
21
- * username+access_key flow at all. `ai_agent_notify` is what Atlas matches on
22
- * (`delegation.required_scope`, checked as exact membership of the token's `scopes` claim in
23
- * `web/oauth.py`); both halves move together with Atlas.
24
- *
25
- * THIS SCOPE MAY SIMPLY NOT BE ISSUABLE TO US, and the reasons are worth stating rather than
26
- * discovering. From the merged `browserstack/railsApp#175367` (2026-08-24):
27
- *
28
- * - `ai_agent_notify` is documented there as CLIENT_ID/SECRET auth, and
29
- * `USERNAME_ACCESS_KEY_ONLY_SCOPES` remains only `user_management, oauth_user_profile`.
30
- * We are on the username+access_key flow, which those restrictions are not written for.
31
- * - It is additionally covered by a new
32
- * `APP_REGISTERED_SCOPE_REQUIRED = %w[ai_agent ai_agent_notify]` gate, requiring the
33
- * calling APPLICATION to be registered for it — though that gate sits in the
34
- * `client_id + client_secret` path, not ours.
35
- * - railsApp defines it as the PRODUCT -> AGENT direction: "a product reporting progress
36
- * back to an AI agent for work the agent dispatched." We use it in the opposite
37
- * direction, as an agent -> Atlas inbound credential.
38
- * - `central_ai_s2s`, which this replaces, was deliberately EXCLUDED from that new gate.
39
- *
40
- * So this is strictly more restricted than what it replaces. If the endpoint refuses it, that
41
- * is a PROVISIONING problem — the scope is not available to this credential type or this
42
- * application — and it is reported as one, naming the scope. It is never retried with a
43
- * different scope: a silent downgrade to a different authorization is exactly the kind of
44
- * thing nobody notices until it matters.
45
- */
46
- export declare const CENTRAL_SCOPE = "oauth_user_profile ai_agent_notify";
47
- /** What we ask for. The endpoint clamps to its own maximum, so the response wins. */
48
- export declare const REQUESTED_EXPIRES_IN = 3600;
49
- /**
50
- * Treat a token as stale this long before it actually expires.
51
- *
52
- * NOT the usual small skew. This token is not merely used to open the request — Atlas holds
53
- * it for the life of the run and re-uses it for product egress, so it has to outlive the
54
- * whole call, and our own `/agent` budget is already 330s. Handing out a token with 61
55
- * seconds left would mean a human approves a write and the egress that follows fails on an
56
- * expired credential, which is the exact mid-flight expiry this cache exists to prevent.
57
- */
58
- export declare const REFRESH_SKEW_MS: number;
59
- /** The token endpoint gets its own, much shorter budget than `/agent`. */
60
- export declare const TOKEN_TIMEOUT_MS = 15000;
61
- export interface TokenResponse {
62
- status: number;
63
- body: unknown;
64
- /** Only when there was no response at all to speak for itself. */
65
- error?: string;
66
- }
67
- export type TokenTransport = (url: string, form: Record<string, string>) => Promise<TokenResponse>;
68
- /**
69
- * Was this refusal about the SCOPE or about the CREDENTIAL?
70
- *
71
- * The two need completely different fixes — provisioning versus a password — so collapsing
72
- * them into one message sends someone to the wrong place entirely. Our form has five fields
73
- * and four of them are constants, so a refusal of the REQUEST (as opposed to the caller) can
74
- * only really be about the scope.
75
- *
76
- * Nothing from the body is ever surfaced; the code is used to classify and then discarded.
77
- */
78
- export declare function refusalIsAboutScope(status: number, body: unknown): boolean;
79
- /**
80
- * The ways authentication can fail, kept apart because a user cannot act on them otherwise.
81
- *
82
- * `scope refused` is a provisioning problem; `rejected` is "your credentials are wrong";
83
- * `unreachable` is "auth is down". A fourth — Atlas refusing a token we minted successfully —
84
- * is a server misconfiguration and lives in `relay.ts`, because it is discovered from
85
- * `/agent`. Four different fixes, so four different sentences.
86
- */
87
- export declare const AUTH_SCOPE_REFUSED_DETAIL: (status: number) => string;
88
- export declare const AUTH_REJECTED_DETAIL: (status: number) => string;
89
- export declare const AUTH_UNREACHABLE_DETAIL: string;
90
- /**
91
- * A 5xx from auth: their service is down, not your password.
92
- *
93
- * Split out because routing 5xx to `AUTH_REJECTED_DETAIL` actively misdirects the reader,
94
- * and did: a preprod outage returned 503 and the tool answered "Your BrowserStack
95
- * credentials were rejected … Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY",
96
- * sending someone to audit env vars that had worked minutes earlier. The status alone
97
- * settles it — OAuth2 says a bad client is 401/403 and a bad request is 400, so nothing in
98
- * the 5xx range is ever a statement about the caller.
99
- */
100
- export declare const AUTH_SERVER_ERROR_DETAIL: (status: number) => string;
101
- export declare const AUTH_UNUSABLE_DETAIL: (status: number) => string;
102
- /** Drop every cached token. For tests, and for a credential rotation. */
103
- export declare function resetTokenCache(): void;
104
- /**
105
- * The token endpoint, through `apiClient` per rules/security.md — no bare `fetch`.
106
- *
107
- * `raise_error: false` keeps the status-first contract this transport has always had: the
108
- * caller distinguishes a 400 scope refusal from a 401 rejection from an unreachable host,
109
- * so a thrown AxiosError on any non-2xx would destroy the only signal it reads.
110
- */
111
- export declare function fetchTokenTransport(timeoutMs?: number): TokenTransport;
112
- /** The exact form body of the `client_credentials` grant. */
113
- export declare function mintForm(credentials: Credentials): Record<string, string>;
114
- /**
115
- * Return a valid token, minting one only when the cache has nothing fresh.
116
- *
117
- * Minting per tool call would add a round trip to every request and make the token endpoint
118
- * a hot dependency of the whole surface.
119
- */
120
- export declare function mintCentralToken(url: string, credentials: Credentials, transport: TokenTransport, now?: number): Promise<string>;
@@ -1,277 +0,0 @@
1
- /**
2
- * Mint a BrowserStack central-OAuth JWT from the caller's username and access key.
3
- *
4
- * This replaces a shared delegation token, and the upgrade is not cosmetic.
5
- * `validate_delegation_token` refuses any token without `user.user_id`/`user.group_id`, so
6
- * what we mint here is USER-ATTESTED: Atlas sets `principal_verified=True`, takes the acting
7
- * user from signed claims rather than from anything we put in the request body, and reuses
8
- * this same JWT as its `egress_token` — so the product call a human approves runs as that
9
- * human, not as a shared service account.
10
- *
11
- * SECRET HYGIENE IS THE WHOLE POINT OF THIS MODULE, and Atlas's `central_oauth.py` learned
12
- * it the hard way: "The body can echo the credential back on some errors, so it is NOT
13
- * logged or raised — only the status." Neither the access key nor the minted token is ever
14
- * logged, returned, or put in an error message. Only a status code is.
15
- */
16
- import { createHash } from "node:crypto";
17
- import { apiClient } from "../../lib/apiClient.js";
18
- import appConfig from "../../config.js";
19
- import logger from "../../logger.js";
20
- import { AGENT_TIMEOUT_MS, AskError } from "./config.js";
21
- /**
22
- * BOTH PARTS ARE REQUIRED, AND THERE IS NO FALLBACK TO ANOTHER SCOPE.
23
- *
24
- * `oauth_user_profile` stays because it is what makes the pair obtainable through the
25
- * username+access_key flow at all. `ai_agent_notify` is what Atlas matches on
26
- * (`delegation.required_scope`, checked as exact membership of the token's `scopes` claim in
27
- * `web/oauth.py`); both halves move together with Atlas.
28
- *
29
- * THIS SCOPE MAY SIMPLY NOT BE ISSUABLE TO US, and the reasons are worth stating rather than
30
- * discovering. From the merged `browserstack/railsApp#175367` (2026-08-24):
31
- *
32
- * - `ai_agent_notify` is documented there as CLIENT_ID/SECRET auth, and
33
- * `USERNAME_ACCESS_KEY_ONLY_SCOPES` remains only `user_management, oauth_user_profile`.
34
- * We are on the username+access_key flow, which those restrictions are not written for.
35
- * - It is additionally covered by a new
36
- * `APP_REGISTERED_SCOPE_REQUIRED = %w[ai_agent ai_agent_notify]` gate, requiring the
37
- * calling APPLICATION to be registered for it — though that gate sits in the
38
- * `client_id + client_secret` path, not ours.
39
- * - railsApp defines it as the PRODUCT -> AGENT direction: "a product reporting progress
40
- * back to an AI agent for work the agent dispatched." We use it in the opposite
41
- * direction, as an agent -> Atlas inbound credential.
42
- * - `central_ai_s2s`, which this replaces, was deliberately EXCLUDED from that new gate.
43
- *
44
- * So this is strictly more restricted than what it replaces. If the endpoint refuses it, that
45
- * is a PROVISIONING problem — the scope is not available to this credential type or this
46
- * application — and it is reported as one, naming the scope. It is never retried with a
47
- * different scope: a silent downgrade to a different authorization is exactly the kind of
48
- * thing nobody notices until it matters.
49
- */
50
- export const CENTRAL_SCOPE = "oauth_user_profile ai_agent_notify";
51
- /** What we ask for. The endpoint clamps to its own maximum, so the response wins. */
52
- export const REQUESTED_EXPIRES_IN = 3600;
53
- /**
54
- * Treat a token as stale this long before it actually expires.
55
- *
56
- * NOT the usual small skew. This token is not merely used to open the request — Atlas holds
57
- * it for the life of the run and re-uses it for product egress, so it has to outlive the
58
- * whole call, and our own `/agent` budget is already 330s. Handing out a token with 61
59
- * seconds left would mean a human approves a write and the egress that follows fails on an
60
- * expired credential, which is the exact mid-flight expiry this cache exists to prevent.
61
- */
62
- export const REFRESH_SKEW_MS = AGENT_TIMEOUT_MS + 60_000;
63
- /** The token endpoint gets its own, much shorter budget than `/agent`. */
64
- export const TOKEN_TIMEOUT_MS = 15_000;
65
- /**
66
- * The OAuth2 error codes we are willing to read out of a failure body.
67
- *
68
- * `error` is a fixed enum token in the spec, so it cannot carry a credential; `error_description`
69
- * is free text and demonstrably CAN ("access_key <key> is invalid"), which is why only the
70
- * code is ever looked at and only when it is one of these. Anything else is ignored entirely
71
- * and the classification falls back to the status.
72
- */
73
- const SCOPE_ERROR_CODES = [
74
- "invalid_scope",
75
- "unauthorized_client",
76
- "invalid_request",
77
- ];
78
- const CREDENTIAL_ERROR_CODES = [
79
- "invalid_client",
80
- "invalid_grant",
81
- "access_denied",
82
- ];
83
- /**
84
- * Was this refusal about the SCOPE or about the CREDENTIAL?
85
- *
86
- * The two need completely different fixes — provisioning versus a password — so collapsing
87
- * them into one message sends someone to the wrong place entirely. Our form has five fields
88
- * and four of them are constants, so a refusal of the REQUEST (as opposed to the caller) can
89
- * only really be about the scope.
90
- *
91
- * Nothing from the body is ever surfaced; the code is used to classify and then discarded.
92
- */
93
- export function refusalIsAboutScope(status, body) {
94
- const payload = typeof body === "object" && body !== null
95
- ? body
96
- : {};
97
- const code = typeof payload.error === "string" ? payload.error : "";
98
- if (SCOPE_ERROR_CODES.includes(code))
99
- return true;
100
- if (CREDENTIAL_ERROR_CODES.includes(code))
101
- return false;
102
- // No usable code. OAuth2 answers a bad REQUEST with 400 and a bad CLIENT with 401/403, so
103
- // the status is the next best evidence.
104
- return status === 400;
105
- }
106
- /**
107
- * The ways authentication can fail, kept apart because a user cannot act on them otherwise.
108
- *
109
- * `scope refused` is a provisioning problem; `rejected` is "your credentials are wrong";
110
- * `unreachable` is "auth is down". A fourth — Atlas refusing a token we minted successfully —
111
- * is a server misconfiguration and lives in `relay.ts`, because it is discovered from
112
- * `/agent`. Four different fixes, so four different sentences.
113
- */
114
- export const AUTH_SCOPE_REFUSED_DETAIL = (status) => `BrowserStack auth would not issue a token for the scope "${CENTRAL_SCOPE}" (HTTP ${status}). ` +
115
- `YOUR CREDENTIALS ARE NOT THE PROBLEM — this is a provisioning problem: \`ai_agent_notify\` ` +
116
- `is documented as a client_id/secret scope, it is not in the username+access_key allow ` +
117
- `list, and it carries an application-registration requirement. It has to be enabled for ` +
118
- `this account or application; a different password will not help, and this server will ` +
119
- `NOT quietly retry with a weaker scope. NOTHING REACHED THE AGENT — no request was made, ` +
120
- `no prompt appeared and nothing was changed.`;
121
- export const AUTH_REJECTED_DETAIL = (status) => `Your BrowserStack credentials were rejected by BrowserStack auth (HTTP ${status}). ` +
122
- `NOTHING REACHED THE AGENT — no request was made, no prompt appeared and nothing was ` +
123
- `changed. Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`;
124
- export const AUTH_UNREACHABLE_DETAIL = "Could not reach BrowserStack auth to sign in. NOTHING REACHED THE AGENT — no request " +
125
- "was made, no prompt appeared and nothing was changed. This is a connectivity or " +
126
- "auth-server problem, not a problem with your credentials.";
127
- /**
128
- * A 5xx from auth: their service is down, not your password.
129
- *
130
- * Split out because routing 5xx to `AUTH_REJECTED_DETAIL` actively misdirects the reader,
131
- * and did: a preprod outage returned 503 and the tool answered "Your BrowserStack
132
- * credentials were rejected … Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY",
133
- * sending someone to audit env vars that had worked minutes earlier. The status alone
134
- * settles it — OAuth2 says a bad client is 401/403 and a bad request is 400, so nothing in
135
- * the 5xx range is ever a statement about the caller.
136
- */
137
- export const AUTH_SERVER_ERROR_DETAIL = (status) => `BrowserStack auth is unavailable (HTTP ${status}). YOUR CREDENTIALS ARE NOT THE ` +
138
- `PROBLEM — a 5xx is the auth service failing, not a rejection, so there is nothing to ` +
139
- `change on your side and nothing to retry differently. NOTHING REACHED THE AGENT — no ` +
140
- `request was made, no prompt appeared and nothing was changed. Try again once ` +
141
- `BrowserStack auth is back.`;
142
- export const AUTH_UNUSABLE_DETAIL = (status) => `BrowserStack auth answered HTTP ${status} without issuing a token. NOTHING REACHED THE ` +
143
- `AGENT — no request was made, no prompt appeared and nothing was changed.`;
144
- const cache = new Map();
145
- /** Drop every cached token. For tests, and for a credential rotation. */
146
- export function resetTokenCache() {
147
- cache.clear();
148
- }
149
- /**
150
- * The cache key.
151
- *
152
- * Keyed on the access key so that ROTATING it mints immediately rather than leaving a
153
- * revoked credential working until expiry — but on a SHA-256 of it, never the value, so the
154
- * secret is not left sitting in a map key for the life of the process.
155
- */
156
- function cacheKey(url, credentials) {
157
- const digest = createHash("sha256")
158
- .update(credentials.accessKey)
159
- .digest("hex");
160
- return `${url} ${credentials.username} ${CENTRAL_SCOPE} ${digest}`;
161
- }
162
- /**
163
- * The token endpoint, through `apiClient` per rules/security.md — no bare `fetch`.
164
- *
165
- * `raise_error: false` keeps the status-first contract this transport has always had: the
166
- * caller distinguishes a 400 scope refusal from a 401 rejection from an unreachable host,
167
- * so a thrown AxiosError on any non-2xx would destroy the only signal it reads.
168
- */
169
- export function fetchTokenTransport(timeoutMs = TOKEN_TIMEOUT_MS) {
170
- return async (url, form) => {
171
- try {
172
- const response = await apiClient.post({
173
- url,
174
- headers: {
175
- "Content-Type": "application/x-www-form-urlencoded",
176
- Accept: "application/json",
177
- },
178
- body: new URLSearchParams(form).toString(),
179
- timeout: timeoutMs,
180
- raise_error: false,
181
- });
182
- return { status: response.status, body: response.data ?? null };
183
- }
184
- catch {
185
- // DNS, TLS, timeout — all of them mean "no token". The reason is deliberately not
186
- // carried: it can name the URL and, on some stacks, echo the request body.
187
- return { status: 0, body: null, error: "auth could not be reached" };
188
- }
189
- };
190
- }
191
- /** The exact form body of the `client_credentials` grant. */
192
- export function mintForm(credentials) {
193
- return {
194
- grant_type: "client_credentials",
195
- username: credentials.username,
196
- access_key: credentials.accessKey,
197
- scope: CENTRAL_SCOPE,
198
- expires_in: String(REQUESTED_EXPIRES_IN),
199
- };
200
- }
201
- async function mintOnce(url, credentials, transport) {
202
- const response = await transport(url, mintForm(credentials));
203
- if (response.status === 0)
204
- throw new AskError(AUTH_UNREACHABLE_DETAIL);
205
- // 5xx BEFORE the refusal branch: a server error is not a refusal, and reading it as one
206
- // is worse than saying nothing — it names the caller's credentials as the fault.
207
- if (response.status >= 500) {
208
- throw new AskError(AUTH_SERVER_ERROR_DETAIL(response.status));
209
- }
210
- if (response.status !== 200) {
211
- // ONLY THE STATUS CROSSES. The body is read solely to tell a provisioning problem from a
212
- // credential one, and nothing out of it is ever put in the message — a non-200 body can
213
- // echo the access key straight back.
214
- throw new AskError(refusalIsAboutScope(response.status, response.body)
215
- ? AUTH_SCOPE_REFUSED_DETAIL(response.status)
216
- : AUTH_REJECTED_DETAIL(response.status));
217
- }
218
- const body = typeof response.body === "object" && response.body !== null
219
- ? response.body
220
- : {};
221
- const token = body.access_token;
222
- if (typeof token !== "string" || !token) {
223
- throw new AskError(AUTH_UNUSABLE_DETAIL(response.status));
224
- }
225
- // Trust the SERVER's lifetime over what we asked for — it clamps to its own maximum, and
226
- // caching for the requested hour when it granted less would hand out a dead token.
227
- const granted = Number(body.expires_in);
228
- const seconds = Number.isFinite(granted) && granted > 0 ? granted : REQUESTED_EXPIRES_IN;
229
- return { token, lifetimeMs: seconds * 1000 };
230
- }
231
- /**
232
- * Return a valid token, minting one only when the cache has nothing fresh.
233
- *
234
- * Minting per tool call would add a round trip to every request and make the token endpoint
235
- * a hot dependency of the whole surface.
236
- */
237
- export async function mintCentralToken(url, credentials, transport, now = Date.now()) {
238
- // Refused before any network call, and by name: these ARE the auth credential now, not
239
- // merely attribution, so an empty one is our missing configuration rather than the user's
240
- // rejected password, and must not read like one.
241
- if (!credentials?.username || !credentials?.accessKey) {
242
- throw new AskError("BrowserStack AI is not authenticated: BROWSERSTACK_USERNAME and " +
243
- "BROWSERSTACK_ACCESS_KEY are required to sign in");
244
- }
245
- // NOT CACHED IN HOSTED MODE. These tokens are per-user, attested credentials, and the
246
- // process is shared by every tenant — `rules/multi-tenant-safety.md` forbids holding user
247
- // data in module-level state there, so remote mode mints per call. Keying on
248
- // username + sha256(accessKey) already means one user can never be SERVED another's token,
249
- // but containment is not the contract; not holding it at all is.
250
- if (appConfig.REMOTE_MCP) {
251
- return mintOnce(url, credentials, transport).then(({ token }) => {
252
- logger.info("askBrowserStackAI: signed in as %s", credentials.username);
253
- return token;
254
- });
255
- }
256
- const key = cacheKey(url, credentials);
257
- const entry = cache.get(key);
258
- if (entry && entry.token && now < entry.expiresAt - REFRESH_SKEW_MS) {
259
- return entry.token;
260
- }
261
- // Double-checked through a shared promise: concurrent callers await the same mint.
262
- if (entry?.inflight)
263
- return entry.inflight;
264
- const pending = mintOnce(url, credentials, transport)
265
- .then(({ token, lifetimeMs }) => {
266
- cache.set(key, { token, expiresAt: now + lifetimeMs });
267
- logger.info("askBrowserStackAI: signed in as %s (lifetime %ss)", credentials.username, Math.round(lifetimeMs / 1000));
268
- return token;
269
- })
270
- .catch((error) => {
271
- // Never leave a rejected promise cached, or every later call inherits this failure.
272
- cache.delete(key);
273
- throw error;
274
- });
275
- cache.set(key, { token: "", expiresAt: 0, inflight: pending });
276
- return pending;
277
- }
@@ -1,102 +0,0 @@
1
- /**
2
- * Where Atlas lives, and the timeout ladder.
3
- *
4
- * The host IS compiled in, matching every other tool here — `TM_BASE_URLS`, the
5
- * instrumentation endpoint — so an install needs no configuration to work. One env var
6
- * overrides it. See the warning on `DEFAULT_ATLAS_URL`: the compiled-in value is currently
7
- * STAGING and is a deliberate placeholder.
8
- */
9
- /**
10
- * CONTRACT §4 — the timeout ladder, outermost first. EACH LAYER MUST EXCEED THE ONE INSIDE
11
- * IT, or a layer dies before the layer it is waiting on can answer:
12
- *
13
- * MCP client -> tool call longest, client-side, not ours
14
- * POST /agent HTTP request 330s <- here
15
- * Atlas gate -> stream ask 300s Atlas's `permission_relay_timeout`
16
- * elicitInput 270s <- here
17
- *
18
- * 300s is the browser path's existing PERMISSION_TIMEOUT, which also auto-rejects.
19
- */
20
- export declare const AGENT_TIMEOUT_MS = 330000;
21
- export declare const ELICITATION_TIMEOUT_MS = 270000;
22
- /** Thrown for anything this tool refuses to attempt. Never carries a credential. */
23
- export declare class AskError extends Error {
24
- }
25
- /**
26
- * Off by default is wrong for a shipped feature, but a kill switch is not.
27
- *
28
- * The only setting here still read from `process.env` per call, and deliberately: a kill
29
- * switch that needs a process restart is slowest exactly when it is needed fastest. The
30
- * other three are on the config singleton (rules/tool-design.md).
31
- */
32
- export declare function isEnabled(): boolean;
33
- /**
34
- * May the relay be offered in the hosted (`REMOTE_MCP`) deployment?
35
- *
36
- * OFF BY DEFAULT, because it depends on something outside this package: the host has to
37
- * keep one `McpServer` alive per session. Stateless hosts build a fresh server per POST,
38
- * and an elicitation answer — which arrives as a SEPARATE POST — then reaches an instance
39
- * that never asked anything, leaving the real one suspended until it times out. So this
40
- * must stay opt-in per deployment rather than become a default that silently hangs.
41
- *
42
- * Turning it on does NOT force the relay on: `relayMode` still asks whether THIS client
43
- * declared the `elicitation` capability, and a client that did not still gets a read-only
44
- * run. This flag only removes the blanket refusal.
45
- */
46
- export declare function allowRemoteRelay(): boolean;
47
- /**
48
- * ============================================================================
49
- * PRODUCTION DEFAULTS
50
- * ============================================================================
51
- *
52
- * These hosts are PRODUCTION. They replace the interim staging placeholders that this
53
- * package shipped with while the relay was being built ("for now lets hardcode the
54
- * base_url to staging only then we will point this to prod url later") — that step is
55
- * now done.
56
- *
57
- * `https://workflows.browserstack.com` was verified, not guessed: its `/api/profiles`
58
- * answers `401 {"detail":"authentication required"}`, byte-identical to staging Atlas.
59
- * The production auth endpoint is `https://auth.browserstack.com/oauth2/v2/token`.
60
- *
61
- * WHY THIS MATTERS: this package publishes to npm as `@browserstack/mcp-server`, so an
62
- * install with no environment variables set now talks to PRODUCTION. That is correct for
63
- * a production deployment, but it removes the old safety property — a misconfigured or
64
- * test deployment that forgets `ASK_BROWSERSTACK_ATLAS_URL` no longer fails safe onto
65
- * staging, it reads and writes REAL customer data. Non-production deployments MUST set
66
- * that variable explicitly. The resolved host is logged at info on first use, naming
67
- * whether it came from the env var or from here, so a deployment pointing at the wrong
68
- * Atlas is visible in a log line rather than inferred later from confusing data.
69
- *
70
- * Staging hosts, for anyone setting the override:
71
- * ASK_BROWSERSTACK_ATLAS_URL = https://ai-platform-service.bsstag.com
72
- * ASK_BROWSERSTACK_AUTH_TOKEN_URL = https://auth-preprod.bsstag.com/oauth2/v2/token
73
- *
74
- * The tests assert these literals precisely so that repointing has to be deliberate
75
- * rather than something that slips through.
76
- *
77
- * grep: DEFAULT-PROD-HOSTS
78
- */
79
- export declare const DEFAULT_ATLAS_URL = "https://workflows.browserstack.com";
80
- export declare const DEFAULT_AUTH_TOKEN_URL = "https://auth.browserstack.com/oauth2/v2/token";
81
- /** For tests, and for anything that legitimately re-resolves. */
82
- export declare function resetHostAnnouncements(): void;
83
- /**
84
- * Resolve Atlas's base URL:
85
- *
86
- * 1. ASK_BROWSERSTACK_ATLAS_URL explicit override
87
- * 2. the built-in staging default (see the warning above)
88
- *
89
- * Matching every other tool here, which ships its host in the code and treats the env var as
90
- * an override — `TM_BASE_URLS`, the instrumentation endpoint. There is no environment map and
91
- * no selector: one default, one override.
92
- */
93
- export declare function atlasBaseUrl(): string;
94
- /** Resolved per call, never captured at construction. */
95
- export declare function agentUrl(): string;
96
- /**
97
- * Where a central-OAuth JWT is minted (CONTRACT v1.2 §I, as amended by task 7).
98
- *
99
- * The shared `delegation.token` path is gone from Atlas, so a user-attested central JWT is
100
- * the only way in. Same two rungs as the host, and the same staging default.
101
- */
102
- export declare function authTokenUrl(): string;
@@ -1,140 +0,0 @@
1
- import appConfig from "../../config.js";
2
- import logger from "../../logger.js";
3
- /**
4
- * Where Atlas lives, and the timeout ladder.
5
- *
6
- * The host IS compiled in, matching every other tool here — `TM_BASE_URLS`, the
7
- * instrumentation endpoint — so an install needs no configuration to work. One env var
8
- * overrides it. See the warning on `DEFAULT_ATLAS_URL`: the compiled-in value is currently
9
- * STAGING and is a deliberate placeholder.
10
- */
11
- /**
12
- * CONTRACT §4 — the timeout ladder, outermost first. EACH LAYER MUST EXCEED THE ONE INSIDE
13
- * IT, or a layer dies before the layer it is waiting on can answer:
14
- *
15
- * MCP client -> tool call longest, client-side, not ours
16
- * POST /agent HTTP request 330s <- here
17
- * Atlas gate -> stream ask 300s Atlas's `permission_relay_timeout`
18
- * elicitInput 270s <- here
19
- *
20
- * 300s is the browser path's existing PERMISSION_TIMEOUT, which also auto-rejects.
21
- */
22
- export const AGENT_TIMEOUT_MS = 330_000;
23
- export const ELICITATION_TIMEOUT_MS = 270_000;
24
- /** Thrown for anything this tool refuses to attempt. Never carries a credential. */
25
- export class AskError extends Error {
26
- }
27
- /**
28
- * Off by default is wrong for a shipped feature, but a kill switch is not.
29
- *
30
- * The only setting here still read from `process.env` per call, and deliberately: a kill
31
- * switch that needs a process restart is slowest exactly when it is needed fastest. The
32
- * other three are on the config singleton (rules/tool-design.md).
33
- */
34
- export function isEnabled() {
35
- return (process.env.ASK_BROWSERSTACK_DISABLED || "").toLowerCase() !== "true";
36
- }
37
- /**
38
- * May the relay be offered in the hosted (`REMOTE_MCP`) deployment?
39
- *
40
- * OFF BY DEFAULT, because it depends on something outside this package: the host has to
41
- * keep one `McpServer` alive per session. Stateless hosts build a fresh server per POST,
42
- * and an elicitation answer — which arrives as a SEPARATE POST — then reaches an instance
43
- * that never asked anything, leaving the real one suspended until it times out. So this
44
- * must stay opt-in per deployment rather than become a default that silently hangs.
45
- *
46
- * Turning it on does NOT force the relay on: `relayMode` still asks whether THIS client
47
- * declared the `elicitation` capability, and a client that did not still gets a read-only
48
- * run. This flag only removes the blanket refusal.
49
- */
50
- export function allowRemoteRelay() {
51
- return appConfig.ASK_BROWSERSTACK_ALLOW_REMOTE_RELAY;
52
- }
53
- /**
54
- * ============================================================================
55
- * PRODUCTION DEFAULTS
56
- * ============================================================================
57
- *
58
- * These hosts are PRODUCTION. They replace the interim staging placeholders that this
59
- * package shipped with while the relay was being built ("for now lets hardcode the
60
- * base_url to staging only then we will point this to prod url later") — that step is
61
- * now done.
62
- *
63
- * `https://workflows.browserstack.com` was verified, not guessed: its `/api/profiles`
64
- * answers `401 {"detail":"authentication required"}`, byte-identical to staging Atlas.
65
- * The production auth endpoint is `https://auth.browserstack.com/oauth2/v2/token`.
66
- *
67
- * WHY THIS MATTERS: this package publishes to npm as `@browserstack/mcp-server`, so an
68
- * install with no environment variables set now talks to PRODUCTION. That is correct for
69
- * a production deployment, but it removes the old safety property — a misconfigured or
70
- * test deployment that forgets `ASK_BROWSERSTACK_ATLAS_URL` no longer fails safe onto
71
- * staging, it reads and writes REAL customer data. Non-production deployments MUST set
72
- * that variable explicitly. The resolved host is logged at info on first use, naming
73
- * whether it came from the env var or from here, so a deployment pointing at the wrong
74
- * Atlas is visible in a log line rather than inferred later from confusing data.
75
- *
76
- * Staging hosts, for anyone setting the override:
77
- * ASK_BROWSERSTACK_ATLAS_URL = https://ai-platform-service.bsstag.com
78
- * ASK_BROWSERSTACK_AUTH_TOKEN_URL = https://auth-preprod.bsstag.com/oauth2/v2/token
79
- *
80
- * The tests assert these literals precisely so that repointing has to be deliberate
81
- * rather than something that slips through.
82
- *
83
- * grep: DEFAULT-PROD-HOSTS
84
- */
85
- export const DEFAULT_ATLAS_URL = "https://workflows.browserstack.com";
86
- export const DEFAULT_AUTH_TOKEN_URL = "https://auth.browserstack.com/oauth2/v2/token";
87
- /** An operator's override may carry a trailing slash; the constants above do not. */
88
- function trimUrl(value) {
89
- return value.trim().replace(/\/+$/, "");
90
- }
91
- /**
92
- * Announced ONCE per distinct resolution, not per tool call.
93
- *
94
- * The point is that a deployment talking to the wrong Atlas shows up in the log; repeating it
95
- * on every call would only make it easier to scroll past.
96
- */
97
- const announced = new Set();
98
- /** For tests, and for anything that legitimately re-resolves. */
99
- export function resetHostAnnouncements() {
100
- announced.clear();
101
- }
102
- function announce(what, url, source) {
103
- const line = `${what}|${url}|${source}`;
104
- if (announced.has(line))
105
- return;
106
- announced.add(line);
107
- logger.info("askBrowserStackAI: %s is %s (source: %s)", what, url, source);
108
- }
109
- /**
110
- * Resolve Atlas's base URL:
111
- *
112
- * 1. ASK_BROWSERSTACK_ATLAS_URL explicit override
113
- * 2. the built-in staging default (see the warning above)
114
- *
115
- * Matching every other tool here, which ships its host in the code and treats the env var as
116
- * an override — `TM_BASE_URLS`, the instrumentation endpoint. There is no environment map and
117
- * no selector: one default, one override.
118
- */
119
- export function atlasBaseUrl() {
120
- const explicit = appConfig.ASK_BROWSERSTACK_ATLAS_URL;
121
- const url = explicit && explicit.trim() ? trimUrl(explicit) : DEFAULT_ATLAS_URL;
122
- announce("Atlas", url, explicit && explicit.trim() ? "env" : "default");
123
- return url;
124
- }
125
- /** Resolved per call, never captured at construction. */
126
- export function agentUrl() {
127
- return `${atlasBaseUrl()}/agent`;
128
- }
129
- /**
130
- * Where a central-OAuth JWT is minted (CONTRACT v1.2 §I, as amended by task 7).
131
- *
132
- * The shared `delegation.token` path is gone from Atlas, so a user-attested central JWT is
133
- * the only way in. Same two rungs as the host, and the same staging default.
134
- */
135
- export function authTokenUrl() {
136
- const explicit = appConfig.ASK_BROWSERSTACK_AUTH_TOKEN_URL;
137
- const url = explicit && explicit.trim() ? trimUrl(explicit) : DEFAULT_AUTH_TOKEN_URL;
138
- announce("auth token endpoint", url, explicit && explicit.trim() ? "env" : "default");
139
- return url;
140
- }