@mitralab.io/platform-sdk 1.7.0-beta.2 → 1.8.0-beta.0

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 CHANGED
@@ -2,6 +2,50 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.8.0-beta.0
6
+
7
+ Sign-in by email and password for apps whose accounts are their own (exclusive login mode).
8
+
9
+ - `auth.signInWithPassword()`, `auth.signUpWithPassword()` and `auth.changePassword()` open the
10
+ Mitra auth page (`sdk-auth.html`) in a popup with `provider=password` and `view=login`, `signup`
11
+ or `change`. The password is typed only there and never passes through the app's code. The page
12
+ hands back the same single-use exchange code as the email sign-in, redeemed at
13
+ `/auth/magic-link/exchange`. Popup only: there is no redirect mode for these methods.
14
+ - `changePassword()` needs a session. The page asks for it with a `mitra-auth-session-request`
15
+ message, and the SDK answers `mitra-auth-session` with the access token through `postMessage`
16
+ to the auth page origin, never in the URL. IAM ends every session of the account when the
17
+ password changes, so the page signs in again and the new session replaces the current one. When
18
+ the change goes through but that sign-in fails, the call rejects with
19
+ `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared.
20
+ - `auth.requestPasswordReset(email, { language })` asks IAM to email a reset link and returns
21
+ `{ resendAfterSeconds }`, neutral about whether the address has an account. The link opens the
22
+ Mitra auth page, where the new password is typed, so there is no `confirmPasswordReset`. Asking
23
+ too often answers `RATE_LIMITED` (per address) or `RATE_LIMIT_EXCEEDED` (per network).
24
+ - `auth.signOut()` also ends the session on the server when it belongs to an exclusive app
25
+ account: it sends the refresh token to `POST /auth/logout` with `keepalive`, ignores the answer,
26
+ and clears the local state right away, as before. A shared app session, or one without a
27
+ refresh token, is only cleared locally.
28
+ - `mitra.passwordLoginEnabled`, read from the app info by `init()`, `false` when the server omits it.
29
+ - `signIn` and `signUp` with a password stay deprecated and now point to the new methods.
30
+ - Export `PasswordResetOptions` and `PasswordResetRequestResult`.
31
+
32
+ ## 1.7.0
33
+
34
+ Stable release of the 1.7.0-beta line, with `@mitralab.io/sdk-core@0.3.0`.
35
+
36
+ - Depend on `@mitralab.io/sdk-core@0.3.0`, the agent session that follows T3. A message sent while
37
+ a reply runs no longer waits in a local queue of the SDK: it goes to the box at once, with no mode
38
+ by default, and T3 decides, steering it into the running turn or queueing it.
39
+ `send(prompt, { mode: "queue" | "steer" })` asks on purpose. `session.history` is the live
40
+ conversation in the box's order (asked with `kinds=all`), with a tool's call and result as two
41
+ items, as in 0.2.13, the question as the person wrote it, and T3's approvals and mid-turn
42
+ questions where they came. `queue` mirrors T3's queue, with `steerQueueItem`, `resumeQueue` and
43
+ `backgroundTasks`. The history keeps the 0.2.13 format; against an old box the new functions show
44
+ nothing.
45
+ - `agentTasks.session(...).send` returns the id of the message the core sends (its
46
+ `clientMessageId`); a prompt held while the browser is offline returns `undefined`.
47
+ - Includes `auth.allTokens.backoffice` and `auth.ensureFreshBackofficeToken()` from 1.7.0-beta.0.
48
+
5
49
  ## 1.7.0-beta.0
6
50
 
7
51
  - `auth.allTokens` gains a fourth family, `backoffice`: the access token of the person's own
package/README.md CHANGED
@@ -36,12 +36,13 @@ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já v
36
36
 
37
37
  ## O que dá para fazer
38
38
 
39
- - `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`) ou código por e-mail, mais `currentUser`, `onAuthStateChange` e `signOut`.
39
+ - `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`), código por e-mail ou e-mail e senha (`signInWithPassword`), mais `currentUser`, `onAuthStateChange` e `signOut`.
40
40
  - `entities.<Tabela>`: `list`, `filter`, `get`, `create`, `bulkCreate`, `update`, `delete` e `deleteMany` nas tabelas do app.
41
41
  - `queries.execute(id, params)`: roda uma query salva no app.
42
42
  - `functions`: `execute` espera o resultado da Server Function; `executeAsync` devolve a execução para acompanhar com `getExecution` ou parar com `cancelExecution`. `publicFunctions` chama as Functions publicadas como públicas, sem login.
43
43
  - `integration.executeByAlias(alias, request)`: chama uma API externa configurada no app. A credencial do provedor fica na Mitra e não passa pelo browser.
44
44
  - `agentTasks.session(...)`: chat com agente, com `send`, `sendAndWait`, `cancel` e eventos como `delta`, `turnEnd` e `error`.
45
+ `send` devolve o id da mensagem; com o browser offline a mensagem espera a rede e `send` devolve `undefined`.
45
46
  - `agentCredentials`: credenciais de provedor de IA e modelos disponíveis.
46
47
 
47
48
  Login por código no e-mail, para quem monta a própria tela:
@@ -51,6 +52,14 @@ const { receipt } = await mitra.auth.requestEmailCode({ email })
51
52
  const user = await mitra.auth.verifyEmailCode({ receipt, code })
52
53
  ```
