@mitralab.io/platform-sdk 1.8.6 → 1.9.0-beta.1
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 +94 -0
- package/README.md +42 -4
- package/dist/index.cjs +521 -33
- package/dist/index.d.cts +89 -6
- package/dist/index.d.ts +89 -6
- package/dist/index.js +522 -33
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -365,6 +365,7 @@ var LegacySessionBridge = class {
|
|
|
365
365
|
this.unsubscribeFromAuth = null;
|
|
366
366
|
}
|
|
367
367
|
syncToLegacy(session) {
|
|
368
|
+
const refreshToken = this.auth.isTabScoped() ? null : session.refreshToken;
|
|
368
369
|
try {
|
|
369
370
|
const authPageUrl = resolveAuthPageUrl(
|
|
370
371
|
this.apiUrl,
|
|
@@ -377,11 +378,11 @@ var LegacySessionBridge = class {
|
|
|
377
378
|
projectId: this.appId,
|
|
378
379
|
onTokenRefresh: (session2) => this.rotate(session2),
|
|
379
380
|
...session.token ? { token: session.token } : {},
|
|
380
|
-
...
|
|
381
|
+
...refreshToken ? { refreshToken } : {}
|
|
381
382
|
});
|
|
382
383
|
const legacyConfig = (0, import_mitra_interactions_sdk.getConfig)();
|
|
383
384
|
if (!session.token) delete legacyConfig.token;
|
|
384
|
-
if (!
|
|
385
|
+
if (!refreshToken) delete legacyConfig.refreshToken;
|
|
385
386
|
} catch {
|
|
386
387
|
}
|
|
387
388
|
}
|
|
@@ -1153,6 +1154,346 @@ var EmailCodeFlow = class {
|
|
|
1153
1154
|
}
|
|
1154
1155
|
};
|
|
1155
1156
|
|
|
1157
|
+
// src/modules/identity-connection-flow.ts
|
|
1158
|
+
var STATE_PREFIX = "connection.";
|
|
1159
|
+
var SLUG_PATTERN = /^[a-z0-9-]{1,64}$/;
|
|
1160
|
+
var WILDCARD_PREFIX = "https://*.";
|
|
1161
|
+
var ERROR_CODE_PATTERN = /^[a-z_]{1,64}$/;
|
|
1162
|
+
function isAllowedOrigin(origin, allowed) {
|
|
1163
|
+
const normalized = origin.toLowerCase();
|
|
1164
|
+
return allowed.some((candidate) => {
|
|
1165
|
+
if (!candidate.startsWith(WILDCARD_PREFIX)) return candidate === normalized;
|
|
1166
|
+
if (!normalized.startsWith("https://")) return false;
|
|
1167
|
+
const host = normalized.slice("https://".length);
|
|
1168
|
+
const domain = candidate.slice(WILDCARD_PREFIX.length);
|
|
1169
|
+
return !host.includes(":") && !host.includes("/") && host.endsWith(`.${domain}`) && host.length > domain.length + 1;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
function readAllowedOrigins(response) {
|
|
1173
|
+
const origins = response?.allowedOrigins;
|
|
1174
|
+
return Array.isArray(origins) ? origins.filter((origin) => typeof origin === "string") : [];
|
|
1175
|
+
}
|
|
1176
|
+
async function exchangeIdentityConnectionCode(client, slug, appId, code) {
|
|
1177
|
+
const response = await client.post(
|
|
1178
|
+
`/api/v1/auth/identity-connections/${slug}/exchange`,
|
|
1179
|
+
{ appId, code }
|
|
1180
|
+
);
|
|
1181
|
+
return expectAuthTokenResponse(response);
|
|
1182
|
+
}
|
|
1183
|
+
var IdentityConnectionFlow = class {
|
|
1184
|
+
appId;
|
|
1185
|
+
client;
|
|
1186
|
+
constructor(config) {
|
|
1187
|
+
this.appId = config.appId;
|
|
1188
|
+
this.client = config.client;
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Redeems the code the bridge put in the fragment, or returns `null` when the
|
|
1192
|
+
* fragment belongs to no identity connection. A fragment of another flow is
|
|
1193
|
+
* left exactly as it was found, so its own completion can still read it.
|
|
1194
|
+
*
|
|
1195
|
+
* A fragment of this flow is removed from the URL before anything can fail,
|
|
1196
|
+
* so a failure is reported once instead of on every reload, and the code is
|
|
1197
|
+
* never redeemed twice.
|
|
1198
|
+
*/
|
|
1199
|
+
async completeRedirect() {
|
|
1200
|
+
if (globalThis.window === void 0) {
|
|
1201
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1202
|
+
}
|
|
1203
|
+
const browserWindow = globalThis.window;
|
|
1204
|
+
const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
|
|
1205
|
+
const slug = params.get("connectionMitra");
|
|
1206
|
+
const state = params.get("stateMitra");
|
|
1207
|
+
if (slug === null || !state?.startsWith(STATE_PREFIX)) return null;
|
|
1208
|
+
const code = params.get("codeMitra");
|
|
1209
|
+
const error = params.get("errorMitra");
|
|
1210
|
+
browserWindow.history.replaceState(
|
|
1211
|
+
{},
|
|
1212
|
+
"",
|
|
1213
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}`
|
|
1214
|
+
);
|
|
1215
|
+
if (browserWindow.self === browserWindow.top) {
|
|
1216
|
+
throw new Error("Identity connection sign-in is only accepted inside the host system iframe.");
|
|
1217
|
+
}
|
|
1218
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1219
|
+
throw new Error("Identity connection sign-in redirect names an invalid connection.");
|
|
1220
|
+
}
|
|
1221
|
+
if (error !== null) {
|
|
1222
|
+
const reason = ERROR_CODE_PATTERN.test(error) ? `: ${error}` : "";
|
|
1223
|
+
throw new Error(`Identity connection sign-in failed${reason}.`);
|
|
1224
|
+
}
|
|
1225
|
+
if (!code?.trim()) {
|
|
1226
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1227
|
+
}
|
|
1228
|
+
await this.requireAllowedHost(browserWindow, slug);
|
|
1229
|
+
return exchangeIdentityConnectionCode(this.client, slug, this.appId, code);
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* A code is only redeemed when every page in the chain embedding this app is
|
|
1233
|
+
* a host system the connection allows. A page of someone else embedding the
|
|
1234
|
+
* app, directly or around an allowed host, with a code of another account
|
|
1235
|
+
* would otherwise sign this browser in as that account. The check mirrors
|
|
1236
|
+
* the one the bridge made on the message that carried the token.
|
|
1237
|
+
*
|
|
1238
|
+
* Only a browser that exposes `location.ancestorOrigins` can tell who embeds
|
|
1239
|
+
* the frame. Without it the host cannot be verified and the code is refused:
|
|
1240
|
+
* an unverifiable host is the exact case the check exists for.
|
|
1241
|
+
*/
|
|
1242
|
+
async requireAllowedHost(browserWindow, slug) {
|
|
1243
|
+
const hostOrigins = Array.from(browserWindow.location.ancestorOrigins ?? []);
|
|
1244
|
+
if (hostOrigins.length === 0) {
|
|
1245
|
+
throw new Error("Identity connection sign-in needs a browser that exposes the host system origin.");
|
|
1246
|
+
}
|
|
1247
|
+
const connection = await this.client.get(`/api/v1/auth/identity-connections/${slug}`);
|
|
1248
|
+
const allowedOrigins = readAllowedOrigins(connection);
|
|
1249
|
+
if (!hostOrigins.every((origin) => isAllowedOrigin(origin, allowedOrigins))) {
|
|
1250
|
+
throw new Error("Identity connection sign-in is not accepted under this host system.");
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
|
|
1255
|
+
// src/modules/identity-connection-redirect-flow.ts
|
|
1256
|
+
var STATE_PREFIX2 = "connection.";
|
|
1257
|
+
var SCOPE = "openid email profile";
|
|
1258
|
+
var CALLBACK_PARAMS = ["code", "state", "error", "error_description", "error_uri", "session_state", "iss"];
|
|
1259
|
+
var TOKEN_REQUEST_TIMEOUT_MS = 15e3;
|
|
1260
|
+
var STORAGE_UNREADABLE = Symbol("storage-unreadable");
|
|
1261
|
+
var UnsolicitedIdentityConnectionRedirectError = class extends Error {
|
|
1262
|
+
};
|
|
1263
|
+
function requireBrowser() {
|
|
1264
|
+
if (globalThis.window === void 0) {
|
|
1265
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1266
|
+
}
|
|
1267
|
+
return globalThis.window;
|
|
1268
|
+
}
|
|
1269
|
+
function isNonEmptyString2(value) {
|
|
1270
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
1271
|
+
}
|
|
1272
|
+
function readEndpoints(connection) {
|
|
1273
|
+
const fields = connection ?? {};
|
|
1274
|
+
const { authorizationEndpoint, tokenEndpoint, clientId } = fields;
|
|
1275
|
+
if (!isNonEmptyString2(authorizationEndpoint) || !isNonEmptyString2(tokenEndpoint) || !isNonEmptyString2(clientId)) {
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
return { authorizationEndpoint, tokenEndpoint, clientId };
|
|
1279
|
+
}
|
|
1280
|
+
function base64Url(bytes) {
|
|
1281
|
+
const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
|
|
1282
|
+
let encoded = btoa(binary).replaceAll("+", "-").replaceAll("/", "_");
|
|
1283
|
+
while (encoded.endsWith("=")) encoded = encoded.slice(0, -1);
|
|
1284
|
+
return encoded;
|
|
1285
|
+
}
|
|
1286
|
+
function randomBytes(length) {
|
|
1287
|
+
if (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {
|
|
1288
|
+
throw new Error("Identity connection sign-in requires the Web Crypto API.");
|
|
1289
|
+
}
|
|
1290
|
+
const bytes = new Uint8Array(length);
|
|
1291
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1292
|
+
return bytes;
|
|
1293
|
+
}
|
|
1294
|
+
async function codeChallengeOf(codeVerifier) {
|
|
1295
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
1296
|
+
return base64Url(new Uint8Array(digest));
|
|
1297
|
+
}
|
|
1298
|
+
function requireBareRedirectUri(redirectUri, browserWindow) {
|
|
1299
|
+
let parsed;
|
|
1300
|
+
try {
|
|
1301
|
+
parsed = new URL(redirectUri);
|
|
1302
|
+
} catch {
|
|
1303
|
+
throw new Error("Identity connection sign-in redirectUri must be an absolute URL.");
|
|
1304
|
+
}
|
|
1305
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
1306
|
+
throw new Error("Identity connection sign-in redirectUri must be an http or https URL.");
|
|
1307
|
+
}
|
|
1308
|
+
if (parsed.origin !== browserWindow.location.origin) {
|
|
1309
|
+
throw new Error("Identity connection sign-in redirectUri must be on the app origin.");
|
|
1310
|
+
}
|
|
1311
|
+
if (parsed.search || parsed.hash) {
|
|
1312
|
+
throw new Error("Identity connection sign-in redirectUri must have no query and no fragment.");
|
|
1313
|
+
}
|
|
1314
|
+
return redirectUri;
|
|
1315
|
+
}
|
|
1316
|
+
function readContext(value) {
|
|
1317
|
+
if (!value) return null;
|
|
1318
|
+
try {
|
|
1319
|
+
const context = JSON.parse(value);
|
|
1320
|
+
const complete = isNonEmptyString2(context.state) && isNonEmptyString2(context.codeVerifier) && isNonEmptyString2(context.slug) && isNonEmptyString2(context.redirectUri) && isNonEmptyString2(context.tokenEndpoint) && isNonEmptyString2(context.clientId);
|
|
1321
|
+
return complete ? context : null;
|
|
1322
|
+
} catch {
|
|
1323
|
+
return null;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
var IdentityConnectionRedirectFlow = class {
|
|
1327
|
+
appId;
|
|
1328
|
+
client;
|
|
1329
|
+
storageKey;
|
|
1330
|
+
constructor(config) {
|
|
1331
|
+
this.appId = config.appId;
|
|
1332
|
+
this.client = config.client;
|
|
1333
|
+
this.storageKey = config.storageKey;
|
|
1334
|
+
}
|
|
1335
|
+
async start(slug, options = {}) {
|
|
1336
|
+
const browserWindow = requireBrowser();
|
|
1337
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1338
|
+
throw new Error("Identity connection sign-in names an invalid connection.");
|
|
1339
|
+
}
|
|
1340
|
+
const redirectUri = options.redirectUri === void 0 ? `${browserWindow.location.origin}${browserWindow.location.pathname}` : requireBareRedirectUri(options.redirectUri, browserWindow);
|
|
1341
|
+
const endpoints = readEndpoints(
|
|
1342
|
+
await this.client.get(`/api/v1/auth/identity-connections/${slug}`)
|
|
1343
|
+
);
|
|
1344
|
+
if (!endpoints) {
|
|
1345
|
+
throw new Error(`Identity connection ${slug} does not support redirect sign-in.`);
|
|
1346
|
+
}
|
|
1347
|
+
const random = Array.from(randomBytes(16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1348
|
+
const state = `${STATE_PREFIX2}${slug}.${random}`;
|
|
1349
|
+
const codeVerifier = base64Url(randomBytes(32));
|
|
1350
|
+
const context = {
|
|
1351
|
+
state,
|
|
1352
|
+
codeVerifier,
|
|
1353
|
+
slug,
|
|
1354
|
+
redirectUri,
|
|
1355
|
+
tokenEndpoint: endpoints.tokenEndpoint,
|
|
1356
|
+
clientId: endpoints.clientId,
|
|
1357
|
+
language: resolveLanguage(options.language, browserWindow)
|
|
1358
|
+
};
|
|
1359
|
+
try {
|
|
1360
|
+
browserWindow.sessionStorage.setItem(this.storageKey, JSON.stringify(context));
|
|
1361
|
+
} catch {
|
|
1362
|
+
throw new Error("Identity connection sign-in redirect requires sessionStorage.");
|
|
1363
|
+
}
|
|
1364
|
+
const query = Object.entries({
|
|
1365
|
+
response_type: "code",
|
|
1366
|
+
client_id: endpoints.clientId,
|
|
1367
|
+
redirect_uri: redirectUri,
|
|
1368
|
+
scope: SCOPE,
|
|
1369
|
+
state,
|
|
1370
|
+
code_challenge: await codeChallengeOf(codeVerifier),
|
|
1371
|
+
code_challenge_method: "S256"
|
|
1372
|
+
}).map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("&");
|
|
1373
|
+
const separator = endpoints.authorizationEndpoint.includes("?") ? "&" : "?";
|
|
1374
|
+
browserWindow.location.assign(`${endpoints.authorizationEndpoint}${separator}${query}`);
|
|
1375
|
+
return new Promise(() => void 0);
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Finishes the sign-in from the query the identity provider sent back, or
|
|
1379
|
+
* returns `null` when the query belongs to no identity connection redirect,
|
|
1380
|
+
* leaving the URL as it was. The query of this flow is removed before
|
|
1381
|
+
* anything can fail, and the stored context is spent on the first read, so a
|
|
1382
|
+
* failure is reported once and a code is never redeemed twice.
|
|
1383
|
+
*/
|
|
1384
|
+
async complete() {
|
|
1385
|
+
const browserWindow = requireBrowser();
|
|
1386
|
+
const params = new URLSearchParams(browserWindow.location.search);
|
|
1387
|
+
const state = params.get("state");
|
|
1388
|
+
if (!state?.startsWith(STATE_PREFIX2)) return null;
|
|
1389
|
+
const code = params.get("code");
|
|
1390
|
+
const error = params.get("error");
|
|
1391
|
+
const errorDescription = params.get("error_description");
|
|
1392
|
+
const context = this.takeContext(browserWindow);
|
|
1393
|
+
this.clearCallbackQuery(browserWindow, params);
|
|
1394
|
+
if (context === STORAGE_UNREADABLE) {
|
|
1395
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1396
|
+
"Identity connection sign-in context was not found in this tab: sessionStorage is unreadable."
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
if (!context) {
|
|
1400
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1401
|
+
"Identity connection sign-in redirect does not match a pending request (possible CSRF)."
|
|
1402
|
+
);
|
|
1403
|
+
}
|
|
1404
|
+
if (context.state !== state) {
|
|
1405
|
+
throw new Error("Identity connection sign-in redirect does not match a pending request (possible CSRF).");
|
|
1406
|
+
}
|
|
1407
|
+
if (error !== null) {
|
|
1408
|
+
throw new Error(errorDescription?.trim() || error.trim() || "Identity connection sign-in failed.");
|
|
1409
|
+
}
|
|
1410
|
+
if (!code?.trim()) {
|
|
1411
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1412
|
+
}
|
|
1413
|
+
const assertion = await this.redeemAuthorizationCode(context, code);
|
|
1414
|
+
const login = await this.client.post(
|
|
1415
|
+
`/api/v1/auth/identity-connections/${context.slug}/login`,
|
|
1416
|
+
{ token: assertion, appId: this.appId, language: context.language }
|
|
1417
|
+
);
|
|
1418
|
+
if (!isNonEmptyString2(login?.exchangeCode)) {
|
|
1419
|
+
throw new Error("Identity connection sign-in did not return an exchange code.");
|
|
1420
|
+
}
|
|
1421
|
+
return exchangeIdentityConnectionCode(this.client, context.slug, this.appId, login.exchangeCode);
|
|
1422
|
+
}
|
|
1423
|
+
takeContext(browserWindow) {
|
|
1424
|
+
try {
|
|
1425
|
+
const context = readContext(browserWindow.sessionStorage.getItem(this.storageKey));
|
|
1426
|
+
browserWindow.sessionStorage.removeItem(this.storageKey);
|
|
1427
|
+
return context;
|
|
1428
|
+
} catch {
|
|
1429
|
+
return STORAGE_UNREADABLE;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
clearCallbackQuery(browserWindow, params) {
|
|
1433
|
+
CALLBACK_PARAMS.forEach((name) => params.delete(name));
|
|
1434
|
+
const query = params.toString();
|
|
1435
|
+
const search = query ? `?${query}` : "";
|
|
1436
|
+
browserWindow.history.replaceState(
|
|
1437
|
+
{},
|
|
1438
|
+
"",
|
|
1439
|
+
`${browserWindow.location.pathname}${search}${browserWindow.location.hash}`
|
|
1440
|
+
);
|
|
1441
|
+
}
|
|
1442
|
+
async redeemAuthorizationCode(context, code) {
|
|
1443
|
+
const controller = new AbortController();
|
|
1444
|
+
let timer;
|
|
1445
|
+
const timedOut = new Error("Identity connection sign-in timed out redeeming the authorization code at the identity provider.");
|
|
1446
|
+
const timeout = new Promise((_, reject) => {
|
|
1447
|
+
timer = setTimeout(() => {
|
|
1448
|
+
controller.abort();
|
|
1449
|
+
reject(timedOut);
|
|
1450
|
+
}, TOKEN_REQUEST_TIMEOUT_MS);
|
|
1451
|
+
});
|
|
1452
|
+
let response;
|
|
1453
|
+
let body;
|
|
1454
|
+
try {
|
|
1455
|
+
response = await Promise.race([
|
|
1456
|
+
fetch(context.tokenEndpoint, {
|
|
1457
|
+
method: "POST",
|
|
1458
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
1459
|
+
body: new URLSearchParams({
|
|
1460
|
+
grant_type: "authorization_code",
|
|
1461
|
+
client_id: context.clientId,
|
|
1462
|
+
code,
|
|
1463
|
+
redirect_uri: context.redirectUri,
|
|
1464
|
+
code_verifier: context.codeVerifier
|
|
1465
|
+
}).toString(),
|
|
1466
|
+
credentials: "omit",
|
|
1467
|
+
// The code and the verifier go to the token endpoint the connection named, never to a
|
|
1468
|
+
// host a redirect would pick.
|
|
1469
|
+
redirect: "error",
|
|
1470
|
+
signal: controller.signal
|
|
1471
|
+
}),
|
|
1472
|
+
timeout
|
|
1473
|
+
]);
|
|
1474
|
+
body = await Promise.race([response.json().catch(() => null), timeout]);
|
|
1475
|
+
} catch (error) {
|
|
1476
|
+
if (error === timedOut) throw error;
|
|
1477
|
+
throw new Error(
|
|
1478
|
+
"Identity connection sign-in could not reach the identity provider token endpoint; check that the app origin is in its Web Origins."
|
|
1479
|
+
);
|
|
1480
|
+
} finally {
|
|
1481
|
+
clearTimeout(timer);
|
|
1482
|
+
}
|
|
1483
|
+
if (!response.ok) {
|
|
1484
|
+
const reason = [body?.error, body?.error_description].filter(isNonEmptyString2).join(": ").split(code).join("[redacted]").split(context.codeVerifier).join("[redacted]");
|
|
1485
|
+
const detail = reason ? `, ${reason}` : "";
|
|
1486
|
+
throw new Error(
|
|
1487
|
+
`Identity connection sign-in could not redeem the authorization code (status ${response.status}${detail}).`
|
|
1488
|
+
);
|
|
1489
|
+
}
|
|
1490
|
+
if (!isNonEmptyString2(body?.access_token)) {
|
|
1491
|
+
throw new Error("Identity connection sign-in did not receive an access token from the identity provider.");
|
|
1492
|
+
}
|
|
1493
|
+
return body.access_token;
|
|
1494
|
+
}
|
|
1495
|
+
};
|
|
1496
|
+
|
|
1156
1497
|
// src/modules/password-form-flow.ts
|
|
1157
1498
|
var PASSWORD_PATH = "/api/v1/auth/password";
|
|
1158
1499
|
var LOGIN_PATH = `${PASSWORD_PATH}/login`;
|
|
@@ -1385,7 +1726,11 @@ var AuthModule = class {
|
|
|
1385
1726
|
passwordAuth;
|
|
1386
1727
|
emailCode;
|
|
1387
1728
|
passwordForm;
|
|
1729
|
+
identityConnection;
|
|
1730
|
+
identityConnectionRedirect;
|
|
1388
1731
|
brand = null;
|
|
1732
|
+
/** 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. */
|
|
1733
|
+
sessionScoped = false;
|
|
1389
1734
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
1390
1735
|
this.appId = appId;
|
|
1391
1736
|
const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
|
|
@@ -1439,6 +1784,12 @@ var AuthModule = class {
|
|
|
1439
1784
|
client: this.publicClient,
|
|
1440
1785
|
exchange: this.passwordAuth
|
|
1441
1786
|
});
|
|
1787
|
+
this.identityConnection = new IdentityConnectionFlow({ appId, client: this.publicClient });
|
|
1788
|
+
this.identityConnectionRedirect = new IdentityConnectionRedirectFlow({
|
|
1789
|
+
appId,
|
|
1790
|
+
client: this.publicClient,
|
|
1791
|
+
storageKey: `mitra_identity_connection_redirect_${appId}`
|
|
1792
|
+
});
|
|
1442
1793
|
this.loadFromStorage();
|
|
1443
1794
|
const readAccessToken = () => this.#accessToken;
|
|
1444
1795
|
sessionPorts.set(this, {
|
|
@@ -1448,6 +1799,7 @@ var AuthModule = class {
|
|
|
1448
1799
|
ensureFreshSession: (minValidityMs) => this.ensureFreshSession(minValidityMs),
|
|
1449
1800
|
handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
|
|
1450
1801
|
readSessionTokens: () => this.readSessionTokens(),
|
|
1802
|
+
isTabScoped: () => this.sessionScoped,
|
|
1451
1803
|
onSessionChange: (callback) => this.onSessionChange(callback),
|
|
1452
1804
|
adoptSession: (session) => this.adoptSession(session),
|
|
1453
1805
|
rotateSession: (session) => this.rotateSession(session)
|
|
@@ -1734,6 +2086,83 @@ var AuthModule = class {
|
|
|
1734
2086
|
const tokenResponse = await this.emailAuth.completeRedirect();
|
|
1735
2087
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1736
2088
|
}
|
|
2089
|
+
/**
|
|
2090
|
+
* Completes a sign-in made through an identity connection, such as Sankhya
|
|
2091
|
+
* Pass, from the single-use code the platform bridge page leaves in the
|
|
2092
|
+
* fragment (`#codeMitra`, `#stateMitra=connection.*`, `#connectionMitra`).
|
|
2093
|
+
*
|
|
2094
|
+
* `init()` already calls it, so an application only calls it itself when it
|
|
2095
|
+
* does not call `init()`. The session is kept in `sessionStorage`, not
|
|
2096
|
+
* `localStorage`, and so lives only as long as its tab.
|
|
2097
|
+
*
|
|
2098
|
+
* @returns The authenticated user, or `null` when the URL carries no
|
|
2099
|
+
* identity connection result. A fragment of another sign-in method is left
|
|
2100
|
+
* untouched.
|
|
2101
|
+
* @throws When the fragment belongs to an identity connection but cannot be
|
|
2102
|
+
* redeemed: outside an iframe, with an invalid connection, an error from the
|
|
2103
|
+
* bridge, no code, or a code IAM refuses. The fragment is removed first, and
|
|
2104
|
+
* the session this page held is dropped from memory, though not from storage.
|
|
2105
|
+
*/
|
|
2106
|
+
async completeIdentityConnectionSignInRedirect() {
|
|
2107
|
+
let tokenResponse;
|
|
2108
|
+
try {
|
|
2109
|
+
tokenResponse = await this.identityConnection.completeRedirect();
|
|
2110
|
+
} catch (error) {
|
|
2111
|
+
this.clearAuthState({ keepStorage: true });
|
|
2112
|
+
throw error;
|
|
2113
|
+
}
|
|
2114
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* Signs in through an identity connection, such as Sankhya Pass, outside a
|
|
2118
|
+
* host system iframe: the page is sent to the connection's identity provider
|
|
2119
|
+
* (Authorization Code with PKCE) and comes back to `redirectUri` with a code.
|
|
2120
|
+
* `init()` finishes it on the way back, or {@link completeIdentityConnectionRedirect}
|
|
2121
|
+
* when the app does not call `init()`. The returned promise never resolves,
|
|
2122
|
+
* because the page navigates away.
|
|
2123
|
+
*
|
|
2124
|
+
* @param slug - The connection, such as `sankhya-pass`.
|
|
2125
|
+
* @throws When the slug is invalid, the connection is unknown or does not
|
|
2126
|
+
* support redirect sign-in, or `sessionStorage` is unavailable.
|
|
2127
|
+
*
|
|
2128
|
+
* @example
|
|
2129
|
+
* ```typescript
|
|
2130
|
+
* await mitra.auth.signInWithIdentityConnection('sankhya-pass', { mode: 'redirect' });
|
|
2131
|
+
* ```
|
|
2132
|
+
*/
|
|
2133
|
+
async signInWithIdentityConnection(slug, options) {
|
|
2134
|
+
if (options?.mode !== "redirect") {
|
|
2135
|
+
throw new Error(`Unsupported identity connection sign-in mode: ${String(options?.mode)}`);
|
|
2136
|
+
}
|
|
2137
|
+
return this.identityConnectionRedirect.start(slug, options);
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* Completes a redirect started by {@link signInWithIdentityConnection} from
|
|
2141
|
+
* the query the identity provider sent back (`?code=...&state=connection.*`).
|
|
2142
|
+
*
|
|
2143
|
+
* `init()` already calls it. The session is kept in `sessionStorage`, like
|
|
2144
|
+
* the one from the host system iframe, and lives only as long as its tab.
|
|
2145
|
+
*
|
|
2146
|
+
* @returns The authenticated user, or `null` when the query carries no
|
|
2147
|
+
* identity connection redirect. Another query is left untouched.
|
|
2148
|
+
* @throws When the query belongs to this flow but no pending request in this
|
|
2149
|
+
* tab matches its state, the provider reports an error, or the provider or
|
|
2150
|
+
* IAM refuses the code. The query is removed first. When a sign-in was
|
|
2151
|
+
* pending in this tab, the session this page held is dropped from memory,
|
|
2152
|
+
* though not from storage; a callback with no pending sign-in leaves it.
|
|
2153
|
+
*/
|
|
2154
|
+
async completeIdentityConnectionRedirect() {
|
|
2155
|
+
let tokenResponse;
|
|
2156
|
+
try {
|
|
2157
|
+
tokenResponse = await this.identityConnectionRedirect.complete();
|
|
2158
|
+
} catch (error) {
|
|
2159
|
+
if (!(error instanceof UnsolicitedIdentityConnectionRedirectError)) {
|
|
2160
|
+
this.clearAuthState({ keepStorage: true });
|
|
2161
|
+
}
|
|
2162
|
+
throw error;
|
|
2163
|
+
}
|
|
2164
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2165
|
+
}
|
|
1737
2166
|
/**
|
|
1738
2167
|
* @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
|
|
1739
2168
|
* startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
|
|
@@ -2081,7 +2510,7 @@ var AuthModule = class {
|
|
|
2081
2510
|
return this.passwordForm.confirmReset(confirmation);
|
|
2082
2511
|
}
|
|
2083
2512
|
/**
|
|
2084
|
-
* Signs out the current user, clearing all auth state and
|
|
2513
|
+
* Signs out the current user, clearing all auth state and the stored session.
|
|
2085
2514
|
*
|
|
2086
2515
|
* In an app whose accounts are its own, the session also ends on the server:
|
|
2087
2516
|
* the refresh token is sent to IAM's logout, so it can no longer be renewed.
|
|
@@ -2214,6 +2643,9 @@ var AuthModule = class {
|
|
|
2214
2643
|
*
|
|
2215
2644
|
* Call `me()` afterwards to fetch the associated user data. {@link allTokens}
|
|
2216
2645
|
* goes back to `null`, because it belongs to the session being replaced.
|
|
2646
|
+
* The token starts a session of its own, so it is kept in `localStorage`
|
|
2647
|
+
* even when the one it replaces lived in its tab, and that tab copy is
|
|
2648
|
+
* removed in any case.
|
|
2217
2649
|
*
|
|
2218
2650
|
* @param token - JWT access token.
|
|
2219
2651
|
* @param saveToStorage - Whether to persist to localStorage (default: true).
|
|
@@ -2232,6 +2664,9 @@ var AuthModule = class {
|
|
|
2232
2664
|
this.invalidatePendingRefreshes();
|
|
2233
2665
|
this.#accessToken = token;
|
|
2234
2666
|
this.#allTokens = null;
|
|
2667
|
+
if (this.sessionScoped) this.#refreshToken = null;
|
|
2668
|
+
this.sessionScoped = false;
|
|
2669
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2235
2670
|
if (saveToStorage) {
|
|
2236
2671
|
this.saveToStorage();
|
|
2237
2672
|
}
|
|
@@ -2358,7 +2793,7 @@ var AuthModule = class {
|
|
|
2358
2793
|
* @internal
|
|
2359
2794
|
*/
|
|
2360
2795
|
adoptSession(session) {
|
|
2361
|
-
return this.applySession(session, false);
|
|
2796
|
+
return this.applySession(session, { keepAllTokens: false, replacesSession: true });
|
|
2362
2797
|
}
|
|
2363
2798
|
/**
|
|
2364
2799
|
* Stores tokens another issuer rotated for the session already in place, such
|
|
@@ -2368,19 +2803,23 @@ var AuthModule = class {
|
|
|
2368
2803
|
* @internal
|
|
2369
2804
|
*/
|
|
2370
2805
|
rotateSession(session) {
|
|
2371
|
-
return this.applySession(session,
|
|
2806
|
+
return this.applySession(session, {
|
|
2807
|
+
keepAllTokens: this.isSamePerson(session.token),
|
|
2808
|
+
replacesSession: false
|
|
2809
|
+
});
|
|
2372
2810
|
}
|
|
2373
2811
|
isSamePerson(token) {
|
|
2374
2812
|
const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
|
|
2375
2813
|
return current !== null && current === subjectOf(token);
|
|
2376
2814
|
}
|
|
2377
|
-
applySession(session, keepAllTokens) {
|
|
2815
|
+
applySession(session, { keepAllTokens, replacesSession }) {
|
|
2378
2816
|
if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
|
|
2379
2817
|
this.clearAuthState();
|
|
2380
2818
|
return false;
|
|
2381
2819
|
}
|
|
2382
2820
|
this.invalidatePendingRefreshes();
|
|
2383
2821
|
if (!keepAllTokens) this.#allTokens = null;
|
|
2822
|
+
if (replacesSession) this.sessionScoped = false;
|
|
2384
2823
|
this.#accessToken = session.token;
|
|
2385
2824
|
if (session.refreshToken !== void 0) {
|
|
2386
2825
|
this.#refreshToken = session.refreshToken;
|
|
@@ -2466,9 +2905,9 @@ var AuthModule = class {
|
|
|
2466
2905
|
this.notifySessionListeners();
|
|
2467
2906
|
return true;
|
|
2468
2907
|
}
|
|
2469
|
-
async establishSession(tokenResponse) {
|
|
2908
|
+
async establishSession(tokenResponse, sessionScoped = false) {
|
|
2470
2909
|
if (!this.belongsToConfiguredApp(tokenResponse.accessToken) || !this.belongsToConfiguredApp(tokenResponse.refreshToken)) {
|
|
2471
|
-
this.clearAuthState();
|
|
2910
|
+
this.clearAuthState({ keepStorage: sessionScoped });
|
|
2472
2911
|
throw coreErrors.invalidResponse("Authentication returned a token for a different app");
|
|
2473
2912
|
}
|
|
2474
2913
|
this.invalidatePendingRefreshes();
|
|
@@ -2476,6 +2915,7 @@ var AuthModule = class {
|
|
|
2476
2915
|
this.#accessToken = tokenResponse.accessToken;
|
|
2477
2916
|
this.#refreshToken = tokenResponse.refreshToken;
|
|
2478
2917
|
this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
|
|
2918
|
+
this.sessionScoped = sessionScoped;
|
|
2479
2919
|
try {
|
|
2480
2920
|
const user = await this.getCurrentUser();
|
|
2481
2921
|
if (generation !== this.sessionGeneration) {
|
|
@@ -2502,14 +2942,15 @@ var AuthModule = class {
|
|
|
2502
2942
|
const user = await this.currentUserApi.me();
|
|
2503
2943
|
return { ...user, tenantId: user.tenant.id };
|
|
2504
2944
|
}
|
|
2505
|
-
clearAuthState() {
|
|
2945
|
+
clearAuthState({ keepStorage = false } = {}) {
|
|
2506
2946
|
const hadAuthState = this._currentUser !== null || this.#accessToken !== null || this.#refreshToken !== null;
|
|
2507
2947
|
this.invalidatePendingRefreshes();
|
|
2508
2948
|
this._currentUser = null;
|
|
2509
2949
|
this.#accessToken = null;
|
|
2510
2950
|
this.#refreshToken = null;
|
|
2511
2951
|
this.#allTokens = null;
|
|
2512
|
-
this.removeFromStorage();
|
|
2952
|
+
if (!keepStorage) this.removeFromStorage();
|
|
2953
|
+
this.sessionScoped = false;
|
|
2513
2954
|
if (hadAuthState) {
|
|
2514
2955
|
this.notifySessionListeners();
|
|
2515
2956
|
this.notifyListeners();
|
|
@@ -2557,9 +2998,10 @@ var AuthModule = class {
|
|
|
2557
2998
|
});
|
|
2558
2999
|
}
|
|
2559
3000
|
saveToStorage() {
|
|
2560
|
-
|
|
3001
|
+
const target = this.sessionScoped ? sessionStorageOrNull() : localStorageOrNull();
|
|
3002
|
+
if (!target) return;
|
|
2561
3003
|
try {
|
|
2562
|
-
|
|
3004
|
+
target.setItem(
|
|
2563
3005
|
this.storageKey,
|
|
2564
3006
|
JSON.stringify({
|
|
2565
3007
|
user: this._currentUser,
|
|
@@ -2572,36 +3014,68 @@ var AuthModule = class {
|
|
|
2572
3014
|
})
|
|
2573
3015
|
);
|
|
2574
3016
|
} catch {
|
|
3017
|
+
return;
|
|
2575
3018
|
}
|
|
3019
|
+
if (!this.sessionScoped) removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2576
3020
|
}
|
|
2577
3021
|
loadFromStorage() {
|
|
2578
|
-
if (
|
|
3022
|
+
if (this.restoreFrom(sessionStorageOrNull(), true)) return;
|
|
3023
|
+
this.restoreFrom(localStorageOrNull(), false);
|
|
3024
|
+
}
|
|
3025
|
+
/** An unusable entry is removed from this storage only, so a broken tab session does not take the shared one with it. */
|
|
3026
|
+
restoreFrom(storage, sessionScoped) {
|
|
3027
|
+
const stored = readItem(storage, this.storageKey);
|
|
3028
|
+
if (!stored) return false;
|
|
2579
3029
|
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();
|
|
3030
|
+
const { user, token, refreshToken, allTokens } = JSON.parse(stored);
|
|
3031
|
+
if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
|
|
3032
|
+
removeItem(storage, this.storageKey);
|
|
3033
|
+
return false;
|
|
2592
3034
|
}
|
|
3035
|
+
this._currentUser = user;
|
|
3036
|
+
this.#accessToken = token;
|
|
3037
|
+
this.#refreshToken = refreshToken ?? null;
|
|
3038
|
+
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
3039
|
+
this.sessionScoped = sessionScoped;
|
|
3040
|
+
this.invalidatePendingRefreshes();
|
|
3041
|
+
return true;
|
|
2593
3042
|
} catch {
|
|
2594
|
-
this.
|
|
3043
|
+
removeItem(storage, this.storageKey);
|
|
3044
|
+
return false;
|
|
2595
3045
|
}
|
|
2596
3046
|
}
|
|
2597
3047
|
removeFromStorage() {
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
localStorage.removeItem(this.storageKey);
|
|
2601
|
-
} catch {
|
|
2602
|
-
}
|
|
3048
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
3049
|
+
if (!this.sessionScoped) removeItem(localStorageOrNull(), this.storageKey);
|
|
2603
3050
|
}
|
|
2604
3051
|
};
|
|
3052
|
+
function localStorageOrNull() {
|
|
3053
|
+
try {
|
|
3054
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
3055
|
+
} catch {
|
|
3056
|
+
return null;
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
function sessionStorageOrNull() {
|
|
3060
|
+
try {
|
|
3061
|
+
return typeof sessionStorage === "undefined" ? null : sessionStorage;
|
|
3062
|
+
} catch {
|
|
3063
|
+
return null;
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
function readItem(storage, key) {
|
|
3067
|
+
try {
|
|
3068
|
+
return storage?.getItem(key) ?? null;
|
|
3069
|
+
} catch {
|
|
3070
|
+
return null;
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
function removeItem(storage, key) {
|
|
3074
|
+
try {
|
|
3075
|
+
storage?.removeItem(key);
|
|
3076
|
+
} catch {
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
2605
3079
|
|
|
2606
3080
|
// src/modules/entities.ts
|
|
2607
3081
|
var import_sdk_core5 = require("@mitralab.io/sdk-core");
|
|
@@ -3365,6 +3839,7 @@ function createClient(config) {
|
|
|
3365
3839
|
})
|
|
3366
3840
|
);
|
|
3367
3841
|
const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
|
|
3842
|
+
const aiProvidersModule = (0, import_sdk_core11.createAiProvidersModule)(copilotHttpClient, coreErrors);
|
|
3368
3843
|
const integrationHttpClient = new HttpClient({
|
|
3369
3844
|
baseUrl: integrationUrl,
|
|
3370
3845
|
getToken: () => authModule.accessToken,
|
|
@@ -3379,11 +3854,19 @@ function createClient(config) {
|
|
|
3379
3854
|
setActiveBridge(legacyBridge);
|
|
3380
3855
|
legacyBridge.connect();
|
|
3381
3856
|
let initialized = false;
|
|
3857
|
+
let initFlight = null;
|
|
3382
3858
|
let allowSignup = true;
|
|
3383
3859
|
let emailLoginEnabled = false;
|
|
3384
3860
|
let passwordLoginEnabled = false;
|
|
3385
|
-
|
|
3386
|
-
if (
|
|
3861
|
+
function init() {
|
|
3862
|
+
if (initFlight) return initFlight;
|
|
3863
|
+
if (initialized) return Promise.resolve();
|
|
3864
|
+
initFlight = runInit().finally(() => {
|
|
3865
|
+
initFlight = null;
|
|
3866
|
+
});
|
|
3867
|
+
return initFlight;
|
|
3868
|
+
}
|
|
3869
|
+
async function runInit() {
|
|
3387
3870
|
const publicClient = new HttpClient({
|
|
3388
3871
|
baseUrl: codeStudioUrl,
|
|
3389
3872
|
getToken: () => null
|
|
@@ -3403,6 +3886,10 @@ function createClient(config) {
|
|
|
3403
3886
|
emailLoginEnabled = appInfo.emailLoginEnabled;
|
|
3404
3887
|
passwordLoginEnabled = appInfo.passwordLoginEnabled;
|
|
3405
3888
|
initialized = true;
|
|
3889
|
+
if (globalThis.window !== void 0) {
|
|
3890
|
+
await authModule.completeIdentityConnectionSignInRedirect();
|
|
3891
|
+
await authModule.completeIdentityConnectionRedirect();
|
|
3892
|
+
}
|
|
3406
3893
|
}
|
|
3407
3894
|
return {
|
|
3408
3895
|
init,
|
|
@@ -3412,6 +3899,7 @@ function createClient(config) {
|
|
|
3412
3899
|
publicFunctions: publicFunctionsModule,
|
|
3413
3900
|
agentTasks: agentTasksModule,
|
|
3414
3901
|
agentCredentials: agentCredentialsModule,
|
|
3902
|
+
aiProviders: aiProvidersModule,
|
|
3415
3903
|
integration: integrationModule,
|
|
3416
3904
|
queries: queriesModule,
|
|
3417
3905
|
get allowSignup() {
|