@mitralab.io/platform-sdk 1.9.0-beta.1 → 1.9.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.9.0-beta.2
6
+
7
+ App files through `client.files`, and a single sign-in screen with every method the app has.
8
+
9
+ - Depend on `@mitralab.io/sdk-core@0.3.10` for its `files` module, exposed as `client.files`: app
10
+ files kept by the Data Manager under `/data-manager/api/v1/files`. `upload(fileOrBlob, options)`
11
+ requests the upload, sends the bytes to the signed link and confirms, resolving only with the
12
+ `READY` file; `requestUpload` and `confirmUpload` are the steps on their own. `get`, `getUrl`,
13
+ `getUrls` (1 to 100 ids), `download` and `delete` complete the module.
14
+ - The API calls go through the Data Manager client of this SDK, with the session token,
15
+ `X-App-Id`, the renewal before the request and the global `onError`. The bytes go to the signed
16
+ link through the global `fetch`, without `Authorization`, `X-App-Id` or any other header this SDK
17
+ adds: the link is the credential, and storage gets only the headers the API signed it with.
18
+ - An API refusal rejects with `MitraApiError`. A failure after the upload request rejects with the
19
+ Core `FileTransferError` (`step` `send`, `confirm` or `download`), now exported by this package,
20
+ and never carries the link; a failed send deletes the pending file first. A `signal` stops the
21
+ transfer with storage and the call rejects with `signal.reason` (`AbortError`, or `TimeoutError`
22
+ from `AbortSignal.timeout`). The transfer with storage does not reach `onError`.
23
+ - New exported types: `FilesModule`, `FileUploadOptions`, `FileDownloadOptions`, `FileMetadata`,
24
+ `FileKind`, `FileVisibility`, `FileStatus`, `FileCreator`, `FileUpload`, `FileUploadInput`,
25
+ `FileReadUrl`, `FileReadUrlItem`, `FileReadUrlOptions`, `FileReadUrls` and `FileTransferStep`.
26
+ - `auth.signInWithAuthPage({ mode? })` opens the Mitra sign-in page, in a popup or by redirect, on
27
+ a choice screen with the methods the app has: Google and Microsoft always, password and e-mail
28
+ code when the app has them on. The person chooses there, and the SDK exchanges the code through
29
+ the route of the chosen method. It is optional: an app that does not call it stays the same. In
30
+ `redirect` mode, and for the tab opened by the e-mail link, call
31
+ `auth.completeAuthPageSignInRedirect()` at startup; it returns `null` when the URL is not its
32
+ own. The pending request stays in `localStorage` for 10 minutes under
33
+ `mitra_all_redirect_{appId}`: the single-use state and the page address, never a token. An answer
34
+ from the page without the chosen method is refused, and the code is not exchanged.
35
+
5
36
  ## 1.9.0-beta.1
6
37
 
7
38
  Sign-in through an identity connection by redirect, for an app opened directly in the browser,
package/README.md CHANGED
@@ -36,7 +36,7 @@ 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`), código por e-mail ou e-mail e senha (`signInWithPassword` no popup da Mitra, ou `signInWithPasswordForm` no formulário do próprio app), mais `currentUser`, `onAuthStateChange` e `signOut`.
39
+ - `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`), código por e-mail ou e-mail e senha (`signInWithPassword` no popup da Mitra, ou `signInWithPasswordForm` no formulário do próprio app), ou todos numa tela só (`signInWithAuthPage`), 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.
@@ -46,6 +46,7 @@ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já v
46
46
  `loadOlder()` traz a página anterior do histórico e põe antes de `history`; `hasOlder` diz se ainda há mais antiga.
47
47
  - `agentCredentials`: credenciais de provedor de IA e modelos disponíveis. `providers(agentId?)` devolve numa chamada só os provedores em que o próximo turno pode rodar, cada um com os modelos e a última leitura da assinatura.
48
48
  - `aiProviders.get()`: consulta tipada de `GET /copilot/api/v1/ai-providers`, com o token da sessão e o `X-App-Id` do cliente. Retorna engine ativa, quota pessoal, provedores personalizados, conexão OpenCode e `managedAiProfile`. O módulo oferece somente leitura: não altera preferências, cria tarefas ou conecta provedores.
49
+ - `files`: arquivos do app, com `upload`, `get`, `getUrl`, `getUrls`, `download` e `delete`, mais os passos `requestUpload` e `confirmUpload` (ver [Arquivos do app](#arquivos-do-app)).
49
50
 
50
51
  `managedAiProfile` é `null` quando inelegível e pode estar ausente em backends anteriores. Quando o Copilot oferece Immersion, o perfil traz `profile: "IMMERSION"`, `agentType: "IMMERSION"`, `selectionMode: "FORCED"`, `model: "immersion"` e `requiredScope: "ACCOUNT"`. A leitura preserva a engine ativa e a quota pessoal; não calcula elegibilidade com base nelas. Falhas, inclusive `404` de backend sem a rota, chegam como `MitraApiError`.
51
52
 
@@ -58,6 +59,22 @@ const { receipt } = await mitra.auth.requestEmailCode({ email })
58
59
  const user = await mitra.auth.verifyEmailCode({ receipt, code })
59
60
  ```
60
61
 
62
+ ### Tela única de login
63
+
64
+ `signInWithAuthPage()` abre a página de login da Mitra numa tela de escolha, com os métodos que o app tem: Google e Microsoft sempre, e senha e código por e-mail quando estão ligados no app. A pessoa escolhe lá, e o SDK troca o código pela rota do método escolhido, como o método sozinho faria. É opcional: o app que não chama esse método continua igual. Chame direto do clique, antes de qualquer `await`, para o browser não bloquear o popup:
65
+
66
+ ```typescript
67
+ const user = await mitra.auth.signInWithAuthPage() // popup
68
+ await mitra.auth.signInWithAuthPage({ mode: "redirect" })
69
+
70
+ // no startup, para o modo redirect e para a aba aberta pelo link do e-mail
71
+ const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect()
72
+ ```
73
+
74
+ - Como a pessoa pode escolher o código por e-mail, o pedido pendente fica no `localStorage` por 10 minutos, na chave `mitra_all_redirect_{appId}`, como no `signInWithEmail()`: o state de uso único e o endereço da página, nunca um token. O popup também espera até 10 minutos.
75
+ - Se a pessoa terminar pelo link do e-mail em outra aba, o popup não recebe o resultado e a chamada termina por tempo esgotado; trate como popup cancelado.
76
+ - Uma resposta da página sem o método escolhido é recusada, e o código não é trocado.
77
+
61
78
  ### Login por e-mail e senha
62
79
 
63
80
  Só em app com contas próprias (modo exclusivo) e quando `mitra.passwordLoginEnabled` for `true`. O dono do app escolhe um de dois modos, app a app.
@@ -142,13 +159,63 @@ const { content } = await chat.sendAndWait("Resuma os pedidos de hoje")
142
159
  chat.close()
