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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,88 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.9.0-beta.1
6
+
7
+ Sign-in through an identity connection by redirect, for an app opened directly in the browser,
8
+ outside a host system iframe (a "Sign in with Sankhya Pass" button).
9
+
10
+ - `auth.signInWithIdentityConnection(slug, { mode: 'redirect', redirectUri?, language? })` reads
11
+ the connection (`GET /api/v1/auth/identity-connections/{slug}`), which now carries
12
+ `authorizationEndpoint`, `tokenEndpoint` and `clientId`, and sends the page to the provider with
13
+ Authorization Code and PKCE (S256). A connection without those fields is refused before anything
14
+ is stored. The pending request (`state` prefixed `connection.{slug}.`, `code_verifier`, redirect
15
+ URI, token endpoint) is kept in `sessionStorage` under `mitra_identity_connection_redirect_{appId}`.
16
+ The redirect URI defaults to the current origin and path, without query or fragment; a
17
+ `redirectUri` outside the app origin, not http(s), or with a query or a fragment is refused
18
+ before any request (RFC 6749 3.1.2).
19
+ - `auth.completeIdentityConnectionRedirect()` reads `code` and `state` from the query, not the
20
+ fragment, so it never collides with the bridge completion. It returns `null`, without a request
21
+ and without touching the URL, when `state` does not start with `connection.`. From there on the
22
+ pending request is spent, the callback parameters leave the URL before anything can fail, and a
23
+ state that matches no pending request in the tab is refused without a request. The code is
24
+ redeemed at the provider's token endpoint saved at start, the provider's access token is sent to
25
+ `POST /api/v1/auth/identity-connections/{slug}/login` and the returned exchange code is redeemed
26
+ at `/exchange`, as the bridge flow does. The token endpoint call gives up after 15 seconds, and
27
+ its error message masks the code and the verifier. The provider's id token and refresh token are never kept.
28
+ The session is tab-scoped, like the bridge one, and a failure with a sign-in pending in the tab
29
+ drops the in-memory session while keeping it stored; a callback with nothing pending, such as a
30
+ forged link, is refused and leaves the session alone.
31
+ - `init()` calls it in a browser right after the bridge completion; a failure rejects `init()`.
32
+ - New exported type: `IdentityConnectionSignInOptions`.
33
+
34
+ ## 1.9.0-beta.0
35
+
36
+ Sign-in through an identity connection, starting with Sankhya Pass, for an app opened inside the
37
+ host system's iframe.
38
+
39
+ - `auth.completeIdentityConnectionSignInRedirect()` reads `codeMitra`, `stateMitra` and
40
+ `connectionMitra` from the fragment the platform bridge page (`sankhya-auth.html`) leaves on the
41
+ app's origin, and redeems the single-use code at
42
+ `POST /api/v1/auth/identity-connections/{slug}/exchange` with `{ appId, code }`. The response is
43
+ read like every other exchange, `allTokens` included. Tokens never travel in the URL or by
44
+ `postMessage`.
45
+ - It returns `null`, without a request and without touching the URL, when the fragment has no
46
+ `connectionMitra` or its `stateMitra` does not start with `connection.`, so the other completions
47
+ still read their own fragment. From there on the fragment belongs to this flow and is removed
48
+ before anything can fail. It rejects in a top-level tab (the bridge only runs in an iframe), for
49
+ a connection slug outside `[a-z0-9-]{1,64}`, for an `errorMitra` (with a fixed message that names
50
+ the error only when it matches `[a-z_]{1,64}`, since any embedding page can write it), for a
51
+ missing code and when IAM refuses the code (`401 INVALID_EXCHANGE_CODE`). It also reads the
52
+ connection (`GET /api/v1/auth/identity-connections/{slug}`) and rejects, without redeeming the
53
+ code, unless every page in the chain embedding the app (`location.ancestorOrigins`) is one of its
54
+ `allowedOrigins`; a page of someone else could otherwise embed the app, directly or around an
55
+ allowed host, with a code of another account and sign the visitor in as it. A browser that does
56
+ not expose `ancestorOrigins` is refused the same way: the requirement is the API, which Chromium
57
+ and WebKit expose and Firefox exposes from version 148.
58
+ - `init()` calls it in a browser after reading the app info, so an app that already calls
59
+ `await mitra.init()` opens signed in with no change. A refused code rejects `init()`; the
60
+ fragment is already gone, so a reload does not repeat the failure. Without the fragment `init()`
61
+ makes no extra request. A call to `init()` while another one runs now waits for it instead of
62
+ reading the app info a second time, so a double boot (React `StrictMode`) redeems the code once.
63
+ - A session from an identity connection is kept in `sessionStorage` under `mitra_auth_{appId}`
64
+ instead of `localStorage`, and lives only as long as its tab: two accounts of the host system
65
+ (two Sankhya demo bases) open in one browser no longer hand each other's session to the next
66
+ reload. On startup the tab's session wins over the shared one, which is left in place for the
67
+ other tabs of the app; a broken tab session is dropped alone and the shared one is restored.
68
+ `signOut()` in that tab ends only the tab session. Another sign-in or `setSession()` in the same
69
+ tab goes back to `localStorage` and removes the tab copy; after `setToken()` the session always
70
+ goes to `localStorage`, and the tab copy is removed even with `setToken(token, false)`. The
71
+ refresh token of the tab session is dropped by `setToken()` as well, so it never reaches the
72
+ shared storage or the legacy SDK with the hand-set token. A renewal keeps the session where it
73
+ is.
74
+ - When the identity connection sign-in fails, the session the client restored at startup is
75
+ dropped from memory and stays stored where it was (`localStorage`, or `sessionStorage` for a tab
76
+ session), so the iframe does not stay signed in as someone else after a refused Sankhya Pass
77
+ login. `init()` still rejects. An exchange that returns a token of another app leaves the shared
78
+ session stored as well.
79
+ - The deprecated `mitra-interactions-sdk` exports get only the access token of a tab session.
80
+ Its refresh token is not handed over, because the legacy SDK writes every refresh token it
81
+ receives to `localStorage` (`mitra-session`), where it would outlive the tab. So in a tab session
82
+ the legacy exports do not renew on their own, and this SDK renews only before one of its own
83
+ requests, in `ensureFreshSession()` or in `refreshSession()`, with no timer. An app that uses
84
+ only the legacy exports gets `401` once the access token expires, unless it makes a call through
85
+ this SDK or calls `refreshSession()`; the renewed token then reaches the legacy SDK at once.
86
+
5
87
  ## 1.8.7
