@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/dist/index.js CHANGED
@@ -942,32 +942,20 @@ function optionalString2(value) {
942
942
  function isMagicLinkState(value) {
943
943
  return value === "OK" || value === "EXPIRED" || value === "USED" || value === "INVALID";
944
944
  }
945
- function expectEmailCodeRequestResult(value) {
946
- const response = expectObject2(
947
- value,
948
- "Email code request response",
949
- coreErrors
950
- );
945
+ function expectEmailCodeRequestResult(value, label = "Email code request response") {
946
+ const response = expectObject2(value, label, coreErrors);
951
947
  if (typeof response.receipt !== "string" || !response.receipt.trim()) {
952
- throw coreErrors.invalidResponse("Email code request response has an invalid receipt field");
948
+ throw coreErrors.invalidResponse(`${label} has an invalid receipt field`);
953
949
  }
954
950
  if (typeof response.resendAfterSeconds !== "number" || !Number.isFinite(response.resendAfterSeconds)) {
955
- throw coreErrors.invalidResponse(
956
- "Email code request response has an invalid resendAfterSeconds field"
957
- );
951
+ throw coreErrors.invalidResponse(`${label} has an invalid resendAfterSeconds field`);
958
952
  }
959
953
  return { receipt: response.receipt, resendAfterSeconds: response.resendAfterSeconds };
960
954
  }
961
- function expectExchangeCode(value) {
962
- const response = expectObject2(
963
- value,
964
- "Email sign-in exchange code response",
965
- coreErrors
966
- );
955
+ function expectExchangeCode(value, label = "Email sign-in exchange code response") {
956
+ const response = expectObject2(value, label, coreErrors);
967
957
  if (typeof response.exchangeCode !== "string" || !response.exchangeCode.trim()) {
968
- throw coreErrors.invalidResponse(
969
- "Email sign-in exchange code response has an invalid exchangeCode field"
970
- );
958
+ throw coreErrors.invalidResponse(`${label} has an invalid exchangeCode field`);
971
959
  }
972
960
  return response.exchangeCode;
973
961
  }
@@ -1115,6 +1103,144 @@ var EmailCodeFlow = class {
1115
1103
  }
1116
1104
  };
1117
1105
 
1106
+ // src/modules/password-form-flow.ts
1107
+ var PASSWORD_PATH = "/api/v1/auth/password";
1108
+ var LOGIN_PATH = `${PASSWORD_PATH}/login`;
1109
+ var SIGNUP_PATH = `${PASSWORD_PATH}/signup`;
1110
+ var SIGNUP_VERIFY_PATH = `${SIGNUP_PATH}/verify`;
1111
+ var RESET_CONFIRM_PATH = `${PASSWORD_PATH}/reset/confirm`;
1112
+ var RESET_TOKEN_KEY = "resetToken";
1113
+ var PASSWORD_FORM_NOT_ENABLED = "PASSWORD_FORM_NOT_ENABLED";
1114
+ function passwordChangedSignInAgain(cause) {
1115
+ const error = new MitraApiError(
1116
+ "The password was changed, but signing in again failed. Sign in with the new password.",
1117
+ 401,
1118
+ PASSWORD_CHANGED_SIGN_IN_AGAIN
1119
+ );
1120
+ error.cause = cause;
1121
+ return error;
1122
+ }
1123
+ function explainFormNotEnabled(error) {
1124
+ if (!(error instanceof MitraApiError) || error.code !== PASSWORD_FORM_NOT_ENABLED) return error;
1125
+ return new MitraApiError(
1126
+ '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().',
1127
+ error.status,
1128
+ error.code,
1129
+ error.details,
1130
+ error.retryAfterSeconds
1131
+ );
1132
+ }
1133
+ var PasswordFormFlow = class {
1134
+ appId;
1135
+ client;
1136
+ exchange;
1137
+ constructor(config) {
1138
+ this.appId = config.appId;
1139
+ this.client = config.client;
1140
+ this.exchange = config.exchange;
1141
+ }
1142
+ async signIn(credentials) {
1143
+ const browserWindow = this.requireBrowser();
1144
+ return this.formRequest(async () => {
1145
+ const exchangeCode = expectExchangeCode(
1146
+ await this.client.post(LOGIN_PATH, {
1147
+ email: credentials.email,
1148
+ password: credentials.password,
1149
+ appId: this.appId,
1150
+ origin: browserWindow.location.origin
1151
+ }),
1152
+ "Password login response"
1153
+ );
1154
+ return this.exchange.redeemExchangeCode(exchangeCode);
1155
+ });
1156
+ }
1157
+ async startSignUp(request) {
1158
+ const browserWindow = this.requireBrowser();
1159
+ return expectEmailCodeRequestResult(
1160
+ await this.client.post(SIGNUP_PATH, {
1161
+ email: request.email,
1162
+ appId: this.appId,
1163
+ origin: browserWindow.location.origin,
1164
+ language: resolveLanguage(request.language, browserWindow)
1165
+ }),
1166
+ "Password sign-up request response"
1167
+ );
1168
+ }
1169
+ async completeSignUp(completion) {
1170
+ this.requireBrowser();
1171
+ return this.formRequest(async () => {
1172
+ const exchangeCode = expectExchangeCode(
1173
+ await this.client.post(SIGNUP_VERIFY_PATH, {
1174
+ receipt: completion.receipt,
1175
+ code: completion.code,
1176
+ password: completion.password
1177
+ }),
1178
+ "Password sign-up verification response"
1179
+ );
1180
+ return this.exchange.redeemExchangeCode(exchangeCode);
1181
+ });
1182
+ }
1183
+ /**
1184
+ * The token goes in the header by hand, on a client that never retries. IAM
1185
+ * answers a wrong current password with `401`, and a client that refreshes
1186
+ * and retries on `401` would spend a second guess against the account's
1187
+ * lockout with the same password.
1188
+ */
1189
+ async changePassword(change, accessToken) {
1190
+ this.requireBrowser();
1191
+ return this.formRequest(async () => {
1192
+ await this.client.request(PASSWORD_PATH, {
1193
+ method: "PUT",
1194
+ headers: { Authorization: `Bearer ${accessToken}` },
1195
+ body: {
1196
+ ...change.currentPassword === void 0 ? {} : { currentPassword: change.currentPassword },
1197
+ newPassword: change.newPassword
1198
+ }
1199
+ });
1200
+ });
1201
+ }
1202
+ /**
1203
+ * The whole fragment leaves the URL, not only the token: the link IAM sends
1204
+ * to `/reset-password` carries only the token and the language of the
1205
+ * message, and the token would otherwise stay in the history and in every
1206
+ * reload.
1207
+ */
1208
+ readResetToken() {
1209
+ const browserWindow = this.requireBrowser();
1210
+ const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
1211
+ if (!params.has(RESET_TOKEN_KEY)) return null;
1212
+ browserWindow.history.replaceState(
1213
+ {},
1214
+ "",
1215
+ `${browserWindow.location.pathname}${browserWindow.location.search}`
1216
+ );
1217
+ const token = params.get(RESET_TOKEN_KEY)?.trim();
1218
+ return token || null;
1219
+ }
1220
+ async confirmReset(confirmation) {
1221
+ this.requireBrowser();
1222
+ return this.formRequest(async () => {
1223
+ await this.client.post(RESET_CONFIRM_PATH, {
1224
+ token: confirmation.token,
1225
+ newPassword: confirmation.newPassword
1226
+ });
1227
+ });
1228
+ }
1229
+ async formRequest(request) {
1230
+ try {
1231
+ return await request();
1232
+ } catch (error) {
1233
+ throw explainFormNotEnabled(error);
1234
+ }
1235
+ }
1236
+ requireBrowser() {
1237
+ if (globalThis.window === void 0) {
1238
+ throw new Error("Password login is only available in a browser.");
1239
+ }
1240
+ return globalThis.window;
1241
+ }
1242
+ };
1243
+
1118
1244
  // src/modules/auth.ts
1119
1245
  var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
1120
1246
  var LOGOUT_PATH = "/api/v1/auth/logout";
@@ -1208,6 +1334,7 @@ var AuthModule = class {
1208
1334
  emailAuth;
1209
1335
  passwordAuth;
1210
1336
  emailCode;
1337
+ passwordForm;
1211
1338
  brand = null;
1212
1339
  constructor(appId, iamBaseUrl, options = {}) {
1213
1340
  this.appId = appId;
@@ -1257,6 +1384,11 @@ var AuthModule = class {
1257
1384
  client: this.publicClient,
1258
1385
  pendingRequest: this.emailAuth
1259
1386
  });
1387
+ this.passwordForm = new PasswordFormFlow({
1388
+ appId,
1389
+ client: this.publicClient,
1390
+ exchange: this.passwordAuth
1391
+ });
1260
1392
  this.loadFromStorage();
1261
1393
  const readAccessToken = () => this.#accessToken;
1262
1394
  sessionPorts.set(this, {
@@ -1302,8 +1434,8 @@ var AuthModule = class {
1302
1434
  return this._currentUser !== null && this.#accessToken !== null;
1303
1435
  }
1304
1436
  /**
1305
- * @deprecated The password never goes through the app's code. Use
1306
- * signInWithPassword(), which opens the Mitra auth page, signInWithEmail() or SSO.
1437
+ * @deprecated Use signInWithPassword(), which opens the Mitra auth page,
1438
+ * signInWithPasswordForm() in an app with the form mode on, signInWithEmail() or SSO.
1307
1439
  */
1308
1440
  signIn(_credentials) {
1309
1441
  return Promise.reject(
@@ -1553,8 +1685,8 @@ var AuthModule = class {
1553
1685
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1554
1686
  }
1555
1687
  /**
1556
- * @deprecated The password never goes through the app's code. Use
1557
- * signUpWithPassword(), which opens the Mitra auth page, signInWithEmail() or SSO.
1688
+ * @deprecated Use signUpWithPassword(), which opens the Mitra auth page,
1689
+ * startPasswordSignUp() in an app with the form mode on, signInWithEmail() or SSO.
1558
1690
  */
1559
1691
  signUp(_data) {
1560
1692
  return Promise.reject(
@@ -1654,9 +1786,12 @@ var AuthModule = class {
1654
1786
  return this.establishSession(tokenResponse);
1655
1787
  }
1656
1788
  /**
1657
- * Asks IAM to email a link to set a new password. Only the address goes: the
1658
- * link opens the Mitra auth page, where the new password is typed, so there
1659
- * is no method here to confirm the reset.
1789
+ * Asks IAM to email a link to set a new password. Only the address goes.
1790
+ * Where the link opens depends on the app's mode of the password login: with
1791
+ * the Mitra auth page, the default, the new password is typed there; with the
1792
+ * form in the app itself, the link opens `/reset-password` on this app's
1793
+ * origin, which reads it with {@link readPasswordResetToken} and finishes
1794
+ * with {@link confirmPasswordReset}.
1660
1795
  *
1661
1796
  * IAM answers the same whether or not the address has an account, so this
1662
1797
  * resolves without saying which.
@@ -1687,6 +1822,214 @@ var AuthModule = class {
1687
1822
  })
1688
1823
  );
1689
1824
  }
1825
+ /**
1826
+ * The password goes through the app's code. Do not store it, do not log it
1827
+ * and do not send it anywhere other than this method. The safer default is
1828
+ * signInWithPassword(), which uses the Mitra auth page.
1829
+ *
1830
+ * Works only when the app has the "form in the app itself" mode of the
1831
+ * password login turned on. Otherwise IAM refuses it with
1832
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1833
+ *
1834
+ * Signs in with the address and password typed into the app's own form.
1835
+ *
1836
+ * @returns The authenticated and hydrated user.
1837
+ * @throws {MitraApiError} `INVALID_CREDENTIALS` (status `401`) for a wrong
1838
+ * address or password, a locked account or one without a password, all
1839
+ * answered alike, `SIGNUP_NOT_ALLOWED` (status `403`) when the account lost
1840
+ * its access to an app that takes no new accounts, `RATE_LIMIT_EXCEEDED`
1841
+ * (status `429`, with `retryAfterSeconds` when IAM sends it) when this
1842
+ * network called the password routes too often or IAM is at its limit of
1843
+ * passwords being hashed, so wait `retryAfterSeconds`, and
1844
+ * `PASSWORD_FORM_NOT_ENABLED` as above.
1845
+ *
1846
+ * @example
1847
+ * ```typescript
1848
+ * const user = await mitra.auth.signInWithPasswordForm({ email, password });
1849
+ * ```
1850
+ */
1851
+ async signInWithPasswordForm(credentials) {
1852
+ return this.establishSession(await this.passwordForm.signIn(credentials));
1853
+ }
1854
+ /**
1855
+ * The password goes through the app's code. Do not store it, do not log it
1856
+ * and do not send it anywhere other than this method. The safer default is
1857
+ * signInWithPassword(), which uses the Mitra auth page.
1858
+ *
1859
+ * First step of creating a password from the app's own form: IAM emails a
1860
+ * six-digit code to the address, to prove the mailbox is the person's. No
1861
+ * password goes in this step, which IAM takes in either mode of the app; the
1862
+ * "form in the app itself" mode is required at {@link completePasswordSignUp},
1863
+ * where the password goes. Browser only.
1864
+ *
1865
+ * IAM answers the same whether or not the address has an account, so this
1866
+ * resolves without saying which.
1867
+ *
1868
+ * @param request - The address, and the language of the message.
1869
+ * @returns The receipt that names this request, and the resend delay.
1870
+ * @throws {MitraApiError} `RATE_LIMITED` (with `retryAfterSeconds`) when this
1871
+ * address asked too often, and `RATE_LIMIT_EXCEEDED` (status `429`, with
1872
+ * `retryAfterSeconds` when IAM sends it) when this network called the
1873
+ * password routes too often.
1874
+ *
1875
+ * @example
1876
+ * ```typescript
1877
+ * const { receipt, resendAfterSeconds } = await mitra.auth.startPasswordSignUp({ email });
1878
+ * ```
1879
+ */
1880
+ async startPasswordSignUp(request) {
1881
+ return this.passwordForm.startSignUp(request);
1882
+ }
1883
+ /**
1884
+ * The password goes through the app's code. Do not store it, do not log it
1885
+ * and do not send it anywhere other than this method. The safer default is
1886
+ * signInWithPassword(), which uses the Mitra auth page.
1887
+ *
1888
+ * Works only when the app has the "form in the app itself" mode of the
1889
+ * password login turned on. Otherwise IAM refuses it with
1890
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1891
+ *
1892
+ * Second step of {@link startPasswordSignUp}: the code from the message and
1893
+ * the chosen password. The person ends signed in, as with
1894
+ * {@link signInWithPasswordForm}.
1895
+ *
1896
+ * @param completion - The receipt, the code and the password.
1897
+ * @returns The authenticated and hydrated user.
1898
+ * @throws {MitraApiError} `INVALID_CODE` when the code does not match or the
1899
+ * request expired, `MAGIC_LINK_USED` when it was already completed,
1900
+ * `PASSWORD_ALREADY_SET` when the account has a password (the way to replace
1901
+ * it is the reset), `SSO_ACCOUNT` (status `409`) when the account signs in
1902
+ * with Google or Microsoft, `SIGNUP_NOT_ALLOWED` when the app takes no new
1903
+ * accounts, `WEAK_PASSWORD` (status `400`) with the rule the password broke,
1904
+ * `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds` when IAM
1905
+ * sends it) when this network called the password routes too often or IAM is
1906
+ * at its limit of passwords being hashed, so wait `retryAfterSeconds`, and
1907
+ * `PASSWORD_FORM_NOT_ENABLED` as above.
1908
+ *
1909
+ * @example
1910
+ * ```typescript
1911
+ * const user = await mitra.auth.completePasswordSignUp({ receipt, code, password });
1912
+ * ```
1913
+ */
1914
+ async completePasswordSignUp(completion) {
1915
+ return this.establishSession(await this.passwordForm.completeSignUp(completion));
1916
+ }
1917
+ /**
1918
+ * The password goes through the app's code. Do not store it, do not log it
1919
+ * and do not send it anywhere other than this method. The safer default is
1920
+ * signInWithPassword(), which uses the Mitra auth page.
1921
+ *
1922
+ * Works only when the app has the "form in the app itself" mode of the
1923
+ * password login turned on. Otherwise IAM refuses it with
1924
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
1925
+ *
1926
+ * Changes the password of the signed-in person from the app's own form. IAM
1927
+ * ends every session of the account when the password changes, this one
1928
+ * included, so the SDK signs in again with the address of this session and
1929
+ * the new password, and that session replaces the current one.
1930
+ *
1931
+ * When the change goes through but that new sign-in fails, the call rejects
1932
+ * with `PASSWORD_CHANGED_SIGN_IN_AGAIN` and the local session is cleared,
1933
+ * since IAM already ended it: send the person to sign in with the new password.
1934
+ *
1935
+ * @param change - The current password, required whenever the account
1936
+ * already has one, and the new one.
1937
+ * @returns The user of the new session.
1938
+ * @throws {MitraApiError} `401` when nobody is signed in,
1939
+ * `PASSWORD_CHANGED_SIGN_IN_AGAIN` (status `401`) as above,
1940
+ * `INVALID_CREDENTIALS` (status `401`) for a wrong current password,
1941
+ * `CURRENT_PASSWORD_REQUIRED` and `WEAK_PASSWORD` (status `400`),
1942
+ * `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
1943
+ * Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
1944
+ * when IAM sends it) when this network called the password routes too often
1945
+ * or IAM is at its limit of passwords being hashed, so wait
1946
+ * `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
1947
+ *
1948
+ * @example
1949
+ * ```typescript
1950
+ * await mitra.auth.changePasswordForm({ currentPassword, newPassword });
1951
+ * ```
1952
+ */
1953
+ async changePasswordForm(change) {
1954
+ if (!this.#accessToken) {
1955
+ throw new MitraApiError("Sign in before changing the password.", 401);
1956
+ }
1957
+ const email = this._currentUser?.email ?? (await this.getCurrentUser()).email;
1958
+ await this.ensureFreshSession();
1959
+ const accessToken = this.#accessToken;
1960
+ if (!accessToken) {
1961
+ throw new MitraApiError("Sign in before changing the password.", 401);
1962
+ }
1963
+ const generation = this.sessionGeneration;
1964
+ await this.passwordForm.changePassword(change, accessToken);
1965
+ try {
1966
+ return await this.signInWithPasswordForm({ email, password: change.newPassword });
1967
+ } catch (error) {
1968
+ if (generation === this.sessionGeneration) {
1969
+ this.clearAuthState();
1970
+ }
1971
+ throw passwordChangedSignInAgain(error);
1972
+ }
1973
+ }
1974
+ /**
1975
+ * The password goes through the app's code. Do not store it, do not log it
1976
+ * and do not send it anywhere other than this method. The safer default is
1977
+ * signInWithPassword(), which uses the Mitra auth page.
1978
+ *
1979
+ * The reset token is single use and works as a credential until it is spent:
1980
+ * do not log it either.
1981
+ *
1982
+ * Reads the token of a password reset link that landed on this app, and
1983
+ * removes the fragment from the URL so the token does not stay in the
1984
+ * history. With the form in the app itself turned on, IAM sends the link to
1985
+ * `/reset-password#resetToken=...` on the origin the reset was asked from:
1986
+ * call this when that route loads, then {@link confirmPasswordReset}.
1987
+ *
1988
+ * Nothing is sent to IAM here, and a URL without the link is left as it is.
1989
+ * Browser only.
1990
+ *
1991
+ * @returns The token, or `null` when the URL carries none.
1992
+ *
1993
+ * @example
1994
+ * ```typescript
1995
+ * const token = mitra.auth.readPasswordResetToken();
1996
+ * ```
1997
+ */
1998
+ readPasswordResetToken() {
1999
+ return this.passwordForm.readResetToken();
2000
+ }
2001
+ /**
2002
+ * The password goes through the app's code. Do not store it, do not log it
2003
+ * and do not send it anywhere other than this method. The safer default is
2004
+ * signInWithPassword(), which uses the Mitra auth page.
2005
+ *
2006
+ * Works only when the app has the "form in the app itself" mode of the
2007
+ * password login turned on. Otherwise IAM refuses it with
2008
+ * `PASSWORD_FORM_NOT_ENABLED` (status `403`). Browser only.
2009
+ *
2010
+ * Sets the new password with the token from the reset link. The link is
2011
+ * single use, and IAM ends every session of the account, so the person signs
2012
+ * in afterwards with the new password; this method signs nobody in.
2013
+ *
2014
+ * @param confirmation - The token from {@link readPasswordResetToken} and the
2015
+ * new password.
2016
+ * @throws {MitraApiError} `RESET_TOKEN_USED` or `RESET_TOKEN_EXPIRED` (status
2017
+ * `409`) when the link can no longer be used; a token IAM does not know also
2018
+ * answers `RESET_TOKEN_EXPIRED`. Also `WEAK_PASSWORD` (status `400`),
2019
+ * `SSO_ACCOUNT` (status `409`) when the account signs in with Google or
2020
+ * Microsoft, `RATE_LIMIT_EXCEEDED` (status `429`, with `retryAfterSeconds`
2021
+ * when IAM sends it) when this network called the password routes too often
2022
+ * or IAM is at its limit of passwords being hashed, so wait
2023
+ * `retryAfterSeconds`, and `PASSWORD_FORM_NOT_ENABLED` as above.
2024
+ *
2025
+ * @example
2026
+ * ```typescript
2027
+ * await mitra.auth.confirmPasswordReset({ token, newPassword });
2028
+ * ```
2029
+ */
2030
+ async confirmPasswordReset(confirmation) {
2031
+ return this.passwordForm.confirmReset(confirmation);
2032
+ }
1690
2033
  /**
1691
2034
  * Signs out the current user, clearing all auth state and localStorage.
1692
2035
  *
@@ -2864,6 +3207,7 @@ function createBrowserAgentCredentialsModule(httpClient) {
2864
3207
  return {
2865
3208
  list: (options) => core.list(options),
2866
3209
  listModels: (agentId, options) => core.listModels(agentId, options),
3210
+ providers: (agentId, options) => core.providers(agentId, options),
2867
3211
  usage: (provider, options) => {
2868
3212
  requireProvider(provider, ["ANTHROPIC", "OPENAI"], "Subscription usage");
2869
3213
  return core.usage(provider, options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/platform-sdk",
3
- "version": "1.8.0-beta.0",
3
+ "version": "1.8.0",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "url": "https://github.com/mitralab-dev/mitra-platform-sdk/issues"
63
63
  },
64
64
  "dependencies": {
65
- "@mitralab.io/sdk-core": "0.3.0",
65
+ "@mitralab.io/sdk-core": "0.3.1",
66
66
  "mitra-interactions-sdk": "1.0.60-beta.48"
67
67
  },
68
68
  "devDependencies": {