143
160
  ```
144
161
 
162
+ ### Arquivos do app
163
+
164
+ Os arquivos que a pessoa envia pelo app ficam no storage da Mitra, registrados pelo Data Manager. Os bytes não passam pela API: o browser manda e lê direto do storage por um link assinado, que vale poucos minutos, e a API só autoriza e registra. As chamadas à API levam o token da sessão e o `X-App-Id`; o envio e o download saem pelo `fetch` do browser sem eles, porque o link já é a credencial.
165
+
166
+ Envio a partir de um `<input type="file">`:
167
+
168
+ ```typescript
169
+ // <input type="file" id="attachment"> e <button id="cancel">
170
+ const input = document.querySelector<HTMLInputElement>("#attachment")!
171
+ const cancel = document.querySelector<HTMLButtonElement>("#cancel")!
172
+
173
+ input.addEventListener("change", async () => {
174
+ const picked = input.files?.[0]
175
+ if (!picked) return
176
+
177
+ const sending = new AbortController()
178
+ cancel.onclick = () => sending.abort()
179
+ try {
180
+ const file = await mitra.files.upload(picked, {
181
+ kind: "PERMANENT",
182
+ visibility: "PRIVATE",
183
+ signal: sending.signal,
184
+ })
185
+ await mitra.entities.Attachment.create({ fileId: file.id, name: file.name })
186
+ } catch (error) {
187
+ if (error instanceof DOMException && error.name === "AbortError") return
188
+ throw error
189
+ }
190
+ })
191
+ ```
192
+
193
+ Quem lê o arquivo depende da visibilidade, não de quem tem o `fileId`: `PRIVATE` só quem enviou, `APP` qualquer pessoa do app, `RESTRICTED` quem enviou e quem a regra do app liberar, por uma Server Function que roda em nome de um usuário; a execução pública de uma Server Function não recebe o link.
194
+
195
+ Exibição pelo link de leitura:
196
+
197
+ ```typescript
198
+ // <img id="preview">
199
+ const { url } = await mitra.files.getUrl(attachment.fileId)
200
+ document.querySelector<HTMLImageElement>("#preview")!.src = url
201
+ ```
202
+
203
+ - `upload` pede o envio com o nome, o tipo e o tamanho do `File`, manda os bytes ao link com os headers que a API devolveu e confirma; só resolve com o arquivo `READY`. Um `Blob` que não é `File` precisa de `name` nas opções.
204
+ - `kind`: `TEMPORARY` vence 7 dias depois do pedido de envio, `PERMANENT` fica até ser apagado.
205
+ - Guarde o `id`, nunca o link: ele vence e autoriza sozinho quem o tiver. O link de `PRIVATE` e `RESTRICTED` vale 5 minutos e não se estende; o de `APP` aceita `expiresInSeconds` até 1 hora. Peça o link na hora de exibir, e peça outro quando uma imagem voltar a montar depois do prazo, pelo `expiresAt` ou no `onerror` do `<img>`. Para várias imagens, `getUrls(ids)` traz até 100 numa chamada. Aberto direto numa aba, o link baixa o arquivo com o nome original. `download(fileId)` devolve o conteúdo como `Blob`.
206
+ - Recusa da API chega como `MitraApiError`, como nas outras chamadas: `FILE_TOO_LARGE`, `FILE_QUOTA_REACHED` e `FILE_PENDING_LIMIT_REACHED` no pedido de envio, `NOT_FOUND` para arquivo que a pessoa não pode ler.
207
+ - Falha depois do pedido de envio chega como `FileTransferError`, com `step` (`send`, `confirm` ou `download`) e `fileId`, e nunca carrega o link. No `send`, o `upload` já apagou o arquivo pendente quando `cleanedUp` é `true`; com `false`, apague com `files.delete(fileId)`. No `confirm`, os bytes já estão no storage: confirme de novo com `files.confirmUpload(fileId)` ou apague. A exclusão que limpa um envio que falhou é uma chamada à plataforma como as outras, então a falha dela passa pelo `onError`; o erro do envio já traz `cleanedUp: false`.
208
+ - O `signal` interrompe só a transferência dos bytes, e a chamada rejeita com o `signal.reason`, como o `fetch`: `AbortError` no `abort()` do exemplo. Um envio cancelado no meio já tentou apagar o arquivo pendente, que vence sozinho em 24 horas se a exclusão falhar. Sem `signal`, o browser não dá prazo à transferência. Um prazo por `AbortSignal.timeout(ms)` rejeita com `TimeoutError`, mas conta desde a criação do sinal, pedido de envio incluído, e corta um envio legítimo de 25 MiB numa rede lenta: dimensione pelo tamanho do arquivo.
209
+
210
+ O comportamento completo, com as garantias sobre o link e os erros, está no [README do Core](https://github.com/mitralab-dev/mitra-core-sdk#arquivos-de-app), que este módulo usa sem mudar.
211
+
145
212
  ## Configuração
146
213
 
147
214
  | Campo | Obrigatório | Uso |
148
215
  |---|---|---|
149
216
  | `appId` | sim | ID do app no Code Studio |
150
217
  | `apiUrl` | sim | URL do API gateway da Mitra |
151
- | `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks`, `agentCredentials` e `aiProviders`; `init()`, login, `publicFunctions` e falha de rede não passam por ele e são tratados no `catch` de cada chamada |
218
+ | `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks`, `agentCredentials`, `aiProviders` e das chamadas de `files` à API, inclusive a exclusão que limpa um envio que falhou; `init()`, login, `publicFunctions`, a transferência de `files` com o storage e falha de rede não passam por ele e são tratados no `catch` de cada chamada |
152
219
  | `authPageUrl` | não | URL da página de login da Mitra; sem ela, o SDK descobre sozinho |
153
220
  | `apiKey` | não | chave padrão de `auth.signInWithApiKey()`; só em código de servidor, nunca no bundle do browser |
154
221
 
@@ -182,7 +249,7 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
182
249
  ## Boas práticas
183
250
 
184
251
  - Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled`, `passwordLoginEnabled` e o login por e-mail dependem dele.
