@mitralab.io/platform-sdk 1.2.0-beta.1 → 1.2.0-beta.2
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/CHANGELOG.md +50 -0
- package/README.md +147 -52
- package/dist/index.cjs +465 -60
- package/dist/index.d.cts +131 -23
- package/dist/index.d.ts +131 -23
- package/dist/index.js +445 -40
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ function stripTrailingSlashes(value) {
|
|
|
9
9
|
import {
|
|
10
10
|
createPublicFunctionsModule,
|
|
11
11
|
encodePathSegment,
|
|
12
|
-
expectObject as
|
|
12
|
+
expectObject as expectObject3
|
|
13
13
|
} from "@mitralab.io/sdk-core";
|
|
14
14
|
|
|
15
15
|
// src/utils/http-client.ts
|
|
@@ -45,6 +45,12 @@ function asErrorPayload(value) {
|
|
|
45
45
|
function optionalString(value) {
|
|
46
46
|
return typeof value === "string" ? value : void 0;
|
|
47
47
|
}
|
|
48
|
+
function readRetryAfterSeconds(response) {
|
|
49
|
+
const header = response.headers?.get("Retry-After");
|
|
50
|
+
if (!header) return null;
|
|
51
|
+
const seconds = Number(header.trim());
|
|
52
|
+
return Number.isInteger(seconds) && seconds >= 0 ? seconds : null;
|
|
53
|
+
}
|
|
48
54
|
function buildRequestUrl(baseUrl, path, params) {
|
|
49
55
|
const url = `${baseUrl}${path}`;
|
|
50
56
|
if (!params) return url;
|
|
@@ -145,7 +151,8 @@ var HttpClient = class {
|
|
|
145
151
|
redactText(rawMessage || `Request failed with status ${response.status}`, token),
|
|
146
152
|
response.status,
|
|
147
153
|
rawCode === void 0 ? void 0 : redactText(rawCode, token),
|
|
148
|
-
redactDetails(errorBody, token)
|
|
154
|
+
redactDetails(errorBody, token),
|
|
155
|
+
readRetryAfterSeconds(response)
|
|
149
156
|
);
|
|
150
157
|
}
|
|
151
158
|
async parseResponseBody(response, path) {
|
|
@@ -233,11 +240,12 @@ var HttpClient = class {
|
|
|
233
240
|
}
|
|
234
241
|
};
|
|
235
242
|
var MitraApiError = class extends Error {
|
|
236
|
-
constructor(message, status, code, details) {
|
|
243
|
+
constructor(message, status, code, details, retryAfterSeconds = null) {
|
|
237
244
|
super(message);
|
|
238
245
|
this.status = status;
|
|
239
246
|
this.code = code;
|
|
240
247
|
this.details = details;
|
|
248
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
241
249
|
this.name = "MitraApiError";
|
|
242
250
|
}
|
|
243
251
|
};
|
|
@@ -540,7 +548,10 @@ var AuthPageFlow = class {
|
|
|
540
548
|
);
|
|
541
549
|
const completedInAnotherTab = this.profile.pendingRequestTtlMs !== void 0;
|
|
542
550
|
if (completedInAnotherTab) {
|
|
543
|
-
this.writeRedirectContext(
|
|
551
|
+
this.writeRedirectContext(
|
|
552
|
+
browserWindow,
|
|
553
|
+
this.newRedirectContext(state, this.getRedirectUri(authPageUrl))
|
|
554
|
+
);
|
|
544
555
|
}
|
|
545
556
|
const popup = this.openPopup(browserWindow, this.buildStartUrl(browserWindow, authPageUrl, state));
|
|
546
557
|
const result = await this.waitForPopupResult(browserWindow, popup, authPageUrl.origin, state);
|
|
@@ -555,7 +566,8 @@ var AuthPageFlow = class {
|
|
|
555
566
|
this.configuredAuthPageUrl,
|
|
556
567
|
browserWindow
|
|
557
568
|
);
|
|
558
|
-
|
|
569
|
+
const context = this.newRedirectContext(state, this.getRedirectUri(authPageUrl));
|
|
570
|
+
if (!this.writeRedirectContext(browserWindow, context)) {
|
|
559
571
|
throw new Error(
|
|
560
572
|
`${this.providerLabel} sign-in redirect requires ${this.profile.redirectStorage}.`
|
|
561
573
|
);
|
|
@@ -564,11 +576,62 @@ var AuthPageFlow = class {
|
|
|
564
576
|
browserWindow.location.assign(startUrl.toString());
|
|
565
577
|
return new Promise(() => void 0);
|
|
566
578
|
}
|
|
579
|
+
/**
|
|
580
|
+
* A one-time state for a request that is finished somewhere other than here:
|
|
581
|
+
* the tab a link in a message opens, or a code typed into the application
|
|
582
|
+
* itself. Generating it changes nothing, so a request that is never accepted
|
|
583
|
+
* leaves the one pending here alone.
|
|
584
|
+
*
|
|
585
|
+
* @internal
|
|
586
|
+
*/
|
|
587
|
+
newRequestState() {
|
|
588
|
+
this.requireBrowser();
|
|
589
|
+
return this.generateState();
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Writes down a request whoever finishes it will need, replacing the one
|
|
593
|
+
* pending here.
|
|
594
|
+
*
|
|
595
|
+
* Writing it is best effort. Without storage only the completion from the link
|
|
596
|
+
* is lost, and the code typed into the application still finishes the sign-in.
|
|
597
|
+
*
|
|
598
|
+
* @internal
|
|
599
|
+
*/
|
|
600
|
+
rememberPendingRequest(state, redirectUri) {
|
|
601
|
+
const browserWindow = this.requireBrowser();
|
|
602
|
+
this.writeRedirectContext(browserWindow, this.newRedirectContext(state, redirectUri));
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* The one-time state of the request pending in this browser, or `null` when
|
|
606
|
+
* there is none or it is too old to be finished.
|
|
607
|
+
*
|
|
608
|
+
* @internal
|
|
609
|
+
*/
|
|
610
|
+
pendingRequestState() {
|
|
611
|
+
const context = this.readRedirectContext(this.requireBrowser());
|
|
612
|
+
if (!context || this.hasExpired(context)) return null;
|
|
613
|
+
return context.state;
|
|
614
|
+
}
|
|
615
|
+
/** @internal */
|
|
616
|
+
discardPendingRequest() {
|
|
617
|
+
this.clearRedirectContext(this.requireBrowser());
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Redeems a single-use exchange code for an app session, through the same IAM
|
|
621
|
+
* route this provider's auth page handshake uses. For a provider that binds
|
|
622
|
+
* the code to the page that received it, use that handshake instead: this one
|
|
623
|
+
* has no page to name.
|
|
624
|
+
*
|
|
625
|
+
* @internal
|
|
626
|
+
*/
|
|
627
|
+
redeemExchangeCode(code) {
|
|
628
|
+
return this.exchangeCode(code, null);
|
|
629
|
+
}
|
|
567
630
|
async exchangeCode(code, redirectUri) {
|
|
568
631
|
const response = await this.client.post(this.profile.exchangePath, {
|
|
569
632
|
appId: this.appId,
|
|
570
633
|
code,
|
|
571
|
-
...this.profile.sendsRedirectUri ? { redirectUri } : {}
|
|
634
|
+
...this.profile.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
|
|
572
635
|
});
|
|
573
636
|
return expectAuthTokenResponse(response);
|
|
574
637
|
}
|
|
@@ -585,10 +648,10 @@ var AuthPageFlow = class {
|
|
|
585
648
|
getRedirectUri(authPageUrl) {
|
|
586
649
|
return `${authPageUrl.origin}${authPageUrl.pathname}`;
|
|
587
650
|
}
|
|
588
|
-
newRedirectContext(state,
|
|
651
|
+
newRedirectContext(state, redirectUri) {
|
|
589
652
|
return {
|
|
590
653
|
state,
|
|
591
|
-
redirectUri
|
|
654
|
+
redirectUri,
|
|
592
655
|
createdAt: Date.now()
|
|
593
656
|
};
|
|
594
657
|
}
|
|
@@ -729,6 +792,213 @@ var AuthPageFlow = class {
|
|
|
729
792
|
}
|
|
730
793
|
};
|
|
731
794
|
|
|
795
|
+
// src/modules/email-code-flow.ts
|
|
796
|
+
import { expectObject as expectObject2 } from "@mitralab.io/sdk-core";
|
|
797
|
+
var MAGIC_LINK_PATH = "/api/v1/auth/magic-link";
|
|
798
|
+
var VERIFY_PATH = `${MAGIC_LINK_PATH}/verify`;
|
|
799
|
+
var CONFIRM_PATH = `${MAGIC_LINK_PATH}/confirm`;
|
|
800
|
+
var LINK_TOKEN_KEY = "emailToken";
|
|
801
|
+
var DEFAULT_LANGUAGE = "pt-BR";
|
|
802
|
+
var LINK_FAILURES = {
|
|
803
|
+
EXPIRED: {
|
|
804
|
+
status: 409,
|
|
805
|
+
code: "MAGIC_LINK_EXPIRED",
|
|
806
|
+
message: "This sign-in link expired. Ask for a new message."
|
|
807
|
+
},
|
|
808
|
+
USED: {
|
|
809
|
+
status: 409,
|
|
810
|
+
code: "MAGIC_LINK_USED",
|
|
811
|
+
message: "This sign-in link was already used. Ask for a new message."
|
|
812
|
+
},
|
|
813
|
+
INVALID: {
|
|
814
|
+
status: 401,
|
|
815
|
+
code: "MAGIC_LINK_INVALID",
|
|
816
|
+
message: "This sign-in link is not valid."
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
function linkFailure(state) {
|
|
820
|
+
const failure = LINK_FAILURES[state];
|
|
821
|
+
return new MitraApiError(failure.message, failure.status, failure.code);
|
|
822
|
+
}
|
|
823
|
+
function optionalString2(value) {
|
|
824
|
+
return typeof value === "string" ? value : void 0;
|
|
825
|
+
}
|
|
826
|
+
function isMagicLinkState(value) {
|
|
827
|
+
return value === "OK" || value === "EXPIRED" || value === "USED" || value === "INVALID";
|
|
828
|
+
}
|
|
829
|
+
function expectEmailCodeRequestResult(value) {
|
|
830
|
+
const response = expectObject2(
|
|
831
|
+
value,
|
|
832
|
+
"Email code request response",
|
|
833
|
+
coreErrors
|
|
834
|
+
);
|
|
835
|
+
if (typeof response.receipt !== "string" || !response.receipt.trim()) {
|
|
836
|
+
throw coreErrors.invalidResponse("Email code request response has an invalid receipt field");
|
|
837
|
+
}
|
|
838
|
+
if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
|
|
839
|
+
throw coreErrors.invalidResponse(
|
|
840
|
+
"Email code request response has an invalid resendAfterSeconds field"
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
return { receipt: response.receipt, resendAfterSeconds: response.resendAfterSeconds };
|
|
844
|
+
}
|
|
845
|
+
function expectExchangeCode(value) {
|
|
846
|
+
const response = expectObject2(
|
|
847
|
+
value,
|
|
848
|
+
"Email sign-in exchange code response",
|
|
849
|
+
coreErrors
|
|
850
|
+
);
|
|
851
|
+
if (typeof response.exchangeCode !== "string" || !response.exchangeCode.trim()) {
|
|
852
|
+
throw coreErrors.invalidResponse(
|
|
853
|
+
"Email sign-in exchange code response has an invalid exchangeCode field"
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
return response.exchangeCode;
|
|
857
|
+
}
|
|
858
|
+
function expectMagicLinkInspection(value) {
|
|
859
|
+
const response = expectObject2(
|
|
860
|
+
value,
|
|
861
|
+
"Email sign-in link inspection response",
|
|
862
|
+
coreErrors
|
|
863
|
+
);
|
|
864
|
+
const state = optionalString2(response.state);
|
|
865
|
+
if (!state?.trim()) {
|
|
866
|
+
throw coreErrors.invalidResponse(
|
|
867
|
+
"Email sign-in link inspection response has an invalid state field"
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
return {
|
|
871
|
+
state: isMagicLinkState(state) ? state : "INVALID",
|
|
872
|
+
origin: optionalString2(response.origin),
|
|
873
|
+
sdkState: optionalString2(response.sdkState)
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
function resolveLanguage(requested, browserWindow) {
|
|
877
|
+
if (requested) return requested;
|
|
878
|
+
const preferred = browserWindow.navigator?.language ?? "";
|
|
879
|
+
return preferred.toLowerCase().startsWith("en") ? "en" : DEFAULT_LANGUAGE;
|
|
880
|
+
}
|
|
881
|
+
var EmailCodeFlow = class {
|
|
882
|
+
appId;
|
|
883
|
+
client;
|
|
884
|
+
pendingRequest;
|
|
885
|
+
constructor(config) {
|
|
886
|
+
this.appId = config.appId;
|
|
887
|
+
this.client = config.client;
|
|
888
|
+
this.pendingRequest = config.pendingRequest;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Asks IAM to send a code to an address, and writes down that a request is in
|
|
892
|
+
* flight so the tab the link opens can finish it. Calling it again replaces
|
|
893
|
+
* the pending request, which is what resending is.
|
|
894
|
+
*
|
|
895
|
+
* The request is written only once IAM accepts it. A resend IAM refuses, a
|
|
896
|
+
* rate limit being the everyday case, would otherwise replace the request the
|
|
897
|
+
* message already in the mailbox names, and silently kill that link.
|
|
898
|
+
*/
|
|
899
|
+
async requestCode(request, brand) {
|
|
900
|
+
const browserWindow = this.requireBrowser();
|
|
901
|
+
const origin = browserWindow.location.origin;
|
|
902
|
+
const state = this.pendingRequest.newRequestState();
|
|
903
|
+
const result = expectEmailCodeRequestResult(
|
|
904
|
+
await this.client.post(MAGIC_LINK_PATH, {
|
|
905
|
+
email: request.email,
|
|
906
|
+
brand,
|
|
907
|
+
language: resolveLanguage(request.language, browserWindow),
|
|
908
|
+
appId: this.appId,
|
|
909
|
+
origin,
|
|
910
|
+
state
|
|
911
|
+
})
|
|
912
|
+
);
|
|
913
|
+
this.pendingRequest.rememberPendingRequest(state, origin);
|
|
914
|
+
return result;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Turns the code the person typed into an app session. IAM answers the
|
|
918
|
+
* verification with a single-use exchange code, redeemed here through the same
|
|
919
|
+
* route the auth page handshake uses.
|
|
920
|
+
*/
|
|
921
|
+
async verifyCode(verification) {
|
|
922
|
+
this.requireBrowser();
|
|
923
|
+
const exchangeCode = expectExchangeCode(
|
|
924
|
+
await this.client.post(VERIFY_PATH, {
|
|
925
|
+
receipt: verification.receipt,
|
|
926
|
+
code: verification.code
|
|
927
|
+
})
|
|
928
|
+
);
|
|
929
|
+
this.pendingRequest.discardPendingRequest();
|
|
930
|
+
return this.pendingRequest.redeemExchangeCode(exchangeCode);
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Finishes the sign-in from a `#emailToken=` link that landed on this origin,
|
|
934
|
+
* or returns `null` when the URL carries no link, or carries one this browser
|
|
935
|
+
* cannot claim. A link that can be claimed but is expired, already used, or
|
|
936
|
+
* unknown to IAM is reported as a {@link MitraApiError}.
|
|
937
|
+
*
|
|
938
|
+
* The link is inspected before it is consumed, so a browser without the
|
|
939
|
+
* pending request never spends it.
|
|
940
|
+
*/
|
|
941
|
+
async completeLink() {
|
|
942
|
+
const browserWindow = this.requireBrowser();
|
|
943
|
+
const fragment = browserWindow.location.hash.replace(/^#/, "");
|
|
944
|
+
const token = new URLSearchParams(fragment).get(LINK_TOKEN_KEY);
|
|
945
|
+
if (!token?.trim()) return null;
|
|
946
|
+
const pendingState = this.pendingRequest.pendingRequestState();
|
|
947
|
+
if (pendingState === null) {
|
|
948
|
+
this.dropLinkFromFragment(browserWindow, fragment);
|
|
949
|
+
this.pendingRequest.discardPendingRequest();
|
|
950
|
+
return null;
|
|
951
|
+
}
|
|
952
|
+
let inspection;
|
|
953
|
+
try {
|
|
954
|
+
inspection = expectMagicLinkInspection(
|
|
955
|
+
await this.client.get(CONFIRM_PATH, { token })
|
|
956
|
+
);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
this.dropLinkFromFragment(browserWindow, fragment);
|
|
959
|
+
throw error;
|
|
960
|
+
}
|
|
961
|
+
if (inspection.state !== "OK") {
|
|
962
|
+
this.dropLinkFromFragment(browserWindow, fragment);
|
|
963
|
+
throw linkFailure(inspection.state);
|
|
964
|
+
}
|
|
965
|
+
if (inspection.origin !== browserWindow.location.origin || inspection.sdkState !== pendingState) {
|
|
966
|
+
this.dropLinkFromFragment(browserWindow, fragment);
|
|
967
|
+
return null;
|
|
968
|
+
}
|
|
969
|
+
try {
|
|
970
|
+
const exchangeCode = expectExchangeCode(
|
|
971
|
+
await this.client.post(CONFIRM_PATH, { token })
|
|
972
|
+
);
|
|
973
|
+
return await this.pendingRequest.redeemExchangeCode(exchangeCode);
|
|
974
|
+
} finally {
|
|
975
|
+
this.dropLinkFromFragment(browserWindow, fragment);
|
|
976
|
+
this.pendingRequest.discardPendingRequest();
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Removes the link from the URL and leaves the rest of the fragment exactly as
|
|
981
|
+
* it was found. An application may route on it, and rewriting the fragment as
|
|
982
|
+
* parameters would turn a path like `#/orders/1` into something its router no
|
|
983
|
+
* longer recognizes.
|
|
984
|
+
*/
|
|
985
|
+
dropLinkFromFragment(browserWindow, fragment) {
|
|
986
|
+
const remaining = fragment.split("&").filter((part) => part !== LINK_TOKEN_KEY && !part.startsWith(`${LINK_TOKEN_KEY}=`)).join("&");
|
|
987
|
+
const hash = remaining ? `#${remaining}` : "";
|
|
988
|
+
browserWindow.history.replaceState(
|
|
989
|
+
{},
|
|
990
|
+
"",
|
|
991
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}${hash}`
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
requireBrowser() {
|
|
995
|
+
if (globalThis.window === void 0) {
|
|
996
|
+
throw new Error("Email sign-in is only available in a browser.");
|
|
997
|
+
}
|
|
998
|
+
return globalThis.window;
|
|
999
|
+
}
|
|
1000
|
+
};
|
|
1001
|
+
|
|
732
1002
|
// src/modules/auth.ts
|
|
733
1003
|
var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
|
|
734
1004
|
var sessionPorts = /* @__PURE__ */ new WeakMap();
|
|
@@ -781,6 +1051,8 @@ var AuthModule = class {
|
|
|
781
1051
|
googleAuth;
|
|
782
1052
|
microsoftAuth;
|
|
783
1053
|
emailAuth;
|
|
1054
|
+
emailCode;
|
|
1055
|
+
brand = null;
|
|
784
1056
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
785
1057
|
this.appId = appId;
|
|
786
1058
|
const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
|
|
@@ -817,6 +1089,11 @@ var AuthModule = class {
|
|
|
817
1089
|
client: this.publicClient,
|
|
818
1090
|
provider: "email"
|
|
819
1091
|
});
|
|
1092
|
+
this.emailCode = new EmailCodeFlow({
|
|
1093
|
+
appId,
|
|
1094
|
+
client: this.publicClient,
|
|
1095
|
+
pendingRequest: this.emailAuth
|
|
1096
|
+
});
|
|
820
1097
|
this.loadFromStorage();
|
|
821
1098
|
const readAccessToken = () => this.#accessToken;
|
|
822
1099
|
sessionPorts.set(this, {
|
|
@@ -998,19 +1275,92 @@ var AuthModule = class {
|
|
|
998
1275
|
return this.establishSession(await this.emailAuth.signIn(options));
|
|
999
1276
|
}
|
|
1000
1277
|
/**
|
|
1001
|
-
*
|
|
1002
|
-
*
|
|
1278
|
+
* Publishes the brand `init()` read from the app info, which IAM needs to
|
|
1279
|
+
* choose the message it sends for {@link requestEmailCode}.
|
|
1003
1280
|
*
|
|
1004
|
-
*
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1281
|
+
* @internal
|
|
1282
|
+
*/
|
|
1283
|
+
setBrand(brand) {
|
|
1284
|
+
this.brand = brand;
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Asks IAM to email a six-digit code, without any platform screen: the
|
|
1288
|
+
* application renders its own address and code fields, and the message is
|
|
1289
|
+
* branded as the app. Answer it with {@link verifyEmailCode}.
|
|
1290
|
+
*
|
|
1291
|
+
* The same message also carries a link back to this application's own origin.
|
|
1292
|
+
* Sign-in continues there through {@link completeEmailSignInRedirect}, so the
|
|
1293
|
+
* request is written to `localStorage` under `mitra_email_redirect_{appId}` -
|
|
1294
|
+
* the one-time state and this origin, never a token - for 10 minutes. Only the
|
|
1295
|
+
* browser that asked can finish through the link.
|
|
1296
|
+
*
|
|
1297
|
+
* Resending is calling this again: the new request replaces the pending one,
|
|
1298
|
+
* and `resendAfterSeconds` says how long the application should wait before
|
|
1299
|
+
* offering that.
|
|
1300
|
+
*
|
|
1301
|
+
* @param request - Address to send to, and the language to write in.
|
|
1302
|
+
* @returns The receipt that names this request, and the resend delay.
|
|
1303
|
+
* @throws {MitraApiError} `INVALID_CONFIGURATION` before `init()` resolved the
|
|
1304
|
+
* app info, `RATE_LIMITED` (with `retryAfterSeconds`) when IAM asks the person
|
|
1305
|
+
* to wait, and the app access codes when this app refuses the address.
|
|
1009
1306
|
*
|
|
1010
|
-
* @
|
|
1011
|
-
*
|
|
1307
|
+
* @example
|
|
1308
|
+
* ```typescript
|
|
1309
|
+
* const { receipt, resendAfterSeconds } = await mitra.auth.requestEmailCode({
|
|
1310
|
+
* email: 'person@example.com',
|
|
1311
|
+
* });
|
|
1312
|
+
* ```
|
|
1313
|
+
*/
|
|
1314
|
+
async requestEmailCode(request) {
|
|
1315
|
+
return this.emailCode.requestCode(request, this.requireBrand());
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Turns the code from the message into a session, hydrating and persisting it
|
|
1319
|
+
* exactly like SSO does.
|
|
1320
|
+
*
|
|
1321
|
+
* @param verification - The receipt from {@link requestEmailCode} and the code
|
|
1322
|
+
* the person typed.
|
|
1323
|
+
* @returns The authenticated and hydrated user.
|
|
1324
|
+
* @throws {MitraApiError} `INVALID_CODE` when the code does not match,
|
|
1325
|
+
* `MAGIC_LINK_EXPIRED` or `MAGIC_LINK_USED` when the request is over.
|
|
1326
|
+
*
|
|
1327
|
+
* @example
|
|
1328
|
+
* ```typescript
|
|
1329
|
+
* const user = await mitra.auth.verifyEmailCode({ receipt, code: '123456' });
|
|
1330
|
+
* ```
|
|
1331
|
+
*/
|
|
1332
|
+
async verifyEmailCode(verification) {
|
|
1333
|
+
return this.establishSession(await this.emailCode.verifyCode(verification));
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Completes an email sign-in during application startup, like
|
|
1337
|
+
* {@link completeGoogleSignInRedirect}.
|
|
1338
|
+
*
|
|
1339
|
+
* It covers every way the flow comes back. The link in the message lands on
|
|
1340
|
+
* this application's own origin as `#emailToken=`, and that is the headless
|
|
1341
|
+
* flow: the link is inspected before it is spent, and it is only spent when
|
|
1342
|
+
* IAM reports the same origin the page is on and the one-time state of the
|
|
1343
|
+
* request pending in this browser. A browser without that request - another
|
|
1344
|
+
* device, or a scanner opening links on the way to a mailbox - consumes
|
|
1345
|
+
* nothing and leaves the link valid for the person who asked for it.
|
|
1346
|
+
*
|
|
1347
|
+
* The platform auth page instead comes back as `#codeMitra` and `#stateMitra`,
|
|
1348
|
+
* from the redirect in the tab that started it or from the tab the older link
|
|
1349
|
+
* opened, and is completed by the same state check.
|
|
1350
|
+
*
|
|
1351
|
+
* From the link, only `emailToken` leaves the URL, so a fragment the
|
|
1352
|
+
* application routes on is left as it was. Coming back from the platform auth
|
|
1353
|
+
* page, the fragment is removed whole.
|
|
1354
|
+
*
|
|
1355
|
+
* @returns The authenticated user, or `null` when the URL carries no result,
|
|
1356
|
+
* carries one that belongs to another sign-in method's flow, or carries a link
|
|
1357
|
+
* this browser cannot claim.
|
|
1358
|
+
* @throws {MitraApiError} `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, or
|
|
1359
|
+
* `MAGIC_LINK_INVALID` when the link belongs here but cannot be used.
|
|
1012
1360
|
*/
|
|
1013
1361
|
async completeEmailSignInRedirect() {
|
|
1362
|
+
const linkResponse = await this.emailCode.completeLink();
|
|
1363
|
+
if (linkResponse) return this.establishSession(linkResponse);
|
|
1014
1364
|
const tokenResponse = await this.emailAuth.completeRedirect();
|
|
1015
1365
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1016
1366
|
}
|
|
@@ -1390,6 +1740,19 @@ var AuthModule = class {
|
|
|
1390
1740
|
belongsToConfiguredApp(token) {
|
|
1391
1741
|
return belongsToApp(token, this.appId);
|
|
1392
1742
|
}
|
|
1743
|
+
/**
|
|
1744
|
+
* The brand IAM needs to brand the message. It arrives with the app info, so
|
|
1745
|
+
* asking before `init()` is a configuration mistake rather than something to
|
|
1746
|
+
* guess a default for: the wrong brand sends the wrong message.
|
|
1747
|
+
*/
|
|
1748
|
+
requireBrand() {
|
|
1749
|
+
if (!this.brand) {
|
|
1750
|
+
throw coreErrors.configuration(
|
|
1751
|
+
"Email sign-in needs the app info resolved by init(). Call init() before requestEmailCode()."
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
return this.brand;
|
|
1755
|
+
}
|
|
1393
1756
|
notifySessionListeners() {
|
|
1394
1757
|
const session = this.readSessionTokens();
|
|
1395
1758
|
this.sessionListeners.forEach((callback) => {
|
|
@@ -1774,6 +2137,7 @@ var CONNECT_TIMEOUT_MS = 15e3;
|
|
|
1774
2137
|
var SILENCE_TIMEOUT_MS = 6e4;
|
|
1775
2138
|
var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
|
|
1776
2139
|
var SUPERSEDED_CLOSE_CODE = 4409;
|
|
2140
|
+
var SOCKET_OPEN = 1;
|
|
1777
2141
|
var SilenceWatchdog = class {
|
|
1778
2142
|
constructor(onSilence) {
|
|
1779
2143
|
this.onSilence = onSilence;
|
|
@@ -1889,6 +2253,8 @@ var BrowserAgentTaskEventSource = class {
|
|
|
1889
2253
|
*/
|
|
1890
2254
|
boxCursors = /* @__PURE__ */ new Map();
|
|
1891
2255
|
boxAddresses = /* @__PURE__ */ new Map();
|
|
2256
|
+
/** The box socket a task is talking on right now; absent while it is lost or being redialed. */
|
|
2257
|
+
directSockets = /* @__PURE__ */ new Map();
|
|
1892
2258
|
async open(taskId, observer, signal, transport = "auto") {
|
|
1893
2259
|
if (transport === "http") return this.openSse(taskId, observer, signal);
|
|
1894
2260
|
if (transport === "websocket") return this.openWebSocket(taskId, observer, signal);
|
|
@@ -1920,6 +2286,23 @@ var BrowserAgentTaskEventSource = class {
|
|
|
1920
2286
|
}
|
|
1921
2287
|
};
|
|
1922
2288
|
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Writes a message or an interrupt on the box socket when the task is on the direct channel
|
|
2291
|
+
* and that socket is open right now. The box accepts the core's input as its own inbound
|
|
2292
|
+
* frame, asks the copilot for admission itself and answers on this same socket with the
|
|
2293
|
+
* frames the observer already reads, so the copilot's host socket is off the message path.
|
|
2294
|
+
* False sends the caller to REST: no direct channel, a socket lost or mid-redial, or an
|
|
2295
|
+
* approval, which stays on REST as it is.
|
|
2296
|
+
*
|
|
2297
|
+
* A frame written on a socket that closes before the box acknowledges it is not sent again
|
|
2298
|
+
* over REST: the box may have admitted the turn already, and a second copy would start it
|
|
2299
|
+
* twice. The redial replays the box log, which is the same recovery a REST 202 gets when its
|
|
2300
|
+
* turn is lost.
|
|
2301
|
+
*/
|
|
2302
|
+
sendOnChannel(taskId, input) {
|
|
2303
|
+
if (input.type === "approval_response") return false;
|
|
2304
|
+
return this.directSockets.get(taskId)?.send(JSON.stringify(input)) ?? false;
|
|
2305
|
+
}
|
|
1923
2306
|
async requireFreshToken() {
|
|
1924
2307
|
const fresh = await this.auth.ensureFreshSession();
|
|
1925
2308
|
const token = this.auth.accessToken;
|
|
@@ -2006,6 +2389,11 @@ var BrowserAgentTaskEventSource = class {
|
|
|
2006
2389
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2007
2390
|
let inTurn = false;
|
|
2008
2391
|
let current = null;
|
|
2392
|
+
const track = (socket) => {
|
|
2393
|
+
if (socket) this.directSockets.set(taskId, socket);
|
|
2394
|
+
else if (current && this.directSockets.get(taskId) === current) this.directSockets.delete(taskId);
|
|
2395
|
+
current = socket;
|
|
2396
|
+
};
|
|
2009
2397
|
const onFrame = (event) => {
|
|
2010
2398
|
if (typeof event.sequence === "number") {
|
|
2011
2399
|
const seen = this.boxCursors.get(taskId) ?? 0;
|
|
@@ -2015,22 +2403,21 @@ var BrowserAgentTaskEventSource = class {
|
|
|
2015
2403
|
observer.onEvent(event);
|
|
2016
2404
|
};
|
|
2017
2405
|
const onLost = (error, code) => {
|
|
2018
|
-
|
|
2406
|
+
track(null);
|
|
2019
2407
|
if (link.signal.aborted) return;
|
|
2020
2408
|
if (!inTurn || code === SUPERSEDED_CLOSE_CODE) {
|
|
2021
2409
|
observer.onDisconnect(error);
|
|
2022
2410
|
return;
|
|
2023
2411
|
}
|
|
2024
|
-
void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then(
|
|
2025
|
-
current = socket;
|
|
2026
|
-
});
|
|
2412
|
+
void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then(track);
|
|
2027
2413
|
};
|
|
2028
|
-
|
|
2414
|
+
track(await this.dial(channel.wsUrl, { signal: link.signal, onFrame, onLost }));
|
|
2029
2415
|
return {
|
|
2030
2416
|
close: () => {
|
|
2031
2417
|
signal?.removeEventListener("abort", onAbort);
|
|
2032
2418
|
link.abort();
|
|
2033
2419
|
current?.close();
|
|
2420
|
+
track(null);
|
|
2034
2421
|
}
|
|
2035
2422
|
};
|
|
2036
2423
|
}
|
|
@@ -2115,6 +2502,15 @@ var BrowserAgentTaskEventSource = class {
|
|
|
2115
2502
|
removeAbortListener();
|
|
2116
2503
|
socket.close(1e3, "Client closed");
|
|
2117
2504
|
};
|
|
2505
|
+
const send = (frame) => {
|
|
2506
|
+
if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
|
|
2507
|
+
try {
|
|
2508
|
+
socket.send(frame);
|
|
2509
|
+
return true;
|
|
2510
|
+
} catch {
|
|
2511
|
+
return false;
|
|
2512
|
+
}
|
|
2513
|
+
};
|
|
2118
2514
|
const onAbort = () => {
|
|
2119
2515
|
if (!opened) {
|
|
2120
2516
|
rejectHandshake(signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted."));
|
|
@@ -2138,7 +2534,7 @@ var BrowserAgentTaskEventSource = class {
|
|
|
2138
2534
|
} catch {
|
|
2139
2535
|
}
|
|
2140
2536
|
}
|
|
2141
|
-
resolve({ close });
|
|
2537
|
+
resolve({ close, send });
|
|
2142
2538
|
};
|
|
2143
2539
|
socket.onerror = () => {
|
|
2144
2540
|
if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
|
|
@@ -2274,7 +2670,10 @@ function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
|
|
|
2274
2670
|
}
|
|
2275
2671
|
};
|
|
2276
2672
|
const manager = createAgentTaskSessionManager({
|
|
2277
|
-
tasks: {
|
|
2673
|
+
tasks: {
|
|
2674
|
+
...tasks,
|
|
2675
|
+
sendInput: (taskId, input) => source.sendOnChannel(taskId, input) ? Promise.resolve() : outbox.sendInput(taskId, input)
|
|
2676
|
+
},
|
|
2278
2677
|
eventSource
|
|
2279
2678
|
});
|
|
2280
2679
|
return withAgentTaskSessions(tasks, {
|
|
@@ -2294,38 +2693,38 @@ function requireProvider(provider, allowed, flow) {
|
|
|
2294
2693
|
function createBrowserAgentCredentialsModule(httpClient) {
|
|
2295
2694
|
const core = createAgentCredentialsModule(httpClient, coreErrors);
|
|
2296
2695
|
return {
|
|
2297
|
-
list: () => core.list(),
|
|
2298
|
-
listModels: (agentId) => core.listModels(agentId),
|
|
2299
|
-
saveApiKey: (provider, apiKey) => {
|
|
2696
|
+
list: (options) => core.list(options),
|
|
2697
|
+
listModels: (agentId, options) => core.listModels(agentId, options),
|
|
2698
|
+
saveApiKey: (provider, apiKey, options) => {
|
|
2300
2699
|
requireProvider(provider, ["ANTHROPIC", "OPENAI"], "API key authentication");
|
|
2301
|
-
return core.saveApiKey(provider, apiKey);
|
|
2700
|
+
return core.saveApiKey(provider, apiKey, options);
|
|
2302
2701
|
},
|
|
2303
|
-
remove: (provider) => {
|
|
2702
|
+
remove: (provider, options) => {
|
|
2304
2703
|
requireProvider(provider, ["ANTHROPIC", "OPENAI"], "Credential removal");
|
|
2305
|
-
return core.remove(provider);
|
|
2704
|
+
return core.remove(provider, options);
|
|
2306
2705
|
},
|
|
2307
|
-
startOAuth: (provider) => {
|
|
2706
|
+
startOAuth: (provider, options) => {
|
|
2308
2707
|
requireProvider(provider, ["ANTHROPIC"], "OAuth");
|
|
2309
|
-
return core.startOAuth(provider);
|
|
2708
|
+
return core.startOAuth(provider, options);
|
|
2310
2709
|
},
|
|
2311
|
-
exchangeOAuth: (provider, input) => {
|
|
2710
|
+
exchangeOAuth: (provider, input, options) => {
|
|
2312
2711
|
requireProvider(provider, ["ANTHROPIC"], "OAuth");
|
|
2313
|
-
return core.exchangeOAuth(provider, input);
|
|
2712
|
+
return core.exchangeOAuth(provider, input, options);
|
|
2314
2713
|
},
|
|
2315
|
-
startDeviceAuthorization: (provider) => {
|
|
2714
|
+
startDeviceAuthorization: (provider, options) => {
|
|
2316
2715
|
requireProvider(provider, ["OPENAI"], "Device authorization");
|
|
2317
|
-
return core.startDeviceAuthorization(provider);
|
|
2716
|
+
return core.startDeviceAuthorization(provider, options);
|
|
2318
2717
|
},
|
|
2319
|
-
pollDeviceAuthorization: (provider, deviceAuthId) => {
|
|
2718
|
+
pollDeviceAuthorization: (provider, deviceAuthId, options) => {
|
|
2320
2719
|
requireProvider(provider, ["OPENAI"], "Device authorization");
|
|
2321
|
-
return core.pollDeviceAuthorization(provider, deviceAuthId);
|
|
2720
|
+
return core.pollDeviceAuthorization(provider, deviceAuthId, options);
|
|
2322
2721
|
}
|
|
2323
2722
|
};
|
|
2324
2723
|
}
|
|
2325
2724
|
|
|
2326
2725
|
// src/client.ts
|
|
2327
2726
|
function expectAppInfoResponse(value) {
|
|
2328
|
-
const response =
|
|
2727
|
+
const response = expectObject3(
|
|
2329
2728
|
value,
|
|
2330
2729
|
"App info response",
|
|
2331
2730
|
coreErrors
|
|
@@ -2347,7 +2746,10 @@ function expectAppInfoResponse(value) {
|
|
|
2347
2746
|
// instead of failing `init()`: a Code Studio older than the email login gate
|
|
2348
2747
|
// answers without this field, and an app that cannot prove it is enabled
|
|
2349
2748
|
// should stop offering the option, not stop starting.
|
|
2350
|
-
emailLoginEnabled: response.emailLoginEnabled === true
|
|
2749
|
+
emailLoginEnabled: response.emailLoginEnabled === true,
|
|
2750
|
+
// Same reasoning, and the brand is never guessed: without it the headless
|
|
2751
|
+
// email methods refuse instead of asking IAM to brand a message at random.
|
|
2752
|
+
brand: typeof response.brand === "string" && response.brand.trim() ? response.brand : null
|
|
2351
2753
|
};
|
|
2352
2754
|
}
|
|
2353
2755
|
function createClient(config) {
|
|
@@ -2430,6 +2832,9 @@ function createClient(config) {
|
|
|
2430
2832
|
if (appInfo.dataSourceId) {
|
|
2431
2833
|
entitiesModule.setDataSourceId(appInfo.dataSourceId);
|
|
2432
2834
|
}
|
|
2835
|
+
if (appInfo.brand) {
|
|
2836
|
+
authModule.setBrand(appInfo.brand);
|
|
2837
|
+
}
|
|
2433
2838
|
allowSignup = appInfo.allowSignup;
|
|
2434
2839
|
emailLoginEnabled = appInfo.emailLoginEnabled;
|
|
2435
2840
|
initialized = true;
|