53
54
 
55
+ Login por e-mail e senha, só em app com contas próprias (modo exclusivo) e quando `mitra.passwordLoginEnabled` for `true`. A senha é digitada no popup da Mitra e nunca passa pelo código do app; chame direto do clique, antes de qualquer `await`, para o browser não bloquear o popup:
56
+
57
+ ```typescript
58
+ const user = await mitra.auth.signInWithPassword() // ou signUpWithPassword()
59
+ await mitra.auth.changePassword() // com a pessoa logada
60
+ const { resendAfterSeconds } = await mitra.auth.requestPasswordReset(email) // o link do e-mail abre a página da Mitra
61
+ ```
62
+
54
63
  Chat com agente:
55
64
 
56
65
  ```typescript
@@ -82,7 +91,9 @@ Falhas de API lançam `MitraApiError`, com `status`, `code`, `details` e `retryA
82
91
  | `403` | a pessoa não tem acesso ao recurso | confira as permissões dela no app |
83
92
  | `429`, `5xx` | limite de requisições ou falha no servidor | espere `retryAfterSeconds`, quando vier, e repita se a operação puder ser repetida |
84
93
  | `INVALID_CONFIGURATION` | argumento inválido, ou `requestEmailCode()` antes de `init()` | corrija o argumento ou chame `init()` no startup |
85
- | `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` com senha | use Google, Microsoft ou código por e-mail |
94
+ | `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` antigos, com senha no código do app | use `signInWithPassword()` ou `signUpWithPassword()` |
95
+ | `PASSWORD_CHANGED_SIGN_IN_AGAIN` | `changePassword()` trocou a senha, mas o novo login falhou; a sessão local já foi limpa | leve a pessoa ao login com a senha nova |
96
+ | `RATE_LIMITED`, `RATE_LIMIT_EXCEEDED` | `requestPasswordReset()` pedido vezes demais para o mesmo endereço (`RATE_LIMITED`) ou da mesma rede (`RATE_LIMIT_EXCEEDED`) | espere `retryAfterSeconds`, quando vier |
86
97
  | `INVALID_CODE` | o código digitado não confere | peça para a pessoa conferir o código |
87
98
  | `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, `MAGIC_LINK_INVALID` | o link do e-mail venceu, já foi usado ou não vale | peça um código novo |
88
99
  | `REDIRECT_NOT_ALLOWED` | o servidor respondeu com redirect | confira o `apiUrl` |
@@ -92,9 +103,9 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
92
103
 
93
104
  ## Boas práticas
94
105
 
95
- - Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled` e o login por e-mail dependem dele.
106
+ - Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled`, `passwordLoginEnabled` e o login por e-mail dependem dele.
96
107
  - Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()` ou `completeEmailSignInRedirect()` do método que você usa. Cada um devolve `null` quando a URL não é dele. O link do e-mail completa o login no mesmo browser que pediu o código; em outro aparelho, a pessoa digita o código.