185
- - 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. O login por conexão de identidade (Sankhya Pass), pelo iframe ou por redirect, dispensa essa chamada: o `init()` já completa.
252
+ - Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()`, `completeEmailSignInRedirect()` ou `completeAuthPageSignInRedirect()` 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. O login por conexão de identidade (Sankhya Pass), pelo iframe ou por redirect, dispensa essa chamada: o `init()` já completa.
186
253
  - A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. A do login por conexão de identidade fica no `sessionStorage` da aba, na mesma chave. `signOut()` limpa a sessão 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.
187
254
  - 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 storage 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.
188
255
  - O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ FileTransferError: () => import_sdk_core12.FileTransferError,
23
24
  MitraApiError: () => MitraApiError,
24
25
  callIntegrationMitra: () => import_mitra_interactions_sdk14.callIntegrationMitra,
25
26
  configureSdkMitra: () => import_mitra_interactions_sdk3.configureSdkMitra,
@@ -461,41 +462,59 @@ var RESULT_TYPE = "mitra-oauth-result";
461
462
  var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
462
463
  var SESSION_TYPE = "mitra-auth-session";
463
464
  var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
465
+ var AUTH_PAGE_METHODS = /* @__PURE__ */ new Set([
466
+ "google",
467
+ "microsoft",
468
+ "email",
469
+ "password"
470
+ ]);
471
+ function isAuthPageMethod(value) {
472
+ return typeof value === "string" && AUTH_PAGE_METHODS.has(value);
473
+ }
474
+ var EXCHANGE_ROUTES = {
475
+ google: { path: "/api/v1/auth/google", sendsRedirectUri: true },
476
+ microsoft: { path: "/api/v1/auth/microsoft", sendsRedirectUri: true },
477
+ email: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false },
478
+ password: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false }
479
+ };
464
480
  var FIVE_MINUTES_MS = 5 * 60 * 1e3;
465
481
  var TEN_MINUTES_MS = 10 * 60 * 1e3;
466
482
  var PROVIDERS = {
467
483
  google: {
468
484
  label: "Google",
469
- exchangePath: "/api/v1/auth/google",
470
- sendsRedirectUri: true,
485
+ exchange: EXCHANGE_ROUTES.google,
471
486
  redirectStorage: "sessionStorage",
472
487
  popupTimeoutMs: FIVE_MINUTES_MS
473
488
  },
474
489
  microsoft: {
475
490
  label: "Microsoft",
476
- exchangePath: "/api/v1/auth/microsoft",
477
- sendsRedirectUri: true,
491
+ exchange: EXCHANGE_ROUTES.microsoft,
478
492
  redirectStorage: "sessionStorage",
479
493
  popupTimeoutMs: FIVE_MINUTES_MS
480
494
  },
481
495
  email: {
482
496
  label: "Email",
483
- exchangePath: "/api/v1/auth/magic-link/exchange",
484
- sendsRedirectUri: false,
497
+ exchange: EXCHANGE_ROUTES.email,
485
498
  redirectStorage: "localStorage",
486
499
  pendingRequestTtlMs: TEN_MINUTES_MS,
487
500
  popupTimeoutMs: TEN_MINUTES_MS
488
501
  },
489
- // IAM answers a password login, signup or change with the same single-use
490
- // exchange code the email flow gets. Signing up waits on a code read from a
491
- // mailbox, hence the email timeout; there is no link, so nothing pending is
492
- // written for another tab.
502
+ // Signing up waits on a code read from a mailbox, hence the email timeout;
503
+ // there is no link, so nothing pending is written for another tab.
493
504
  password: {
494
505
  label: "Password",
495
- exchangePath: "/api/v1/auth/magic-link/exchange",
496
- sendsRedirectUri: false,
506
+ exchange: EXCHANGE_ROUTES.password,
497
507
  redirectStorage: "sessionStorage",
498
508
  popupTimeoutMs: TEN_MINUTES_MS
509
+ },
510
+ // The person may pick the email code on this screen, and its message carries
511
+ // a link that opens another tab, so this flow keeps the email lifetimes.
512
+ all: {
513
+ label: "Auth page",
514
+ exchange: "reportedMethod",
515
+ redirectStorage: "localStorage",
516
+ pendingRequestTtlMs: TEN_MINUTES_MS,
517
+ popupTimeoutMs: TEN_MINUTES_MS
499
518
  }
500
519
  };
501
520
  var POPUP_WIDTH = 480;
@@ -627,6 +646,7 @@ var AuthPageFlow = class {
627
646
  const code = params.get("codeMitra");
628
647
  const state = params.get("stateMitra");
629
648
  const error = params.get("errorMitra");
649
+ const reportedMethod = params.get("providerMitra");
630
650
  if (code === null && state === null && error === null) return null;
631
651
  const context = this.readRedirectContext(browserWindow);
632
652
  const hasState = state !== null && state.trim() !== "";
@@ -668,7 +688,7 @@ var AuthPageFlow = class {
668
688
  if (!code?.trim()) {
669
689
  throw new Error(`${this.providerLabel} sign-in redirect is missing code.`);
670
690
  }
671
- return this.exchangeCode(code, context.redirectUri);
691
+ return this.exchangeCode(code, context.redirectUri, this.readReportedMethod(reportedMethod));
672
692
  }
673
693
  async startPopup(browserWindow, request) {
674
694
  const state = this.generateState();
@@ -696,7 +716,10 @@ var AuthPageFlow = class {
696
716
  request.sessionToken
697
717
  );
698
718
  if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
699
- if (result.code) return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl));
719
+ const reportedMethod = this.readReportedMethod(result.method);
720
+ if (result.code) {
721
+ return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl), reportedMethod);
722
+ }
700
723
  return expectAuthTokenResponse(result.token);
701
724
  }
702
725
  startRedirect(browserWindow) {
@@ -767,14 +790,36 @@ var AuthPageFlow = class {
767
790
  redeemExchangeCode(code) {
768
791
  return this.exchangeCode(code, null);
769
792
  }
770
- async exchangeCode(code, redirectUri) {
771
- const response = await this.client.post(this.profile.exchangePath, {
793
+ async exchangeCode(code, redirectUri, reportedMethod) {
794
+ const route = this.exchangeRoute(reportedMethod);
795
+ const response = await this.client.post(route.path, {
772
796
  appId: this.appId,
773
797
  code,
774
- ...this.profile.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
798
+ ...route.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
775
799
  });
776
800
  return expectAuthTokenResponse(response);
777
801
  }
802
+ exchangeRoute(reportedMethod) {
803
+ if (this.profile.exchange !== "reportedMethod") return this.profile.exchange;
804
+ if (!reportedMethod) {
805
+ throw new Error("The all-methods sign-in cannot redeem a code without the method the auth page reported.");
806
+ }
807
+ return EXCHANGE_ROUTES[reportedMethod];
808
+ }
809
+ /**
810
+ * The method the auth page says produced the code. Only the flow that asked
811
+ * for the page with every method reads it: a single-method page sends no such
812
+ * field, and its own route is already known. Anything outside the known
813
+ * methods is refused rather than mapped to a route, since a code redeemed at
814
+ * the wrong route is spent for nothing.
815
+ */
816
+ readReportedMethod(value) {
817
+ if (this.profile.exchange !== "reportedMethod") return void 0;
818
+ if (!isAuthPageMethod(value)) {
819
+ throw new Error(`${this.providerLabel} did not report which sign-in method produced the code.`);
820
+ }
821
+ return value;
822
+ }
778
823
  buildStartUrl(browserWindow, authPageUrl, state, view) {
779
824
  const startUrl = new URL(authPageUrl);
780
825
  startUrl.searchParams.set("provider", this.provider);
@@ -815,7 +860,12 @@ var AuthPageFlow = class {
815
860
  if (!Number.isFinite(context.createdAt)) return true;
816
861
  return Date.now() - context.createdAt > ttlMs;
817
862
  }
818
- /** A one-time state that names the flow that created it, so its fragment is recognizable. */
863
+ /**
864
+ * A one-time state that names the flow that created it, so its fragment is
865
+ * recognizable. The auth page relies on the `all.` prefix too: the tab the
866
+ * email link opens has only the state to tell a chooser request apart, and
867
+ * answers it with `providerMitra=email`.
868
+ */
819
869
  generateState() {
820
870
  if (!globalThis.crypto?.getRandomValues) {
821
871
  throw new Error(`${this.providerLabel} sign-in requires crypto.getRandomValues.`);
@@ -954,9 +1004,15 @@ function readPopupResult(data, expectedState, providerLabel) {
954
1004
  }
955
1005
  const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
956
1006
  if (!code && data.token === void 0) {
957
- return { error: new Error(`${providerLabel} auth page returned neither code nor token.`) };
1007
+ return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
958
1008
  }
959
- return { value: { ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} } };
1009
+ return {
1010
+ value: {
1011
+ ...code ? { code } : {},
1012
+ ...data.token !== void 0 ? { token: data.token } : {},
1013
+ ...data.provider !== void 0 ? { method: data.provider } : {}
1014
+ }
1015
+ };
960
1016
  }
961
1017
 
962
1018
  // src/modules/email-code-flow.ts
@@ -1724,6 +1780,7 @@ var AuthModule = class {
1724
1780
  microsoftAuth;
1725
1781
  emailAuth;
1726
1782
  passwordAuth;
1783
+ authPage;
1727
1784
  emailCode;
1728
1785
  passwordForm;
1729
1786
  identityConnection;
@@ -1774,6 +1831,13 @@ var AuthModule = class {
1774
1831
  client: this.publicClient,
1775
1832
  provider: "password"
1776
1833
  });
1834
+ this.authPage = new AuthPageFlow({
1835
+ appId,
1836
+ apiUrl,
1837
+ authPageUrl: options.authPageUrl,
1838
+ client: this.publicClient,
1839
+ provider: "all"
1840
+ });
1777
1841
  this.emailCode = new EmailCodeFlow({
1778
1842
  appId,
1779
1843
  client: this.publicClient,
@@ -2086,6 +2150,62 @@ var AuthModule = class {
2086
2150
  const tokenResponse = await this.emailAuth.completeRedirect();
2087
2151
  return tokenResponse ? this.establishSession(tokenResponse) : null;
2088
2152
  }
2153
+ /**
2154
+ * Signs in on a single screen of the Mitra auth page that offers every method
2155
+ * the app has on: Google and Microsoft always, plus password and the email
2156
+ * code when the app has them enabled. The person picks one there, and
2157
+ * the page reports which; the code is redeemed at that method's IAM route,
2158
+ * exactly as the method's own sign-in would.
2159
+ *
2160
+ * Popup by default; redirect mode navigates away, and
2161
+ * {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
2162
+ * person may choose the email code, whose message carries a link that opens
2163
+ * a new tab, the pending request is kept in `localStorage` under
2164
+ * `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
2165
+ * auth page URL, never a token - as {@link signInWithEmail} does.
2166
+ *
2167
+ * Call it straight from the click handler, before any `await`, or the browser
2168
+ * blocks the popup.
2169
+ *
2170
+ * @param options - Popup or redirect mode.
2171
+ * @returns The authenticated and hydrated user in popup mode.
2172
+ * @throws {MitraApiError} When IAM rejects the exchange code.
2173
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
2174
+ * out, the response fails origin, source, state, or shape validation, or the
2175
+ * page does not say which method produced the code. A person who finishes
2176
+ * through the email link instead of the popup leaves this call to time out,
2177
+ * which the application should treat as a cancelled popup.
2178
+ *
2179
+ * @example
2180
+ * ```typescript
2181
+ * const user = await mitra.auth.signInWithAuthPage();
2182
+ * ```
2183
+ */
2184
+ async signInWithAuthPage(options = {}) {
2185
+ return this.establishSession(await this.authPage.signIn(options));
2186
+ }
2187
+ /**
2188
+ * Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
2189
+ * `#stateMitra` and `#providerMitra`, during application startup: the redirect
2190
+ * back to the tab that started it, or the tab the email link opened. The state
2191
+ * must match the request pending in this browser, as in
2192
+ * {@link completeEmailSignInRedirect}.
2193
+ *
2194
+ * @returns The authenticated user, or `null` when the URL carries no result,
2195
+ * or carries one that belongs to another sign-in method's flow.
2196
+ * @throws When the fragment belongs to this flow but its state does not match,
2197
+ * the request expired, the page reports an error, or it does not say which
2198
+ * method produced the code. The fragment is removed first.
2199
+ *
2200
+ * @example
2201
+ * ```typescript
2202
+ * const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
2203
+ * ```
2204
+ */
2205
+ async completeAuthPageSignInRedirect() {
2206
+ const tokenResponse = await this.authPage.completeRedirect();
2207
+ return tokenResponse ? this.establishSession(tokenResponse) : null;
2208
+ }
2089
2209
  /**
2090
2210
  * Completes a sign-in made through an identity connection, such as Sankhya
2091
2211
  * Pass, from the single-use code the platform bridge page leaves in the
@@ -3840,6 +3960,7 @@ function createClient(config) {
3840
3960
  );
3841
3961
  const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
3842
3962
  const aiProvidersModule = (0, import_sdk_core11.createAiProvidersModule)(copilotHttpClient, coreErrors);
3963
+ const filesModule = (0, import_sdk_core11.createFilesModule)(httpClient, {}, coreErrors);
3843
3964
  const integrationHttpClient = new HttpClient({
3844
3965
  baseUrl: integrationUrl,
3845
3966
  getToken: () => authModule.accessToken,
@@ -3900,6 +4021,7 @@ function createClient(config) {
3900
4021
  agentTasks: agentTasksModule,
3901
4022
  agentCredentials: agentCredentialsModule,
3902
4023
  aiProviders: aiProvidersModule,
4024
+ files: filesModule,
3903
4025
  integration: integrationModule,
3904
4026
  queries: queriesModule,
3905
4027
  get allowSignup() {
@@ -3915,6 +4037,9 @@ function createClient(config) {
3915
4037
  };
3916
4038
  }
3917
4039
 
4040
+ // src/index.ts
4041
+ var import_sdk_core12 = require("@mitralab.io/sdk-core");
4042
+
3918
4043
  // src/legacy/index.ts
3919
4044
  var import_mitra_interactions_sdk2 = require("mitra-interactions-sdk");
3920
4045
  var import_mitra_interactions_sdk3 = require("mitra-interactions-sdk");
@@ -3962,6 +4087,7 @@ var exchangeSsoCodeMitra = async (options) => {
3962
4087
  };
3963
4088
  // Annotate the CommonJS export names for ESM import in node:
3964
4089
  0 && (module.exports = {
4090
+ FileTransferError,
3965
4091
  MitraApiError,
3966
4092
  callIntegrationMitra,
3967
4093
  configureSdkMitra,
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, FunctionExecution, ListTemplateConfigsOptions, TemplateConfigPage, ProxyResult, ProxyInput, QueryResult, AgentCredentialOptions, CredentialStatus, AgentModel as AgentModel$1, AgentReadyProvider, CredentialUsage, OAuthStartResult, OAuthExchangeInput, AuthenticationResult, DeviceAuthorization, AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, PublicFunctionsModule, AgentTasksWithSessions, AiProvidersModule } from '@mitralab.io/sdk-core';
2
- export { AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, AgentCredentialOptions, AgentCredentialScope, AgentProviderUsage, AgentQueueItem, AgentReadyProvider, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskInput, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTurnResult, AgentTurnUsage, AgentTurnUsageRequest, AiProviders, AiProvidersModule, AuthenticationResult, CredentialStatus, CredentialUsage, CredentialUsageWindow, DeviceAuthorization, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionExecution, IncludedAiQuota, IncludedAiQuotaWindow, ListTemplateConfigsOptions, ManagedAiProfile, AgentMessage as NativeAgentMessage, AgentModel as NativeAgentModel, AgentTaskSession as NativeAgentTaskSession, AgentTimelineItem as NativeAgentTimelineItem, AgentToolEvent as NativeAgentToolEvent, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, OpencodeAiProvider, Page, PageOptions, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueryResult, TemplateConfigPage } from '@mitralab.io/sdk-core';
1
+ import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, FunctionExecution, ListTemplateConfigsOptions, TemplateConfigPage, ProxyResult, ProxyInput, QueryResult, AgentCredentialOptions, CredentialStatus, AgentModel as AgentModel$1, AgentReadyProvider, CredentialUsage, OAuthStartResult, OAuthExchangeInput, AuthenticationResult, DeviceAuthorization, AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, PublicFunctionsModule, AgentTasksWithSessions, AiProvidersModule, FilesModule } from '@mitralab.io/sdk-core';
2
+ export { AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, AgentCredentialOptions, AgentCredentialScope, AgentProviderUsage, AgentQueueItem, AgentReadyProvider, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskInput, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTurnResult, AgentTurnUsage, AgentTurnUsageRequest, AiProviders, AiProvidersModule, AuthenticationResult, CredentialStatus, CredentialUsage, CredentialUsageWindow, DeviceAuthorization, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FileCreator, FileDownloadOptions, FileKind, FileMetadata, FileReadUrl, FileReadUrlItem, FileReadUrlOptions, FileReadUrls, FileStatus, FileTransferError, FileTransferStep, FileUpload, FileUploadInput, FileUploadOptions, FileVisibility, FilesModule, FunctionExecution, IncludedAiQuota, IncludedAiQuotaWindow, ListTemplateConfigsOptions, ManagedAiProfile, AgentMessage as NativeAgentMessage, AgentModel as NativeAgentModel, AgentTaskSession as NativeAgentTaskSession, AgentTimelineItem as NativeAgentTimelineItem, AgentToolEvent as NativeAgentToolEvent, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, OpencodeAiProvider, Page, PageOptions, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueryResult, TemplateConfigPage } from '@mitralab.io/sdk-core';
3
3
  import * as LegacyTypes from 'mitra-interactions-sdk';
4
4
  import { exchangeSsoCodeMitra as exchangeSsoCodeMitra$1, loginMitra as loginMitra$1, loginWithGoogleMitra as loginWithGoogleMitra$1, loginWithMicrosoftMitra as loginWithMicrosoftMitra$1 } from 'mitra-interactions-sdk';
5
5
  export { callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, manageAgentChatMitra, manageAgentCredentialMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra } from 'mitra-interactions-sdk';
@@ -362,7 +362,8 @@ interface AuthModuleOptions {
362
362
  /**
363
363
  * Authentication module for managing user sessions.
364
364
  *
365
- * Handles Google and Microsoft SSO, email and password sign-in, trusted session adoption, sign-out,
365
+ * Handles Google and Microsoft SSO, email and password sign-in, the auth page screen that offers
366
+ * them all, trusted session adoption, sign-out,
366
367
  * and automatic token refresh.
367
368
  * Auth state is persisted to localStorage with key `mitra_auth_{appId}`
368
369
  * and restored on page reload; a session from an identity connection is kept
@@ -392,6 +393,7 @@ declare class AuthModule {
392
393
  private readonly microsoftAuth;
393
394
  private readonly emailAuth;
394
395
  private readonly passwordAuth;
396
+ private readonly authPage;
395
397
  private readonly emailCode;
396
398
  private readonly passwordForm;
397
399
  private readonly identityConnection;
@@ -621,6 +623,57 @@ declare class AuthModule {
621
623
  * `MAGIC_LINK_INVALID` when the link belongs here but cannot be used.
622
624
  */
