@eulab/connect 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.d.ts CHANGED
@@ -3,14 +3,15 @@ export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js'
3
3
  export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
4
4
  export type { WhatsAppBotDefinition, WhatsAppBotNode, WhatsAppBotState, WhatsAppBotTurn, WhatsAppBot } from './bot.js';
5
5
  export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
6
- export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser } from './functions.js';
7
- import type { AccessResult, ConnectUser } 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
8
  export type { WhatsAppSession, WhatsAppArchive, Conversation, WhatsAppMessage, WhatsAppPayload } from './whatsapp.js';
9
9
  export interface LocalUserProfile {
10
10
  localUserId: string;
11
11
  username: string;
12
12
  email: string;
13
13
  displayName: string;
14
+ initialPassword?: string;
14
15
  }
15
16
  export interface MirroredUser {
16
17
  installationId: string;
@@ -22,6 +23,131 @@ export interface MirroredUser {
22
23
  status: 'created' | 'already_linked' | 'recovered';
23
24
  ssoSetupRequired: boolean | null;
24
25
  }
26
+ export type OnboardingRequestState = 'pending' | 'approved' | 'migrating' | 'completed' | 'rejected' | 'expired' | 'failed';
27
+ export type OnboardingNextAction = 'wait' | 'sign_in' | 'choose_connect_password' | 'resubmit' | 'contact_admin' | 'closed';
28
+ export interface OnboardingRequestStatus {
29
+ requestId: string;
30
+ state: OnboardingRequestState;
31
+ nextAction?: OnboardingNextAction;
32
+ }
33
+ export interface OnboardingPasswordRecovery {
34
+ requestId: string;
35
+ localTenantId: string;
36
+ localUserId: string;
37
+ email: string;
38
+ consentVersion: string;
39
+ newPassword: string;
40
+ }
41
+ export interface AuthorizedConnectContext {
42
+ tenant: {
43
+ id: string;
44
+ name: string;
45
+ slug: string;
46
+ };
47
+ binding: {
48
+ customerId: string;
49
+ installationId: string;
50
+ secret: string;
51
+ };
52
+ user: {
53
+ id: string;
54
+ subject: string;
55
+ email: string;
56
+ firstName: string;
57
+ lastName: string;
58
+ role: 'owner' | 'manager' | 'reception' | 'collaborator';
59
+ permissions: string[];
60
+ };
61
+ }
62
+ export interface ApprovedApplicationConfiguration {
63
+ sourceId: string;
64
+ appId: string;
65
+ issuer: string;
66
+ clientId: string;
67
+ redirectUri: string;
68
+ clientSecret?: string;
69
+ }
70
+ export interface DeploymentMetadata {
71
+ name: string;
72
+ environment: 'development' | 'staging' | 'production';
73
+ origins: string[];
74
+ catalogUrl?: string;
75
+ oidcCallbacks?: string[];
76
+ }
77
+ export type AppOnboardingLoginContext = {
78
+ status: 'configuration_required';
79
+ appId: string;
80
+ context: AuthorizedConnectContext;
81
+ } | {
82
+ status: 'connect';
83
+ context: AuthorizedConnectContext;
84
+ } | {
85
+ status: 'not_found';
86
+ request?: OnboardingRequestStatus;
87
+ };
88
+ export interface AppOnboardingMigrationRequest {
89
+ kind: 'migration';
90
+ consentVersion: string;
91
+ localTenant: {
92
+ id: string;
93
+ name: string;
94
+ slug: string;
95
+ };
96
+ localUser: {
97
+ id: string;
98
+ email: string;
99
+ firstName: string;
100
+ lastName: string;
101
+ role: 'owner' | 'manager' | 'reception' | 'collaborator';
102
+ permissions: string[];
103
+ };
104
+ /** Password verificata localmente: transito cifrato a TTL, mai restituita o registrata in chiaro. */
105
+ initialPassword: string;
106
+ }
107
+ export interface AppOnboardingActivationRequest {
108
+ kind: 'activation';
109
+ companyName: string;
110
+ applicant: {
111
+ email: string;
112
+ firstName: string;
113
+ lastName: string;
114
+ };
115
+ initialPassword: string;
116
+ }
117
+ export type AppOnboardingRequest = AppOnboardingMigrationRequest | AppOnboardingActivationRequest;
118
+ /** Errore del contratto sorgente: lo stato HTTP resta disponibile al chiamante. */
119
+ export declare class ConnectOnboardingError extends Error {
120
+ readonly status: number;
121
+ constructor(status: number, message: string);
122
+ }
123
+ /**
124
+ * Client backend della sorgente/deployment per l'onboarding assistito.
125
+ * Non va usato nel browser: il segreto bootstrap resta sul server della sorgente.
126
+ * `submit` non sostituisce mai una credenziale già acquisita con la stessa chiave.
127
+ */
128
+ export declare class ConnectOnboardingSource {
129
+ private readonly config;
130
+ constructor(config: {
131
+ apiUrl: string;
132
+ sourceId: string;
133
+ appId: string;
134
+ secret: string;
135
+ presenterId?: string;
136
+ deployment?: DeploymentMetadata;
137
+ });
138
+ private post;
139
+ private status;
140
+ configuration(): Promise<{
141
+ status: "pending" | "configuration_required";
142
+ plannedAppId?: string;
143
+ } | {
144
+ status: "ready";
145
+ configuration: ApprovedApplicationConfiguration;
146
+ }>;
147
+ recoverPassword(input: OnboardingPasswordRecovery, idempotencyKey: string): Promise<OnboardingRequestStatus>;
148
+ loginContext(email: string): Promise<AppOnboardingLoginContext>;
149
+ submit(request: AppOnboardingRequest, idempotencyKey: string): Promise<OnboardingRequestStatus>;
150
+ }
25
151
  export declare class ConnectServer {
26
152
  private readonly config;
27
153
  constructor(config: {
@@ -32,6 +158,7 @@ export declare class ConnectServer {
32
158
  functionFallbackUrl?: string;
33
159
  catalogUrl?: string;
34
160
  basePath?: string;
161
+ requestTimeoutMs?: number;
35
162
  });
36
163
  request<T = any>(path: string, method?: string, body?: unknown, accessToken?: string, extra?: Record<string, string>): Promise<T>;
37
164
  functionUrl(feature: string, path?: string): string;
@@ -119,7 +246,27 @@ export declare class ConnectServer {
119
246
  }>;
120
247
  };
121
248
  registerFunctions(url?: string): Promise<any>;
249
+ /**
250
+ * Crea o recupera l'identità centrale collegata all'utente locale.
251
+ *
252
+ * `initialPassword` deve provenire da una verifica locale appena conclusa e viene usata
253
+ * soltanto per inizializzare una nuova identità nel provider. Non viene conservata da
254
+ * Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
255
+ * Le chiamate esistenti senza il campo mantengono il comportamento precedente.
256
+ */
122
257
  mirrorUser(user: LocalUserProfile): Promise<MirroredUser>;
258
+ teamOverview(accessToken: string): Promise<TeamOverview>;
259
+ teamUsers(accessToken: string): Promise<TeamUser[]>;
260
+ teamRoles(accessToken: string): Promise<TeamRole[]>;
261
+ teamFunctions(accessToken: string): Promise<TeamFunction[]>;
262
+ createTeamRole(accessToken: string, role: TeamRoleInput): Promise<TeamRole>;
263
+ updateTeamRole(accessToken: string, id: string, role: TeamRoleInput): Promise<TeamRole>;
264
+ deleteTeamRole(accessToken: string, id: string): Promise<{
265
+ removed: boolean;
266
+ }>;
267
+ setTeamUserRoles(accessToken: string, subject: string, roleIds: string[]): Promise<TeamUserAssignment>;
268
+ revokeTeamUser(accessToken: string, subject: string): Promise<TeamRevocation>;
269
+ restoreTeamUser(accessToken: string, subject: string): Promise<TeamRestore>;
123
270
  permissions(accessToken: string): Promise<AccessResult>;
124
271
  notifications(accessToken: string, options?: {
125
272
  unread?: boolean;
package/dist/server.js CHANGED
@@ -2,13 +2,77 @@ export { defineFunctions, functionsResponse, functionCatalogPath } from './funct
2
2
  import { functionCatalogPath } from './functions.js';
3
3
  import { whatsappClient } from './whatsapp.js';
4
4
  import { createHmac, timingSafeEqual } from 'node:crypto';
5
+ /** Errore del contratto sorgente: lo stato HTTP resta disponibile al chiamante. */
6
+ export class ConnectOnboardingError extends Error {
7
+ status;
8
+ constructor(status, message) {
9
+ super(message);
10
+ this.status = status;
11
+ this.name = 'ConnectOnboardingError';
12
+ }
13
+ }
14
+ /**
15
+ * Client backend della sorgente/deployment per l'onboarding assistito.
16
+ * Non va usato nel browser: il segreto bootstrap resta sul server della sorgente.
17
+ * `submit` non sostituisce mai una credenziale già acquisita con la stessa chiave.
18
+ */
19
+ export class ConnectOnboardingSource {
20
+ config;
21
+ constructor(config) {
22
+ this.config = config;
23
+ }
24
+ async post(path, body, idempotencyKey) {
25
+ const url = new URL('/v1/app-onboarding/' + path, this.config.apiUrl);
26
+ const response = await fetch(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
27
+ 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 } : {}),
28
+ ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}) },
29
+ body: JSON.stringify({ schemaVersion: 1, appId: this.config.appId, sourceId: this.config.sourceId, ...(this.config.deployment ? { deployment: this.config.deployment } : {}), ...body }) });
30
+ const text = await response.text();
31
+ let result = null;
32
+ try {
33
+ result = text ? JSON.parse(text) : null;
34
+ }
35
+ catch {
36
+ result = null;
37
+ }
38
+ if (!response.ok)
39
+ throw new ConnectOnboardingError(response.status, `Connect onboarding ${response.status}`);
40
+ if (!result || typeof result !== 'object')
41
+ throw new ConnectOnboardingError(response.status, 'Risposta onboarding non valida');
42
+ return result;
43
+ }
44
+ status(value) {
45
+ if (!value || typeof value.requestId !== 'string' || !['pending', 'approved', 'migrating', 'completed', 'rejected', 'expired', 'failed'].includes(value.state))
46
+ throw new ConnectOnboardingError(502, 'Risposta onboarding non valida');
47
+ const known = ['wait', 'sign_in', 'choose_connect_password', 'resubmit', 'contact_admin', 'closed'];
48
+ return { requestId: value.requestId, state: value.state, ...(value.nextAction ? { nextAction: known.includes(value.nextAction) ? value.nextAction : 'contact_admin' } : {}) };
49
+ }
50
+ configuration() { return this.post('configuration', {}); }
51
+ async recoverPassword(input, idempotencyKey) { return this.status(await this.post('password-recovery', input, idempotencyKey)); }
52
+ async loginContext(email) {
53
+ const value = await this.post('login-context', { email });
54
+ if (value.status === 'not_found')
55
+ return { status: 'not_found', ...(value.request ? { request: this.status(value.request) } : {}) };
56
+ if (value.status === 'connect' || value.status === 'configuration_required') {
57
+ const c = value.context, strings = (v) => v.every(x => typeof x === 'string' && x.length > 0);
58
+ 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'))
59
+ return value;
60
+ }
61
+ throw new ConnectOnboardingError(502, 'Risposta onboarding non valida');
62
+ }
63
+ async submit(request, idempotencyKey) {
64
+ if (!idempotencyKey || idempotencyKey.length < 8 || idempotencyKey.length > 200)
65
+ throw new Error('Idempotency-Key non valida');
66
+ return this.status(await this.post('requests', request, idempotencyKey));
67
+ }
68
+ }
5
69
  export class ConnectServer {
6
70
  config;
7
71
  constructor(config) {
8
72
  this.config = config;
9
73
  }
10
74
  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) });