6
88
 
7
89
  - Depend on `@mitralab.io/sdk-core@0.3.9`: a history reread while a turn runs no longer drops the
package/README.md CHANGED
@@ -98,6 +98,39 @@ if (token) await mitra.auth.confirmPasswordReset({ token, newPassword })
98
98
 
99
99
  A troca e o reset encerram todas as sessões da conta. Depois do reset, a pessoa entra de novo com a senha nova.
100
100
 
101
+ ### Login por conexão de identidade (Sankhya Pass)
102
+
103
+ Para app aberto dentro do iframe de outro sistema, como o SKW da Sankhya. O sistema hospedeiro abre a página de ponte da Mitra (`sankhya-auth.html`), que faz o login no IAM com o token dele e manda o iframe para a origem do app com um código de uso único no fragmento (`#codeMitra=...&stateMitra=connection.*&connectionMitra=sankhya-pass`). Nenhum token passa pela URL ou por `postMessage`.
104
+
105
+ O `await mitra.init()` troca esse código pela sessão sozinho, então o app abre logado sem código novo. Se a troca falhar, o `init()` rejeita; o fragmento já saiu da URL, e um reload não repete o erro. Fora desse fluxo, o `init()` não faz requisição a mais. Quem não chama `init()` usa `completeIdentityConnectionSignInRedirect()` no startup, que devolve `null` quando a URL não é dele.
106
+
107
+ O código só é aceito dentro de iframe e sob um sistema hospedeiro permitido: o SDK lê `location.ancestorOrigins` e confere toda a cadeia de páginas que embute o app contra os `allowedOrigins` da conexão (`GET /api/v1/auth/identity-connections/{slug}`). Aba de topo, qualquer origem da cadeia fora da lista ou browser que não expõe `ancestorOrigins` recusam o código sem trocá-lo. O requisito é a API, não a família do browser: Chromium e WebKit a expõem há anos, e o Firefox a partir da versão 148.
108
+
109
+ A sessão desse login fica no `sessionStorage`, na mesma chave `mitra_auth_{appId}`, e dura só enquanto a aba existe. É assim porque o sistema hospedeiro abre o app com a conta de cada base, e duas bases demo da Sankhya abertas no mesmo browser, dividindo o `localStorage`, trocavam a sessão e o alias uma da outra no reload, como já acontecia no legado.
110
+
111
+ - No startup, a sessão da aba vale antes da sessão compartilhada do `localStorage`. A sessão compartilhada não é apagada: ela é das outras abas do app, logadas do jeito normal. Se a aba não tem sessão própria, ela usa a compartilhada.
112
+ - `signOut()` numa aba assim encerra só a sessão da aba.
113
+ - Um login por outro método ou `setSession()` na mesma aba volta a gravar no `localStorage` e apaga a cópia da aba. Depois de `setToken()` o destino é sempre o `localStorage`, e a cópia da aba é apagada mesmo com `setToken(token, false)`.
114
+ - Se o login pela conexão for recusado, o `init()` rejeita e a sessão que o app tinha restaurado no startup deixa de valer naquela página, para o iframe não seguir logado com outra pessoa. Ela continua guardada onde estava: no `localStorage`, ou no `sessionStorage` se era uma sessão por aba.
115
+ - Os exports legados do `mitra-interactions-sdk` recebem dessa sessão só o access token. O refresh token não vai para eles, porque o SDK legado grava o refresh token no `localStorage` (`mitra-session`), onde ele sobreviveria à aba. Por isso, numa sessão por aba, os exports legados não renovam sozinhos, e o SDK novo também não renova em segundo plano: ele renova antes de uma requisição dele mesmo, em `ensureFreshSession()` ou em `refreshSession()`. Um app que só usa os exports legados recebe `401` quando o access token vence, a menos que faça uma chamada pelo SDK novo ou chame `refreshSession()`; o token renovado chega ao legado na hora.
116
+
117
+ #### Modo redirect, fora do iframe
118
+
119
+ Para um botão "Entrar com Sankhya Pass" num app aberto direto no browser, sem sistema hospedeiro. O SDK manda a página para o provedor de identidade da conexão (o Keycloak do Sankhya Pass), com Authorization Code e PKCE (Proof Key for Code Exchange, a prova que amarra o código a quem pediu), e o provedor devolve a pessoa ao app com um código na query.
120
+
121
+ ```typescript
122
+ await mitra.auth.signInWithIdentityConnection("sankhya-pass", { mode: "redirect" })
123
+ ```
124
+
125
+ - No retorno, o `await mitra.init()` completa o login sozinho. Quem não chama `init()` usa `completeIdentityConnectionRedirect()` no startup, que devolve `null` quando a query não é dele. Se o login falhar, o `init()` rejeita; a query já saiu da URL, e um reload não repete o erro.
126
+ - O app volta para a origem e o caminho atuais, sem query e sem fragmento, ou para o `redirectUri` passado nas opções, que precisa ser http ou https, estar na origem do app e não ter query nem fragmento (o SDK recusa antes de sair da página).
127
+ - O client público da conexão no provedor precisa de duas liberações para a origem do app: o redirect URI, para o provedor devolver a pessoa, e a origem em Web Origins (CORS, a regra que deixa o browser ler a resposta de outro domínio), porque o SDK troca o código no token endpoint direto do browser. Sem a segunda, essa troca falha com `TypeError` de rede. Peça à Mitra para liberar as duas.
128
+ - O pedido pendente (`state` e `code_verifier`) fica no `sessionStorage` da aba e vale uma vez. Retorno sem pedido pendente na aba, ou com `state` diferente, é recusado sem requisição. Sem pedido pendente, como num link forjado, a sessão que a página já tinha continua valendo.
129
+ - A troca no token endpoint espera até 15 segundos; passado isso, o login rejeita.
130
+ - O token do provedor serve só para o IAM validar quem é a pessoa e é descartado em seguida. O `id_token` e o `refresh_token` do provedor não são guardados.
131
+ - A sessão fica no `sessionStorage`, como no login pelo iframe, com as mesmas regras de sessão por aba descritas acima.
132
+ - Como não há iframe, não há requisito de `ancestorOrigins`: funciona em Chromium, WebKit e Firefox.
133
+
101
134
  Chat com agente:
102
135
 
103
136
  ```typescript
@@ -149,9 +182,9 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
149
182
  ## Boas práticas
150
183
 
151
184
  - Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled`, `passwordLoginEnabled` e o login por e-mail dependem dele.
152
- - 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.
153
- - A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa e, em app com contas próprias, encerra a sessão no servidor: o refresh token deixa de renovar, e o access token já emitido vale até vencer.
154
- - Alguns apps recebem tokens extras junto da sessão, em `auth.allTokens`, liberados app por app pela Mitra. O de backoffice é o mais sensível: ele carrega os acessos que a pessoa tem no backoffice da Mitra, vale uma hora e fica no mesmo `localStorage` da sessão, onde qualquer script do domínio do app consegue ler. Leia ele por `auth.ensureFreshBackofficeToken()`, que renova o token quando está perto de vencer e devolve `null` quando o app ou a pessoa não têm esse acesso. Use só contra o backoffice e não repasse para outro serviço.
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.
186
+ - 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
+ - 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.
155
188
  - O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
156
189
  - Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
157
190