623
625
  completeEmailSignInRedirect(): Promise<User | null>;
626
+ /**
627
+ * Signs in on a single screen of the Mitra auth page that offers every method
628
+ * the app has on: Google and Microsoft always, plus password and the email
629
+ * code when the app has them enabled. The person picks one there, and
630
+ * the page reports which; the code is redeemed at that method's IAM route,
631
+ * exactly as the method's own sign-in would.
632
+ *
633
+ * Popup by default; redirect mode navigates away, and
634
+ * {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
635
+ * person may choose the email code, whose message carries a link that opens
636
+ * a new tab, the pending request is kept in `localStorage` under
637
+ * `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
638
+ * auth page URL, never a token - as {@link signInWithEmail} does.
639
+ *
640
+ * Call it straight from the click handler, before any `await`, or the browser
641
+ * blocks the popup.
642
+ *
643
+ * @param options - Popup or redirect mode.
644
+ * @returns The authenticated and hydrated user in popup mode.
645
+ * @throws {MitraApiError} When IAM rejects the exchange code.
646
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
647
+ * out, the response fails origin, source, state, or shape validation, or the
648
+ * page does not say which method produced the code. A person who finishes
649
+ * through the email link instead of the popup leaves this call to time out,
650
+ * which the application should treat as a cancelled popup.
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * const user = await mitra.auth.signInWithAuthPage();
655
+ * ```
656
+ */
657
+ signInWithAuthPage(options?: AuthPageSignInOptions): Promise<User>;
658
+ /**
659
+ * Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
660
+ * `#stateMitra` and `#providerMitra`, during application startup: the redirect
661
+ * back to the tab that started it, or the tab the email link opened. The state
662
+ * must match the request pending in this browser, as in
663
+ * {@link completeEmailSignInRedirect}.
664
+ *
665
+ * @returns The authenticated user, or `null` when the URL carries no result,
666
+ * or carries one that belongs to another sign-in method's flow.
667
+ * @throws When the fragment belongs to this flow but its state does not match,
668
+ * the request expired, the page reports an error, or it does not say which
669
+ * method produced the code. The fragment is removed first.
670
+ *
671
+ * @example
672
+ * ```typescript
673
+ * const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
674
+ * ```
675
+ */
676
+ completeAuthPageSignInRedirect(): Promise<User | null>;
624
677
  /**
625
678
  * Completes a sign-in made through an identity connection, such as Sankhya
626
679
  * Pass, from the single-use code the platform bridge page leaves in the
@@ -1426,6 +1479,26 @@ interface MitraClient {
1426
1479
  /** Browser-safe credential status, model discovery, and provider auth flows. */