75
+ 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
76
  const result = await response.json();
13
77
  if (!response.ok)
14
78
  throw new Error(`Connect ${response.status}: ${JSON.stringify(result)}`);
@@ -26,7 +90,25 @@ export class ConnectServer {
26
90
  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 }); }
27
91
  registerFunctions(url) { const source = url || this.config.catalogUrl || (this.config.domain ? this.config.domain + (this.config.basePath || '') + functionCatalogPath : undefined); if (!source)
28
92
  throw new Error('URL funzioni o dominio richiesto'); return this.request('/v1/catalog-source', 'POST', { url: source }); }
93
+ /**
94
+ * Crea o recupera l'identità centrale collegata all'utente locale.
95
+ *
96
+ * `initialPassword` deve provenire da una verifica locale appena conclusa e viene usata
97
+ * soltanto per inizializzare una nuova identità nel provider. Non viene conservata da
98
+ * Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
99
+ * Le chiamate esistenti senza il campo mantengono il comportamento precedente.
100
+ */
29
101
  mirrorUser(user) { return this.request('/v1/users/mirror', 'POST', user); }
102
+ teamOverview(accessToken) { return this.request('/v1/team', 'GET', undefined, accessToken); }
103
+ teamUsers(accessToken) { return this.request('/v1/team/users', 'GET', undefined, accessToken); }
104
+ teamRoles(accessToken) { return this.request('/v1/team/roles', 'GET', undefined, accessToken); }
105
+ teamFunctions(accessToken) { return this.request('/v1/team/functions', 'GET', undefined, accessToken); }
106
+ createTeamRole(accessToken, role) { return this.request('/v1/team/roles', 'POST', role, accessToken); }
107
+ updateTeamRole(accessToken, id, role) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'PUT', role, accessToken); }
108
+ deleteTeamRole(accessToken, id) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'DELETE', undefined, accessToken); }
109
+ setTeamUserRoles(accessToken, subject, roleIds) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/roles', 'PUT', { roleIds }, accessToken); }
110
+ revokeTeamUser(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject), 'DELETE', undefined, accessToken); }
111
+ restoreTeamUser(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/restore', 'POST', undefined, accessToken); }
30
112
  permissions(accessToken) { return this.request('/v1/access', 'GET', undefined, accessToken); }
31
113
  notifications(accessToken, options = {}) { const query = new URLSearchParams(); for (const [key, value] of Object.entries(options))
32
114
  if (value !== undefined)
@@ -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.10.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.10.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
+ );
@@ -0,0 +1,88 @@
1
+ import {createServer} from 'node:http';
2
+ import {readFile} from 'node:fs/promises';
3
+ import {scryptSync,timingSafeEqual,randomBytes} from 'node:crypto';
4
+ import pg from 'pg';
5
+ import {ConnectApplication,ConnectApplicationError,PostgresConnectApplicationStore} from '@eulab/connect/application';
6
+ import {defineFunctions,functionsResponse} from '@eulab/connect/server';
7
+ const required=key=>{if(!process.env[key])throw Error('Missing '+key);return process.env[key];};
8
+ const pool=new pg.Pool({connectionString:required('DATABASE_URL'),max:10});
9
+ const store=new PostgresConnectApplicationStore(pool,required('CONNECT_SOURCE_ID'));
10
+ const origin=required('CONNECT_ORIGIN');
11
+ const catalog=defineFunctions({appId:required('CONNECT_APP_ID'),version:1,functions:[{key:'projects.read',name:'Read projects'}]});
12
+ const accounts={
13
+ async verifyLegacy({email,password}){
14
+ // An ambiguous local account requires local selection; it never chooses a company by guessing.
15
+ const {rows}=await pool.query('SELECT * FROM workshop_accounts WHERE lower(email)=lower($1)',[email]);
16
+ const row=rows.length===1?rows[0]:null;
17
+ if(!row?.password_hash||!timingSafeEqual(scryptSync(password,row.password_salt,32),Buffer.from(row.password_hash,'hex')))return null;
18
+ return {localTenant:{id:row.tenant_id,name:'Workshop',slug:'workshop'},localUser:{id:row.id,email:row.email,firstName:row.first_name,lastName:row.last_name,role:'owner',permissions:['projects.read']}};
19
+ },
20
+ async provision(context,{transaction}){
21
+ const {tenant,user,binding}=context;
22
+ // Same connection and transaction as handoff consumption. No email join, no legacy hash update.
23
+ const {rows}=await transaction.sql.query(`INSERT INTO workshop_accounts(tenant_id,id,email,first_name,last_name,connect_subject,connect_installation)
24
+ VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(tenant_id,id) DO UPDATE SET connect_subject=EXCLUDED.connect_subject,connect_installation=EXCLUDED.connect_installation
25
+ WHERE (workshop_accounts.connect_subject IS NULL OR workshop_accounts.connect_subject=EXCLUDED.connect_subject)
26
+ AND (workshop_accounts.connect_installation IS NULL OR workshop_accounts.connect_installation=EXCLUDED.connect_installation) RETURNING id`,
27
+ [tenant.id,user.id,user.email,user.firstName,user.lastName,user.subject,binding.installationId]);
28
+ if(rows.length!==1)throw new ConnectApplicationError('provision_conflict');
29
+ return {localTenantId:tenant.id,localUserId:user.id};
30
+ },
31
+ async restrict(profile,key,resource){return key==='projects.read'&&resource?.tenantId===profile.localTenantId;}
32
+ };
33
+ // The only SDK instance in this application. Existing team/WhatsApp/catalog methods remain available through services().
34
+ const connect=new ConnectApplication({apiUrl:required('CONNECT_API_URL'),sourceId:required('CONNECT_SOURCE_ID'),sourceSecret:process.env.CONNECT_SOURCE_SECRET,appId:catalog.appId,
35
+ ...(process.env.CONNECT_PRESENTER_ID?{presenter:{id:process.env.CONNECT_PRESENTER_ID,secret:required('CONNECT_PRESENTER_SECRET'),deployment:{name:required('CONNECT_DEPLOYMENT_NAME'),environment:'development',origins:[origin],catalogUrl:origin+'/.well-known/eulab-connect.json',oidcCallbacks:[origin+'/callback']}}}:{}),
36
+ issuer:process.env.CONNECT_ISSUER||undefined,clientId:process.env.CONNECT_CLIENT_ID||undefined,clientSecret:process.env.CONNECT_CLIENT_SECRET||undefined,
37
+ appOrigin:origin,redirectUri:process.env.CONNECT_ISSUER?origin+'/callback':undefined,allowLoopbackHttp:true,encryptionKey:required('CONNECT_ENCRYPTION_KEY'),store,accounts,catalog});
38
+ if(process.argv.includes('--check')){console.log(JSON.stringify(await connect.diagnose(process.env.DEMO_LEGACY_EMAIL),null,2));await pool.end();}
39
+ else if(process.argv.includes('--migrate')){await store.migrate();await pool.query(await readFile(new URL('./schema.sql',import.meta.url),'utf8'));await pool.end();}
40
+ else if(process.argv.includes('--seed')){
41
+ const password=required('DEMO_LEGACY_PASSWORD'),salt=randomBytes(16).toString('hex');
42
+ await pool.query("INSERT INTO workshop_accounts(tenant_id,id,email,first_name,last_name,password_salt,password_hash) VALUES('workspace-1','local-1',$1,'Demo','User',$2,$3) ON CONFLICT DO NOTHING",[required('DEMO_LEGACY_EMAIL'),salt,scryptSync(password,salt,32).toString('hex')]);
43
+ await pool.query("INSERT INTO workshop_projects(id,tenant_id,name) VALUES('demo-project','workspace-1','First project') ON CONFLICT DO NOTHING");await pool.end();
44
+ }else{
45
+ const cookieString=c=>`${c.name}=${encodeURIComponent(c.value)}; Path=${c.path}; Max-Age=${c.maxAge}; HttpOnly; SameSite=Lax${c.secure?'; Secure':''}`;
46
+ const server=createServer(async(req,res)=>{
47
+ res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('Content-Security-Policy',"default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
48
+ const send=(data,status=200,cookies=[])=>{res.writeHead(status,{'content-type':'application/json','set-cookie':cookies.map(cookieString)});res.end(JSON.stringify(data));};
49
+ try{
50
+ if(req.headers.host!==new URL(origin).host)return send({code:'invalid_context'},400);
51
+ const url=new URL(req.url,origin),cookies=Object.fromEntries((req.headers.cookie||'').split(';').filter(Boolean).map(v=>{const [k,...parts]=v.trim().split('=');return [k,decodeURIComponent(parts.join('='))];}));
52
+ const ctx={origin:req.method==='POST'?req.headers.origin:origin,cookies};
53
+ if(req.method==='GET'&&url.pathname==='/.well-known/eulab-connect.json'){const r=functionsResponse(connect.catalog);res.writeHead(r.status,Object.fromEntries(r.headers));return res.end(await r.text());}
54
+ if(req.method==='GET'&&url.pathname==='/callback'){
55
+ const r=await connect.auth.callback({state:url.searchParams.get('state')||'',code:url.searchParams.get('code')||undefined,error:url.searchParams.get('error')||undefined,iss:url.searchParams.get('iss')||undefined},ctx);
56
+ res.writeHead(303,{location:origin+'/#handoff='+encodeURIComponent(r.handoff),'set-cookie':r.cookies.map(cookieString)});return res.end();
57
+ }
58
+ if(req.method==='GET'&&['/','/app.js'].includes(url.pathname)){res.setHeader('content-type',url.pathname==='/'?'text/html; charset=utf-8':'text/javascript; charset=utf-8');return res.end(await readFile(new URL(url.pathname==='/'?'./index.html':'./app.js',import.meta.url)));}
59
+ if(req.method==='POST'){
60
+ if(req.headers.origin!==origin)return send({code:'invalid_context'},403);
61
+ let raw='';for await(const part of req){raw+=part;if(Buffer.byteLength(raw)>16384)return send({code:'invalid_input'},413);}
62
+ const body=JSON.parse(raw||'{}');let result;
63
+ switch(url.pathname){
64
+ case '/auth/configuration':result=await connect.configuration.sync();break;
65
+ case '/auth/sign-in':result=await connect.auth.signIn(body,ctx);break;
66
+ case '/auth/migration':result=await connect.migration.submit(body,ctx);break;
67
+ case '/auth/activation':result=await connect.activation.submit({...body,kind:'activation'},ctx);break;
68
+ case '/auth/exchange':result=await connect.auth.exchange(body.handoff,ctx);break;
69
+ case '/auth/refresh':result={session:await connect.auth.refresh(connect.auth.fromCookies(ctx))};break;
70
+ case '/auth/logout':result=await connect.auth.logout(connect.auth.fromCookies(ctx),ctx);break;
71
+ case '/projects':{
72
+ const id=connect.auth.fromCookies(ctx),session=await connect.auth.resolve(id),tenantId=session.profile.localTenantId;
73
+ const access=await connect.access.authorize(id,'projects.read',{tenantId});if(!access.allowed)return send({code:'access_denied'},403);
74
+ // Central authorization is followed by a tenant predicate on every local data query.
75
+ const projects=(await pool.query('SELECT id,name FROM workshop_projects WHERE tenant_id=$1',[tenantId])).rows;return send({projects});
76
+ }
77
+ default:return send({code:'not_found'},404);
78
+ }
79
+ const {cookies:directives=[],...publicResult}=result;
80
+ // Session handles live in HttpOnly cookies; expose only the profile.
81
+ if(publicResult.session)publicResult.session={profile:publicResult.session.profile,expiresAt:publicResult.session.expiresAt};
82
+ return send(publicResult,200,directives);
83
+ }
84
+ return send({code:'not_found'},404);
85
+ }catch(e){return send({code:e instanceof ConnectApplicationError?e.code:'request_failed'},400);}
86
+ });
87
+ server.listen(Number(new URL(origin).port||443),'127.0.0.1',()=>console.log('Workshop BFF ready on '+origin));
88
+ }
@@ -0,0 +1,7 @@
1
+
2
+ CREATE TABLE IF NOT EXISTS connect_sdk_schema(version integer PRIMARY KEY);
3
+ CREATE TABLE IF NOT EXISTS connect_sdk_records(
4
+ namespace text NOT NULL, id text NOT NULL, cipher text NOT NULL,
5
+ expires_at timestamptz NOT NULL, PRIMARY KEY(namespace,id));
6
+ CREATE INDEX IF NOT EXISTS connect_sdk_expiry ON connect_sdk_records(expires_at);
7
+ INSERT INTO connect_sdk_schema(version) VALUES(1) ON CONFLICT DO NOTHING;
package/package.json CHANGED
@@ -1,21 +1,42 @@
1
1
  {
2
2
  "name": "@eulab/connect",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "SDK EULab Connect per browser e server: SSO, permessi e WhatsApp",
5
5
  "author": "EULAB",
6
6
  "type": "module",
7
7
  "exports": {
8
- "./browser": {"types": "./dist/browser.d.ts", "import": "./dist/browser.js"},
9
- "./server": {"types": "./dist/server.d.ts", "import": "./dist/server.js"}
8
+ "./browser": {
9
+ "types": "./dist/browser.d.ts",
10
+ "import": "./dist/browser.js"
11
+ },
12
+ "./server": {
13
+ "types": "./dist/server.d.ts",
14
+ "import": "./dist/server.js"
15
+ },
16
+ "./application": {
17
+ "types": "./dist/application.d.ts",
18
+ "import": "./dist/application.js"
19
+ }
10
20
  },
11
21
  "scripts": {
12
22
  "build": "tsc -p tsconfig.json",
13
23
  "prepack": "npm run build"
14
24
  },
15
- "publishConfig": {"access": "public", "registry": "https://registry.npmjs.org/"},
16
- "engines": {"node": ">=22"},
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org/"
28
+ },
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
17
32
  "files": [
18
33
  "dist",
19
- "!dist/**/*.map"
20
- ]
34
+ "!dist/**/*.map",
35
+ "examples",
36
+ "migrations",
37
+ "INTEGRATION.md"
38
+ ],
39
+ "dependencies": {
40
+ "jose": "^6.2.12"
41
+ }
21
42
  }