@mitralab.io/platform-sdk 1.8.7 → 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 +82 -0
- package/README.md +36 -3
- package/dist/index.cjs +519 -33
- package/dist/index.d.cts +86 -4
- package/dist/index.d.ts +86 -4
- package/dist/index.js +519 -33
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -316,6 +316,7 @@ var LegacySessionBridge = class {
|
|
|
316
316
|
this.unsubscribeFromAuth = null;
|
|
317
317
|
}
|
|
318
318
|
syncToLegacy(session) {
|
|
319
|
+
const refreshToken = this.auth.isTabScoped() ? null : session.refreshToken;
|
|
319
320
|
try {
|
|
320
321
|
const authPageUrl = resolveAuthPageUrl(
|
|
321
322
|
this.apiUrl,
|
|
@@ -328,11 +329,11 @@ var LegacySessionBridge = class {
|
|
|
328
329
|
projectId: this.appId,
|
|
329
330
|
onTokenRefresh: (session2) => this.rotate(session2),
|
|
330
331
|
...session.token ? { token: session.token } : {},
|
|
331
|
-
...
|
|
332
|
+
...refreshToken ? { refreshToken } : {}
|
|
332
333
|
});
|
|
333
334
|
const legacyConfig = getConfig();
|
|
334
335
|
if (!session.token) delete legacyConfig.token;
|
|
335
|
-
if (!
|
|
336
|
+
if (!refreshToken) delete legacyConfig.refreshToken;
|
|
336
337
|
} catch {
|
|
337
338
|
}
|
|
338
339
|
}
|
|
@@ -1104,6 +1105,346 @@ var EmailCodeFlow = class {
|
|
|
1104
1105
|
}
|
|
1105
1106
|
};
|
|
1106
1107
|
|
|
1108
|
+
// src/modules/identity-connection-flow.ts
|
|
1109
|
+
var STATE_PREFIX = "connection.";
|
|
1110
|
+
var SLUG_PATTERN = /^[a-z0-9-]{1,64}$/;
|
|
1111
|
+
var WILDCARD_PREFIX = "https://*.";
|
|
1112
|
+
var ERROR_CODE_PATTERN = /^[a-z_]{1,64}$/;
|
|
1113
|
+
function isAllowedOrigin(origin, allowed) {
|
|
1114
|
+
const normalized = origin.toLowerCase();
|
|
1115
|
+
return allowed.some((candidate) => {
|
|
1116
|
+
if (!candidate.startsWith(WILDCARD_PREFIX)) return candidate === normalized;
|
|
1117
|
+
if (!normalized.startsWith("https://")) return false;
|
|
1118
|
+
const host = normalized.slice("https://".length);
|
|
1119
|
+
const domain = candidate.slice(WILDCARD_PREFIX.length);
|
|
1120
|
+
return !host.includes(":") && !host.includes("/") && host.endsWith(`.${domain}`) && host.length > domain.length + 1;
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
function readAllowedOrigins(response) {
|
|
1124
|
+
const origins = response?.allowedOrigins;
|
|
1125
|
+
return Array.isArray(origins) ? origins.filter((origin) => typeof origin === "string") : [];
|
|
1126
|
+
}
|
|
1127
|
+
async function exchangeIdentityConnectionCode(client, slug, appId, code) {
|
|
1128
|
+
const response = await client.post(
|
|
1129
|
+
`/api/v1/auth/identity-connections/${slug}/exchange`,
|
|
1130
|
+
{ appId, code }
|
|
1131
|
+
);
|
|
1132
|
+
return expectAuthTokenResponse(response);
|
|
1133
|
+
}
|
|
1134
|
+
var IdentityConnectionFlow = class {
|
|
1135
|
+
appId;
|
|
1136
|
+
client;
|
|
1137
|
+
constructor(config) {
|
|
1138
|
+
this.appId = config.appId;
|
|
1139
|
+
this.client = config.client;
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Redeems the code the bridge put in the fragment, or returns `null` when the
|
|
1143
|
+
* fragment belongs to no identity connection. A fragment of another flow is
|
|
1144
|
+
* left exactly as it was found, so its own completion can still read it.
|
|
1145
|
+
*
|
|
1146
|
+
* A fragment of this flow is removed from the URL before anything can fail,
|
|
1147
|
+
* so a failure is reported once instead of on every reload, and the code is
|
|
1148
|
+
* never redeemed twice.
|
|
1149
|
+
*/
|
|
1150
|
+
async completeRedirect() {
|
|
1151
|
+
if (globalThis.window === void 0) {
|
|
1152
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1153
|
+
}
|
|
1154
|
+
const browserWindow = globalThis.window;
|
|
1155
|
+
const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
|
|
1156
|
+
const slug = params.get("connectionMitra");
|
|
1157
|
+
const state = params.get("stateMitra");
|
|
1158
|
+
if (slug === null || !state?.startsWith(STATE_PREFIX)) return null;
|
|
1159
|
+
const code = params.get("codeMitra");
|
|
1160
|
+
const error = params.get("errorMitra");
|
|
1161
|
+
browserWindow.history.replaceState(
|
|
1162
|
+
{},
|
|
1163
|
+
"",
|
|
1164
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}`
|
|
1165
|
+
);
|
|
1166
|
+
if (browserWindow.self === browserWindow.top) {
|
|
1167
|
+
throw new Error("Identity connection sign-in is only accepted inside the host system iframe.");
|
|
1168
|
+
}
|
|
1169
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1170
|
+
throw new Error("Identity connection sign-in redirect names an invalid connection.");
|
|
1171
|
+
}
|
|
1172
|
+
if (error !== null) {
|
|
1173
|
+
const reason = ERROR_CODE_PATTERN.test(error) ? `: ${error}` : "";
|
|
1174
|
+
throw new Error(`Identity connection sign-in failed${reason}.`);
|
|
1175
|
+
}
|
|
1176
|
+
if (!code?.trim()) {
|
|
1177
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1178
|
+
}
|
|
1179
|
+
await this.requireAllowedHost(browserWindow, slug);
|
|
1180
|
+
return exchangeIdentityConnectionCode(this.client, slug, this.appId, code);
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* A code is only redeemed when every page in the chain embedding this app is
|
|
1184
|
+
* a host system the connection allows. A page of someone else embedding the
|
|
1185
|
+
* app, directly or around an allowed host, with a code of another account
|
|
1186
|
+
* would otherwise sign this browser in as that account. The check mirrors
|
|
1187
|
+
* the one the bridge made on the message that carried the token.
|
|
1188
|
+
*
|
|
1189
|
+
* Only a browser that exposes `location.ancestorOrigins` can tell who embeds
|
|
1190
|
+
* the frame. Without it the host cannot be verified and the code is refused:
|
|
1191
|
+
* an unverifiable host is the exact case the check exists for.
|
|
1192
|
+
*/
|
|
1193
|
+
async requireAllowedHost(browserWindow, slug) {
|
|
1194
|
+
const hostOrigins = Array.from(browserWindow.location.ancestorOrigins ?? []);
|
|
1195
|
+
if (hostOrigins.length === 0) {
|
|
1196
|
+
throw new Error("Identity connection sign-in needs a browser that exposes the host system origin.");
|
|
1197
|
+
}
|
|
1198
|
+
const connection = await this.client.get(`/api/v1/auth/identity-connections/${slug}`);
|
|
1199
|
+
const allowedOrigins = readAllowedOrigins(connection);
|
|
1200
|
+
if (!hostOrigins.every((origin) => isAllowedOrigin(origin, allowedOrigins))) {
|
|
1201
|
+
throw new Error("Identity connection sign-in is not accepted under this host system.");
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
|
|
1206
|
+
// src/modules/identity-connection-redirect-flow.ts
|
|
1207
|
+
var STATE_PREFIX2 = "connection.";
|
|
1208
|
+
var SCOPE = "openid email profile";
|
|
1209
|
+
var CALLBACK_PARAMS = ["code", "state", "error", "error_description", "error_uri", "session_state", "iss"];
|
|
1210
|
+
var TOKEN_REQUEST_TIMEOUT_MS = 15e3;
|
|
1211
|
+
var STORAGE_UNREADABLE = Symbol("storage-unreadable");
|
|
1212
|
+
var UnsolicitedIdentityConnectionRedirectError = class extends Error {
|
|
1213
|
+
};
|
|
1214
|
+
function requireBrowser() {
|
|
1215
|
+
if (globalThis.window === void 0) {
|
|
1216
|
+
throw new Error("Identity connection sign-in is only available in a browser.");
|
|
1217
|
+
}
|
|
1218
|
+
return globalThis.window;
|
|
1219
|
+
}
|
|
1220
|
+
function isNonEmptyString2(value) {
|
|
1221
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
1222
|
+
}
|
|
1223
|
+
function readEndpoints(connection) {
|
|
1224
|
+
const fields = connection ?? {};
|
|
1225
|
+
const { authorizationEndpoint, tokenEndpoint, clientId } = fields;
|
|
1226
|
+
if (!isNonEmptyString2(authorizationEndpoint) || !isNonEmptyString2(tokenEndpoint) || !isNonEmptyString2(clientId)) {
|
|
1227
|
+
return null;
|
|
1228
|
+
}
|
|
1229
|
+
return { authorizationEndpoint, tokenEndpoint, clientId };
|
|
1230
|
+
}
|
|
1231
|
+
function base64Url(bytes) {
|
|
1232
|
+
const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
|
|
1233
|
+
let encoded = btoa(binary).replaceAll("+", "-").replaceAll("/", "_");
|
|
1234
|
+
while (encoded.endsWith("=")) encoded = encoded.slice(0, -1);
|
|
1235
|
+
return encoded;
|
|
1236
|
+
}
|
|
1237
|
+
function randomBytes(length) {
|
|
1238
|
+
if (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {
|
|
1239
|
+
throw new Error("Identity connection sign-in requires the Web Crypto API.");
|
|
1240
|
+
}
|
|
1241
|
+
const bytes = new Uint8Array(length);
|
|
1242
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1243
|
+
return bytes;
|
|
1244
|
+
}
|
|
1245
|
+
async function codeChallengeOf(codeVerifier) {
|
|
1246
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
1247
|
+
return base64Url(new Uint8Array(digest));
|
|
1248
|
+
}
|
|
1249
|
+
function requireBareRedirectUri(redirectUri, browserWindow) {
|
|
1250
|
+
let parsed;
|
|
1251
|
+
try {
|
|
1252
|
+
parsed = new URL(redirectUri);
|
|
1253
|
+
} catch {
|
|
1254
|
+
throw new Error("Identity connection sign-in redirectUri must be an absolute URL.");
|
|
1255
|
+
}
|
|
1256
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
1257
|
+
throw new Error("Identity connection sign-in redirectUri must be an http or https URL.");
|
|
1258
|
+
}
|
|
1259
|
+
if (parsed.origin !== browserWindow.location.origin) {
|
|
1260
|
+
throw new Error("Identity connection sign-in redirectUri must be on the app origin.");
|
|
1261
|
+
}
|
|
1262
|
+
if (parsed.search || parsed.hash) {
|
|
1263
|
+
throw new Error("Identity connection sign-in redirectUri must have no query and no fragment.");
|
|
1264
|
+
}
|
|
1265
|
+
return redirectUri;
|
|
1266
|
+
}
|
|
1267
|
+
function readContext(value) {
|
|
1268
|
+
if (!value) return null;
|
|
1269
|
+
try {
|
|
1270
|
+
const context = JSON.parse(value);
|
|
1271
|
+
const complete = isNonEmptyString2(context.state) && isNonEmptyString2(context.codeVerifier) && isNonEmptyString2(context.slug) && isNonEmptyString2(context.redirectUri) && isNonEmptyString2(context.tokenEndpoint) && isNonEmptyString2(context.clientId);
|
|
1272
|
+
return complete ? context : null;
|
|
1273
|
+
} catch {
|
|
1274
|
+
return null;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
var IdentityConnectionRedirectFlow = class {
|
|
1278
|
+
appId;
|
|
1279
|
+
client;
|
|
1280
|
+
storageKey;
|
|
1281
|
+
constructor(config) {
|
|
1282
|
+
this.appId = config.appId;
|
|
1283
|
+
this.client = config.client;
|
|
1284
|
+
this.storageKey = config.storageKey;
|
|
1285
|
+
}
|
|
1286
|
+
async start(slug, options = {}) {
|
|
1287
|
+
const browserWindow = requireBrowser();
|
|
1288
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
1289
|
+
throw new Error("Identity connection sign-in names an invalid connection.");
|
|
1290
|
+
}
|
|
1291
|
+
const redirectUri = options.redirectUri === void 0 ? `${browserWindow.location.origin}${browserWindow.location.pathname}` : requireBareRedirectUri(options.redirectUri, browserWindow);
|
|
1292
|
+
const endpoints = readEndpoints(
|
|
1293
|
+
await this.client.get(`/api/v1/auth/identity-connections/${slug}`)
|
|
1294
|
+
);
|
|
1295
|
+
if (!endpoints) {
|
|
1296
|
+
throw new Error(`Identity connection ${slug} does not support redirect sign-in.`);
|
|
1297
|
+
}
|
|
1298
|
+
const random = Array.from(randomBytes(16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1299
|
+
const state = `${STATE_PREFIX2}${slug}.${random}`;
|
|
1300
|
+
const codeVerifier = base64Url(randomBytes(32));
|
|
1301
|
+
const context = {
|
|
1302
|
+
state,
|
|
1303
|
+
codeVerifier,
|
|
1304
|
+
slug,
|
|
1305
|
+
redirectUri,
|
|
1306
|
+
tokenEndpoint: endpoints.tokenEndpoint,
|
|
1307
|
+
clientId: endpoints.clientId,
|
|
1308
|
+
language: resolveLanguage(options.language, browserWindow)
|
|
1309
|
+
};
|
|
1310
|
+
try {
|
|
1311
|
+
browserWindow.sessionStorage.setItem(this.storageKey, JSON.stringify(context));
|
|
1312
|
+
} catch {
|
|
1313
|
+
throw new Error("Identity connection sign-in redirect requires sessionStorage.");
|
|
1314
|
+
}
|
|
1315
|
+
const query = Object.entries({
|
|
1316
|
+
response_type: "code",
|
|
1317
|
+
client_id: endpoints.clientId,
|
|
1318
|
+
redirect_uri: redirectUri,
|
|
1319
|
+
scope: SCOPE,
|
|
1320
|
+
state,
|
|
1321
|
+
code_challenge: await codeChallengeOf(codeVerifier),
|
|
1322
|
+
code_challenge_method: "S256"
|
|
1323
|
+
}).map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("&");
|
|
1324
|
+
const separator = endpoints.authorizationEndpoint.includes("?") ? "&" : "?";
|
|
1325
|
+
browserWindow.location.assign(`${endpoints.authorizationEndpoint}${separator}${query}`);
|
|
1326
|
+
return new Promise(() => void 0);
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Finishes the sign-in from the query the identity provider sent back, or
|
|
1330
|
+
* returns `null` when the query belongs to no identity connection redirect,
|
|
1331
|
+
* leaving the URL as it was. The query of this flow is removed before
|
|
1332
|
+
* anything can fail, and the stored context is spent on the first read, so a
|
|
1333
|
+
* failure is reported once and a code is never redeemed twice.
|
|
1334
|
+
*/
|
|
1335
|
+
async complete() {
|
|
1336
|
+
const browserWindow = requireBrowser();
|
|
1337
|
+
const params = new URLSearchParams(browserWindow.location.search);
|
|
1338
|
+
const state = params.get("state");
|
|
1339
|
+
if (!state?.startsWith(STATE_PREFIX2)) return null;
|
|
1340
|
+
const code = params.get("code");
|
|
1341
|
+
const error = params.get("error");
|
|
1342
|
+
const errorDescription = params.get("error_description");
|
|
1343
|
+
const context = this.takeContext(browserWindow);
|
|
1344
|
+
this.clearCallbackQuery(browserWindow, params);
|
|
1345
|
+
if (context === STORAGE_UNREADABLE) {
|
|
1346
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1347
|
+
"Identity connection sign-in context was not found in this tab: sessionStorage is unreadable."
|
|
1348
|
+
);
|
|
1349
|
+
}
|
|
1350
|
+
if (!context) {
|
|
1351
|
+
throw new UnsolicitedIdentityConnectionRedirectError(
|
|
1352
|
+
"Identity connection sign-in redirect does not match a pending request (possible CSRF)."
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
if (context.state !== state) {
|
|
1356
|
+
throw new Error("Identity connection sign-in redirect does not match a pending request (possible CSRF).");
|
|
1357
|
+
}
|
|
1358
|
+
if (error !== null) {
|
|
1359
|
+
throw new Error(errorDescription?.trim() || error.trim() || "Identity connection sign-in failed.");
|
|
1360
|
+
}
|
|
1361
|
+
if (!code?.trim()) {
|
|
1362
|
+
throw new Error("Identity connection sign-in redirect is missing code.");
|
|
1363
|
+
}
|
|
1364
|
+
const assertion = await this.redeemAuthorizationCode(context, code);
|
|
1365
|
+
const login = await this.client.post(
|
|
1366
|
+
`/api/v1/auth/identity-connections/${context.slug}/login`,
|
|
1367
|
+
{ token: assertion, appId: this.appId, language: context.language }
|
|
1368
|
+
);
|
|
1369
|
+
if (!isNonEmptyString2(login?.exchangeCode)) {
|
|
1370
|
+
throw new Error("Identity connection sign-in did not return an exchange code.");
|
|
1371
|
+
}
|
|
1372
|
+
return exchangeIdentityConnectionCode(this.client, context.slug, this.appId, login.exchangeCode);
|
|
1373
|
+
}
|
|
1374
|
+
takeContext(browserWindow) {
|
|
1375
|
+
try {
|
|
1376
|
+
const context = readContext(browserWindow.sessionStorage.getItem(this.storageKey));
|
|
1377
|
+
browserWindow.sessionStorage.removeItem(this.storageKey);
|
|
1378
|
+
return context;
|
|
1379
|
+
} catch {
|
|
1380
|
+
return STORAGE_UNREADABLE;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
clearCallbackQuery(browserWindow, params) {
|
|
1384
|
+
CALLBACK_PARAMS.forEach((name) => params.delete(name));
|
|
1385
|
+
const query = params.toString();
|
|
1386
|
+
const search = query ? `?${query}` : "";
|
|
1387
|
+
browserWindow.history.replaceState(
|
|
1388
|
+
{},
|
|
1389
|
+
"",
|
|
1390
|
+
`${browserWindow.location.pathname}${search}${browserWindow.location.hash}`
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
async redeemAuthorizationCode(context, code) {
|
|
1394
|
+
const controller = new AbortController();
|
|
1395
|
+
let timer;
|
|
1396
|
+
const timedOut = new Error("Identity connection sign-in timed out redeeming the authorization code at the identity provider.");
|
|
1397
|
+
const timeout = new Promise((_, reject) => {
|
|
1398
|
+
timer = setTimeout(() => {
|
|
1399
|
+
controller.abort();
|
|
1400
|
+
reject(timedOut);
|
|
1401
|
+
}, TOKEN_REQUEST_TIMEOUT_MS);
|
|
1402
|
+
});
|
|
1403
|
+
let response;
|
|
1404
|
+
let body;
|
|
1405
|
+
try {
|
|
1406
|
+
response = await Promise.race([
|
|
1407
|
+
fetch(context.tokenEndpoint, {
|
|
1408
|
+
method: "POST",
|
|
1409
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
1410
|
+
body: new URLSearchParams({
|
|
1411
|
+
grant_type: "authorization_code",
|
|
1412
|
+
client_id: context.clientId,
|
|
1413
|
+
code,
|
|
1414
|
+
redirect_uri: context.redirectUri,
|
|
1415
|
+
code_verifier: context.codeVerifier
|
|
1416
|
+
}).toString(),
|
|
1417
|
+
credentials: "omit",
|
|
1418
|
+
// The code and the verifier go to the token endpoint the connection named, never to a
|
|
1419
|
+
// host a redirect would pick.
|
|
1420
|
+
redirect: "error",
|
|
1421
|
+
signal: controller.signal
|
|
1422
|
+
}),
|
|
1423
|
+
timeout
|
|
1424
|
+
]);
|
|
1425
|
+
body = await Promise.race([response.json().catch(() => null), timeout]);
|
|
1426
|
+
} catch (error) {
|
|
1427
|
+
if (error === timedOut) throw error;
|
|
1428
|
+
throw new Error(
|
|
1429
|
+
"Identity connection sign-in could not reach the identity provider token endpoint; check that the app origin is in its Web Origins."
|
|
1430
|
+
);
|
|
1431
|
+
} finally {
|
|
1432
|
+
clearTimeout(timer);
|
|
1433
|
+
}
|
|
1434
|
+
if (!response.ok) {
|
|
1435
|
+
const reason = [body?.error, body?.error_description].filter(isNonEmptyString2).join(": ").split(code).join("[redacted]").split(context.codeVerifier).join("[redacted]");
|
|
1436
|
+
const detail = reason ? `, ${reason}` : "";
|
|
1437
|
+
throw new Error(
|
|
1438
|
+
`Identity connection sign-in could not redeem the authorization code (status ${response.status}${detail}).`
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
if (!isNonEmptyString2(body?.access_token)) {
|
|
1442
|
+
throw new Error("Identity connection sign-in did not receive an access token from the identity provider.");
|
|
1443
|
+
}
|
|
1444
|
+
return body.access_token;
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
|
|
1107
1448
|
// src/modules/password-form-flow.ts
|
|
1108
1449
|
var PASSWORD_PATH = "/api/v1/auth/password";
|
|
1109
1450
|
var LOGIN_PATH = `${PASSWORD_PATH}/login`;
|
|
@@ -1336,7 +1677,11 @@ var AuthModule = class {
|
|
|
1336
1677
|
passwordAuth;
|
|
1337
1678
|
emailCode;
|
|
1338
1679
|
passwordForm;
|
|
1680
|
+
identityConnection;
|
|
1681
|
+
identityConnectionRedirect;
|
|
1339
1682
|
brand = null;
|
|
1683
|
+
/** 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. */
|
|
1684
|
+
sessionScoped = false;
|
|
1340
1685
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
1341
1686
|
this.appId = appId;
|
|
1342
1687
|
const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
|
|
@@ -1390,6 +1735,12 @@ var AuthModule = class {
|
|
|
1390
1735
|
client: this.publicClient,
|
|
1391
1736
|
exchange: this.passwordAuth
|
|
1392
1737
|
});
|
|
1738
|
+
this.identityConnection = new IdentityConnectionFlow({ appId, client: this.publicClient });
|
|
1739
|
+
this.identityConnectionRedirect = new IdentityConnectionRedirectFlow({
|
|
1740
|
+
appId,
|
|
1741
|
+
client: this.publicClient,
|
|
1742
|
+
storageKey: `mitra_identity_connection_redirect_${appId}`
|
|
1743
|
+
});
|
|
1393
1744
|
this.loadFromStorage();
|
|
1394
1745
|
const readAccessToken = () => this.#accessToken;
|
|
1395
1746
|
sessionPorts.set(this, {
|
|
@@ -1399,6 +1750,7 @@ var AuthModule = class {
|
|
|
1399
1750
|
ensureFreshSession: (minValidityMs) => this.ensureFreshSession(minValidityMs),
|
|
1400
1751
|
handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
|
|
1401
1752
|
readSessionTokens: () => this.readSessionTokens(),
|
|
1753
|
+
isTabScoped: () => this.sessionScoped,
|
|
1402
1754
|
onSessionChange: (callback) => this.onSessionChange(callback),
|
|
1403
1755
|
adoptSession: (session) => this.adoptSession(session),
|
|
1404
1756
|
rotateSession: (session) => this.rotateSession(session)
|
|
@@ -1685,6 +2037,83 @@ var AuthModule = class {
|
|
|
1685
2037
|
const tokenResponse = await this.emailAuth.completeRedirect();
|
|
1686
2038
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1687
2039
|
}
|
|
2040
|
+
/**
|
|
2041
|
+
* Completes a sign-in made through an identity connection, such as Sankhya
|
|
2042
|
+
* Pass, from the single-use code the platform bridge page leaves in the
|
|
2043
|
+
* fragment (`#codeMitra`, `#stateMitra=connection.*`, `#connectionMitra`).
|
|
2044
|
+
*
|
|
2045
|
+
* `init()` already calls it, so an application only calls it itself when it
|
|
2046
|
+
* does not call `init()`. The session is kept in `sessionStorage`, not
|
|
2047
|
+
* `localStorage`, and so lives only as long as its tab.
|
|
2048
|
+
*
|
|
2049
|
+
* @returns The authenticated user, or `null` when the URL carries no
|
|
2050
|
+
* identity connection result. A fragment of another sign-in method is left
|
|
2051
|
+
* untouched.
|
|
2052
|
+
* @throws When the fragment belongs to an identity connection but cannot be
|
|
2053
|
+
* redeemed: outside an iframe, with an invalid connection, an error from the
|
|
2054
|
+
* bridge, no code, or a code IAM refuses. The fragment is removed first, and
|
|
2055
|
+
* the session this page held is dropped from memory, though not from storage.
|
|
2056
|
+
*/
|
|
2057
|
+
async completeIdentityConnectionSignInRedirect() {
|
|
2058
|
+
let tokenResponse;
|
|
2059
|
+
try {
|
|
2060
|
+
tokenResponse = await this.identityConnection.completeRedirect();
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
this.clearAuthState({ keepStorage: true });
|
|
2063
|
+
throw error;
|
|
2064
|
+
}
|
|
2065
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2066
|
+
}
|
|
2067
|
+
/**
|
|
2068
|
+
* Signs in through an identity connection, such as Sankhya Pass, outside a
|
|
2069
|
+
* host system iframe: the page is sent to the connection's identity provider
|
|
2070
|
+
* (Authorization Code with PKCE) and comes back to `redirectUri` with a code.
|
|
2071
|
+
* `init()` finishes it on the way back, or {@link completeIdentityConnectionRedirect}
|
|
2072
|
+
* when the app does not call `init()`. The returned promise never resolves,
|
|
2073
|
+
* because the page navigates away.
|
|
2074
|
+
*
|
|
2075
|
+
* @param slug - The connection, such as `sankhya-pass`.
|
|
2076
|
+
* @throws When the slug is invalid, the connection is unknown or does not
|
|
2077
|
+
* support redirect sign-in, or `sessionStorage` is unavailable.
|
|
2078
|
+
*
|
|
2079
|
+
* @example
|
|
2080
|
+
* ```typescript
|
|
2081
|
+
* await mitra.auth.signInWithIdentityConnection('sankhya-pass', { mode: 'redirect' });
|
|
2082
|
+
* ```
|
|
2083
|
+
*/
|
|
2084
|
+
async signInWithIdentityConnection(slug, options) {
|
|
2085
|
+
if (options?.mode !== "redirect") {
|
|
2086
|
+
throw new Error(`Unsupported identity connection sign-in mode: ${String(options?.mode)}`);
|
|
2087
|
+
}
|
|
2088
|
+
return this.identityConnectionRedirect.start(slug, options);
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* Completes a redirect started by {@link signInWithIdentityConnection} from
|
|
2092
|
+
* the query the identity provider sent back (`?code=...&state=connection.*`).
|
|
2093
|
+
*
|
|
2094
|
+
* `init()` already calls it. The session is kept in `sessionStorage`, like
|
|
2095
|
+
* the one from the host system iframe, and lives only as long as its tab.
|
|
2096
|
+
*
|
|
2097
|
+
* @returns The authenticated user, or `null` when the query carries no
|
|
2098
|
+
* identity connection redirect. Another query is left untouched.
|
|
2099
|
+
* @throws When the query belongs to this flow but no pending request in this
|
|
2100
|
+
* tab matches its state, the provider reports an error, or the provider or
|
|
2101
|
+
* IAM refuses the code. The query is removed first. When a sign-in was
|
|
2102
|
+
* pending in this tab, the session this page held is dropped from memory,
|
|
2103
|
+
* though not from storage; a callback with no pending sign-in leaves it.
|
|
2104
|
+
*/
|
|
2105
|
+
async completeIdentityConnectionRedirect() {
|
|
2106
|
+
let tokenResponse;
|
|
2107
|
+
try {
|
|
2108
|
+
tokenResponse = await this.identityConnectionRedirect.complete();
|
|
2109
|
+
} catch (error) {
|
|
2110
|
+
if (!(error instanceof UnsolicitedIdentityConnectionRedirectError)) {
|
|
2111
|
+
this.clearAuthState({ keepStorage: true });
|
|
2112
|
+
}
|
|
2113
|
+
throw error;
|
|
2114
|
+
}
|
|
2115
|
+
return tokenResponse ? this.establishSession(tokenResponse, true) : null;
|
|
2116
|
+
}
|
|
1688
2117
|
/**
|
|
1689
2118
|
* @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
|
|
1690
2119
|
* startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
|
|
@@ -2032,7 +2461,7 @@ var AuthModule = class {
|
|
|
2032
2461
|
return this.passwordForm.confirmReset(confirmation);
|
|
2033
2462
|
}
|
|
2034
2463
|
/**
|
|
2035
|
-
* Signs out the current user, clearing all auth state and
|
|
2464
|
+
* Signs out the current user, clearing all auth state and the stored session.
|
|
2036
2465
|
*
|
|
2037
2466
|
* In an app whose accounts are its own, the session also ends on the server:
|
|
2038
2467
|
* the refresh token is sent to IAM's logout, so it can no longer be renewed.
|
|
@@ -2165,6 +2594,9 @@ var AuthModule = class {
|
|
|
2165
2594
|
*
|
|
2166
2595
|
* Call `me()` afterwards to fetch the associated user data. {@link allTokens}
|
|
2167
2596
|
* goes back to `null`, because it belongs to the session being replaced.
|
|
2597
|
+
* The token starts a session of its own, so it is kept in `localStorage`
|
|
2598
|
+
* even when the one it replaces lived in its tab, and that tab copy is
|
|
2599
|
+
* removed in any case.
|
|
2168
2600
|
*
|
|
2169
2601
|
* @param token - JWT access token.
|
|
2170
2602
|
* @param saveToStorage - Whether to persist to localStorage (default: true).
|
|
@@ -2183,6 +2615,9 @@ var AuthModule = class {
|
|
|
2183
2615
|
this.invalidatePendingRefreshes();
|
|
2184
2616
|
this.#accessToken = token;
|
|
2185
2617
|
this.#allTokens = null;
|
|
2618
|
+
if (this.sessionScoped) this.#refreshToken = null;
|
|
2619
|
+
this.sessionScoped = false;
|
|
2620
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2186
2621
|
if (saveToStorage) {
|
|
2187
2622
|
this.saveToStorage();
|
|
2188
2623
|
}
|
|
@@ -2309,7 +2744,7 @@ var AuthModule = class {
|
|
|
2309
2744
|
* @internal
|
|
2310
2745
|
*/
|
|
2311
2746
|
adoptSession(session) {
|
|
2312
|
-
return this.applySession(session, false);
|
|
2747
|
+
return this.applySession(session, { keepAllTokens: false, replacesSession: true });
|
|
2313
2748
|
}
|
|
2314
2749
|
/**
|
|
2315
2750
|
* Stores tokens another issuer rotated for the session already in place, such
|
|
@@ -2319,19 +2754,23 @@ var AuthModule = class {
|
|
|
2319
2754
|
* @internal
|
|
2320
2755
|
*/
|
|
2321
2756
|
rotateSession(session) {
|
|
2322
|
-
return this.applySession(session,
|
|
2757
|
+
return this.applySession(session, {
|
|
2758
|
+
keepAllTokens: this.isSamePerson(session.token),
|
|
2759
|
+
replacesSession: false
|
|
2760
|
+
});
|
|
2323
2761
|
}
|
|
2324
2762
|
isSamePerson(token) {
|
|
2325
2763
|
const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
|
|
2326
2764
|
return current !== null && current === subjectOf(token);
|
|
2327
2765
|
}
|
|
2328
|
-
applySession(session, keepAllTokens) {
|
|
2766
|
+
applySession(session, { keepAllTokens, replacesSession }) {
|
|
2329
2767
|
if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
|
|
2330
2768
|
this.clearAuthState();
|
|
2331
2769
|
return false;
|
|
2332
2770
|
}
|
|
2333
2771
|
this.invalidatePendingRefreshes();
|
|
2334
2772
|
if (!keepAllTokens) this.#allTokens = null;
|
|
2773
|
+
if (replacesSession) this.sessionScoped = false;
|
|
2335
2774
|
this.#accessToken = session.token;
|
|
2336
2775
|
if (session.refreshToken !== void 0) {
|
|
2337
2776
|
this.#refreshToken = session.refreshToken;
|
|
@@ -2417,9 +2856,9 @@ var AuthModule = class {
|
|
|
2417
2856
|
this.notifySessionListeners();
|
|
2418
2857
|
return true;
|
|
2419
2858
|
}
|
|
2420
|
-
async establishSession(tokenResponse) {
|
|
2859
|
+
async establishSession(tokenResponse, sessionScoped = false) {
|
|
2421
2860
|
if (!this.belongsToConfiguredApp(tokenResponse.accessToken) || !this.belongsToConfiguredApp(tokenResponse.refreshToken)) {
|
|
2422
|
-
this.clearAuthState();
|
|
2861
|
+
this.clearAuthState({ keepStorage: sessionScoped });
|
|
2423
2862
|
throw coreErrors.invalidResponse("Authentication returned a token for a different app");
|
|
2424
2863
|
}
|
|
2425
2864
|
this.invalidatePendingRefreshes();
|
|
@@ -2427,6 +2866,7 @@ var AuthModule = class {
|
|
|
2427
2866
|
this.#accessToken = tokenResponse.accessToken;
|
|
2428
2867
|
this.#refreshToken = tokenResponse.refreshToken;
|
|
2429
2868
|
this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
|
|
2869
|
+
this.sessionScoped = sessionScoped;
|
|
2430
2870
|
try {
|
|
2431
2871
|
const user = await this.getCurrentUser();
|
|
2432
2872
|
if (generation !== this.sessionGeneration) {
|
|
@@ -2453,14 +2893,15 @@ var AuthModule = class {
|
|
|
2453
2893
|
const user = await this.currentUserApi.me();
|
|
2454
2894
|
return { ...user, tenantId: user.tenant.id };
|
|
2455
2895
|
}
|
|
2456
|
-
clearAuthState() {
|
|
2896
|
+
clearAuthState({ keepStorage = false } = {}) {
|
|
2457
2897
|
const hadAuthState = this._currentUser !== null || this.#accessToken !== null || this.#refreshToken !== null;
|
|
2458
2898
|
this.invalidatePendingRefreshes();
|
|
2459
2899
|
this._currentUser = null;
|
|
2460
2900
|
this.#accessToken = null;
|
|
2461
2901
|
this.#refreshToken = null;
|
|
2462
2902
|
this.#allTokens = null;
|
|
2463
|
-
this.removeFromStorage();
|
|
2903
|
+
if (!keepStorage) this.removeFromStorage();
|
|
2904
|
+
this.sessionScoped = false;
|
|
2464
2905
|
if (hadAuthState) {
|
|
2465
2906
|
this.notifySessionListeners();
|
|
2466
2907
|
this.notifyListeners();
|
|
@@ -2508,9 +2949,10 @@ var AuthModule = class {
|
|
|
2508
2949
|
});
|
|
2509
2950
|
}
|
|
2510
2951
|
saveToStorage() {
|
|
2511
|
-
|
|
2952
|
+
const target = this.sessionScoped ? sessionStorageOrNull() : localStorageOrNull();
|
|
2953
|
+
if (!target) return;
|
|
2512
2954
|
try {
|
|
2513
|
-
|
|
2955
|
+
target.setItem(
|
|
2514
2956
|
this.storageKey,
|
|
2515
2957
|
JSON.stringify({
|
|
2516
2958
|
user: this._currentUser,
|
|
@@ -2523,36 +2965,68 @@ var AuthModule = class {
|
|
|
2523
2965
|
})
|
|
2524
2966
|
);
|
|
2525
2967
|
} catch {
|
|
2968
|
+
return;
|
|
2526
2969
|
}
|
|
2970
|
+
if (!this.sessionScoped) removeItem(sessionStorageOrNull(), this.storageKey);
|
|
2527
2971
|
}
|
|
2528
2972
|
loadFromStorage() {
|
|
2529
|
-
if (
|
|
2973
|
+
if (this.restoreFrom(sessionStorageOrNull(), true)) return;
|
|
2974
|
+
this.restoreFrom(localStorageOrNull(), false);
|
|
2975
|
+
}
|
|
2976
|
+
/** An unusable entry is removed from this storage only, so a broken tab session does not take the shared one with it. */
|
|
2977
|
+
restoreFrom(storage, sessionScoped) {
|
|
2978
|
+
const stored = readItem(storage, this.storageKey);
|
|
2979
|
+
if (!stored) return false;
|
|
2530
2980
|
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();
|
|
2981
|
+
const { user, token, refreshToken, allTokens } = JSON.parse(stored);
|
|
2982
|
+
if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
|
|
2983
|
+
removeItem(storage, this.storageKey);
|
|
2984
|
+
return false;
|
|
2543
2985
|
}
|
|
2986
|
+
this._currentUser = user;
|
|
2987
|
+
this.#accessToken = token;
|
|
2988
|
+
this.#refreshToken = refreshToken ?? null;
|
|
2989
|
+
this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
|
|
2990
|
+
this.sessionScoped = sessionScoped;
|
|
2991
|
+
this.invalidatePendingRefreshes();
|
|
2992
|
+
return true;
|
|
2544
2993
|
} catch {
|
|
2545
|
-
this.
|
|
2994
|
+
removeItem(storage, this.storageKey);
|
|
2995
|
+
return false;
|
|
2546
2996
|
}
|
|
2547
2997
|
}
|
|
2548
2998
|
removeFromStorage() {
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
localStorage.removeItem(this.storageKey);
|
|
2552
|
-
} catch {
|
|
2553
|
-
}
|
|
2999
|
+
removeItem(sessionStorageOrNull(), this.storageKey);
|
|
3000
|
+
if (!this.sessionScoped) removeItem(localStorageOrNull(), this.storageKey);
|
|
2554
3001
|
}
|
|
2555
3002
|
};
|
|
3003
|
+
function localStorageOrNull() {
|
|
3004
|
+
try {
|
|
3005
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
3006
|
+
} catch {
|
|
3007
|
+
return null;
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
function sessionStorageOrNull() {
|
|
3011
|
+
try {
|
|
3012
|
+
return typeof sessionStorage === "undefined" ? null : sessionStorage;
|
|
3013
|
+
} catch {
|
|
3014
|
+
return null;
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
function readItem(storage, key) {
|
|
3018
|
+
try {
|
|
3019
|
+
return storage?.getItem(key) ?? null;
|
|
3020
|
+
} catch {
|
|
3021
|
+
return null;
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
function removeItem(storage, key) {
|
|
3025
|
+
try {
|
|
3026
|
+
storage?.removeItem(key);
|
|
3027
|
+
} catch {
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
2556
3030
|
|
|
2557
3031
|
// src/modules/entities.ts
|
|
2558
3032
|
import {
|
|
@@ -3346,11 +3820,19 @@ function createClient(config) {
|
|
|
3346
3820
|
setActiveBridge(legacyBridge);
|
|
3347
3821
|
legacyBridge.connect();
|
|
3348
3822
|
let initialized = false;
|
|
3823
|
+
let initFlight = null;
|
|
3349
3824
|
let allowSignup = true;
|
|
3350
3825
|
let emailLoginEnabled = false;
|
|
3351
3826
|
let passwordLoginEnabled = false;
|
|
3352
|
-
|
|
3353
|
-
if (
|
|
3827
|
+
function init() {
|
|
3828
|
+
if (initFlight) return initFlight;
|
|
3829
|
+
if (initialized) return Promise.resolve();
|
|
3830
|
+
initFlight = runInit().finally(() => {
|
|
3831
|
+
initFlight = null;
|
|
3832
|
+
});
|
|
3833
|
+
return initFlight;
|
|
3834
|
+
}
|
|
3835
|
+
async function runInit() {
|
|
3354
3836
|
const publicClient = new HttpClient({
|
|
3355
3837
|
baseUrl: codeStudioUrl,
|
|
3356
3838
|
getToken: () => null
|
|
@@ -3370,6 +3852,10 @@ function createClient(config) {
|
|
|
3370
3852
|
emailLoginEnabled = appInfo.emailLoginEnabled;
|
|
3371
3853
|
passwordLoginEnabled = appInfo.passwordLoginEnabled;
|
|
3372
3854
|
initialized = true;
|
|
3855
|
+
if (globalThis.window !== void 0) {
|
|
3856
|
+
await authModule.completeIdentityConnectionSignInRedirect();
|
|
3857
|
+
await authModule.completeIdentityConnectionRedirect();
|
|
3858
|
+
}
|
|
3373
3859
|
}
|
|
3374
3860
|
return {
|
|
3375
3861
|
init,
|