@mitralab.io/platform-sdk 1.1.5-beta.0 → 1.2.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
@@ -1,136 +1,163 @@
1
- # Changelog
2
-
3
- All notable changes to this project are documented in this file.
4
-
5
- ## 1.1.5-beta.0
6
-
7
- - The eight `agentCredentials` methods take a trailing `{ scope: "ACCOUNT" }`, sent as the
8
- `scope=ACCOUNT` query parameter, and `session({ create: true })` and `agentTasks.create()`
9
- accept `scope: "ACCOUNT"` in the create body, so the credential and the chat resolve against
10
- the person's own account instead of the app. Without `scope` nothing changes on the wire. The
11
- Copilot honors `ACCOUNT` only for apps listed by flag and answers
12
- `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise.
13
- - Depend on `@mitralab.io/sdk-core@0.2.5-beta.0`, which carries the `scope` option through the
14
- credential calls and into the create request and exports `AgentCredentialScope` and
15
- `AgentCredentialOptions`.
16
-
17
- ## 1.1.4-beta.0
18
-
19
- - On the direct channel the message and the interrupt are written on the box socket, as the
20
- client frames the box already reads, instead of `POST /copilot/api/v1/tasks/{id}/inputs`. The
21
- box asks the Copilot for admission itself and answers on the same socket, so the Copilot's host
22
- socket buffer no longer bounds the message: the only limit is the box channel's own. REST stays
23
- for a chat with no box socket, for a socket not open at the moment of the send, a redial in
24
- progress included, and for every approval answer. A frame written on a socket that closes
25
- before the box acknowledges it is not resent over REST, since the box may have admitted the
26
- turn already; the redial's replay recovers it.
27
-
28
- ## 1.1.3
29
-
30
- - A chat created through `session({ create: true })` over the `auto` or `websocket` transport is
31
- born on the T3 box: the create request carries `runtime: "T3"`. A chat created with
32
- `transport: "http"` stays on the runner, and an explicit `runtime` is forwarded as given.
33
- - The box channel is asked for once. The Copilot now holds the channel request while the box
34
- boots, so the 2 s polling on a 202 answer is gone; a 202 from an older Copilot means the chat
35
- follows the Copilot socket.
36
- - Depend on `@mitralab.io/sdk-core@0.2.4`, which carries the `runtime` session option into the
37
- create request, exports `AgentTaskRuntime`, and sends a prompt whose task already exists even
38
- when the session was closed inside its `taskCreated` handler.
39
-
40
- ## 1.2.0-beta.1
41
-
42
- - Add `signInWithEmail()`: the platform auth page collects the address and the one-time code, and
43
- the single-use exchange code it returns is redeemed at IAM's `/auth/magic-link/exchange` for the
44
- same app session Google and Microsoft SSO already produce.
45
- - Add `completeEmailSignInRedirect()`, which finishes both the mobile redirect and the tab opened
46
- by the link in the message.
47
- - Keep the pending email request, the one-time state and the auth page URL and never a token, in
48
- `localStorage` for 10 minutes, so the tab opened by the link in the message finishes the flow
49
- through the same state check the redirect uses. Writing it is best effort for a popup and
50
- required for a redirect.
51
- - Consume a fragment of the flow's own provider even when it cannot be completed, so a rejected or
52
- expired redirect is reported once instead of on every reload. A fragment of another flow stays
53
- untouched, and a pending request is still dropped only when it expires.
54
- - Name the flow in the one-time state (`google.<random>`, `microsoft.<random>`, `email.<random>`),
55
- which the auth page echoes verbatim, so every `complete*SignInRedirect()` recognizes its own
56
- fragment: a fragment from another method returns `null` untouched, whatever this browser has
57
- pending, and an application that offers all three can call all three at startup in any order. A
58
- fragment that names this flow without matching its pending request is rejected as forged.
59
- - Generalize the auth page handshake into `AuthPageFlow`, parameterized by provider, exchange
60
- route, and where the pending request lives, instead of a second copy for email.
61
- - Upgrading mid-flow: a redirect started by an earlier version stored a state without the provider
62
- name, so the completion after the upgrade returns `null` and the person signs in again. Nothing
63
- is lost beyond that one attempt, and only for redirects in flight during the upgrade.
64
- - Give each provider its own popup window name.
65
- - Point the deprecated `signIn` and `signUp` failures at `signInWithEmail()`.
66
- - Add `mitra.emailLoginEnabled`, read from `/info` during `init()` next to `allowSignup`, so an
67
- application only offers "sign in with email" when this app is inside the platform's rollout.
68
- A Code Studio older than the field answers without it, and any value that is not a boolean is
69
- read as `false`, so `init()` keeps working and an app that cannot prove it is enabled stops
70
- offering the option.
71
-
72
- ## 1.1.2
73
-
74
- - Move the `@mitralab.io/sdk-core` pin from `0.2.1` to `0.2.2`: same surface, published with the
75
- contract corpus that consumers pin, so every SDK released that day sits on the same core.
76
-
77
- ## 1.1.1
78
-
79
- - Depend on `@mitralab.io/sdk-core@0.2.1`, which replays `textChunk` and late deltas after an
80
- interrupted turn.
81
- - Serve the Agent chat from the T3 box over the direct channel when the Copilot offers it.
82
- - Treat a half-open Agent session channel as a disconnect instead of a live one.
83
-
84
- ## 1.1.0-beta.2
85
-
86
- `1.1.0-beta.1` was published from `main` before this change landed, so it still depends on Core `0.2.0-beta.0`; use `1.1.0-beta.2`.
87
-
88
- - Depend on `@mitralab.io/sdk-core@0.2.0-beta.1`, which reads back integration configs with a
89
- null `templateId` (configs born from an inline definition). The browser adapter still only
90
- lists and executes integration configs; authoring stays in the studio SDK and the MCP.
91
-
92
- ## 1.1.0-beta.0
93
-
94
- - Complete native Function sync, async, polling, cancellation, and anonymous public execution.
95
- - Expose browser-safe Agent Tasks, restricted Agent Credentials, and model discovery through Core 0.2 contracts.
96
- - Compose the Core-owned Agent task session manager with Platform WebSocket and HTTP/SSE adapters.
97
- - Add native anonymous polling for executions created by the public async Function route.
98
- - Keep business-Agent administration out of the browser adapter according to the app-role permission matrix.
99
- - Expose app-scoped integration config listing and execution by alias from Core 0.2.
100
- - Document the missing producer contract for native record selection by `jdbcConnectionConfigId` instead of inventing a browser-side translation.
101
- - Document that entity `update` already implements the producer's partial PUT semantics, so no duplicate PATCH method is needed.
102
- - Derive Function execution, integration proxy input, and custom query result types directly from Core without narrowing nullable or producer-returned fields.
103
- - Preserve the complete Data Manager record envelope and execute Custom Queries with only
104
- producer parameters, without a caller-selected Data Source or an `init()` precondition.
105
-
106
- - Refresh app sessions proactively through IAM before authenticated native requests, with a 30-second JWT expiry heuristic and one shared refresh flight.
107
- - Preserve sessions on transient refresh failures, clear them on definitive IAM client failures, and retain the one-time reactive `401` retry.
108
- - Rotate both tokens without fetching the current user or notifying public auth-state listeners, while keeping the legacy bridge synchronized.
109
- - Reject decodable access and refresh tokens whose app scope is missing or differs from the configured app while keeping opaque tokens server-authoritative.
110
- - Fence refresh responses by session generation so late success or failure cannot undo sign-out or overwrite a newer login or bridged session.
111
- - Bind reactive `401` handling to the token used by the rejected request so an old response cannot refresh or clear a replacement session.
112
- - Redact values under sensitive credential field names from recursive API error details.
113
- - Preserve the retained session when `auth.me()` reaches `401` after transient proactive and reactive refresh failures.
114
- - Add native Google SSO through popup and redirect flows with direct IAM code exchange.
115
- - Validate Google SSO origin, popup source, one-time state, cancellation, timeout, and token response shape.
116
- - Require redirect errors to bind to the stored state before exposing or consuming them.
117
- - Keep Google options limited to popup or redirect mode; account creation and locale remain producer concerns.
118
- - Leave legacy-only `returnTo` and `title` on the deprecated aliases because the old runtime did not implement them as native Google controls.
119
- - Preserve the email/password methods already public in Platform SDK 1.0.9 without presenting them as the new template flow.
120
- - Route deprecated calls and legacy authentication through `${apiUrl}/legacy`.
121
- - Apply the native auth page URL precedence to the deprecated SSO bridge.
122
- - Propagate native sign-in, refresh, token changes, and sign-out to the legacy SDK session.
123
- - Re-export the deprecated `mitra-interactions-sdk` surface from the package entrypoint.
124
- - Mark every legacy type alias as deprecated in generated declarations.
125
- - Share one session between this SDK and the legacy SDK in both directions.
126
- - Make the SonarCloud job wait for the Quality Gate result.
127
- - Align the public package metadata and ESM, CommonJS, and TypeScript artifacts.
128
- - Add package shape checks and public tarball smoke coverage.
129
- - Correct public imports and required configuration in documentation examples.
130
- - Add the MIT license.
131
-
132
- ## 1.0.8
133
-
134
- - Share environment-neutral API contracts through `@mitralab.io/sdk-core`.
135
- - Preserve the Platform SDK 1.x browser authentication and entity facade.
136
- - Validate redirects, API errors, sensitive-value redaction, and package consumers.
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ ## 1.2.0-beta.2
6
+
7
+ - Add `requestEmailCode({ email, language? })` and `verifyEmailCode({ receipt, code })`: sign-in by
8
+ email with no platform screen at all. The application renders its own address and code fields,
9
+ IAM sends a message branded as the app, and the verification returns the single-use exchange
10
+ code the SDK redeems for the same app session SSO produces.
11
+ - Land the link that message carries on the application's own origin, as `#emailToken=<token>`,
12
+ completed by the same `completeEmailSignInRedirect()` at startup. The link is inspected before it
13
+ is consumed and spent only when IAM reports the origin the page is on and the one-time state of
14
+ the request pending in this browser, so another browser, another device, or a scanner opening
15
+ links on the way to a mailbox consumes nothing and leaves the link valid for whoever asked.
16
+ - Keep the pending headless request under the same `mitra_email_redirect_{appId}` key the auth page
17
+ flow uses, with the same 10 minutes and the same contents: the one-time state and the app origin,
18
+ never a token. It is written once IAM accepts the request, so a resend IAM refuses, a rate limit
19
+ being the everyday case, leaves the message already in the mailbox completable by its link.
20
+ - Take only `emailToken` out of the URL when the link lands, leaving the rest of the fragment
21
+ exactly as it was found, so an application that routes on it keeps its route.
22
+ - Send `brand` and `language` with the request: the brand comes from the app info `init()` reads,
23
+ and asking before `init()` fails with `INVALID_CONFIGURATION` instead of branding a message at
24
+ random. The language is the caller's, then the browser's, then `pt-BR`.
25
+ - Add `MitraApiError.retryAfterSeconds`, read from `Retry-After`, so a `429` says how long to wait
26
+ instead of leaving the application to guess. It is `null` when the response carries no delay,
27
+ including when CORS keeps the header from reaching the browser. The field is the last constructor
28
+ parameter and optional, so existing construction is unchanged.
29
+ - Keep `signInWithEmail()`, the platform page popup and redirect, working exactly as before, along
30
+ with the `#codeMitra` completion and the Google and Microsoft flows.
31
+
32
+ ## 1.1.5-beta.0
33
+
34
+ - The eight `agentCredentials` methods take a trailing `{ scope: "ACCOUNT" }`, sent as the
35
+ `scope=ACCOUNT` query parameter, and `session({ create: true })` and `agentTasks.create()`
36
+ accept `scope: "ACCOUNT"` in the create body, so the credential and the chat resolve against
37
+ the person's own account instead of the app. Without `scope` nothing changes on the wire. The
38
+ Copilot honors `ACCOUNT` only for apps listed by flag and answers
39
+ `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise.
40
+ - Depend on `@mitralab.io/sdk-core@0.2.5-beta.0`, which carries the `scope` option through the
41
+ credential calls and into the create request and exports `AgentCredentialScope` and
42
+ `AgentCredentialOptions`.
43
+
44
+ ## 1.1.4-beta.0
45
+
46
+ - On the direct channel the message and the interrupt are written on the box socket, as the
47
+ client frames the box already reads, instead of `POST /copilot/api/v1/tasks/{id}/inputs`. The
48
+ box asks the Copilot for admission itself and answers on the same socket, so the Copilot's host
49
+ socket buffer no longer bounds the message: the only limit is the box channel's own. REST stays
50
+ for a chat with no box socket, for a socket not open at the moment of the send, a redial in
51
+ progress included, and for every approval answer. A frame written on a socket that closes
52
+ before the box acknowledges it is not resent over REST, since the box may have admitted the
53
+ turn already; the redial's replay recovers it.
54
+
55
+ ## 1.1.3
56
+
57
+ - A chat created through `session({ create: true })` over the `auto` or `websocket` transport is
58
+ born on the T3 box: the create request carries `runtime: "T3"`. A chat created with
59
+ `transport: "http"` stays on the runner, and an explicit `runtime` is forwarded as given.
60
+ - The box channel is asked for once. The Copilot now holds the channel request while the box
61
+ boots, so the 2 s polling on a 202 answer is gone; a 202 from an older Copilot means the chat
62
+ follows the Copilot socket.
63
+ - Depend on `@mitralab.io/sdk-core@0.2.4`, which carries the `runtime` session option into the
64
+ create request, exports `AgentTaskRuntime`, and sends a prompt whose task already exists even
65
+ when the session was closed inside its `taskCreated` handler.
66
+
67
+ ## 1.2.0-beta.1
68
+
69
+ - Add `signInWithEmail()`: the platform auth page collects the address and the one-time code, and
70
+ the single-use exchange code it returns is redeemed at IAM's `/auth/magic-link/exchange` for the
71
+ same app session Google and Microsoft SSO already produce.
72
+ - Add `completeEmailSignInRedirect()`, which finishes both the mobile redirect and the tab opened
73
+ by the link in the message.
74
+ - Keep the pending email request, the one-time state and the auth page URL and never a token, in
75
+ `localStorage` for 10 minutes, so the tab opened by the link in the message finishes the flow
76
+ through the same state check the redirect uses. Writing it is best effort for a popup and
77
+ required for a redirect.
78
+ - Consume a fragment of the flow's own provider even when it cannot be completed, so a rejected or
79
+ expired redirect is reported once instead of on every reload. A fragment of another flow stays
80
+ untouched, and a pending request is still dropped only when it expires.
81
+ - Name the flow in the one-time state (`google.<random>`, `microsoft.<random>`, `email.<random>`),
82
+ which the auth page echoes verbatim, so every `complete*SignInRedirect()` recognizes its own
83
+ fragment: a fragment from another method returns `null` untouched, whatever this browser has
84
+ pending, and an application that offers all three can call all three at startup in any order. A
85
+ fragment that names this flow without matching its pending request is rejected as forged.
86
+ - Generalize the auth page handshake into `AuthPageFlow`, parameterized by provider, exchange
87
+ route, and where the pending request lives, instead of a second copy for email.
88
+ - Upgrading mid-flow: a redirect started by an earlier version stored a state without the provider
89
+ name, so the completion after the upgrade returns `null` and the person signs in again. Nothing
90
+ is lost beyond that one attempt, and only for redirects in flight during the upgrade.
91
+ - Give each provider its own popup window name.
92
+ - Point the deprecated `signIn` and `signUp` failures at `signInWithEmail()`.
93
+ - Add `mitra.emailLoginEnabled`, read from `/info` during `init()` next to `allowSignup`, so an
94
+ application only offers "sign in with email" when this app is inside the platform's rollout.
95
+ A Code Studio older than the field answers without it, and any value that is not a boolean is
96
+ read as `false`, so `init()` keeps working and an app that cannot prove it is enabled stops
97
+ offering the option.
98
+
99
+ ## 1.1.2
100
+
101
+ - Move the `@mitralab.io/sdk-core` pin from `0.2.1` to `0.2.2`: same surface, published with the
102
+ contract corpus that consumers pin, so every SDK released that day sits on the same core.
103
+
104
+ ## 1.1.1
105
+
106
+ - Depend on `@mitralab.io/sdk-core@0.2.1`, which replays `textChunk` and late deltas after an
107
+ interrupted turn.
108
+ - Serve the Agent chat from the T3 box over the direct channel when the Copilot offers it.
109
+ - Treat a half-open Agent session channel as a disconnect instead of a live one.
110
+
111
+ ## 1.1.0-beta.2
112
+
113
+ `1.1.0-beta.1` was published from `main` before this change landed, so it still depends on Core `0.2.0-beta.0`; use `1.1.0-beta.2`.
114
+
115
+ - Depend on `@mitralab.io/sdk-core@0.2.0-beta.1`, which reads back integration configs with a
116
+ null `templateId` (configs born from an inline definition). The browser adapter still only
117
+ lists and executes integration configs; authoring stays in the studio SDK and the MCP.
118
+
119
+ ## 1.1.0-beta.0
120
+
121
+ - Complete native Function sync, async, polling, cancellation, and anonymous public execution.
122
+ - Expose browser-safe Agent Tasks, restricted Agent Credentials, and model discovery through Core 0.2 contracts.
123
+ - Compose the Core-owned Agent task session manager with Platform WebSocket and HTTP/SSE adapters.
124
+ - Add native anonymous polling for executions created by the public async Function route.
125
+ - Keep business-Agent administration out of the browser adapter according to the app-role permission matrix.
126
+ - Expose app-scoped integration config listing and execution by alias from Core 0.2.
127
+ - Document the missing producer contract for native record selection by `jdbcConnectionConfigId` instead of inventing a browser-side translation.
128
+ - Document that entity `update` already implements the producer's partial PUT semantics, so no duplicate PATCH method is needed.
129
+ - Derive Function execution, integration proxy input, and custom query result types directly from Core without narrowing nullable or producer-returned fields.
130
+ - Preserve the complete Data Manager record envelope and execute Custom Queries with only
131
+ producer parameters, without a caller-selected Data Source or an `init()` precondition.
132
+
133
+ - Refresh app sessions proactively through IAM before authenticated native requests, with a 30-second JWT expiry heuristic and one shared refresh flight.
134
+ - Preserve sessions on transient refresh failures, clear them on definitive IAM client failures, and retain the one-time reactive `401` retry.
135
+ - Rotate both tokens without fetching the current user or notifying public auth-state listeners, while keeping the legacy bridge synchronized.
136
+ - Reject decodable access and refresh tokens whose app scope is missing or differs from the configured app while keeping opaque tokens server-authoritative.
137
+ - Fence refresh responses by session generation so late success or failure cannot undo sign-out or overwrite a newer login or bridged session.
138
+ - Bind reactive `401` handling to the token used by the rejected request so an old response cannot refresh or clear a replacement session.
139
+ - Redact values under sensitive credential field names from recursive API error details.
140
+ - Preserve the retained session when `auth.me()` reaches `401` after transient proactive and reactive refresh failures.
141
+ - Add native Google SSO through popup and redirect flows with direct IAM code exchange.
142
+ - Validate Google SSO origin, popup source, one-time state, cancellation, timeout, and token response shape.
143
+ - Require redirect errors to bind to the stored state before exposing or consuming them.
144
+ - Keep Google options limited to popup or redirect mode; account creation and locale remain producer concerns.
145
+ - Leave legacy-only `returnTo` and `title` on the deprecated aliases because the old runtime did not implement them as native Google controls.
146
+ - Preserve the email/password methods already public in Platform SDK 1.0.9 without presenting them as the new template flow.
147
+ - Route deprecated calls and legacy authentication through `${apiUrl}/legacy`.
148
+ - Apply the native auth page URL precedence to the deprecated SSO bridge.
149
+ - Propagate native sign-in, refresh, token changes, and sign-out to the legacy SDK session.
150
+ - Re-export the deprecated `mitra-interactions-sdk` surface from the package entrypoint.
151
+ - Mark every legacy type alias as deprecated in generated declarations.
152
+ - Share one session between this SDK and the legacy SDK in both directions.
153
+ - Make the SonarCloud job wait for the Quality Gate result.
154
+ - Align the public package metadata and ESM, CommonJS, and TypeScript artifacts.
155
+ - Add package shape checks and public tarball smoke coverage.
156
+ - Correct public imports and required configuration in documentation examples.
157
+ - Add the MIT license.
158
+
159
+ ## 1.0.8
160
+
161
+ - Share environment-neutral API contracts through `@mitralab.io/sdk-core`.
162
+ - Preserve the Platform SDK 1.x browser authentication and entity facade.
163
+ - Validate redirects, API errors, sensitive-value redaction, and package consumers.
package/README.md CHANGED
@@ -30,7 +30,9 @@ await mitra.init()
30
30
  ```
