mitra-interactions-sdk 1.0.60-beta.26 → 1.0.60-beta.27
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/README.md +5 -7
- package/dist/index.d.mts +23 -17
- package/dist/index.d.ts +23 -17
- package/dist/index.js +28 -280
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +24 -276
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -275,11 +275,9 @@ Retorna uma `AgentTaskSession` que encapsula o ciclo de vida do chat. A task é
|
|
|
275
275
|
```typescript
|
|
276
276
|
import { getAgentTaskMitra } from 'mitra-interactions-sdk';
|
|
277
277
|
|
|
278
|
-
// Chat novo —
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
// Chat com um agente business (system prompt + SFs do agente; token escopado)
|
|
282
|
-
const sales = getAgentTaskMitra({ create: true, agentId: 'uuid-do-agente' });
|
|
278
|
+
// Chat novo — SEMPRE com agentId (sessão sem agente não executa nada).
|
|
279
|
+
// taskId é preenchido no primeiro send() (evento taskCreated)
|
|
280
|
+
const session = getAgentTaskMitra({ create: true, agentId: 'uuid-do-agente', agentType: 'ANTHROPIC_CLAUDE_OPUS', name: 'Meu chat' });
|
|
283
281
|
|
|
284
282
|
// Chat existente
|
|
285
283
|
const existing = getAgentTaskMitra({ taskId: 'uuid-da-task' });
|
|
@@ -289,7 +287,7 @@ await existing.loadHistory({ limit: 50 });
|
|
|
289
287
|
`getAgentTaskMitra({ create: true, agentType?, name?, agentId?, transport? })` ou `getAgentTaskMitra({ taskId, transport? })`.
|
|
290
288
|
|
|
291
289
|
- `agentType` vem de `manageAgentCredentialMitra({ action: 'list_models' })` — ex.: `'ANTHROPIC_CLAUDE_OPUS'`, `'OPENAI_GPT5'`, `'GOOGLE_GEMINI_PRO'`. Default: `'ANTHROPIC_CLAUDE_OPUS'`.
|
|
292
|
-
- **`agentId`**: id de um agente business (CRUD via `mitra-sdk`: `listAgentsMitra` e família). A sessão sobe com o system prompt do agente e um token escopado — as tools enxergam só as Server Functions dele. Sem `agentId
|
|
290
|
+
- **`agentId`**: id de um agente business (CRUD via `mitra-sdk`: `listAgentsMitra` e família). A sessão sobe com o system prompt do agente e um token escopado — as tools enxergam só as Server Functions dele. **Sem `agentId`: sessão business sem agente** — sem system prompt e sem acesso às Server Functions (as tools recusam); não há adoção automática de agente único. Na prática, sempre passe `agentId`.
|
|
293
291
|
|
|
294
292
|
#### Propriedades (somente leitura)
|
|
295
293
|
|
|
@@ -318,7 +316,7 @@ await existing.loadHistory({ limit: 50 });
|
|
|
318
316
|
`statusChange` · `historyLoaded` · `taskCreated` · `turnStart` · `delta` (`{ delta, kind: 'text' | 'thinking' }`) · `tool` (`{ tool, toolId?, input?, content?, phase: 'call' | 'result' }`) · `turnEnd` (`{ content }`) · `cancelled` · `queueChange` · `error` (`{ code?, error }`) · `raw` (eventos não mapeados do stream, ex.: `workspace`).
|
|
319
317
|
|
|
320
318
|
```typescript
|
|
321
|
-
const session = getAgentTaskMitra({ create: true });
|
|
319
|
+
const session = getAgentTaskMitra({ create: true, agentId: 'uuid-do-agente' });
|
|
322
320
|
|
|
323
321
|
session.on('delta', ({ delta, kind }) => { if (kind === 'text') process.stdout.write(delta); });
|
|
324
322
|
session.on('tool', ({ tool, phase }) => console.log('🔧', phase, tool));
|
package/dist/index.d.mts
CHANGED
|
@@ -205,7 +205,7 @@ interface AgentChat {
|
|
|
205
205
|
id: string;
|
|
206
206
|
name: string | null;
|
|
207
207
|
agentType: AgentType;
|
|
208
|
-
/** Agente business dono do chat (null =
|
|
208
|
+
/** Agente business dono do chat (null = sessão business sem agente — não executa nada). */
|
|
209
209
|
agentId: string | null;
|
|
210
210
|
archived: boolean;
|
|
211
211
|
createdAt: string;
|
|
@@ -276,8 +276,10 @@ interface GetAgentTaskCreateOptions {
|
|
|
276
276
|
/**
|
|
277
277
|
* ID de um agente business (CRUD via mitra-sdk: listAgentsMitra e família).
|
|
278
278
|
* Com agentId, a sessão sobe com o system prompt do agente e um token escopado —
|
|
279
|
-
* as tools enxergam só as Server Functions daquele agente.
|
|
280
|
-
*
|
|
279
|
+
* as tools enxergam só as Server Functions daquele agente.
|
|
280
|
+
* Sem agentId: sessão business SEM agente — sem system prompt e sem acesso às
|
|
281
|
+
* Server Functions (as tools recusam). Não há adoção automática de agente
|
|
282
|
+
* único; na prática, sempre passe agentId.
|
|
281
283
|
*/
|
|
282
284
|
agentId?: string;
|
|
283
285
|
/** Transporte do prompt (default 'ws'). */
|
|
@@ -523,29 +525,33 @@ declare function getConfig(): MitraConfig;
|
|
|
523
525
|
declare function resolveProjectId(projectId?: number | string): number | string;
|
|
524
526
|
|
|
525
527
|
/**
|
|
526
|
-
* Mitra Interactions SDK - Autenticação (
|
|
528
|
+
* Mitra Interactions SDK - Autenticação (Novo Mitra)
|
|
527
529
|
*
|
|
528
|
-
*
|
|
529
|
-
* -
|
|
530
|
-
*
|
|
531
|
-
*
|
|
532
|
-
*
|
|
530
|
+
* Implementação do auth para o novo Mitra (Kong gateway).
|
|
531
|
+
* - Email login/signup/refresh: via BFF (mitra-legacy-bff), POST {gateway}/auth/*.
|
|
532
|
+
* O BFF resolve projectId->appId, chama o mitra-iam e já devolve o envelope
|
|
533
|
+
* { token, baseURL, integrationURL } que a SDK consome.
|
|
534
|
+
* - SSO (Google): página atravessadora (sdk-auth.html) faz o start do OAuth e
|
|
535
|
+
* devolve o `code` cru (popup via postMessage, redirect via #codeMitra). A SDK
|
|
536
|
+
* troca o code por token no BFF (POST {gateway}/auth/{provider}), mesmo host do
|
|
537
|
+
* /email/login. Provider-agnóstico: Microsoft entra só mudando a allowlist
|
|
538
|
+
* quando o back liberar o endpoint. Suporta popup (desktop) e redirect (mobile).
|
|
533
539
|
*/
|
|
534
540
|
|
|
535
|
-
declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra', options?: LoginOptions): Promise<LoginResponse>;
|
|
536
|
-
declare function loginWithGoogleMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
537
|
-
declare function loginWithMicrosoftMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
538
|
-
declare function refreshTokenSilently(authUrl: string, projectId: number | string): Promise<LoginResponse>;
|
|
539
541
|
/**
|
|
540
|
-
* Gera o JWT a partir do code do SSO (
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
*
|
|
542
|
+
* Gera o JWT a partir do `code` do SSO (retorno do redirect). Valida o `state`
|
|
543
|
+
* contra o nonce gerado no start (anti-CSRF), troca o code no BFF
|
|
544
|
+
* (POST {gateway}/auth/{provider}) e configura o SDK. Ler/limpar o fragment da
|
|
545
|
+
* URL é responsabilidade do app — aqui só se gera o token.
|
|
544
546
|
*/
|
|
545
547
|
declare function exchangeSsoCodeMitra(options: {
|
|
546
548
|
code: string;
|
|
547
549
|
state: string;
|
|
548
550
|
}): Promise<LoginResponse>;
|
|
551
|
+
declare function loginWithGoogleMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
552
|
+
declare function loginWithMicrosoftMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
553
|
+
declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra', options?: LoginOptions): Promise<LoginResponse>;
|
|
554
|
+
declare function refreshTokenSilently(authUrl: string, _projectId: number | string): Promise<LoginResponse>;
|
|
549
555
|
|
|
550
556
|
/**
|
|
551
557
|
* Mitra Interactions SDK — Agent Chat (via BFF)
|
package/dist/index.d.ts
CHANGED
|
@@ -205,7 +205,7 @@ interface AgentChat {
|
|
|
205
205
|
id: string;
|
|
206
206
|
name: string | null;
|
|
207
207
|
agentType: AgentType;
|
|
208
|
-
/** Agente business dono do chat (null =
|
|
208
|
+
/** Agente business dono do chat (null = sessão business sem agente — não executa nada). */
|
|
209
209
|
agentId: string | null;
|
|
210
210
|
archived: boolean;
|
|
211
211
|
createdAt: string;
|
|
@@ -276,8 +276,10 @@ interface GetAgentTaskCreateOptions {
|
|
|
276
276
|
/**
|
|
277
277
|
* ID de um agente business (CRUD via mitra-sdk: listAgentsMitra e família).
|
|
278
278
|
* Com agentId, a sessão sobe com o system prompt do agente e um token escopado —
|
|
279
|
-
* as tools enxergam só as Server Functions daquele agente.
|
|
280
|
-
*
|
|
279
|
+
* as tools enxergam só as Server Functions daquele agente.
|
|
280
|
+
* Sem agentId: sessão business SEM agente — sem system prompt e sem acesso às
|
|
281
|
+
* Server Functions (as tools recusam). Não há adoção automática de agente
|
|
282
|
+
* único; na prática, sempre passe agentId.
|
|
281
283
|
*/
|
|
282
284
|
agentId?: string;
|
|
283
285
|
/** Transporte do prompt (default 'ws'). */
|
|
@@ -523,29 +525,33 @@ declare function getConfig(): MitraConfig;
|
|
|
523
525
|
declare function resolveProjectId(projectId?: number | string): number | string;
|
|
524
526
|
|
|
525
527
|
/**
|
|
526
|
-
* Mitra Interactions SDK - Autenticação (
|
|
528
|
+
* Mitra Interactions SDK - Autenticação (Novo Mitra)
|
|
527
529
|
*
|
|
528
|
-
*
|
|
529
|
-
* -
|
|
530
|
-
*
|
|
531
|
-
*
|
|
532
|
-
*
|
|
530
|
+
* Implementação do auth para o novo Mitra (Kong gateway).
|
|
531
|
+
* - Email login/signup/refresh: via BFF (mitra-legacy-bff), POST {gateway}/auth/*.
|
|
532
|
+
* O BFF resolve projectId->appId, chama o mitra-iam e já devolve o envelope
|
|
533
|
+
* { token, baseURL, integrationURL } que a SDK consome.
|
|
534
|
+
* - SSO (Google): página atravessadora (sdk-auth.html) faz o start do OAuth e
|
|
535
|
+
* devolve o `code` cru (popup via postMessage, redirect via #codeMitra). A SDK
|
|
536
|
+
* troca o code por token no BFF (POST {gateway}/auth/{provider}), mesmo host do
|
|
537
|
+
* /email/login. Provider-agnóstico: Microsoft entra só mudando a allowlist
|
|
538
|
+
* quando o back liberar o endpoint. Suporta popup (desktop) e redirect (mobile).
|
|
533
539
|
*/
|
|
534
540
|
|
|
535
|
-
declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra', options?: LoginOptions): Promise<LoginResponse>;
|
|
536
|
-
declare function loginWithGoogleMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
537
|
-
declare function loginWithMicrosoftMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
538
|
-
declare function refreshTokenSilently(authUrl: string, projectId: number | string): Promise<LoginResponse>;
|
|
539
541
|
/**
|
|
540
|
-
* Gera o JWT a partir do code do SSO (
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
*
|
|
542
|
+
* Gera o JWT a partir do `code` do SSO (retorno do redirect). Valida o `state`
|
|
543
|
+
* contra o nonce gerado no start (anti-CSRF), troca o code no BFF
|
|
544
|
+
* (POST {gateway}/auth/{provider}) e configura o SDK. Ler/limpar o fragment da
|
|
545
|
+
* URL é responsabilidade do app — aqui só se gera o token.
|
|
544
546
|
*/
|
|
545
547
|
declare function exchangeSsoCodeMitra(options: {
|
|
546
548
|
code: string;
|
|
547
549
|
state: string;
|
|
548
550
|
}): Promise<LoginResponse>;
|
|
551
|
+
declare function loginWithGoogleMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
552
|
+
declare function loginWithMicrosoftMitra(options?: LoginOptions): Promise<LoginResponse>;
|
|
553
|
+
declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra', options?: LoginOptions): Promise<LoginResponse>;
|
|
554
|
+
declare function refreshTokenSilently(authUrl: string, _projectId: number | string): Promise<LoginResponse>;
|
|
549
555
|
|
|
550
556
|
/**
|
|
551
557
|
* Mitra Interactions SDK — Agent Chat (via BFF)
|
package/dist/index.js
CHANGED
|
@@ -1,166 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// src/auth-legacy.ts
|
|
4
|
-
var AUTH_MESSAGE_TYPE = "mitra-auth-result";
|
|
5
|
-
var POPUP_WIDTH = 420;
|
|
6
|
-
var POPUP_HEIGHT = 520;
|
|
7
|
-
function getOriginFromUrl(url) {
|
|
8
|
-
try {
|
|
9
|
-
const parsed = new URL(url);
|
|
10
|
-
return parsed.origin;
|
|
11
|
-
} catch (e) {
|
|
12
|
-
return "";
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
function openAuthPopup(url, expectedOrigin) {
|
|
16
|
-
return new Promise((resolve, reject) => {
|
|
17
|
-
const left = (typeof window.screenX === "number" ? window.screenX : 0) + (window.outerWidth - POPUP_WIDTH) / 2;
|
|
18
|
-
const top = (typeof window.screenY === "number" ? window.screenY : 0) + (window.outerHeight - POPUP_HEIGHT) / 2;
|
|
19
|
-
const popup = window.open(
|
|
20
|
-
url,
|
|
21
|
-
"mitra-auth",
|
|
22
|
-
`width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},menubar=no,toolbar=no,status=no`
|
|
23
|
-
);
|
|
24
|
-
if (!popup) {
|
|
25
|
-
reject(new Error("Popup bloqueado pelo navegador. Permita popups para este site."));
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
function onMessage(event) {
|
|
29
|
-
if (event.origin !== expectedOrigin) return;
|
|
30
|
-
if (!event.data || event.data.type !== AUTH_MESSAGE_TYPE) return;
|
|
31
|
-
cleanup();
|
|
32
|
-
if (event.data.success) {
|
|
33
|
-
resolve(event.data.data);
|
|
34
|
-
} else {
|
|
35
|
-
reject(new Error(event.data.error || "Erro na autentica\xE7\xE3o"));
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
const pollTimer = setInterval(() => {
|
|
39
|
-
if (popup.closed) {
|
|
40
|
-
cleanup();
|
|
41
|
-
reject(new Error("Login cancelado pelo usu\xE1rio"));
|
|
42
|
-
}
|
|
43
|
-
}, 500);
|
|
44
|
-
function cleanup() {
|
|
45
|
-
window.removeEventListener("message", onMessage);
|
|
46
|
-
clearInterval(pollTimer);
|
|
47
|
-
}
|
|
48
|
-
window.addEventListener("message", onMessage);
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
function autoConfigureFromLogin(response, authUrl, projectId) {
|
|
52
|
-
if (!response.baseURL) return;
|
|
53
|
-
configureSdkMitra({
|
|
54
|
-
baseURL: response.baseURL,
|
|
55
|
-
token: response.token,
|
|
56
|
-
authUrl,
|
|
57
|
-
projectId,
|
|
58
|
-
...response.integrationURL ? { integrationURL: response.integrationURL } : {}
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
function buildAuthUrl(authUrl, method, projectId, opts) {
|
|
62
|
-
const base = authUrl.endsWith("/") ? authUrl : authUrl + "/";
|
|
63
|
-
const separator = base.includes("?") ? "&" : "?";
|
|
64
|
-
let url = `${base}${separator}method=${method}&projectId=${encodeURIComponent(projectId)}`;
|
|
65
|
-
if (opts == null ? void 0 : opts.returnTo) url += `&returnTo=${encodeURIComponent(opts.returnTo)}`;
|
|
66
|
-
if (opts == null ? void 0 : opts.create) url += `&create=true`;
|
|
67
|
-
if (opts == null ? void 0 : opts.title) url += `&title=${encodeURIComponent(opts.title)}`;
|
|
68
|
-
if (typeof window !== "undefined") {
|
|
69
|
-
url += `&originUrl=${encodeURIComponent(window.location.href)}`;
|
|
70
|
-
}
|
|
71
|
-
return url;
|
|
72
|
-
}
|
|
73
|
-
function resolveLoginOptions(options) {
|
|
74
|
-
var _a;
|
|
75
|
-
const config = isConfigured() ? getConfig() : null;
|
|
76
|
-
const authUrl = (options == null ? void 0 : options.authUrl) || (config == null ? void 0 : config.authUrl);
|
|
77
|
-
const projectId = (_a = options == null ? void 0 : options.projectId) != null ? _a : config == null ? void 0 : config.projectId;
|
|
78
|
-
if (!authUrl) {
|
|
79
|
-
throw new Error("authUrl \xE9 obrigat\xF3rio. Passe em LoginOptions ou configure via configureSdkMitra({ authUrl }).");
|
|
80
|
-
}
|
|
81
|
-
if (projectId == null) {
|
|
82
|
-
throw new Error("projectId \xE9 obrigat\xF3rio. Passe em LoginOptions ou configure via configureSdkMitra({ projectId }).");
|
|
83
|
-
}
|
|
84
|
-
return { authUrl, projectId };
|
|
85
|
-
}
|
|
86
|
-
function resolveReturnTo(returnTo) {
|
|
87
|
-
if (typeof window === "undefined") return returnTo || "";
|
|
88
|
-
if (!returnTo) return window.location.href;
|
|
89
|
-
if (/^https?:\/\//.test(returnTo)) return returnTo;
|
|
90
|
-
return new URL(returnTo, window.location.origin).href;
|
|
91
|
-
}
|
|
92
|
-
async function doLogin(method, options) {
|
|
93
|
-
const { authUrl, projectId } = resolveLoginOptions(options);
|
|
94
|
-
const mode = (options == null ? void 0 : options.mode) || "popup";
|
|
95
|
-
const origin = getOriginFromUrl(authUrl);
|
|
96
|
-
const url = buildAuthUrl(authUrl, method, projectId, {
|
|
97
|
-
returnTo: mode === "redirect" ? resolveReturnTo(options == null ? void 0 : options.returnTo) : void 0,
|
|
98
|
-
create: options == null ? void 0 : options.create,
|
|
99
|
-
title: options == null ? void 0 : options.title
|
|
100
|
-
});
|
|
101
|
-
if (mode === "redirect") {
|
|
102
|
-
window.location.href = url;
|
|
103
|
-
return new Promise(() => {
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
const response = await openAuthPopup(url, origin);
|
|
107
|
-
autoConfigureFromLogin(response, authUrl, projectId);
|
|
108
|
-
return response;
|
|
109
|
-
}
|
|
110
|
-
async function loginWithGoogleMitra(options) {
|
|
111
|
-
return doLogin("google", options);
|
|
112
|
-
}
|
|
113
|
-
async function loginWithMicrosoftMitra(options) {
|
|
114
|
-
return doLogin("microsoft", options);
|
|
115
|
-
}
|
|
116
|
-
async function loginMitra(method, options) {
|
|
117
|
-
return doLogin(method, options);
|
|
118
|
-
}
|
|
119
|
-
var REFRESH_TIMEOUT_MS = 15e3;
|
|
120
|
-
var _refreshPromise = null;
|
|
121
|
-
function openAuthIframe(url, expectedOrigin) {
|
|
122
|
-
return new Promise((resolve, reject) => {
|
|
123
|
-
const iframe = document.createElement("iframe");
|
|
124
|
-
iframe.style.display = "none";
|
|
125
|
-
iframe.src = url;
|
|
126
|
-
const timer = setTimeout(() => {
|
|
127
|
-
cleanup();
|
|
128
|
-
reject(new Error("Token refresh timeout"));
|
|
129
|
-
}, REFRESH_TIMEOUT_MS);
|
|
130
|
-
function onMessage(event) {
|
|
131
|
-
if (event.origin !== expectedOrigin) return;
|
|
132
|
-
if (!event.data || event.data.type !== AUTH_MESSAGE_TYPE) return;
|
|
133
|
-
cleanup();
|
|
134
|
-
if (event.data.success) {
|
|
135
|
-
resolve(event.data.data);
|
|
136
|
-
} else {
|
|
137
|
-
reject(new Error(event.data.error || "Erro no refresh do token"));
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
function cleanup() {
|
|
141
|
-
window.removeEventListener("message", onMessage);
|
|
142
|
-
clearTimeout(timer);
|
|
143
|
-
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
|
|
144
|
-
}
|
|
145
|
-
window.addEventListener("message", onMessage);
|
|
146
|
-
document.body.appendChild(iframe);
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
async function refreshTokenSilently(authUrl, projectId) {
|
|
150
|
-
if (_refreshPromise) return _refreshPromise;
|
|
151
|
-
_refreshPromise = (async () => {
|
|
152
|
-
try {
|
|
153
|
-
const origin = getOriginFromUrl(authUrl);
|
|
154
|
-
const url = buildAuthUrl(authUrl, "refresh", projectId);
|
|
155
|
-
const response = await openAuthIframe(url, origin);
|
|
156
|
-
return response;
|
|
157
|
-
} finally {
|
|
158
|
-
_refreshPromise = null;
|
|
159
|
-
}
|
|
160
|
-
})();
|
|
161
|
-
return _refreshPromise;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
3
|
// src/auth-new.ts
|
|
165
4
|
function getFetch() {
|
|
166
5
|
if (typeof globalThis.fetch === "function") return globalThis.fetch;
|
|
@@ -170,7 +9,7 @@ function buildBffAuthEndpoint(gateway, path) {
|
|
|
170
9
|
const base = gateway.replace(/\/+$/, "");
|
|
171
10
|
return `${base}/auth${path}`;
|
|
172
11
|
}
|
|
173
|
-
function
|
|
12
|
+
function resolveLoginOptions(options) {
|
|
174
13
|
var _a;
|
|
175
14
|
const config = isConfigured() ? getConfig() : null;
|
|
176
15
|
const authUrl = (options == null ? void 0 : options.authUrl) || (config == null ? void 0 : config.authUrl) || (config == null ? void 0 : config.baseURL);
|
|
@@ -183,7 +22,7 @@ function resolveLoginOptions2(options) {
|
|
|
183
22
|
}
|
|
184
23
|
return { authUrl, projectId };
|
|
185
24
|
}
|
|
186
|
-
function
|
|
25
|
+
function autoConfigureFromLogin(response, authUrl, projectId) {
|
|
187
26
|
if (!response.baseURL) return;
|
|
188
27
|
configureSdkMitra({
|
|
189
28
|
baseURL: response.baseURL,
|
|
@@ -257,7 +96,7 @@ async function exchangeSsoCode(authUrl, provider, code, redirectUri, projectId)
|
|
|
257
96
|
baseURL: authUrl,
|
|
258
97
|
...data.refreshToken ? { refreshToken: data.refreshToken } : {}
|
|
259
98
|
};
|
|
260
|
-
|
|
99
|
+
autoConfigureFromLogin(response, authUrl, projectId);
|
|
261
100
|
return response;
|
|
262
101
|
}
|
|
263
102
|
var SSO_REDIRECT_STORE_KEY = "mitra_sso_redirect";
|
|
@@ -297,7 +136,7 @@ function buildStartUrl(authPageUrl, provider, state, appId, apiUrl, returnTo) {
|
|
|
297
136
|
if (returnTo) query.returnTo = returnTo;
|
|
298
137
|
return authPageUrl + sep + new URLSearchParams(query).toString();
|
|
299
138
|
}
|
|
300
|
-
function
|
|
139
|
+
function getOriginFromUrl(url) {
|
|
301
140
|
try {
|
|
302
141
|
return new URL(url).origin;
|
|
303
142
|
} catch (e) {
|
|
@@ -379,11 +218,11 @@ async function loginWithProvider(provider, options) {
|
|
|
379
218
|
if (_oauthInFlight) return _oauthInFlight;
|
|
380
219
|
_oauthInFlight = (async () => {
|
|
381
220
|
try {
|
|
382
|
-
const { authUrl, projectId } =
|
|
221
|
+
const { authUrl, projectId } = resolveLoginOptions(options);
|
|
383
222
|
const state = generateState();
|
|
384
223
|
const appId = String(projectId);
|
|
385
224
|
const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
|
|
386
|
-
const pageOrigin =
|
|
225
|
+
const pageOrigin = getOriginFromUrl(authPageUrl);
|
|
387
226
|
const redirectUri = stripToOriginPath(authPageUrl);
|
|
388
227
|
const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl);
|
|
389
228
|
const { code, token } = await openOAuthPopup(startUrl, pageOrigin, state);
|
|
@@ -391,7 +230,7 @@ async function loginWithProvider(provider, options) {
|
|
|
391
230
|
return await exchangeSsoCode(authUrl, provider, code, redirectUri, projectId);
|
|
392
231
|
}
|
|
393
232
|
const response = normalizeResponse(token, authUrl);
|
|
394
|
-
|
|
233
|
+
autoConfigureFromLogin(response, authUrl, projectId);
|
|
395
234
|
return response;
|
|
396
235
|
} finally {
|
|
397
236
|
_oauthInFlight = null;
|
|
@@ -400,7 +239,7 @@ async function loginWithProvider(provider, options) {
|
|
|
400
239
|
return _oauthInFlight;
|
|
401
240
|
}
|
|
402
241
|
async function startSsoRedirect(provider, options) {
|
|
403
|
-
const { authUrl, projectId } =
|
|
242
|
+
const { authUrl, projectId } = resolveLoginOptions(options);
|
|
404
243
|
const state = generateState();
|
|
405
244
|
const appId = String(projectId);
|
|
406
245
|
const authPageUrl = await fetchSsoAuthPageUrl();
|
|
@@ -419,21 +258,21 @@ async function exchangeSsoCodeMitra(options) {
|
|
|
419
258
|
}
|
|
420
259
|
return exchangeSsoCode(ctx.authUrl, ctx.provider, options.code, ctx.redirectUri, ctx.projectId);
|
|
421
260
|
}
|
|
422
|
-
async function
|
|
261
|
+
async function loginWithGoogleMitra(options) {
|
|
423
262
|
return loginWithProvider("google", options);
|
|
424
263
|
}
|
|
425
|
-
async function
|
|
264
|
+
async function loginWithMicrosoftMitra(options) {
|
|
426
265
|
return loginWithProvider("microsoft", options);
|
|
427
266
|
}
|
|
428
|
-
async function
|
|
267
|
+
async function loginMitra(method, options) {
|
|
429
268
|
if (method === "google") return loginWithProvider("google", options);
|
|
430
269
|
if (method === "microsoft") return loginWithProvider("microsoft", options);
|
|
431
270
|
throw new Error(NOT_SUPPORTED_POPUP);
|
|
432
271
|
}
|
|
433
|
-
var
|
|
434
|
-
async function
|
|
435
|
-
if (
|
|
436
|
-
|
|
272
|
+
var _refreshPromise = null;
|
|
273
|
+
async function refreshTokenSilently(authUrl, _projectId) {
|
|
274
|
+
if (_refreshPromise) return _refreshPromise;
|
|
275
|
+
_refreshPromise = (async () => {
|
|
437
276
|
try {
|
|
438
277
|
const config = isConfigured() ? getConfig() : null;
|
|
439
278
|
const refreshToken = config == null ? void 0 : config.refreshToken;
|
|
@@ -448,52 +287,10 @@ async function refreshTokenSilently2(authUrl, _projectId) {
|
|
|
448
287
|
...data.refreshToken ? { refreshToken: data.refreshToken } : {}
|
|
449
288
|
};
|
|
450
289
|
} finally {
|
|
451
|
-
|
|
290
|
+
_refreshPromise = null;
|
|
452
291
|
}
|
|
453
292
|
})();
|
|
454
|
-
return
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// src/auth.ts
|
|
458
|
-
var LEGACY_AUTH_URLS = [
|
|
459
|
-
"https://coder.mitralab.io/sdk-auth/",
|
|
460
|
-
"https://agent.mitralab.io/sdk-auth/"
|
|
461
|
-
];
|
|
462
|
-
function normalize(url) {
|
|
463
|
-
const stripped = url.split("?")[0].split("#")[0];
|
|
464
|
-
return stripped.endsWith("/") ? stripped : stripped + "/";
|
|
465
|
-
}
|
|
466
|
-
function isLegacyAuthUrl(authUrl) {
|
|
467
|
-
if (!authUrl) return false;
|
|
468
|
-
return LEGACY_AUTH_URLS.includes(normalize(authUrl));
|
|
469
|
-
}
|
|
470
|
-
function isNewWorld(authUrl) {
|
|
471
|
-
const resolved = isConfigured() ? getConfig().authUrl : void 0;
|
|
472
|
-
if (!resolved) return false;
|
|
473
|
-
return !isLegacyAuthUrl(resolved);
|
|
474
|
-
}
|
|
475
|
-
function resolveAuthUrlFromOptions(options) {
|
|
476
|
-
if (options == null ? void 0 : options.authUrl) return options.authUrl;
|
|
477
|
-
if (isConfigured()) return getConfig().authUrl;
|
|
478
|
-
return void 0;
|
|
479
|
-
}
|
|
480
|
-
async function loginMitra3(method, options) {
|
|
481
|
-
const authUrl = resolveAuthUrlFromOptions(options);
|
|
482
|
-
return isLegacyAuthUrl(authUrl) ? loginMitra(method, options) : loginMitra2(method, options);
|
|
483
|
-
}
|
|
484
|
-
async function loginWithGoogleMitra3(options) {
|
|
485
|
-
const authUrl = resolveAuthUrlFromOptions(options);
|
|
486
|
-
return isLegacyAuthUrl(authUrl) ? loginWithGoogleMitra(options) : loginWithGoogleMitra2(options);
|
|
487
|
-
}
|
|
488
|
-
async function loginWithMicrosoftMitra3(options) {
|
|
489
|
-
const authUrl = resolveAuthUrlFromOptions(options);
|
|
490
|
-
return isLegacyAuthUrl(authUrl) ? loginWithMicrosoftMitra(options) : loginWithMicrosoftMitra2(options);
|
|
491
|
-
}
|
|
492
|
-
async function refreshTokenSilently3(authUrl, projectId) {
|
|
493
|
-
return isLegacyAuthUrl(authUrl) ? refreshTokenSilently(authUrl, projectId) : refreshTokenSilently2(authUrl);
|
|
494
|
-
}
|
|
495
|
-
async function exchangeSsoCodeMitra2(options) {
|
|
496
|
-
return exchangeSsoCodeMitra(options);
|
|
293
|
+
return _refreshPromise;
|
|
497
294
|
}
|
|
498
295
|
|
|
499
296
|
// src/client.ts
|
|
@@ -522,36 +319,11 @@ function buildUrl(endpoint, params) {
|
|
|
522
319
|
return url;
|
|
523
320
|
}
|
|
524
321
|
async function tryRefreshToken() {
|
|
525
|
-
var _a, _b;
|
|
526
322
|
const config = getConfig();
|
|
527
323
|
if (!config.token || config.projectId == null || !config.baseURL) return false;
|
|
528
|
-
|
|
529
|
-
try {
|
|
530
|
-
const baseURL = config.baseURL.replace(/\/+$/, "");
|
|
531
|
-
const resp = await getFetch2()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
|
|
532
|
-
method: "GET",
|
|
533
|
-
headers: { "Authorization": formatToken(config.token) }
|
|
534
|
-
});
|
|
535
|
-
if (resp.ok) {
|
|
536
|
-
const data = await resp.json();
|
|
537
|
-
if (data.token) {
|
|
538
|
-
const newToken = `Bearer ${stripBearer(data.token)}`;
|
|
539
|
-
const session = {
|
|
540
|
-
token: newToken,
|
|
541
|
-
baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
|
|
542
|
-
...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
|
|
543
|
-
};
|
|
544
|
-
updateGlobalToken(session.token);
|
|
545
|
-
if (config.onTokenRefresh) config.onTokenRefresh(session);
|
|
546
|
-
return true;
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
} catch (e) {
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
if (!config.authUrl || typeof window === "undefined") return false;
|
|
324
|
+
const gateway = config.authUrl || config.baseURL;
|
|
553
325
|
try {
|
|
554
|
-
const session = await
|
|
326
|
+
const session = await refreshTokenSilently(gateway, config.projectId);
|
|
555
327
|
updateGlobalToken(session.token, session.refreshToken);
|
|
556
328
|
if (config.onTokenRefresh) config.onTokenRefresh(session);
|
|
557
329
|
return true;
|
|
@@ -577,8 +349,7 @@ async function handleResponse(response) {
|
|
|
577
349
|
async function fetchWithRefresh(url, init) {
|
|
578
350
|
const fetchFn = getFetch2();
|
|
579
351
|
const response = await fetchFn(url, init);
|
|
580
|
-
|
|
581
|
-
if (response.status === expiredStatus) {
|
|
352
|
+
if (response.status === 401) {
|
|
582
353
|
const refreshed = await tryRefreshToken();
|
|
583
354
|
if (refreshed) {
|
|
584
355
|
const newHeaders = { ...buildHeaders() };
|
|
@@ -1265,33 +1036,10 @@ function createMitraInstance(initialConfig) {
|
|
|
1265
1036
|
return data;
|
|
1266
1037
|
}
|
|
1267
1038
|
async function tryRefreshToken2() {
|
|
1268
|
-
var _a2, _b;
|
|
1269
1039
|
if (!_config.token || _config.projectId == null || !_config.baseURL) return false;
|
|
1040
|
+
const gateway = _config.authUrl || _config.baseURL;
|
|
1270
1041
|
try {
|
|
1271
|
-
const
|
|
1272
|
-
const resp = await getFetch3()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
|
|
1273
|
-
method: "GET",
|
|
1274
|
-
headers: { "Authorization": formatToken2(_config.token) }
|
|
1275
|
-
});
|
|
1276
|
-
if (resp.ok) {
|
|
1277
|
-
const data = await resp.json();
|
|
1278
|
-
if (data.token) {
|
|
1279
|
-
const newToken = `Bearer ${stripBearer(data.token)}`;
|
|
1280
|
-
const session = {
|
|
1281
|
-
token: newToken,
|
|
1282
|
-
baseURL: ((_a2 = data.merge) == null ? void 0 : _a2.backURL) || _config.baseURL,
|
|
1283
|
-
...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
|
|
1284
|
-
};
|
|
1285
|
-
_config = { ..._config, token: stripBearer(session.token) };
|
|
1286
|
-
if (_config.onTokenRefresh) _config.onTokenRefresh(session);
|
|
1287
|
-
return true;
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
} catch (e) {
|
|
1291
|
-
}
|
|
1292
|
-
if (!_config.authUrl || typeof window === "undefined") return false;
|
|
1293
|
-
try {
|
|
1294
|
-
const session = await refreshTokenSilently3(_config.authUrl, _config.projectId);
|
|
1042
|
+
const session = await refreshTokenSilently(gateway, _config.projectId);
|
|
1295
1043
|
_config = {
|
|
1296
1044
|
..._config,
|
|
1297
1045
|
token: stripBearer(session.token),
|
|
@@ -1306,7 +1054,7 @@ function createMitraInstance(initialConfig) {
|
|
|
1306
1054
|
async function fetchWithRefresh2(url, init) {
|
|
1307
1055
|
const fetchFn = getFetch3();
|
|
1308
1056
|
const response = await fetchFn(url, init);
|
|
1309
|
-
if (response.status ===
|
|
1057
|
+
if (response.status === 401) {
|
|
1310
1058
|
const refreshed = await tryRefreshToken2();
|
|
1311
1059
|
if (refreshed) {
|
|
1312
1060
|
const newHeaders = { ...authHeaders() };
|
|
@@ -1708,7 +1456,7 @@ exports.createMitraInstance = createMitraInstance;
|
|
|
1708
1456
|
exports.createRecordMitra = createRecordMitra;
|
|
1709
1457
|
exports.createRecordsBatchMitra = createRecordsBatchMitra;
|
|
1710
1458
|
exports.deleteRecordMitra = deleteRecordMitra;
|
|
1711
|
-
exports.exchangeSsoCodeMitra =
|
|
1459
|
+
exports.exchangeSsoCodeMitra = exchangeSsoCodeMitra;
|
|
1712
1460
|
exports.executePublicServerFunctionAsyncMitra = executePublicServerFunctionAsyncMitra;
|
|
1713
1461
|
exports.executePublicServerFunctionMitra = executePublicServerFunctionMitra;
|
|
1714
1462
|
exports.executeServerFunctionAsyncMitra = executeServerFunctionAsyncMitra;
|
|
@@ -1719,13 +1467,13 @@ exports.getPublicServerFunctionExecutionMitra = getPublicServerFunctionExecution
|
|
|
1719
1467
|
exports.getRecordMitra = getRecordMitra;
|
|
1720
1468
|
exports.listIntegrationsMitra = listIntegrationsMitra;
|
|
1721
1469
|
exports.listRecordsMitra = listRecordsMitra;
|
|
1722
|
-
exports.loginMitra =
|
|
1723
|
-
exports.loginWithGoogleMitra =
|
|
1724
|
-
exports.loginWithMicrosoftMitra =
|
|
1470
|
+
exports.loginMitra = loginMitra;
|
|
1471
|
+
exports.loginWithGoogleMitra = loginWithGoogleMitra;
|
|
1472
|
+
exports.loginWithMicrosoftMitra = loginWithMicrosoftMitra;
|
|
1725
1473
|
exports.manageAgentChatMitra = manageAgentChatMitra;
|
|
1726
1474
|
exports.manageAgentCredentialMitra = manageAgentCredentialMitra;
|
|
1727
1475
|
exports.patchRecordMitra = patchRecordMitra;
|
|
1728
|
-
exports.refreshTokenSilently =
|
|
1476
|
+
exports.refreshTokenSilently = refreshTokenSilently;
|
|
1729
1477
|
exports.resolveProjectId = resolveProjectId;
|
|
1730
1478
|
exports.stopServerFunctionExecutionMitra = stopServerFunctionExecutionMitra;
|
|
1731
1479
|
exports.updateRecordMitra = updateRecordMitra;
|