@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.js
CHANGED
|
@@ -8,6 +8,7 @@ function stripTrailingSlashes(value) {
|
|
|
8
8
|
// src/client.ts
|
|
9
9
|
import {
|
|
10
10
|
createAiProvidersModule,
|
|
11
|
+
createFilesModule,
|
|
11
12
|
createPublicFunctionsModule,
|
|
12
13
|
encodePathSegment,
|
|
13
14
|
expectObject as expectObject4
|
|
@@ -316,6 +317,7 @@ var LegacySessionBridge = class {
|
|
|
316
317
|
this.unsubscribeFromAuth = null;
|
|
317
318
|
}
|
|
318
319
|
syncToLegacy(session) {
|
|
320
|
+
const refreshToken = this.auth.isTabScoped() ? null : session.refreshToken;
|
|
319
321
|
try {
|
|
320
322
|
const authPageUrl = resolveAuthPageUrl(
|
|
321
323
|
this.apiUrl,
|
|
@@ -328,11 +330,11 @@ var LegacySessionBridge = class {
|
|
|
328
330
|
projectId: this.appId,
|
|
329
331
|
onTokenRefresh: (session2) => this.rotate(session2),
|
|
330
332
|
...session.token ? { token: session.token } : {},
|
|
331
|
-
...
|
|
333
|
+
...refreshToken ? { refreshToken } : {}
|
|
332
334
|
});
|
|
333
335
|
const legacyConfig = getConfig();
|
|
334
336
|
if (!session.token) delete legacyConfig.token;
|
|
335
|
-
if (!
|
|
337
|
+
if (!refreshToken) delete legacyConfig.refreshToken;
|
|
336
338
|
} catch {
|
|
337
339
|
}
|
|
338
340
|
}
|
|
@@ -411,41 +413,59 @@ var RESULT_TYPE = "mitra-oauth-result";
|
|
|
411
413
|
var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
|
|
412
414
|
var SESSION_TYPE = "mitra-auth-session";
|
|
413
415
|
var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
|
|
416
|
+
var AUTH_PAGE_METHODS = /* @__PURE__ */ new Set([
|
|
417
|
+
"google",
|
|
418
|
+
"microsoft",
|
|
419
|
+
"email",
|
|
420
|
+
"password"
|
|
421
|
+
]);
|
|
422
|
+
function isAuthPageMethod(value) {
|
|
423
|
+
return typeof value === "string" && AUTH_PAGE_METHODS.has(value);
|
|
424
|
+
}
|
|
425
|
+
var EXCHANGE_ROUTES = {
|
|
426
|
+
google: { path: "/api/v1/auth/google", sendsRedirectUri: true },
|
|
427
|
+
microsoft: { path: "/api/v1/auth/microsoft", sendsRedirectUri: true },
|
|
428
|
+
email: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false },
|
|
429
|
+
password: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false }
|
|
430
|
+
};
|
|
414
431
|
var FIVE_MINUTES_MS = 5 * 60 * 1e3;
|
|
415
432
|
var TEN_MINUTES_MS = 10 * 60 * 1e3;
|
|
416
433
|
var PROVIDERS = {
|
|
417
434
|
google: {
|
|
418
435
|
label: "Google",
|
|
419
|
-
|
|
420
|
-
sendsRedirectUri: true,
|
|
436
|
+
exchange: EXCHANGE_ROUTES.google,
|
|
421
437
|
redirectStorage: "sessionStorage",
|
|
422
438
|
popupTimeoutMs: FIVE_MINUTES_MS
|
|
423
439
|
},
|
|
424
440
|
microsoft: {
|
|
425
441
|
label: "Microsoft",
|
|
426
|
-
|
|
427
|
-
sendsRedirectUri: true,
|
|
442
|
+
exchange: EXCHANGE_ROUTES.microsoft,
|
|
428
443
|
redirectStorage: "sessionStorage",
|
|
429
444
|
popupTimeoutMs: FIVE_MINUTES_MS
|
|
430
445
|
},
|
|
431
446
|
email: {
|
|
432
447
|
label: "Email",
|
|
433
|
-
|
|
434
|
-
sendsRedirectUri: false,
|
|
448
|
+
exchange: EXCHANGE_ROUTES.email,
|
|
435
449
|
redirectStorage: "localStorage",
|
|
436
450
|
pendingRequestTtlMs: TEN_MINUTES_MS,
|
|
437
451
|
popupTimeoutMs: TEN_MINUTES_MS
|
|
438
452
|
},
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
// mailbox, hence the email timeout; there is no link, so nothing pending is
|
|
442
|
-
// written for another tab.
|
|
453
|
+
// Signing up waits on a code read from a mailbox, hence the email timeout;
|
|
454
|
+
// there is no link, so nothing pending is written for another tab.
|
|
443
455
|
password: {
|
|
444
456
|
label: "Password",
|
|
445
|
-
|
|
446
|
-
sendsRedirectUri: false,
|
|
457
|
+
exchange: EXCHANGE_ROUTES.password,
|
|
447
458
|
redirectStorage: "sessionStorage",
|
|
448
459
|
popupTimeoutMs: TEN_MINUTES_MS
|
|
460
|
+
},
|
|
461
|
+
// The person may pick the email code on this screen, and its message carries
|
|
462
|
+
// a link that opens another tab, so this flow keeps the email lifetimes.
|
|
463
|
+
all: {
|
|
464
|
+
label: "Auth page",
|
|
465
|
+
exchange: "reportedMethod",
|
|
466
|
+
redirectStorage: "localStorage",
|
|
467
|
+
pendingRequestTtlMs: TEN_MINUTES_MS,
|
|
468
|
+
popupTimeoutMs: TEN_MINUTES_MS
|
|
449
469
|
}
|
|
450
470
|
};
|
|
451
471
|
var POPUP_WIDTH = 480;
|
|
@@ -577,6 +597,7 @@ var AuthPageFlow = class {
|
|
|
577
597
|
const code = params.get("codeMitra");
|
|
578
598
|
const state = params.get("stateMitra");
|
|
579
599
|
const error = params.get("errorMitra");
|
|
600
|
+
const reportedMethod = params.get("providerMitra");
|
|
580
601
|
if (code === null && state === null && error === null) return null;
|
|
581
602
|
const context = this.readRedirectContext(browserWindow);
|
|
582
603
|
const hasState = state !== null && state.trim() !== "";
|
|
@@ -618,7 +639,7 @@ var AuthPageFlow = class {
|
|
|
618
639
|
if (!code?.trim()) {
|
|
619
640
|
throw new Error(`${this.providerLabel} sign-in redirect is missing code.`);
|
|
620
641
|
}
|
|
621
|
-
return this.exchangeCode(code, context.redirectUri);
|
|
642
|
+
return this.exchangeCode(code, context.redirectUri, this.readReportedMethod(reportedMethod));
|
|
622
643
|
}
|
|
623
644
|
async startPopup(browserWindow, request) {
|
|
624
645
|
const state = this.generateState();
|
|
@@ -646,7 +667,10 @@ var AuthPageFlow = class {
|
|
|
646
667
|
request.sessionToken
|
|
647
668
|
);
|
|
648
669
|
if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
|
|
649
|
-
|
|
670
|
+
const reportedMethod = this.readReportedMethod(result.method);
|
|
671
|
+
if (result.code) {
|
|
672
|
+
return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl), reportedMethod);
|
|
673
|
+
}
|
|
650
674
|
return expectAuthTokenResponse(result.token);
|
|
651
675
|
}
|
|
652
676
|
startRedirect(browserWindow) {
|
|
@@ -717,14 +741,36 @@ var AuthPageFlow = class {
|
|
|
717
741
|
redeemExchangeCode(code) {
|
|
718
742
|
return this.exchangeCode(code, null);
|
|
719
743
|
}
|
|
720
|
-
async exchangeCode(code, redirectUri) {
|
|
721
|
-
const
|
|
744
|
+
async exchangeCode(code, redirectUri, reportedMethod) {
|
|
745
|
+
const route = this.exchangeRoute(reportedMethod);
|
|
746
|
+
const response = await this.client.post(route.path, {
|
|
722
747
|
appId: this.appId,
|
|
723
748
|
code,
|
|
724
|
-
...
|
|
749
|
+
...route.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
|
|
725
750
|
});
|
|
726
751
|
return expectAuthTokenResponse(response);
|
|
727
752
|
}
|
|
753
|
+
exchangeRoute(reportedMethod) {
|
|
754
|
+
if (this.profile.exchange !== "reportedMethod") return this.profile.exchange;
|
|
755
|
+
if (!reportedMethod) {
|
|
756
|
+
throw new Error("The all-methods sign-in cannot redeem a code without the method the auth page reported.");
|
|
757
|
+
}
|
|
758
|
+
return EXCHANGE_ROUTES[reportedMethod];
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* The method the auth page says produced the code. Only the flow that asked
|
|
762
|
+
* for the page with every method reads it: a single-method page sends no such
|
|
763
|
+
* field, and its own route is already known. Anything outside the known
|
|
764
|
+
* methods is refused rather than mapped to a route, since a code redeemed at
|
|
765
|
+
* the wrong route is spent for nothing.
|
|
766
|
+
*/
|
|
767
|
+
readReportedMethod(value) {
|
|
768
|
+
if (this.profile.exchange !== "reportedMethod") return void 0;
|
|
769
|
+
if (!isAuthPageMethod(value)) {
|
|
770
|
+
throw new Error(`${this.providerLabel} did not report which sign-in method produced the code.`);
|
|
771
|
+
}
|
|
772
|
+
return value;
|
|
773
|
+
}
|
|
728
774
|
buildStartUrl(browserWindow, authPageUrl, state, view) {
|
|
729
775
|
const startUrl = new URL(authPageUrl);
|
|
730
776
|
startUrl.searchParams.set("provider", this.provider);
|
|
@@ -765,7 +811,12 @@ var AuthPageFlow = class {
|
|
|
765
811
|
if (!Number.isFinite(context.createdAt)) return true;
|
|
766
812
|
return Date.now() - context.createdAt > ttlMs;
|
|
767
813
|
}
|
|
768
|
-
/**
|
|
814
|
+
/**
|
|
815
|
+
* A one-time state that names the flow that created it, so its fragment is
|
|
816
|
+
* recognizable. The auth page relies on the `all.` prefix too: the tab the
|
|
817
|
+
* email link opens has only the state to tell a chooser request apart, and
|
|
818
|
+
* answers it with `providerMitra=email`.
|
|
819
|
+
*/
|
|
769
820
|
generateState() {
|
|
770
821
|
if (!globalThis.crypto?.getRandomValues) {
|
|
771
822
|
throw new Error(`${this.providerLabel} sign-in requires crypto.getRandomValues.`);
|
|
@@ -904,9 +955,15 @@ function readPopupResult(data, expectedState, providerLabel) {
|
|
|
904
955
|
}
|
|
905
956
|
const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
|
|
906
957
|
if (!code && data.token === void 0) {
|
|
907
|
-
return { error: new Error(`${providerLabel}
|
|
958
|
+
return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
|
|
908
959
|
}
|
|
909
|
-
return {
|
|
960
|
+
return {
|
|
961
|
+
value: {
|
|
962
|
+
...code ? { code } : {},
|
|
963
|
+
...data.token !== void 0 ? { token: data.token } : {},
|
|
964
|
+
...data.provider !== void 0 ? { method: data.provider } : {}
|
|
965
|
+
}
|
|
966
|
+
};
|
|
910
967
|
}
|
|
911
968
|
|
|
912
969
|
// src/modules/email-code-flow.ts
|
|
@@ -1104,6 +1161,346 @@ var EmailCodeFlow = class {
|
|
|
1104
1161
|
}
|
|
1105
1162
|
};
|
|
1106
1163
|
|
|
1164
|
+
// src/modules/identity-connection-flow.ts
|
|
1165
|
+
var STATE_PREFIX = "connection.";
|
|
1166
|
+
var SLUG_PATTERN = /^[a-z0-9-]{1,64}$/;
|
|
1167
|
+
var WILDCARD_PREFIX = "https://*.";
|
|
1168
|
+
var ERROR_CODE_PATTERN = /^[a-z_]{1,64}$/;
|
|
1169
|
+
function isAllowedOrigin(origin, allowed) {
|
|
1170
|
+
const normalized = origin.toLowerCase();
|
|
1171
|
+
return allowed.some((candidate) => {
|
|
1172
|
+
if (!candidate.startsWith(WILDCARD_PREFIX)) return candidate === normalized;
|
|
1173
|
+
if (!normalized.startsWith("https://")) return false;
|
|
1174
|
+
const host = normalized.slice("https://".length);
|
|
1175
|
+
const domain = candidate.slice(WILDCARD_PREFIX.length);
|
|
1176
|
+
return !host.includes(":") && !host.includes("/") && host.endsWith(`.${domain}`) && host.length > domain.length + 1;
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
function readAllowedOrigins(response) {
|
|
1180
|
+
const origins = response?.allowedOrigins;
|
|
1181
|
+
return Array.isArray(origins) ? origins.filter((origin) => typeof origin === "string") : [];
|
|
1182
|
+
}
|
|
1183
|
+
async function exchangeIdentityConnectionCode(client, slug, appId, code) {
|
|
1184
|
+
const response = await client.post(
|
|
1185
|
+
`/api/v1/auth/identity-connections/${slug}/exchange`,
|
|
1186
|
+
{ appId, code }
|
|
1187
|
+
);
|
|
1188
|
+
return expectAuthTokenResponse(response);
|
|
1189
|
+
}
|
|
1190
|
+
var IdentityConnectionFlow = class {
|
|
1191
|
+
appId;
|
|
1192
|
+
client;
|
|
1193
|
+
constructor(config) {
|
|
1194
|
+
this.appId = config.appId;
|
|
1195
|
+
this.client = config.client;
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* Redeems the code the bridge put in the fragment, or returns `null` when the
|
|
1199
|
+
* fragment belongs to no identity connection. A fragment of another flow is
|
|
1200
|
+
* left exactly as it was found, so its own completion can still read it.
|
|
1201
|
+
*
|
|
1202
|
+
* A fragment of this flow is removed from the URL before anything can fail,
|
|
1203
|
+
* so a failure is reported once instead of on every reload, and the code is
|
|
1204
|
+
* never redeemed twice.
|
|
1205
|
+
*/
|
|
1206
|
+
async completeRedirect() {
|
|
1207
|
+
if (globalThis.window === void 0) {
|
|
1208
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1209
|
+
}
|
|
1210
|
+
const browserWindow = globalThis.window;
|
|
1211
|
+
const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
|
|
1212
|
+
const slug = params.get("connectionMitra");
|
|
1213
|
+
const state = params.get("stateMitra");
|
|
1214
|
+
if (slug === null || !state?.startsWith(STATE_PREFIX)) return null;
|
|
1215
|
+
const code = params.get("codeMitra");
|
|
1216
|
+
const error = params.get("errorMitra");
|
|
1217
|
+
browserWindow.history.replaceState(
|
|
1218
|
+
{},
|
|
1219
|
+
"",
|
|
1220
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}`
|
|
1221
|
+
);
|
|
1222
|
+
if (browserWindow.self === browserWindow.top) {
|
|
1223
|
+
throw new Error("Identity connection sign-in is only accepted inside the host system iframe.");
|
|
1224
|
+
}
|
|
1225
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1226
|
+
throw new Error("Identity connection sign-in redirect names an invalid connection.");
|
|
1227
|
+
}
|
|
1228
|
+
if (error !== null) {
|
|
1229
|
+
const reason = ERROR_CODE_PATTERN.test(error) ? `: ${error}` : "";
|
|
1230
|
+
throw new Error(`Identity connection sign-in failed${reason}.`);
|
|
1231
|
+
}
|
|
1232
|
+
if (!code?.trim()) {
|
|
1233
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1234
|
+
}
|
|
1235
|
+
await this.requireAllowedHost(browserWindow, slug);
|
|
1236
|
+
return exchangeIdentityConnectionCode(this.client, slug, this.appId, code);
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* A code is only redeemed when every page in the chain embedding this app is
|
|
1240
|
+
* a host system the connection allows. A page of someone else embedding the
|
|
1241
|
+
* app, directly or around an allowed host, with a code of another account
|
|
1242
|
+
* would otherwise sign this browser in as that account. The check mirrors
|
|
1243
|
+
* the one the bridge made on the message that carried the token.
|
|
1244
|
+
*
|
|
1245
|
+
* Only a browser that exposes `location.ancestorOrigins` can tell who embeds
|
|
1246
|
+
* the frame. Without it the host cannot be verified and the code is refused:
|
|
1247
|
+
* an unverifiable host is the exact case the check exists for.
|
|
1248
|
+
*/
|
|
1249
|
+
async requireAllowedHost(browserWindow, slug) {
|
|
1250
|
+
const hostOrigins = Array.from(browserWindow.location.ancestorOrigins ?? []);
|
|
1251
|
+
if (hostOrigins.length === 0) {
|
|
1252
|
+
throw new Error("Identity connection sign-in needs a browser that exposes the host system origin.");
|
|
1253
|
+
}
|
|
1254
|
+
const connection = await this.client.get(`/api/v1/auth/identity-connections/${slug}`);
|
|
1255
|
+
const allowedOrigins = readAllowedOrigins(connection);
|
|
1256
|
+
if (!hostOrigins.every((origin) => isAllowedOrigin(origin, allowedOrigins))) {
|
|
1257
|
+
throw new Error("Identity connection sign-in is not accepted under this host system.");
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
// src/modules/identity-connection-redirect-flow.ts
|
|
1263
|
+
var STATE_PREFIX2 = "connection.";
|
|
1264
|
+
var SCOPE = "openid email profile";
|
|
1265
|
+
var CALLBACK_PARAMS = ["code", "state", "error", "error_description", "error_uri", "session_state", "iss"];
|
|
1266
|
+
var TOKEN_REQUEST_TIMEOUT_MS = 15e3;
|
|
1267
|
+
var STORAGE_UNREADABLE = Symbol("storage-unreadable");
|
|
1268
|
+
var UnsolicitedIdentityConnectionRedirectError = class extends Error {
|
|
1269
|
+
};
|
|
1270
|
+
function requireBrowser() {
|
|
1271
|
+
if (globalThis.window === void 0) {
|
|
1272
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1273
|
+
}
|
|
1274
|
+
return globalThis.window;
|
|
1275
|
+
}
|
|
1276
|
+
function isNonEmptyString2(value) {
|
|
1277
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
1278
|
+
}
|
|
1279
|
+
function readEndpoints(connection) {
|
|
1280
|
+
const fields = connection ?? {};
|
|
1281
|
+
const { authorizationEndpoint, tokenEndpoint, clientId } = fields;
|
|
1282
|
+
if (!isNonEmptyString2(authorizationEndpoint) || !isNonEmptyString2(tokenEndpoint) || !isNonEmptyString2(clientId)) {
|
|
1283
|
+
return null;
|
|
1284
|
+
}
|
|
1285
|
+
return { authorizationEndpoint, tokenEndpoint, clientId };
|
|
1286
|
+
}
|
|
1287
|
+
function base64Url(bytes) {
|
|
1288
|
+
const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
|
|
1289
|
+
let encoded = btoa(binary).replaceAll("+", "-").replaceAll("/", "_");
|
|
1290
|
+
while (encoded.endsWith("=")) encoded = encoded.slice(0, -1);
|
|
1291
|
+
return encoded;
|
|
1292
|
+
}
|
|
1293
|
+
function randomBytes(length) {
|
|
1294
|
+
if (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {
|
|
1295
|
+
throw new Error("Identity connection sign-in requires the Web Crypto API.");
|
|
1296
|
+
}
|
|
1297
|
+
const bytes = new Uint8Array(length);
|
|
1298
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1299
|
+
return bytes;
|
|
1300
|
+
}
|
|
1301
|
+
async function codeChallengeOf(codeVerifier) {
|
|
1302
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
1303
|
+
return base64Url(new Uint8Array(digest));
|
|
1304
|
+
}
|
|
1305
|
+
function requireBareRedirectUri(redirectUri, browserWindow) {
|
|
1306
|
+
let parsed;
|
|
1307
|
+
try {
|
|
1308
|
+
parsed = new URL(redirectUri);
|
|
1309
|
+
} catch {
|
|
1310
|
+
throw new Error("Identity connection sign-in redirectUri must be an absolute URL.");
|
|
1311
|
+
}
|
|
1312
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
1313
|
+
throw new Error("Identity connection sign-in redirectUri must be an http or https URL.");
|
|
1314
|
+
}
|
|
1315
|
+
if (parsed.origin !== browserWindow.location.origin) {
|
|
1316
|
+
throw new Error("Identity connection sign-in redirectUri must be on the app origin.");
|
|
1317
|
+
}
|
|
1318
|
+
if (parsed.search || parsed.hash) {
|
|
1319
|
+
throw new Error("Identity connection sign-in redirectUri must have no query and no fragment.");
|
|
1320
|
+
}
|
|
1321
|
+
return redirectUri;
|
|
1322
|
+
}
|
|
1323
|
+
function readContext(value) {
|
|
1324
|
+
if (!value) return null;
|
|
1325
|
+
try {
|
|
1326
|
+
const context = JSON.parse(value);
|
|
1327
|
+
const complete = isNonEmptyString2(context.state) && isNonEmptyString2(context.codeVerifier) && isNonEmptyString2(context.slug) && isNonEmptyString2(context.redirectUri) && isNonEmptyString2(context.tokenEndpoint) && isNonEmptyString2(context.clientId);
|
|
1328
|
+
return complete ? context : null;
|
|
1329
|
+
} catch {
|
|
1330
|
+
return null;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
var IdentityConnectionRedirectFlow = class {
|
|
1334
|
+
appId;
|
|
1335
|
+
client;
|
|
1336
|
+
storageKey;
|
|
1337
|
+
constructor(config) {
|
|
1338
|
+
this.appId = config.appId;
|
|
1339
|
+
this.client = config.client;
|
|
1340
|
+
this.storageKey = config.storageKey;
|
|
1341
|
+
}
|
|
1342
|
+
async start(slug, options = {}) {
|
|
1343
|
+
const browserWindow = requireBrowser();
|
|
1344
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1345
|
+
throw new Error("Identity connection sign-in names an invalid connection.");
|
|
1346
|
+
}
|
|
1347
|
+
const redirectUri = options.redirectUri === void 0 ? `${browserWindow.location.origin}${browserWindow.location.pathname}` : requireBareRedirectUri(options.redirectUri, browserWindow);
|
|
1348
|
+
const endpoints = readEndpoints(
|
|
1349
|
+
await this.client.get(`/api/v1/auth/identity-connections/${slug}`)
|
|
1350
|
+
);
|
|
1351
|
+
if (!endpoints) {
|
|
1352
|
+
throw new Error(`Identity connection ${slug} does not support redirect sign-in.`);
|
|
1353
|
+
}
|
|
1354
|
+
const random = Array.from(randomBytes(16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1355
|
+
const state = `${STATE_PREFIX2}${slug}.${random}`;
|
|
1356
|
+
const codeVerifier = base64Url(randomBytes(32));
|
|
1357
|
+
const context = {
|
|
1358
|
+
state,
|
|
1359
|
+
codeVerifier,
|
|
1360
|
+
slug,
|
|
1361
|
+
redirectUri,
|
|
1362
|
+
tokenEndpoint: endpoints.tokenEndpoint,
|
|
1363
|
+
clientId: endpoints.clientId,
|
|
1364
|
+
language: resolveLanguage(options.language, browserWindow)
|
|
1365
|
+
};
|
|
1366
|
+
try {
|
|
1367
|
+
browserWindow.sessionStorage.setItem(this.storageKey, JSON.stringify(context));
|
|
1368
|
+
} catch {
|
|
1369
|
+
throw new Error("Identity connection sign-in redirect requires sessionStorage.");
|
|
1370
|
+
}
|
|
1371
|
+
const query = Object.entries({
|
|
1372
|
+
response_type: "code",
|
|
1373
|
+
client_id: endpoints.clientId,
|
|
1374
|
+
redirect_uri: redirectUri,
|
|
1375
|
+
scope: SCOPE,
|
|
1376
|
+
state,
|
|
1377
|
+
code_challenge: await codeChallengeOf(codeVerifier),
|
|
1378
|
+
code_challenge_method: "S256"
|
|
1379
|
+
}).map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("&");
|
|
1380
|
+
const separator = endpoints.authorizationEndpoint.includes("?") ? "&" : "?";
|
|
1381
|
+
browserWindow.location.assign(`${endpoints.authorizationEndpoint}${separator}${query}`);
|
|
1382
|
+
return new Promise(() => void 0);
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Finishes the sign-in from the query the identity provider sent back, or
|
|
1386
|
+
* returns `null` when the query belongs to no identity connection redirect,
|
|
1387
|
+
* leaving the URL as it was. The query of this flow is removed before
|
|
1388
|
+
* anything can fail, and the stored context is spent on the first read, so a
|
|
1389
|
+
* failure is reported once and a code is never redeemed twice.
|
|
1390
|
+
*/
|
|
1391
|
+
async complete() {
|
|
1392
|
+
const browserWindow = requireBrowser();
|
|
1393
|
+
const params = new URLSearchParams(browserWindow.location.search);
|
|
1394
|
+
const state = params.get("state");
|
|
1395
|
+
if (!state?.startsWith(STATE_PREFIX2)) return null;
|
|
1396
|
+
const code = params.get("code");
|
|
1397
|
+
const error = params.get("error");
|
|
1398
|
+
const errorDescription = params.get("error_description");
|
|
1399
|
+
const context = this.takeContext(browserWindow);
|
|
1400
|
+
this.clearCallbackQuery(browserWindow, params);
|
|
1401
|
+
if (context === STORAGE_UNREADABLE) {
|
|
1402
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1403
|
+
"Identity connection sign-in context was not found in this tab: sessionStorage is unreadable."
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
if (!context) {
|
|
1407
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1408
|
+
"Identity connection sign-in redirect does not match a pending request (possible CSRF)."
|
|
1409
|
+
);
|
|
1410
|
+
}
|
|
1411
|
+
if (context.state !== state) {
|
|
1412
|
+
throw new Error("Identity connection sign-in redirect does not match a pending request (possible CSRF).");
|
|
1413
|
+
}
|
|
1414
|
+
if (error !== null) {
|
|
1415
|
+
throw new Error(errorDescription?.trim() || error.trim() || "Identity connection sign-in failed.");
|
|
1416
|
+
}
|
|
1417
|
+
if (!code?.trim()) {
|
|
1418
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1419
|
+
}
|
|
1420
|
+
const assertion = await this.redeemAuthorizationCode(context, code);
|
|
1421
|
+
const login = await this.client.post(
|
|
1422
|
+
`/api/v1/auth/identity-connections/${context.slug}/login`,
|
|
1423
|
+
{ token: assertion, appId: this.appId, language: context.language }
|
|
1424
|
+
);
|
|
1425
|
+
if (!isNonEmptyString2(login?.exchangeCode)) {
|
|
1426
|
+
throw new Error("Identity connection sign-in did not return an exchange code.");
|
|
1427
|
+
}
|
|
1428
|
+
return exchangeIdentityConnectionCode(this.client, context.slug, this.appId, login.exchangeCode);
|
|
1429
|
+
}
|
|
1430
|
+
takeContext(browserWindow) {
|
|
1431
|
+
try {
|
|
1432
|
+
const context = readContext(browserWindow.sessionStorage.getItem(this.storageKey));
|
|
1433
|
+
browserWindow.sessionStorage.removeItem(this.storageKey);
|
|
1434
|
+
return context;
|
|
1435
|
+
} catch {
|
|
1436
|
+
return STORAGE_UNREADABLE;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
clearCallbackQuery(browserWindow, params) {
|
|
1440
|
+
CALLBACK_PARAMS.forEach((name) => params.delete(name));
|
|
1441
|
+
const query = params.toString();
|
|
1442
|
+
const search = query ? `?${query}` : "";
|
|
1443
|
+
browserWindow.history.replaceState(
|
|
1444
|
+
{},
|
|
1445
|
+
"",
|
|
1446
|
+
`${browserWindow.location.pathname}${search}${browserWindow.location.hash}`
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
async redeemAuthorizationCode(context, code) {
|
|
1450
|
+
const controller = new AbortController();
|
|
1451
|
+
let timer;
|
|
1452
|
+
const timedOut = new Error("Identity connection sign-in timed out redeeming the authorization code at the identity provider.");
|
|
1453
|
+
const timeout = new Promise((_, reject) => {
|
|
1454
|
+
timer = setTimeout(() => {
|
|
1455
|
+
controller.abort();
|
|
1456
|
+
reject(timedOut);
|
|
1457
|
+
}, TOKEN_REQUEST_TIMEOUT_MS);
|
|
1458
|
+
});
|
|
1459
|
+
let response;
|
|
1460
|
+
let body;
|
|
1461
|
+
try {
|
|
1462
|
+
response = await Promise.race([
|
|
1463
|
+
fetch(context.tokenEndpoint, {
|
|
1464
|
+
method: "POST",
|
|
1465
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
1466
|
+
body: new URLSearchParams({
|
|
1467
|
+
grant_type: "authorization_code",
|
|
1468
|
+
client_id: context.clientId,
|
|
1469
|
+
code,
|
|
1470
|
+
redirect_uri: context.redirectUri,
|
|
1471
|
+
code_verifier: context.codeVerifier
|
|
1472
|
+
}).toString(),
|
|
1473
|
+
credentials: "omit",
|
|
1474
|
+
// The code and the verifier go to the token endpoint the connection named, never to a
|
|
1475
|
+
// host a redirect would pick.
|
|
1476
|
+
redirect: "error",
|
|
1477
|
+
signal: controller.signal
|
|
1478
|
+
}),
|
|
1479
|
+
timeout
|
|
1480
|
+
]);
|
|
1481
|
+
body = await Promise.race([response.json().catch(() => null), timeout]);
|
|
1482
|
+
} catch (error) {
|
|
1483
|
+
if (error === timedOut) throw error;
|
|
1484
|
+
throw new Error(
|
|
1485
|
+
"Identity connection sign-in could not reach the identity provider token endpoint; check that the app origin is in its Web Origins."
|
|
1486
|
+
);
|
|
1487
|
+
} finally {
|
|
1488
|
+
clearTimeout(timer);
|
|
1489
|
+
}
|
|
1490
|
+
if (!response.ok) {
|
|
1491
|
+
const reason = [body?.error, body?.error_description].filter(isNonEmptyString2).join(": ").split(code).join("[redacted]").split(context.codeVerifier).join("[redacted]");
|
|
1492
|
+
const detail = reason ? `, ${reason}` : "";
|
|
1493
|
+
throw new Error(
|
|
1494
|
+
`Identity connection sign-in could not redeem the authorization code (status ${response.status}${detail}).`
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
if (!isNonEmptyString2(body?.access_token)) {
|
|
1498
|
+
throw new Error("Identity connection sign-in did not receive an access token from the identity provider.");
|
|
1499
|
+
}
|
|
1500
|
+
return body.access_token;
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
|
|
1107
1504
|
// src/modules/password-form-flow.ts
|
|
1108
1505
|
var PASSWORD_PATH = "/api/v1/auth/password";
|
|
1109
1506
|
var LOGIN_PATH = `${PASSWORD_PATH}/login`;
|
|
@@ -1334,9 +1731,14 @@ var AuthModule = class {
|
|
|
1334
1731
|
microsoftAuth;
|
|
1335
1732
|
emailAuth;
|
|
1336
1733
|
passwordAuth;
|
|
1734
|
+
authPage;
|
|
1337
1735
|
emailCode;
|
|
1338
1736
|
passwordForm;
|
|
1737
|
+
identityConnection;
|
|
1738
|
+
identityConnectionRedirect;
|
|
1339
1739
|
brand = null;
|
|
1740
|
+
/** 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. */
|
|
1741
|
+
sessionScoped = false;
|
|
1340
1742
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
1341
1743
|
this.appId = appId;
|
|
1342
1744
|
const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
|
|
@@ -1380,6 +1782,13 @@ var AuthModule = class {
|
|
|
1380
1782
|
client: this.publicClient,
|
|
1381
1783
|
provider: "password"
|
|
1382
1784
|
});
|
|
1785
|
+
this.authPage = new AuthPageFlow({
|
|
1786
|
+
appId,
|
|
1787
|
+
apiUrl,
|
|
1788
|
+
authPageUrl: options.authPageUrl,
|
|
1789
|
+
client: this.publicClient,
|
|
1790
|
+
provider: "all"
|
|
1791
|
+
});
|
|
1383
1792
|
this.emailCode = new EmailCodeFlow({
|
|
1384
1793
|
appId,
|
|
1385
1794
|
client: this.publicClient,
|
|
@@ -1390,6 +1799,12 @@ var AuthModule = class {
|
|
|
1390
1799
|
client: this.publicClient,
|
|
1391
1800
|
exchange: this.passwordAuth
|
|
1392
1801
|
});
|
|
1802
|
+
this.identityConnection = new IdentityConnectionFlow({ appId, client: this.publicClient });
|
|
1803
|
+
this.identityConnectionRedirect = new IdentityConnectionRedirectFlow({
|
|
1804
|
+
appId,
|
|
1805
|
+
client: this.publicClient,
|
|
1806
|
+
storageKey: `mitra_identity_connection_redirect_${appId}`
|
|
1807
|
+
});
|
|
1393
1808
|
this.loadFromStorage();
|
|
1394
1809
|
const readAccessToken = () => this.#accessToken;
|
|
1395
1810
|
sessionPorts.set(this, {
|
|
@@ -1399,6 +1814,7 @@ var AuthModule = class {
|
|
|
1399
1814
|
ensureFreshSession: (minValidityMs) => this.ensureFreshSession(minValidityMs),
|
|
1400
1815
|
handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
|
|
1401
1816
|
readSessionTokens: () => this.readSessionTokens(),
|
|
1817
|
+
isTabScoped: () => this.sessionScoped,
|
|
1402
1818
|
onSessionChange: (callback) => this.onSessionChange(callback),
|
|
1403
1819
|
adoptSession: (session) => this.adoptSession(session),
|
|
1404
1820
|
rotateSession: (session) => this.rotateSession(session)
|
|
@@ -1685,6 +2101,139 @@ var AuthModule = class {
|
|
|
1685
2101
|
const tokenResponse = await this.emailAuth.completeRedirect();
|
|
1686
2102
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1687
2103
|
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Signs in on a single screen of the Mitra auth page that offers every method
|
|
2106
|
+
* the app has on: Google and Microsoft always, plus password and the email
|
|
2107
|
+
* code when the app has them enabled. The person picks one there, and
|
|
2108
|
+
* the page reports which; the code is redeemed at that method's IAM route,
|
|
2109
|
+
* exactly as the method's own sign-in would.
|
|
2110
|
+
*
|
|
2111
|
+
* Popup by default; redirect mode navigates away, and
|
|
2112
|
+
* {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
|
|
2113
|
+
* person may choose the email code, whose message carries a link that opens
|
|
2114
|
+
* a new tab, the pending request is kept in `localStorage` under
|
|
2115
|
+
* `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
|
|
2116
|
+
* auth page URL, never a token - as {@link signInWithEmail} does.
|
|
2117
|
+
*
|
|
2118
|
+
* Call it straight from the click handler, before any `await`, or the browser
|
|
2119
|
+
* blocks the popup.
|
|
2120
|
+
*
|
|
2121
|
+
* @param options - Popup or redirect mode.
|
|
2122
|
+
* @returns The authenticated and hydrated user in popup mode.
|
|
2123
|
+
* @throws {MitraApiError} When IAM rejects the exchange code.
|
|
2124
|
+
* @throws {Error} When the browser blocks or cancels the popup, the flow times
|
|
2125
|
+
* out, the response fails origin, source, state, or shape validation, or the
|
|
2126
|
+
* page does not say which method produced the code. A person who finishes
|
|
2127
|
+
* through the email link instead of the popup leaves this call to time out,
|
|
2128
|
+
* which the application should treat as a cancelled popup.
|
|
2129
|
+
*
|
|
2130
|
+
* @example
|
|
2131
|
+
* ```typescript
|
|
2132
|
+
* const user = await mitra.auth.signInWithAuthPage();
|
|
2133
|
+
* ```
|
|
2134
|
+
*/
|
|
2135
|
+
async signInWithAuthPage(options = {}) {
|
|
2136
|
+
return this.establishSession(await this.authPage.signIn(options));
|
|
2137
|
+
}
|
|
2138
|
+
/**
|
|
2139
|
+
* Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
|
|
2140
|
+
* `#stateMitra` and `#providerMitra`, during application startup: the redirect
|
|
2141
|
+
* back to the tab that started it, or the tab the email link opened. The state
|
|
2142
|
+
* must match the request pending in this browser, as in
|
|
2143
|
+
* {@link completeEmailSignInRedirect}.
|
|
2144
|
+
*
|
|
2145
|
+
* @returns The authenticated user, or `null` when the URL carries no result,
|
|
2146
|
+
* or carries one that belongs to another sign-in method's flow.
|
|
2147
|
+
* @throws When the fragment belongs to this flow but its state does not match,
|
|
2148
|
+
* the request expired, the page reports an error, or it does not say which
|
|
2149
|
+
* method produced the code. The fragment is removed first.
|
|
2150
|
+
*
|
|
2151
|
+
* @example
|
|
2152
|
+
* ```typescript
|
|
2153
|
+
* const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
|
|
2154
|
+
* ```
|
|
2155
|
+
*/
|
|
2156
|
+
async completeAuthPageSignInRedirect() {
|
|
2157
|
+
const tokenResponse = await this.authPage.completeRedirect();
|
|
2158
|
+
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
2159
|
+
}
|
|
2160
|
+
/**
|
|
2161
|
+
* Completes a sign-in made through an identity connection, such as Sankhya
|
|
2162
|
+
* Pass, from the single-use code the platform bridge page leaves in the
|
|
2163
|
+
* fragment (`#codeMitra`, `#stateMitra=connection.*`, `#connectionMitra`).
|
|
2164
|
+
*
|
|
2165
|
+
* `init()` already calls it, so an application only calls it itself when it
|
|
2166
|
+
* does not call `init()`. The session is kept in `sessionStorage`, not
|
|
2167
|
+
* `localStorage`, and so lives only as long as its tab.
|
|
2168
|
+
*
|
|
2169
|
+
* @returns The authenticated user, or `null` when the URL carries no
|
|
2170
|
+
* identity connection result. A fragment of another sign-in method is left
|
|
2171
|
+
* untouched.
|
|
2172
|
+
* @throws When the fragment belongs to an identity connection but cannot be
|
|
2173
|
+
* redeemed: outside an iframe, with an invalid connection, an error from the
|
|
2174
|
+
* bridge, no code, or a code IAM refuses. The fragment is removed first, and
|
|
2175
|
+
* the session this page held is dropped from memory, though not from storage.
|
|
2176
|
+
*/
|
|
2177
|
+
async completeIdentityConnectionSignInRedirect() {
|
|
2178
|
+
let tokenResponse;
|
|
2179
|
+
try {
|
|
2180
|
+
tokenResponse = await this.identityConnection.completeRedirect();
|
|
2181
|
+
} catch (error) {
|
|
2182
|
+
this.clearAuthState({ keepStorage: true });
|
|
2183
|
+
throw error;
|
|
2184
|
+
}
|
|
2185
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Signs in through an identity connection, such as Sankhya Pass, outside a
|
|
2189
|
+
* host system iframe: the page is sent to the connection's identity provider
|
|
2190
|
+
* (Authorization Code with PKCE) and comes back to `redirectUri` with a code.
|
|
2191
|
+
* `init()` finishes it on the way back, or {@link completeIdentityConnectionRedirect}
|
|
2192
|
+
* when the app does not call `init()`. The returned promise never resolves,
|
|
2193
|
+
* because the page navigates away.
|
|
2194
|
+
*
|
|
2195
|
+
* @param slug - The connection, such as `sankhya-pass`.
|
|
2196
|
+
* @throws When the slug is invalid, the connection is unknown or does not
|
|
2197
|
+
* support redirect sign-in, or `sessionStorage` is unavailable.
|
|
2198
|
+
*
|
|
2199
|
+
* @example
|
|
2200
|
+
* ```typescript
|
|
2201
|
+
* await mitra.auth.signInWithIdentityConnection('sankhya-pass', { mode: 'redirect' });
|
|
2202
|
+
* ```
|
|
2203
|
+
*/
|
|
2204
|
+
async signInWithIdentityConnection(slug, options) {
|
|
2205
|
+
if (options?.mode !== "redirect") {
|
|
2206
|
+
throw new Error(`Unsupported identity connection sign-in mode: ${String(options?.mode)}`);
|
|
2207
|
+
}
|
|
2208
|
+
return this.identityConnectionRedirect.start(slug, options);
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* Completes a redirect started by {@link signInWithIdentityConnection} from
|
|
2212
|
+
* the query the identity provider sent back (`?code=...&state=connection.*`).
|
|
2213
|
+
*
|
|
2214
|
+
* `init()` already calls it. The session is kept in `sessionStorage`, like
|
|
2215
|
+
* the one from the host system iframe, and lives only as long as its tab.
|
|
2216
|
+
*
|
|
2217
|
+
* @returns The authenticated user, or `null` when the query carries no
|
|
2218
|
+
* identity connection redirect. Another query is left untouched.
|
|
2219
|
+
* @throws When the query belongs to this flow but no pending request in this
|
|
2220
|
+
* tab matches its state, the provider reports an error, or the provider or
|
|
2221
|
+
* IAM refuses the code. The query is removed first. When a sign-in was
|
|
2222
|
+
* pending in this tab, the session this page held is dropped from memory,
|
|
2223
|
+
* though not from storage; a callback with no pending sign-in leaves it.
|
|
2224
|
+
*/
|
|
2225
|
+
async completeIdentityConnectionRedirect() {
|
|
2226
|
+
let tokenResponse;
|
|
2227
|
+
try {
|
|
2228
|
+
tokenResponse = await this.identityConnectionRedirect.complete();
|
|
2229
|
+
} catch (error) {
|
|
2230
|
+
if (!(error instanceof UnsolicitedIdentityConnectionRedirectError)) {
|
|
2231
|
+
this.clearAuthState({ keepStorage: true });
|
|
2232
|
+
}
|
|
2233
|
+
throw error;
|
|
2234
|
+
}
|
|
2235
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2236
|
+
}
|
|
1688
2237
|
/**
|
|
1689
2238
|
* @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
|
|
1690
2239
|
* startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
|
|
@@ -2032,7 +2581,7 @@ var AuthModule = class {
|
|
|
2032
2581
|
return this.passwordForm.confirmReset(confirmation);
|
|
2033
2582
|
}
|
|
2034
2583
|
/**
|
|
2035
|
-
* Signs out the current user, clearing all auth state and
|
|
2584
|
+
* Signs out the current user, clearing all auth state and the stored session.
|
|
2036
2585
|
*
|
|
2037
2586
|
* In an app whose accounts are its own, the session also ends on the server:
|
|
2038
2587
|
* the refresh token is sent to IAM's logout, so it can no longer be renewed.
|
|
@@ -2165,6 +2714,9 @@ var AuthModule = class {
|
|
|
2165
2714
|
*
|
|
2166
2715
|
* Call `me()` afterwards to fetch the associated user data. {@link allTokens}
|
|
2167
2716
|
* goes back to `null`, because it belongs to the session being replaced.
|
|
2717
|
+
* The token starts a session of its own, so it is kept in `localStorage`
|
|
2718
|
+
* even when the one it replaces lived in its tab, and that tab copy is
|
|
2719
|
+
* removed in any case.
|
|
2168
2720
|
*
|
|
2169
2721
|
* @param token - JWT access token.
|
|
2170
2722
|
* @param saveToStorage - Whether to persist to localStorage (default: true).
|
|
@@ -2183,6 +2735,9 @@ var AuthModule = class {
|
|
|
2183
2735
|
this.invalidatePendingRefreshes();
|
|
2184
2736
|
this.#accessToken = token;
|
|
2185
2737
|
this.#allTokens = null;
|
|
2738
|
+
if (this.sessionScoped) this.#refreshToken = null;
|
|
2739
|
+
this.sessionScoped = false;
|
|
2740
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2186
2741
|
if (saveToStorage) {
|
|
2187
2742
|
this.saveToStorage();
|
|
2188
2743
|
}
|
|
@@ -2309,7 +2864,7 @@ var AuthModule = class {
|
|
|
2309
2864
|
* @internal
|
|
2310
2865
|
*/
|
|
2311
2866
|
adoptSession(session) {
|
|
2312
|
-
return this.applySession(session, false);
|
|
2867
|
+
return this.applySession(session, { keepAllTokens: false, replacesSession: true });
|
|
2313
2868
|
}
|
|
2314
2869
|
/**
|
|
2315
2870
|
* Stores tokens another issuer rotated for the session already in place, such
|
|
@@ -2319,19 +2874,23 @@ var AuthModule = class {
|
|
|
2319
2874
|
* @internal
|
|
2320
2875
|
*/
|
|
2321
2876
|
rotateSession(session) {
|
|
2322
|
-
return this.applySession(session,
|
|
2877
|
+
return this.applySession(session, {
|
|
2878
|
+
keepAllTokens: this.isSamePerson(session.token),
|
|
2879
|
+
replacesSession: false
|
|
2880
|
+
});
|
|
2323
2881
|
}
|
|
2324
2882
|
isSamePerson(token) {
|
|
2325
2883
|
const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
|
|
2326
2884
|
return current !== null && current === subjectOf(token);
|
|
2327
2885
|
}
|
|
2328
|
-
applySession(session, keepAllTokens) {
|
|
2886
|
+
applySession(session, { keepAllTokens, replacesSession }) {
|
|
2329
2887
|
if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
|
|
2330
2888
|
this.clearAuthState();
|
|
2331
2889
|
return false;
|
|
2332
2890
|
}
|
|
2333
2891
|
this.invalidatePendingRefreshes();
|
|
2334
2892
|
if (!keepAllTokens) this.#allTokens = null;
|
|
2893
|
+
if (replacesSession) this.sessionScoped = false;
|
|
2335
2894
|
this.#accessToken = session.token;
|
|
2336
2895
|
if (session.refreshToken !== void 0) {
|
|
2337
2896
|
this.#refreshToken = session.refreshToken;
|
|
@@ -2417,9 +2976,9 @@ var AuthModule = class {
|
|
|
2417
2976
|
this.notifySessionListeners();
|
|
2418
2977
|
return true;
|
|
2419
2978
|
}
|
|
2420
|
-
async establishSession(tokenResponse) {
|
|
2979
|
+
async establishSession(tokenResponse, sessionScoped = false) {
|
|
2421
2980
|
if (!this.belongsToConfiguredApp(tokenResponse.accessToken) || !this.belongsToConfiguredApp(tokenResponse.refreshToken)) {
|
|
2422
|
-
this.clearAuthState();
|
|
2981
|
+
this.clearAuthState({ keepStorage: sessionScoped });
|
|
2423
2982
|
throw coreErrors.invalidResponse("Authentication returned a token for a different app");
|
|
2424
2983
|
}
|
|
2425
2984
|
this.invalidatePendingRefreshes();
|
|
@@ -2427,6 +2986,7 @@ var AuthModule = class {
|
|
|
2427
2986
|
this.#accessToken = tokenResponse.accessToken;
|
|
2428
2987
|
this.#refreshToken = tokenResponse.refreshToken;
|
|
2429
2988
|
this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
|
|
2989
|
+
this.sessionScoped = sessionScoped;
|
|
2430
2990
|
try {
|
|
2431
2991
|
const user = await this.getCurrentUser();
|
|
2432
2992
|
if (generation !== this.sessionGeneration) {
|
|
@@ -2453,14 +3013,15 @@ var AuthModule = class {
|
|
|
2453
3013
|
const user = await this.currentUserApi.me();
|
|
2454
3014
|
return { ...user, tenantId: user.tenant.id };
|
|
2455
3015
|
}
|
|
2456
|
-
clearAuthState() {
|
|
3016
|
+
clearAuthState({ keepStorage = false } = {}) {
|
|
2457
3017
|
const hadAuthState = this._currentUser !== null || this.#accessToken !== null || this.#refreshToken !== null;
|
|
2458
3018
|
this.invalidatePendingRefreshes();
|
|
2459
3019
|
this._currentUser = null;
|
|
2460
3020
|
this.#accessToken = null;
|
|
2461
3021
|
this.#refreshToken = null;
|
|
2462
3022
|
this.#allTokens = null;
|
|
2463
|
-
this.removeFromStorage();
|
|
3023
|
+
if (!keepStorage) this.removeFromStorage();
|
|
3024
|
+
this.sessionScoped = false;
|
|
2464
3025
|
if (hadAuthState) {
|
|
2465
3026
|
this.notifySessionListeners();
|
|
2466
3027
|
this.notifyListeners();
|
|
@@ -2508,9 +3069,10 @@ var AuthModule = class {
|
|
|
2508
3069
|
});
|
|
2509
3070
|
}
|
|
2510
3071
|
saveToStorage() {
|
|
2511
|
-
|
|
3072
|
+
const target = this.sessionScoped ? sessionStorageOrNull() : localStorageOrNull();
|
|
3073
|
+
if (!target) return;
|
|
2512
3074
|
try {
|
|
2513
|
-
|
|
3075
|
+
target.setItem(
|
|
2514
3076
|
this.storageKey,
|
|
2515
3077
|
JSON.stringify({
|
|
2516
3078
|
user: this._currentUser,
|
|
@@ -2523,36 +3085,68 @@ var AuthModule = class {
|
|
|
2523
3085
|
})
|
|
2524
3086
|
);
|
|
2525
3087
|
} catch {
|
|
3088
|
+
return;
|
|
2526
3089
|
}
|
|
3090
|
+
if (!this.sessionScoped) removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2527
3091
|
}
|
|
2528
3092
|
loadFromStorage() {
|
|
2529
|
-
if (
|
|
3093
|
+
if (this.restoreFrom(sessionStorageOrNull(), true)) return;
|
|
3094
|
+
this.restoreFrom(localStorageOrNull(), false);
|
|
3095
|
+
}
|
|
3096
|
+
/** An unusable entry is removed from this storage only, so a broken tab session does not take the shared one with it. */
|
|
3097
|
+
restoreFrom(storage, sessionScoped) {
|
|
3098
|
+
const stored = readItem(storage, this.storageKey);
|
|
3099
|
+
if (!stored) return false;
|
|
2530
3100
|
try {
|
|
2531
|
-
const
|
|
2532
|
-
if (
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
this.clearAuthState();
|
|
2536
|
-
return;
|
|
2537
|
-
}
|
|
2538
|
-
this._currentUser = user;
|
|
2539
|
-
this.#accessToken = token;
|
|
2540
|
-
this.#refreshToken = refreshToken ?? null;
|
|
2541
|
-
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
2542
|
-
this.invalidatePendingRefreshes();
|
|
3101
|
+
const { user, token, refreshToken, allTokens } = JSON.parse(stored);
|
|
3102
|
+
if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
|
|
3103
|
+
removeItem(storage, this.storageKey);
|
|
3104
|
+
return false;
|
|
2543
3105
|
}
|
|
3106
|
+
this._currentUser = user;
|
|
3107
|
+
this.#accessToken = token;
|
|
3108
|
+
this.#refreshToken = refreshToken ?? null;
|
|
3109
|
+
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
3110
|
+
this.sessionScoped = sessionScoped;
|
|
3111
|
+
this.invalidatePendingRefreshes();
|
|
3112
|
+
return true;
|
|
2544
3113
|
} catch {
|
|
2545
|
-
this.
|
|
3114
|
+
removeItem(storage, this.storageKey);
|
|
3115
|
+
return false;
|
|
2546
3116
|
}
|
|
2547
3117
|
}
|
|
2548
3118
|
removeFromStorage() {
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
localStorage.removeItem(this.storageKey);
|
|
2552
|
-
} catch {
|
|
2553
|
-
}
|
|
3119
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
3120
|
+
if (!this.sessionScoped) removeItem(localStorageOrNull(), this.storageKey);
|
|
2554
3121
|
}
|
|
2555
3122
|
};
|
|
3123
|
+
function localStorageOrNull() {
|
|
3124
|
+
try {
|
|
3125
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
3126
|
+
} catch {
|
|
3127
|
+
return null;
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
function sessionStorageOrNull() {
|
|
3131
|
+
try {
|
|
3132
|
+
return typeof sessionStorage === "undefined" ? null : sessionStorage;
|
|
3133
|
+
} catch {
|
|
3134
|
+
return null;
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
function readItem(storage, key) {
|
|
3138
|
+
try {
|
|
3139
|
+
return storage?.getItem(key) ?? null;
|
|
3140
|
+
} catch {
|
|
3141
|
+
return null;
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
function removeItem(storage, key) {
|
|
3145
|
+
try {
|
|
3146
|
+
storage?.removeItem(key);
|
|
3147
|
+
} catch {
|
|
3148
|
+
}
|
|
3149
|
+
}
|
|
2556
3150
|
|
|
2557
3151
|
// src/modules/entities.ts
|
|
2558
3152
|
import {
|
|
@@ -3332,6 +3926,7 @@ function createClient(config) {
|
|
|
3332
3926
|
);
|
|
3333
3927
|
const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
|
|
3334
3928
|
const aiProvidersModule = createAiProvidersModule(copilotHttpClient, coreErrors);
|
|
3929
|
+
const filesModule = createFilesModule(httpClient, {}, coreErrors);
|
|
3335
3930
|
const integrationHttpClient = new HttpClient({
|
|
3336
3931
|
baseUrl: integrationUrl,
|
|
3337
3932
|
getToken: () => authModule.accessToken,
|
|
@@ -3346,11 +3941,19 @@ function createClient(config) {
|
|
|
3346
3941
|
setActiveBridge(legacyBridge);
|
|
3347
3942
|
legacyBridge.connect();
|
|
3348
3943
|
let initialized = false;
|
|
3944
|
+
let initFlight = null;
|
|
3349
3945
|
let allowSignup = true;
|
|
3350
3946
|
let emailLoginEnabled = false;
|
|
3351
3947
|
let passwordLoginEnabled = false;
|
|
3352
|
-
|
|
3353
|
-
if (
|
|
3948
|
+
function init() {
|
|
3949
|
+
if (initFlight) return initFlight;
|
|
3950
|
+
if (initialized) return Promise.resolve();
|
|
3951
|
+
initFlight = runInit().finally(() => {
|
|
3952
|
+
initFlight = null;
|
|
3953
|
+
});
|
|
3954
|
+
return initFlight;
|
|
3955
|
+
}
|
|
3956
|
+
async function runInit() {
|
|
3354
3957
|
const publicClient = new HttpClient({
|
|
3355
3958
|
baseUrl: codeStudioUrl,
|
|
3356
3959
|
getToken: () => null
|
|
@@ -3370,6 +3973,10 @@ function createClient(config) {
|
|
|
3370
3973
|
emailLoginEnabled = appInfo.emailLoginEnabled;
|
|
3371
3974
|
passwordLoginEnabled = appInfo.passwordLoginEnabled;
|
|
3372
3975
|
initialized = true;
|
|
3976
|
+
if (globalThis.window !== void 0) {
|
|
3977
|
+
await authModule.completeIdentityConnectionSignInRedirect();
|
|
3978
|
+
await authModule.completeIdentityConnectionRedirect();
|
|
3979
|
+
}
|
|
3373
3980
|
}
|
|
3374
3981
|
return {
|
|
3375
3982
|
init,
|
|
@@ -3380,6 +3987,7 @@ function createClient(config) {
|
|
|
3380
3987
|
agentTasks: agentTasksModule,
|
|
3381
3988
|
agentCredentials: agentCredentialsModule,
|
|
3382
3989
|
aiProviders: aiProvidersModule,
|
|
3990
|
+
files: filesModule,
|
|
3383
3991
|
integration: integrationModule,
|
|
3384
3992
|
queries: queriesModule,
|
|
3385
3993
|
get allowSignup() {
|
|
@@ -3395,6 +4003,9 @@ function createClient(config) {
|
|
|
3395
4003
|
};
|
|
3396
4004
|
}
|
|
3397
4005
|
|
|
4006
|
+
// src/index.ts
|
|
4007
|
+
import { FileTransferError } from "@mitralab.io/sdk-core";
|
|
4008
|
+
|
|
3398
4009
|
// src/legacy/index.ts
|
|
3399
4010
|
import {
|
|
3400
4011
|
exchangeSsoCodeMitra as legacyExchangeSsoCodeMitra,
|
|
@@ -3446,6 +4057,7 @@ var exchangeSsoCodeMitra = async (options) => {
|
|
|
3446
4057
|
return session;
|
|
3447
4058
|
};
|
|
3448
4059
|
export {
|
|
4060
|
+
FileTransferError,
|
|
3449
4061
|
MitraApiError,
|
|
3450
4062
|
callIntegrationMitra,
|
|
3451
4063
|
configureSdkMitra2 as configureSdkMitra,
|