1427
1480
  agentCredentials: AgentCredentialsModule;
1428
1481
  readonly aiProviders: AiProvidersModule;
1482
+ /**
1483
+ * App files kept by the Data Manager: `upload` a `File` or `Blob`, read its
1484
+ * metadata with `get`, ask for signed read links with `getUrl` or `getUrls`,
1485
+ * `download` and `delete`.
1486
+ *
1487
+ * The API calls carry the session token and `X-App-Id`. The bytes go straight
1488
+ * to storage through the signed link, with the browser `fetch` and without
1489
+ * those headers.
1490
+ *
1491
+ * @example
1492
+ * ```typescript
1493
+ * // `picked` is a File from an <input type="file">
1494
+ * const file = await mitra.files.upload(picked, {
1495
+ * kind: 'PERMANENT',
1496
+ * visibility: 'PRIVATE',
1497
+ * });
1498
+ * const { url } = await mitra.files.getUrl(file.id);
1499
+ * ```
1500
+ */
1501
+ readonly files: FilesModule;
1429
1502
  /**
1430
1503
  * Integration module for proxying HTTP requests to external APIs.
1431
1504
  *
@@ -1484,6 +1557,7 @@ interface MitraClient {
1484
1557
  * - **functions**: Serverless function invocation
1485
1558
  * - **integration**: Proxy HTTP requests to external APIs
1486
1559
  * - **queries**: Custom query management and execution
1560
+ * - **files**: App file upload, signed read links and download
1487
1561
  *
1488
1562
  * After creating the client, call `init()` to resolve the app's public config
1489
1563
  * (dataSourceId, allowSignup, emailLoginEnabled, passwordLoginEnabled) automatically from the server.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, FunctionExecution, ListTemplateConfigsOptions, TemplateConfigPage, ProxyResult, ProxyInput, QueryResult, AgentCredentialOptions, CredentialStatus, AgentModel as AgentModel$1, AgentReadyProvider, CredentialUsage, OAuthStartResult, OAuthExchangeInput, AuthenticationResult, DeviceAuthorization, AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, PublicFunctionsModule, AgentTasksWithSessions, AiProvidersModule } from '@mitralab.io/sdk-core';
2
- export { AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, AgentCredentialOptions, AgentCredentialScope, AgentProviderUsage, AgentQueueItem, AgentReadyProvider, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskInput, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTurnResult, AgentTurnUsage, AgentTurnUsageRequest, AiProviders, AiProvidersModule, AuthenticationResult, CredentialStatus, CredentialUsage, CredentialUsageWindow, DeviceAuthorization, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionExecution, IncludedAiQuota, IncludedAiQuotaWindow, ListTemplateConfigsOptions, ManagedAiProfile, AgentMessage as NativeAgentMessage, AgentModel as NativeAgentModel, AgentTaskSession as NativeAgentTaskSession, AgentTimelineItem as NativeAgentTimelineItem, AgentToolEvent as NativeAgentToolEvent, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, OpencodeAiProvider, Page, PageOptions, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueryResult, TemplateConfigPage } from '@mitralab.io/sdk-core';
1
+ import { Transport, TransportRequestOptions, QueryParamValue, EntityTable, FunctionExecution, ListTemplateConfigsOptions, TemplateConfigPage, ProxyResult, ProxyInput, QueryResult, AgentCredentialOptions, CredentialStatus, AgentModel as AgentModel$1, AgentReadyProvider, CredentialUsage, OAuthStartResult, OAuthExchangeInput, AuthenticationResult, DeviceAuthorization, AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, PublicFunctionsModule, AgentTasksWithSessions, AiProvidersModule, FilesModule } from '@mitralab.io/sdk-core';
2
+ export { AgentConnectionCustomProvider, AgentConnectionCustomProviderInput, AgentCredentialOptions, AgentCredentialScope, AgentProviderUsage, AgentQueueItem, AgentReadyProvider, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskInput, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTurnResult, AgentTurnUsage, AgentTurnUsageRequest, AiProviders, AiProvidersModule, AuthenticationResult, CredentialStatus, CredentialUsage, CredentialUsageWindow, DeviceAuthorization, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FileCreator, FileDownloadOptions, FileKind, FileMetadata, FileReadUrl, FileReadUrlItem, FileReadUrlOptions, FileReadUrls, FileStatus, FileTransferError, FileTransferStep, FileUpload, FileUploadInput, FileUploadOptions, FileVisibility, FilesModule, FunctionExecution, IncludedAiQuota, IncludedAiQuotaWindow, ListTemplateConfigsOptions, ManagedAiProfile, AgentMessage as NativeAgentMessage, AgentModel as NativeAgentModel, AgentTaskSession as NativeAgentTaskSession, AgentTimelineItem as NativeAgentTimelineItem, AgentToolEvent as NativeAgentToolEvent, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, OpencodeAiProvider, Page, PageOptions, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueryResult, TemplateConfigPage } from '@mitralab.io/sdk-core';
3
3
  import * as LegacyTypes from 'mitra-interactions-sdk';
4
4
  import { exchangeSsoCodeMitra as exchangeSsoCodeMitra$1, loginMitra as loginMitra$1, loginWithGoogleMitra as loginWithGoogleMitra$1, loginWithMicrosoftMitra as loginWithMicrosoftMitra$1 } from 'mitra-interactions-sdk';
5
5
  export { callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, manageAgentChatMitra, manageAgentCredentialMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra } from 'mitra-interactions-sdk';
@@ -362,7 +362,8 @@ interface AuthModuleOptions {
362
362
  /**
363
363
  * Authentication module for managing user sessions.
364
364
  *
365
- * Handles Google and Microsoft SSO, email and password sign-in, trusted session adoption, sign-out,
365
+ * Handles Google and Microsoft SSO, email and password sign-in, the auth page screen that offers
366
+ * them all, trusted session adoption, sign-out,
366
367
  * and automatic token refresh.
367
368
  * Auth state is persisted to localStorage with key `mitra_auth_{appId}`
368
369
  * and restored on page reload; a session from an identity connection is kept
@@ -392,6 +393,7 @@ declare class AuthModule {
392
393
  private readonly microsoftAuth;
393
394
  private readonly emailAuth;
394
395
  private readonly passwordAuth;
396
+ private readonly authPage;
395
397
  private readonly emailCode;
396
398
  private readonly passwordForm;
397
399
  private readonly identityConnection;
@@ -621,6 +623,57 @@ declare class AuthModule {
621
623
  * `MAGIC_LINK_INVALID` when the link belongs here but cannot be used.
622
624
  */