97
- - A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa.
108
+ - A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa e, em app com contas próprias, encerra a sessão no servidor: o refresh token deixa de renovar, e o access token já emitido vale até vencer.
98
109
  - Alguns apps recebem tokens extras junto da sessão, em `auth.allTokens`, liberados app por app pela Mitra. O de backoffice é o mais sensível: ele carrega os acessos que a pessoa tem no backoffice da Mitra, vale uma hora e fica no mesmo `localStorage` da sessão, onde qualquer script do domínio do app consegue ler. Leia ele por `auth.ensureFreshBackofficeToken()`, que renova o token quando está perto de vencer e devolve `null` quando o app ou a pessoa não têm esse acesso. Use só contra o backoffice e não repasse para outro serviço.
99
110
  - O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
100
111
  - Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
package/dist/index.cjs CHANGED
@@ -150,7 +150,7 @@ var HttpClient = class {
150
150
  * ```
151
151
  */
152
152
  async request(path, options = {}) {
153
- const { method = "GET", body, headers = {}, params, isRetry } = options;
153
+ const { method = "GET", body, headers = {}, params, isRetry, keepalive } = options;
154
154
  const url = buildRequestUrl(this.baseUrl, path, params);
155
155
  if (!isRetry && this.tokenGetter() && this.beforeAuthenticatedRequest) {
156
156
  await this.beforeAuthenticatedRequest();
@@ -168,7 +168,8 @@ var HttpClient = class {
168
168
  method,
169
169
  headers: requestHeaders,
170
170
  body: body ? JSON.stringify(body) : void 0,
171
- redirect: "manual"
171
+ redirect: "manual",
172
+ ...keepalive ? { keepalive } : {}
172
173
  });
173
174
  if (response.redirected || response.type === "opaqueredirect") {
174
175
  const error = new MitraApiError(
@@ -456,6 +457,9 @@ async function resolveApiKeySession(publicClient, appId, apiKey) {
456
457
  // src/modules/auth-page-flow.ts
457
458
  var import_sdk_core2 = require("@mitralab.io/sdk-core");
458
459
  var RESULT_TYPE = "mitra-oauth-result";
460
+ var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
461
+ var SESSION_TYPE = "mitra-auth-session";
462
+ var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
459
463
  var FIVE_MINUTES_MS = 5 * 60 * 1e3;
460
464
  var TEN_MINUTES_MS = 10 * 60 * 1e3;
461
465
  var PROVIDERS = {
@@ -480,6 +484,17 @@ var PROVIDERS = {
480
484
  redirectStorage: "localStorage",
481
485
  pendingRequestTtlMs: TEN_MINUTES_MS,
482
486
  popupTimeoutMs: TEN_MINUTES_MS
487
+ },
488
+ // IAM answers a password login, signup or change with the same single-use
489
+ // exchange code the email flow gets. Signing up waits on a code read from a
490
+ // mailbox, hence the email timeout; there is no link, so nothing pending is
491
+ // written for another tab.
492
+ password: {
493
+ label: "Password",
494
+ exchangePath: "/api/v1/auth/magic-link/exchange",
495
+ sendsRedirectUri: false,
496
+ redirectStorage: "sessionStorage",
497
+ popupTimeoutMs: TEN_MINUTES_MS
483
498
  }
484
499
  };
485
500
  var POPUP_WIDTH = 480;
@@ -552,6 +567,7 @@ var AuthPageFlow = class {
552
567
  providerLabel;
553
568
  redirectStorageKey;
554
569
  popupPromise = null;
570
+ popupView;
555
571
  constructor(config) {
556
572
  this.appId = config.appId;
557
573
  this.apiUrl = stripTrailingSlashes(config.apiUrl);
@@ -570,9 +586,24 @@ var AuthPageFlow = class {
570
586
  if (options.mode !== void 0 && options.mode !== "popup") {
571
587
  return Promise.reject(new Error(`Unsupported ${this.providerLabel} sign-in mode: ${String(options.mode)}`));
572
588
  }
573
- if (this.popupPromise) return this.popupPromise;
574
- this.popupPromise = this.startPopup(browserWindow).finally(() => {
589
+ return this.signInWithPopup({});
590
+ }
591
+ /**
592
+ * Opens the auth page in a popup on the given screen. A second call while the
593
+ * popup is open joins it when it asks for the same screen, and is refused
594
+ * otherwise: both would share one browser window, and the second would
595
+ * navigate it away from the first.
596
+ */
597
+ signInWithPopup(request) {
598
+ const browserWindow = this.requireBrowser();
599
+ if (this.popupPromise) {
600
+ if (this.popupView === request.view) return this.popupPromise;
601
+ return Promise.reject(new Error(`Another ${this.providerLabel} popup is already open.`));
602
+ }
603
+ this.popupView = request.view;
604
+ this.popupPromise = this.startPopup(browserWindow, request).finally(() => {
575
605
  this.popupPromise = null;
606
+ this.popupView = void 0;
576
607
  });
577
608
  return this.popupPromise;
578
609
  }
@@ -638,7 +669,7 @@ var AuthPageFlow = class {
638
669
  }
639
670
  return this.exchangeCode(code, context.redirectUri);
640
671
  }
641
- async startPopup(browserWindow) {
672
+ async startPopup(browserWindow, request) {
642
673
  const state = this.generateState();
643
674
  const authPageUrl = resolveAuthPageUrl(
644
675
  this.apiUrl,
@@ -652,8 +683,17 @@ var AuthPageFlow = class {
652
683
  this.newRedirectContext(state, this.getRedirectUri(authPageUrl))
653
684
  );
654
685
  }
655
- const popup = this.openPopup(browserWindow, this.buildStartUrl(browserWindow, authPageUrl, state));
656
- const result = await this.waitForPopupResult(browserWindow, popup, authPageUrl.origin, state);
686
+ const popup = this.openPopup(
687
+ browserWindow,
688
+ this.buildStartUrl(browserWindow, authPageUrl, state, request.view)
689
+ );
690
+ const result = await this.waitForPopupResult(
691
+ browserWindow,
692
+ popup,
693
+ authPageUrl.origin,
694
+ state,
695
+ request.sessionToken
696
+ );
657
697
  if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
658
698
  if (result.code) return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl));
659
699
  return expectAuthTokenResponse(result.token);
@@ -734,7 +774,7 @@ var AuthPageFlow = class {
734
774
  });
735
775
  return expectAuthTokenResponse(response);
736
776
  }
737
- buildStartUrl(browserWindow, authPageUrl, state) {
777
+ buildStartUrl(browserWindow, authPageUrl, state, view) {
738
778
  const startUrl = new URL(authPageUrl);
739
779
  startUrl.searchParams.set("provider", this.provider);
740
780
  startUrl.searchParams.set("state", state);
@@ -742,6 +782,7 @@ var AuthPageFlow = class {
742
782
  startUrl.searchParams.set("apiUrl", this.apiUrl);
743
783
  startUrl.searchParams.set("origin", browserWindow.location.origin);
744
784
  startUrl.searchParams.set("responseType", "code");
785
+ if (view) startUrl.searchParams.set("view", view);
745
786
  return startUrl;
746
787
  }
747
788
  getRedirectUri(authPageUrl) {
@@ -798,7 +839,7 @@ var AuthPageFlow = class {
798
839
  }
799
840
  return popup;
800
841
  }
801
- waitForPopupResult(browserWindow, popup, expectedOrigin, expectedState) {
842
+ waitForPopupResult(browserWindow, popup, expectedOrigin, expectedState, sessionToken) {
802
843
  return new Promise((resolve, reject) => {
803
844
  const timeout = globalThis.setTimeout(() => {
804
845
  cleanup();
@@ -810,31 +851,33 @@ var AuthPageFlow = class {
810
851
  reject(new Error(`${this.providerLabel} sign-in was cancelled.`));
811
852
  }
812
853
  }, POPUP_CLOSED_POLL_MS);
854
+ let settled = false;
855
+ const handOverSession = async (readToken) => {
856
+ const accessToken = await readToken().catch(() => null);
857
+ if (settled) return;
858
+ if (!accessToken) {
859
+ cleanup();
860
+ reject(new Error(`${this.providerLabel} popup needs a signed-in session.`));
861
+ return;
862
+ }
863
+ popup.postMessage({ type: SESSION_TYPE, state: expectedState, accessToken }, expectedOrigin);
864
+ };
813
865
  const onMessage = (event) => {
814
866
  if (event.origin !== expectedOrigin || event.source !== popup) return;
815
867
  if (!event.data || typeof event.data !== "object") return;
816
868
  const data = event.data;
817
- if (data.type !== RESULT_TYPE) return;
818
- if (data.state !== expectedState) {
819
- cleanup();
820
- reject(new Error(`Invalid ${this.providerLabel} sign-in state (possible CSRF).`));
821
- return;
822
- }
823
- if (data.success !== true) {
824
- cleanup();
825
- reject(new Error(typeof data.error === "string" && data.error.trim() ? data.error : `${this.providerLabel} sign-in failed.`));
826
- return;
827
- }
828
- const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
829
- if (!code && data.token === void 0) {
830
- cleanup();
831
- reject(new Error(`${this.providerLabel} auth page returned neither code nor token.`));
869
+ if (data.type === SESSION_REQUEST_TYPE) {
870
+ if (sessionToken && data.state === expectedState) void handOverSession(sessionToken);
832
871
  return;
833
872
  }
873
+ if (data.type !== RESULT_TYPE) return;
874
+ const outcome = readPopupResult(data, expectedState, this.providerLabel);
834
875
  cleanup();
835
- resolve({ ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} });
876
+ if ("error" in outcome) reject(outcome.error);
877
+ else resolve(outcome.value);
836
878
  };
837
879
  const cleanup = () => {
880
+ settled = true;
838
881
  globalThis.clearTimeout(timeout);
839
882
  globalThis.clearInterval(closedPoll);
840
883
  browserWindow.removeEventListener("message", onMessage);
@@ -890,6 +933,30 @@ var AuthPageFlow = class {
890
933
  return globalThis.window;
891
934
  }
892
935
  };
936
+ function readPopupResult(data, expectedState, providerLabel) {
937
+ if (data.state !== expectedState) {
938
+ return { error: new Error(`Invalid ${providerLabel} sign-in state (possible CSRF).`) };
939
+ }
940
+ if (data.success !== true && data.passwordChanged === true) {
941
+ return {
942
+ error: new MitraApiError(
943
+ "The password was changed, but signing in again failed. Sign in with the new password.",
944
+ 401,
945
+ PASSWORD_CHANGED_SIGN_IN_AGAIN
946
+ )
947
+ };
948
+ }
949
+ if (data.success !== true) {
950
+ return {
951
+ error: new Error(typeof data.error === "string" && data.error.trim() ? data.error : `${providerLabel} sign-in failed.`)
952
+ };
953
+ }
954
+ const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
955
+ if (!code && data.token === void 0) {
956
+ return { error: new Error(`${providerLabel} auth page returned neither code nor token.`) };
957
+ }
958
+ return { value: { ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} } };
959
+ }
893
960
 
894
961
  // src/modules/email-code-flow.ts
895
962
  var import_sdk_core3 = require("@mitralab.io/sdk-core");
@@ -1100,6 +1167,8 @@ var EmailCodeFlow = class {
1100
1167
 
1101
1168
  // src/modules/auth.ts
1102
1169
  var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
1170
+ var LOGOUT_PATH = "/api/v1/auth/logout";
1171
+ var PASSWORD_RESET_PATH = "/api/v1/auth/password/reset";
1103
1172
  var DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS = 6e4;
1104
1173
  var sessionPorts = /* @__PURE__ */ new WeakMap();
1105
1174
  function getAuthSessionPort(auth) {
@@ -1129,6 +1198,22 @@ function subjectOf(token) {
1129
1198
  const sub = decodeJwtPayload(token)?.sub;
1130
1199
  return typeof sub === "string" && sub !== "" ? sub : null;
1131
1200
  }
1201
+ function isExclusiveAppSession(refreshToken) {
1202
+ return decodeJwtPayload(refreshToken)?.login_mode === "exclusive";
1203
+ }
1204
+ function expectPasswordResetRequestResult(value) {
1205
+ const response = (0, import_sdk_core4.expectObject)(
1206
+ value,
1207
+ "Password reset request response",
1208
+ coreErrors
1209
+ );
1210
+ if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
1211
+ throw coreErrors.invalidResponse(
1212
+ "Password reset request response has an invalid resendAfterSeconds field"
1213
+ );
1214
+ }
1215
+ return { resendAfterSeconds: response.resendAfterSeconds };
1216
+ }
1132
1217
  function isTokenExpiring(token, minValidityMs) {
1133
1218
  const exp = decodeJwtPayload(token)?.exp;
1134
1219
  if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
@@ -1171,6 +1256,7 @@ var AuthModule = class {
1171
1256
  googleAuth;
1172
1257
  microsoftAuth;
1173
1258
  emailAuth;
1259
+ passwordAuth;
1174
1260
  emailCode;
1175
1261
  brand = null;
1176
1262
  constructor(appId, iamBaseUrl, options = {}) {
@@ -1209,6 +1295,13 @@ var AuthModule = class {
1209
1295
  client: this.publicClient,
1210
1296
  provider: "email"
1211
1297
  });
1298
+ this.passwordAuth = new AuthPageFlow({
1299
+ appId,
1300
+ apiUrl,
1301
+ authPageUrl: options.authPageUrl,
1302
+ client: this.publicClient,
1303
+ provider: "password"
1304
+ });
1212
1305
  this.emailCode = new EmailCodeFlow({
1213
1306
  appId,
1214
1307
  client: this.publicClient,
@@ -1258,11 +1351,14 @@ var AuthModule = class {
1258
1351
  get isAuthenticated() {
1259
1352
  return this._currentUser !== null && this.#accessToken !== null;
1260
1353
  }
1261
- /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
1354
+ /**
1355
+ * @deprecated The password never goes through the app's code. Use
1356
+ * signInWithPassword(), which opens the Mitra auth page, signInWithEmail() or SSO.
1357
+ */
1262
1358
  signIn(_credentials) {
1263
1359
  return Promise.reject(
1264
1360
  new MitraApiError(
1265
- "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1361
+ "Email/password authentication is not available. Use signInWithPassword(), signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1266
1362
  0,
1267
1363
  "UNSUPPORTED_AUTH_METHOD"
1268
1364
  )
@@ -1506,19 +1602,150 @@ var AuthModule = class {
1506
1602
  const tokenResponse = await this.emailAuth.completeRedirect();
1507
1603
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1508
1604
  }
1509
- /** @deprecated Email/password registration is not implemented by IAM. Use signInWithEmail() or SSO. */
1605
+ /**
1606
+ * @deprecated The password never goes through the app's code. Use
1607
+ * signUpWithPassword(), which opens the Mitra auth page, signInWithEmail() or SSO.
1608
+ */
1510
1609
  signUp(_data) {
1511
1610
  return Promise.reject(
1512
1611
  new MitraApiError(
1513
- "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1612
+ "Email/password registration is not available. Use signUpWithPassword(), signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1514
1613
  0,
1515
1614
  "UNSUPPORTED_AUTH_METHOD"
1516
1615
  )
1517
1616
  );
1518
1617
  }
1618
+ /**
1619
+ * Signs in with email and password, typed into the Mitra auth page in a popup.
1620
+ * The password never reaches the app's code: the page sends it to IAM and
1621
+ * hands back a single-use exchange code, redeemed like the email sign-in.
1622
+ *
1623
+ * Offer it only when `mitra.passwordLoginEnabled` is `true`, which needs an
1624
+ * app whose accounts are its own (exclusive login mode). Call it straight
1625
+ * from the click handler, before any `await`, or the browser blocks the popup.
1626
+ *
1627
+ * @returns The authenticated and hydrated user.
1628
+ * @throws {MitraApiError} When IAM rejects the exchange code.
1629
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
1630
+ * out, or the response fails origin, source, state, or shape validation. Wrong
1631
+ * credentials are answered on the auth page itself, not here.
1632
+ *
1633
+ * @example
1634
+ * ```typescript
1635
+ * const user = await mitra.auth.signInWithPassword();
1636
+ * ```
1637
+ */
1638
+ async signInWithPassword() {
1639
+ return this.establishSession(await this.passwordAuth.signInWithPopup({ view: "login" }));
1640
+ }
1641
+ /**
1642
+ * Creates a password for an app account, on the Mitra auth page in a popup:
1643
+ * the page asks for the address, sends a code to it to prove the mailbox is
1644
+ * the person's, and takes the password with that code. The person ends signed
1645
+ * in, as with {@link signInWithPassword}.
1646
+ *
1647
+ * @returns The authenticated and hydrated user.
1648
+ * @throws The same errors as {@link signInWithPassword}.
1649
+ *
1650
+ * @example
1651
+ * ```typescript
1652
+ * const user = await mitra.auth.signUpWithPassword();
1653
+ * ```
1654
+ */
1655
+ async signUpWithPassword() {
1656
+ return this.establishSession(await this.passwordAuth.signInWithPopup({ view: "signup" }));
1657
+ }
1658
+ /**
1659
+ * Changes the password of the signed-in person, on the Mitra auth page in a
1660
+ * popup. The page asks for the current and the new password itself, so the
1661
+ * app never sees either one.
1662
+ *
1663
+ * The page acts on this session, so it asks for the access token once it
1664
+ * loads, and the SDK answers with `postMessage` to the auth page origin only:
1665
+ * the token never goes in the popup URL.
1666
+ *
1667
+ * IAM ends every session of the account when the password changes, this one
1668
+ * included, so the page signs in again with the new password and hands back a
1669
+ * new session, which replaces the current one.
1670
+ *
1671
+ * When the change goes through but that new sign-in fails, the call rejects
1672
+ * with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared,
1673
+ * since IAM already ended it: send the person to sign in with the new password.
1674
+ *
1675
+ * @returns The user of the new session.
1676
+ * @throws {MitraApiError} `401` when nobody is signed in, and
1677
+ * `PASSWORD_CHANGED_SIGN_IN_AGAIN` (status `401`) as above.
1678
+ * @throws The same errors as {@link signInWithPassword}, and an error when the
1679
+ * session ends while the popup is open.
1680
+ *
1681
+ * @example
1682
+ * ```typescript
1683
+ * await mitra.auth.changePassword();
1684
+ * ```
1685
+ */
1686
+ async changePassword() {
1687
+ if (!this.#accessToken) {
1688
+ throw new MitraApiError("Sign in before changing the password.", 401);
1689
+ }
1690
+ const sessionToken = async () => {
1691
+ await this.ensureFreshSession();
1692
+ return this.#accessToken;
1693
+ };
1694
+ const generation = this.sessionGeneration;
1695
+ let tokenResponse;
1696
+ try {
1697
+ tokenResponse = await this.passwordAuth.signInWithPopup({ view: "change", sessionToken });
1698
+ } catch (error) {
1699
+ if (error instanceof MitraApiError && error.code === PASSWORD_CHANGED_SIGN_IN_AGAIN && generation === this.sessionGeneration) {
1700
+ this.clearAuthState();
1701
+ }
1702
+ throw error;
1703
+ }
1704
+ return this.establishSession(tokenResponse);
1705
+ }
1706
+ /**
1707
+ * Asks IAM to email a link to set a new password. Only the address goes: the
1708
+ * link opens the Mitra auth page, where the new password is typed, so there
1709
+ * is no method here to confirm the reset.
1710
+ *
1711
+ * IAM answers the same whether or not the address has an account, so this
1712
+ * resolves without saying which.
1713
+ *
1714
+ * @param email - The address of the account.
1715
+ * @param options - The language of the message.
1716
+ * @returns How long the application should wait before offering to resend.
1717
+ * @throws {MitraApiError} `RATE_LIMITED` when this address asked too often,
1718
+ * and `RATE_LIMIT_EXCEEDED` when this network did, both with
1719
+ * `retryAfterSeconds` when IAM sends it.
1720
+ *
1721
+ * @example
1722
+ * ```typescript
1723
+ * const { resendAfterSeconds } = await mitra.auth.requestPasswordReset('person@example.com');
1724
+ * ```
1725
+ */
1726
+ async requestPasswordReset(email, options = {}) {
1727
+ if (globalThis.window === void 0) {
1728
+ throw new Error("Password reset is only available in a browser.");
1729
+ }
1730
+ const browserWindow = globalThis.window;
1731
+ return expectPasswordResetRequestResult(
1732
+ await this.publicClient.post(PASSWORD_RESET_PATH, {
1733
+ email,
1734
+ appId: this.appId,
1735
+ origin: browserWindow.location.origin,
1736
+ language: resolveLanguage(options.language, browserWindow)
1737
+ })
1738
+ );
1739
+ }
1519
1740
  /**
1520
1741
  * Signs out the current user, clearing all auth state and localStorage.
1521
1742
  *
1743
+ * In an app whose accounts are its own, the session also ends on the server:
1744
+ * the refresh token is sent to IAM's logout, so it can no longer be renewed.
1745
+ * The local state is cleared right away whatever IAM answers, and the request
1746
+ * survives a navigation to `redirectUrl`. The access token already issued
1747
+ * stays valid until it expires.
1748
+ *
1522
1749
  * @param redirectUrl - Optional URL to navigate to after sign-out.
1523
1750
  *
1524
1751
  * @example
@@ -1528,7 +1755,11 @@ var AuthModule = class {
1528
1755
  * ```
1529
1756
  */
1530
1757
  signOut(redirectUrl) {
1758
+ const refreshToken = this.#refreshToken;
1531
1759
  this.clearAuthState();
1760
+ if (refreshToken && isExclusiveAppSession(refreshToken)) {
1761
+ this.endServerSession(refreshToken);
1762
+ }
1532
1763
  if (globalThis.window !== void 0 && redirectUrl) {
1533
1764
  globalThis.window.location.href = redirectUrl;
1534
1765
  }
@@ -1857,6 +2088,10 @@ var AuthModule = class {
1857
2088
  this.listeners.delete(callback);
1858
2089
  };
1859
2090
  }
2091
+ /** Best effort: the person asked to leave, and that already happened locally. */
2092
+ endServerSession(refreshToken) {
2093
+ this.publicClient.request(LOGOUT_PATH, { method: "POST", body: { refreshToken }, keepalive: true }).catch(() => void 0);
2094
+ }
1860
2095
  async doRefresh(generation, refreshToken) {
1861
2096
  let tokenResponse;
1862
2097
  try {
@@ -2349,11 +2584,9 @@ function holdSendsWhileOffline(session, outbox) {
2349
2584
  };
2350
2585
  },
2351
2586
  send: (prompt, options) => {
2352
- if (passThrough(prompt)) {
2353
- session.send(prompt, options);
2354
- return;
2355
- }
2587
+ if (passThrough(prompt)) return session.send(prompt, options);
2356
2588
  void outbox.holdUntilOnline(session, session.taskId, () => session.send(prompt, options)).catch(() => void 0);
2589
+ return void 0;
2357
2590
  },
2358
2591
  sendAndWait: (prompt, options) => {
2359
2592
  if (passThrough(prompt)) return session.sendAndWait(prompt, options);
@@ -2725,6 +2958,7 @@ function expectAppInfoResponse(value) {
2725
2958
  // answers without this field, and an app that cannot prove it is enabled
2726
2959
  // should stop offering the option, not stop starting.
2727
2960
  emailLoginEnabled: response.emailLoginEnabled === true,
2961
+ passwordLoginEnabled: response.passwordLoginEnabled === true,
2728
2962
  // Same reasoning, and the brand is never guessed: without it the headless
2729
2963
  // email methods refuse instead of asking IAM to brand a message at random.
2730
2964
  brand: typeof response.brand === "string" && response.brand.trim() ? response.brand : null
@@ -2803,6 +3037,7 @@ function createClient(config) {
2803
3037
  let initialized = false;
2804
3038
  let allowSignup = true;
2805
3039
  let emailLoginEnabled = false;
3040
+ let passwordLoginEnabled = false;
2806
3041
  async function init() {
2807
3042
  if (initialized) return;
2808
3043
  const publicClient = new HttpClient({
@@ -2822,6 +3057,7 @@ function createClient(config) {
2822
3057
  }
2823
3058
  allowSignup = appInfo.allowSignup;
2824
3059
  emailLoginEnabled = appInfo.emailLoginEnabled;
3060
+ passwordLoginEnabled = appInfo.passwordLoginEnabled;
2825
3061
  initialized = true;
2826
3062
  }
2827
3063
  return {
@@ -2840,6 +3076,9 @@ function createClient(config) {
2840
3076
  get emailLoginEnabled() {
2841
3077
  return emailLoginEnabled;
2842
3078
  },
3079
+ get passwordLoginEnabled() {
3080
+ return passwordLoginEnabled;
3081
+ },
2843
3082
  config
2844
3083
  };
2845
3084
  }