@mitralab.io/platform-sdk 1.8.7 → 1.9.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 +113 -0
- package/README.md +105 -5
- package/dist/index.cjs +665 -53
- package/dist/index.d.cts +163 -7
- package/dist/index.d.ts +163 -7
- package/dist/index.js +665 -53
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
+
FileTransferError: () => import_sdk_core12.FileTransferError,
|
|
23
24
|
MitraApiError: () => MitraApiError,
|
|
24
25
|
callIntegrationMitra: () => import_mitra_interactions_sdk14.callIntegrationMitra,
|
|
25
26
|
configureSdkMitra: () => import_mitra_interactions_sdk3.configureSdkMitra,
|
|
@@ -365,6 +366,7 @@ var LegacySessionBridge = class {
|
|
|
365
366
|
this.unsubscribeFromAuth = null;
|
|
366
367
|
}
|
|
367
368
|
syncToLegacy(session) {
|
|
369
|
+
const refreshToken = this.auth.isTabScoped() ? null : session.refreshToken;
|
|
368
370
|
try {
|
|
369
371
|
const authPageUrl = resolveAuthPageUrl(
|
|
370
372
|
this.apiUrl,
|
|
@@ -377,11 +379,11 @@ var LegacySessionBridge = class {
|
|
|
377
379
|
projectId: this.appId,
|
|
378
380
|
onTokenRefresh: (session2) => this.rotate(session2),
|
|
379
381
|
...session.token ? { token: session.token } : {},
|
|
380
|
-
...
|
|
382
|
+
...refreshToken ? { refreshToken } : {}
|
|
381
383
|
});
|
|
382
384
|
const legacyConfig = (0, import_mitra_interactions_sdk.getConfig)();
|
|
383
385
|
if (!session.token) delete legacyConfig.token;
|
|
384
|
-
if (!
|
|
386
|
+
if (!refreshToken) delete legacyConfig.refreshToken;
|
|
385
387
|
} catch {
|
|
386
388
|
}
|
|
387
389
|
}
|
|
@@ -460,41 +462,59 @@ var RESULT_TYPE = "mitra-oauth-result";
|
|
|
460
462
|
var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
|
|
461
463
|
var SESSION_TYPE = "mitra-auth-session";
|
|
462
464
|
var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
|
|
465
|
+
var AUTH_PAGE_METHODS = /* @__PURE__ */ new Set([
|
|
466
|
+
"google",
|
|
467
|
+
"microsoft",
|
|
468
|
+
"email",
|
|
469
|
+
"password"
|
|
470
|
+
]);
|
|
471
|
+
function isAuthPageMethod(value) {
|
|
472
|
+
return typeof value === "string" && AUTH_PAGE_METHODS.has(value);
|
|
473
|
+
}
|
|
474
|
+
var EXCHANGE_ROUTES = {
|
|
475
|
+
google: { path: "/api/v1/auth/google", sendsRedirectUri: true },
|
|
476
|
+
microsoft: { path: "/api/v1/auth/microsoft", sendsRedirectUri: true },
|
|
477
|
+
email: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false },
|
|
478
|
+
password: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false }
|
|
479
|
+
};
|
|
463
480
|
var FIVE_MINUTES_MS = 5 * 60 * 1e3;
|
|
464
481
|
var TEN_MINUTES_MS = 10 * 60 * 1e3;
|
|
465
482
|
var PROVIDERS = {
|
|
466
483
|
google: {
|
|
467
484
|
label: "Google",
|
|
468
|
-
|
|
469
|
-
sendsRedirectUri: true,
|
|
485
|
+
exchange: EXCHANGE_ROUTES.google,
|
|
470
486
|
redirectStorage: "sessionStorage",
|
|
471
487
|
popupTimeoutMs: FIVE_MINUTES_MS
|
|
472
488
|
},
|
|
473
489
|
microsoft: {
|
|
474
490
|
label: "Microsoft",
|
|
475
|
-
|
|
476
|
-
sendsRedirectUri: true,
|
|
491
|
+
exchange: EXCHANGE_ROUTES.microsoft,
|
|
477
492
|
redirectStorage: "sessionStorage",
|
|
478
493
|
popupTimeoutMs: FIVE_MINUTES_MS
|
|
479
494
|
},
|
|
480
495
|
email: {
|
|
481
496
|
label: "Email",
|
|
482
|
-
|
|
483
|
-
sendsRedirectUri: false,
|
|
497
|
+
exchange: EXCHANGE_ROUTES.email,
|
|
484
498
|
redirectStorage: "localStorage",
|
|
485
499
|
pendingRequestTtlMs: TEN_MINUTES_MS,
|
|
486
500
|
popupTimeoutMs: TEN_MINUTES_MS
|
|
487
501
|
},
|
|
488
|
-
//
|
|
489
|
-
//
|
|
490
|
-
// mailbox, hence the email timeout; there is no link, so nothing pending is
|
|
491
|
-
// written for another tab.
|
|
502
|
+
// Signing up waits on a code read from a mailbox, hence the email timeout;
|
|
503
|
+
// there is no link, so nothing pending is written for another tab.
|
|
492
504
|
password: {
|
|
493
505
|
label: "Password",
|
|
494
|
-
|
|
495
|
-
sendsRedirectUri: false,
|
|
506
|
+
exchange: EXCHANGE_ROUTES.password,
|
|
496
507
|
redirectStorage: "sessionStorage",
|
|
497
508
|
popupTimeoutMs: TEN_MINUTES_MS
|
|
509
|
+
},
|
|
510
|
+
// The person may pick the email code on this screen, and its message carries
|
|
511
|
+
// a link that opens another tab, so this flow keeps the email lifetimes.
|
|
512
|
+
all: {
|
|
513
|
+
label: "Auth page",
|
|
514
|
+
exchange: "reportedMethod",
|
|
515
|
+
redirectStorage: "localStorage",
|
|
516
|
+
pendingRequestTtlMs: TEN_MINUTES_MS,
|
|
517
|
+
popupTimeoutMs: TEN_MINUTES_MS
|
|
498
518
|
}
|
|
499
519
|
};
|
|
500
520
|
var POPUP_WIDTH = 480;
|
|
@@ -626,6 +646,7 @@ var AuthPageFlow = class {
|
|
|
626
646
|
const code = params.get("codeMitra");
|
|
627
647
|
const state = params.get("stateMitra");
|
|
628
648
|
const error = params.get("errorMitra");
|
|
649
|
+
const reportedMethod = params.get("providerMitra");
|
|
629
650
|
if (code === null && state === null && error === null) return null;
|
|
630
651
|
const context = this.readRedirectContext(browserWindow);
|
|
631
652
|
const hasState = state !== null && state.trim() !== "";
|
|
@@ -667,7 +688,7 @@ var AuthPageFlow = class {
|
|
|
667
688
|
if (!code?.trim()) {
|
|
668
689
|
throw new Error(`${this.providerLabel} sign-in redirect is missing code.`);
|
|
669
690
|
}
|
|
670
|
-
return this.exchangeCode(code, context.redirectUri);
|
|
691
|
+
return this.exchangeCode(code, context.redirectUri, this.readReportedMethod(reportedMethod));
|
|
671
692
|
}
|
|
672
693
|
async startPopup(browserWindow, request) {
|
|
673
694
|
const state = this.generateState();
|
|
@@ -695,7 +716,10 @@ var AuthPageFlow = class {
|
|
|
695
716
|
request.sessionToken
|
|
696
717
|
);
|
|
697
718
|
if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
|
|
698
|
-
|
|
719
|
+
const reportedMethod = this.readReportedMethod(result.method);
|
|
720
|
+
if (result.code) {
|
|
721
|
+
return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl), reportedMethod);
|
|
722
|
+
}
|
|
699
723
|
return expectAuthTokenResponse(result.token);
|
|
700
724
|
}
|
|
701
725
|
startRedirect(browserWindow) {
|
|
@@ -766,14 +790,36 @@ var AuthPageFlow = class {
|
|
|
766
790
|
redeemExchangeCode(code) {
|
|
767
791
|
return this.exchangeCode(code, null);
|
|
768
792
|
}
|
|
769
|
-
async exchangeCode(code, redirectUri) {
|
|
770
|
-
const
|
|
793
|
+
async exchangeCode(code, redirectUri, reportedMethod) {
|
|
794
|
+
const route = this.exchangeRoute(reportedMethod);
|
|
795
|
+
const response = await this.client.post(route.path, {
|
|
771
796
|
appId: this.appId,
|
|
772
797
|
code,
|
|
773
|
-
...
|
|
798
|
+
...route.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
|
|
774
799
|
});
|
|
775
800
|
return expectAuthTokenResponse(response);
|
|
776
801
|
}
|
|
802
|
+
exchangeRoute(reportedMethod) {
|
|
803
|
+
if (this.profile.exchange !== "reportedMethod") return this.profile.exchange;
|
|
804
|
+
if (!reportedMethod) {
|
|
805
|
+
throw new Error("The all-methods sign-in cannot redeem a code without the method the auth page reported.");
|
|
806
|
+
}
|
|
807
|
+
return EXCHANGE_ROUTES[reportedMethod];
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* The method the auth page says produced the code. Only the flow that asked
|
|
811
|
+
* for the page with every method reads it: a single-method page sends no such
|
|
812
|
+
* field, and its own route is already known. Anything outside the known
|
|
813
|
+
* methods is refused rather than mapped to a route, since a code redeemed at
|
|
814
|
+
* the wrong route is spent for nothing.
|
|
815
|
+
*/
|
|
816
|
+
readReportedMethod(value) {
|
|
817
|
+
if (this.profile.exchange !== "reportedMethod") return void 0;
|
|
818
|
+
if (!isAuthPageMethod(value)) {
|
|
819
|
+
throw new Error(`${this.providerLabel} did not report which sign-in method produced the code.`);
|
|
820
|
+
}
|
|
821
|
+
return value;
|
|
822
|
+
}
|
|
777
823
|
buildStartUrl(browserWindow, authPageUrl, state, view) {
|
|
778
824
|
const startUrl = new URL(authPageUrl);
|
|
779
825
|
startUrl.searchParams.set("provider", this.provider);
|
|
@@ -814,7 +860,12 @@ var AuthPageFlow = class {
|
|
|
814
860
|
if (!Number.isFinite(context.createdAt)) return true;
|
|
815
861
|
return Date.now() - context.createdAt > ttlMs;
|
|
816
862
|
}
|
|
817
|
-
/**
|
|
863
|
+
/**
|
|
864
|
+
* A one-time state that names the flow that created it, so its fragment is
|
|
865
|
+
* recognizable. The auth page relies on the `all.` prefix too: the tab the
|
|
866
|
+
* email link opens has only the state to tell a chooser request apart, and
|
|
867
|
+
* answers it with `providerMitra=email`.
|
|
868
|
+
*/
|
|
818
869
|
generateState() {
|
|
819
870
|
if (!globalThis.crypto?.getRandomValues) {
|
|
820
871
|
throw new Error(`${this.providerLabel} sign-in requires crypto.getRandomValues.`);
|
|
@@ -953,9 +1004,15 @@ function readPopupResult(data, expectedState, providerLabel) {
|
|
|
953
1004
|
}
|
|
954
1005
|
const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
|
|
955
1006
|
if (!code && data.token === void 0) {
|
|
956
|
-
return { error: new Error(`${providerLabel}
|
|
1007
|
+
return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
|
|
957
1008
|
}
|
|
958
|
-
return {
|
|
1009
|
+
return {
|
|
1010
|
+
value: {
|
|
1011
|
+
...code ? { code } : {},
|
|
1012
|
+
...data.token !== void 0 ? { token: data.token } : {},
|
|
1013
|
+
...data.provider !== void 0 ? { method: data.provider } : {}
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
959
1016
|
}
|
|
960
1017
|
|
|
961
1018
|
// src/modules/email-code-flow.ts
|
|
@@ -1153,6 +1210,346 @@ var EmailCodeFlow = class {
|
|
|
1153
1210
|
}
|
|
1154
1211
|
};
|
|
1155
1212
|
|
|
1213
|
+
// src/modules/identity-connection-flow.ts
|
|
1214
|
+
var STATE_PREFIX = "connection.";
|
|
1215
|
+
var SLUG_PATTERN = /^[a-z0-9-]{1,64}$/;
|
|
1216
|
+
var WILDCARD_PREFIX = "https://*.";
|
|
1217
|
+
var ERROR_CODE_PATTERN = /^[a-z_]{1,64}$/;
|
|
1218
|
+
function isAllowedOrigin(origin, allowed) {
|
|
1219
|
+
const normalized = origin.toLowerCase();
|
|
1220
|
+
return allowed.some((candidate) => {
|
|
1221
|
+
if (!candidate.startsWith(WILDCARD_PREFIX)) return candidate === normalized;
|
|
1222
|
+
if (!normalized.startsWith("https://")) return false;
|
|
1223
|
+
const host = normalized.slice("https://".length);
|
|
1224
|
+
const domain = candidate.slice(WILDCARD_PREFIX.length);
|
|
1225
|
+
return !host.includes(":") && !host.includes("/") && host.endsWith(`.${domain}`) && host.length > domain.length + 1;
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
function readAllowedOrigins(response) {
|
|
1229
|
+
const origins = response?.allowedOrigins;
|
|
1230
|
+
return Array.isArray(origins) ? origins.filter((origin) => typeof origin === "string") : [];
|
|
1231
|
+
}
|
|
1232
|
+
async function exchangeIdentityConnectionCode(client, slug, appId, code) {
|
|
1233
|
+
const response = await client.post(
|
|
1234
|
+
`/api/v1/auth/identity-connections/${slug}/exchange`,
|
|
1235
|
+
{ appId, code }
|
|
1236
|
+
);
|
|
1237
|
+
return expectAuthTokenResponse(response);
|
|
1238
|
+
}
|
|
1239
|
+
var IdentityConnectionFlow = class {
|
|
1240
|
+
appId;
|
|
1241
|
+
client;
|
|
1242
|
+
constructor(config) {
|
|
1243
|
+
this.appId = config.appId;
|
|
1244
|
+
this.client = config.client;
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Redeems the code the bridge put in the fragment, or returns `null` when the
|
|
1248
|
+
* fragment belongs to no identity connection. A fragment of another flow is
|
|
1249
|
+
* left exactly as it was found, so its own completion can still read it.
|
|
1250
|
+
*
|
|
1251
|
+
* A fragment of this flow is removed from the URL before anything can fail,
|
|
1252
|
+
* so a failure is reported once instead of on every reload, and the code is
|
|
1253
|
+
* never redeemed twice.
|
|
1254
|
+
*/
|
|
1255
|
+
async completeRedirect() {
|
|
1256
|
+
if (globalThis.window === void 0) {
|
|
1257
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1258
|
+
}
|
|
1259
|
+
const browserWindow = globalThis.window;
|
|
1260
|
+
const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
|
|
1261
|
+
const slug = params.get("connectionMitra");
|
|
1262
|
+
const state = params.get("stateMitra");
|
|
1263
|
+
if (slug === null || !state?.startsWith(STATE_PREFIX)) return null;
|
|
1264
|
+
const code = params.get("codeMitra");
|
|
1265
|
+
const error = params.get("errorMitra");
|
|
1266
|
+
browserWindow.history.replaceState(
|
|
1267
|
+
{},
|
|
1268
|
+
"",
|
|
1269
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}`
|
|
1270
|
+
);
|
|
1271
|
+
if (browserWindow.self === browserWindow.top) {
|
|
1272
|
+
throw new Error("Identity connection sign-in is only accepted inside the host system iframe.");
|
|
1273
|
+
}
|
|
1274
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1275
|
+
throw new Error("Identity connection sign-in redirect names an invalid connection.");
|
|
1276
|
+
}
|
|
1277
|
+
if (error !== null) {
|
|
1278
|
+
const reason = ERROR_CODE_PATTERN.test(error) ? `: ${error}` : "";
|
|
1279
|
+
throw new Error(`Identity connection sign-in failed${reason}.`);
|
|
1280
|
+
}
|
|
1281
|
+
if (!code?.trim()) {
|
|
1282
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1283
|
+
}
|
|
1284
|
+
await this.requireAllowedHost(browserWindow, slug);
|
|
1285
|
+
return exchangeIdentityConnectionCode(this.client, slug, this.appId, code);
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* A code is only redeemed when every page in the chain embedding this app is
|
|
1289
|
+
* a host system the connection allows. A page of someone else embedding the
|
|
1290
|
+
* app, directly or around an allowed host, with a code of another account
|
|
1291
|
+
* would otherwise sign this browser in as that account. The check mirrors
|
|
1292
|
+
* the one the bridge made on the message that carried the token.
|
|
1293
|
+
*
|
|
1294
|
+
* Only a browser that exposes `location.ancestorOrigins` can tell who embeds
|
|
1295
|
+
* the frame. Without it the host cannot be verified and the code is refused:
|
|
1296
|
+
* an unverifiable host is the exact case the check exists for.
|
|
1297
|
+
*/
|
|
1298
|
+
async requireAllowedHost(browserWindow, slug) {
|
|
1299
|
+
const hostOrigins = Array.from(browserWindow.location.ancestorOrigins ?? []);
|
|
1300
|
+
if (hostOrigins.length === 0) {
|
|
1301
|
+
throw new Error("Identity connection sign-in needs a browser that exposes the host system origin.");
|
|
1302
|
+
}
|
|
1303
|
+
const connection = await this.client.get(`/api/v1/auth/identity-connections/${slug}`);
|
|
1304
|
+
const allowedOrigins = readAllowedOrigins(connection);
|
|
1305
|
+
if (!hostOrigins.every((origin) => isAllowedOrigin(origin, allowedOrigins))) {
|
|
1306
|
+
throw new Error("Identity connection sign-in is not accepted under this host system.");
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
|
|
1311
|
+
// src/modules/identity-connection-redirect-flow.ts
|
|
1312
|
+
var STATE_PREFIX2 = "connection.";
|
|
1313
|
+
var SCOPE = "openid email profile";
|
|
1314
|
+
var CALLBACK_PARAMS = ["code", "state", "error", "error_description", "error_uri", "session_state", "iss"];
|
|
1315
|
+
var TOKEN_REQUEST_TIMEOUT_MS = 15e3;
|
|
1316
|
+
var STORAGE_UNREADABLE = Symbol("storage-unreadable");
|
|
1317
|
+
var UnsolicitedIdentityConnectionRedirectError = class extends Error {
|
|
1318
|
+
};
|
|
1319
|
+
function requireBrowser() {
|
|
1320
|
+
if (globalThis.window === void 0) {
|
|
1321
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1322
|
+
}
|
|
1323
|
+
return globalThis.window;
|
|
1324
|
+
}
|
|
1325
|
+
function isNonEmptyString2(value) {
|
|
1326
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
1327
|
+
}
|
|
1328
|
+
function readEndpoints(connection) {
|
|
1329
|
+
const fields = connection ?? {};
|
|
1330
|
+
const { authorizationEndpoint, tokenEndpoint, clientId } = fields;
|
|
1331
|
+
if (!isNonEmptyString2(authorizationEndpoint) || !isNonEmptyString2(tokenEndpoint) || !isNonEmptyString2(clientId)) {
|
|
1332
|
+
return null;
|
|
1333
|
+
}
|
|
1334
|
+
return { authorizationEndpoint, tokenEndpoint, clientId };
|
|
1335
|
+
}
|
|
1336
|
+
function base64Url(bytes) {
|
|
1337
|
+
const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
|
|
1338
|
+
let encoded = btoa(binary).replaceAll("+", "-").replaceAll("/", "_");
|
|
1339
|
+
while (encoded.endsWith("=")) encoded = encoded.slice(0, -1);
|
|
1340
|
+
return encoded;
|
|
1341
|
+
}
|
|
1342
|
+
function randomBytes(length) {
|
|
1343
|
+
if (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {
|
|
1344
|
+
throw new Error("Identity connection sign-in requires the Web Crypto API.");
|
|
1345
|
+
}
|
|
1346
|
+
const bytes = new Uint8Array(length);
|
|
1347
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1348
|
+
return bytes;
|
|
1349
|
+
}
|
|
1350
|
+
async function codeChallengeOf(codeVerifier) {
|
|
1351
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
1352
|
+
return base64Url(new Uint8Array(digest));
|
|
1353
|
+
}
|
|
1354
|
+
function requireBareRedirectUri(redirectUri, browserWindow) {
|
|
1355
|
+
let parsed;
|
|
1356
|
+
try {
|
|
1357
|
+
parsed = new URL(redirectUri);
|
|
1358
|
+
} catch {
|
|
1359
|
+
throw new Error("Identity connection sign-in redirectUri must be an absolute URL.");
|
|
1360
|
+
}
|
|
1361
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
1362
|
+
throw new Error("Identity connection sign-in redirectUri must be an http or https URL.");
|
|
1363
|
+
}
|
|
1364
|
+
if (parsed.origin !== browserWindow.location.origin) {
|
|
1365
|
+
throw new Error("Identity connection sign-in redirectUri must be on the app origin.");
|
|
1366
|
+
}
|
|
1367
|
+
if (parsed.search || parsed.hash) {
|
|
1368
|
+
throw new Error("Identity connection sign-in redirectUri must have no query and no fragment.");
|
|
1369
|
+
}
|
|
1370
|
+
return redirectUri;
|
|
1371
|
+
}
|
|
1372
|
+
function readContext(value) {
|
|
1373
|
+
if (!value) return null;
|
|
1374
|
+
try {
|
|
1375
|
+
const context = JSON.parse(value);
|
|
1376
|
+
const complete = isNonEmptyString2(context.state) && isNonEmptyString2(context.codeVerifier) && isNonEmptyString2(context.slug) && isNonEmptyString2(context.redirectUri) && isNonEmptyString2(context.tokenEndpoint) && isNonEmptyString2(context.clientId);
|
|
1377
|
+
return complete ? context : null;
|
|
1378
|
+
} catch {
|
|
1379
|
+
return null;
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
var IdentityConnectionRedirectFlow = class {
|
|
1383
|
+
appId;
|
|
1384
|
+
client;
|
|
1385
|
+
storageKey;
|
|
1386
|
+
constructor(config) {
|
|
1387
|
+
this.appId = config.appId;
|
|
1388
|
+
this.client = config.client;
|
|
1389
|
+
this.storageKey = config.storageKey;
|
|
1390
|
+
}
|
|
1391
|
+
async start(slug, options = {}) {
|
|
1392
|
+
const browserWindow = requireBrowser();
|
|
1393
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1394
|
+
throw new Error("Identity connection sign-in names an invalid connection.");
|
|
1395
|
+
}
|
|
1396
|
+
const redirectUri = options.redirectUri === void 0 ? `${browserWindow.location.origin}${browserWindow.location.pathname}` : requireBareRedirectUri(options.redirectUri, browserWindow);
|
|
1397
|
+
const endpoints = readEndpoints(
|
|
1398
|
+
await this.client.get(`/api/v1/auth/identity-connections/${slug}`)
|
|
1399
|
+
);
|
|
1400
|
+
if (!endpoints) {
|
|
1401
|
+
throw new Error(`Identity connection ${slug} does not support redirect sign-in.`);
|
|
1402
|
+
}
|
|
1403
|
+
const random = Array.from(randomBytes(16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1404
|
+
const state = `${STATE_PREFIX2}${slug}.${random}`;
|
|
1405
|
+
const codeVerifier = base64Url(randomBytes(32));
|
|
1406
|
+
const context = {
|
|
1407
|
+
state,
|
|
1408
|
+
codeVerifier,
|
|
1409
|
+
slug,
|
|
1410
|
+
redirectUri,
|
|
1411
|
+
tokenEndpoint: endpoints.tokenEndpoint,
|
|
1412
|
+
clientId: endpoints.clientId,
|
|
1413
|
+
language: resolveLanguage(options.language, browserWindow)
|
|
1414
|
+
};
|
|
1415
|
+
try {
|
|
1416
|
+
browserWindow.sessionStorage.setItem(this.storageKey, JSON.stringify(context));
|
|
1417
|
+
} catch {
|
|
1418
|
+
throw new Error("Identity connection sign-in redirect requires sessionStorage.");
|
|
1419
|
+
}
|
|
1420
|
+
const query = Object.entries({
|
|
1421
|
+
response_type: "code",
|
|
1422
|
+
client_id: endpoints.clientId,
|
|
1423
|
+
redirect_uri: redirectUri,
|
|
1424
|
+
scope: SCOPE,
|
|
1425
|
+
state,
|
|
1426
|
+
code_challenge: await codeChallengeOf(codeVerifier),
|
|
1427
|
+
code_challenge_method: "S256"
|
|
1428
|
+
}).map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("&");
|
|
1429
|
+
const separator = endpoints.authorizationEndpoint.includes("?") ? "&" : "?";
|
|
1430
|
+
browserWindow.location.assign(`${endpoints.authorizationEndpoint}${separator}${query}`);
|
|
1431
|
+
return new Promise(() => void 0);
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Finishes the sign-in from the query the identity provider sent back, or
|
|
1435
|
+
* returns `null` when the query belongs to no identity connection redirect,
|
|
1436
|
+
* leaving the URL as it was. The query of this flow is removed before
|
|
1437
|
+
* anything can fail, and the stored context is spent on the first read, so a
|
|
1438
|
+
* failure is reported once and a code is never redeemed twice.
|
|
1439
|
+
*/
|
|
1440
|
+
async complete() {
|
|
1441
|
+
const browserWindow = requireBrowser();
|
|
1442
|
+
const params = new URLSearchParams(browserWindow.location.search);
|
|
1443
|
+
const state = params.get("state");
|
|
1444
|
+
if (!state?.startsWith(STATE_PREFIX2)) return null;
|
|
1445
|
+
const code = params.get("code");
|
|
1446
|
+
const error = params.get("error");
|
|
1447
|
+
const errorDescription = params.get("error_description");
|
|
1448
|
+
const context = this.takeContext(browserWindow);
|
|
1449
|
+
this.clearCallbackQuery(browserWindow, params);
|
|
1450
|
+
if (context === STORAGE_UNREADABLE) {
|
|
1451
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1452
|
+
"Identity connection sign-in context was not found in this tab: sessionStorage is unreadable."
|
|
1453
|
+
);
|
|
1454
|
+
}
|
|
1455
|
+
if (!context) {
|
|
1456
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1457
|
+
"Identity connection sign-in redirect does not match a pending request (possible CSRF)."
|
|
1458
|
+
);
|
|
1459
|
+
}
|
|
1460
|
+
if (context.state !== state) {
|
|
1461
|
+
throw new Error("Identity connection sign-in redirect does not match a pending request (possible CSRF).");
|
|
1462
|
+
}
|
|
1463
|
+
if (error !== null) {
|
|
1464
|
+
throw new Error(errorDescription?.trim() || error.trim() || "Identity connection sign-in failed.");
|
|
1465
|
+
}
|
|
1466
|
+
if (!code?.trim()) {
|
|
1467
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1468
|
+
}
|
|
1469
|
+
const assertion = await this.redeemAuthorizationCode(context, code);
|
|
1470
|
+
const login = await this.client.post(
|
|
1471
|
+
`/api/v1/auth/identity-connections/${context.slug}/login`,
|
|
1472
|
+
{ token: assertion, appId: this.appId, language: context.language }
|
|
1473
|
+
);
|
|
1474
|
+
if (!isNonEmptyString2(login?.exchangeCode)) {
|
|
1475
|
+
throw new Error("Identity connection sign-in did not return an exchange code.");
|
|
1476
|
+
}
|
|
1477
|
+
return exchangeIdentityConnectionCode(this.client, context.slug, this.appId, login.exchangeCode);
|
|
1478
|
+
}
|
|
1479
|
+
takeContext(browserWindow) {
|
|
1480
|
+
try {
|
|
1481
|
+
const context = readContext(browserWindow.sessionStorage.getItem(this.storageKey));
|
|
1482
|
+
browserWindow.sessionStorage.removeItem(this.storageKey);
|
|
1483
|
+
return context;
|
|
1484
|
+
} catch {
|
|
1485
|
+
return STORAGE_UNREADABLE;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
clearCallbackQuery(browserWindow, params) {
|
|
1489
|
+
CALLBACK_PARAMS.forEach((name) => params.delete(name));
|
|
1490
|
+
const query = params.toString();
|
|
1491
|
+
const search = query ? `?${query}` : "";
|
|
1492
|
+
browserWindow.history.replaceState(
|
|
1493
|
+
{},
|
|
1494
|
+
"",
|
|
1495
|
+
`${browserWindow.location.pathname}${search}${browserWindow.location.hash}`
|
|
1496
|
+
);
|
|
1497
|
+
}
|
|
1498
|
+
async redeemAuthorizationCode(context, code) {
|
|
1499
|
+
const controller = new AbortController();
|
|
1500
|
+
let timer;
|
|
1501
|
+
const timedOut = new Error("Identity connection sign-in timed out redeeming the authorization code at the identity provider.");
|
|
1502
|
+
const timeout = new Promise((_, reject) => {
|
|
1503
|
+
timer = setTimeout(() => {
|
|
1504
|
+
controller.abort();
|
|
1505
|
+
reject(timedOut);
|
|
1506
|
+
}, TOKEN_REQUEST_TIMEOUT_MS);
|
|
1507
|
+
});
|
|
1508
|
+
let response;
|
|
1509
|
+
let body;
|
|
1510
|
+
try {
|
|
1511
|
+
response = await Promise.race([
|
|
1512
|
+
fetch(context.tokenEndpoint, {
|
|
1513
|
+
method: "POST",
|
|
1514
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
1515
|
+
body: new URLSearchParams({
|
|
1516
|
+
grant_type: "authorization_code",
|
|
1517
|
+
client_id: context.clientId,
|
|
1518
|
+
code,
|
|
1519
|
+
redirect_uri: context.redirectUri,
|
|
1520
|
+
code_verifier: context.codeVerifier
|
|
1521
|
+
}).toString(),
|
|
1522
|
+
credentials: "omit",
|
|
1523
|
+
// The code and the verifier go to the token endpoint the connection named, never to a
|
|
1524
|
+
// host a redirect would pick.
|
|
1525
|
+
redirect: "error",
|
|
1526
|
+
signal: controller.signal
|
|
1527
|
+
}),
|
|
1528
|
+
timeout
|
|
1529
|
+
]);
|
|
1530
|
+
body = await Promise.race([response.json().catch(() => null), timeout]);
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
if (error === timedOut) throw error;
|
|
1533
|
+
throw new Error(
|
|
1534
|
+
"Identity connection sign-in could not reach the identity provider token endpoint; check that the app origin is in its Web Origins."
|
|
1535
|
+
);
|
|
1536
|
+
} finally {
|
|
1537
|
+
clearTimeout(timer);
|
|
1538
|
+
}
|
|
1539
|
+
if (!response.ok) {
|
|
1540
|
+
const reason = [body?.error, body?.error_description].filter(isNonEmptyString2).join(": ").split(code).join("[redacted]").split(context.codeVerifier).join("[redacted]");
|
|
1541
|
+
const detail = reason ? `, ${reason}` : "";
|
|
1542
|
+
throw new Error(
|
|
1543
|
+
`Identity connection sign-in could not redeem the authorization code (status ${response.status}${detail}).`
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
if (!isNonEmptyString2(body?.access_token)) {
|
|
1547
|
+
throw new Error("Identity connection sign-in did not receive an access token from the identity provider.");
|
|
1548
|
+
}
|
|
1549
|
+
return body.access_token;
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
|
|
1156
1553
|
// src/modules/password-form-flow.ts
|
|
1157
1554
|
var PASSWORD_PATH = "/api/v1/auth/password";
|
|
1158
1555
|
var LOGIN_PATH = `${PASSWORD_PATH}/login`;
|
|
@@ -1383,9 +1780,14 @@ var AuthModule = class {
|
|
|
1383
1780
|
microsoftAuth;
|
|
1384
1781
|
emailAuth;
|
|
1385
1782
|
passwordAuth;
|
|
1783
|
+
authPage;
|
|
1386
1784
|
emailCode;
|
|
1387
1785
|
passwordForm;
|
|
1786
|
+
identityConnection;
|
|
1787
|
+
identityConnectionRedirect;
|
|
1388
1788
|
brand = null;
|
|
1789
|
+
/** Session kept in sessionStorage: an identity connection opens one app per host account, and sharing localStorage would hand one account's session to another tab's reload. */
|
|
1790
|
+
sessionScoped = false;
|
|
1389
1791
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
1390
1792
|
this.appId = appId;
|
|
1391
1793
|
const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
|
|
@@ -1429,6 +1831,13 @@ var AuthModule = class {
|
|
|
1429
1831
|
client: this.publicClient,
|
|
1430
1832
|
provider: "password"
|
|
1431
1833
|
});
|
|
1834
|
+
this.authPage = new AuthPageFlow({
|
|
1835
|
+
appId,
|
|
1836
|
+
apiUrl,
|
|
1837
|
+
authPageUrl: options.authPageUrl,
|
|
1838
|
+
client: this.publicClient,
|
|
1839
|
+
provider: "all"
|
|
1840
|
+
});
|
|
1432
1841
|
this.emailCode = new EmailCodeFlow({
|
|
1433
1842
|
appId,
|
|
1434
1843
|
client: this.publicClient,
|
|
@@ -1439,6 +1848,12 @@ var AuthModule = class {
|
|
|
1439
1848
|
client: this.publicClient,
|
|
1440
1849
|
exchange: this.passwordAuth
|
|
1441
1850
|
});
|
|
1851
|
+
this.identityConnection = new IdentityConnectionFlow({ appId, client: this.publicClient });
|
|
1852
|
+
this.identityConnectionRedirect = new IdentityConnectionRedirectFlow({
|
|
1853
|
+
appId,
|
|
1854
|
+
client: this.publicClient,
|
|
1855
|
+
storageKey: `mitra_identity_connection_redirect_${appId}`
|
|
1856
|
+
});
|
|
1442
1857
|
this.loadFromStorage();
|
|
1443
1858
|
const readAccessToken = () => this.#accessToken;
|
|
1444
1859
|
sessionPorts.set(this, {
|
|
@@ -1448,6 +1863,7 @@ var AuthModule = class {
|
|
|
1448
1863
|
ensureFreshSession: (minValidityMs) => this.ensureFreshSession(minValidityMs),
|
|
1449
1864
|
handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
|
|
1450
1865
|
readSessionTokens: () => this.readSessionTokens(),
|
|
1866
|
+
isTabScoped: () => this.sessionScoped,
|
|
1451
1867
|
onSessionChange: (callback) => this.onSessionChange(callback),
|
|
1452
1868
|
adoptSession: (session) => this.adoptSession(session),
|
|
1453
1869
|
rotateSession: (session) => this.rotateSession(session)
|
|
@@ -1734,6 +2150,139 @@ var AuthModule = class {
|
|
|
1734
2150
|
const tokenResponse = await this.emailAuth.completeRedirect();
|
|
1735
2151
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1736
2152
|
}
|
|
2153
|
+
/**
|
|
2154
|
+
* Signs in on a single screen of the Mitra auth page that offers every method
|
|
2155
|
+
* the app has on: Google and Microsoft always, plus password and the email
|
|
2156
|
+
* code when the app has them enabled. The person picks one there, and
|
|
2157
|
+
* the page reports which; the code is redeemed at that method's IAM route,
|
|
2158
|
+
* exactly as the method's own sign-in would.
|
|
2159
|
+
*
|
|
2160
|
+
* Popup by default; redirect mode navigates away, and
|
|
2161
|
+
* {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
|
|
2162
|
+
* person may choose the email code, whose message carries a link that opens
|
|
2163
|
+
* a new tab, the pending request is kept in `localStorage` under
|
|
2164
|
+
* `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
|
|
2165
|
+
* auth page URL, never a token - as {@link signInWithEmail} does.
|
|
2166
|
+
*
|
|
2167
|
+
* Call it straight from the click handler, before any `await`, or the browser
|
|
2168
|
+
* blocks the popup.
|
|
2169
|
+
*
|
|
2170
|
+
* @param options - Popup or redirect mode.
|
|
2171
|
+
* @returns The authenticated and hydrated user in popup mode.
|
|
2172
|
+
* @throws {MitraApiError} When IAM rejects the exchange code.
|
|
2173
|
+
* @throws {Error} When the browser blocks or cancels the popup, the flow times
|
|
2174
|
+
* out, the response fails origin, source, state, or shape validation, or the
|
|
2175
|
+
* page does not say which method produced the code. A person who finishes
|
|
2176
|
+
* through the email link instead of the popup leaves this call to time out,
|
|
2177
|
+
* which the application should treat as a cancelled popup.
|
|
2178
|
+
*
|
|
2179
|
+
* @example
|
|
2180
|
+
* ```typescript
|
|
2181
|
+
* const user = await mitra.auth.signInWithAuthPage();
|
|
2182
|
+
* ```
|
|
2183
|
+
*/
|
|
2184
|
+
async signInWithAuthPage(options = {}) {
|
|
2185
|
+
return this.establishSession(await this.authPage.signIn(options));
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
|
|
2189
|
+
* `#stateMitra` and `#providerMitra`, during application startup: the redirect
|
|
2190
|
+
* back to the tab that started it, or the tab the email link opened. The state
|
|
2191
|
+
* must match the request pending in this browser, as in
|
|
2192
|
+
* {@link completeEmailSignInRedirect}.
|
|
2193
|
+
*
|
|
2194
|
+
* @returns The authenticated user, or `null` when the URL carries no result,
|
|
2195
|
+
* or carries one that belongs to another sign-in method's flow.
|
|
2196
|
+
* @throws When the fragment belongs to this flow but its state does not match,
|
|
2197
|
+
* the request expired, the page reports an error, or it does not say which
|
|
2198
|
+
* method produced the code. The fragment is removed first.
|
|
2199
|
+
*
|
|
2200
|
+
* @example
|
|
2201
|
+
* ```typescript
|
|
2202
|
+
* const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
|
|
2203
|
+
* ```
|
|
2204
|
+
*/
|
|
2205
|
+
async completeAuthPageSignInRedirect() {
|
|
2206
|
+
const tokenResponse = await this.authPage.completeRedirect();
|
|
2207
|
+
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Completes a sign-in made through an identity connection, such as Sankhya
|
|
2211
|
+
* Pass, from the single-use code the platform bridge page leaves in the
|
|
2212
|
+
* fragment (`#codeMitra`, `#stateMitra=connection.*`, `#connectionMitra`).
|
|
2213
|
+
*
|
|
2214
|
+
* `init()` already calls it, so an application only calls it itself when it
|
|
2215
|
+
* does not call `init()`. The session is kept in `sessionStorage`, not
|
|
2216
|
+
* `localStorage`, and so lives only as long as its tab.
|
|
2217
|
+
*
|
|
2218
|
+
* @returns The authenticated user, or `null` when the URL carries no
|
|
2219
|
+
* identity connection result. A fragment of another sign-in method is left
|
|
2220
|
+
* untouched.
|
|
2221
|
+
* @throws When the fragment belongs to an identity connection but cannot be
|
|
2222
|
+
* redeemed: outside an iframe, with an invalid connection, an error from the
|
|
2223
|
+
* bridge, no code, or a code IAM refuses. The fragment is removed first, and
|
|
2224
|
+
* the session this page held is dropped from memory, though not from storage.
|
|
2225
|
+
*/
|
|
2226
|
+
async completeIdentityConnectionSignInRedirect() {
|
|
2227
|
+
let tokenResponse;
|
|
2228
|
+
try {
|
|
2229
|
+
tokenResponse = await this.identityConnection.completeRedirect();
|
|
2230
|
+
} catch (error) {
|
|
2231
|
+
this.clearAuthState({ keepStorage: true });
|
|
2232
|
+
throw error;
|
|
2233
|
+
}
|
|
2234
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2235
|
+
}
|
|
2236
|
+
/**
|
|
2237
|
+
* Signs in through an identity connection, such as Sankhya Pass, outside a
|
|
2238
|
+
* host system iframe: the page is sent to the connection's identity provider
|
|
2239
|
+
* (Authorization Code with PKCE) and comes back to `redirectUri` with a code.
|
|
2240
|
+
* `init()` finishes it on the way back, or {@link completeIdentityConnectionRedirect}
|
|
2241
|
+
* when the app does not call `init()`. The returned promise never resolves,
|
|
2242
|
+
* because the page navigates away.
|
|
2243
|
+
*
|
|
2244
|
+
* @param slug - The connection, such as `sankhya-pass`.
|
|
2245
|
+
* @throws When the slug is invalid, the connection is unknown or does not
|
|
2246
|
+
* support redirect sign-in, or `sessionStorage` is unavailable.
|
|
2247
|
+
*
|
|
2248
|
+
* @example
|
|
2249
|
+
* ```typescript
|
|
2250
|
+
* await mitra.auth.signInWithIdentityConnection('sankhya-pass', { mode: 'redirect' });
|
|
2251
|
+
* ```
|
|
2252
|
+
*/
|
|
2253
|
+
async signInWithIdentityConnection(slug, options) {
|
|
2254
|
+
if (options?.mode !== "redirect") {
|
|
2255
|
+
throw new Error(`Unsupported identity connection sign-in mode: ${String(options?.mode)}`);
|
|
2256
|
+
}
|
|
2257
|
+
return this.identityConnectionRedirect.start(slug, options);
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* Completes a redirect started by {@link signInWithIdentityConnection} from
|
|
2261
|
+
* the query the identity provider sent back (`?code=...&state=connection.*`).
|
|
2262
|
+
*
|
|
2263
|
+
* `init()` already calls it. The session is kept in `sessionStorage`, like
|
|
2264
|
+
* the one from the host system iframe, and lives only as long as its tab.
|
|
2265
|
+
*
|
|
2266
|
+
* @returns The authenticated user, or `null` when the query carries no
|
|
2267
|
+
* identity connection redirect. Another query is left untouched.
|
|
2268
|
+
* @throws When the query belongs to this flow but no pending request in this
|
|
2269
|
+
* tab matches its state, the provider reports an error, or the provider or
|
|
2270
|
+
* IAM refuses the code. The query is removed first. When a sign-in was
|
|
2271
|
+
* pending in this tab, the session this page held is dropped from memory,
|
|
2272
|
+
* though not from storage; a callback with no pending sign-in leaves it.
|
|
2273
|
+
*/
|
|
2274
|
+
async completeIdentityConnectionRedirect() {
|
|
2275
|
+
let tokenResponse;
|
|
2276
|
+
try {
|
|
2277
|
+
tokenResponse = await this.identityConnectionRedirect.complete();
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
if (!(error instanceof UnsolicitedIdentityConnectionRedirectError)) {
|
|
2280
|
+
this.clearAuthState({ keepStorage: true });
|
|
2281
|
+
}
|
|
2282
|
+
throw error;
|
|
2283
|
+
}
|
|
2284
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2285
|
+
}
|
|
1737
2286
|
/**
|
|
1738
2287
|
* @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
|
|
1739
2288
|
* startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
|
|
@@ -2081,7 +2630,7 @@ var AuthModule = class {
|
|
|
2081
2630
|
return this.passwordForm.confirmReset(confirmation);
|
|
2082
2631
|
}
|
|
2083
2632
|
/**
|
|
2084
|
-
* Signs out the current user, clearing all auth state and
|
|
2633
|
+
* Signs out the current user, clearing all auth state and the stored session.
|
|
2085
2634
|
*
|
|
2086
2635
|
* In an app whose accounts are its own, the session also ends on the server:
|
|
2087
2636
|
* the refresh token is sent to IAM's logout, so it can no longer be renewed.
|
|
@@ -2214,6 +2763,9 @@ var AuthModule = class {
|
|
|
2214
2763
|
*
|
|
2215
2764
|
* Call `me()` afterwards to fetch the associated user data. {@link allTokens}
|
|
2216
2765
|
* goes back to `null`, because it belongs to the session being replaced.
|
|
2766
|
+
* The token starts a session of its own, so it is kept in `localStorage`
|
|
2767
|
+
* even when the one it replaces lived in its tab, and that tab copy is
|
|
2768
|
+
* removed in any case.
|
|
2217
2769
|
*
|
|
2218
2770
|
* @param token - JWT access token.
|
|
2219
2771
|
* @param saveToStorage - Whether to persist to localStorage (default: true).
|
|
@@ -2232,6 +2784,9 @@ var AuthModule = class {
|
|
|
2232
2784
|
this.invalidatePendingRefreshes();
|
|
2233
2785
|
this.#accessToken = token;
|
|
2234
2786
|
this.#allTokens = null;
|
|
2787
|
+
if (this.sessionScoped) this.#refreshToken = null;
|
|
2788
|
+
this.sessionScoped = false;
|
|
2789
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2235
2790
|
if (saveToStorage) {
|
|
2236
2791
|
this.saveToStorage();
|
|
2237
2792
|
}
|
|
@@ -2358,7 +2913,7 @@ var AuthModule = class {
|
|
|
2358
2913
|
* @internal
|
|
2359
2914
|
*/
|
|
2360
2915
|
adoptSession(session) {
|
|
2361
|
-
return this.applySession(session, false);
|
|
2916
|
+
return this.applySession(session, { keepAllTokens: false, replacesSession: true });
|
|
2362
2917
|
}
|
|
2363
2918
|
/**
|
|
2364
2919
|
* Stores tokens another issuer rotated for the session already in place, such
|
|
@@ -2368,19 +2923,23 @@ var AuthModule = class {
|
|
|
2368
2923
|
* @internal
|
|
2369
2924
|
*/
|
|
2370
2925
|
rotateSession(session) {
|
|
2371
|
-
return this.applySession(session,
|
|
2926
|
+
return this.applySession(session, {
|
|
2927
|
+
keepAllTokens: this.isSamePerson(session.token),
|
|
2928
|
+
replacesSession: false
|
|
2929
|
+
});
|
|
2372
2930
|
}
|
|
2373
2931
|
isSamePerson(token) {
|
|
2374
2932
|
const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
|
|
2375
2933
|
return current !== null && current === subjectOf(token);
|
|
2376
2934
|
}
|
|
2377
|
-
applySession(session, keepAllTokens) {
|
|
2935
|
+
applySession(session, { keepAllTokens, replacesSession }) {
|
|
2378
2936
|
if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
|
|
2379
2937
|
this.clearAuthState();
|
|
2380
2938
|
return false;
|
|
2381
2939
|
}
|
|
2382
2940
|
this.invalidatePendingRefreshes();
|
|
2383
2941
|
if (!keepAllTokens) this.#allTokens = null;
|
|
2942
|
+
if (replacesSession) this.sessionScoped = false;
|
|
2384
2943
|
this.#accessToken = session.token;
|
|
2385
2944
|
if (session.refreshToken !== void 0) {
|
|
2386
2945
|
this.#refreshToken = session.refreshToken;
|
|
@@ -2466,9 +3025,9 @@ var AuthModule = class {
|
|
|
2466
3025
|
this.notifySessionListeners();
|
|
2467
3026
|
return true;
|
|
2468
3027
|
}
|
|
2469
|
-
async establishSession(tokenResponse) {
|
|
3028
|
+
async establishSession(tokenResponse, sessionScoped = false) {
|
|
2470
3029
|
if (!this.belongsToConfiguredApp(tokenResponse.accessToken) || !this.belongsToConfiguredApp(tokenResponse.refreshToken)) {
|
|
2471
|
-
this.clearAuthState();
|
|
3030
|
+
this.clearAuthState({ keepStorage: sessionScoped });
|
|
2472
3031
|
throw coreErrors.invalidResponse("Authentication returned a token for a different app");
|
|
2473
3032
|
}
|
|
2474
3033
|
this.invalidatePendingRefreshes();
|
|
@@ -2476,6 +3035,7 @@ var AuthModule = class {
|
|
|
2476
3035
|
this.#accessToken = tokenResponse.accessToken;
|
|
2477
3036
|
this.#refreshToken = tokenResponse.refreshToken;
|
|
2478
3037
|
this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
|
|
3038
|
+
this.sessionScoped = sessionScoped;
|
|
2479
3039
|
try {
|
|
2480
3040
|
const user = await this.getCurrentUser();
|
|
2481
3041
|
if (generation !== this.sessionGeneration) {
|
|
@@ -2502,14 +3062,15 @@ var AuthModule = class {
|
|
|
2502
3062
|
const user = await this.currentUserApi.me();
|
|
2503
3063
|
return { ...user, tenantId: user.tenant.id };
|
|
2504
3064
|
}
|
|
2505
|
-
clearAuthState() {
|
|
3065
|
+
clearAuthState({ keepStorage = false } = {}) {
|
|
2506
3066
|
const hadAuthState = this._currentUser !== null || this.#accessToken !== null || this.#refreshToken !== null;
|
|
2507
3067
|
this.invalidatePendingRefreshes();
|
|
2508
3068
|
this._currentUser = null;
|
|
2509
3069
|
this.#accessToken = null;
|
|
2510
3070
|
this.#refreshToken = null;
|
|
2511
3071
|
this.#allTokens = null;
|
|
2512
|
-
this.removeFromStorage();
|
|
3072
|
+
if (!keepStorage) this.removeFromStorage();
|
|
3073
|
+
this.sessionScoped = false;
|
|
2513
3074
|
if (hadAuthState) {
|
|
2514
3075
|
this.notifySessionListeners();
|
|
2515
3076
|
this.notifyListeners();
|
|
@@ -2557,9 +3118,10 @@ var AuthModule = class {
|
|
|
2557
3118
|
});
|
|
2558
3119
|
}
|
|
2559
3120
|
saveToStorage() {
|
|
2560
|
-
|
|
3121
|
+
const target = this.sessionScoped ? sessionStorageOrNull() : localStorageOrNull();
|
|
3122
|
+
if (!target) return;
|
|
2561
3123
|
try {
|
|
2562
|
-
|
|
3124
|
+
target.setItem(
|
|
2563
3125
|
this.storageKey,
|
|
2564
3126
|
JSON.stringify({
|
|
2565
3127
|
user: this._currentUser,
|
|
@@ -2572,36 +3134,68 @@ var AuthModule = class {
|
|
|
2572
3134
|
})
|
|
2573
3135
|
);
|
|
2574
3136
|
} catch {
|
|
3137
|
+
return;
|
|
2575
3138
|
}
|
|
3139
|
+
if (!this.sessionScoped) removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2576
3140
|
}
|
|
2577
3141
|
loadFromStorage() {
|
|
2578
|
-
if (
|
|
3142
|
+
if (this.restoreFrom(sessionStorageOrNull(), true)) return;
|
|
3143
|
+
this.restoreFrom(localStorageOrNull(), false);
|
|
3144
|
+
}
|
|
3145
|
+
/** An unusable entry is removed from this storage only, so a broken tab session does not take the shared one with it. */
|
|
3146
|
+
restoreFrom(storage, sessionScoped) {
|
|
3147
|
+
const stored = readItem(storage, this.storageKey);
|
|
3148
|
+
if (!stored) return false;
|
|
2579
3149
|
try {
|
|
2580
|
-
const
|
|
2581
|
-
if (
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
this.clearAuthState();
|
|
2585
|
-
return;
|
|
2586
|
-
}
|
|
2587
|
-
this._currentUser = user;
|
|
2588
|
-
this.#accessToken = token;
|
|
2589
|
-
this.#refreshToken = refreshToken ?? null;
|
|
2590
|
-
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
2591
|
-
this.invalidatePendingRefreshes();
|
|
3150
|
+
const { user, token, refreshToken, allTokens } = JSON.parse(stored);
|
|
3151
|
+
if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
|
|
3152
|
+
removeItem(storage, this.storageKey);
|
|
3153
|
+
return false;
|
|
2592
3154
|
}
|
|
3155
|
+
this._currentUser = user;
|
|
3156
|
+
this.#accessToken = token;
|
|
3157
|
+
this.#refreshToken = refreshToken ?? null;
|
|
3158
|
+
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
3159
|
+
this.sessionScoped = sessionScoped;
|
|
3160
|
+
this.invalidatePendingRefreshes();
|
|
3161
|
+
return true;
|
|
2593
3162
|
} catch {
|
|
2594
|
-
this.
|
|
3163
|
+
removeItem(storage, this.storageKey);
|
|
3164
|
+
return false;
|
|
2595
3165
|
}
|
|
2596
3166
|
}
|
|
2597
3167
|
removeFromStorage() {
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
localStorage.removeItem(this.storageKey);
|
|
2601
|
-
} catch {
|
|
2602
|
-
}
|
|
3168
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
3169
|
+
if (!this.sessionScoped) removeItem(localStorageOrNull(), this.storageKey);
|
|
2603
3170
|
}
|
|
2604
3171
|
};
|
|
3172
|
+
function localStorageOrNull() {
|
|
3173
|
+
try {
|
|
3174
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
3175
|
+
} catch {
|
|
3176
|
+
return null;
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
function sessionStorageOrNull() {
|
|
3180
|
+
try {
|
|
3181
|
+
return typeof sessionStorage === "undefined" ? null : sessionStorage;
|
|
3182
|
+
} catch {
|
|
3183
|
+
return null;
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
function readItem(storage, key) {
|
|
3187
|
+
try {
|
|
3188
|
+
return storage?.getItem(key) ?? null;
|
|
3189
|
+
} catch {
|
|
3190
|
+
return null;
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
function removeItem(storage, key) {
|
|
3194
|
+
try {
|
|
3195
|
+
storage?.removeItem(key);
|
|
3196
|
+
} catch {
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
2605
3199
|
|
|
2606
3200
|
// src/modules/entities.ts
|
|
2607
3201
|
var import_sdk_core5 = require("@mitralab.io/sdk-core");
|
|
@@ -3366,6 +3960,7 @@ function createClient(config) {
|
|
|
3366
3960
|
);
|
|
3367
3961
|
const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
|
|
3368
3962
|
const aiProvidersModule = (0, import_sdk_core11.createAiProvidersModule)(copilotHttpClient, coreErrors);
|
|
3963
|
+
const filesModule = (0, import_sdk_core11.createFilesModule)(httpClient, {}, coreErrors);
|
|
3369
3964
|
const integrationHttpClient = new HttpClient({
|
|
3370
3965
|
baseUrl: integrationUrl,
|
|
3371
3966
|
getToken: () => authModule.accessToken,
|
|
@@ -3380,11 +3975,19 @@ function createClient(config) {
|
|
|
3380
3975
|
setActiveBridge(legacyBridge);
|
|
3381
3976
|
legacyBridge.connect();
|
|
3382
3977
|
let initialized = false;
|
|
3978
|
+
let initFlight = null;
|
|
3383
3979
|
let allowSignup = true;
|
|
3384
3980
|
let emailLoginEnabled = false;
|
|
3385
3981
|
let passwordLoginEnabled = false;
|
|
3386
|
-
|
|
3387
|
-
if (
|
|
3982
|
+
function init() {
|
|
3983
|
+
if (initFlight) return initFlight;
|
|
3984
|
+
if (initialized) return Promise.resolve();
|
|
3985
|
+
initFlight = runInit().finally(() => {
|
|
3986
|
+
initFlight = null;
|
|
3987
|
+
});
|
|
3988
|
+
return initFlight;
|
|
3989
|
+
}
|
|
3990
|
+
async function runInit() {
|
|
3388
3991
|
const publicClient = new HttpClient({
|
|
3389
3992
|
baseUrl: codeStudioUrl,
|
|
3390
3993
|
getToken: () => null
|
|
@@ -3404,6 +4007,10 @@ function createClient(config) {
|
|
|
3404
4007
|
emailLoginEnabled = appInfo.emailLoginEnabled;
|
|
3405
4008
|
passwordLoginEnabled = appInfo.passwordLoginEnabled;
|
|
3406
4009
|
initialized = true;
|
|
4010
|
+
if (globalThis.window !== void 0) {
|
|
4011
|
+
await authModule.completeIdentityConnectionSignInRedirect();
|
|
4012
|
+
await authModule.completeIdentityConnectionRedirect();
|
|
4013
|
+
}
|
|
3407
4014
|
}
|
|
3408
4015
|
return {
|
|
3409
4016
|
init,
|
|
@@ -3414,6 +4021,7 @@ function createClient(config) {
|
|
|
3414
4021
|
agentTasks: agentTasksModule,
|
|
3415
4022
|
agentCredentials: agentCredentialsModule,
|
|
3416
4023
|
aiProviders: aiProvidersModule,
|
|
4024
|
+
files: filesModule,
|
|
3417
4025
|
integration: integrationModule,
|
|
3418
4026
|
queries: queriesModule,
|
|
3419
4027
|
get allowSignup() {
|
|
@@ -3429,6 +4037,9 @@ function createClient(config) {
|
|
|
3429
4037
|
};
|
|
3430
4038
|
}
|
|
3431
4039
|
|
|
4040
|
+
// src/index.ts
|
|
4041
|
+
var import_sdk_core12 = require("@mitralab.io/sdk-core");
|
|
4042
|
+
|
|
3432
4043
|
// src/legacy/index.ts
|
|
3433
4044
|
var import_mitra_interactions_sdk2 = require("mitra-interactions-sdk");
|
|
3434
4045
|
var import_mitra_interactions_sdk3 = require("mitra-interactions-sdk");
|
|
@@ -3476,6 +4087,7 @@ var exchangeSsoCodeMitra = async (options) => {
|
|
|
3476
4087
|
};
|
|
3477
4088
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3478
4089
|
0 && (module.exports = {
|
|
4090
|
+
FileTransferError,
|
|
3479
4091
|
MitraApiError,
|
|
3480
4092
|
callIntegrationMitra,
|
|
3481
4093
|
configureSdkMitra,
|