623
625
  completeEmailSignInRedirect(): Promise<User | null>;
626
+ /**
627
+ * Signs in on a single screen of the Mitra auth page that offers every method
628
+ * the app has on: Google and Microsoft always, plus password and the email
629
+ * code when the app has them enabled. The person picks one there, and
630
+ * the page reports which; the code is redeemed at that method's IAM route,
631
+ * exactly as the method's own sign-in would.
632
+ *
633
+ * Popup by default; redirect mode navigates away, and
634
+ * {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
635
+ * person may choose the email code, whose message carries a link that opens
636
+ * a new tab, the pending request is kept in `localStorage` under
637
+ * `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
638
+ * auth page URL, never a token - as {@link signInWithEmail} does.
639
+ *
640
+ * Call it straight from the click handler, before any `await`, or the browser
641
+ * blocks the popup.
642
+ *
643
+ * @param options - Popup or redirect mode.
644
+ * @returns The authenticated and hydrated user in popup mode.
645
+ * @throws {MitraApiError} When IAM rejects the exchange code.
646
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
647
+ * out, the response fails origin, source, state, or shape validation, or the
648
+ * page does not say which method produced the code. A person who finishes
649
+ * through the email link instead of the popup leaves this call to time out,
650
+ * which the application should treat as a cancelled popup.
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * const user = await mitra.auth.signInWithAuthPage();
655
+ * ```
656
+ */
657
+ signInWithAuthPage(options?: AuthPageSignInOptions): Promise<User>;
658
+ /**
659
+ * Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
660
+ * `#stateMitra` and `#providerMitra`, during application startup: the redirect
661
+ * back to the tab that started it, or the tab the email link opened. The state
662
+ * must match the request pending in this browser, as in
663
+ * {@link completeEmailSignInRedirect}.
664
+ *
665
+ * @returns The authenticated user, or `null` when the URL carries no result,
666
+ * or carries one that belongs to another sign-in method's flow.
667
+ * @throws When the fragment belongs to this flow but its state does not match,
668
+ * the request expired, the page reports an error, or it does not say which
669
+ * method produced the code. The fragment is removed first.
670
+ *
671
+ * @example
672
+ * ```typescript
673
+ * const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
674
+ * ```
675
+ */
676
+ completeAuthPageSignInRedirect(): Promise<User | null>;
624
677
  /**
625
678
  * Completes a sign-in made through an identity connection, such as Sankhya
626
679
  * Pass, from the single-use code the platform bridge page leaves in the
@@ -1426,6 +1479,26 @@ interface MitraClient {
1426
1479
  /** Browser-safe credential status, model discovery, and provider auth flows. */
1427
1480
  agentCredentials: AgentCredentialsModule;
1428
1481
  readonly aiProviders: AiProvidersModule;
