@eulab/connect 0.8.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ import type { WhatsAppPayload, Request } from './whatsapp.js';
2
+ export type AutomationChannel = 'whatsapp' | 'application_notification' | 'email';
3
+ export interface AutomationDelegationInput {
4
+ purpose: string;
5
+ channel: AutomationChannel;
6
+ functions: string[];
7
+ archiveId?: string;
8
+ expiresAt: string;
9
+ }
10
+ export interface AutomationDelegation {
11
+ id: string;
12
+ installationId: string;
13
+ appId: string;
14
+ actor: string;
15
+ purpose: string;
16
+ channel: AutomationChannel;
17
+ functions: string[];
18
+ archiveId: string | null;
19
+ revision: number;
20
+ expiresAt: string;
21
+ revokedAt: string | null;
22
+ createdAt: string;
23
+ }
24
+ /** Secret-bearing result: persist encrypted on the consumer server, never project to the UI. */
25
+ export interface AutomationGrant {
26
+ delegation: AutomationDelegation;
27
+ credential: string;
28
+ }
29
+ export interface AutomationScope {
30
+ purpose: string;
31
+ channel: AutomationChannel;
32
+ functions: string[];
33
+ }
34
+ export interface AutomationVerification {
35
+ allowed: boolean;
36
+ reason: string;
37
+ }
38
+ export interface DelegatedMessageInput {
39
+ purpose: string;
40
+ sessionId: string;
41
+ payload: WhatsAppPayload;
42
+ }
43
+ export interface DelegatedMessageStatus {
44
+ id: string;
45
+ sessionId: string;
46
+ state: 'queued' | 'sending' | 'sent' | 'failed' | 'uncertain' | 'cancelled';
47
+ providerId: string | null;
48
+ error: string | null;
49
+ createdAt: string;
50
+ }
51
+ /** Withdrawal never implies cancellation of an effect that the runner has already acquired. */
52
+ export type DelegatedMessageWithdrawal = {
53
+ outcome: 'withdrawn';
54
+ message: DelegatedMessageStatus & {
55
+ state: 'cancelled';
56
+ };
57
+ } | {
58
+ outcome: 'already_terminal';
59
+ message: DelegatedMessageStatus & {
60
+ state: 'cancelled' | 'failed';
61
+ };
62
+ } | {
63
+ outcome: 'effect_started';
64
+ message: DelegatedMessageStatus & {
65
+ state: 'sending' | 'sent' | 'uncertain';
66
+ };
67
+ };
68
+ export interface WebhookRegistration {
69
+ id: string;
70
+ url: string;
71
+ enabled: boolean;
72
+ secret: string;
73
+ }
74
+ /** Signed original-body webhook envelope. Signature verification does not replace durable event-ID deduplication. */
75
+ export interface ConnectWebhookEvent<T = unknown> {
76
+ id: string;
77
+ installationId: string;
78
+ sessionId: string;
79
+ kind: string;
80
+ createdAt: string;
81
+ payload: T;
82
+ }
83
+ export interface WhatsAppMessageEventPayload {
84
+ messageId: string;
85
+ providerId: string;
86
+ sessionId: string;
87
+ messageSessionId: string;
88
+ archiveId: string;
89
+ chatId: string;
90
+ direction: 'in' | 'out' | 'unknown';
91
+ fromMe: boolean | null;
92
+ senderId: string | null;
93
+ recipientId: string | null;
94
+ occurredAt: string;
95
+ observedAt: string;
96
+ timestampSource: 'provider' | 'connect' | 'unknown';
97
+ source: 'whatsapp_provider';
98
+ addressingVerified: boolean;
99
+ kind: string;
100
+ body: {
101
+ text: string;
102
+ selectedButtonId: string | null;
103
+ [key: string]: unknown;
104
+ };
105
+ }
106
+ export declare function automationClient(request: Request, installationId: string): {
107
+ create: (input: AutomationDelegationInput, key: string) => Promise<AutomationGrant>;
108
+ recover: (key: string) => Promise<AutomationGrant>;
109
+ get: (id: string, credential?: string) => Promise<AutomationDelegation>;
110
+ verify: (id: string, scope: AutomationScope, credential?: string) => Promise<AutomationVerification>;
111
+ revoke: (id: string, credential?: string) => Promise<AutomationDelegation>;
112
+ send: (id: string, credential: string, input: DelegatedMessageInput, key: string) => Promise<DelegatedMessageStatus>;
113
+ message: (id: string, credential: string, key: string) => Promise<DelegatedMessageStatus>;
114
+ withdraw: (id: string, credential: string, input: DelegatedMessageInput, key: string) => Promise<DelegatedMessageWithdrawal>;
115
+ webhooks: {
116
+ create: (url: string, key: string) => Promise<WebhookRegistration>;
117
+ recover: (key: string) => Promise<WebhookRegistration>;
118
+ };
119
+ };
@@ -0,0 +1,17 @@
1
+ export function automationClient(request, installationId) {
2
+ const root = `/v1/installations/${encodeURIComponent(installationId)}/automations`, delegation = (id) => root + '/delegations/' + encodeURIComponent(id), headers = (credential) => credential ? { 'X-Connect-Delegation': credential } : {};
3
+ return {
4
+ create: (input, key) => request(root + '/delegations', 'POST', input, { 'Idempotency-Key': key }),
5
+ recover: (key) => request(root + '/delegations/by-key/' + encodeURIComponent(key)),
6
+ get: (id, credential) => request(delegation(id), 'GET', undefined, headers(credential)),
7
+ verify: (id, scope, credential) => request(delegation(id) + '/verify', 'POST', scope, headers(credential)),
8
+ revoke: (id, credential) => request(delegation(id), 'DELETE', undefined, headers(credential)),
9
+ send: (id, credential, input, key) => request(delegation(id) + '/messages', 'POST', input, { ...headers(credential), 'Idempotency-Key': key }),
10
+ message: (id, credential, key) => request(delegation(id) + '/messages/by-key/' + encodeURIComponent(key), 'GET', undefined, headers(credential)),
11
+ withdraw: (id, credential, input, key) => request(delegation(id) + '/messages/by-key/' + encodeURIComponent(key) + '/withdraw', 'POST', input, headers(credential)),
12
+ webhooks: {
13
+ create: (url, key) => request(root + '/webhooks', 'POST', { url }, { 'Idempotency-Key': key }),
14
+ recover: (key) => request(root + '/webhooks/by-key/' + encodeURIComponent(key))
15
+ }
16
+ };
17
+ }
package/dist/browser.js CHANGED
@@ -265,11 +265,26 @@ export class ConnectBrowser {
265
265
  throw new Error('Accedi con EULab SSO');
266
266
  const version = this.sessionVersion, token = this.token;
267
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();
268
+ // Proxies answer with HTML pages (502/503/504): never show raw parser errors to people.
269
+ const text = await response.text();
270
+ let data = null;
271
+ let parsed = true;
272
+ if (text) {
273
+ try {
274
+ data = JSON.parse(text);
275
+ }
276
+ catch {
277
+ parsed = false;
278
+ }
279
+ }
269
280
  if (response.status === 401 && version === this.sessionVersion && token === this.token)
270
281
  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 });
