@mitralab.io/platform-sdk 1.8.0-beta.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +46 -6
- package/dist/index.cjs +370 -26
- package/dist/index.d.cts +225 -10
- package/dist/index.d.ts +225 -10
- package/dist/index.js +370 -26
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,62 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## 1.8.0
|
|
6
|
+
|
|
7
|
+
Stable release of the 1.8.0-beta line, with `@mitralab.io/sdk-core@0.3.1`.
|
|
8
|
+
|
|
9
|
+
- Includes the password sign-in of 1.8.0-beta.0 (#171/#172) and 1.8.0-beta.1 (#173/#174), both
|
|
10
|
+
detailed below: `signInWithPassword()`, `signUpWithPassword()`, `changePassword()` and
|
|
11
|
+
`requestPasswordReset()` on the Mitra auth page, `signOut()` ending an exclusive app session on
|
|
12
|
+
the server, `mitra.passwordLoginEnabled`, and the app's own form with
|
|
13
|
+
`signInWithPasswordForm()`, `startPasswordSignUp()`, `completePasswordSignUp()`,
|
|
14
|
+
`changePasswordForm()`, `readPasswordResetToken()` and `confirmPasswordReset()`.
|
|
15
|
+
- Depend on `@mitralab.io/sdk-core@0.3.1`. Both additions need the Copilot with
|
|
16
|
+
mitra-copilot#549.
|
|
17
|
+
- `agentCredentials.providers(agentId?, options?)`: the providers the next turn can run on, in one
|
|
18
|
+
call to the Copilot's `GET /api/v1/models/providers`, each with `provider`, `providerName`,
|
|
19
|
+
`models` and `usage` (null on an API key, a custom provider, before a turn reported a window and
|
|
20
|
+
when the Copilot could not read it). Export `AgentReadyProvider`.
|
|
21
|
+
- `agentTasks.session(...).loadOlder()` reads the page before the oldest row `history` holds and
|
|
22
|
+
puts it before `history`; `hasOlder` says whether the last page read had more. Both come from the
|
|
23
|
+
core session, which the offline gate passes through.
|
|
24
|
+
|
|
25
|
+
## 1.8.0-beta.1
|
|
26
|
+
|
|
27
|
+
Password login from the app's own form, for apps whose owner turns that mode on (the Mitra auth
|
|
28
|
+
page stays the default and the recommended one).
|
|
29
|
+
|
|
30
|
+
- `auth.signInWithPasswordForm({ email, password })` posts to `/auth/password/login` with
|
|
31
|
+
`appId` and `origin: location.origin`, redeems the exchange code at `/auth/magic-link/exchange`
|
|
32
|
+
and stores the session like the popup does. No popup is opened.
|
|
33
|
+
- `auth.startPasswordSignUp({ email, language })` asks for the code at `/auth/password/signup` and
|
|
34
|
+
returns `{ receipt, resendAfterSeconds }`; `auth.completePasswordSignUp({ receipt, code, password })`
|
|
35
|
+
verifies it at `/auth/password/signup/verify` and signs the person in.
|
|
36
|
+
- `auth.changePasswordForm({ currentPassword, newPassword })` sends `PUT /auth/password` with the
|
|
37
|
+
access token of this session (`currentPassword` may be left out only for an account without a
|
|
38
|
+
password). The request goes on a client that does not refresh and retry on `401`, so a wrong
|
|
39
|
+
current password is tried once. IAM ends every session of the account, so the SDK signs in again
|
|
40
|
+
with the address of this session and the new password. When that sign-in fails, the call rejects
|
|
41
|
+
with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared, unless another session
|
|
42
|
+
replaced it meanwhile.
|
|
43
|
+
- `auth.readPasswordResetToken()` returns the `resetToken` of the reset link that lands on
|
|
44
|
+
`/reset-password` and removes the fragment from the URL; `auth.confirmPasswordReset({ token,
|
|
45
|
+
newPassword })` posts it to `/auth/password/reset/confirm`.
|
|
46
|
+
- A `403 PASSWORD_FORM_NOT_ENABLED` from IAM in `signInWithPasswordForm()`,
|
|
47
|
+
`completePasswordSignUp()`, `changePasswordForm()` or `confirmPasswordReset()` keeps its status
|
|
48
|
+
and code and gets a message saying to turn on the "form in the app itself" mode in the app or to
|
|
49
|
+
use the Mitra auth page methods. `startPasswordSignUp()` carries no password and IAM takes it in
|
|
50
|
+
either mode.
|
|
51
|
+
- Nothing changes in the existing methods: `signInWithPassword()`, `signUpWithPassword()`,
|
|
52
|
+
`changePassword()`, `requestPasswordReset()`, the email code, SSO, `signOut()` and the HTTP
|
|
53
|
+
client send the same requests and fail with the same messages. Only the JSDoc of
|
|
54
|
+
`requestPasswordReset()` changes: where its link opens now depends on the app's mode.
|
|
55
|
+
- The JSDoc of each form method opens with the warning that the password goes through the app's
|
|
56
|
+
code, and the README documents both modes. The JSDoc of the deprecated `signIn` and `signUp` also
|
|
57
|
+
points to the form methods; their error stays the same.
|
|
58
|
+
- Export `PasswordChange`, `PasswordResetConfirmation`, `PasswordSignUpCompletion`,
|
|
59
|
+
`PasswordSignUpRequest` and `PasswordSignUpRequestResult`.
|
|
60
|
+
|
|
5
61
|
## 1.8.0-beta.0
|
|
6
62
|
|
|
7
63
|
Sign-in by email and password for apps whose accounts are their own (exclusive login mode).
|
package/README.md
CHANGED
|
@@ -36,14 +36,15 @@ 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`), 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), mais `currentUser`, `onAuthStateChange` e `signOut`.
|
|
40
40
|
- `entities.<Tabela>`: `list`, `filter`, `get`, `create`, `bulkCreate`, `update`, `delete` e `deleteMany` nas tabelas do app.
|
|
41
41
|
- `queries.execute(id, params)`: roda uma query salva no app.
|
|
42
42
|
- `functions`: `execute` espera o resultado da Server Function; `executeAsync` devolve a execução para acompanhar com `getExecution` ou parar com `cancelExecution`. `publicFunctions` chama as Functions publicadas como públicas, sem login.
|
|
43
43
|
- `integration.executeByAlias(alias, request)`: chama uma API externa configurada no app. A credencial do provedor fica na Mitra e não passa pelo browser.
|
|
44
44
|
- `agentTasks.session(...)`: chat com agente, com `send`, `sendAndWait`, `cancel` e eventos como `delta`, `turnEnd` e `error`.
|
|
45
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
|
+
- `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.
|
|
47
48
|
|
|
48
49
|
Login por código no e-mail, para quem monta a própria tela:
|
|
49
50
|
|
|
@@ -52,7 +53,11 @@ const { receipt } = await mitra.auth.requestEmailCode({ email })
|
|
|
52
53
|
const user = await mitra.auth.verifyEmailCode({ receipt, code })
|
|
53
54
|
```
|
|
54
55
|
|
|
55
|
-
Login por e-mail e senha
|
|
56
|
+
### Login por e-mail e senha
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
**Tela da Mitra (recomendado).** A senha é digitada no popup da Mitra e não passa pelo código do app. Chame direto do clique, antes de qualquer `await`, para o browser não bloquear o popup:
|
|
56
61
|
|
|
57
62
|
```typescript
|
|
58
63
|
const user = await mitra.auth.signInWithPassword() // ou signUpWithPassword()
|
|
@@ -60,6 +65,34 @@ await mitra.auth.changePassword() // com a pessoa logada
|
|
|
60
65
|
const { resendAfterSeconds } = await mitra.auth.requestPasswordReset(email) // o link do e-mail abre a página da Mitra
|
|
61
66
|
```
|
|
62
67
|
|
|
68
|
+
**Formulário no próprio app.** O app desenha a própria tela e o SDK chama o IAM direto, sem popup. Só funciona com esse modo ligado no app: desligado, o IAM recusa com `PASSWORD_FORM_NOT_ENABLED` o login, a confirmação do cadastro, a troca e a confirmação do reset. O pedido do código de cadastro e o pedido do link de reset não levam senha e passam nos dois modos.
|
|
69
|
+
|
|
70
|
+
> A senha passa pelo código do app. Não guarde, não registre em log e não envie a senha a nenhum outro lugar além do método do SDK. O padrão mais seguro é `signInWithPassword()`, que usa a tela da Mitra.
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
// login
|
|
74
|
+
const user = await mitra.auth.signInWithPasswordForm({ email, password })
|
|
75
|
+
|
|
76
|
+
// cadastro em dois passos: o código vai por e-mail, a senha vai junto do código
|
|
77
|
+
const { receipt } = await mitra.auth.startPasswordSignUp({ email })
|
|
78
|
+
const newUser = await mitra.auth.completePasswordSignUp({ receipt, code, password })
|
|
79
|
+
|
|
80
|
+
// troca, com a pessoa logada; o SDK entra de novo com a senha nova
|
|
81
|
+
await mitra.auth.changePasswordForm({ currentPassword, newPassword })
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
No reset, o link do e-mail abre `/reset-password` na origem do app, com o token no fragmento da URL. Crie essa rota no app, leia o token e confirme:
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
await mitra.auth.requestPasswordReset(email)
|
|
88
|
+
|
|
89
|
+
// na rota /reset-password
|
|
90
|
+
const token = mitra.auth.readPasswordResetToken() // tira o token da URL
|
|
91
|
+
if (token) await mitra.auth.confirmPasswordReset({ token, newPassword })
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A troca e o reset encerram todas as sessões da conta. Depois do reset, a pessoa entra de novo com a senha nova.
|
|
95
|
+
|
|
63
96
|
Chat com agente:
|
|
64
97
|
|
|
65
98
|
```typescript
|
|
@@ -91,9 +124,16 @@ Falhas de API lançam `MitraApiError`, com `status`, `code`, `details` e `retryA
|
|
|
91
124
|
| `403` | a pessoa não tem acesso ao recurso | confira as permissões dela no app |
|
|
92
125
|
| `429`, `5xx` | limite de requisições ou falha no servidor | espere `retryAfterSeconds`, quando vier, e repita se a operação puder ser repetida |
|
|
93
126
|
| `INVALID_CONFIGURATION` | argumento inválido, ou `requestEmailCode()` antes de `init()` | corrija o argumento ou chame `init()` no startup |
|
|
94
|
-
| `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` antigos
|
|
95
|
-
| `
|
|
96
|
-
| `
|
|
127
|
+
| `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` antigos | use `signInWithPassword()` ou `signUpWithPassword()`; no formulário próprio, `signInWithPasswordForm()` ou `startPasswordSignUp()` |
|
|
128
|
+
| `PASSWORD_FORM_NOT_ENABLED` | `403` em `signInWithPasswordForm()`, `completePasswordSignUp()`, `changePasswordForm()` ou `confirmPasswordReset()`, com o app no modo da tela da Mitra | ligue o modo "Formulário no próprio app" no login por senha do app, ou use os métodos da tela da Mitra (`signInWithPassword()`, `signUpWithPassword()`, `changePassword()`) |
|
|
129
|
+
| `INVALID_CREDENTIALS` | `401` de e-mail ou senha errados, conta bloqueada ou sem senha, todos com a mesma resposta; na troca, a senha atual errada | mostre uma mensagem só, sem dizer qual dado errou |
|
|
130
|
+
| `WEAK_PASSWORD` | a senha nova não passa na política; a mensagem diz a regra | mostre a mensagem e peça outra senha |
|
|
131
|
+
| `CURRENT_PASSWORD_REQUIRED` | `changePasswordForm()` sem a senha atual, numa conta que já tem senha | peça a senha atual |
|
|
132
|
+
| `PASSWORD_ALREADY_SET` | `completePasswordSignUp()` numa conta que já tem senha | leve a pessoa ao login ou ao reset |
|
|
133
|
+
| `SSO_ACCOUNT` | `changePasswordForm()`, `completePasswordSignUp()` ou `confirmPasswordReset()` numa conta que entra com Google ou Microsoft | leve a pessoa ao login pelo provedor dela |
|
|
134
|
+
| `RESET_TOKEN_USED`, `RESET_TOKEN_EXPIRED` | o link de reset já foi usado ou venceu; token desconhecido também chega como `RESET_TOKEN_EXPIRED` | peça um link novo com `requestPasswordReset()` |
|
|
135
|
+
| `PASSWORD_CHANGED_SIGN_IN_AGAIN` | `changePassword()` ou `changePasswordForm()` trocou a senha, mas o novo login falhou; a sessão local já foi limpa | leve a pessoa ao login com a senha nova |
|
|
136
|
+
| `RATE_LIMITED`, `RATE_LIMIT_EXCEEDED` | `requestPasswordReset()` ou `startPasswordSignUp()` pedido vezes demais para o mesmo endereço (`RATE_LIMITED`), ou rotas de senha chamadas vezes demais da mesma rede, nos métodos do formulário próprio também (`RATE_LIMIT_EXCEEDED`); no login, na confirmação do cadastro, na troca e na confirmação do reset do formulário próprio, `RATE_LIMIT_EXCEEDED` também sai quando o IAM está no limite de senhas em processamento | espere `retryAfterSeconds`, quando vier |
|
|
97
137
|
| `INVALID_CODE` | o código digitado não confere | peça para a pessoa conferir o código |
|
|
98
138
|
| `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, `MAGIC_LINK_INVALID` | o link do e-mail venceu, já foi usado ou não vale | peça um código novo |
|
|
99
139
|
| `REDIRECT_NOT_ALLOWED` | o servidor respondeu com redirect | confira o `apiUrl` |
|
package/dist/index.cjs
CHANGED
|
@@ -992,32 +992,20 @@ function optionalString2(value) {
|
|
|
992
992
|
function isMagicLinkState(value) {
|
|
993
993
|
return value === "OK" || value === "EXPIRED" || value === "USED" || value === "INVALID";
|
|
994
994
|
}
|
|
995
|
-
function expectEmailCodeRequestResult(value) {
|
|
996
|
-
const response = (0, import_sdk_core3.expectObject)(
|
|
997
|
-
value,
|
|
998
|
-
"Email code request response",
|
|
999
|
-
coreErrors
|
|
1000
|
-
);
|
|
995
|
+
function expectEmailCodeRequestResult(value, label = "Email code request response") {
|
|
996
|
+
const response = (0, import_sdk_core3.expectObject)(value, label, coreErrors);
|
|
1001
997
|
if (typeof response.receipt !== "string" || !response.receipt.trim()) {
|
|
1002
|
-
throw coreErrors.invalidResponse(
|
|
998
|
+
throw coreErrors.invalidResponse(`${label} has an invalid receipt field`);
|
|
1003
999
|
}
|
|
1004
1000
|
if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
|
|
1005
|
-
throw coreErrors.invalidResponse(
|
|
1006
|
-
"Email code request response has an invalid resendAfterSeconds field"
|
|
1007
|
-
);
|
|
1001
|
+
throw coreErrors.invalidResponse(`${label} has an invalid resendAfterSeconds field`);
|
|
1008
1002
|
}
|
|
1009
1003
|
return { receipt: response.receipt, resendAfterSeconds: response.resendAfterSeconds };
|
|
1010
1004
|
}
|
|
1011
|
-
function expectExchangeCode(value) {
|
|
1012
|
-
const response = (0, import_sdk_core3.expectObject)(
|
|
1013
|
-
value,
|
|
1014
|
-
"Email sign-in exchange code response",
|
|
1015
|
-
coreErrors
|
|
1016
|
-
);
|
|
1005
|
+
function expectExchangeCode(value, label = "Email sign-in exchange code response") {
|
|
1006
|
+
const response = (0, import_sdk_core3.expectObject)(value, label, coreErrors);
|
|
1017
1007
|
if (typeof response.exchangeCode !== "string" || !response.exchangeCode.trim()) {
|
|
1018
|
-
throw coreErrors.invalidResponse(
|
|
1019
|
-
"Email sign-in exchange code response has an invalid exchangeCode field"
|
|
1020
|
-
);
|
|
1008
|
+
throw coreErrors.invalidResponse(`${label} has an invalid exchangeCode field`);
|
|
1021
1009
|
}
|
|
1022
1010
|
return response.exchangeCode;
|
|
1023
1011
|
}
|
|
@@ -1165,6 +1153,144 @@ var EmailCodeFlow = class {
|
|
|
1165
1153
|
}
|
|
1166
1154
|
};
|
|
1167
1155
|
|
|
1156
|
+
// src/modules/password-form-flow.ts
|
|
1157
|
+
var PASSWORD_PATH = "/api/v1/auth/password";
|
|
1158
|
+
var LOGIN_PATH = `${PASSWORD_PATH}/login`;
|
|
1159
|
+
var SIGNUP_PATH = `${PASSWORD_PATH}/signup`;
|
|
1160
|
+
var SIGNUP_VERIFY_PATH = `${SIGNUP_PATH}/verify`;
|
|
1161
|
+
var RESET_CONFIRM_PATH = `${PASSWORD_PATH}/reset/confirm`;
|
|
1162
|
+
var RESET_TOKEN_KEY = "resetToken";
|
|
1163
|
+
var PASSWORD_FORM_NOT_ENABLED = "PASSWORD_FORM_NOT_ENABLED";
|
|
1164
|
+
function passwordChangedSignInAgain(cause) {
|
|
1165
|
+
const error = new MitraApiError(
|
|
1166
|
+
"The password was changed, but signing in again failed. Sign in with the new password.",
|
|
1167
|
+
401,
|
|
1168
|
+
PASSWORD_CHANGED_SIGN_IN_AGAIN
|
|
1169
|
+
);
|
|
1170
|
+
error.cause = cause;
|
|
1171
|
+
return error;
|
|
1172
|
+
}
|
|
1173
|
+
function explainFormNotEnabled(error) {
|
|
1174
|
+
if (!(error instanceof MitraApiError) || error.code !== PASSWORD_FORM_NOT_ENABLED) return error;
|
|
1175
|
+
return new MitraApiError(
|
|
1176
|
+
'This app does not accept the password from its own form. Turn on the "form in the app itself" mode of the password login in the app, or use the methods of the Mitra auth page: signInWithPassword(), signUpWithPassword() and changePassword().',
|
|
1177
|
+
error.status,
|
|
1178
|
+
error.code,
|
|
1179
|
+
error.details,
|
|
1180
|
+
error.retryAfterSeconds
|
|
1181
|
+
);
|
|
1182
|
+
}
|
|
1183
|
+
var PasswordFormFlow = class {
|
|
1184
|
+
appId;
|
|
1185
|
+
client;
|
|
1186
|
+
exchange;
|
|
1187
|
+
constructor(config) {
|
|
1188
|
+
this.appId = config.appId;
|
|
1189
|
+
this.client = config.client;
|
|
1190
|
+
this.exchange = config.exchange;
|
|
1191
|
+
}
|
|
1192
|
+
async signIn(credentials) {
|
|
1193
|
+
const browserWindow = this.requireBrowser();
|
|
1194
|
+
return this.formRequest(async () => {
|
|
1195
|
+
const exchangeCode = expectExchangeCode(
|
|
1196
|
+
await this.client.post(LOGIN_PATH, {
|
|
1197
|
+
email: credentials.email,
|
|
1198
|
+
password: credentials.password,
|
|
1199
|
+
appId: this.appId,
|
|
1200
|
+
origin: browserWindow.location.origin
|
|
1201
|
+
}),
|
|
1202
|
+
"Password login response"
|
|
1203
|
+
);
|
|
1204
|
+
return this.exchange.redeemExchangeCode(exchangeCode);
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
async startSignUp(request) {
|
|
1208
|
+
const browserWindow = this.requireBrowser();
|
|
1209
|
+
return expectEmailCodeRequestResult(
|
|
1210
|
+
await this.client.post(SIGNUP_PATH, {
|
|
1211
|
+
email: request.email,
|
|
1212
|
+
appId: this.appId,
|
|
1213
|
+
origin: browserWindow.location.origin,
|
|
1214
|
+
language: resolveLanguage(request.language, browserWindow)
|
|
1215
|
+
}),
|
|
1216
|
+
"Password sign-up request response"
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
async completeSignUp(completion) {
|
|
1220
|
+
this.requireBrowser();
|
|
1221
|
+
return this.formRequest(async () => {
|
|
1222
|
+
const exchangeCode = expectExchangeCode(
|
|
1223
|
+
await this.client.post(SIGNUP_VERIFY_PATH, {
|
|
1224
|
+
receipt: completion.receipt,
|
|
1225
|
+
code: completion.code,
|
|
1226
|
+
password: completion.password
|
|
1227
|
+
}),
|
|
1228
|
+
"Password sign-up verification response"
|
|
1229
|
+
);
|
|
1230
|
+
return this.exchange.redeemExchangeCode(exchangeCode);
|
|
1231
|
+
});
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* The token goes in the header by hand, on a client that never retries. IAM
|
|
1235
|
+
* answers a wrong current password with `401`, and a client that refreshes
|
|
1236
|
+
* and retries on `401` would spend a second guess against the account's
|
|
1237
|
+
* lockout with the same password.
|
|
1238
|
+
*/
|
|
1239
|
+
async changePassword(change, accessToken) {
|
|
1240
|
+
this.requireBrowser();
|
|
1241
|
+
return this.formRequest(async () => {
|
|
1242
|
+
await this.client.request(PASSWORD_PATH, {
|
|
1243
|
+
method: "PUT",
|
|
1244
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
1245
|
+
body: {
|
|
1246
|
+
...change.currentPassword === void 0 ? {} : { currentPassword: change.currentPassword },
|
|
1247
|
+
newPassword: change.newPassword
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* The whole fragment leaves the URL, not only the token: the link IAM sends
|
|
1254
|
+
* to `/reset-password` carries only the token and the language of the
|
|
1255
|
+
* message, and the token would otherwise stay in the history and in every
|
|
1256
|
+
* reload.
|
|
1257
|
+
*/
|
|
1258
|
+
readResetToken() {
|
|
1259
|
+
const browserWindow = this.requireBrowser();
|
|
1260
|
+
const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
|
|
1261
|
+
if (!params.has(RESET_TOKEN_KEY)) return null;
|
|
1262
|
+
browserWindow.history.replaceState(
|
|
1263
|
+
{},
|
|
1264
|
+
"",
|
|
1265
|
+
`${browserWindow.location.pathname}${browserWindow.location.search}`
|
|
1266
|
+
);
|
|
1267
|
+
const token = params.get(RESET_TOKEN_KEY)?.trim();
|
|
1268
|
+
return token || null;
|
|
1269
|
+
}
|
|
1270
|
+
async confirmReset(confirmation) {
|
|
1271
|
+
this.requireBrowser();
|
|
1272
|
+
return this.formRequest(async () => {
|
|
1273
|
+
await this.client.post(RESET_CONFIRM_PATH, {
|
|
1274
|
+
token: confirmation.token,
|
|
1275
|
+
newPassword: confirmation.newPassword
|
|
1276
|
+
});
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
async formRequest(request) {
|
|
1280
|
+
try {
|
|
1281
|
+
return await request();
|
|
1282
|
+
} catch (error) {
|
|
1283
|
+
throw explainFormNotEnabled(error);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
requireBrowser() {
|
|
1287
|
+
if (globalThis.window === void 0) {
|
|
1288
|
+
throw new Error("Password login is only available in a browser.");
|
|
1289
|
+
}
|
|
1290
|
+
return globalThis.window;
|
|
1291
|
+
}
|
|
1292
|
+
};
|
|
1293
|
+
|
|
1168
1294
|
// src/modules/auth.ts
|
|
1169
1295
|
var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
|
|
1170
1296
|
var LOGOUT_PATH = "/api/v1/auth/logout";
|
|
@@ -1258,6 +1384,7 @@ var AuthModule = class {
|
|
|
1258
1384
|
emailAuth;
|
|
1259
1385
|
passwordAuth;
|
|
1260
1386
|
emailCode;
|
|
1387
|
+
passwordForm;
|
|
1261
1388
|
brand = null;
|
|
1262
1389
|
constructor(appId, iamBaseUrl, options = {}) {
|
|
1263
1390
|
this.appId = appId;
|
|
@@ -1307,6 +1434,11 @@ var AuthModule = class {
|
|
|
1307
1434
|
client: this.publicClient,
|
|
1308
1435
|
pendingRequest: this.emailAuth
|
|
1309
1436
|
});
|
|
1437
|
+
this.passwordForm = new PasswordFormFlow({
|
|
1438
|
+
appId,
|
|
1439
|
+
client: this.publicClient,
|
|
1440
|
+
exchange: this.passwordAuth
|
|
1441
|
+
});
|
|
1310
1442
|
this.loadFromStorage();
|
|
1311
1443
|
const readAccessToken = () => this.#accessToken;
|
|
1312
1444
|
sessionPorts.set(this, {
|
|
@@ -1352,8 +1484,8 @@ var AuthModule = class {
|
|
|
1352
1484
|
return this._currentUser !== null && this.#accessToken !== null;
|
|
1353
1485
|
}
|
|
1354
1486
|
/**
|
|
1355
|
-
* @deprecated
|
|
1356
|
-
*
|
|
1487
|
+
* @deprecated Use signInWithPassword(), which opens the Mitra auth page,
|
|
1488
|
+
* signInWithPasswordForm() in an app with the form mode on, signInWithEmail() or SSO.
|
|
1357
1489
|
*/
|
|
1358
1490
|
signIn(_credentials) {
|
|
1359
1491
|
return Promise.reject(
|
|
@@ -1603,8 +1735,8 @@ var AuthModule = class {
|
|
|
1603
1735
|
return tokenResponse ? this.establishSession(tokenResponse) : null;
|
|
1604
1736
|
}
|
|
1605
1737
|
/**
|
|
1606
|
-
* @deprecated
|
|
1607
|
-
*
|
|
1738
|
+
* @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
|
|
1739
|
+
* startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
|
|
1608
1740
|
*/
|
|
1609
1741
|
signUp(_data) {
|
|
1610
1742
|
return Promise.reject(
|
|
@@ -1704,9 +1836,12 @@ var AuthModule = class {
|
|
|
1704
1836
|
return this.establishSession(tokenResponse);
|
|
1705
1837
|
}
|
|
1706
1838
|
/**
|
|
1707
|
-
* Asks IAM to email a link to set a new password. Only the address goes
|
|
1708
|
-
* link opens the
|
|
1709
|
-
*
|
|
1839
|
+
* Asks IAM to email a link to set a new password. Only the address goes.
|
|
1840
|
+
* Where the link opens depends on the app's mode of the password login: with
|
|
1841
|
+
* the Mitra auth page, the default, the new password is typed there; with the
|
|
1842
|
+
* form in the app itself, the link opens `/reset-password` on this app's
|
|
1843
|
+
* origin, which reads it with {@link readPasswordResetToken} and finishes
|
|
1844
|
+
* with {@link confirmPasswordReset}.
|
|
1710
1845
|
*
|
|
1711
1846
|
* IAM answers the same whether or not the address has an account, so this
|
|
1712
1847
|
* resolves without saying which.
|
|
@@ -1737,6 +1872,214 @@ var AuthModule = class {
|
|
|
1737
1872
|
})
|
|
1738
1873
|
);
|
|
1739
1874
|
}
|
|
1875
|
+
/**
|
|
1876
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
1877
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
1878
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
1879
|
+
*
|
|
1880
|
+
* Works only when the app has the "form in the app itself" mode of the
|
|
1881
|
+
* password login turned on. Otherwise IAM refuses it with
|
|
1882
|
+
* `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
|
|
1883
|
+
*
|
|
1884
|
+
* Signs in with the address and password typed into the app's own form.
|
|
1885
|
+
*
|
|
1886
|
+
* @returns The authenticated and hydrated user.
|
|
1887
|
+
* @throws {MitraApiError} `INVALID_CREDENTIALS` (status `401`) for a wrong
|
|
1888
|
+
* address or password, a locked account or one without a password, all
|
|
1889
|
+
* answered alike, `SIGNUP_NOT_ALLOWED` (status `403`) when the account lost
|
|
1890
|
+
* its access to an app that takes no new accounts, `RATE_LIMIT_EXCEEDED`
|
|
1891
|
+
* (status `429`, with `retryAfterSeconds` when IAM sends it) when this
|
|
1892
|
+
* network called the password routes too often or IAM is at its limit of
|
|
1893
|
+
* passwords being hashed, so wait `retryAfterSeconds`, and
|
|
1894
|
+
* `PASSWORD_FORM_NOT_ENABLED` as above.
|
|
1895
|
+
*
|
|
1896
|
+
* @example
|
|
1897
|
+
* ```typescript
|
|
1898
|
+
* const user = await mitra.auth.signInWithPasswordForm({ email, password });
|
|
1899
|
+
* ```
|
|
1900
|
+
*/
|
|
1901
|
+
async signInWithPasswordForm(credentials) {
|
|
1902
|
+
return this.establishSession(await this.passwordForm.signIn(credentials));
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
1906
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
1907
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
1908
|
+
*
|
|
1909
|
+
* First step of creating a password from the app's own form: IAM emails a
|
|
1910
|
+
* six-digit code to the address, to prove the mailbox is the person's. No
|
|
1911
|
+
* password goes in this step, which IAM takes in either mode of the app; the
|
|
1912
|
+
* "form in the app itself" mode is required at {@link completePasswordSignUp},
|
|
1913
|
+
* where the password goes. Browser only.
|
|
1914
|
+
*
|
|
1915
|
+
* IAM answers the same whether or not the address has an account, so this
|
|
1916
|
+
* resolves without saying which.
|
|
1917
|
+
*
|
|
1918
|
+
* @param request - The address, and the language of the message.
|
|
1919
|
+
* @returns The receipt that names this request, and the resend delay.
|
|
1920
|
+
* @throws {MitraApiError} `RATE_LIMITED` (with `retryAfterSeconds`) when this
|
|
1921
|
+
* address asked too often, and `RATE_LIMIT_EXCEEDED` (status `429`, with
|
|
1922
|
+
* `retryAfterSeconds` when IAM sends it) when this network called the
|
|
1923
|
+
* password routes too often.
|
|
1924
|
+
*
|
|
1925
|
+
* @example
|
|
1926
|
+
* ```typescript
|
|
1927
|
+
* const { receipt, resendAfterSeconds } = await mitra.auth.startPasswordSignUp({ email });
|
|
1928
|
+
* ```
|
|
1929
|
+
*/
|
|
1930
|
+
async startPasswordSignUp(request) {
|
|
1931
|
+
return this.passwordForm.startSignUp(request);
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
1935
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
1936
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
1937
|
+
*
|
|
1938
|
+
* Works only when the app has the "form in the app itself" mode of the
|
|
1939
|
+
* password login turned on. Otherwise IAM refuses it with
|
|
1940
|
+
* `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
|
|
1941
|
+
*
|
|
1942
|
+
* Second step of {@link startPasswordSignUp}: the code from the message and
|
|
1943
|
+
* the chosen password. The person ends signed in, as with
|
|
1944
|
+
* {@link signInWithPasswordForm}.
|
|
1945
|
+
*
|
|
1946
|
+
* @param completion - The receipt, the code and the password.
|
|
1947
|
+
* @returns The authenticated and hydrated user.
|
|
1948
|
+
* @throws {MitraApiError} `INVALID_CODE` when the code does not match or the
|
|
1949
|
+
* request expired, `MAGIC_LINK_USED` when it was already completed,
|
|
1950
|
+
* `PASSWORD_ALREADY_SET` when the account has a password (the way to replace
|
|
1951
|
+
* it is the reset), `SSO_ACCOUNT` (status `409`) when the account signs in
|
|
1952
|
+
* with Google or Microsoft, `SIGNUP_NOT_ALLOWED` when the app takes no new
|
|
1953
|
+
* accounts, `WEAK_PASSWORD` (status `400`) with the rule the password broke,
|
|
1954
|
+
* `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds` when IAM
|
|
1955
|
+
* sends it) when this network called the password routes too often or IAM is
|
|
1956
|
+
* at its limit of passwords being hashed, so wait `retryAfterSeconds`, and
|
|
1957
|
+
* `PASSWORD_FORM_NOT_ENABLED` as above.
|
|
1958
|
+
*
|
|
1959
|
+
* @example
|
|
1960
|
+
* ```typescript
|
|
1961
|
+
* const user = await mitra.auth.completePasswordSignUp({ receipt, code, password });
|
|
1962
|
+
* ```
|
|
1963
|
+
*/
|
|
1964
|
+
async completePasswordSignUp(completion) {
|
|
1965
|
+
return this.establishSession(await this.passwordForm.completeSignUp(completion));
|
|
1966
|
+
}
|
|
1967
|
+
/**
|
|
1968
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
1969
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
1970
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
1971
|
+
*
|
|
1972
|
+
* Works only when the app has the "form in the app itself" mode of the
|
|
1973
|
+
* password login turned on. Otherwise IAM refuses it with
|
|
1974
|
+
* `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
|
|
1975
|
+
*
|
|
1976
|
+
* Changes the password of the signed-in person from the app's own form. IAM
|
|
1977
|
+
* ends every session of the account when the password changes, this one
|
|
1978
|
+
* included, so the SDK signs in again with the address of this session and
|
|
1979
|
+
* the new password, and that session replaces the current one.
|
|
1980
|
+
*
|
|
1981
|
+
* When the change goes through but that new sign-in fails, the call rejects
|
|
1982
|
+
* with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared,
|
|
1983
|
+
* since IAM already ended it: send the person to sign in with the new password.
|
|
1984
|
+
*
|
|
1985
|
+
* @param change - The current password, required whenever the account
|
|
1986
|
+
* already has one, and the new one.
|
|
1987
|
+
* @returns The user of the new session.
|
|
1988
|
+
* @throws {MitraApiError} `401` when nobody is signed in,
|
|
1989
|
+
* `PASSWORD_CHANGED_SIGN_IN_AGAIN` (status `401`) as above,
|
|
1990
|
+
* `INVALID_CREDENTIALS` (status `401`) for a wrong current password,
|
|
1991
|
+
* `CURRENT_PASSWORD_REQUIRED` and `WEAK_PASSWORD` (status `400`),
|
|
1992
|
+
* `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
|
|
1993
|
+
* Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
|
|
1994
|
+
* when IAM sends it) when this network called the password routes too often
|
|
1995
|
+
* or IAM is at its limit of passwords being hashed, so wait
|
|
1996
|
+
* `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
|
|
1997
|
+
*
|
|
1998
|
+
* @example
|
|
1999
|
+
* ```typescript
|
|
2000
|
+
* await mitra.auth.changePasswordForm({ currentPassword, newPassword });
|
|
2001
|
+
* ```
|
|
2002
|
+
*/
|
|
2003
|
+
async changePasswordForm(change) {
|
|
2004
|
+
if (!this.#accessToken) {
|
|
2005
|
+
throw new MitraApiError("Sign in before changing the password.", 401);
|
|
2006
|
+
}
|
|
2007
|
+
const email = this._currentUser?.email ?? (await this.getCurrentUser()).email;
|
|
2008
|
+
await this.ensureFreshSession();
|
|
2009
|
+
const accessToken = this.#accessToken;
|
|
2010
|
+
if (!accessToken) {
|
|
2011
|
+
throw new MitraApiError("Sign in before changing the password.", 401);
|
|
2012
|
+
}
|
|
2013
|
+
const generation = this.sessionGeneration;
|
|
2014
|
+
await this.passwordForm.changePassword(change, accessToken);
|
|
2015
|
+
try {
|
|
2016
|
+
return await this.signInWithPasswordForm({ email, password: change.newPassword });
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
if (generation === this.sessionGeneration) {
|
|
2019
|
+
this.clearAuthState();
|
|
2020
|
+
}
|
|
2021
|
+
throw passwordChangedSignInAgain(error);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
2026
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
2027
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
2028
|
+
*
|
|
2029
|
+
* The reset token is single use and works as a credential until it is spent:
|
|
2030
|
+
* do not log it either.
|
|
2031
|
+
*
|
|
2032
|
+
* Reads the token of a password reset link that landed on this app, and
|
|
2033
|
+
* removes the fragment from the URL so the token does not stay in the
|
|
2034
|
+
* history. With the form in the app itself turned on, IAM sends the link to
|
|
2035
|
+
* `/reset-password#resetToken=...` on the origin the reset was asked from:
|
|
2036
|
+
* call this when that route loads, then {@link confirmPasswordReset}.
|
|
2037
|
+
*
|
|
2038
|
+
* Nothing is sent to IAM here, and a URL without the link is left as it is.
|
|
2039
|
+
* Browser only.
|
|
2040
|
+
*
|
|
2041
|
+
* @returns The token, or `null` when the URL carries none.
|
|
2042
|
+
*
|
|
2043
|
+
* @example
|
|
2044
|
+
* ```typescript
|
|
2045
|
+
* const token = mitra.auth.readPasswordResetToken();
|
|
2046
|
+
* ```
|
|
2047
|
+
*/
|
|
2048
|
+
readPasswordResetToken() {
|
|
2049
|
+
return this.passwordForm.readResetToken();
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* The password goes through the app's code. Do not store it, do not log it
|
|
2053
|
+
* and do not send it anywhere other than this method. The safer default is
|
|
2054
|
+
* signInWithPassword(), which uses the Mitra auth page.
|
|
2055
|
+
*
|
|
2056
|
+
* Works only when the app has the "form in the app itself" mode of the
|
|
2057
|
+
* password login turned on. Otherwise IAM refuses it with
|
|
2058
|
+
* `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
|
|
2059
|
+
*
|
|
2060
|
+
* Sets the new password with the token from the reset link. The link is
|
|
2061
|
+
* single use, and IAM ends every session of the account, so the person signs
|
|
2062
|
+
* in afterwards with the new password; this method signs nobody in.
|
|
2063
|
+
*
|
|
2064
|
+
* @param confirmation - The token from {@link readPasswordResetToken} and the
|
|
2065
|
+
* new password.
|
|
2066
|
+
* @throws {MitraApiError} `RESET_TOKEN_USED` or `RESET_TOKEN_EXPIRED` (status
|
|
2067
|
+
* `409`) when the link can no longer be used; a token IAM does not know also
|
|
2068
|
+
* answers `RESET_TOKEN_EXPIRED`. Also `WEAK_PASSWORD` (status `400`),
|
|
2069
|
+
* `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
|
|
2070
|
+
* Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
|
|
2071
|
+
* when IAM sends it) when this network called the password routes too often
|
|
2072
|
+
* or IAM is at its limit of passwords being hashed, so wait
|
|
2073
|
+
* `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
|
|
2074
|
+
*
|
|
2075
|
+
* @example
|
|
2076
|
+
* ```typescript
|
|
2077
|
+
* await mitra.auth.confirmPasswordReset({ token, newPassword });
|
|
2078
|
+
* ```
|
|
2079
|
+
*/
|
|
2080
|
+
async confirmPasswordReset(confirmation) {
|
|
2081
|
+
return this.passwordForm.confirmReset(confirmation);
|
|
2082
|
+
}
|
|
1740
2083
|
/**
|
|
1741
2084
|
* Signs out the current user, clearing all auth state and localStorage.
|
|
1742
2085
|
*
|
|
@@ -2899,6 +3242,7 @@ function createBrowserAgentCredentialsModule(httpClient) {
|
|
|
2899
3242
|
return {
|
|
2900
3243
|
list: (options) => core.list(options),
|
|
2901
3244
|
listModels: (agentId, options) => core.listModels(agentId, options),
|
|
3245
|
+
providers: (agentId, options) => core.providers(agentId, options),
|
|
2902
3246
|
usage: (provider, options) => {
|
|
2903
3247
|
requireProvider(provider, ["ANTHROPIC", "OPENAI"], "Subscription usage");
|
|
2904
3248
|
return core.usage(provider, options);
|