1482
+ /**
1483
+ * App files kept by the Data Manager: `upload` a `File` or `Blob`, read its
1484
+ * metadata with `get`, ask for signed read links with `getUrl` or `getUrls`,
1485
+ * `download` and `delete`.
1486
+ *
1487
+ * The API calls carry the session token and `X-App-Id`. The bytes go straight
1488
+ * to storage through the signed link, with the browser `fetch` and without
1489
+ * those headers.
1490
+ *
1491
+ * @example
1492
+ * ```typescript
1493
+ * // `picked` is a File from an <input type="file">
1494
+ * const file = await mitra.files.upload(picked, {
1495
+ * kind: 'PERMANENT',
1496
+ * visibility: 'PRIVATE',
1497
+ * });
1498
+ * const { url } = await mitra.files.getUrl(file.id);
1499
+ * ```
1500
+ */
1501
+ readonly files: FilesModule;
1429
1502
  /**
1430
1503
  * Integration module for proxying HTTP requests to external APIs.
1431
1504
  *
@@ -1484,6 +1557,7 @@ interface MitraClient {
1484
1557
  * - **functions**: Serverless function invocation
1485
1558
  * - **integration**: Proxy HTTP requests to external APIs
1486
1559
  * - **queries**: Custom query management and execution
1560
+ * - **files**: App file upload, signed read links and download
1487
1561
  *
1488
1562
  * After creating the client, call `init()` to resolve the app's public config
1489
1563
  * (dataSourceId, allowSignup, emailLoginEnabled, passwordLoginEnabled) automatically from the server.
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ function stripTrailingSlashes(value) {
8
8
  // src/client.ts
9
9
  import {
10
10
  createAiProvidersModule,
11
+ createFilesModule,
11
12
  createPublicFunctionsModule,
12
13
  encodePathSegment,
13
14
  expectObject as expectObject4
@@ -412,41 +413,59 @@ var RESULT_TYPE = "mitra-oauth-result";
412
413
  var SESSION_REQUEST_TYPE = "mitra-auth-session-request";
413
414
  var SESSION_TYPE = "mitra-auth-session";
414
415
  var PASSWORD_CHANGED_SIGN_IN_AGAIN = "PASSWORD_CHANGED_SIGN_IN_AGAIN";
416
+ var AUTH_PAGE_METHODS = /* @__PURE__ */ new Set([
417
+ "google",
418
+ "microsoft",
419
+ "email",
420
+ "password"
421
+ ]);
422
+ function isAuthPageMethod(value) {
423
+ return typeof value === "string" && AUTH_PAGE_METHODS.has(value);
424
+ }
425
+ var EXCHANGE_ROUTES = {
426
+ google: { path: "/api/v1/auth/google", sendsRedirectUri: true },
427
+ microsoft: { path: "/api/v1/auth/microsoft", sendsRedirectUri: true },
428
+ email: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false },
429
+ password: { path: "/api/v1/auth/magic-link/exchange", sendsRedirectUri: false }
430
+ };
415
431
  var FIVE_MINUTES_MS = 5 * 60 * 1e3;
416
432
  var TEN_MINUTES_MS = 10 * 60 * 1e3;
417
433
  var PROVIDERS = {
418
434
  google: {
419
435
  label: "Google",
420
- exchangePath: "/api/v1/auth/google",
421
- sendsRedirectUri: true,
436
+ exchange: EXCHANGE_ROUTES.google,
422
437
  redirectStorage: "sessionStorage",
423
438
  popupTimeoutMs: FIVE_MINUTES_MS
424
439
  },
425
440
  microsoft: {
426
441
  label: "Microsoft",
427
- exchangePath: "/api/v1/auth/microsoft",
428
- sendsRedirectUri: true,
442
+ exchange: EXCHANGE_ROUTES.microsoft,
429
443
  redirectStorage: "sessionStorage",
430
444
  popupTimeoutMs: FIVE_MINUTES_MS
431
445
  },
432
446
  email: {
433
447
  label: "Email",
434
- exchangePath: "/api/v1/auth/magic-link/exchange",
435
- sendsRedirectUri: false,
448
+ exchange: EXCHANGE_ROUTES.email,
436
449
  redirectStorage: "localStorage",
437
450
  pendingRequestTtlMs: TEN_MINUTES_MS,
438
451
  popupTimeoutMs: TEN_MINUTES_MS
439
452
  },
440
- // IAM answers a password login, signup or change with the same single-use
441
- // exchange code the email flow gets. Signing up waits on a code read from a
442
- // mailbox, hence the email timeout; there is no link, so nothing pending is
443
- // written for another tab.
453
+ // Signing up waits on a code read from a mailbox, hence the email timeout;
454
+ // there is no link, so nothing pending is written for another tab.
444
455
  password: {
445
456
  label: "Password",
446
- exchangePath: "/api/v1/auth/magic-link/exchange",
447
- sendsRedirectUri: false,
457
+ exchange: EXCHANGE_ROUTES.password,
448
458
  redirectStorage: "sessionStorage",
449
459
  popupTimeoutMs: TEN_MINUTES_MS
460
+ },
461
+ // The person may pick the email code on this screen, and its message carries
462
+ // a link that opens another tab, so this flow keeps the email lifetimes.
463
+ all: {
464
+ label: "Auth page",
465
+ exchange: "reportedMethod",
466
+ redirectStorage: "localStorage",
467
+ pendingRequestTtlMs: TEN_MINUTES_MS,
468
+ popupTimeoutMs: TEN_MINUTES_MS
450
469
  }
451
470
  };
452
471
  var POPUP_WIDTH = 480;
@@ -578,6 +597,7 @@ var AuthPageFlow = class {
578
597
  const code = params.get("codeMitra");
579
598
  const state = params.get("stateMitra");
580
599
  const error = params.get("errorMitra");
600
+ const reportedMethod = params.get("providerMitra");
581
601
  if (code === null && state === null && error === null) return null;
582
602
  const context = this.readRedirectContext(browserWindow);
583
603
  const hasState = state !== null && state.trim() !== "";
@@ -619,7 +639,7 @@ var AuthPageFlow = class {
619
639
  if (!code?.trim()) {
620
640
  throw new Error(`${this.providerLabel} sign-in redirect is missing code.`);
621
641
  }
622
- return this.exchangeCode(code, context.redirectUri);
642
+ return this.exchangeCode(code, context.redirectUri, this.readReportedMethod(reportedMethod));
623
643
  }
624
644
  async startPopup(browserWindow, request) {
625
645
  const state = this.generateState();
@@ -647,7 +667,10 @@ var AuthPageFlow = class {
647
667
  request.sessionToken
648
668
  );
649
669
  if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
650
- if (result.code) return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl));
670
+ const reportedMethod = this.readReportedMethod(result.method);
671
+ if (result.code) {
672
+ return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl), reportedMethod);
673
+ }
651
674
  return expectAuthTokenResponse(result.token);
652
675
  }
