@eulab/connect 0.0.0-stage → 0.8.1

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 CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # EULab Connect SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SDK ESM per SSO, permessi, utenti e WhatsApp tramite EULab Connect. Richiede un'installazione Connect configurata; il server SDK richiede Node.js 22 o successivo.
4
+
5
+ ```sh
6
+ npm install @eulab/connect
7
+ ```
8
+
9
+ ```ts
10
+ import {ConnectBrowser} from '@eulab/connect/browser';
11
+
12
+ // Mantieni un'istanza condivisa nel service dell'applicazione.
13
+ const connect = new ConnectBrowser({
14
+ apiUrl: 'https://auth.eulab.cloud',
15
+ issuer: 'https://auth.eulab.cloud/sso/realms/eulab',
16
+ clientId: 'client-id-della-tua-app',
17
+ redirectUri: 'https://app.example/callback',
18
+ installationId: 'id-installazione',
19
+ });
20
+ await connect.init({loginRequired: true});
21
+ ```
22
+
23
+ L'entrypoint server espone `ConnectServer` e `verifyWebhook`:
24
+
25
+ ```ts
26
+ import {ConnectServer, verifyWebhook} from '@eulab/connect/server';
27
+ ```
28
+
29
+ Gli export browser e server includono le dichiarazioni TypeScript. Il pacchetto contiene solo JavaScript compilato, tipi e questo README; non contiene credenziali o profili WhatsApp. I segreti dell’installazione devono rimanere sul backend. Il backend deve verificare licenza e permessi per ogni operazione.
30
+
31
+ `ConnectServer.mirrorUser()` collega un utente locale a Connect. Il campo opzionale `initialPassword` proviene da una verifica locale appena conclusa, serve solo a inizializzare una nuova identità nel provider e non viene conservato da Connect. Non è disponibile nell’SDK browser.
32
+
33
+ Le API `/v1/team` sono esposte da `teamOverview`, `teamUsers`, `teamRoles`, `teamFunctions`, `createTeamRole`, `updateTeamRole`, `deleteTeamRole`, `setTeamUserRoles`, `revokeTeamUser` e `restoreTeamUser`. Cliente e applicazione derivano dall’installazione autenticata; ogni assegnazione resta limitata a funzioni attive, licenziate e presenti nella delega del chiamante. Le operazioni di modifica richiedono `team.manage` nella delega effettiva.
package/dist/bot.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ /** The application supplies all business content and the number of nodes/levels. */
2
+ export type IVRChannel = 'whatsapp' | 'voice';
3
+ export type IVRInput = {
4
+ type: 'start' | 'back' | 'restart';
5
+ } | {
6
+ type: 'text' | 'speech' | 'dtmf' | 'choice';
7
+ value: string;
8
+ };
9
+ export interface IVRPrompt {
10
+ nodeId: string;
11
+ text: string;
12
+ speech: string;
13
+ expects: 'choice' | 'text' | 'none';
14
+ choices: {
15
+ id: string;
16
+ key: string;
17
+ label: string;
18
+ dtmf: string | null;
19
+ }[];
20
+ }
21
+ export interface VoiceIVRSession {
22
+ id: string;
23
+ callId: string;
24
+ revision: number;
25
+ turn: number;
26
+ result: WhatsAppBotTurn;
27
+ expiresAt: string;
28
+ }
29
+ export type WhatsAppBotNode = {
30
+ id: string;
31
+ type: 'menu';
32
+ text: string;
33
+ speech?: string;
34
+ options: {
35
+ key: string;
36
+ label: string;
37
+ next: string;
38
+ aliases?: string[];
39
+ }[];
40
+ } | {
41
+ id: string;
42
+ type: 'question';
43
+ text: string;
44
+ speech?: string;
45
+ next: string;
46
+ } | {
47
+ id: string;
48
+ type: 'end';
49
+ text: string;
50
+ speech?: string;
51
+ outcome?: string;
52
+ };
53
+ export interface WhatsAppBotDefinition {
54
+ name: string;
55
+ startNodeId: string;
56
+ trigger: string;
57
+ sessionTimeoutMinutes: number;
58
+ invalidReply: string;
59
+ nodes: WhatsAppBotNode[];
60
+ }
61
+ export interface WhatsAppBotState {
62
+ nodeId: string;
63
+ history: string[];
64
+ answers: Record<string, string>;
65
+ }
66
+ export interface WhatsAppBotTurn {
67
+ reply: string | null;
68
+ state: WhatsAppBotState | null;
69
+ completed: boolean;
70
+ answers: Record<string, string>;
71
+ outcome?: string;
72
+ prompt?: IVRPrompt;
73
+ channel?: IVRChannel;
74
+ }
75
+ export interface WhatsAppBot {
76
+ archiveId: string;
77
+ revision: number;
78
+ enabled: boolean;
79
+ connected: boolean;
80
+ definition: WhatsAppBotDefinition | null;
81
+ }
package/dist/bot.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,245 @@
1
+ export type { InteractiveAction, InteractiveContent, InteractiveResponse, ProviderCommand, ProviderOperation, ConversationContact, CallIdentity, CallSnapshot, CallCapabilities, CallActionResult } from './interactive.js';
2
+ export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js';
3
+ export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
4
+ export type { WhatsAppBotDefinition, WhatsAppBotNode, WhatsAppBotState, WhatsAppBotTurn, WhatsAppBot } from './bot.js';
5
+ export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
6
+ export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser, TeamFunction, TeamRole, TeamUser, TeamOverview, TeamRoleInput, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
7
+ import type { AccessResult, ConnectUser, TeamFunction, TeamOverview, TeamRole, TeamRoleInput, TeamUser, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
8
+ export type { WhatsAppSession, WhatsAppArchive, Conversation, WhatsAppMessage, WhatsAppPayload } from './whatsapp.js';
9
+ export interface BrowserConfig {
10
+ apiUrl: string;
11
+ installationId?: string;
12
+ issuer: string;
13
+ clientId: string;
14
+ redirectUri: string;
15
+ functionFallbackUrl?: string;
16
+ }
17
+ export interface LoginOptions {
18
+ returnTo?: string;
19
+ prompt?: 'login' | 'none';
20
+ action?: 'CONFIGURE_TOTP' | 'VERIFY_EMAIL' | 'UPDATE_PASSWORD';
21
+ maxAge?: number;
22
+ }
23
+ export type LoginResult = {
24
+ status: 'authenticated';
25
+ access: AccessResult | null;
26
+ returnTo: string;
27
+ actionStatus: string | null;
28
+ } | {
29
+ status: 'anonymous';
30
+ } | {
31
+ status: 'error';
32
+ code: string;
33
+ message: string;
34
+ };
35
+ export declare class ConnectLoginError extends Error {
36
+ readonly code: string;
37
+ constructor(code: string, message: string);
38
+ }
39
+ export interface AccountSecurity {
40
+ totp: boolean;
41
+ preferredMethod: 'auto' | 'totp' | 'email';
42
+ emailVerified: boolean;
43
+ requiredActions: string[];
44
+ authenticators: {
45
+ id: string;
46
+ name: string;
47
+ createdAt: number;
48
+ }[];
49
+ trustedDevices: {
50
+ id: string;
51
+ name: string;
52
+ createdAt: number;
53
+ expiresAt: number;
54
+ }[];
55
+ }
56
+ export interface Notification {
57
+ id: string;
58
+ title: string;
59
+ body: string;
60
+ created_at: string;
61
+ read_at: string | null;
62
+ }
63
+ export declare class ConnectBrowser {
64
+ readonly config: BrowserConfig;
65
+ private readonly streams;
66
+ private accessState;
67
+ private token;
68
+ private refreshToken;
69
+ private idToken;
70
+ private expiresAt;
71
+ private refreshing?;
72
+ private initializing?;
73
+ private restoring?;
74
+ private sessionVersion;
75
+ private get storageKey();
76
+ private clear;
77
+ private accept;
78
+ refresh(): Promise<void>;
79
+ checkSession(): Promise<boolean>;
80
+ init(options?: {
81
+ loginRequired?: boolean;
82
+ }): Promise<boolean>;
83
+ get access(): AccessResult | null;
84
+ can(functionKey: string): boolean;
85
+ permissions(): Promise<AccessResult>;
86
+ users(): Promise<ConnectUser[]>;
87
+ teamOverview(): Promise<TeamOverview>;
88
+ teamUsers(): Promise<TeamUser[]>;
89
+ teamRoles(): Promise<TeamRole[]>;
90
+ teamFunctions(): Promise<TeamFunction[]>;
91
+ createTeamRole(role: TeamRoleInput): Promise<TeamRole>;
92
+ updateTeamRole(id: string, role: TeamRoleInput): Promise<TeamRole>;
93
+ deleteTeamRole(id: string): Promise<{
94
+ removed: boolean;
95
+ }>;
96
+ setTeamUserRoles(subject: string, roleIds: string[]): Promise<TeamUserAssignment>;
97
+ revokeTeamUser(subject: string): Promise<TeamRevocation>;
98
+ restoreTeamUser(subject: string): Promise<TeamRestore>;
99
+ watchAccess(onChange: (access: AccessResult | null) => void, intervalMs?: number): () => void;
100
+ watchSession(onChange: (valid: boolean | null) => void, intervalMs?: number): () => void;
101
+ get authenticated(): boolean;
102
+ constructor(config: BrowserConfig);
103
+ private destination;
104
+ loginResult(): Promise<LoginResult>;
105
+ private actionStatus;
106
+ login(options?: LoginOptions): Promise<void>;
107
+ callback(): Promise<boolean>;
108
+ private handleCallback;
109
+ configureMfa(returnTo?: string): Promise<void>;
110
+ verifyEmail(returnTo?: string): Promise<void>;
111
+ accountSecurity(): Promise<AccountSecurity>;
112
+ setMfaPreference(preferredMethod: AccountSecurity['preferredMethod']): Promise<AccountSecurity>;
113
+ userSecurity(subject: string): Promise<AccountSecurity>;
114
+ setUserMfaPreference(subject: string, preferredMethod: AccountSecurity['preferredMethod']): Promise<AccountSecurity>;
115
+ revokeUserCredential(subject: string, id: string): Promise<{
116
+ revoked: boolean;
117
+ sessionsLoggedOut: boolean;
118
+ trustedDevicesRevoked: boolean;
119
+ }>;
120
+ revokeTrustedDevice(id: string): Promise<{
121
+ revoked: boolean;
122
+ sessionsLoggedOut: boolean;
123
+ }>;
124
+ notifications(options?: {
125
+ unread?: boolean;
126
+ before?: string;
127
+ beforeId?: string;
128
+ limit?: number;
129
+ }): Promise<{
130
+ items: Notification[];
131
+ unreadCount: number;
132
+ next: {
133
+ before: string;
134
+ beforeId: string;
135
+ } | null;
136
+ }>;
137
+ markNotification(id: string, read?: boolean): Promise<any>;
138
+ markAllNotificationsRead(): Promise<any>;
139
+ setAccessToken(token: string): void;
140
+ logout(): void;
141
+ request<T = any>(path: string, method?: string, body?: unknown, extra?: Record<string, string>): Promise<T>;
142
+ functionUrl(feature: string, path?: string): string;
143
+ sessions(): Promise<{
144
+ sessions: {
145
+ id: string;
146
+ subject: string;
147
+ username: string;
148
+ ipAddress: string;
149
+ startedAt: number;
150
+ lastAccess: number;
151
+ clients: string[];
152
+ current: boolean;
153
+ }[];
154
+ truncated: boolean;
155
+ }>;
156
+ logoutSession(id: string): Promise<{
157
+ loggedOut: boolean;
158
+ current: boolean;
159
+ }>;
160
+ logoutAllSessions(): Promise<any>;
161
+ context(): Promise<any>;
162
+ authorize(installationId: string, permission: string): Promise<{
163
+ allowed: boolean;
164
+ reason: string;
165
+ }>;
166
+ whatsapp(installationId?: string | undefined): {
167
+ subscribe: (options: import("./realtime.js").WhatsAppSubscribeOptions) => import("./realtime.js").WhatsAppSubscription;
168
+ bot: {
169
+ get: (archiveId: string) => Promise<import("./bot.js").WhatsAppBot>;
170
+ configure: (archiveId: string, definition: import("./bot.js").WhatsAppBotDefinition, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
171
+ activate: (archiveId: string, enabled: boolean, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
172
+ preview: (definition: import("./bot.js").WhatsAppBotDefinition, input: string | import("./bot.js").IVRInput, state?: import("./bot.js").WhatsAppBotState | null, channel?: import("./bot.js").IVRChannel) => Promise<import("./bot.js").WhatsAppBotTurn & {
173
+ sent: false;
174
+ }>;
175
+ };
176
+ ivr: {
177
+ get: (archiveId: string, id: string) => Promise<import("./bot.js").VoiceIVRSession>;
178
+ start: (archiveId: string, callId: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
179
+ advance: (archiveId: string, id: string, input: import("./bot.js").IVRInput, expectedTurn: number, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
180
+ };
181
+ operations: {
182
+ get: <T = unknown>(id: string) => Promise<import("./interactive.js").ProviderOperation<T>>;
183
+ list: () => Promise<import("./interactive.js").ProviderOperation<unknown>[]>;
184
+ submit: (id: string, command: import("./interactive.js").ProviderCommand, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<unknown>>;
185
+ };
186
+ calls: {
187
+ inspect: (id: string) => Promise<import("./interactive.js").ProviderOperation<{
188
+ capabilities: import("./interactive.js").CallCapabilities;
189
+ active: import("./interactive.js").CallSnapshot | null;
190
+ }>>;
191
+ start: (id: string, to: string, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
192
+ control: (id: string, action: "accept" | "reject" | "end" | "mute", call: import("./interactive.js").CallIdentity, muted?: boolean, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
193
+ };
194
+ refreshContact: (id: string, chatId: string) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").ConversationContact>>;
195
+ sessions: () => Promise<import("./whatsapp.js").WhatsAppSession[]>;
196
+ connect: () => Promise<{
197
+ id: string;
198
+ state: string;
199
+ }>;
200
+ qr: (id: string) => Promise<{
201
+ state: string;
202
+ qr: string | null;
203
+ }>;
204
+ send: (id: string, payload: import("./whatsapp.js").WhatsAppPayload, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
205
+ id: string;
206
+ state: string;
207
+ }>;
208
+ test: (id: string, payload: import("./whatsapp.js").WhatsAppPayload) => Promise<{
209
+ valid: boolean;
210
+ kind: string;
211
+ to: string;
212
+ connected: boolean;
213
+ sent: false;
214
+ }>;
215
+ outbox: () => Promise<{
216
+ id: string;
217
+ session_id: string;
218
+ state: string;
219
+ provider_id: string | null;
220
+ error: string | null;
221
+ created_at: string;
222
+ }[]>;
223
+ sendText: (id: string, to: string, text: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
224
+ id: string;
225
+ state: string;
226
+ }>;
227
+ reconnect: (id: string) => Promise<any>;
228
+ disconnect: (id: string) => Promise<any>;
229
+ deleteConnection: (id: string) => Promise<{
230
+ removed: boolean;
231
+ state: string;
232
+ }>;
233
+ deleteArchive: (id: string) => Promise<{
234
+ removed: boolean;
235
+ state: string;
236
+ }>;
237
+ archives: () => Promise<import("./whatsapp.js").WhatsAppArchive[]>;
238
+ messages: (id: string, before?: string, chat?: string) => Promise<import("./whatsapp.js").WhatsAppMessage[]>;
239
+ conversations: (id: string) => Promise<import("./whatsapp.js").Conversation[]>;
240
+ media: (archiveId: string, messageId: string) => Promise<{
241
+ data: string | null;
242
+ state: "available" | "queued";
243
+ }>;
244
+ };
245
+ }
@@ -0,0 +1,291 @@
1
+ export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
2
+ import { whatsappClient } from './whatsapp.js';
3
+ export class ConnectLoginError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.code = code;
8
+ this.name = 'ConnectLoginError';
9
+ }
10
+ }
11
+ export class ConnectBrowser {
12
+ config;
13
+ streams = new Set();
14
+ accessState = null;
15
+ token = null;
16
+ refreshToken = null;
17
+ idToken = null;
18
+ expiresAt = 0;
19
+ refreshing;
20
+ initializing;
21
+ restoring;
22
+ sessionVersion = 0;
23
+ get storageKey() { return `connect.session:${this.config.issuer}:${this.config.clientId}`; }
24
+ clear() { for (const close of this.streams)
25
+ close(); this.streams.clear(); this.sessionVersion++; this.refreshing = undefined; this.accessState = null; this.token = null; this.refreshToken = null; this.idToken = null; this.expiresAt = 0; sessionStorage.removeItem(this.storageKey); }
26
+ accept(result) { if (typeof result?.access_token !== 'string' || !result.access_token) {
27
+ this.clear();
28
+ throw new ConnectLoginError('invalid_token_response', 'Risposta SSO non valida');
29
+ } this.sessionVersion++; this.token = result.access_token; this.refreshToken = result.refresh_token || this.refreshToken; this.idToken = result.id_token || this.idToken; this.expiresAt = Date.now() + (result.expires_in || 300) * 1000; sessionStorage.setItem(this.storageKey, JSON.stringify({ refreshToken: this.refreshToken, idToken: this.idToken })); }
30
+ async refresh() {
31
+ if (this.refreshing)
32
+ return this.refreshing;
33
+ if (!this.refreshToken)
34
+ throw new ConnectLoginError('session_expired', 'Sessione SSO scaduta. Accedi di nuovo.');
35
+ const refreshToken = this.refreshToken, version = this.sessionVersion;
36
+ const operation = (async () => {
37
+ const response = await fetch(`${this.config.issuer}/protocol/openid-connect/token`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'refresh_token', client_id: this.config.clientId, refresh_token: refreshToken }), signal: AbortSignal.timeout(10000) });
38
+ if (version !== this.sessionVersion)
39
+ throw new ConnectLoginError('session_changed', 'Sessione modificata durante il rinnovo');
40
+ if (!response.ok) {
41
+ if (response.status === 400 || response.status === 401) {
42
+ this.clear();
43
+ throw new ConnectLoginError('session_expired', 'Sessione SSO scaduta o revocata. Accedi di nuovo.');
44
+ }
45
+ throw new ConnectLoginError('refresh_unavailable', 'Rinnovo SSO temporaneamente non disponibile');
46
+ }
47
+ let result;
48
+ try {
49
+ result = await response.json();
50
+ }
51
+ catch {
52
+ if (version === this.sessionVersion)
53
+ this.clear();
54
+ throw new ConnectLoginError('invalid_token_response', 'Risposta SSO non valida');
55
+ }
56
+ if (version !== this.sessionVersion)
57
+ throw new ConnectLoginError('session_changed', 'Sessione modificata durante il rinnovo');
58
+ this.accept(result);
59
+ })().finally(() => { if (this.refreshing === operation)
60
+ this.refreshing = undefined; });
61
+ this.refreshing = operation;
62
+ return operation;
63
+ }
64
+ async checkSession() {
65
+ if (!this.refreshToken && !this.token) {
66
+ const saved = sessionStorage.getItem(this.storageKey);
67
+ if (!saved)
68
+ return false;
69
+ try {
70
+ const value = JSON.parse(saved);
71
+ if (typeof value.refreshToken !== 'string' || !value.refreshToken)
72
+ throw new Error();
73
+ this.refreshToken = value.refreshToken;
74
+ this.idToken = typeof value.idToken === 'string' ? value.idToken : null;
75
+ }
76
+ catch {
77
+ this.clear();
78
+ return false;
79
+ }
80
+ }
81
+ try {
82
+ // The refresh grant validates the server-side SSO session on every explicit check.
83
+ if (this.refreshToken)
84
+ await this.refresh();
85
+ else
86
+ await this.request('/v1/context');
87
+ return true;
88
+ }
89
+ catch (error) {
90
+ if (error instanceof ConnectLoginError && error.code === 'session_expired')
91
+ return false;
92
+ if (!this.token && !this.refreshToken)
93
+ return false;
94
+ throw error;
95
+ }
96
+ }
97
+ async init(options = {}) {
98
+ if (this.initializing)
99
+ return this.initializing;
100
+ const operation = (async () => { const authenticated = await this.callback(); if (!authenticated) {
101
+ if (options.loginRequired)
102
+ await this.login();
103
+ return false;
104
+ } if (this.config.installationId)
105
+ return (await this.permissions()).canLogin; return true; })().finally(() => { if (this.initializing === operation)
106
+ this.initializing = undefined; });
107
+ this.initializing = operation;
108
+ return operation;
109
+ }
110
+ get access() { return this.accessState; }
111
+ can(functionKey) { return !!this.accessState?.canLogin && this.accessState.functions.some(f => f.key === functionKey); }
112
+ async permissions() { const result = await this.request('/v1/access'); this.accessState = result; return result; }
113
+ users() { return this.request('/v1/users'); }
114
+ teamOverview() { return this.request('/v1/team'); }
115
+ teamUsers() { return this.request('/v1/team/users'); }
116
+ teamRoles() { return this.request('/v1/team/roles'); }
117
+ teamFunctions() { return this.request('/v1/team/functions'); }
118
+ createTeamRole(role) { return this.request('/v1/team/roles', 'POST', role); }
119
+ updateTeamRole(id, role) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'PUT', role); }
120
+ deleteTeamRole(id) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'DELETE'); }
121
+ setTeamUserRoles(subject, roleIds) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/roles', 'PUT', { roleIds }); }
122
+ revokeTeamUser(subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject), 'DELETE'); }
123
+ restoreTeamUser(subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/restore', 'POST'); }
124
+ watchAccess(onChange, intervalMs = 30000) { const refresh = async () => { try {
125
+ if (!await this.checkSession()) {
126
+ this.accessState = null;
127
+ onChange(null);
128
+ return;
129
+ }
130
+ onChange(await this.permissions());
131
+ }
132
+ catch {
133
+ this.accessState = null;
134
+ onChange(null);
135
+ } }; const timer = setInterval(() => void refresh(), Math.max(intervalMs, 5000)); return () => clearInterval(timer); }
136
+ watchSession(onChange, intervalMs = 30000) { const check = async () => { try {
137
+ onChange(await this.checkSession());
138
+ }
139
+ catch {
140
+ onChange(null);
141
+ } }; const timer = setInterval(() => void check(), Math.max(intervalMs, 5000)); return () => clearInterval(timer); }
142
+ get authenticated() { return !!this.token; }
143
+ constructor(config) {
144
+ this.config = config;
145
+ }
146
+ destination(value = this.config.redirectUri) { const target = new URL(value, location.href), callback = new URL(this.config.redirectUri); if (target.origin !== callback.origin || target.username || target.password)
147
+ throw new ConnectLoginError('invalid_return_to', 'Pagina di ritorno esterna all’app'); return target.href; }
148
+ async loginResult() { try {
149
+ if (!await this.callback())
150
+ return { status: 'anonymous' };
151
+ if (this.config.installationId) {
152
+ const access = await this.permissions();
153
+ if (!access.canLogin)
154
+ return { status: 'error', code: access.reason, message: 'Accesso all’applicazione non consentito: ' + access.reason };
155
+ }
156
+ return { status: 'authenticated', access: this.accessState, returnTo: location.href, actionStatus: this.actionStatus };
157
+ }
158
+ catch (e) {
159
+ return { status: 'error', code: e instanceof ConnectLoginError ? e.code : 'login_failed', message: e.message };
160
+ } }
161
+ actionStatus = null;
162
+ async login(options = {}) {
163
+ const returnTo = this.destination(options.returnTo);
164
+ if (options.maxAge !== undefined && (!Number.isInteger(options.maxAge) || options.maxAge < 0))
165
+ throw new ConnectLoginError('invalid_max_age', 'Durata autenticazione non valida');
166
+ const verifier = Array.from(crypto.getRandomValues(new Uint8Array(48)), x => x.toString(16).padStart(2, '0')).join('');
167
+ const challenge = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
168
+ const state = crypto.randomUUID();
169
+ sessionStorage.setItem(this.storageKey + ':pkce', JSON.stringify({ verifier, state, createdAt: Date.now(), returnTo, redirectUri: this.config.redirectUri }));
170
+ const url = new URL(`${this.config.issuer}/protocol/openid-connect/auth`);
171
+ Object.entries({ client_id: this.config.clientId, redirect_uri: this.config.redirectUri, response_type: 'code', scope: 'openid profile email', state, code_challenge: challenge, code_challenge_method: 'S256' }).forEach(([k, v]) => url.searchParams.set(k, v));
172
+ if (options.prompt)
173
+ url.searchParams.set('prompt', options.prompt);
174
+ if (options.action)
175
+ url.searchParams.set('kc_action', options.action);
176
+ if (options.maxAge !== undefined)
177
+ url.searchParams.set('max_age', String(options.maxAge));
178
+ location.assign(url);
179
+ }
180
+ async callback() {
181
+ if (this.restoring)
182
+ return this.restoring;
183
+ const operation = this.handleCallback().finally(() => { if (this.restoring === operation)
184
+ this.restoring = undefined; });
185
+ this.restoring = operation;
186
+ return operation;
187
+ }
188
+ async handleCallback() {
189
+ const url = new URL(location.href), code = url.searchParams.get('code'), error = url.searchParams.get('error');
190
+ if (!code && !error)
191
+ return this.checkSession();
192
+ const stored = sessionStorage.getItem(this.storageKey + ':pkce');
193
+ sessionStorage.removeItem(this.storageKey + ':pkce');
194
+ // Remove authorization parameters even when the callback is rejected.
195
+ history.replaceState({}, '', this.config.redirectUri);
196
+ let callbackVersion;
197
+ try {
198
+ if (!stored)
199
+ throw new ConnectLoginError('missing_request', 'Richiesta SSO assente o già utilizzata');
200
+ let pending;
201
+ try {
202
+ pending = JSON.parse(stored);
203
+ }
204
+ catch {
205
+ throw new ConnectLoginError('invalid_request', 'Richiesta SSO non valida');
206
+ }
207
+ if (url.searchParams.getAll('state').length !== 1 || url.searchParams.get('state') !== pending.state)
208
+ throw new ConnectLoginError('invalid_state', 'Stato SSO non valido');
209
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > 600000 || pending.createdAt > Date.now() + 30000 || pending.redirectUri !== this.config.redirectUri)
210
+ throw new ConnectLoginError('expired_request', 'Richiesta SSO scaduta');
211
+ if (url.searchParams.has('iss') && url.searchParams.get('iss') !== this.config.issuer)
212
+ throw new ConnectLoginError('invalid_issuer', 'Provider SSO non valido');
213
+ const returnTo = this.destination(pending.returnTo);
214
+ if (error)
215
+ throw new ConnectLoginError(error, ['access_denied', 'login_required', 'interaction_required'].includes(error) ? 'Accesso SSO annullato o da ripetere.' : 'Accesso SSO non riuscito.');
216
+ if (!code || url.searchParams.getAll('code').length !== 1)
217
+ throw new ConnectLoginError('invalid_code', 'Codice SSO non valido');
218
+ this.clear();
219
+ const version = this.sessionVersion;
220
+ callbackVersion = version;
221
+ const response = await fetch(`${this.config.issuer}/protocol/openid-connect/token`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', client_id: this.config.clientId, redirect_uri: this.config.redirectUri, code, code_verifier: pending.verifier }), signal: AbortSignal.timeout(10000) });
222
+ if (version !== this.sessionVersion)
223
+ throw new ConnectLoginError('session_changed', 'Sessione modificata durante il login');
224
+ if (!response.ok)
225
+ throw new ConnectLoginError('token_exchange_failed', 'Scambio SSO fallito');
226
+ const result = await response.json();
227
+ if (typeof result.access_token !== 'string' || !result.access_token)
228
+ throw new ConnectLoginError('invalid_token_response', 'Risposta SSO non valida');
229
+ if (version !== this.sessionVersion)
230
+ throw new ConnectLoginError('session_changed', 'Sessione modificata durante il login');
231
+ this.accept(result);
232
+ this.actionStatus = url.searchParams.get('kc_action_status');
233
+ history.replaceState({}, '', returnTo);
234
+ return true;
235
+ }
236
+ catch (e) {
237
+ if (callbackVersion === undefined || callbackVersion === this.sessionVersion)
238
+ this.clear();
239
+ throw e;
240
+ }
241
+ }
242
+ configureMfa(returnTo = location.href) { return this.login({ action: 'CONFIGURE_TOTP', returnTo }); }
243
+ verifyEmail(returnTo = location.href) { return this.login({ action: 'VERIFY_EMAIL', returnTo }); }
244
+ accountSecurity() { return this.request('/v1/security/me'); }
245
+ setMfaPreference(preferredMethod) { return this.request('/v1/security/me/preferences', 'PUT', { preferredMethod }); }
246
+ userSecurity(subject) { return this.request('/v1/security/users/' + encodeURIComponent(subject)); }
247
+ setUserMfaPreference(subject, preferredMethod) { return this.request('/v1/security/users/' + encodeURIComponent(subject) + '/preferences', 'PUT', { preferredMethod }); }
248
+ revokeUserCredential(subject, id) { return this.request('/v1/security/users/' + encodeURIComponent(subject) + '/credentials/' + encodeURIComponent(id), 'DELETE'); }
249
+ async revokeTrustedDevice(id) { const result = await this.request('/v1/security/devices/' + encodeURIComponent(id), 'DELETE'); if (result.sessionsLoggedOut)
250
+ this.clear(); return result; }
251
+ notifications(options = {}) { const q = new URLSearchParams(); for (const [key, value] of Object.entries(options))
252
+ if (value !== undefined)
253
+ q.set(key, String(value)); return this.request('/v1/notifications?' + q); }
254
+ markNotification(id, read = true) { return this.request('/v1/notifications/' + encodeURIComponent(id) + '/read', 'PUT', { read }); }
255
+ markAllNotificationsRead() { return this.request('/v1/notifications/read-all', 'POST'); }
256
+ setAccessToken(token) { this.clear(); this.token = token; this.expiresAt = Infinity; this.refreshToken = null; }
257
+ logout() { const hint = this.idToken; this.clear(); const url = new URL(`${this.config.issuer}/protocol/openid-connect/logout`); if (hint)
258
+ url.searchParams.set('id_token_hint', hint); url.searchParams.set('client_id', this.config.clientId); url.searchParams.set('post_logout_redirect_uri', this.config.redirectUri); location.assign(url); }
259
+ async request(path, method = 'GET', body, extra = {}) {
260
+ if (this.refreshing)
261
+ await this.refreshing;
262
+ if (this.token && Date.now() >= this.expiresAt - 30000)
263
+ await this.refresh();
264
+ if (!this.token)
265
+ throw new Error('Accedi con EULab SSO');
266
+ const version = this.sessionVersion, token = this.token;
267
+ const response = await fetch(`${this.config.apiUrl}${path}`, { method, referrerPolicy: 'origin', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...(this.config.installationId ? { 'X-Installation-Id': this.config.installationId } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });
268
+ const data = await response.json();
269
+ if (response.status === 401 && version === this.sessionVersion && token === this.token)
270
+ this.clear();
271
+ if (!response.ok)
272
+ throw Object.assign(new Error(typeof data.message === 'string' ? data.message : JSON.stringify(data.message || data)), { status: response.status });
273
+ return data;
274
+ }
275
+ functionUrl(feature, path) {
276
+ if (!/^[a-z][a-z0-9_.:-]{0,79}$/.test(feature))
277
+ throw new Error('Chiave funzione non valida');
278
+ const url = path ? new URL(path, location.origin) : new URL(`${(this.config.functionFallbackUrl || location.origin + '/eulab/connect/functions').replace(/\/$/, '')}/${encodeURIComponent(feature)}`);
279
+ if (url.origin !== location.origin)
280
+ throw new Error('URL funzione esterno al dominio autorizzato');
281
+ return url.href;
282
+ }
283
+ sessions() { return this.request('/v1/sessions'); }
284
+ async logoutSession(id) { const result = await this.request(`/v1/sessions/${encodeURIComponent(id)}/logout`, 'POST'); if (result.current)
285
+ this.clear(); return result; }
286
+ async logoutAllSessions() { const result = await this.request('/v1/sessions/logout-all', 'POST'); this.clear(); return result; }
287
+ context() { return this.request('/v1/context'); }
288
+ authorize(installationId, permission) { return this.request('/v1/authorize', 'POST', { installationId, permission }); }
289
+ whatsapp(installationId = this.config.installationId) { if (!installationId)
290
+ throw new Error('InstallationId richiesto'); return whatsappClient(this.request.bind(this), installationId, { apiUrl: this.config.apiUrl, register: close => { this.streams.add(close); return () => { this.streams.delete(close); }; } }); }
291
+ }