31
31
 
32
32
  `init()` resolves the application's public Code Studio configuration, including nullable
33
- `dataSourceId`, `allowSignup`, and `emailLoginEnabled`. The Data Source value remains part of the
33
+ `dataSourceId`, `allowSignup`, and `emailLoginEnabled`. It also reads the application's brand, which
34
+ does not become a public property: it is what `requestEmailCode()` sends so IAM writes the
35
+ message as the application. The Data Source value remains part of the
34
36
  Platform 1.x compatibility flow; native Entities and Custom Queries resolve the current app through
35
37
  the authenticated request. Call `init()` during application startup before the compatibility
36
38
  sign-up method needs `allowSignup` or the login screen needs `emailLoginEnabled`.
@@ -160,67 +162,146 @@ const mitra = createClient({
160
162
 
161
163
  ### Signing in with email
162
164
 
163
- Email sign-in needs neither a password nor an SSO account. The same platform page opens, a popup
164
- by default, collects the address, sends a six-digit code, and IAM answers with a single-use
165
- exchange code that the SDK redeems at `/iam/api/v1/auth/magic-link/exchange`. What comes back is
166
- the app session SSO already returns, persisted and refreshed the same way:
165
+ Email sign-in needs neither a password nor an SSO account, and the application
166
+ never has to send anyone to a platform screen. It renders its own address and
167
+ code fields, IAM sends a message branded as the app, and the link in that
168
+ message comes back to the application's own origin:
167
169
 
168
170
  ```typescript
169
- const user = await mitra.auth.signInWithEmail()
171
+ const { receipt, resendAfterSeconds } = await mitra.auth.requestEmailCode({
172
+ email: "person@example.com",
173
+ })
174
+
175
+ const user = await mitra.auth.verifyEmailCode({ receipt, code: "123456" })
170
176
  ```
171
177
 
172
- Not every app is in the rollout. `mitra.emailLoginEnabled` is this app's own verdict, read from
173
- `/info` during `init()`, and it is what a login screen should offer the option on:
178
+ `requestEmailCode()` answers the same way whatever the address is, so nothing in
179
+ it says whether that person already exists. The `receipt` names the request when
180
+ the code comes back; it is not a credential and authorizes nothing on its own.
181
+ Resending is calling `requestEmailCode()` again, which replaces the request in
182
+ flight; `resendAfterSeconds` is how long to wait before offering that.
183
+
184
+ The message is written in `pt-BR` or `en`. Pass `language` to choose; without it
185
+ the SDK reads the browser's language and falls back to `pt-BR`.
186
+
187
+ `requestEmailCode()` needs `init()` to have run, because the message is branded
188
+ with the app's own brand, read from `/info`. Calling it before that fails with
189
+ `INVALID_CONFIGURATION` rather than sending a message branded at random.
190
+ `mitra.emailLoginEnabled`, read from the same `/info`, is this app's own verdict
191
+ about the rollout, and it is what a login screen should offer the option on:
174
192
 
175
193
  ```typescript
176
194
  await mitra.init()
177
195
 
178
196
  if (mitra.emailLoginEnabled) {
179
- // render "sign in with email"
197
+ // render the email field
180
198
  }
181
199
  ```
182
200
 
183
- It is `false` before `init()` runs, `false` when the server answers without the field or with
184
- something that is not a boolean, and `false` is the safe answer: the app is outside the rollout,
185
- IAM answers a request neutrally without sending anything, and the person would wait for a message
186
- that never arrives. Calling `signInWithEmail()` anyway is not blocked by the SDK; the verdict is
187
- there so the application does not offer a door that does not open.
201
+ It is `false` before `init()` runs, `false` when the server answers without the
202
+ field or with something that is not a boolean, and `false` is the safe answer:
203
+ the app is outside the rollout, IAM answers a request neutrally without sending
204
+ anything, and the person would wait for a message that never arrives. Calling
205
+ the email methods anyway is not blocked by the SDK; the verdict is there so the
206
+ application does not offer a door that does not open.
207
+
208
+ #### The link in the message
188
209
 
189
- Redirect mode navigates the current page instead of opening a popup, and is completed during
190
- startup like the SSO redirect:
210
+ The same message carries a link back to this application's own origin, as
211
+ `#emailToken=<token>`. Complete it during application startup, before rendering
212
+ authenticated routes:
191
213
 
192
214
  ```typescript
193
- await mitra.auth.signInWithEmail({ mode: "redirect" })
215
+ const emailUser = await mitra.auth.completeEmailSignInRedirect()
194
216
  ```
195
217
 
218
+ The token travels in the fragment, so it never reaches a server other than the
219
+ one this SDK sends it to. The SDK inspects the link first, without consuming it,
220
+ and spends it only when IAM reports the origin the page is on and the one-time
221
+ state of the request pending in this browser. That pending request is written by
222
+ `requestEmailCode()` to `localStorage` under `mitra_email_redirect_{appId}`, for
223
+ 10 minutes:
224
+
225
+ ```json
226
+ { "state": "email.<random>", "redirectUri": "https://app.example.com", "createdAt": 0 }
227
+ ```
228
+
229
+ **No token is written there.** What is persisted is only the record of a request
230
+ already in flight, which is the smallest thing that lets the tab the link opens
231
+ finish it, and it expires on its own. Writing it is best effort: without
232
+ `localStorage` the code typed into the application still signs in and only the
233
+ completion from the link is lost.
234
+
235
+ **The link has to be opened in the same browser that asked for the message.**
236
+ Another browser or device has no pending request, so the SDK consumes nothing,
237
+ returns `null`, and the link stays valid for the person who asked. The same
238
+ answer protects against a scanner that opens links on their way to a mailbox. On
239
+ another device, type the six-digit code instead.
240
+
241
+ Only `emailToken` is taken out of the URL. The rest of the fragment is left
242
+ exactly as it was found, so an application that routes on it keeps its route.
243
+
244
+ `completeEmailSignInRedirect()` returns `null` when the URL carries no sign-in
245
+ result, when it carries one belonging to another method's flow, and when it
246
+ carries a link this browser cannot claim. A link that does belong here but
247
+ cannot be used is reported as a `MitraApiError`:
248
+
249
+ | Code | Status | What happened |
250
+ |---|---|---|
251
+ | `MAGIC_LINK_EXPIRED` | 409 | The request behind the link is over. Ask for a new message. |
252
+ | `MAGIC_LINK_USED` | 409 | The link was already spent, here or elsewhere. |
253
+ | `MAGIC_LINK_INVALID` | 401 | IAM does not recognize the token in the link. |
254
+
255
+ `verifyEmailCode()` reports `INVALID_CODE` (401) for a code that does not match,
256
+ and the same `MAGIC_LINK_EXPIRED` and `MAGIC_LINK_USED` when the request is
257
+ over. Both methods report `RATE_LIMITED` (429) when IAM asks the person to slow
258
+ down, and `SIGNUP_NOT_ALLOWED`, `APP_ACCESS_REQUIRED`, `APP_ACCESS_REVOKED`
259
+ (403) or `APP_ACCESS_LIMIT_REACHED` (409) when this app does not admit that
260
+ address. A `429` carries `error.retryAfterSeconds` when the gateway exposes
261
+ `Retry-After`, and `null` when it does not.
262
+
263
+ `requestEmailCode()` also reports `INVALID_ORIGIN` (400) when the page asking
264
+ for the message is not on one of the origins published for this application, and
265
+ both methods report `VALIDATION_FAILED` (400) for a field IAM refuses to read,
266
+ such as a malformed address or a code that is not six digits.
267
+
268
+ #### Through the platform page
269
+
270
+ `signInWithEmail()` is the older flow and still works: the same platform page
271
+ SSO opens collects the address and the code, and the single-use exchange code it
272
+ returns is redeemed at `/iam/api/v1/auth/magic-link/exchange` for the same app
273
+ session:
274
+
196
275
  ```typescript
197
- const emailUser = await mitra.auth.completeEmailSignInRedirect()
276
+ const user = await mitra.auth.signInWithEmail()
277
+ ```
278
+
279
+ It opens a popup by default, and redirect mode navigates the current page
280
+ instead:
281
+
282
+ ```typescript
283
+ await mitra.auth.signInWithEmail({ mode: "redirect" })
198
284
  ```
199
285
 
200
- Call `completeEmailSignInRedirect()` at startup even when sign-in was started as a popup, because
201
- the message carries a link as well as the code, and that link opens a **new tab**. That tab never
202
- saw the popup, so the pending request has to outlive the tab that opened it: the one-time state
203
- and the resolved auth page URL are written to `localStorage` under `mitra_email_redirect_{appId}`
204
- for 10 minutes, dropped when the flow completes, or discarded as stale the next time a result is read. `sessionStorage`,
205
- which the SSO redirect uses, is scoped to a single tab and cannot answer for another one. The link still has
206
- to be opened in the same browser that started the sign-in: another browser or device has no pending request,
207
- refuses the fragment, and the exchange code was already spent by the page. On another device, use the
208
- six-digit code in the popup instead.
209
-
210
- **No token is written there.** What is persisted is only the record of a request already in
211
- flight, which is the smallest thing that lets the other tab finish it, and it expires on its own.
212
- The tab opened by the link comes back with the same one-time state the flow started with, so it
213
- is completed by exactly the check the redirect uses; a request older than 10 minutes is discarded
214
- rather than completed. Writing the request is best effort for a popup: without `localStorage` the
215
- popup still signs in and only the completion from the link is lost, while redirect mode, which has
216
- nowhere else to keep it, fails at the start.
217
-
218
- When the person finishes in the tab the link opened, the `signInWithEmail()` call still waiting in
219
- the original tab eventually times out. Treat that rejection as a cancelled popup: the session is
220
- already established wherever the application called `completeEmailSignInRedirect()`.
221
-
222
- One fragment belongs to one flow, and an application that offers more than one method can call
223
- every completion at startup, in any order:
286
+ Both come back as `#codeMitra` and `#stateMitra`, and are completed by the same
287
+ `completeEmailSignInRedirect()` at startup. The message that page sends carries a
288
+ link too, which opens a **new tab** that never saw the popup, so the pending
289
+ request is written before the popup opens, for the same 10 minutes and under the
290
+ same key. `sessionStorage`, which the SSO redirect uses, is scoped to a single
291
+ tab and cannot answer for another one. Writing the request is best effort for a
292
+ popup: without `localStorage` the popup still signs in and only the completion
293
+ from the link is lost, while redirect mode, which has nowhere else to keep it,
294
+ fails at the start.
295
+
296
+ When the person finishes in the tab the link opened, the `signInWithEmail()`
297
+ call still waiting in the original tab eventually times out. Treat that
298
+ rejection as a cancelled popup: the session is already established wherever the
299
+ application called `completeEmailSignInRedirect()`.
300
+
301
+ #### One fragment, one flow
302
+
303
+ An application that offers more than one method can call every completion at
304
+ startup, in any order:
224
305
 
225
306
  ```typescript
226
307
  const user =
@@ -229,16 +310,18 @@ const user =
229
310
  (await mitra.auth.completeMicrosoftSignInRedirect())
230
311
  ```
231
312
 
232
- A chain like that propagates a rejection: an expired request or a forged fragment on the first
233
- completion keeps the others from running. Wrap each call in `try`/`catch` when the application
234
- should still try the remaining methods after one of them refuses a fragment.
235
-
236
- The one-time state each flow generates names that flow, as in `google.<random>` or
237
- `email.<random>`, and the auth page echoes it verbatim, so a completion recognizes its own
238
- fragment. A fragment from another method returns `null` and leaves the fragment and that other
239
- flow's pending request untouched, whatever this browser has pending. A fragment that does name
240
- this flow but does not match its pending request is rejected as forged, and the fragment is
241
- removed from the URL on the way out, so the rejection is reported once instead of on every
313
+ A chain like that propagates a rejection: an expired request or a forged
314
+ fragment on the first completion keeps the others from running. Wrap each call
315
+ in `try`/`catch` when the application should still try the remaining methods
316
+ after one of them refuses a fragment.
317
+
318
+ The one-time state each flow generates names that flow, as in `google.<random>`
319
+ or `email.<random>`, and the auth page echoes it verbatim, so a completion
320
+ recognizes its own fragment. A fragment from another method returns `null` and
321
+ leaves the fragment and that other flow's pending request untouched, whatever
322
+ this browser has pending. A fragment that does name this flow but does not match
323
+ its pending request is rejected as forged, and the fragment is removed from the
324
+ URL on the way out, so the rejection is reported once instead of on every
242
325
  reload.
243
326
 
244
327
  ## Entities
@@ -441,6 +524,12 @@ try {
441
524
  }
442
525
  ```
443
526
 
527
+ A `429` also carries `error.retryAfterSeconds`, read from the `Retry-After`
528
+ header, so the application can tell the person how long to wait instead of
529
+ guessing. It is `null` when the response carries no such delay, which includes
530
+ the case where the gateway does not expose the header to this origin and the one
531
+ where the server answers with an HTTP date rather than a number of seconds.
532
+
444
533
  The transport refuses HTTP redirects. Statuses `307` and `308`, opaque redirects, and responses already marked as redirected fail without replay. The only automatic replay is the single request attempted after reactive `401` recovery with either a refreshed token or a session that changed while the original request was in flight.
445
534
 
446
535
  Before constructing `MitraApiError`, the SDK recursively redacts the token used by the request and credentials in `Bearer` format from the error message, code, details, arrays, values, and object keys. Values under credential fields such as `accessToken`, `refreshToken`, `apiKey`, `password`, `authorization`, `secret`, and `clientSecret` are also replaced with `[REDACTED]`.