653
676
  startRedirect(browserWindow) {
@@ -718,14 +741,36 @@ var AuthPageFlow = class {
718
741
  redeemExchangeCode(code) {
719
742
  return this.exchangeCode(code, null);
720
743
  }
721
- async exchangeCode(code, redirectUri) {
722
- const response = await this.client.post(this.profile.exchangePath, {
744
+ async exchangeCode(code, redirectUri, reportedMethod) {
745
+ const route = this.exchangeRoute(reportedMethod);
746
+ const response = await this.client.post(route.path, {
723
747
  appId: this.appId,
724
748
  code,
725
- ...this.profile.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
749
+ ...route.sendsRedirectUri && redirectUri !== null ? { redirectUri } : {}
726
750
  });
727
751
  return expectAuthTokenResponse(response);
728
752
  }
753
+ exchangeRoute(reportedMethod) {
754
+ if (this.profile.exchange !== "reportedMethod") return this.profile.exchange;
755
+ if (!reportedMethod) {
756
+ throw new Error("The all-methods sign-in cannot redeem a code without the method the auth page reported.");
757
+ }
758
+ return EXCHANGE_ROUTES[reportedMethod];
759
+ }
760
+ /**
761
+ * The method the auth page says produced the code. Only the flow that asked
762
+ * for the page with every method reads it: a single-method page sends no such
763
+ * field, and its own route is already known. Anything outside the known
764
+ * methods is refused rather than mapped to a route, since a code redeemed at
765
+ * the wrong route is spent for nothing.
766
+ */
767
+ readReportedMethod(value) {
768
+ if (this.profile.exchange !== "reportedMethod") return void 0;
769
+ if (!isAuthPageMethod(value)) {
770
+ throw new Error(`${this.providerLabel} did not report which sign-in method produced the code.`);
771
+ }
772
+ return value;
773
+ }
729
774
  buildStartUrl(browserWindow, authPageUrl, state, view) {
730
775
  const startUrl = new URL(authPageUrl);
731
776
  startUrl.searchParams.set("provider", this.provider);
@@ -766,7 +811,12 @@ var AuthPageFlow = class {
766
811
  if (!Number.isFinite(context.createdAt)) return true;
767
812
  return Date.now() - context.createdAt > ttlMs;
768
813
  }
769
- /** A one-time state that names the flow that created it, so its fragment is recognizable. */
814
+ /**
815
+ * A one-time state that names the flow that created it, so its fragment is
816
+ * recognizable. The auth page relies on the `all.` prefix too: the tab the
817
+ * email link opens has only the state to tell a chooser request apart, and
818
+ * answers it with `providerMitra=email`.
819
+ */
770
820
  generateState() {
771
821
  if (!globalThis.crypto?.getRandomValues) {
772
822
  throw new Error(`${this.providerLabel} sign-in requires crypto.getRandomValues.`);
@@ -905,9 +955,15 @@ function readPopupResult(data, expectedState, providerLabel) {
905
955
  }
906
956
  const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
907
957
  if (!code && data.token === void 0) {
908
- return { error: new Error(`${providerLabel} auth page returned neither code nor token.`) };
958
+ return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
909
959
  }
910
- return { value: { ...code ? { code } : {}, ...data.token !== void 0 ? { token: data.token } : {} } };
960
+ return {
961
+ value: {
962
+ ...code ? { code } : {},
963
+ ...data.token !== void 0 ? { token: data.token } : {},
964
+ ...data.provider !== void 0 ? { method: data.provider } : {}
965
+ }
966
+ };
911
967
  }
912
968
 
913
969
  // src/modules/email-code-flow.ts
@@ -1675,6 +1731,7 @@ var AuthModule = class {
1675
1731
  microsoftAuth;
1676
1732
  emailAuth;
1677
1733
  passwordAuth;
1734
+ authPage;
1678
1735
  emailCode;
1679
1736
  passwordForm;
1680
1737
  identityConnection;
@@ -1725,6 +1782,13 @@ var AuthModule = class {
1725
1782
  client: this.publicClient,
1726
1783
  provider: "password"
1727
1784
  });
1785
+ this.authPage = new AuthPageFlow({
1786
+ appId,
1787
+ apiUrl,
1788
+ authPageUrl: options.authPageUrl,
1789
+ client: this.publicClient,
1790
+ provider: "all"
1791
+ });
1728
1792
  this.emailCode = new EmailCodeFlow({
1729
1793
  appId,
1730
1794
  client: this.publicClient,
@@ -2037,6 +2101,62 @@ var AuthModule = class {
2037
2101
  const tokenResponse = await this.emailAuth.completeRedirect();
2038
2102
  return tokenResponse ? this.establishSession(tokenResponse) : null;
2039
2103
  }
2104
+ /**
2105
+ * Signs in on a single screen of the Mitra auth page that offers every method
2106
+ * the app has on: Google and Microsoft always, plus password and the email
2107
+ * code when the app has them enabled. The person picks one there, and
2108
+ * the page reports which; the code is redeemed at that method's IAM route,
2109
+ * exactly as the method's own sign-in would.
2110
+ *
2111
+ * Popup by default; redirect mode navigates away, and
2112
+ * {@link completeAuthPageSignInRedirect} finishes it at startup. Since the
2113
+ * person may choose the email code, whose message carries a link that opens
2114
+ * a new tab, the pending request is kept in `localStorage` under
2115
+ * `mitra_all_redirect_{appId}` for 10 minutes - the one-time state and the
2116
+ * auth page URL, never a token - as {@link signInWithEmail} does.
2117
+ *
2118
+ * Call it straight from the click handler, before any `await`, or the browser
2119
+ * blocks the popup.
2120
+ *
2121
+ * @param options - Popup or redirect mode.
2122
+ * @returns The authenticated and hydrated user in popup mode.
2123
+ * @throws {MitraApiError} When IAM rejects the exchange code.
2124
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
2125
+ * out, the response fails origin, source, state, or shape validation, or the
2126
+ * page does not say which method produced the code. A person who finishes
2127
+ * through the email link instead of the popup leaves this call to time out,
2128
+ * which the application should treat as a cancelled popup.
2129
+ *
2130
+ * @example
2131
+ * ```typescript
2132
+ * const user = await mitra.auth.signInWithAuthPage();
2133
+ * ```
2134
+ */
2135
+ async signInWithAuthPage(options = {}) {
2136
+ return this.establishSession(await this.authPage.signIn(options));
2137
+ }
2138
+ /**
2139
+ * Completes a sign-in started by {@link signInWithAuthPage} from `#codeMitra`,
2140
+ * `#stateMitra` and `#providerMitra`, during application startup: the redirect
2141
+ * back to the tab that started it, or the tab the email link opened. The state
2142
+ * must match the request pending in this browser, as in
2143
+ * {@link completeEmailSignInRedirect}.
2144
+ *
2145
+ * @returns The authenticated user, or `null` when the URL carries no result,
2146
+ * or carries one that belongs to another sign-in method's flow.
2147
+ * @throws When the fragment belongs to this flow but its state does not match,
2148
+ * the request expired, the page reports an error, or it does not say which
2149
+ * method produced the code. The fragment is removed first.
2150
+ *
2151
+ * @example
2152
+ * ```typescript
2153
+ * const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect();
2154
+ * ```
2155
+ */
2156
+ async completeAuthPageSignInRedirect() {
2157
+ const tokenResponse = await this.authPage.completeRedirect();
2158
+ return tokenResponse ? this.establishSession(tokenResponse) : null;
2159
+ }
2040
2160
  /**
2041
2161
  * Completes a sign-in made through an identity connection, such as Sankhya
2042
2162
  * Pass, from the single-use code the platform bridge page leaves in the
@@ -3806,6 +3926,7 @@ function createClient(config) {
3806
3926
  );
3807
3927
  const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
3808
3928
  const aiProvidersModule = createAiProvidersModule(copilotHttpClient, coreErrors);
3929
+ const filesModule = createFilesModule(httpClient, {}, coreErrors);
3809
3930
  const integrationHttpClient = new HttpClient({
3810
3931
  baseUrl: integrationUrl,
3811
3932
  getToken: () => authModule.accessToken,
@@ -3866,6 +3987,7 @@ function createClient(config) {
3866
3987
  agentTasks: agentTasksModule,
3867
3988
  agentCredentials: agentCredentialsModule,
3868
3989
  aiProviders: aiProvidersModule,
3990
+ files: filesModule,
3869
3991
  integration: integrationModule,
3870
3992
  queries: queriesModule,
3871
3993
  get allowSignup() {
@@ -3881,6 +4003,9 @@ function createClient(config) {
3881
4003
  };
3882
4004
  }
3883
4005
 
4006
+ // src/index.ts
4007
+ import { FileTransferError } from "@mitralab.io/sdk-core";
4008
+
3884
4009
  // src/legacy/index.ts
3885
4010
  import {
3886
4011
  exchangeSsoCodeMitra as legacyExchangeSsoCodeMitra,
@@ -3932,6 +4057,7 @@ var exchangeSsoCodeMitra = async (options) => {
3932
4057
  return session;
3933
4058
  };
3934
4059
  export {
4060
+ FileTransferError,
3935
4061
  MitraApiError,
3936
4062
  callIntegrationMitra,
3937
4063
  configureSdkMitra2 as configureSdkMitra,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/platform-sdk",
3
- "version": "1.9.0-beta.1",
3
+ "version": "1.9.0-beta.2",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "url": "https://github.com/mitralab-dev/mitra-platform-sdk/issues"
63
63
  },
64
64
  "dependencies": {
65
- "@mitralab.io/sdk-core": "0.3.9",
65
+ "@mitralab.io/sdk-core": "0.3.10",
66
66
  "mitra-interactions-sdk": "1.0.60-beta.48"
67
67
  },
68
68
  "devDependencies": {