@mitralab.io/platform-sdk 1.9.0-beta.1 → 1.9.0-beta.3
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 +46 -0
- package/README.md +73 -3
- package/dist/index.cjs +146 -20
- package/dist/index.d.cts +77 -3
- package/dist/index.d.ts +77 -3
- package/dist/index.js +146 -20
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,52 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## 1.9.0-beta.3
|
|
6
|
+
|
|
7
|
+
The turn state and the chat's own instructions, from `@mitralab.io/sdk-core@0.3.11`
|
|
8
|
+
(mitra-copilot#585 and #589).
|
|
9
|
+
|
|
10
|
+
- Depend on `@mitralab.io/sdk-core@0.3.11`. `client.agentTasks` now has `turnStates(ids)`, which
|
|
11
|
+
reads where the turn of several chats stands in one call (an id that is not a UUID is left out
|
|
12
|
+
before the request), and `setInstructions(id, instructions | null)`. `get` answers `turn` for a
|
|
13
|
+
chat on an agent box; `create` takes `instructions` and `folderKey`, and the task carries them
|
|
14
|
+
back. The session emits `contextCompacted`, and `turnEnd` and `sendAndWait` carry
|
|
15
|
+
`compactions`, always set and empty when the box sent none. The details are in the Core
|
|
16
|
+
changelog for 0.3.11.
|
|
17
|
+
- New exported types: `AgentTaskTurn`, `AgentTaskLastTurn`, `AgentTaskTurnStateEntry` and
|
|
18
|
+
`AgentTurnCompaction`.
|
|
19
|
+
|
|
20
|
+
## 1.9.0-beta.2
|
|
21
|
+
|
|
22
|
+
App files through `client.files`, and a single sign-in screen with every method the app has.
|
|
23
|
+
|
|
24
|
+
- Depend on `@mitralab.io/sdk-core@0.3.10` for its `files` module, exposed as `client.files`: app
|
|
25
|
+
files kept by the Data Manager under `/data-manager/api/v1/files`. `upload(fileOrBlob, options)`
|
|
26
|
+
requests the upload, sends the bytes to the signed link and confirms, resolving only with the
|
|
27
|
+
`READY` file; `requestUpload` and `confirmUpload` are the steps on their own. `get`, `getUrl`,
|
|
28
|
+
`getUrls` (1 to 100 ids), `download` and `delete` complete the module.
|
|
29
|
+
- The API calls go through the Data Manager client of this SDK, with the session token,
|
|
30
|
+
`X-App-Id`, the renewal before the request and the global `onError`. The bytes go to the signed
|
|
31
|
+
link through the global `fetch`, without `Authorization`, `X-App-Id` or any other header this SDK
|
|
32
|
+
adds: the link is the credential, and storage gets only the headers the API signed it with.
|
|
33
|
+
- An API refusal rejects with `MitraApiError`. A failure after the upload request rejects with the
|
|
34
|
+
Core `FileTransferError` (`step` `send`, `confirm` or `download`), now exported by this package,
|
|
35
|
+
and never carries the link; a failed send deletes the pending file first. A `signal` stops the
|
|
36
|
+
transfer with storage and the call rejects with `signal.reason` (`AbortError`, or `TimeoutError`
|
|
37
|
+
from `AbortSignal.timeout`). The transfer with storage does not reach `onError`.
|
|
38
|
+
- New exported types: `FilesModule`, `FileUploadOptions`, `FileDownloadOptions`, `FileMetadata`,
|
|
39
|
+
`FileKind`, `FileVisibility`, `FileStatus`, `FileCreator`, `FileUpload`, `FileUploadInput`,
|
|
40
|
+
`FileReadUrl`, `FileReadUrlItem`, `FileReadUrlOptions`, `FileReadUrls` and `FileTransferStep`.
|
|
41
|
+
- `auth.signInWithAuthPage({ mode? })` opens the Mitra sign-in page, in a popup or by redirect, on
|
|
42
|
+
a choice screen with the methods the app has: Google and Microsoft always, password and e-mail
|
|
43
|
+
code when the app has them on. The person chooses there, and the SDK exchanges the code through
|
|
44
|
+
the route of the chosen method. It is optional: an app that does not call it stays the same. In
|
|
45
|
+
`redirect` mode, and for the tab opened by the e-mail link, call
|
|
46
|
+
`auth.completeAuthPageSignInRedirect()` at startup; it returns `null` when the URL is not its
|
|
47
|
+
own. The pending request stays in `localStorage` for 10 minutes under
|
|
48
|
+
`mitra_all_redirect_{appId}`: the single-use state and the page address, never a token. An answer
|
|
49
|
+
from the page without the chosen method is refused, and the code is not exchanged.
|
|
50
|
+
|
|
5
51
|
## 1.9.0-beta.1
|
|
6
52
|
|
|
7
53
|
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.
|
|
@@ -44,8 +44,12 @@ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já v
|
|
|
44
44
|
- `agentTasks.session(...)`: chat com agente, com `send`, `sendAndWait`, `cancel` e eventos como `delta`, `turnEnd` e `error`.
|
|
45
45
|
`send` devolve o id da mensagem; com o browser offline a mensagem espera a rede e `send` devolve `undefined`.
|
|
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
|
+
O evento `contextCompacted` avisa quando o provedor compacta a conversa, e `turnEnd` e `sendAndWait` trazem `compactions`, a lista das compactações do turno (vazia quando não houve).
|
|
48
|
+
- `agentTasks.get(id)` traz `turn`, onde o turno do chat está (`RUNNING`, `QUEUED` ou `IDLE`) e como terminou o último, sem abrir sessão. `agentTasks.turnStates(ids)` faz o mesmo para vários chats numa chamada; id que não é UUID fica de fora.
|
|
49
|
+
- Instruções próprias do chat: `agentTasks.create({ ..., instructions, folderKey })` e `agentTasks.setInstructions(id, texto | null)`. Só aceita `setInstructions` o chat criado com instruções ou com `folderKey`; chats com a mesma `folderKey` dividem pasta e instruções. Detalhes no [README da sdk-core](https://github.com/mitralab-dev/mitra-core-sdk#readme) e no CHANGELOG dela, seção 0.3.11.
|
|
47
50
|
- `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
51
|
- `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.
|
|
52
|
+
- `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
53
|
|
|
50
54
|
`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
55
|
|
|
@@ -58,6 +62,22 @@ const { receipt } = await mitra.auth.requestEmailCode({ email })
|
|
|
58
62
|
const user = await mitra.auth.verifyEmailCode({ receipt, code })
|
|
59
63
|
```
|
|
60
64
|
|
|
65
|
+
### Tela única de login
|
|
66
|
+
|
|
67
|
+
`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:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
const user = await mitra.auth.signInWithAuthPage() // popup
|
|
71
|
+
await mitra.auth.signInWithAuthPage({ mode: "redirect" })
|
|
72
|
+
|
|
73
|
+
// no startup, para o modo redirect e para a aba aberta pelo link do e-mail
|
|
74
|
+
const redirectedUser = await mitra.auth.completeAuthPageSignInRedirect()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- 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.
|
|
78
|
+
- 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.
|
|
79
|
+
- Uma resposta da página sem o método escolhido é recusada, e o código não é trocado.
|
|
80
|
+
|
|
61
81
|
### Login por e-mail e senha
|
|
62
82
|
|
|
63
83
|
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 +162,63 @@ const { content } = await chat.sendAndWait("Resuma os pedidos de hoje")
|
|
|
142
162
|
chat.close()
|
|
143
163
|
```
|
|
144
164
|
|
|
165
|
+
### Arquivos do app
|
|
166
|
+
|
|
167
|
+
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.
|
|
168
|
+
|
|
169
|
+
Envio a partir de um `<input type="file">`:
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
// <input type="file" id="attachment"> e <button id="cancel">
|
|
173
|
+
const input = document.querySelector<HTMLInputElement>("#attachment")!
|
|
174
|
+
const cancel = document.querySelector<HTMLButtonElement>("#cancel")!
|
|
175
|
+
|
|
176
|
+
input.addEventListener("change", async () => {
|
|
177
|
+
const picked = input.files?.[0]
|
|
178
|
+
if (!picked) return
|
|
179
|
+
|
|
180
|
+
const sending = new AbortController()
|
|
181
|
+
cancel.onclick = () => sending.abort()
|
|
182
|
+
try {
|
|
183
|
+
const file = await mitra.files.upload(picked, {
|
|
184
|
+
kind: "PERMANENT",
|
|
185
|
+
visibility: "PRIVATE",
|
|
186
|
+
signal: sending.signal,
|
|
187
|
+
})
|
|
188
|
+
await mitra.entities.Attachment.create({ fileId: file.id, name: file.name })
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error instanceof DOMException && error.name === "AbortError") return
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
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.
|
|
197
|
+
|
|
198
|
+
Exibição pelo link de leitura:
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
// <img id="preview">
|
|
202
|
+
const { url } = await mitra.files.getUrl(attachment.fileId)
|
|
203
|
+
document.querySelector<HTMLImageElement>("#preview")!.src = url
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
- `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.
|
|
207
|
+
- `kind`: `TEMPORARY` vence 7 dias depois do pedido de envio, `PERMANENT` fica até ser apagado.
|
|
208
|
+
- 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`.
|
|
209
|
+
- 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.
|
|
210
|
+
- 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`.
|
|
211
|
+
- 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.
|
|
212
|
+
|
|
213
|
+
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.
|
|
214
|
+
|
|
145
215
|
## Configuração
|
|
146
216
|
|
|
147
217
|
| Campo | Obrigatório | Uso |
|
|
148
218
|
|---|---|---|
|
|
149
219
|
| `appId` | sim | ID do app no Code Studio |
|
|
150
220
|
| `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 `
|
|
221
|
+
| `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
222
|
| `authPageUrl` | não | URL da página de login da Mitra; sem ela, o SDK descobre sozinho |
|
|
153
223
|
| `apiKey` | não | chave padrão de `auth.signInWithApiKey()`; só em código de servidor, nunca no bundle do browser |
|
|
154
224
|
|
|
@@ -182,7 +252,7 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
|
|
|
182
252
|
## Boas práticas
|
|
183
253
|
|
|
184
254
|
- 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 `
|
|
255
|
+
- 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
256
|
- 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
257
|
- 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
258
|
- 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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
490
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
...
|
|
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
|
-
/**
|
|
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}
|
|
1007
|
+
return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
|
|
958
1008
|
}
|
|
959
|
-
return {
|
|
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, AgentTaskLastTurn, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTaskTurn, AgentTaskTurnStateEntry, AgentTurnCompaction, 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,
|
|
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, AgentTaskLastTurn, AgentTaskListOptions, AgentTaskRuntime, AgentTaskSessionEventMap, AgentTaskSessionOptions, AgentTaskSessionStatus, AgentTaskTurn, AgentTaskTurnStateEntry, AgentTurnCompaction, 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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
441
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
...
|
|
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
|
-
/**
|
|
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}
|
|
958
|
+
return { error: new Error(`${providerLabel} sign-in returned neither code nor token.`) };
|
|
909
959
|
}
|
|
910
|
-
return {
|
|
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.
|
|
3
|
+
"version": "1.9.0-beta.3",
|
|
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.
|
|
65
|
+
"@mitralab.io/sdk-core": "0.3.11",
|
|
66
66
|
"mitra-interactions-sdk": "1.0.60-beta.48"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|