282
+ if (!response.ok) {
283
+ const message = parsed && data && typeof data.message === 'string' ? data.message : parsed && data?.message ? JSON.stringify(data.message) : httpMessage(response.status);
284
+ throw Object.assign(new Error(message), { status: response.status });
285
+ }
286
+ if (!parsed)
287
+ throw Object.assign(new Error('Risposta non valida dal server EULab Connect. Riprova tra poco.'), { status: response.status });
273
288
  return data;
274
289
  }
275
290
  functionUrl(feature, path) {
@@ -289,3 +304,17 @@ export class ConnectBrowser {
289
304
  whatsapp(installationId = this.config.installationId) { if (!installationId)
290
305
  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
306
  }
307
+ /** Plain-language message when the server did not send a JSON error. */
308
+ function httpMessage(status) {
309
+ if (status === 401)
310
+ return 'Sessione scaduta. Accedi di nuovo.';
311
+ if (status === 403)
312
+ return 'Non hai i permessi per questa sezione.';
313
+ if (status === 404)
314
+ return 'Elemento non trovato.';
315
+ if (status === 429)
316
+ return 'Troppe richieste ravvicinate. Attendi qualche secondo.';
317
+ if (status >= 500)
318
+ return 'EULab Connect non è raggiungibile in questo momento. Riprova tra poco.';
319
+ return 'Richiesta non riuscita (' + status + ').';
320
+ }
package/dist/server.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export type { AutomationChannel, AutomationDelegationInput, AutomationDelegation, AutomationGrant, AutomationScope, AutomationVerification, DelegatedMessageInput, DelegatedMessageStatus, DelegatedMessageWithdrawal, WebhookRegistration, ConnectWebhookEvent, WhatsAppMessageEventPayload } from './automations.js';
1
2
  export type { InteractiveAction, InteractiveContent, InteractiveResponse, ProviderCommand, ProviderOperation, ConversationContact, CallIdentity, CallSnapshot, CallCapabilities, CallActionResult } from './interactive.js';
2
3
  export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js';
3
4
  export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
@@ -12,6 +13,7 @@ export interface LocalUserProfile {
12
13
  email: string;
13
14
  displayName: string;
14
15
  initialPassword?: string;
16
+ initialPasswordTemporary?: boolean;
15
17
  }
16
18
  export interface MirroredUser {
17
19
  installationId: string;
@@ -23,6 +25,172 @@ export interface MirroredUser {
23
25
  status: 'created' | 'already_linked' | 'recovered';
24
26
  ssoSetupRequired: boolean | null;
25
27
  }
28
+ export interface ApplicationTeamUserInput {
29
+ localUser: {
30
+ localUserId: string;
31
+ username?: string;
32
+ email: string;
33
+ firstName: string;
34
+ lastName: string;
35
+ role: 'manager' | 'reception' | 'collaborator';
36
+ permissions: string[];
37
+ };
38
+ roleIds: string[];
39
+ initialPassword?: string;
40
+ initialPasswordTemporary?: boolean;
41
+ }
42
+ export interface ApplicationMirrorInput extends LocalUserProfile {
43
+ application: {
44
+ sourceId: string;
45
+ localTenantId: string;
46
+ firstName: string;
47
+ lastName: string;
48
+ role: 'manager' | 'reception' | 'collaborator';
49
+ permissions: string[];
50
+ roleIds: string[];
51
+ };
52
+ }
53
+ export interface ApplicationTeamUserResult extends MirroredUser {
54
+ appId: string;
55
+ sourceId: string;
56
+ localTenantId: string;
57
+ roleIds: string[];
58
+ applicationAccess: boolean;
59
+ }
60
+ /** Business failures preserve a valid application session; uncertain outcomes require an explicit read/retry. */
61
+ export declare class ConnectApiError extends Error {
62
+ readonly status: number;
63
+ readonly code: string;
64
+ constructor(status: number, result: {
65
+ code?: string;
66
+ message?: unknown;
67
+ });
68
+ }
69
+ export type OnboardingRequestState = 'pending' | 'approved' | 'migrating' | 'completed' | 'rejected' | 'expired' | 'failed';
70
+ export type OnboardingNextAction = 'wait' | 'sign_in' | 'choose_connect_password' | 'resubmit' | 'contact_admin' | 'closed';
71
+ export interface OnboardingRequestStatus {
72
+ requestId: string;
73
+ state: OnboardingRequestState;
74
+ nextAction?: OnboardingNextAction;
75
+ }
76
+ export interface OnboardingPasswordRecovery {
77
+ requestId: string;
78
+ localTenantId: string;
79
+ localUserId: string;
80
+ email: string;
81
+ consentVersion: string;
82
+ newPassword: string;
83
+ }
84
+ export interface AuthorizedConnectContext {
85
+ tenant: {
86
+ id: string;
87
+ name: string;
88
+ slug: string;
89
+ };
90
+ binding: {
91
+ customerId: string;
92
+ installationId: string;
93
+ secret: string;
94
+ };
95
+ user: {
96
+ id: string;
97
+ subject: string;
98
+ email: string;
99
+ firstName: string;
100
+ lastName: string;
101
+ role: 'owner' | 'manager' | 'reception' | 'collaborator';
102
+ permissions: string[];
103
+ };
104
+ }
105
+ export interface ApprovedApplicationConfiguration {
106
+ sourceId: string;
107
+ appId: string;
108
+ issuer: string;
109
+ clientId: string;
110
+ redirectUri: string;
111
+ clientSecret?: string;
112
+ }
113
+ export interface DeploymentMetadata {
114
+ name: string;
115
+ environment: 'development' | 'staging' | 'production';
116
+ origins: string[];
117
+ catalogUrl?: string;
118
+ oidcCallbacks?: string[];
119
+ }
120
+ export type AppOnboardingLoginContext = {
121
+ status: 'configuration_required';
122
+ appId: string;
123
+ context: AuthorizedConnectContext;
124
+ } | {
125
+ status: 'connect';
126
+ context: AuthorizedConnectContext;
127
+ } | {
128
+ status: 'not_found';
129
+ request?: OnboardingRequestStatus;
130
+ };
131
+ export interface AppOnboardingMigrationRequest {
132
+ kind: 'migration';
133
+ consentVersion: string;
134
+ localTenant: {
135
+ id: string;
136
+ name: string;
137
+ slug: string;
138
+ };
139
+ localUser: {
140
+ id: string;
141
+ email: string;
142
+ firstName: string;
143
+ lastName: string;
144
+ role: 'owner' | 'manager' | 'reception' | 'collaborator';
145
+ permissions: string[];
146
+ };
147
+ /** Password verificata localmente: transito cifrato a TTL, mai restituita o registrata in chiaro. */
148
+ initialPassword: string;
149
+ }
150
+ export interface AppOnboardingActivationRequest {
151
+ kind: 'activation';
152
+ companyName: string;
153
+ applicant: {
154
+ email: string;
155
+ firstName: string;
156
+ lastName: string;
157
+ };
158
+ initialPassword: string;
159
+ }
160
+ export type AppOnboardingRequest = AppOnboardingMigrationRequest | AppOnboardingActivationRequest;
161
+ /** Errore del contratto sorgente: lo stato HTTP resta disponibile al chiamante. */
162
+ export declare class ConnectOnboardingError extends Error {
163
+ readonly status: number;
164
+ constructor(status: number, message: string);
165
+ }
166
+ /**
167
+ * Client backend della sorgente/deployment per l'onboarding assistito.
168
+ * Non va usato nel browser: il segreto bootstrap resta sul server della sorgente.
169
+ * `submit` non sostituisce mai una credenziale già acquisita con la stessa chiave.
170
+ */
171
+ export declare class ConnectOnboardingSource {
172
+ private readonly config;
173
+ constructor(config: {
174
+ apiUrl: string;
175
+ sourceId: string;
176
+ appId: string;
177
+ secret: string;
178
+ presenterId?: string;
179
+ deployment?: DeploymentMetadata;
180
+ });
181
+ private post;
182
+ private status;
183
+ configuration(): Promise<{
184
+ status: "pending" | "configuration_required";
185
+ plannedAppId?: string;
186
+ } | {
187
+ status: "ready";
188
+ configuration: ApprovedApplicationConfiguration;
189
+ }>;
190
+ recoverPassword(input: OnboardingPasswordRecovery, idempotencyKey: string): Promise<OnboardingRequestStatus>;
191
+ loginContext(email: string): Promise<AppOnboardingLoginContext>;
192
+ submit(request: AppOnboardingRequest, idempotencyKey: string): Promise<OnboardingRequestStatus>;
193
+ }
26
194
  export declare class ConnectServer {
27
195
  private readonly config;
28
196
  constructor(config: {
@@ -33,6 +201,7 @@ export declare class ConnectServer {
33
201
  functionFallbackUrl?: string;
34
202
  catalogUrl?: string;
35
203
  basePath?: string;
204
+ requestTimeoutMs?: number;
36
205
  });
37
206
  request<T = any>(path: string, method?: string, body?: unknown, accessToken?: string, extra?: Record<string, string>): Promise<T>;
38
207
  functionUrl(feature: string, path?: string): string;
@@ -119,6 +288,21 @@ export declare class ConnectServer {
119
288
  state: "available" | "queued";
120
289
  }>;
121
290
  };
291
+ /** Backend only. Supply a personal token for creation/recovery; workers use the stored delegation credential. */
292
+ automations(accessToken?: string | (() => Promise<string>)): {
293
+ create: (input: import("./automations.js").AutomationDelegationInput, key: string) => Promise<import("./automations.js").AutomationGrant>;
294
+ recover: (key: string) => Promise<import("./automations.js").AutomationGrant>;
295
+ get: (id: string, credential?: string) => Promise<import("./automations.js").AutomationDelegation>;
296
+ verify: (id: string, scope: import("./automations.js").AutomationScope, credential?: string) => Promise<import("./automations.js").AutomationVerification>;
297
+ revoke: (id: string, credential?: string) => Promise<import("./automations.js").AutomationDelegation>;
298
+ send: (id: string, credential: string, input: import("./automations.js").DelegatedMessageInput, key: string) => Promise<import("./automations.js").DelegatedMessageStatus>;
299
+ message: (id: string, credential: string, key: string) => Promise<import("./automations.js").DelegatedMessageStatus>;
300
+ withdraw: (id: string, credential: string, input: import("./automations.js").DelegatedMessageInput, key: string) => Promise<import("./automations.js").DelegatedMessageWithdrawal>;
301
+ webhooks: {
302
+ create: (url: string, key: string) => Promise<import("./automations.js").WebhookRegistration>;
303
+ recover: (key: string) => Promise<import("./automations.js").WebhookRegistration>;
304
+ };
305
+ };
122
306
  registerFunctions(url?: string): Promise<any>;
123
307
  /**
124
308
  * Crea o recupera l'identità centrale collegata all'utente locale.
@@ -128,7 +312,11 @@ export declare class ConnectServer {
128
312
  * Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
129
313
  * Le chiamate esistenti senza il campo mantengono il comportamento precedente.
130
314
  */
315
+ requestTeamPasswordReset(accessToken: string, subject: string): Promise<{
316
+ requested: true;
317
+ }>;
131
318
  mirrorUser(user: LocalUserProfile): Promise<MirroredUser>;
319
+ mirrorApplicationUser(accessToken: string, user: ApplicationMirrorInput): Promise<ApplicationTeamUserResult>;
132
320
  teamOverview(accessToken: string): Promise<TeamOverview>;
133
321
  teamUsers(accessToken: string): Promise<TeamUser[]>;
134
322
  teamRoles(accessToken: string): Promise<TeamRole[]>;
package/dist/server.js CHANGED
@@ -1,17 +1,93 @@
1
+ import { automationClient } from './automations.js';
1
2
  export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
2
3
  import { functionCatalogPath } from './functions.js';
3
4
  import { whatsappClient } from './whatsapp.js';
4
5
  import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ /** Business failures preserve a valid application session; uncertain outcomes require an explicit read/retry. */
7
+ export class ConnectApiError extends Error {
8
+ status;
9
+ code;
10
+ constructor(status, result) {
11
+ super(`Connect ${status}: ${JSON.stringify(result)}`);
12
+ this.status = status;
13
+ this.name = 'ConnectApiError';
14
+ this.code = typeof result.code === 'string' ? result.code : status === 401 ? 'authentication_required' : status === 403 ? 'forbidden' : status === 400 ? 'invalid_input' : status === 409 ? 'conflict' : 'service_unavailable';
15
+ }
16
+ }
17
+ /** Errore del contratto sorgente: lo stato HTTP resta disponibile al chiamante. */
18
+ export class ConnectOnboardingError extends Error {
19
+ status;
20
+ constructor(status, message) {
21
+ super(message);
22
+ this.status = status;
23
+ this.name = 'ConnectOnboardingError';
24
+ }
25
+ }
26
+ /**
27
+ * Client backend della sorgente/deployment per l'onboarding assistito.
28
+ * Non va usato nel browser: il segreto bootstrap resta sul server della sorgente.
29
+ * `submit` non sostituisce mai una credenziale già acquisita con la stessa chiave.
30
+ */
31
+ export class ConnectOnboardingSource {
32
+ config;
33
+ constructor(config) {
34
+ this.config = config;
35
+ }
36
+ async post(path, body, idempotencyKey) {
37
+ const url = new URL('/v1/app-onboarding/' + path, this.config.apiUrl);
38
+ const response = await fetch(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
39
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + this.config.secret, 'X-Connect-Source': this.config.sourceId, ...(this.config.presenterId ? { 'X-Connect-Presenter': this.config.presenterId } : {}),
40
+ ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}) },
41
+ body: JSON.stringify({ schemaVersion: 1, appId: this.config.appId, sourceId: this.config.sourceId, ...(this.config.deployment ? { deployment: this.config.deployment } : {}), ...body }) });
42
+ const text = await response.text();
43
+ let result = null;
44
+ try {
45
+ result = text ? JSON.parse(text) : null;
46
+ }
47
+ catch {
48
+ result = null;
49
+ }
50
+ if (!response.ok)
51
+ throw new ConnectOnboardingError(response.status, `Connect onboarding ${response.status}`);
52
+ if (!result || typeof result !== 'object')
53
+ throw new ConnectOnboardingError(response.status, 'Risposta onboarding non valida');
54
+ return result;
55
+ }
56
+ status(value) {
57
+ if (!value || typeof value.requestId !== 'string' || !['pending', 'approved', 'migrating', 'completed', 'rejected', 'expired', 'failed'].includes(value.state))
58
+ throw new ConnectOnboardingError(502, 'Risposta onboarding non valida');
59
+ const known = ['wait', 'sign_in', 'choose_connect_password', 'resubmit', 'contact_admin', 'closed'];
60
+ return { requestId: value.requestId, state: value.state, ...(value.nextAction ? { nextAction: known.includes(value.nextAction) ? value.nextAction : 'contact_admin' } : {}) };
61
+ }
62
+ configuration() { return this.post('configuration', {}); }
63
+ async recoverPassword(input, idempotencyKey) { return this.status(await this.post('password-recovery', input, idempotencyKey)); }
64
+ async loginContext(email) {
65
+ const value = await this.post('login-context', { email });
66
+ if (value.status === 'not_found')
67
+ return { status: 'not_found', ...(value.request ? { request: this.status(value.request) } : {}) };
68
+ if (value.status === 'connect' || value.status === 'configuration_required') {
69
+ const c = value.context, strings = (v) => v.every(x => typeof x === 'string' && x.length > 0);
70
+ if (c?.tenant && c?.binding && c?.user && strings([c.tenant.id, c.tenant.name, c.tenant.slug, c.binding.customerId, c.binding.installationId, c.binding.secret, c.user.id, c.user.subject, c.user.email]) && typeof c.user.firstName === 'string' && typeof c.user.lastName === 'string' && ['owner', 'manager', 'reception', 'collaborator'].includes(c.user.role) && Array.isArray(c.user.permissions) && c.user.permissions.every(p => typeof p === 'string'))
71
+ return value;
72
+ }
73
+ throw new ConnectOnboardingError(502, 'Risposta onboarding non valida');
74
+ }
75
+ async submit(request, idempotencyKey) {
76
+ if (!idempotencyKey || idempotencyKey.length < 8 || idempotencyKey.length > 200)
77
+ throw new Error('Idempotency-Key non valida');
78
+ return this.status(await this.post('requests', request, idempotencyKey));
79
+ }
80
+ }
5
81
  export class ConnectServer {
6
82
  config;
7
83
  constructor(config) {
8
84
  this.config = config;
9
85
  }
10
86
  async request(path, method = 'GET', body, accessToken, extra = {}) {
11
- const response = await fetch(`${this.config.apiUrl}${path}`, { method, headers: { 'Content-Type': 'application/json', 'X-Installation-Id': this.config.installationId, 'X-Installation-Secret': this.config.secret, ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });
87
+ const response = await fetch(`${this.config.apiUrl}${path}`, { method, ...(this.config.requestTimeoutMs ? { signal: AbortSignal.timeout(this.config.requestTimeoutMs), redirect: 'error' } : {}), headers: { 'Content-Type': 'application/json', 'X-Installation-Id': this.config.installationId, 'X-Installation-Secret': this.config.secret, ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });
12
88
  const result = await response.json();
13
89
  if (!response.ok)
14
- throw new Error(`Connect ${response.status}: ${JSON.stringify(result)}`);
90
+ throw new ConnectApiError(response.status, result);
15
91
  return result;
16
92
  }
17
93
  functionUrl(feature, path) {
@@ -24,6 +100,8 @@ export class ConnectServer {
24
100
  }
25
101
  authorize(accessToken, permission) { return this.request('/v1/authorize', 'POST', { installationId: this.config.installationId, permission }, accessToken); }
26
102
  whatsapp(accessToken) { return whatsappClient(async (path, method, body, extra) => this.request(path, method, body, typeof accessToken === 'function' ? await accessToken() : accessToken, extra), this.config.installationId, { apiUrl: this.config.apiUrl }); }
103
+ /** Backend only. Supply a personal token for creation/recovery; workers use the stored delegation credential. */
104
+ automations(accessToken) { return automationClient(async (path, method, body, extra) => this.request(path, method, body, typeof accessToken === 'function' ? await accessToken() : accessToken, extra), this.config.installationId); }
27
105
  registerFunctions(url) { const source = url || this.config.catalogUrl || (this.config.domain ? this.config.domain + (this.config.basePath || '') + functionCatalogPath : undefined); if (!source)
28
106
  throw new Error('URL funzioni o dominio richiesto'); return this.request('/v1/catalog-source', 'POST', { url: source }); }
29
107
  /**
@@ -34,7 +112,18 @@ export class ConnectServer {
34
112
  * Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
35
113
  * Le chiamate esistenti senza il campo mantengono il comportamento precedente.
36
114
  */
115
+ requestTeamPasswordReset(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/password-reset', 'POST', {}, accessToken); }
37
116
  mirrorUser(user) { return this.request('/v1/users/mirror', 'POST', user); }
117
+ async mirrorApplicationUser(accessToken, user) {
118
+ try {
119
+ return await this.request('/v1/users/mirror', 'POST', user, accessToken);
120
+ }
121
+ catch (error) {
122
+ if (error instanceof ConnectApiError)
123
+ throw error;
124
+ throw new ConnectApiError(0, { code: 'mirror_outcome_uncertain', message: 'Esito incerto: verifica e riprendi esplicitamente sullo stesso ID locale' });
125
+ }
126
+ }
38
127
  teamOverview(accessToken) { return this.request('/v1/team', 'GET', undefined, accessToken); }
39
128
  teamUsers(accessToken) { return this.request('/v1/team/users', 'GET', undefined, accessToken); }
40
129
  teamRoles(accessToken) { return this.request('/v1/team/roles', 'GET', undefined, accessToken); }
@@ -0,0 +1,18 @@
1
+ # Server only. Generate keys locally; do not commit filled values.
2
+ DATABASE_URL=
3
+ CONNECT_API_URL=http://localhost:8088
4
+ CONNECT_SOURCE_ID=workshop-development
5
+ CONNECT_SOURCE_SECRET=
6
+ # Alternative: technical credential issued for this deployment before app/source approval.
7
+ CONNECT_PRESENTER_ID=
8
+ CONNECT_PRESENTER_SECRET=
9
+ CONNECT_DEPLOYMENT_NAME=Workshop deployment
10
+ CONNECT_APP_ID=workshop
11
+ CONNECT_ISSUER=
12
+ CONNECT_CLIENT_ID=
13
+ CONNECT_CLIENT_SECRET=
14
+ CONNECT_ORIGIN=http://127.0.0.1:55179
15
+ CONNECT_ENCRYPTION_KEY=
16
+ # Used only by the explicit seed command; legacy password is hashed, never sent at startup.
17
+ DEMO_LEGACY_EMAIL=
18
+ DEMO_LEGACY_PASSWORD=
@@ -0,0 +1,13 @@
1
+ # Workshop BFF
2
+
3
+ Seconda applicazione autonoma, senza import ALORA, Nest o Angular. Un solo `ConnectApplication` e quattro adattatori: credenziali legacy, provisioning, persistenza PostgreSQL, restrizioni sui progetti. Nessun grant, PKCE, cifratura o macchina degli stati è implementato qui.
4
+
5
+ 1. Estrarre il tarball SDK e copiare questa cartella fuori dal repository. Installare con `npm install @eulab/connect@/percorso/eulab-connect-0.11.0.tgz pg@8.23.0` (sostituisce il riferimento relativo di esempio).
6
+ 2. Copiare `.env.example` in `.env`, impostare una **banca dati dedicata**, credenziale tecnica presenter e segreti secondo [la guida](../../INTEGRATION.md). Generare la chiave con `openssl rand -hex 32` e salvarla solo in `.env`.
7
+ 3. `npm run migrate`; facoltativamente impostare email/password legacy in `.env` e usare `npm run seed`. Il seed non sovrascrive account o hash esistenti. Nessun account admin o licenza viene creato.
8
+ 4. `npm run check` controlla discovery e sorgente, senza scritture. `npm start`, aprire `http://127.0.0.1:55179`.
9
+ 5. Accesso legacy → consenso → richiesta in attesa. L’amministratore Connect approva piano, catalogo e assegnazioni, poi esegue la pratica. Nel piano sceglie/crea app, cliente e installazione e configura il client SSO. Usare **Sincronizza configurazione approvata** prima del successivo accesso: la configurazione resta cifrata sul backend, poi si apre SSO. Prima dell’approvazione non servono issuer/clientId o sorgente registrata. Per `choose_connect_password`, ripetere la prova locale e scegliere una password Connect diversa; l’esecuzione successiva rimane esplicita in Connect.
10
+ 6. Se si adotta una sorgente già registrata, usare invece CONNECT_SOURCE_SECRET e configurazione OIDC statica: entrambi i percorsi restano supportati.
11
+ 7. Login SSO → callback BFF → handoff → cookie HttpOnly → progetti. Licenza e restrizioni per azienda vengono verificate prima della query. Refresh/logout sono chiamate SDK.
12
+
13
+ Il BFF limita il body e controlla Host/Origin. In produzione usare TLS e un adattatore HTTP per il proprio proxy verificato; rimuovere l’opt-in HTTP locale. Il demo usa intenzionalmente una sola origine loopback. Non è un sistema di amministrazione o una UI di produzione.
@@ -0,0 +1,9 @@
1
+ const $=id=>document.getElementById(id);let proposal;
2
+ async function call(path,body={}){const r=await fetch(path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)}),data=await r.json();if(!r.ok)throw Error(data.code);return data;}
3
+ function render(data){$('result').textContent=JSON.stringify(data,null,2);if(data.status==='redirect')location.assign(data.url);if(data.status==='configuration_required')$('result').textContent='Integrazione completata. Sincronizza la configurazione dal backend, poi ripeti l’accesso.';if(data.status==='administrative_required')$('result').textContent='Intervento amministrativo richiesto: '+data.reason;if(data.status==='migration_required'){proposal=data;$('migration').hidden=false;const recovery=data.request?.nextAction==='choose_connect_password';$('new-password').hidden=!recovery;$('action').textContent=recovery?'Scegli una nuova password per Connect, diversa dalla password locale.':'Conferma la prova locale e il consenso.';}}
4
+ async function show(fn){try{render(await fn());}catch(e){$('result').textContent=e.message;}}
5
+ $('login').onsubmit=e=>{e.preventDefault();show(async()=>{const d=Object.fromEntries(new FormData(e.target)),r=await call('/auth/sign-in',d);e.target.reset();return r;});};
6
+ $('migration').onsubmit=e=>{e.preventDefault();show(async()=>{const d=Object.fromEntries(new FormData(e.target));const r=await call('/auth/migration',{challenge:proposal.challenge,consentVersion:proposal.consentVersion,legacyPassword:d.legacyPassword,...(d.newConnectPassword?{newConnectPassword:d.newConnectPassword}:{}),idempotencyKey:crypto.randomUUID()});e.target.reset();$('migration').hidden=true;return r;});};
7
+ $('activation').onsubmit=e=>{e.preventDefault();show(async()=>{const d=Object.fromEntries(new FormData(e.target)),r=await call('/auth/activation',{kind:'activation',companyName:d.companyName,applicant:{email:d.email,firstName:d.firstName,lastName:d.lastName},initialPassword:d.password,consentVersion:'2026-10-21-mandatory-v1',idempotencyKey:crypto.randomUUID()});e.target.reset();return r;});};
8
+ for(const [id,path] of [['configuration','/auth/configuration'],['projects','/projects'],['refresh','/auth/refresh'],['logout','/auth/logout']])$(id).onclick=()=>show(()=>call(path));
9
+ const handoff=new URLSearchParams(location.hash.slice(1)).get('handoff');if(handoff){history.replaceState(null,'','/');show(()=>call('/auth/exchange',{handoff}));}
@@ -0,0 +1,6 @@
1
+ <!doctype html><html lang="it"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Workshop · Connect SDK</title>
2
+ <body><main><h1>Workshop</h1><p>Applicazione indipendente con BFF Connect. Le credenziali restano solo nei campi del modulo fino al loro invio esplicito.</p>
3
+ <form id="login"><label>Email <input name="email" type="email" required autocomplete="username"></label><label>Password locale <input name="password" type="password" autocomplete="current-password"></label><button>Accedi</button></form>
4
+ <form id="migration" hidden><h2>Consenso migrazione</h2><p id="action"></p><label>Password locale (prova) <input name="legacyPassword" type="password" required autocomplete="current-password"></label><label id="new-password" hidden>Nuova password Connect <input name="newConnectPassword" type="password" autocomplete="new-password"></label><label><input name="consent" type="checkbox" required>Acconsento alla migrazione verso Connect</label><button>Invia richiesta</button></form>
5
+ <details><summary>Richiedi attivazione di una nuova azienda</summary><form id="activation"><input name="companyName" placeholder="Azienda" required><input name="email" type="email" placeholder="Email" required><input name="firstName" placeholder="Nome" required><input name="lastName" placeholder="Cognome" required><input name="password" type="password" placeholder="Password Connect" required autocomplete="new-password"><label><input type="checkbox" required>Acconsento all’attivazione Connect</label><button>Richiedi attivazione</button></form></details>
6
+ <button id="configuration">Sincronizza configurazione approvata</button><button id="projects">Progetti</button><button id="refresh">Rinnova sessione</button><button id="logout">Esci</button><pre id="result" role="status"></pre></main><script src="/app.js" type="module"></script></body></html>
@@ -0,0 +1,8 @@
1
+ {
2
+ "name":"connect-workshop-demo",
3
+ "private":true,
4
+ "type":"module",
5
+ "engines":{"node":">=22"},
6
+ "scripts":{"start":"node --env-file=.env server.mjs","check":"node --env-file=.env server.mjs --check","migrate":"node --env-file=.env server.mjs --migrate","seed":"node --env-file=.env server.mjs --seed"},
7
+ "dependencies":{"@eulab/connect":"file:../../eulab-connect-0.11.0.tgz","pg":"8.23.0"}
8
+ }
@@ -0,0 +1,10 @@
1
+ CREATE TABLE IF NOT EXISTS workshop_accounts (
2
+ tenant_id text NOT NULL, id text NOT NULL, email text NOT NULL,
3
+ first_name text NOT NULL,last_name text NOT NULL,
4
+ password_salt text,password_hash text,
5
+ connect_subject text,connect_installation text,
6
+ PRIMARY KEY(tenant_id,id),UNIQUE(connect_installation,connect_subject)
7
+ );
8
+ CREATE TABLE IF NOT EXISTS workshop_projects (
9
+ id text PRIMARY KEY,tenant_id text NOT NULL,name text NOT NULL
10
+ );