@mitralab.io/platform-sdk 1.2.0-beta.1 → 1.2.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -60,7 +60,7 @@ function stripTrailingSlashes(value) {
60
60
  }
61
61
 
62
62
  // src/client.ts
63
- var import_sdk_core10 = require("@mitralab.io/sdk-core");
63
+ var import_sdk_core11 = require("@mitralab.io/sdk-core");
64
64
 
65
65
  // src/utils/http-client.ts
66
66
  var bearerCredentialPattern = /(Bearer\s+)\S+/gi;
@@ -95,6 +95,12 @@ function asErrorPayload(value) {
95
95
  function optionalString(value) {
96
96
  return typeof value === "string" ? value : void 0;
97
97
  }
98
+ function readRetryAfterSeconds(response) {
99
+ const header = response.headers?.get("Retry-After");
100
+ if (!header) return null;
101
+ const seconds = Number(header.trim());
102
+ return Number.isInteger(seconds) && seconds >= 0 ? seconds : null;
103
+ }
98
104
  function buildRequestUrl(baseUrl, path, params) {
99
105
  const url = `${baseUrl}${path}`;
100
106
  if (!params) return url;
@@ -195,7 +201,8 @@ var HttpClient = class {
195
201
  redactText(rawMessage || `Request failed with status ${response.status}`, token),
196
202
  response.status,
197
203
  rawCode === void 0 ? void 0 : redactText(rawCode, token),
198
- redactDetails(errorBody, token)
204
+ redactDetails(errorBody, token),
205
+ readRetryAfterSeconds(response)
199
206
  );
200
207
  }
201
208
  async parseResponseBody(response, path) {
@@ -283,11 +290,12 @@ var HttpClient = class {
283
290
  }
284
291
  };
285
292
  var MitraApiError = class extends Error {
286
- constructor(message, status, code, details) {
293
+ constructor(message, status, code, details, retryAfterSeconds = null) {
287
294
  super(message);
288
295
  this.status = status;
289
296
  this.code = code;
290
297
  this.details = details;
298
+ this.retryAfterSeconds = retryAfterSeconds;
291
299
  this.name = "MitraApiError";
292
300
  }
293
301
  };
@@ -396,7 +404,7 @@ function adoptLegacySession(session) {
396
404
  }
397
405
 
398
406
  // src/modules/auth.ts
399
- var import_sdk_core3 = require("@mitralab.io/sdk-core");
407
+ var import_sdk_core4 = require("@mitralab.io/sdk-core");
400
408
 
401
409
  // src/modules/api-key-auth.ts
402
410
  var import_sdk_core = require("@mitralab.io/sdk-core");
@@ -590,7 +598,10 @@ var AuthPageFlow = class {
590
598
  );
591
599
  const completedInAnotherTab = this.profile.pendingRequestTtlMs !== void 0;
592
600
  if (completedInAnotherTab) {
593
- this.writeRedirectContext(browserWindow, this.newRedirectContext(state, authPageUrl));
601
+ this.writeRedirectContext(
602
+ browserWindow,
603
+ this.newRedirectContext(state, this.getRedirectUri(authPageUrl))
604
+ );
594
605
  }
595
606
  const popup = this.openPopup(browserWindow, this.buildStartUrl(browserWindow, authPageUrl, state));
596
607
  const result = await this.waitForPopupResult(browserWindow, popup, authPageUrl.origin, state);
@@ -605,7 +616,8 @@ var AuthPageFlow = class {
605
616
  this.configuredAuthPageUrl,
606
617
  browserWindow
607
618
  );
608
- if (!this.writeRedirectContext(browserWindow, this.newRedirectContext(state, authPageUrl))) {
619
+ const context = this.newRedirectContext(state, this.getRedirectUri(authPageUrl));
620
+ if (!this.writeRedirectContext(browserWindow, context)) {
609
621
  throw new Error(
610
622
  `${this.providerLabel} sign-in redirect requires ${this.profile.redirectStorage}.`
611
623
  );
@@ -614,11 +626,62 @@ var AuthPageFlow = class {
614
626
  browserWindow.location.assign(startUrl.toString());
615
627
  return new Promise(() => void 0);
616
628
  }
629
+ /**
630
+ * A one-time state for a request that is finished somewhere other than here:
631
+ * the tab a link in a message opens, or a code typed into the application
632
+ * itself. Generating it changes nothing, so a request that is never accepted
633
+ * leaves the one pending here alone.
634
+ *
635
+ * @internal
636
+ */
637
+ newRequestState() {
638
+ this.requireBrowser();
639
+ return this.generateState();
640
+ }
641
+ /**
642
+ * Writes down a request whoever finishes it will need, replacing the one
643
+ * pending here.
644
+ *
645
+ * Writing it is best effort. Without storage only the completion from the link
646
+ * is lost, and the code typed into the application still finishes the sign-in.
647
+ *
648
+ * @internal
649
+ */
650
+ rememberPendingRequest(state, redirectUri) {
651
+ const browserWindow = this.requireBrowser();
652
+ this.writeRedirectContext(browserWindow, this.newRedirectContext(state, redirectUri));
653
+ }
654
+ /**
655
+ * The one-time state of the request pending in this browser, or `null` when
656
+ * there is none or it is too old to be finished.
657
+ *
658
+ * @internal
659
+ */
660
+ pendingRequestState() {
661
+ const context = this.readRedirectContext(this.requireBrowser());
662
+ if (!context || this.hasExpired(context)) return null;
663
+ return context.state;
664
+ }
665
+ /** @internal */
666
+ discardPendingRequest() {
667
+ this.clearRedirectContext(this.requireBrowser());
668
+ }
669
+ /**
670
+ * Redeems a single-use exchange code for an app session, through the same IAM
671
+ * route this provider's auth page handshake uses. For a provider that binds
672
+ * the code to the page that received it, use that handshake instead: this one
673
+ * has no page to name.
674
+ *
675
+ * @internal
676
+ */
677
+ redeemExchangeCode(code) {
678
+ return this.exchangeCode(code, null);
679
+ }
617
680
  async exchangeCode(code, redirectUri) {
618
681
  const response = await this.client.post(this.profile.exchangePath, {
619
682
  appId: this.appId,
620
683
  code,
621
- ...this.profile.sendsRedirectUri ? { redirectUri } : {}
684
+ ...this.profile.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
622
685
  });
623
686
  return expectAuthTokenResponse(response);
624
687
  }
@@ -635,10 +698,10 @@ var AuthPageFlow = class {
635
698
  getRedirectUri(authPageUrl) {
636
699
  return `${authPageUrl.origin}${authPageUrl.pathname}`;
637
700
  }
638
- newRedirectContext(state, authPageUrl) {
701
+ newRedirectContext(state, redirectUri) {
639
702
  return {
640
703
  state,
641
- redirectUri: this.getRedirectUri(authPageUrl),
704
+ redirectUri,
642
705
  createdAt: Date.now()
643
706
  };
644
707
  }
@@ -779,6 +842,213 @@ var AuthPageFlow = class {
779
842
  }
780
843
  };
781
844
 
845
+ // src/modules/email-code-flow.ts
846
+ var import_sdk_core3 = require("@mitralab.io/sdk-core");
847
+ var MAGIC_LINK_PATH = "/api/v1/auth/magic-link";
848
+ var VERIFY_PATH = `${MAGIC_LINK_PATH}/verify`;
849
+ var CONFIRM_PATH = `${MAGIC_LINK_PATH}/confirm`;
850
+ var LINK_TOKEN_KEY = "emailToken";
851
+ var DEFAULT_LANGUAGE = "pt-BR";
852
+ var LINK_FAILURES = {
853
+ EXPIRED: {
854
+ status: 409,
855
+ code: "MAGIC_LINK_EXPIRED",
856
+ message: "This sign-in link expired. Ask for a new message."
857
+ },
858
+ USED: {
859
+ status: 409,
860
+ code: "MAGIC_LINK_USED",
861
+ message: "This sign-in link was already used. Ask for a new message."
862
+ },
863
+ INVALID: {
864
+ status: 401,
865
+ code: "MAGIC_LINK_INVALID",
866
+ message: "This sign-in link is not valid."
867
+ }
868
+ };
869
+ function linkFailure(state) {
870
+ const failure = LINK_FAILURES[state];
871
+ return new MitraApiError(failure.message, failure.status, failure.code);
872
+ }
873
+ function optionalString2(value) {
874
+ return typeof value === "string" ? value : void 0;
875
+ }
876
+ function isMagicLinkState(value) {
877
+ return value === "OK" || value === "EXPIRED" || value === "USED" || value === "INVALID";
878
+ }
879
+ function expectEmailCodeRequestResult(value) {
880
+ const response = (0, import_sdk_core3.expectObject)(
881
+ value,
882
+ "Email code request response",
883
+ coreErrors
884
+ );
885
+ if (typeof response.receipt !== "string" || !response.receipt.trim()) {
886
+ throw coreErrors.invalidResponse("Email code request response has an invalid receipt field");
887
+ }
888
+ if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
889
+ throw coreErrors.invalidResponse(
890
+ "Email code request response has an invalid resendAfterSeconds field"
891
+ );
892
+ }
893
+ return { receipt: response.receipt, resendAfterSeconds: response.resendAfterSeconds };
894
+ }
895
+ function expectExchangeCode(value) {
896
+ const response = (0, import_sdk_core3.expectObject)(
897
+ value,
898
+ "Email sign-in exchange code response",
899
+ coreErrors
900
+ );
901
+ if (typeof response.exchangeCode !== "string" || !response.exchangeCode.trim()) {
902
+ throw coreErrors.invalidResponse(
903
+ "Email sign-in exchange code response has an invalid exchangeCode field"
904
+ );
905
+ }
906
+ return response.exchangeCode;
907
+ }
908
+ function expectMagicLinkInspection(value) {
909
+ const response = (0, import_sdk_core3.expectObject)(
910
+ value,
911
+ "Email sign-in link inspection response",
912
+ coreErrors
913
+ );
914
+ const state = optionalString2(response.state);
915
+ if (!state?.trim()) {
916
+ throw coreErrors.invalidResponse(
917
+ "Email sign-in link inspection response has an invalid state field"
918
+ );
919
+ }
920
+ return {
921
+ state: isMagicLinkState(state) ? state : "INVALID",
922
+ origin: optionalString2(response.origin),
923
+ sdkState: optionalString2(response.sdkState)
924
+ };
925
+ }
926
+ function resolveLanguage(requested, browserWindow) {
927
+ if (requested) return requested;
928
+ const preferred = browserWindow.navigator?.language ?? "";
929
+ return preferred.toLowerCase().startsWith("en") ? "en" : DEFAULT_LANGUAGE;
930
+ }
931
+ var EmailCodeFlow = class {
932
+ appId;
933
+ client;
934
+ pendingRequest;
935
+ constructor(config) {
936
+ this.appId = config.appId;
937
+ this.client = config.client;
938
+ this.pendingRequest = config.pendingRequest;
939
+ }
940
+ /**
941
+ * Asks IAM to send a code to an address, and writes down that a request is in
942
+ * flight so the tab the link opens can finish it. Calling it again replaces
943
+ * the pending request, which is what resending is.
944
+ *
945
+ * The request is written only once IAM accepts it. A resend IAM refuses, a
946
+ * rate limit being the everyday case, would otherwise replace the request the
947
+ * message already in the mailbox names, and silently kill that link.
948
+ */
949
+ async requestCode(request, brand) {
950
+ const browserWindow = this.requireBrowser();
951
+ const origin = browserWindow.location.origin;
952
+ const state = this.pendingRequest.newRequestState();
953
+ const result = expectEmailCodeRequestResult(
954
+ await this.client.post(MAGIC_LINK_PATH, {
955
+ email: request.email,
956
+ brand,
957
+ language: resolveLanguage(request.language, browserWindow),
958
+ appId: this.appId,
959
+ origin,
960
+ state
961
+ })
962
+ );
963
+ this.pendingRequest.rememberPendingRequest(state, origin);
964
+ return result;
965
+ }
966
+ /**
967
+ * Turns the code the person typed into an app session. IAM answers the
968
+ * verification with a single-use exchange code, redeemed here through the same
969
+ * route the auth page handshake uses.
970
+ */
971
+ async verifyCode(verification) {
972
+ this.requireBrowser();
973
+ const exchangeCode = expectExchangeCode(
974
+ await this.client.post(VERIFY_PATH, {
975
+ receipt: verification.receipt,
976
+ code: verification.code
977
+ })
978
+ );
979
+ this.pendingRequest.discardPendingRequest();
980
+ return this.pendingRequest.redeemExchangeCode(exchangeCode);
981
+ }
982
+ /**
983
+ * Finishes the sign-in from a `#emailToken=` link that landed on this origin,
984
+ * or returns `null` when the URL carries no link, or carries one this browser
985
+ * cannot claim. A link that can be claimed but is expired, already used, or
986
+ * unknown to IAM is reported as a {@link MitraApiError}.
987
+ *
988
+ * The link is inspected before it is consumed, so a browser without the
989
+ * pending request never spends it.
990
+ */
991
+ async completeLink() {
992
+ const browserWindow = this.requireBrowser();
993
+ const fragment = browserWindow.location.hash.replace(/^#/, "");
994
+ const token = new URLSearchParams(fragment).get(LINK_TOKEN_KEY);
995
+ if (!token?.trim()) return null;
996
+ const pendingState = this.pendingRequest.pendingRequestState();
997
+ if (pendingState === null) {
998
+ this.dropLinkFromFragment(browserWindow, fragment);
999
+ this.pendingRequest.discardPendingRequest();
1000
+ return null;
1001
+ }
1002
+ let inspection;
1003
+ try {
1004
+ inspection = expectMagicLinkInspection(
1005
+ await this.client.get(CONFIRM_PATH, { token })
1006
+ );
1007
+ } catch (error) {
1008
+ this.dropLinkFromFragment(browserWindow, fragment);
1009
+ throw error;
1010
+ }
1011
+ if (inspection.state !== "OK") {
1012
+ this.dropLinkFromFragment(browserWindow, fragment);
1013
+ throw linkFailure(inspection.state);
1014
+ }
1015
+ if (inspection.origin !== browserWindow.location.origin || inspection.sdkState !== pendingState) {
1016
+ this.dropLinkFromFragment(browserWindow, fragment);
1017
+ return null;
1018
+ }
1019
+ try {
1020
+ const exchangeCode = expectExchangeCode(
1021
+ await this.client.post(CONFIRM_PATH, { token })
1022
+ );
1023
+ return await this.pendingRequest.redeemExchangeCode(exchangeCode);
1024
+ } finally {
1025
+ this.dropLinkFromFragment(browserWindow, fragment);
1026
+ this.pendingRequest.discardPendingRequest();
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Removes the link from the URL and leaves the rest of the fragment exactly as
1031
+ * it was found. An application may route on it, and rewriting the fragment as
1032
+ * parameters would turn a path like `#/orders/1` into something its router no
1033
+ * longer recognizes.
1034
+ */
1035
+ dropLinkFromFragment(browserWindow, fragment) {
1036
+ const remaining = fragment.split("&").filter((part) => part !== LINK_TOKEN_KEY && !part.startsWith(`${LINK_TOKEN_KEY}=`)).join("&");
1037
+ const hash = remaining ? `#${remaining}` : "";
1038
+ browserWindow.history.replaceState(
1039
+ {},
1040
+ "",
1041
+ `${browserWindow.location.pathname}${browserWindow.location.search}${hash}`
1042
+ );
1043
+ }
1044
+ requireBrowser() {
1045
+ if (globalThis.window === void 0) {
1046
+ throw new Error("Email sign-in is only available in a browser.");
1047
+ }
1048
+ return globalThis.window;
1049
+ }
1050
+ };
1051
+
782
1052
  // src/modules/auth.ts
783
1053
  var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
784
1054
  var sessionPorts = /* @__PURE__ */ new WeakMap();
@@ -831,6 +1101,8 @@ var AuthModule = class {
831
1101
  googleAuth;
832
1102
  microsoftAuth;
833
1103
  emailAuth;
1104
+ emailCode;
1105
+ brand = null;
834
1106
  constructor(appId, iamBaseUrl, options = {}) {
835
1107
  this.appId = appId;
836
1108
  const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
@@ -846,7 +1118,7 @@ var AuthModule = class {
846
1118
  beforeAuthenticatedRequest: () => this.ensureFreshSession().then(() => void 0),
847
1119
  onUnauthorized: (requestToken) => this.handleUnauthorized(requestToken)
848
1120
  });
849
- this.currentUserApi = (0, import_sdk_core3.createAuthModule)(this.authedClient, coreErrors);
1121
+ this.currentUserApi = (0, import_sdk_core4.createAuthModule)(this.authedClient, coreErrors);
850
1122
  this.googleAuth = new AuthPageFlow({
851
1123
  appId,
852
1124
  apiUrl,
@@ -867,6 +1139,11 @@ var AuthModule = class {
867
1139
  client: this.publicClient,
868
1140
  provider: "email"
869
1141
  });
1142
+ this.emailCode = new EmailCodeFlow({
1143
+ appId,
1144
+ client: this.publicClient,
1145
+ pendingRequest: this.emailAuth
1146
+ });
870
1147
  this.loadFromStorage();
871
1148
  const readAccessToken = () => this.#accessToken;
872
1149
  sessionPorts.set(this, {
@@ -1048,19 +1325,92 @@ var AuthModule = class {
1048
1325
  return this.establishSession(await this.emailAuth.signIn(options));
1049
1326
  }
1050
1327
  /**
1051
- * Completes an email sign-in from `#codeMitra` and `#stateMitra`, during
1052
- * application startup like {@link completeGoogleSignInRedirect}.
1328
+ * Publishes the brand `init()` read from the app info, which IAM needs to
1329
+ * choose the message it sends for {@link requestEmailCode}.
1053
1330
  *
1054
- * It covers both ways the flow comes back, and they are the same check: a
1055
- * redirect in the tab that started it, and the tab the link in the message
1056
- * opened. Both carry the one-time state this SDK generated, which the second
1057
- * tab matches against the pending request kept in `localStorage`. A request
1058
- * older than 10 minutes is discarded instead of completed.
1331
+ * @internal
1332
+ */
1333
+ setBrand(brand) {
1334
+ this.brand = brand;
1335
+ }
1336
+ /**
1337
+ * Asks IAM to email a six-digit code, without any platform screen: the
1338
+ * application renders its own address and code fields, and the message is
1339
+ * branded as the app. Answer it with {@link verifyEmailCode}.
1340
+ *
1341
+ * The same message also carries a link back to this application's own origin.
1342
+ * Sign-in continues there through {@link completeEmailSignInRedirect}, so the
1343
+ * request is written to `localStorage` under `mitra_email_redirect_{appId}` -
1344
+ * the one-time state and this origin, never a token - for 10 minutes. Only the
1345
+ * browser that asked can finish through the link.
1346
+ *
1347
+ * Resending is calling this again: the new request replaces the pending one,
1348
+ * and `resendAfterSeconds` says how long the application should wait before
1349
+ * offering that.
1350
+ *
1351
+ * @param request - Address to send to, and the language to write in.
1352
+ * @returns The receipt that names this request, and the resend delay.
1353
+ * @throws {MitraApiError} `INVALID_CONFIGURATION` before `init()` resolved the
1354
+ * app info, `RATE_LIMITED` (with `retryAfterSeconds`) when IAM asks the person
1355
+ * to wait, and the app access codes when this app refuses the address.
1059
1356
  *
1060
- * @returns The authenticated user, or `null` when the URL carries no result or
1061
- * carries one that belongs to another sign-in method's flow.
1357
+ * @example
1358
+ * ```typescript
1359
+ * const { receipt, resendAfterSeconds } = await mitra.auth.requestEmailCode({
1360
+ * email: 'person@example.com',
1361
+ * });
1362
+ * ```
1363
+ */
1364
+ async requestEmailCode(request) {
1365
+ return this.emailCode.requestCode(request, this.requireBrand());
1366
+ }
1367
+ /**
1368
+ * Turns the code from the message into a session, hydrating and persisting it
1369
+ * exactly like SSO does.
1370
+ *
1371
+ * @param verification - The receipt from {@link requestEmailCode} and the code
1372
+ * the person typed.
1373
+ * @returns The authenticated and hydrated user.
1374
+ * @throws {MitraApiError} `INVALID_CODE` when the code does not match,
1375
+ * `MAGIC_LINK_EXPIRED` or `MAGIC_LINK_USED` when the request is over.
1376
+ *
1377
+ * @example
1378
+ * ```typescript
1379
+ * const user = await mitra.auth.verifyEmailCode({ receipt, code: '123456' });
1380
+ * ```
1381
+ */
1382
+ async verifyEmailCode(verification) {
1383
+ return this.establishSession(await this.emailCode.verifyCode(verification));
1384
+ }
1385
+ /**
1386
+ * Completes an email sign-in during application startup, like
1387
+ * {@link completeGoogleSignInRedirect}.
1388
+ *
1389
+ * It covers every way the flow comes back. The link in the message lands on
1390
+ * this application's own origin as `#emailToken=`, and that is the headless
1391
+ * flow: the link is inspected before it is spent, and it is only spent when
1392
+ * IAM reports the same origin the page is on and the one-time state of the
1393
+ * request pending in this browser. A browser without that request - another
1394
+ * device, or a scanner opening links on the way to a mailbox - consumes
1395
+ * nothing and leaves the link valid for the person who asked for it.
1396
+ *
1397
+ * The platform auth page instead comes back as `#codeMitra` and `#stateMitra`,
1398
+ * from the redirect in the tab that started it or from the tab the older link
1399
+ * opened, and is completed by the same state check.
1400
+ *
1401
+ * From the link, only `emailToken` leaves the URL, so a fragment the
1402
+ * application routes on is left as it was. Coming back from the platform auth
1403
+ * page, the fragment is removed whole.
1404
+ *
1405
+ * @returns The authenticated user, or `null` when the URL carries no result,
1406
+ * carries one that belongs to another sign-in method's flow, or carries a link
1407
+ * this browser cannot claim.
1408
+ * @throws {MitraApiError} `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, or
1409
+ * `MAGIC_LINK_INVALID` when the link belongs here but cannot be used.
1062
1410
  */
1063
1411
  async completeEmailSignInRedirect() {
1412
+ const linkResponse = await this.emailCode.completeLink();
1413
+ if (linkResponse) return this.establishSession(linkResponse);
1064
1414
  const tokenResponse = await this.emailAuth.completeRedirect();
1065
1415
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1066
1416
  }
@@ -1440,6 +1790,19 @@ var AuthModule = class {
1440
1790
  belongsToConfiguredApp(token) {
1441
1791
  return belongsToApp(token, this.appId);
1442
1792
  }
1793
+ /**
1794
+ * The brand IAM needs to brand the message. It arrives with the app info, so
1795
+ * asking before `init()` is a configuration mistake rather than something to
1796
+ * guess a default for: the wrong brand sends the wrong message.
1797
+ */
1798
+ requireBrand() {
1799
+ if (!this.brand) {
1800
+ throw coreErrors.configuration(
1801
+ "Email sign-in needs the app info resolved by init(). Call init() before requestEmailCode()."
1802
+ );
1803
+ }
1804
+ return this.brand;
1805
+ }
1443
1806
  notifySessionListeners() {
1444
1807
  const session = this.readSessionTokens();
1445
1808
  this.sessionListeners.forEach((callback) => {
@@ -1501,11 +1864,11 @@ var AuthModule = class {
1501
1864
  };
1502
1865
 
1503
1866
  // src/modules/entities.ts
1504
- var import_sdk_core4 = require("@mitralab.io/sdk-core");
1867
+ var import_sdk_core5 = require("@mitralab.io/sdk-core");
1505
1868
  var EntitiesModule = class _EntitiesModule {
1506
1869
  constructor(httpClient, _dataSourceId) {
1507
1870
  this.httpClient = httpClient;
1508
- this.core = (0, import_sdk_core4.createEntitiesModule)(httpClient, coreErrors);
1871
+ this.core = (0, import_sdk_core5.createEntitiesModule)(httpClient, coreErrors);
1509
1872
  }
1510
1873
  core;
1511
1874
  static createProxy(httpClient, dataSourceId) {
@@ -1524,7 +1887,7 @@ var EntitiesModule = class _EntitiesModule {
1524
1887
  * Records now resolve the app from authenticated context instead of a data source path.
1525
1888
  */
1526
1889
  setDataSourceId(_dataSourceId) {
1527
- this.core = (0, import_sdk_core4.createEntitiesModule)(this.httpClient, coreErrors);
1890
+ this.core = (0, import_sdk_core5.createEntitiesModule)(this.httpClient, coreErrors);
1528
1891
  }
1529
1892
  getTable(tableName) {
1530
1893
  return this.core.getTable(tableName);
@@ -1532,11 +1895,11 @@ var EntitiesModule = class _EntitiesModule {
1532
1895
  };
1533
1896
 
1534
1897
  // src/modules/functions.ts
1535
- var import_sdk_core5 = require("@mitralab.io/sdk-core");
1898
+ var import_sdk_core6 = require("@mitralab.io/sdk-core");
1536
1899
  var FunctionsModule = class {
1537
1900
  core;
1538
1901
  constructor(httpClient) {
1539
- this.core = (0, import_sdk_core5.createFunctionsModule)(
1902
+ this.core = (0, import_sdk_core6.createFunctionsModule)(
1540
1903
  httpClient,
1541
1904
  { emptyInput: "omit-body", executeInvocationType: "sync" },
1542
1905
  coreErrors
@@ -1563,13 +1926,13 @@ var FunctionsModule = class {
1563
1926
  };
1564
1927
 
1565
1928
  // src/modules/integration.ts
1566
- var import_sdk_core6 = require("@mitralab.io/sdk-core");
1929
+ var import_sdk_core7 = require("@mitralab.io/sdk-core");
1567
1930
  var IntegrationModule = class {
1568
1931
  core;
1569
1932
  configs;
1570
1933
  constructor(httpClient) {
1571
- this.core = (0, import_sdk_core6.createIntegrationModule)(httpClient, coreErrors);
1572
- this.configs = (0, import_sdk_core6.createIntegrationAdminModule)(httpClient, coreErrors);
1934
+ this.core = (0, import_sdk_core7.createIntegrationModule)(httpClient, coreErrors);
1935
+ this.configs = (0, import_sdk_core7.createIntegrationAdminModule)(httpClient, coreErrors);
1573
1936
  }
1574
1937
  /** Lists the current app's integration configs without exposing admin mutations. */
1575
1938
  list(options) {
@@ -1588,11 +1951,11 @@ var IntegrationModule = class {
1588
1951
  };
1589
1952
 
1590
1953
  // src/modules/queries.ts
1591
- var import_sdk_core7 = require("@mitralab.io/sdk-core");
1954
+ var import_sdk_core8 = require("@mitralab.io/sdk-core");
1592
1955
  var QueriesModule = class {
1593
1956
  core;
1594
1957
  constructor(httpClient) {
1595
- this.core = (0, import_sdk_core7.createQueriesModule)(httpClient, coreErrors);
1958
+ this.core = (0, import_sdk_core8.createQueriesModule)(httpClient, coreErrors);
1596
1959
  }
1597
1960
  /**
1598
1961
  * @deprecated Preserved for Platform SDK 1.x source compatibility. Data Manager now resolves
@@ -1606,7 +1969,7 @@ var QueriesModule = class {
1606
1969
  };
1607
1970
 
1608
1971
  // src/modules/agent-tasks.ts
1609
- var import_sdk_core8 = require("@mitralab.io/sdk-core");
1972
+ var import_sdk_core9 = require("@mitralab.io/sdk-core");
1610
1973
 
1611
1974
  // src/modules/agent-outbox.ts
1612
1975
  var OUTBOX_DELAYS_MS = [2e3, 5e3, 1e4, 2e4, 4e4];
@@ -1811,6 +2174,7 @@ var CONNECT_TIMEOUT_MS = 15e3;
1811
2174
  var SILENCE_TIMEOUT_MS = 6e4;
1812
2175
  var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
1813
2176
  var SUPERSEDED_CLOSE_CODE = 4409;
2177
+ var SOCKET_OPEN = 1;
1814
2178
  var SilenceWatchdog = class {
1815
2179
  constructor(onSilence) {
1816
2180
  this.onSilence = onSilence;
@@ -1926,6 +2290,8 @@ var BrowserAgentTaskEventSource = class {
1926
2290
  */
1927
2291
  boxCursors = /* @__PURE__ */ new Map();
1928
2292
  boxAddresses = /* @__PURE__ */ new Map();
2293
+ /** The box socket a task is talking on right now; absent while it is lost or being redialed. */
2294
+ directSockets = /* @__PURE__ */ new Map();
1929
2295
  async open(taskId, observer, signal, transport = "auto") {
1930
2296
  if (transport === "http") return this.openSse(taskId, observer, signal);
1931
2297
  if (transport === "websocket") return this.openWebSocket(taskId, observer, signal);
@@ -1957,6 +2323,23 @@ var BrowserAgentTaskEventSource = class {
1957
2323
  }
1958
2324
  };
1959
2325
  }
2326
+ /**
2327
+ * Writes a message or an interrupt on the box socket when the task is on the direct channel
2328
+ * and that socket is open right now. The box accepts the core's input as its own inbound
2329
+ * frame, asks the copilot for admission itself and answers on this same socket with the
2330
+ * frames the observer already reads, so the copilot's host socket is off the message path.
2331
+ * False sends the caller to REST: no direct channel, a socket lost or mid-redial, or an
2332
+ * approval, which stays on REST as it is.
2333
+ *
2334
+ * A frame written on a socket that closes before the box acknowledges it is not sent again
2335
+ * over REST: the box may have admitted the turn already, and a second copy would start it
2336
+ * twice. The redial replays the box log, which is the same recovery a REST 202 gets when its
2337
+ * turn is lost.
2338
+ */
2339
+ sendOnChannel(taskId, input) {
2340
+ if (input.type === "approval_response") return false;
2341
+ return this.directSockets.get(taskId)?.send(JSON.stringify(input)) ?? false;
2342
+ }
1960
2343
  async requireFreshToken() {
1961
2344
  const fresh = await this.auth.ensureFreshSession();
1962
2345
  const token = this.auth.accessToken;
@@ -2043,6 +2426,11 @@ var BrowserAgentTaskEventSource = class {
2043
2426
  signal?.addEventListener("abort", onAbort, { once: true });
2044
2427
  let inTurn = false;
2045
2428
  let current = null;
2429
+ const track = (socket) => {
2430
+ if (socket) this.directSockets.set(taskId, socket);
2431
+ else if (current && this.directSockets.get(taskId) === current) this.directSockets.delete(taskId);
2432
+ current = socket;
2433
+ };
2046
2434
  const onFrame = (event) => {
2047
2435
  if (typeof event.sequence === "number") {
2048
2436
  const seen = this.boxCursors.get(taskId) ?? 0;
@@ -2052,22 +2440,21 @@ var BrowserAgentTaskEventSource = class {
2052
2440
  observer.onEvent(event);
2053
2441
  };
2054
2442
  const onLost = (error, code) => {
2055
- current = null;
2443
+ track(null);
2056
2444
  if (link.signal.aborted) return;
2057
2445
  if (!inTurn || code === SUPERSEDED_CLOSE_CODE) {
2058
2446
  observer.onDisconnect(error);
2059
2447
  return;
2060
2448
  }
2061
- void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then((socket) => {
2062
- current = socket;
2063
- });
2449
+ void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then(track);
2064
2450
  };
2065
- current = await this.dial(channel.wsUrl, { signal: link.signal, onFrame, onLost });
2451
+ track(await this.dial(channel.wsUrl, { signal: link.signal, onFrame, onLost }));
2066
2452
  return {
2067
2453
  close: () => {
2068
2454
  signal?.removeEventListener("abort", onAbort);
2069
2455
  link.abort();
2070
2456
  current?.close();
2457
+ track(null);
2071
2458
  }
2072
2459
  };
2073
2460
  }
@@ -2152,6 +2539,15 @@ var BrowserAgentTaskEventSource = class {
2152
2539
  removeAbortListener();
2153
2540
  socket.close(1e3, "Client closed");
2154
2541
  };
2542
+ const send = (frame) => {
2543
+ if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
2544
+ try {
2545
+ socket.send(frame);
2546
+ return true;
2547
+ } catch {
2548
+ return false;
2549
+ }
2550
+ };
2155
2551
  const onAbort = () => {
2156
2552
  if (!opened) {
2157
2553
  rejectHandshake(signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted."));
@@ -2175,7 +2571,7 @@ var BrowserAgentTaskEventSource = class {
2175
2571
  } catch {
2176
2572
  }
2177
2573
  }
2178
- resolve({ close });
2574
+ resolve({ close, send });
2179
2575
  };
2180
2576
  socket.onerror = () => {
2181
2577
  if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
@@ -2287,7 +2683,7 @@ function bornOnBox(options) {
2287
2683
  return { ...options, runtime: "T3" };
2288
2684
  }
2289
2685
  function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2290
- const tasks = (0, import_sdk_core8.createAgentTasksModule)(httpClient, coreErrors);
2686
+ const tasks = (0, import_sdk_core9.createAgentTasksModule)(httpClient, coreErrors);
2291
2687
  const source = new BrowserAgentTaskEventSource(auth, apiUrl);
2292
2688
  const observers = /* @__PURE__ */ new Map();
2293
2689
  const outbox = new AgentInputOutbox(tasks, (taskId, event) => observers.get(taskId)?.onEvent(event));
@@ -2310,57 +2706,60 @@ function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2310
2706
  };
2311
2707
  }
2312
2708
  };
2313
- const manager = (0, import_sdk_core8.createAgentTaskSessionManager)({
2314
- tasks: { ...tasks, sendInput: (taskId, input) => outbox.sendInput(taskId, input) },
2709
+ const manager = (0, import_sdk_core9.createAgentTaskSessionManager)({
2710
+ tasks: {
2711
+ ...tasks,
2712
+ sendInput: (taskId, input) => source.sendOnChannel(taskId, input) ? Promise.resolve() : outbox.sendInput(taskId, input)
2713
+ },
2315
2714
  eventSource
2316
2715
  });
2317
- return (0, import_sdk_core8.withAgentTaskSessions)(tasks, {
2716
+ return (0, import_sdk_core9.withAgentTaskSessions)(tasks, {
2318
2717
  session: (options) => holdSendsWhileOffline(manager.session(bornOnBox(options)), outbox)
2319
2718
  });
2320
2719
  }
2321
2720
 
2322
2721
  // src/modules/agent-credentials.ts
2323
- var import_sdk_core9 = require("@mitralab.io/sdk-core");
2722
+ var import_sdk_core10 = require("@mitralab.io/sdk-core");
2324
2723
  function requireProvider(provider, allowed, flow) {
2325
2724
  if (!allowed.includes(provider)) {
2326
2725
  throw new TypeError(`${flow} does not support provider ${provider}.`);
2327
2726
  }
2328
2727
  }
2329
2728
  function createBrowserAgentCredentialsModule(httpClient) {
2330
- const core = (0, import_sdk_core9.createAgentCredentialsModule)(httpClient, coreErrors);
2729
+ const core = (0, import_sdk_core10.createAgentCredentialsModule)(httpClient, coreErrors);
2331
2730
  return {
2332
- list: () => core.list(),
2333
- listModels: (agentId) => core.listModels(agentId),
2334
- saveApiKey: (provider, apiKey) => {
2731
+ list: (options) => core.list(options),
2732
+ listModels: (agentId, options) => core.listModels(agentId, options),
2733
+ saveApiKey: (provider, apiKey, options) => {
2335
2734
  requireProvider(provider, ["ANTHROPIC", "OPENAI"], "API key authentication");
2336
- return core.saveApiKey(provider, apiKey);
2735
+ return core.saveApiKey(provider, apiKey, options);
2337
2736
  },
2338
- remove: (provider) => {
2737
+ remove: (provider, options) => {
2339
2738
  requireProvider(provider, ["ANTHROPIC", "OPENAI"], "Credential removal");
2340
- return core.remove(provider);
2739
+ return core.remove(provider, options);
2341
2740
  },
2342
- startOAuth: (provider) => {
2741
+ startOAuth: (provider, options) => {
2343
2742
  requireProvider(provider, ["ANTHROPIC"], "OAuth");
2344
- return core.startOAuth(provider);
2743
+ return core.startOAuth(provider, options);
2345
2744
  },
2346
- exchangeOAuth: (provider, input) => {
2745
+ exchangeOAuth: (provider, input, options) => {
2347
2746
  requireProvider(provider, ["ANTHROPIC"], "OAuth");
2348
- return core.exchangeOAuth(provider, input);
2747
+ return core.exchangeOAuth(provider, input, options);
2349
2748
  },
2350
- startDeviceAuthorization: (provider) => {
2749
+ startDeviceAuthorization: (provider, options) => {
2351
2750
  requireProvider(provider, ["OPENAI"], "Device authorization");
2352
- return core.startDeviceAuthorization(provider);
2751
+ return core.startDeviceAuthorization(provider, options);
2353
2752
  },
2354
- pollDeviceAuthorization: (provider, deviceAuthId) => {
2753
+ pollDeviceAuthorization: (provider, deviceAuthId, options) => {
2355
2754
  requireProvider(provider, ["OPENAI"], "Device authorization");
2356
- return core.pollDeviceAuthorization(provider, deviceAuthId);
2755
+ return core.pollDeviceAuthorization(provider, deviceAuthId, options);
2357
2756
  }
2358
2757
  };
2359
2758
  }
2360
2759
 
2361
2760
  // src/client.ts
2362
2761
  function expectAppInfoResponse(value) {
2363
- const response = (0, import_sdk_core10.expectObject)(
2762
+ const response = (0, import_sdk_core11.expectObject)(
2364
2763
  value,
2365
2764
  "App info response",
2366
2765
  coreErrors
@@ -2382,7 +2781,10 @@ function expectAppInfoResponse(value) {
2382
2781
  // instead of failing `init()`: a Code Studio older than the email login gate
2383
2782
  // answers without this field, and an app that cannot prove it is enabled
2384
2783
  // should stop offering the option, not stop starting.
2385
- emailLoginEnabled: response.emailLoginEnabled === true
2784
+ emailLoginEnabled: response.emailLoginEnabled === true,
2785
+ // Same reasoning, and the brand is never guessed: without it the headless
2786
+ // email methods refuse instead of asking IAM to brand a message at random.
2787
+ brand: typeof response.brand === "string" && response.brand.trim() ? response.brand : null
2386
2788
  };
2387
2789
  }
2388
2790
  function createClient(config) {
@@ -2417,7 +2819,7 @@ function createClient(config) {
2417
2819
  defaultHeaders
2418
2820
  });
2419
2821
  const functionsModule = new FunctionsModule(functionsHttpClient);
2420
- const publicFunctionsModule = (0, import_sdk_core10.createPublicFunctionsModule)(
2822
+ const publicFunctionsModule = (0, import_sdk_core11.createPublicFunctionsModule)(
2421
2823
  new HttpClient({ baseUrl: functionsUrl, getToken: () => null }),
2422
2824
  coreErrors
2423
2825
  );
@@ -2459,12 +2861,15 @@ function createClient(config) {
2459
2861
  });
2460
2862
  const appInfo = expectAppInfoResponse(
2461
2863
  await publicClient.get(
2462
- `/api/v1/apps/${(0, import_sdk_core10.encodePathSegment)(appId, "appId", coreErrors)}/info`
2864
+ `/api/v1/apps/${(0, import_sdk_core11.encodePathSegment)(appId, "appId", coreErrors)}/info`
2463
2865
  )
2464
2866
  );
2465
2867
  if (appInfo.dataSourceId) {
2466
2868
  entitiesModule.setDataSourceId(appInfo.dataSourceId);
2467
2869
  }
2870
+ if (appInfo.brand) {
2871
+ authModule.setBrand(appInfo.brand);
2872
+ }
2468
2873
  allowSignup = appInfo.allowSignup;
2469
2874
  emailLoginEnabled = appInfo.emailLoginEnabled;
2470
2875
  initialized = true;