@mitralab.io/platform-sdk 1.5.0 → 1.7.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 +30 -0
- package/README.md +3 -2
- package/dist/index.cjs +56 -3
- package/dist/index.d.cts +49 -1
- package/dist/index.d.ts +49 -1
- package/dist/index.js +56 -3
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## 1.7.0-beta.0
|
|
6
|
+
|
|
7
|
+
- `auth.allTokens` gains a fourth family, `backoffice`: the access token of the person's own
|
|
8
|
+
backoffice grant (`accessToken`, `tokenType`, `expiresIn`), for an app that reaches the backoffice
|
|
9
|
+
of the Mitra brand with the access they already have there. It is `null` unless IAM enabled the
|
|
10
|
+
app for this token and the person is staff with a backoffice grant, and a malformed part reads as
|
|
11
|
+
`null` without failing the login, as the other families already do.
|
|
12
|
+
- It is the only family without a `refreshToken`: the backoffice refresh is accepted only on an
|
|
13
|
+
internal IAM route. IAM mints a new one on every app refresh instead, so on a refresh the field
|
|
14
|
+
follows the `platform` rule and is replaced by what IAM sent, `null` included. A `null` there is
|
|
15
|
+
how a grant the person lost, or an app taken out of the flag, arrives.
|
|
16
|
+
- `auth.ensureFreshBackofficeToken()` answers that token, refreshing the app session first when it
|
|
17
|
+
is within 60 seconds of expiring, and `null` when this session has none. The backoffice access
|
|
18
|
+
lives one hour while the app session lives far longer, so reading the field directly would hand
|
|
19
|
+
out a dead token from the second hour on. The refresh is shared with every other caller, and a
|
|
20
|
+
transient failure answers the token in hand instead of dropping it. A login by another person
|
|
21
|
+
landing during the refresh answers `null`, never their token.
|
|
22
|
+
- An `allTokens` carrying only `backoffice` is no longer read as empty.
|
|
23
|
+
- A session stored by 1.6.0 or earlier carries no `backoffice` key, so it reads as `null` until the
|
|
24
|
+
next app refresh. An app that needs the token right after the upgrade can call
|
|
25
|
+
`auth.refreshSession()` once.
|
|
26
|
+
- Export `BackofficeToken`.
|
|
27
|
+
|
|
28
|
+
## 1.6.0
|
|
29
|
+
|
|
30
|
+
- Depend on `@mitralab.io/sdk-core@0.2.13`: `AgentTurnUsage` gains `contextTokens`, the tokens
|
|
31
|
+
occupying the chat's context window at the end of the turn (subagents excluded), and
|
|
32
|
+
`contextWindow`, the model's window size. Both show live in `turnEnd` and `sendAndWait` and in
|
|
33
|
+
the `agent` item of the history, and are absent when the box does not report them.
|
|
34
|
+
|
|
5
35
|
## 1.5.0
|
|
6
36
|
|
|
7
37
|
Stable release of the 1.5.0-beta line, already on the `beta` tag.
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Mitra Platform SDK
|
|
2
2
|
|
|
3
|
-
[](https://sonar.mitralab.ai/dashboard?id=mitra-platform-sdk)
|
|
4
|
+
[](https://sonar.mitralab.ai/dashboard?id=mitra-platform-sdk)
|
|
5
5
|
|
|
6
6
|
SDK JavaScript e TypeScript para apps de browser feitos na Mitra: login da pessoa, dados do app, Server Functions, queries, integrações e chats de agente. Para código que roda dentro de uma Server Function, use [`@mitralab.io/functions-sdk`](https://www.npmjs.com/package/@mitralab.io/functions-sdk).
|
|
7
7
|
|
|
@@ -95,6 +95,7 @@ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar po
|
|
|
95
95
|
- Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled` e o login por e-mail dependem dele.
|
|
96
96
|
- Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()` ou `completeEmailSignInRedirect()` do método que você usa. Cada um devolve `null` quando a URL não é dele. O link do e-mail completa o login no mesmo browser que pediu o código; em outro aparelho, a pessoa digita o código.
|
|
97
97
|
- A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa.
|
|
98
|
+
- Alguns apps recebem tokens extras junto da sessão, em `auth.allTokens`, liberados app por app pela Mitra. O de backoffice é o mais sensível: ele carrega os acessos que a pessoa tem no backoffice da Mitra, vale uma hora e fica no mesmo `localStorage` da sessão, onde qualquer script do domínio do app consegue ler. Leia ele por `auth.ensureFreshBackofficeToken()`, que renova o token quando está perto de vencer e devolve `null` quando o app ou a pessoa não têm esse acesso. Use só contra o backoffice e não repasse para outro serviço.
|
|
98
99
|
- O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
|
|
99
100
|
- Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
|
|
100
101
|
|
package/dist/index.cjs
CHANGED
|
@@ -505,12 +505,20 @@ function readMitraSpaceToken(value) {
|
|
|
505
505
|
if (!isNonEmptyString(token) || !isNonEmptyString(tokenType)) return null;
|
|
506
506
|
return Object.freeze({ token, tokenType });
|
|
507
507
|
}
|
|
508
|
+
function readBackofficeToken(value) {
|
|
509
|
+
if (!isPlainObject(value)) return null;
|
|
510
|
+
const { accessToken, tokenType, expiresIn } = value;
|
|
511
|
+
if (!isNonEmptyString(accessToken) || !isNonEmptyString(tokenType)) return null;
|
|
512
|
+
if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn)) return null;
|
|
513
|
+
return Object.freeze({ accessToken, tokenType, expiresIn });
|
|
514
|
+
}
|
|
508
515
|
function normalizeAllTokens(value) {
|
|
509
516
|
if (!isPlainObject(value)) return void 0;
|
|
510
517
|
return Object.freeze({
|
|
511
518
|
platform: readSessionPair(value.platform),
|
|
512
519
|
mitraSpace: readMitraSpaceToken(value.mitraSpace),
|
|
513
|
-
b2bToken: readSessionPair(value.b2bToken)
|
|
520
|
+
b2bToken: readSessionPair(value.b2bToken),
|
|
521
|
+
backoffice: readBackofficeToken(value.backoffice)
|
|
514
522
|
});
|
|
515
523
|
}
|
|
516
524
|
function expectAuthTokenResponse(value) {
|
|
@@ -1092,6 +1100,7 @@ var EmailCodeFlow = class {
|
|
|
1092
1100
|
|
|
1093
1101
|
// src/modules/auth.ts
|
|
1094
1102
|
var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
|
|
1103
|
+
var DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS = 6e4;
|
|
1095
1104
|
var sessionPorts = /* @__PURE__ */ new WeakMap();
|
|
1096
1105
|
function getAuthSessionPort(auth) {
|
|
1097
1106
|
const port = sessionPorts.get(auth);
|
|
@@ -1126,7 +1135,9 @@ function isTokenExpiring(token, minValidityMs) {
|
|
|
1126
1135
|
return exp * 1e3 - Date.now() < minValidityMs;
|
|
1127
1136
|
}
|
|
1128
1137
|
function discardEmptyAllTokens(tokens) {
|
|
1129
|
-
if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken)
|
|
1138
|
+
if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken && !tokens.backoffice) {
|
|
1139
|
+
return null;
|
|
1140
|
+
}
|
|
1130
1141
|
return tokens;
|
|
1131
1142
|
}
|
|
1132
1143
|
function mergeAllTokens(current, incoming) {
|
|
@@ -1134,7 +1145,8 @@ function mergeAllTokens(current, incoming) {
|
|
|
1134
1145
|
return discardEmptyAllTokens(Object.freeze({
|
|
1135
1146
|
platform: incoming.platform,
|
|
1136
1147
|
mitraSpace: incoming.mitraSpace ?? current?.mitraSpace ?? null,
|
|
1137
|
-
b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null
|
|
1148
|
+
b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null,
|
|
1149
|
+
backoffice: incoming.backoffice
|
|
1138
1150
|
}));
|
|
1139
1151
|
}
|
|
1140
1152
|
function isDefinitiveRefreshFailure(error) {
|
|
@@ -1230,6 +1242,10 @@ var AuthModule = class {
|
|
|
1230
1242
|
* on each app refresh, and these changes are not announced to auth-state
|
|
1231
1243
|
* listeners, so read them here right before use instead of caching them.
|
|
1232
1244
|
*
|
|
1245
|
+
* The `backoffice` token is read through {@link ensureFreshBackofficeToken}
|
|
1246
|
+
* instead, which renews it: it expires well before the app session that
|
|
1247
|
+
* carries it.
|
|
1248
|
+
*
|
|
1233
1249
|
* @example
|
|
1234
1250
|
* ```typescript
|
|
1235
1251
|
* const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
|
|
@@ -1704,6 +1720,43 @@ var AuthModule = class {
|
|
|
1704
1720
|
if (!isTokenExpiring(this.#accessToken, minValidityMs)) return true;
|
|
1705
1721
|
return this.refreshSession();
|
|
1706
1722
|
}
|
|
1723
|
+
/**
|
|
1724
|
+
* The backoffice token of {@link allTokens}, renewed when it is close to
|
|
1725
|
+
* expiring.
|
|
1726
|
+
*
|
|
1727
|
+
* Renewing it means refreshing the app session, which this method does when
|
|
1728
|
+
* the token is within `minValidityMs` of its expiry. Call it before each
|
|
1729
|
+
* backoffice request: refreshes are shared with every other caller, so it
|
|
1730
|
+
* costs one request per expiry, not one per call. The expiry is read from the
|
|
1731
|
+
* JWT as a scheduling heuristic, the same as {@link ensureFreshSession}, so a
|
|
1732
|
+
* token whose `exp` cannot be read is used as it is.
|
|
1733
|
+
*
|
|
1734
|
+
* @param minValidityMs - Minimum remaining token lifetime. Defaults to 60 seconds.
|
|
1735
|
+
* @returns The token to use, or `null` when this session has none, when the
|
|
1736
|
+
* refresh reports the grant is gone, or when another person signed in while
|
|
1737
|
+
* the refresh was in flight. A refresh that fails transiently keeps the
|
|
1738
|
+
* session, so the token in hand is returned and the receiving service decides.
|
|
1739
|
+
*
|
|
1740
|
+
* @example
|
|
1741
|
+
* ```typescript
|
|
1742
|
+
* const backoffice = await mitra.auth.ensureFreshBackofficeToken();
|
|
1743
|
+
* if (!backoffice) return renderWithoutAdminArea();
|
|
1744
|
+
* const authorization = `${backoffice.tokenType} ${backoffice.accessToken}`;
|
|
1745
|
+
* await fetch(url, { headers: { Authorization: authorization } });
|
|
1746
|
+
* ```
|
|
1747
|
+
*/
|
|
1748
|
+
async ensureFreshBackofficeToken(minValidityMs = DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS) {
|
|
1749
|
+
if (!Number.isFinite(minValidityMs) || minValidityMs < 0) {
|
|
1750
|
+
throw new RangeError("minValidityMs must be a finite non-negative number");
|
|
1751
|
+
}
|
|
1752
|
+
const current = this.#allTokens?.backoffice ?? null;
|
|
1753
|
+
if (!current) return null;
|
|
1754
|
+
if (!isTokenExpiring(current.accessToken, minValidityMs)) return current;
|
|
1755
|
+
const generation = this.sessionGeneration;
|
|
1756
|
+
await this.refreshSession();
|
|
1757
|
+
if (generation !== this.sessionGeneration) return null;
|
|
1758
|
+
return this.#allTokens?.backoffice ?? null;
|
|
1759
|
+
}
|
|
1707
1760
|
/**
|
|
1708
1761
|
* Subscribes an internal boundary to token changes without triggering login
|
|
1709
1762
|
* or refresh. Unlike auth-state listeners, this callback is not invoked
|
package/dist/index.d.cts
CHANGED
|
@@ -263,6 +263,19 @@ interface MitraSpaceToken {
|
|
|
263
263
|
readonly token: string;
|
|
264
264
|
readonly tokenType: string;
|
|
265
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Access token for the backoffice of the Mitra brand, so an app can reach it
|
|
268
|
+
* with the access the person already has there. It carries the resources of
|
|
269
|
+
* their backoffice grant and no refresh token, because the backoffice refresh
|
|
270
|
+
* is only accepted on an internal IAM route: in the browser it is replaced by
|
|
271
|
+
* the app refresh, which mints a new one.
|
|
272
|
+
*/
|
|
273
|
+
interface BackofficeToken {
|
|
274
|
+
readonly accessToken: string;
|
|
275
|
+
readonly tokenType: string;
|
|
276
|
+
/** Lifetime of `accessToken` in seconds, as IAM issued it. Renewal reads the JWT `exp`, not this. */
|
|
277
|
+
readonly expiresIn: number;
|
|
278
|
+
}
|
|
266
279
|
/**
|
|
267
280
|
* Extra tokens IAM returns at login only for apps enabled server-side. The SDK
|
|
268
281
|
* hands out frozen instances: the object is persisted with the session, so a
|
|
@@ -275,6 +288,11 @@ interface AllTokens {
|
|
|
275
288
|
readonly mitraSpace: MitraSpaceToken | null;
|
|
276
289
|
/** Session of the same person in the IAM of another environment, or null on any failure there. */
|
|
277
290
|
readonly b2bToken: PlatformSessionTokens | null;
|
|
291
|
+
/**
|
|
292
|
+
* Null unless the app is enabled for this token and the person is Mitra staff with a backoffice
|
|
293
|
+
* grant, and null again on the first app refresh after either stops holding.
|
|
294
|
+
*/
|
|
295
|
+
readonly backoffice: BackofficeToken | null;
|
|
278
296
|
}
|
|
279
297
|
/** Callback for auth state changes. Receives the user on login, null on logout. */
|
|
280
298
|
type AuthStateChangeCallback = (user: User | null) => void;
|
|
@@ -329,6 +347,10 @@ declare class AuthModule {
|
|
|
329
347
|
* on each app refresh, and these changes are not announced to auth-state
|
|
330
348
|
* listeners, so read them here right before use instead of caching them.
|
|
331
349
|
*
|
|
350
|
+
* The `backoffice` token is read through {@link ensureFreshBackofficeToken}
|
|
351
|
+
* instead, which renews it: it expires well before the app session that
|
|
352
|
+
* carries it.
|
|
353
|
+
*
|
|
332
354
|
* @example
|
|
333
355
|
* ```typescript
|
|
334
356
|
* const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
|
|
@@ -657,6 +679,32 @@ declare class AuthModule {
|
|
|
657
679
|
* the current session available for a reactive server-authoritative fallback.
|
|
658
680
|
*/
|
|
659
681
|
ensureFreshSession(minValidityMs?: number): Promise<boolean>;
|
|
682
|
+
/**
|
|
683
|
+
* The backoffice token of {@link allTokens}, renewed when it is close to
|
|
684
|
+
* expiring.
|
|
685
|
+
*
|
|
686
|
+
* Renewing it means refreshing the app session, which this method does when
|
|
687
|
+
* the token is within `minValidityMs` of its expiry. Call it before each
|
|
688
|
+
* backoffice request: refreshes are shared with every other caller, so it
|
|
689
|
+
* costs one request per expiry, not one per call. The expiry is read from the
|
|
690
|
+
* JWT as a scheduling heuristic, the same as {@link ensureFreshSession}, so a
|
|
691
|
+
* token whose `exp` cannot be read is used as it is.
|
|
692
|
+
*
|
|
693
|
+
* @param minValidityMs - Minimum remaining token lifetime. Defaults to 60 seconds.
|
|
694
|
+
* @returns The token to use, or `null` when this session has none, when the
|
|
695
|
+
* refresh reports the grant is gone, or when another person signed in while
|
|
696
|
+
* the refresh was in flight. A refresh that fails transiently keeps the
|
|
697
|
+
* session, so the token in hand is returned and the receiving service decides.
|
|
698
|
+
*
|
|
699
|
+
* @example
|
|
700
|
+
* ```typescript
|
|
701
|
+
* const backoffice = await mitra.auth.ensureFreshBackofficeToken();
|
|
702
|
+
* if (!backoffice) return renderWithoutAdminArea();
|
|
703
|
+
* const authorization = `${backoffice.tokenType} ${backoffice.accessToken}`;
|
|
704
|
+
* await fetch(url, { headers: { Authorization: authorization } });
|
|
705
|
+
* ```
|
|
706
|
+
*/
|
|
707
|
+
ensureFreshBackofficeToken(minValidityMs?: number): Promise<BackofficeToken | null>;
|
|
660
708
|
/**
|
|
661
709
|
* Subscribes an internal boundary to token changes without triggering login
|
|
662
710
|
* or refresh. Unlike auth-state listeners, this callback is not invoked
|
|
@@ -1223,4 +1271,4 @@ type StopServerFunctionExecutionResponse = LegacyTypes.StopServerFunctionExecuti
|
|
|
1223
1271
|
/** @deprecated Legacy compatibility type. */
|
|
1224
1272
|
type UpdateRecordOptions = LegacyTypes.UpdateRecordOptions;
|
|
1225
1273
|
|
|
1226
|
-
export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
|
|
1274
|
+
export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type BackofficeToken, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
|
package/dist/index.d.ts
CHANGED
|
@@ -263,6 +263,19 @@ interface MitraSpaceToken {
|
|
|
263
263
|
readonly token: string;
|
|
264
264
|
readonly tokenType: string;
|
|
265
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Access token for the backoffice of the Mitra brand, so an app can reach it
|
|
268
|
+
* with the access the person already has there. It carries the resources of
|
|
269
|
+
* their backoffice grant and no refresh token, because the backoffice refresh
|
|
270
|
+
* is only accepted on an internal IAM route: in the browser it is replaced by
|
|
271
|
+
* the app refresh, which mints a new one.
|
|
272
|
+
*/
|
|
273
|
+
interface BackofficeToken {
|
|
274
|
+
readonly accessToken: string;
|
|
275
|
+
readonly tokenType: string;
|
|
276
|
+
/** Lifetime of `accessToken` in seconds, as IAM issued it. Renewal reads the JWT `exp`, not this. */
|
|
277
|
+
readonly expiresIn: number;
|
|
278
|
+
}
|
|
266
279
|
/**
|
|
267
280
|
* Extra tokens IAM returns at login only for apps enabled server-side. The SDK
|
|
268
281
|
* hands out frozen instances: the object is persisted with the session, so a
|
|
@@ -275,6 +288,11 @@ interface AllTokens {
|
|
|
275
288
|
readonly mitraSpace: MitraSpaceToken | null;
|
|
276
289
|
/** Session of the same person in the IAM of another environment, or null on any failure there. */
|
|
277
290
|
readonly b2bToken: PlatformSessionTokens | null;
|
|
291
|
+
/**
|
|
292
|
+
* Null unless the app is enabled for this token and the person is Mitra staff with a backoffice
|
|
293
|
+
* grant, and null again on the first app refresh after either stops holding.
|
|
294
|
+
*/
|
|
295
|
+
readonly backoffice: BackofficeToken | null;
|
|
278
296
|
}
|
|
279
297
|
/** Callback for auth state changes. Receives the user on login, null on logout. */
|
|
280
298
|
type AuthStateChangeCallback = (user: User | null) => void;
|
|
@@ -329,6 +347,10 @@ declare class AuthModule {
|
|
|
329
347
|
* on each app refresh, and these changes are not announced to auth-state
|
|
330
348
|
* listeners, so read them here right before use instead of caching them.
|
|
331
349
|
*
|
|
350
|
+
* The `backoffice` token is read through {@link ensureFreshBackofficeToken}
|
|
351
|
+
* instead, which renews it: it expires well before the app session that
|
|
352
|
+
* carries it.
|
|
353
|
+
*
|
|
332
354
|
* @example
|
|
333
355
|
* ```typescript
|
|
334
356
|
* const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
|
|
@@ -657,6 +679,32 @@ declare class AuthModule {
|
|
|
657
679
|
* the current session available for a reactive server-authoritative fallback.
|
|
658
680
|
*/
|
|
659
681
|
ensureFreshSession(minValidityMs?: number): Promise<boolean>;
|
|
682
|
+
/**
|
|
683
|
+
* The backoffice token of {@link allTokens}, renewed when it is close to
|
|
684
|
+
* expiring.
|
|
685
|
+
*
|
|
686
|
+
* Renewing it means refreshing the app session, which this method does when
|
|
687
|
+
* the token is within `minValidityMs` of its expiry. Call it before each
|
|
688
|
+
* backoffice request: refreshes are shared with every other caller, so it
|
|
689
|
+
* costs one request per expiry, not one per call. The expiry is read from the
|
|
690
|
+
* JWT as a scheduling heuristic, the same as {@link ensureFreshSession}, so a
|
|
691
|
+
* token whose `exp` cannot be read is used as it is.
|
|
692
|
+
*
|
|
693
|
+
* @param minValidityMs - Minimum remaining token lifetime. Defaults to 60 seconds.
|
|
694
|
+
* @returns The token to use, or `null` when this session has none, when the
|
|
695
|
+
* refresh reports the grant is gone, or when another person signed in while
|
|
696
|
+
* the refresh was in flight. A refresh that fails transiently keeps the
|
|
697
|
+
* session, so the token in hand is returned and the receiving service decides.
|
|
698
|
+
*
|
|
699
|
+
* @example
|
|
700
|
+
* ```typescript
|
|
701
|
+
* const backoffice = await mitra.auth.ensureFreshBackofficeToken();
|
|
702
|
+
* if (!backoffice) return renderWithoutAdminArea();
|
|
703
|
+
* const authorization = `${backoffice.tokenType} ${backoffice.accessToken}`;
|
|
704
|
+
* await fetch(url, { headers: { Authorization: authorization } });
|
|
705
|
+
* ```
|
|
706
|
+
*/
|
|
707
|
+
ensureFreshBackofficeToken(minValidityMs?: number): Promise<BackofficeToken | null>;
|
|
660
708
|
/**
|
|
661
709
|
* Subscribes an internal boundary to token changes without triggering login
|
|
662
710
|
* or refresh. Unlike auth-state listeners, this callback is not invoked
|
|
@@ -1223,4 +1271,4 @@ type StopServerFunctionExecutionResponse = LegacyTypes.StopServerFunctionExecuti
|
|
|
1223
1271
|
/** @deprecated Legacy compatibility type. */
|
|
1224
1272
|
type UpdateRecordOptions = LegacyTypes.UpdateRecordOptions;
|
|
1225
1273
|
|
|
1226
|
-
export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
|
|
1274
|
+
export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type BackofficeToken, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
|
package/dist/index.js
CHANGED
|
@@ -455,12 +455,20 @@ function readMitraSpaceToken(value) {
|
|
|
455
455
|
if (!isNonEmptyString(token) || !isNonEmptyString(tokenType)) return null;
|
|
456
456
|
return Object.freeze({ token, tokenType });
|
|
457
457
|
}
|
|
458
|
+
function readBackofficeToken(value) {
|
|
459
|
+
if (!isPlainObject(value)) return null;
|
|
460
|
+
const { accessToken, tokenType, expiresIn } = value;
|
|
461
|
+
if (!isNonEmptyString(accessToken) || !isNonEmptyString(tokenType)) return null;
|
|
462
|
+
if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn)) return null;
|
|
463
|
+
return Object.freeze({ accessToken, tokenType, expiresIn });
|
|
464
|
+
}
|
|
458
465
|
function normalizeAllTokens(value) {
|
|
459
466
|
if (!isPlainObject(value)) return void 0;
|
|
460
467
|
return Object.freeze({
|
|
461
468
|
platform: readSessionPair(value.platform),
|
|
462
469
|
mitraSpace: readMitraSpaceToken(value.mitraSpace),
|
|
463
|
-
b2bToken: readSessionPair(value.b2bToken)
|
|
470
|
+
b2bToken: readSessionPair(value.b2bToken),
|
|
471
|
+
backoffice: readBackofficeToken(value.backoffice)
|
|
464
472
|
});
|
|
465
473
|
}
|
|
466
474
|
function expectAuthTokenResponse(value) {
|
|
@@ -1042,6 +1050,7 @@ var EmailCodeFlow = class {
|
|
|
1042
1050
|
|
|
1043
1051
|
// src/modules/auth.ts
|
|
1044
1052
|
var DEFAULT_TOKEN_VALIDITY_MS = 3e4;
|
|
1053
|
+
var DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS = 6e4;
|
|
1045
1054
|
var sessionPorts = /* @__PURE__ */ new WeakMap();
|
|
1046
1055
|
function getAuthSessionPort(auth) {
|
|
1047
1056
|
const port = sessionPorts.get(auth);
|
|
@@ -1076,7 +1085,9 @@ function isTokenExpiring(token, minValidityMs) {
|
|
|
1076
1085
|
return exp * 1e3 - Date.now() < minValidityMs;
|
|
1077
1086
|
}
|
|
1078
1087
|
function discardEmptyAllTokens(tokens) {
|
|
1079
|
-
if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken)
|
|
1088
|
+
if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken && !tokens.backoffice) {
|
|
1089
|
+
return null;
|
|
1090
|
+
}
|
|
1080
1091
|
return tokens;
|
|
1081
1092
|
}
|
|
1082
1093
|
function mergeAllTokens(current, incoming) {
|
|
@@ -1084,7 +1095,8 @@ function mergeAllTokens(current, incoming) {
|
|
|
1084
1095
|
return discardEmptyAllTokens(Object.freeze({
|
|
1085
1096
|
platform: incoming.platform,
|
|
1086
1097
|
mitraSpace: incoming.mitraSpace ?? current?.mitraSpace ?? null,
|
|
1087
|
-
b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null
|
|
1098
|
+
b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null,
|
|
1099
|
+
backoffice: incoming.backoffice
|
|
1088
1100
|
}));
|
|
1089
1101
|
}
|
|
1090
1102
|
function isDefinitiveRefreshFailure(error) {
|
|
@@ -1180,6 +1192,10 @@ var AuthModule = class {
|
|
|
1180
1192
|
* on each app refresh, and these changes are not announced to auth-state
|
|
1181
1193
|
* listeners, so read them here right before use instead of caching them.
|
|
1182
1194
|
*
|
|
1195
|
+
* The `backoffice` token is read through {@link ensureFreshBackofficeToken}
|
|
1196
|
+
* instead, which renews it: it expires well before the app session that
|
|
1197
|
+
* carries it.
|
|
1198
|
+
*
|
|
1183
1199
|
* @example
|
|
1184
1200
|
* ```typescript
|
|
1185
1201
|
* const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
|
|
@@ -1654,6 +1670,43 @@ var AuthModule = class {
|
|
|
1654
1670
|
if (!isTokenExpiring(this.#accessToken, minValidityMs)) return true;
|
|
1655
1671
|
return this.refreshSession();
|
|
1656
1672
|
}
|
|
1673
|
+
/**
|
|
1674
|
+
* The backoffice token of {@link allTokens}, renewed when it is close to
|
|
1675
|
+
* expiring.
|
|
1676
|
+
*
|
|
1677
|
+
* Renewing it means refreshing the app session, which this method does when
|
|
1678
|
+
* the token is within `minValidityMs` of its expiry. Call it before each
|
|
1679
|
+
* backoffice request: refreshes are shared with every other caller, so it
|
|
1680
|
+
* costs one request per expiry, not one per call. The expiry is read from the
|
|
1681
|
+
* JWT as a scheduling heuristic, the same as {@link ensureFreshSession}, so a
|
|
1682
|
+
* token whose `exp` cannot be read is used as it is.
|
|
1683
|
+
*
|
|
1684
|
+
* @param minValidityMs - Minimum remaining token lifetime. Defaults to 60 seconds.
|
|
1685
|
+
* @returns The token to use, or `null` when this session has none, when the
|
|
1686
|
+
* refresh reports the grant is gone, or when another person signed in while
|
|
1687
|
+
* the refresh was in flight. A refresh that fails transiently keeps the
|
|
1688
|
+
* session, so the token in hand is returned and the receiving service decides.
|
|
1689
|
+
*
|
|
1690
|
+
* @example
|
|
1691
|
+
* ```typescript
|
|
1692
|
+
* const backoffice = await mitra.auth.ensureFreshBackofficeToken();
|
|
1693
|
+
* if (!backoffice) return renderWithoutAdminArea();
|
|
1694
|
+
* const authorization = `${backoffice.tokenType} ${backoffice.accessToken}`;
|
|
1695
|
+
* await fetch(url, { headers: { Authorization: authorization } });
|
|
1696
|
+
* ```
|
|
1697
|
+
*/
|
|
1698
|
+
async ensureFreshBackofficeToken(minValidityMs = DEFAULT_BACKOFFICE_TOKEN_VALIDITY_MS) {
|
|
1699
|
+
if (!Number.isFinite(minValidityMs) || minValidityMs < 0) {
|
|
1700
|
+
throw new RangeError("minValidityMs must be a finite non-negative number");
|
|
1701
|
+
}
|
|
1702
|
+
const current = this.#allTokens?.backoffice ?? null;
|
|
1703
|
+
if (!current) return null;
|
|
1704
|
+
if (!isTokenExpiring(current.accessToken, minValidityMs)) return current;
|
|
1705
|
+
const generation = this.sessionGeneration;
|
|
1706
|
+
await this.refreshSession();
|
|
1707
|
+
if (generation !== this.sessionGeneration) return null;
|
|
1708
|
+
return this.#allTokens?.backoffice ?? null;
|
|
1709
|
+
}
|
|
1657
1710
|
/**
|
|
1658
1711
|
* Subscribes an internal boundary to token changes without triggering login
|
|
1659
1712
|
* or refresh. Unlike auth-state listeners, this callback is not invoked
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mitralab.io/platform-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0-beta.2",
|
|
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.2.
|
|
65
|
+
"@mitralab.io/sdk-core": "0.2.13",
|
|
66
66
|
"mitra-interactions-sdk": "1.0.60-beta.48"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|