@mitralab.io/platform-sdk 1.7.0 → 1.8.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/dist/index.js CHANGED
@@ -9,7 +9,7 @@ function stripTrailingSlashes(value) {
9
9
  import {
10
10
  createPublicFunctionsModule,
11
11
  encodePathSegment,
12
- expectObject as expectObject3
12
+ expectObject as expectObject4
13
13
  } from "@mitralab.io/sdk-core";
14
14
 
15
15
  // src/utils/http-client.ts
@@ -100,7 +100,7 @@ var HttpClient = class {
100
100
  * ```
101
101
  */
102
102
  async request(path, options = {}) {
103
- const { method = "GET", body, headers = {}, params, isRetry } = options;
103
+ const { method = "GET", body, headers = {}, params, isRetry, keepalive } = options;
104
104
  const url = buildRequestUrl(this.baseUrl, path, params);
105
105
  if (!isRetry && this.tokenGetter() && this.beforeAuthenticatedRequest) {
106
106
  await this.beforeAuthenticatedRequest();
@@ -118,7 +118,8 @@ var HttpClient = class {
118
118
  method,
119
119
  headers: requestHeaders,
120
120
  body: body ? JSON.stringify(body) : void 0,
121
- redirect: "manual"
121
+ redirect: "manual",
122
+ ...keepalive ? { keepalive } : {}
122
123
  });
123
124
  if (response.redirected || response.type === "opaqueredirect") {
124
125
  const error = new MitraApiError(
@@ -365,7 +366,7 @@ function adoptLegacySession(session) {
365
366
  }
366
367
 
367
368
  // src/modules/auth.ts
368
- import { createAuthModule } from "@mitralab.io/sdk-core";
369
+ import { createAuthModule, expectObject as expectObject3 } from "@mitralab.io/sdk-core";
369
370
 
370
371
  // src/modules/api-key-auth.ts
371
372
  import { resolveApiKeyToken } from "@mitralab.io/sdk-core";
@@ -406,6 +407,9 @@ async function resolveApiKeySession(publicClient, appId, apiKey) {
406
407
  // src/modules/auth-page-flow.ts
407
408
  import { expectObject } from "@mitralab.io/sdk-core";
408
409
  var RESULT_TYPE = "mitra-oauth-result";
410
+ var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
411
+ var SESSION_TYPE = "mitra-auth-session";
412
+ var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
409
413
  var FIVE_MINUTES_MS = 5 * 60 * 1e3;
410
414
  var TEN_MINUTES_MS = 10 * 60 * 1e3;
411
415
  var PROVIDERS = {
@@ -430,6 +434,17 @@ var PROVIDERS = {
430
434
  redirectStorage: "localStorage",
431
435
  pendingRequestTtlMs: TEN_MINUTES_MS,
432
436
  popupTimeoutMs: TEN_MINUTES_MS
437
+ },
438
+ // IAM answers a password login, signup or change with the same single-use
439
+ // exchange code the email flow gets. Signing up waits on a code read from a
440
+ // mailbox, hence the email timeout; there is no link, so nothing pending is
441
+ // written for another tab.
442
+ password: {
443
+ label: "Password",
444
+ exchangePath: "/api/v1/auth/magic-link/exchange",
445
+ sendsRedirectUri: false,
446
+ redirectStorage: "sessionStorage",
447
+ popupTimeoutMs: TEN_MINUTES_MS
433
448
  }
434
449
  };
435
450
  var POPUP_WIDTH = 480;
@@ -502,6 +517,7 @@ var AuthPageFlow = class {
502
517
  providerLabel;
503
518
  redirectStorageKey;
504
519
  popupPromise = null;
520
+ popupView;
505
521
  constructor(config) {
506
522
  this.appId = config.appId;
507
523
  this.apiUrl = stripTrailingSlashes(config.apiUrl);
@@ -520,9 +536,24 @@ var AuthPageFlow = class {
520
536
  if (options.mode !== void 0 && options.mode !== "popup") {
521
537
  return Promise.reject(new Error(`Unsupported ${this.providerLabel} sign-in mode: ${String(options.mode)}`));
522
538
  }
523
- if (this.popupPromise) return this.popupPromise;
524
- this.popupPromise = this.startPopup(browserWindow).finally(() => {
539
+ return this.signInWithPopup({});
540
+ }
541
+ /**
542
+ * Opens the auth page in a popup on the given screen. A second call while the
543
+ * popup is open joins it when it asks for the same screen, and is refused
544
+ * otherwise: both would share one browser window, and the second would
545
+ * navigate it away from the first.
546
+ */
547
+ signInWithPopup(request) {
548
+ const browserWindow = this.requireBrowser();
549
+ if (this.popupPromise) {
550
+ if (this.popupView === request.view) return this.popupPromise;
551
+ return Promise.reject(new Error(`Another ${this.providerLabel} popup is already open.`));
552
+ }
553
+ this.popupView = request.view;
554
+ this.popupPromise = this.startPopup(browserWindow, request).finally(() => {
525
555
  this.popupPromise = null;
556
+ this.popupView = void 0;
526
557
  });
527
558
  return this.popupPromise;
528
559
  }
@@ -588,7 +619,7 @@ var AuthPageFlow = class {
588
619
  }
589
620
  return this.exchangeCode(code, context.redirectUri);
590
621
  }
591
- async startPopup(browserWindow) {
622
+ async startPopup(browserWindow, request) {
592
623
  const state = this.generateState();
593
624
  const authPageUrl = resolveAuthPageUrl(
594
625
  this.apiUrl,
@@ -602,8 +633,17 @@ var AuthPageFlow = class {
602
633
  this.newRedirectContext(state, this.getRedirectUri(authPageUrl))
603
634
  );
604
635
  }
605
- const popup = this.openPopup(browserWindow, this.buildStartUrl(browserWindow, authPageUrl, state));
606
- const result = await this.waitForPopupResult(browserWindow, popup, authPageUrl.origin, state);
636
+ const popup = this.openPopup(
637
+ browserWindow,
638
+ this.buildStartUrl(browserWindow, authPageUrl, state, request.view)
639
+ );
640
+ const result = await this.waitForPopupResult(
641
+ browserWindow,
642
+ popup,
643
+ authPageUrl.origin,
644
+ state,
645
+ request.sessionToken
646
+ );
607
647
  if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
608
648
  if (result.code) return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl));
609
649
  return expectAuthTokenResponse(result.token);
@@ -684,7 +724,7 @@ var AuthPageFlow = class {
684
724
  });
685
725
  return expectAuthTokenResponse(response);
686
726
  }
687
- buildStartUrl(browserWindow, authPageUrl, state) {
727
+ buildStartUrl(browserWindow, authPageUrl, state, view) {
688
728
  const startUrl = new URL(authPageUrl);
689
729
  startUrl.searchParams.set("provider", this.provider);
690
730
  startUrl.searchParams.set("state", state);
@@ -692,6 +732,7 @@ var AuthPageFlow = class {
692
732
  startUrl.searchParams.set("apiUrl", this.apiUrl);
693
733
  startUrl.searchParams.set("origin", browserWindow.location.origin);
694
734
  startUrl.searchParams.set("responseType", "code");
735
+ if (view) startUrl.searchParams.set("view", view);
695
736
  return startUrl;
696
737
  }
697
738
  getRedirectUri(authPageUrl) {
@@ -748,7 +789,7 @@ var AuthPageFlow = class {
748
789
  }
749
790
  return popup;
750
791
  }
751
- waitForPopupResult(browserWindow, popup, expectedOrigin, expectedState) {
792
+ waitForPopupResult(browserWindow, popup, expectedOrigin, expectedState, sessionToken) {
752
793
  return new Promise((resolve, reject) => {
753
794
  const timeout = globalThis.setTimeout(() => {
754
795
  cleanup();
@@ -760,31 +801,33 @@ var AuthPageFlow = class {
760
801
  reject(new Error(`${this.providerLabel} sign-in was cancelled.`));
761
802
  }
762
803
  }, POPUP_CLOSED_POLL_MS);
804
+ let settled = false;
805
+ const handOverSession = async (readToken) => {
806
+ const accessToken = await readToken().catch(() => null);
807
+ if (settled) return;
808
+ if (!accessToken) {
809
+ cleanup();
810
+ reject(new Error(`${this.providerLabel} popup needs a signed-in session.`));
811
+ return;
812
+ }
813
+ popup.postMessage({ type: SESSION_TYPE, state: expectedState, accessToken }, expectedOrigin);
814
+ };
763
815
  const onMessage = (event) => {
764
816
  if (event.origin !== expectedOrigin || event.source !== popup) return;
765
817
  if (!event.data || typeof event.data !== "object") return;
766
818
  const data = event.data;
767
- if (data.type !== RESULT_TYPE) return;
768
- if (data.state !== expectedState) {
769
- cleanup();
770
- reject(new Error(`Invalid ${this.providerLabel} sign-in state (possible CSRF).`));
771
- return;
772
- }
773
- if (data.success !== true) {
774
- cleanup();
775
- reject(new Error(typeof data.error === "string" && data.error.trim() ? data.error : `${this.providerLabel} sign-in failed.`));
776
- return;
777
- }
778
- const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
779
- if (!code && data.token === void 0) {
780
- cleanup();
781
- reject(new Error(`${this.providerLabel} auth page returned neither code nor token.`));
819
+ if (data.type === SESSION_REQUEST_TYPE) {
820
+ if (sessionToken && data.state === expectedState) void handOverSession(sessionToken);
782
821
  return;
783
822
  }
823
+ if (data.type !== RESULT_TYPE) return;
824
+ const outcome = readPopupResult(data, expectedState, this.providerLabel);
784
825
  cleanup();
785
- resolve({ ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} });
826
+ if ("error" in outcome) reject(outcome.error);
827
+ else resolve(outcome.value);
786
828
  };
787
829
  const cleanup = () => {
830
+ settled = true;
788
831
  globalThis.clearTimeout(timeout);
789
832
  globalThis.clearInterval(closedPoll);
790
833
  browserWindow.removeEventListener("message", onMessage);
@@ -840,6 +883,30 @@ var AuthPageFlow = class {
840
883
  return globalThis.window;
841
884
  }
842
885
  };
886
+ function readPopupResult(data, expectedState, providerLabel) {
887
+ if (data.state !== expectedState) {
888
+ return { error: new Error(`Invalid ${providerLabel} sign-in state (possible CSRF).`) };
889
+ }
890
+ if (data.success !== true && data.passwordChanged === true) {
891
+ return {
892
+ error: new MitraApiError(
893
+ "The password was changed, but signing in again failed. Sign in with the new password.",
894
+ 401,
895
+ PASSWORD_CHANGED_SIGN_IN_AGAIN
896
+ )
897
+ };
898
+ }
899
+ if (data.success !== true) {
900
+ return {
901
+ error: new Error(typeof data.error === "string" && data.error.trim() ? data.error : `${providerLabel} sign-in failed.`)
902
+ };
903
+ }
904
+ const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
905
+ if (!code && data.token === void 0) {
906
+ return { error: new Error(`${providerLabel} auth page returned neither code nor token.`) };
907
+ }
908
+ return { value: { ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} } };
909
+ }
843
910
 
844
911
  // src/modules/email-code-flow.ts
845
912
  import { expectObject as expectObject2 } from "@mitralab.io/sdk-core";
@@ -875,32 +942,20 @@ function optionalString2(value) {
875
942
  function isMagicLinkState(value) {
876
943
  return value === "OK" || value === "EXPIRED" || value === "USED" || value === "INVALID";
877
944
  }
878
- function expectEmailCodeRequestResult(value) {
879
- const response = expectObject2(
880
- value,
881
- "Email code request response",
882
- coreErrors
883
- );
945
+ function expectEmailCodeRequestResult(value, label = "Email code request response") {
946
+ const response = expectObject2(value, label, coreErrors);
884
947
  if (typeof response.receipt !== "string" || !response.receipt.trim()) {
885
- throw coreErrors.invalidResponse("Email code request response has an invalid receipt field");
948
+ throw coreErrors.invalidResponse(`${label} has an invalid receipt field`);
886
949
  }
887
950
  if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
888
- throw coreErrors.invalidResponse(
889
- "Email code request response has an invalid resendAfterSeconds field"
890
- );
951
+ throw coreErrors.invalidResponse(`${label} has an invalid resendAfterSeconds field`);
891
952
  }
892
953
  return { receipt: response.receipt, resendAfterSeconds: response.resendAfterSeconds };
893
954
  }
894
- function expectExchangeCode(value) {
895
- const response = expectObject2(
896
- value,
897
- "Email sign-in exchange code response",
898
- coreErrors
899
- );
955
+ function expectExchangeCode(value, label = "Email sign-in exchange code response") {
956
+ const response = expectObject2(value, label, coreErrors);
900
957
  if (typeof response.exchangeCode !== "string" || !response.exchangeCode.trim()) {
901
- throw coreErrors.invalidResponse(
902
- "Email sign-in exchange code response has an invalid exchangeCode field"
903
- );
958
+ throw coreErrors.invalidResponse(`${label} has an invalid exchangeCode field`);
904
959
  }
905
960
  return response.exchangeCode;
906
961
  }
@@ -1048,8 +1103,148 @@ var EmailCodeFlow = class {
1048
1103
  }
1049
1104
  };
1050
1105
 
1106
+ // src/modules/password-form-flow.ts
1107
+ var PASSWORD_PATH = "/api/v1/auth/password";
1108
+ var LOGIN_PATH = `${PASSWORD_PATH}/login`;
1109
+ var SIGNUP_PATH = `${PASSWORD_PATH}/signup`;
1110
+ var SIGNUP_VERIFY_PATH = `${SIGNUP_PATH}/verify`;
1111
+ var RESET_CONFIRM_PATH = `${PASSWORD_PATH}/reset/confirm`;
1112
+ var RESET_TOKEN_KEY = "resetToken";
1113
+ var PASSWORD_FORM_NOT_ENABLED = "PASSWORD_FORM_NOT_ENABLED";
1114
+ function passwordChangedSignInAgain(cause) {
1115
+ const error = new MitraApiError(
1116
+ "The password was changed, but signing in again failed. Sign in with the new password.",
1117
+ 401,
1118
+ PASSWORD_CHANGED_SIGN_IN_AGAIN
1119
+ );
1120
+ error.cause = cause;
1121
+ return error;
1122
+ }
1123
+ function explainFormNotEnabled(error) {
1124
+ if (!(error instanceof MitraApiError) || error.code !== PASSWORD_FORM_NOT_ENABLED) return error;
1125
+ return new MitraApiError(
1126
+ 'This app does not accept the password from its own form. Turn on the "form in the app itself" mode of the password login in the app, or use the methods of the Mitra auth page: signInWithPassword(), signUpWithPassword() and changePassword().',
1127
+ error.status,
1128
+ error.code,
1129
+ error.details,
1130
+ error.retryAfterSeconds
1131
+ );
1132
+ }
1133
+ var PasswordFormFlow = class {
1134
+ appId;
1135
+ client;
1136
+ exchange;
1137
+ constructor(config) {
1138
+ this.appId = config.appId;
1139
+ this.client = config.client;
1140
+ this.exchange = config.exchange;
1141
+ }
1142
+ async signIn(credentials) {
1143
+ const browserWindow = this.requireBrowser();
1144
+ return this.formRequest(async () => {
1145
+ const exchangeCode = expectExchangeCode(
1146
+ await this.client.post(LOGIN_PATH, {
1147
+ email: credentials.email,
1148
+ password: credentials.password,
1149
+ appId: this.appId,
1150
+ origin: browserWindow.location.origin
1151
+ }),
1152
+ "Password login response"
1153
+ );
1154
+ return this.exchange.redeemExchangeCode(exchangeCode);
1155
+ });
1156
+ }
1157
+ async startSignUp(request) {
1158
+ const browserWindow = this.requireBrowser();
1159
+ return expectEmailCodeRequestResult(
1160
+ await this.client.post(SIGNUP_PATH, {
1161
+ email: request.email,
1162
+ appId: this.appId,
1163
+ origin: browserWindow.location.origin,
1164
+ language: resolveLanguage(request.language, browserWindow)
1165
+ }),
1166
+ "Password sign-up request response"
1167
+ );
1168
+ }
1169
+ async completeSignUp(completion) {
1170
+ this.requireBrowser();
1171
+ return this.formRequest(async () => {
1172
+ const exchangeCode = expectExchangeCode(
1173
+ await this.client.post(SIGNUP_VERIFY_PATH, {
1174
+ receipt: completion.receipt,
1175
+ code: completion.code,
1176
+ password: completion.password
1177
+ }),
1178
+ "Password sign-up verification response"
1179
+ );
1180
+ return this.exchange.redeemExchangeCode(exchangeCode);
1181
+ });
1182
+ }
1183
+ /**
1184
+ * The token goes in the header by hand, on a client that never retries. IAM
1185
+ * answers a wrong current password with `401`, and a client that refreshes
1186
+ * and retries on `401` would spend a second guess against the account's
1187
+ * lockout with the same password.
1188
+ */
1189
+ async changePassword(change, accessToken) {
1190
+ this.requireBrowser();
1191
+ return this.formRequest(async () => {
1192
+ await this.client.request(PASSWORD_PATH, {
1193
+ method: "PUT",
1194
+ headers: { Authorization: `Bearer ${accessToken}` },
1195
+ body: {
1196
+ ...change.currentPassword === void 0 ? {} : { currentPassword: change.currentPassword },
1197
+ newPassword: change.newPassword
1198
+ }
1199
+ });
1200
+ });
1201
+ }
1202
+ /**
1203
+ * The whole fragment leaves the URL, not only the token: the link IAM sends
1204
+ * to `/reset-password` carries only the token and the language of the
1205
+ * message, and the token would otherwise stay in the history and in every
1206
+ * reload.
1207
+ */
1208
+ readResetToken() {
1209
+ const browserWindow = this.requireBrowser();
1210
+ const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
1211
+ if (!params.has(RESET_TOKEN_KEY)) return null;
1212
+ browserWindow.history.replaceState(
1213
+ {},
1214
+ "",
1215
+ `${browserWindow.location.pathname}${browserWindow.location.search}`
1216
+ );
1217
+ const token = params.get(RESET_TOKEN_KEY)?.trim();
1218
+ return token || null;
1219
+ }
1220
+ async confirmReset(confirmation) {
1221
+ this.requireBrowser();
1222
+ return this.formRequest(async () => {
1223
+ await this.client.post(RESET_CONFIRM_PATH, {
1224
+ token: confirmation.token,
1225
+ newPassword: confirmation.newPassword
1226
+ });
1227
+ });
1228
+ }
1229
+ async formRequest(request) {
1230
+ try {
1231
+ return await request();
1232
+ } catch (error) {
1233
+ throw explainFormNotEnabled(error);
1234
+ }
1235
+ }
1236
+ requireBrowser() {
1237
+ if (globalThis.window === void 0) {
1238
+ throw new Error("Password login is only available in a browser.");
1239
+ }
1240
+ return globalThis.window;
1241
+ }
1242
+ };
1243
+
1051
1244
  // src/modules/auth.ts
1052
1245
  var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
1246
+ var LOGOUT_PATH = "/api/v1/auth/logout";
1247
+ var PASSWORD_RESET_PATH = "/api/v1/auth/password/reset";
1053
1248
  var DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS = 6e4;
1054
1249
  var sessionPorts = /* @__PURE__ */ new WeakMap();
1055
1250
  function getAuthSessionPort(auth) {
@@ -1079,6 +1274,22 @@ function subjectOf(token) {
1079
1274
  const sub = decodeJwtPayload(token)?.sub;
1080
1275
  return typeof sub === "string" && sub !== "" ? sub : null;
1081
1276
  }
1277
+ function isExclusiveAppSession(refreshToken) {
1278
+ return decodeJwtPayload(refreshToken)?.login_mode === "exclusive";
1279
+ }
1280
+ function expectPasswordResetRequestResult(value) {
1281
+ const response = expectObject3(
1282
+ value,
1283
+ "Password reset request response",
1284
+ coreErrors
1285
+ );
1286
+ if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
1287
+ throw coreErrors.invalidResponse(
1288
+ "Password reset request response has an invalid resendAfterSeconds field"
1289
+ );
1290
+ }
1291
+ return { resendAfterSeconds: response.resendAfterSeconds };
1292
+ }
1082
1293
  function isTokenExpiring(token, minValidityMs) {
1083
1294
  const exp = decodeJwtPayload(token)?.exp;
1084
1295
  if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
@@ -1121,7 +1332,9 @@ var AuthModule = class {
1121
1332
  googleAuth;
1122
1333
  microsoftAuth;
1123
1334
  emailAuth;
1335
+ passwordAuth;
1124
1336
  emailCode;
1337
+ passwordForm;
1125
1338
  brand = null;
1126
1339
  constructor(appId, iamBaseUrl, options = {}) {
1127
1340
  this.appId = appId;
@@ -1159,11 +1372,23 @@ var AuthModule = class {
1159
1372
  client: this.publicClient,
1160
1373
  provider: "email"
1161
1374
  });
1375
+ this.passwordAuth = new AuthPageFlow({
1376
+ appId,
1377
+ apiUrl,
1378
+ authPageUrl: options.authPageUrl,
1379
+ client: this.publicClient,
1380
+ provider: "password"
1381
+ });
1162
1382
  this.emailCode = new EmailCodeFlow({
1163
1383
  appId,
1164
1384
  client: this.publicClient,
1165
1385
  pendingRequest: this.emailAuth
1166
1386
  });
1387
+ this.passwordForm = new PasswordFormFlow({
1388
+ appId,
1389
+ client: this.publicClient,
1390
+ exchange: this.passwordAuth
1391
+ });
1167
1392
  this.loadFromStorage();
1168
1393
  const readAccessToken = () => this.#accessToken;
1169
1394
  sessionPorts.set(this, {
@@ -1208,11 +1433,14 @@ var AuthModule = class {
1208
1433
  get isAuthenticated() {
1209
1434
  return this._currentUser !== null && this.#accessToken !== null;
1210
1435
  }
1211
- /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
1436
+ /**
1437
+ * @deprecated Use signInWithPassword(), which opens the Mitra auth page,
1438
+ * signInWithPasswordForm() in an app with the form mode on, signInWithEmail() or SSO.
1439
+ */
1212
1440
  signIn(_credentials) {
1213
1441
  return Promise.reject(
1214
1442
  new MitraApiError(
1215
- "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1443
+ "Email/password authentication is not available. Use signInWithPassword(), signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1216
1444
  0,
1217
1445
  "UNSUPPORTED_AUTH_METHOD"
1218
1446
  )
@@ -1456,19 +1684,361 @@ var AuthModule = class {
1456
1684
  const tokenResponse = await this.emailAuth.completeRedirect();
1457
1685
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1458
1686
  }
1459
- /** @deprecated Email/password registration is not implemented by IAM. Use signInWithEmail() or SSO. */
1687
+ /**
1688
+ * @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
1689
+ * startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
1690
+ */
1460
1691
  signUp(_data) {
1461
1692
  return Promise.reject(
1462
1693
  new MitraApiError(
1463
- "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1694
+ "Email/password registration is not available. Use signUpWithPassword(), signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1464
1695
  0,
1465
1696
  "UNSUPPORTED_AUTH_METHOD"
1466
1697
  )
1467
1698
  );
1468
1699
  }
1700
+ /**
1701
+ * Signs in with email and password, typed into the Mitra auth page in a popup.
1702
+ * The password never reaches the app's code: the page sends it to IAM and
1703
+ * hands back a single-use exchange code, redeemed like the email sign-in.
1704
+ *
1705
+ * Offer it only when `mitra.passwordLoginEnabled` is `true`, which needs an
1706
+ * app whose accounts are its own (exclusive login mode). Call it straight
1707
+ * from the click handler, before any `await`, or the browser blocks the popup.
1708
+ *
1709
+ * @returns The authenticated and hydrated user.
1710
+ * @throws {MitraApiError} When IAM rejects the exchange code.
1711
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
1712
+ * out, or the response fails origin, source, state, or shape validation. Wrong
1713
+ * credentials are answered on the auth page itself, not here.
1714
+ *
1715
+ * @example
1716
+ * ```typescript
1717
+ * const user = await mitra.auth.signInWithPassword();
1718
+ * ```
1719
+ */
1720
+ async signInWithPassword() {
1721
+ return this.establishSession(await this.passwordAuth.signInWithPopup({ view: "login" }));
1722
+ }
1723
+ /**
1724
+ * Creates a password for an app account, on the Mitra auth page in a popup:
1725
+ * the page asks for the address, sends a code to it to prove the mailbox is
1726
+ * the person's, and takes the password with that code. The person ends signed
1727
+ * in, as with {@link signInWithPassword}.
1728
+ *
1729
+ * @returns The authenticated and hydrated user.
1730
+ * @throws The same errors as {@link signInWithPassword}.
1731
+ *
1732
+ * @example
1733
+ * ```typescript
1734
+ * const user = await mitra.auth.signUpWithPassword();
1735
+ * ```
1736
+ */
1737
+ async signUpWithPassword() {
1738
+ return this.establishSession(await this.passwordAuth.signInWithPopup({ view: "signup" }));
1739
+ }
1740
+ /**
1741
+ * Changes the password of the signed-in person, on the Mitra auth page in a
1742
+ * popup. The page asks for the current and the new password itself, so the
1743
+ * app never sees either one.
1744
+ *
1745
+ * The page acts on this session, so it asks for the access token once it
1746
+ * loads, and the SDK answers with `postMessage` to the auth page origin only:
1747
+ * the token never goes in the popup URL.
1748
+ *
1749
+ * IAM ends every session of the account when the password changes, this one
1750
+ * included, so the page signs in again with the new password and hands back a
1751
+ * new session, which replaces the current one.
1752
+ *
1753
+ * When the change goes through but that new sign-in fails, the call rejects
1754
+ * with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared,
1755
+ * since IAM already ended it: send the person to sign in with the new password.
1756
+ *
1757
+ * @returns The user of the new session.
1758
+ * @throws {MitraApiError} `401` when nobody is signed in, and
1759
+ * `PASSWORD_CHANGED_SIGN_IN_AGAIN` (status `401`) as above.
1760
+ * @throws The same errors as {@link signInWithPassword}, and an error when the
1761
+ * session ends while the popup is open.
1762
+ *
1763
+ * @example
1764
+ * ```typescript
1765
+ * await mitra.auth.changePassword();
1766
+ * ```
1767
+ */
1768
+ async changePassword() {
1769
+ if (!this.#accessToken) {
1770
+ throw new MitraApiError("Sign in before changing the password.", 401);
1771
+ }
1772
+ const sessionToken = async () => {
1773
+ await this.ensureFreshSession();
1774
+ return this.#accessToken;
1775
+ };
1776
+ const generation = this.sessionGeneration;
1777
+ let tokenResponse;
1778
+ try {
1779
+ tokenResponse = await this.passwordAuth.signInWithPopup({ view: "change", sessionToken });
1780
+ } catch (error) {
1781
+ if (error instanceof MitraApiError && error.code === PASSWORD_CHANGED_SIGN_IN_AGAIN && generation === this.sessionGeneration) {
1782
+ this.clearAuthState();
1783
+ }
1784
+ throw error;
1785
+ }
1786
+ return this.establishSession(tokenResponse);
1787
+ }
1788
+ /**
1789
+ * Asks IAM to email a link to set a new password. Only the address goes.
1790
+ * Where the link opens depends on the app's mode of the password login: with
1791
+ * the Mitra auth page, the default, the new password is typed there; with the
1792
+ * form in the app itself, the link opens `/reset-password` on this app's
1793
+ * origin, which reads it with {@link readPasswordResetToken} and finishes
1794
+ * with {@link confirmPasswordReset}.
1795
+ *
1796
+ * IAM answers the same whether or not the address has an account, so this
1797
+ * resolves without saying which.
1798
+ *
1799
+ * @param email - The address of the account.
1800
+ * @param options - The language of the message.
1801
+ * @returns How long the application should wait before offering to resend.
1802
+ * @throws {MitraApiError} `RATE_LIMITED` when this address asked too often,
1803
+ * and `RATE_LIMIT_EXCEEDED` when this network did, both with
1804
+ * `retryAfterSeconds` when IAM sends it.
1805
+ *
1806
+ * @example
1807
+ * ```typescript
1808
+ * const { resendAfterSeconds } = await mitra.auth.requestPasswordReset('person@example.com');
1809
+ * ```
1810
+ */
1811
+ async requestPasswordReset(email, options = {}) {
1812
+ if (globalThis.window === void 0) {
1813
+ throw new Error("Password reset is only available in a browser.");
1814
+ }
1815
+ const browserWindow = globalThis.window;
1816
+ return expectPasswordResetRequestResult(
1817
+ await this.publicClient.post(PASSWORD_RESET_PATH, {
1818
+ email,
1819
+ appId: this.appId,
1820
+ origin: browserWindow.location.origin,
1821
+ language: resolveLanguage(options.language, browserWindow)
1822
+ })
1823
+ );
1824
+ }
1825
+ /**
1826
+ * The password goes through the app's code. Do not store it, do not log it
1827
+ * and do not send it anywhere other than this method. The safer default is
1828
+ * signInWithPassword(), which uses the Mitra auth page.
1829
+ *
1830
+ * Works only when the app has the "form in the app itself" mode of the
1831
+ * password login turned on. Otherwise IAM refuses it with
1832
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1833
+ *
1834
+ * Signs in with the address and password typed into the app's own form.
1835
+ *
1836
+ * @returns The authenticated and hydrated user.
1837
+ * @throws {MitraApiError} `INVALID_CREDENTIALS` (status `401`) for a wrong
1838
+ * address or password, a locked account or one without a password, all
1839
+ * answered alike, `SIGNUP_NOT_ALLOWED` (status `403`) when the account lost
1840
+ * its access to an app that takes no new accounts, `RATE_LIMIT_EXCEEDED`
1841
+ * (status `429`, with `retryAfterSeconds` when IAM sends it) when this
1842
+ * network called the password routes too often or IAM is at its limit of
1843
+ * passwords being hashed, so wait `retryAfterSeconds`, and
1844
+ * `PASSWORD_FORM_NOT_ENABLED` as above.
1845
+ *
1846
+ * @example
1847
+ * ```typescript
1848
+ * const user = await mitra.auth.signInWithPasswordForm({ email, password });
1849
+ * ```
1850
+ */
1851
+ async signInWithPasswordForm(credentials) {
1852
+ return this.establishSession(await this.passwordForm.signIn(credentials));
1853
+ }
1854
+ /**
1855
+ * The password goes through the app's code. Do not store it, do not log it
1856
+ * and do not send it anywhere other than this method. The safer default is
1857
+ * signInWithPassword(), which uses the Mitra auth page.
1858
+ *
1859
+ * First step of creating a password from the app's own form: IAM emails a
1860
+ * six-digit code to the address, to prove the mailbox is the person's. No
1861
+ * password goes in this step, which IAM takes in either mode of the app; the
1862
+ * "form in the app itself" mode is required at {@link completePasswordSignUp},
1863
+ * where the password goes. Browser only.
1864
+ *
1865
+ * IAM answers the same whether or not the address has an account, so this
1866
+ * resolves without saying which.
1867
+ *
1868
+ * @param request - The address, and the language of the message.
1869
+ * @returns The receipt that names this request, and the resend delay.
1870
+ * @throws {MitraApiError} `RATE_LIMITED` (with `retryAfterSeconds`) when this
1871
+ * address asked too often, and `RATE_LIMIT_EXCEEDED` (status `429`, with
1872
+ * `retryAfterSeconds` when IAM sends it) when this network called the
1873
+ * password routes too often.
1874
+ *
1875
+ * @example
1876
+ * ```typescript
1877
+ * const { receipt, resendAfterSeconds } = await mitra.auth.startPasswordSignUp({ email });
1878
+ * ```
1879
+ */
1880
+ async startPasswordSignUp(request) {
1881
+ return this.passwordForm.startSignUp(request);
1882
+ }
1883
+ /**
1884
+ * The password goes through the app's code. Do not store it, do not log it
1885
+ * and do not send it anywhere other than this method. The safer default is
1886
+ * signInWithPassword(), which uses the Mitra auth page.
1887
+ *
1888
+ * Works only when the app has the "form in the app itself" mode of the
1889
+ * password login turned on. Otherwise IAM refuses it with
1890
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1891
+ *
1892
+ * Second step of {@link startPasswordSignUp}: the code from the message and
1893
+ * the chosen password. The person ends signed in, as with
1894
+ * {@link signInWithPasswordForm}.
1895
+ *
1896
+ * @param completion - The receipt, the code and the password.
1897
+ * @returns The authenticated and hydrated user.
1898
+ * @throws {MitraApiError} `INVALID_CODE` when the code does not match or the
1899
+ * request expired, `MAGIC_LINK_USED` when it was already completed,
1900
+ * `PASSWORD_ALREADY_SET` when the account has a password (the way to replace
1901
+ * it is the reset), `SSO_ACCOUNT` (status `409`) when the account signs in
1902
+ * with Google or Microsoft, `SIGNUP_NOT_ALLOWED` when the app takes no new
1903
+ * accounts, `WEAK_PASSWORD` (status `400`) with the rule the password broke,
1904
+ * `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds` when IAM
1905
+ * sends it) when this network called the password routes too often or IAM is
1906
+ * at its limit of passwords being hashed, so wait `retryAfterSeconds`, and
1907
+ * `PASSWORD_FORM_NOT_ENABLED` as above.
1908
+ *
1909
+ * @example
1910
+ * ```typescript
1911
+ * const user = await mitra.auth.completePasswordSignUp({ receipt, code, password });
1912
+ * ```
1913
+ */
1914
+ async completePasswordSignUp(completion) {
1915
+ return this.establishSession(await this.passwordForm.completeSignUp(completion));
1916
+ }
1917
+ /**
1918
+ * The password goes through the app's code. Do not store it, do not log it
1919
+ * and do not send it anywhere other than this method. The safer default is
1920
+ * signInWithPassword(), which uses the Mitra auth page.
1921
+ *
1922
+ * Works only when the app has the "form in the app itself" mode of the
1923
+ * password login turned on. Otherwise IAM refuses it with
1924
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1925
+ *
1926
+ * Changes the password of the signed-in person from the app's own form. IAM
1927
+ * ends every session of the account when the password changes, this one
1928
+ * included, so the SDK signs in again with the address of this session and
1929
+ * the new password, and that session replaces the current one.
1930
+ *
1931
+ * When the change goes through but that new sign-in fails, the call rejects
1932
+ * with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared,
1933
+ * since IAM already ended it: send the person to sign in with the new password.
1934
+ *
1935
+ * @param change - The current password, required whenever the account
1936
+ * already has one, and the new one.
1937
+ * @returns The user of the new session.
1938
+ * @throws {MitraApiError} `401` when nobody is signed in,
1939
+ * `PASSWORD_CHANGED_SIGN_IN_AGAIN` (status `401`) as above,
1940
+ * `INVALID_CREDENTIALS` (status `401`) for a wrong current password,
1941
+ * `CURRENT_PASSWORD_REQUIRED` and `WEAK_PASSWORD` (status `400`),
1942
+ * `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
1943
+ * Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
1944
+ * when IAM sends it) when this network called the password routes too often
1945
+ * or IAM is at its limit of passwords being hashed, so wait
1946
+ * `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
1947
+ *
1948
+ * @example
1949
+ * ```typescript
1950
+ * await mitra.auth.changePasswordForm({ currentPassword, newPassword });
1951
+ * ```
1952
+ */
1953
+ async changePasswordForm(change) {
1954
+ if (!this.#accessToken) {
1955
+ throw new MitraApiError("Sign in before changing the password.", 401);
1956
+ }
1957
+ const email = this._currentUser?.email ?? (await this.getCurrentUser()).email;
1958
+ await this.ensureFreshSession();
1959
+ const accessToken = this.#accessToken;
1960
+ if (!accessToken) {
1961
+ throw new MitraApiError("Sign in before changing the password.", 401);
1962
+ }
1963
+ const generation = this.sessionGeneration;
1964
+ await this.passwordForm.changePassword(change, accessToken);
1965
+ try {
1966
+ return await this.signInWithPasswordForm({ email, password: change.newPassword });
1967
+ } catch (error) {
1968
+ if (generation === this.sessionGeneration) {
1969
+ this.clearAuthState();
1970
+ }
1971
+ throw passwordChangedSignInAgain(error);
1972
+ }
1973
+ }
1974
+ /**
1975
+ * The password goes through the app's code. Do not store it, do not log it
1976
+ * and do not send it anywhere other than this method. The safer default is
1977
+ * signInWithPassword(), which uses the Mitra auth page.
1978
+ *
1979
+ * The reset token is single use and works as a credential until it is spent:
1980
+ * do not log it either.
1981
+ *
1982
+ * Reads the token of a password reset link that landed on this app, and
1983
+ * removes the fragment from the URL so the token does not stay in the
1984
+ * history. With the form in the app itself turned on, IAM sends the link to
1985
+ * `/reset-password#resetToken=...` on the origin the reset was asked from:
1986
+ * call this when that route loads, then {@link confirmPasswordReset}.
1987
+ *
1988
+ * Nothing is sent to IAM here, and a URL without the link is left as it is.
1989
+ * Browser only.
1990
+ *
1991
+ * @returns The token, or `null` when the URL carries none.
1992
+ *
1993
+ * @example
1994
+ * ```typescript
1995
+ * const token = mitra.auth.readPasswordResetToken();
1996
+ * ```
1997
+ */
1998
+ readPasswordResetToken() {
1999
+ return this.passwordForm.readResetToken();
2000
+ }
2001
+ /**
2002
+ * The password goes through the app's code. Do not store it, do not log it
2003
+ * and do not send it anywhere other than this method. The safer default is
2004
+ * signInWithPassword(), which uses the Mitra auth page.
2005
+ *
2006
+ * Works only when the app has the "form in the app itself" mode of the
2007
+ * password login turned on. Otherwise IAM refuses it with
2008
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
2009
+ *
2010
+ * Sets the new password with the token from the reset link. The link is
2011
+ * single use, and IAM ends every session of the account, so the person signs
2012
+ * in afterwards with the new password; this method signs nobody in.
2013
+ *
2014
+ * @param confirmation - The token from {@link readPasswordResetToken} and the
2015
+ * new password.
2016
+ * @throws {MitraApiError} `RESET_TOKEN_USED` or `RESET_TOKEN_EXPIRED` (status
2017
+ * `409`) when the link can no longer be used; a token IAM does not know also
2018
+ * answers `RESET_TOKEN_EXPIRED`. Also `WEAK_PASSWORD` (status `400`),
2019
+ * `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
2020
+ * Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
2021
+ * when IAM sends it) when this network called the password routes too often
2022
+ * or IAM is at its limit of passwords being hashed, so wait
2023
+ * `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
2024
+ *
2025
+ * @example
2026
+ * ```typescript
2027
+ * await mitra.auth.confirmPasswordReset({ token, newPassword });
2028
+ * ```
2029
+ */
2030
+ async confirmPasswordReset(confirmation) {
2031
+ return this.passwordForm.confirmReset(confirmation);
2032
+ }
1469
2033
  /**
1470
2034
  * Signs out the current user, clearing all auth state and localStorage.
1471
2035
  *
2036
+ * In an app whose accounts are its own, the session also ends on the server:
2037
+ * the refresh token is sent to IAM's logout, so it can no longer be renewed.
2038
+ * The local state is cleared right away whatever IAM answers, and the request
2039
+ * survives a navigation to `redirectUrl`. The access token already issued
2040
+ * stays valid until it expires.
2041
+ *
1472
2042
  * @param redirectUrl - Optional URL to navigate to after sign-out.
1473
2043
  *
1474
2044
  * @example
@@ -1478,7 +2048,11 @@ var AuthModule = class {
1478
2048
  * ```
1479
2049
  */
1480
2050
  signOut(redirectUrl) {
2051
+ const refreshToken = this.#refreshToken;
1481
2052
  this.clearAuthState();
2053
+ if (refreshToken && isExclusiveAppSession(refreshToken)) {
2054
+ this.endServerSession(refreshToken);
2055
+ }
1482
2056
  if (globalThis.window !== void 0 && redirectUrl) {
1483
2057
  globalThis.window.location.href = redirectUrl;
1484
2058
  }
@@ -1807,6 +2381,10 @@ var AuthModule = class {
1807
2381
  this.listeners.delete(callback);
1808
2382
  };
1809
2383
  }
2384
+ /** Best effort: the person asked to leave, and that already happened locally. */
2385
+ endServerSession(refreshToken) {
2386
+ this.publicClient.request(LOGOUT_PATH, { method: "POST", body: { refreshToken }, keepalive: true }).catch(() => void 0);
2387
+ }
1810
2388
  async doRefresh(generation, refreshToken) {
1811
2389
  let tokenResponse;
1812
2390
  try {
@@ -2665,7 +3243,7 @@ function createBrowserAgentCredentialsModule(httpClient) {
2665
3243
 
2666
3244
  // src/client.ts
2667
3245
  function expectAppInfoResponse(value) {
2668
- const response = expectObject3(
3246
+ const response = expectObject4(
2669
3247
  value,
2670
3248
  "App info response",
2671
3249
  coreErrors
@@ -2688,6 +3266,7 @@ function expectAppInfoResponse(value) {
2688
3266
  // answers without this field, and an app that cannot prove it is enabled
2689
3267
  // should stop offering the option, not stop starting.
2690
3268
  emailLoginEnabled: response.emailLoginEnabled === true,
3269
+ passwordLoginEnabled: response.passwordLoginEnabled === true,
2691
3270
  // Same reasoning, and the brand is never guessed: without it the headless
2692
3271
  // email methods refuse instead of asking IAM to brand a message at random.
2693
3272
  brand: typeof response.brand === "string" && response.brand.trim() ? response.brand : null
@@ -2766,6 +3345,7 @@ function createClient(config) {
2766
3345
  let initialized = false;
2767
3346
  let allowSignup = true;
2768
3347
  let emailLoginEnabled = false;
3348
+ let passwordLoginEnabled = false;
2769
3349
  async function init() {
2770
3350
  if (initialized) return;
2771
3351
  const publicClient = new HttpClient({
@@ -2785,6 +3365,7 @@ function createClient(config) {
2785
3365
  }
2786
3366
  allowSignup = appInfo.allowSignup;
2787
3367
  emailLoginEnabled = appInfo.emailLoginEnabled;
3368
+ passwordLoginEnabled = appInfo.passwordLoginEnabled;
2788
3369
  initialized = true;
2789
3370
  }
2790
3371
  return {
@@ -2803,6 +3384,9 @@ function createClient(config) {
2803
3384
  get emailLoginEnabled() {
2804
3385
  return emailLoginEnabled;
2805
3386
  },
3387
+ get passwordLoginEnabled() {
3388
+ return passwordLoginEnabled;
3389
+ },
2806
3390
  config
2807
3391
  };
2808
3392
  }