@eulab/connect 0.10.0 → 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.
- package/AUTOMATIONS.md +144 -0
- package/INTEGRATION.md +15 -0
- package/README.md +13 -0
- package/dist/application.d.ts +6 -0
- package/dist/application.js +33 -7
- package/dist/automations.d.ts +119 -0
- package/dist/automations.js +17 -0
- package/dist/browser.js +32 -3
- package/dist/server.d.ts +62 -0
- package/dist/server.js +26 -1
- package/examples/workshop/README.md +1 -1
- package/examples/workshop/package.json +1 -1
- package/package.json +8 -2
package/AUTOMATIONS.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# Automazioni server — 0.12.0
|
|
2
|
+
|
|
3
|
+
Richiede Connect con schema **015** e API/runner aggiornati insieme. Contratto aggiuntivo: invii manuali, delega bot e `verifyWebhook` mantengono le firme esistenti. Nessuna pubblicazione npm implicita.
|
|
4
|
+
|
|
5
|
+
## Autorizzazione e credenziali
|
|
6
|
+
|
|
7
|
+
`ConnectServer.automations(accessToken?)` è disponibile solo nell’entrypoint `@eulab/connect/server`. Creazione e recupero richiedono credenziale dell’installazione e token personale corrente dell’autore. Il worker usa la credenziale della delega e quella dell’installazione, senza token UI o refresh token. Le route rifiutano chiamate con `Origin` o `Sec-Fetch-Site`, oltre a quelle prive dell’autenticazione server.
|
|
8
|
+
|
|
9
|
+
La delega registra autore verificato dal guard, installazione/app, finalità, canale, funzioni, archivio del numero WhatsApp, revisione, scadenza e revoca. Non assegna ruoli o permessi. Nessun `subject`, `admin` o token personale è accettato nel payload del job. Anche un amministratore deve possedere i diritti applicativi correnti: nessun bypass tecnico viene conservato nella delega.
|
|
10
|
+
|
|
11
|
+
Per `whatsapp` sono obbligatorie esattamente `whatsapp.manage` e `whatsapp.send`, oltre all’archivio appartenente all’installazione. Il controllo corrente comprende installazione/app, identità e membership abilitate, link locale, revoca applicativa, ruoli, catalogo, entitlement acquistato/abilitato, licenza attiva/non scaduta. Il provider identità viene letto tramite il servizio identità esistente: autore assente/disabilitato nega l’autorizzazione; indisponibilità nega l’effetto. Il token browser non viene conservato nella delega o nella sua outbox.
|
|
12
|
+
|
|
13
|
+
`application_notification` ed `email` richiedono deleghe **distinte**, con funzioni esistenti nel catalogo dell’app e prive del prefisso `whatsapp.`. Non ammettono `archiveId`. Il loro uso è autorizzabile con `verify`; gli effetti applicativi/email restano al consumer. Questo candidato non aggiunge un servizio di invio email delegato e non estende `POST /v1/notifications`.
|
|
14
|
+
|
|
15
|
+
Connect conserva la credenziale cifrata con la chiave dati esistente, più un hash per verificarla. `AutomationGrant` e `WebhookRegistration` contengono segreti: il consumer deve persisterli cifrati nel proprio store server, senza loggarli o restituirli al browser. `get`, `verify`, `revoke`, stato outbox, overview e liste webhook non restituiscono credenziali. Non passare segreti in URL o query string.
|
|
16
|
+
|
|
17
|
+
## Metodi SDK e route
|
|
18
|
+
|
|
19
|
+
Prefisso `R = /v1/installations/:installationId/automations`.
|
|
20
|
+
|
|
21
|
+
| SDK | HTTP | Autenticazione oltre alla credenziale installazione |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| `create(input, key)` | `POST R/delegations` | Token personale, `Idempotency-Key` |
|
|
24
|
+
| `recover(key)` | `GET R/delegations/by-key/:key` | Token personale dello stesso autore |
|
|
25
|
+
| `get(id, credential?)` | `GET R/delegations/:id` | Credenziale delega oppure token dello stesso autore |
|
|
26
|
+
| `verify(id, scope, credential?)` | `POST R/delegations/:id/verify` | Come `get` |
|
|
27
|
+
| `revoke(id, credential?)` | `DELETE R/delegations/:id` | Come `get`; ripetibile |
|
|
28
|
+
| `send(id, credential, input, key)` | `POST R/delegations/:id/messages` | `X-Connect-Delegation`, `Idempotency-Key` |
|
|
29
|
+
| `message(id, credential, key)` | `GET R/delegations/:id/messages/by-key/:key` | `X-Connect-Delegation` |
|
|
30
|
+
| `withdraw(id, credential, input, key)` | `POST R/delegations/:id/messages/by-key/:key/withdraw` | `X-Connect-Delegation`, stesso comando originale nel body |
|
|
31
|
+
| `webhooks.create(url, key)` | `POST R/webhooks` | Token personale con `whatsapp.manage`, `Idempotency-Key` |
|
|
32
|
+
| `webhooks.recover(key)` | `GET R/webhooks/by-key/:key` | Token personale dello stesso autore con `whatsapp.manage` |
|
|
33
|
+
|
|
34
|
+
Le chiavi sono obbligatorie, 8–128 caratteri `[A-Za-z0-9_-]`. Lo SDK non le genera e non ripete automaticamente le chiamate. `create` restituisce `{delegation, credential}`; `webhooks.create/recover` restituiscono `{id, url, enabled, secret}`. `verify` riceve `{purpose, channel, functions}` e restituisce `{allowed, reason}`. Errori di autenticazione, input, conflitto o indisponibilità restano errori HTTP/`ConnectApiError`.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import {ConnectServer} from '@eulab/connect/server';
|
|
38
|
+
|
|
39
|
+
// Eseguito esclusivamente nel backend. binding proviene dallo store server cifrato.
|
|
40
|
+
const connect = new ConnectServer({apiUrl, ...binding});
|
|
41
|
+
const grant = await connect.automations(currentAccessToken).create({
|
|
42
|
+
purpose: 'appointments.reminder',
|
|
43
|
+
channel: 'whatsapp',
|
|
44
|
+
functions: ['whatsapp.manage', 'whatsapp.send'],
|
|
45
|
+
archiveId,
|
|
46
|
+
expiresAt: '2026-12-01T00:00:00Z',
|
|
47
|
+
}, persistedGrantKey);
|
|
48
|
+
// consumerVault è lo store cifrato del consumer, da implementare/riusare nel consumer.
|
|
49
|
+
await consumerVault.putEncrypted(grant.delegation.id, grant.credential);
|
|
50
|
+
// Al browser restituire solo stato, scadenza e motivo sicuro.
|
|
51
|
+
const ui = {id: grant.delegation.id, expiresAt: grant.delegation.expiresAt};
|
|
52
|
+
|
|
53
|
+
// Giorni dopo, anche con sessione UI scaduta:
|
|
54
|
+
const worker = connect.automations();
|
|
55
|
+
const credential = await consumerVault.readDecrypted(ui.id);
|
|
56
|
+
const accepted = await worker.send(ui.id, credential, {
|
|
57
|
+
purpose: 'appointments.reminder', sessionId,
|
|
58
|
+
payload: {kind: 'text', to: recipient, text: reminder},
|
|
59
|
+
}, persistedMessageKey);
|
|
60
|
+
const authoritative = await worker.message(ui.id, credential, persistedMessageKey);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Con la facciata esistente, creazione/recupero si eseguono dentro `application.services(sessionId, (client, token) => ...)`, salvando il segreto nel backend e proiettando solo campi sicuri. Il worker successivo usa il binding server e la credenziale cifrata salvata, senza riaprire quella sessione.
|
|
64
|
+
|
|
65
|
+
## Idempotenza, scadenza e outbox
|
|
66
|
+
|
|
67
|
+
Creazione: ricevuta unica per `(installazione, autore, chiave)` e hash del payload canonico. Replay identico o `recover` restituiscono la stessa credenziale senza rotazione; il recupero ricontrolla i diritti correnti. Cambiare finalità, archivio, scadenza o funzioni con la stessa chiave produce `409`. Le funzioni sono ordinate e deduplicate; l’ordine delle proprietà JSON non cambia la ricevuta. La scadenza iniziale deve essere futura ed entro 366 giorni. Una delega scaduta/revocata non si rinnova con la stessa chiave.
|
|
68
|
+
|
|
69
|
+
Invio: stessa outbox Connect, stessa unicità `(installazione, chiave)`. La ricevuta include delega, autore, sessione, finalità e payload. Replay discordante produce `409`, anche tra deleghe/canali/manuale/bot. Una risposta HTTP persa si recupera con `message` o con lo stesso `send`, senza cambiare chiave. La lettura della ricevuta originaria resta possibile dopo revoca/scadenza/disconnessione, mentre nuovi invii sono negati. L’accesso API richiede comunque una credenziale installazione ancora abilitata. Una nuova sessione sullo stesso archivio è ammessa con una nuova richiesta; una sessione di altro numero/installazione è rifiutata. Un invio già accettato sulla sessione precedente non viene trasferito automaticamente.
|
|
70
|
+
|
|
71
|
+
| Stato | Significato |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `queued` | Accettato in outbox; nessuna prova di invio |
|
|
74
|
+
| `sending` | Tentativo acquisito una sola volta; esito ancora aperto |
|
|
75
|
+
| `sent` | Provider ha restituito un identificatore, commit outbox/evento riuscito; non prova consegna al dispositivo |
|
|
76
|
+
| `cancelled` | Ritiro esplicito o arresto prima dell’effetto per revoca/scadenza/sessione non valida |
|
|
77
|
+
| `failed` | Stato storico compatibile; il nuovo percorso non deduce un rifiuto certo da un timeout |
|
|
78
|
+
| `uncertain` | Esito ambiguo o worker interrotto; nessun reinvio automatico |
|
|
79
|
+
|
|
80
|
+
Il runner ricontrolla il grant corrente prima di acquisire il tentativo e immediatamente prima della chiamata provider. L’acquisizione serializza con la revoca; anche una revoca conclusa tra acquisizione e ultimo controllo impedisce l’effetto. Non è possibile annullare una chiamata già entrata nel provider o garantire atomicità distribuita tra SQL, provider identità e WhatsApp. Un crash prima/dopo l’effetto lascia `sending`, trasformato in `uncertain` all’avvio: si conserva l’incertezza anche se il messaggio potrebbe non essere mai partito. Un errore del provider identità prima dell’acquisizione lascia il comando in coda, senza effetto.
|
|
81
|
+
|
|
82
|
+
Non usare una nuova chiave per aggirare `uncertain`. Il consumer deve mantenere la stessa chiave per lo stesso comando di dominio e gestire la riconciliazione esplicita. Le ricevute hanno la durata dei dati: l’eliminazione esplicita di archivio/installazione può eliminarle; non è una procedura di retry.
|
|
83
|
+
|
|
84
|
+
## Ritiro del singolo comando (0.12.0)
|
|
85
|
+
|
|
86
|
+
Il ritiro usa `connect.automations().withdraw(id, credential, originalInput, originalKey)` senza token browser. `originalInput` ha lo stesso tipo `DelegatedMessageInput` e la stessa normalizzazione di `send`: `{purpose, sessionId, payload}`. `originalKey` è la chiave dell’invio, presente nel path; non serve una seconda chiave di idempotenza. Le firme di `send`, `message`, `revoke` e delle API manuali/bot restano invariate.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
const result = await connect.automations().withdraw(
|
|
90
|
+
delegationId, credential, originalCommand, persistedMessageKey,
|
|
91
|
+
);
|
|
92
|
+
if (result.outcome === 'withdrawn') {
|
|
93
|
+
// result.message.state è tipizzato come 'cancelled'.
|
|
94
|
+
// Questa ricevuta impedisce anche un successivo replay di send.
|
|
95
|
+
} else if (result.outcome === 'effect_started') {
|
|
96
|
+
// 'sending', 'sent' o 'uncertain': non dichiarare annullato l’effetto.
|
|
97
|
+
// Leggere message con la stessa chiave; nessun nuovo tentativo automatico.
|
|
98
|
+
} else {
|
|
99
|
+
// 'already_terminal': fallito o già cancellato per un altro motivo.
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Il risultato è l’unione discriminata `DelegatedMessageWithdrawal`, con `{outcome, message}`. `message` contiene la stessa proiezione autorevole di `message()`, senza payload o credenziali.
|
|
104
|
+
|
|
105
|
+
| Stato trovato sotto lock | Esito | Transizione |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| Comando assente | `withdrawn` | Ricevuta preventiva nella stessa outbox: `cancelled`, `error='command_withdrawn'`; mai `queued` |
|
|
108
|
+
| `queued` | `withdrawn` | Stessa riga/ID passa a `cancelled`, `error='command_withdrawn'` |
|
|
109
|
+
| `cancelled` con `command_withdrawn` | `withdrawn` | Nessuna modifica; replay del ritiro già riuscito |
|
|
110
|
+
| `cancelled` per altro motivo oppure `failed` | `already_terminal` | Nessuna modifica; non è una nuova cancellazione |
|
|
111
|
+
| `sending`, `sent`, `uncertain` | `effect_started` | Nessuna modifica; l’effetto acquisito non viene dichiarato ritirato |
|
|
112
|
+
|
|
113
|
+
La ricevuta è vincolata a installazione, delega/autore, finalità, sessione, chiave e hash canonico del payload originale, identico a quello di `send`. Se la chiave è già occupata da un altro comando, delega o invio manuale, oppure i dati originali non coincidono, il ritiro restituisce `409` e non cambia la riga. Per una ricevuta ancora assente si verifica comunque che la delega sia WhatsApp, la finalità coincida e la sessione appartenga all’installazione e all’archivio autorizzati; non occorre una sessione attualmente connessa. Credenziali installazione ancora valide e possesso della credenziale delega restano obbligatori. Una delega estranea non è visibile (`404`), un binding di installazione discordante è rifiutato; le chiavi restano nel namespace della rispettiva installazione.
|
|
114
|
+
|
|
115
|
+
**Serializzazione:** ritiro, `send` e acquisizione runner prendono il medesimo lock della delega prima del lock della riga outbox. Un `send` che non ha ancora inserito/commesso mantiene già quel lock: il ritiro attende il commit/rollback e poi cancella la coda o riserva la ricevuta preventiva, purché il runner non abbia già acquisito il tentativo; in quel caso restituisce `effect_started`. Se il ritiro arriva prima, la riga `cancelled` viene commessa prima che il `send` possa proseguire; quest’ultimo legge la stessa ricevuta senza accodare. Il vincolo univoco `(installazione, chiave)` e il confronto del digest risolvono anche collisioni tra deleghe differenti. Il ritiro non si conclude con un `404` per il solo fatto che l’invio non è ancora visibile.
|
|
116
|
+
|
|
117
|
+
Non è richiesta una migrazione: il candidato riusa colonne, stato terminale e vincoli dello schema 015. Non viene aggiunta una seconda outbox o una coda di cancellazioni. Il replay del ritiro riuscito restituisce lo stesso ID/stato; una risposta persa dopo commit si recupera ripetendo `withdraw` o leggendo `message`, con la stessa chiave. La ricevuta non viene riaperta da `send`, anche dopo scadenza/revoca. La lettura dello stato corrente di un tentativo già acquisito può invece evolvere, ad esempio da `sending` a `sent`: il ritiro resta `effect_started`, senza congelare uno stato vecchio.
|
|
118
|
+
|
|
119
|
+
Ritiro e lettura sono operazioni di proprietà, permesse anche dopo scadenza/revoca della delega e senza interrogare il provider identità o ampliare i diritti. Nuovi invii restano soggetti ai controlli correnti. Una revoca che aveva già cancellato la riga produce `already_terminal`; un comando ancora assente può essere riservato come ritirato anche con grant scaduto/revocato. Il ritiro non revoca la delega condivisa e non modifica le altre prenotazioni.
|
|
120
|
+
|
|
121
|
+
Nessuna cancellazione dal dispositivo, nessuna rotazione di credenziali e nessun annullamento di una chiamata già entrata nel provider. L’aggiornamento della prenotazione ALORA e il ritiro Connect non condividono una transazione: ALORA deve mantenere visibili gli esiti `effect_started` e `uncertain`, senza inventare un nuovo invio. Le ricevute durano quanto i dati dell’archivio/installazione, secondo il confine di conservazione già previsto; l’eliminazione esplicita dello storico non è una procedura di retry.
|
|
122
|
+
|
|
123
|
+
## Webhook recuperabili
|
|
124
|
+
|
|
125
|
+
Le nuove route usano `webhook_endpoints` esistente. Creazione concorrente o risposta persa dopo commit: ripetere la stessa chiave/URL o usare `recover`, con stesso autore e installazione. ID e segreto restano invariati. URL diverso con stessa chiave: `409`. Un endpoint disabilitato rimane disabilitato anche al replay. Gli endpoint storici/manuali non vengono adottati né duplicati da un recupero: senza ricevuta la nuova route restituisce `404`. L’API manuale storica resta disponibile.
|
|
126
|
+
|
|
127
|
+
Il trasporto mantiene HTTPS/443, controllo DNS e rifiuto di indirizzi privati. Un test loopback non dimostra raggiungibilità pubblica; non abilitare localhost nel runner per collaudare il consumer.
|
|
128
|
+
|
|
129
|
+
## Eventi firmati e risposte interattive
|
|
130
|
+
|
|
131
|
+
Envelope aggiuntivo compatibile: `{id, kind, createdAt, installationId, sessionId, payload}`. Il runner conserva `x-eulab-event-id`, `x-eulab-timestamp`, `x-eulab-signature`; HMAC-SHA256 su `timestamp.rawBody`. Riutilizzare `verifyWebhook(secret, rawBody, timestamp, signature)` esistente, con tolleranza di cinque minuti. Verificare il corpo originale prima del parsing; la firma non deduplica e non autorizza un’azione ALORA.
|
|
132
|
+
|
|
133
|
+
`message.received` conserva il nome storico e può indicare anche un messaggio proprio: controllare sempre `direction` e `fromMe`. Il payload tipizzato `WhatsAppMessageEventPayload` include:
|
|
134
|
+
|
|
135
|
+
- `messageId`, `providerId`, `chatId`, `sessionId`, `messageSessionId`, `archiveId`;
|
|
136
|
+
- `direction` (`in`, `out`, `unknown`), `fromMe`, `senderId`, `recipientId`;
|
|
137
|
+
- `occurredAt`, `observedAt`, `timestampSource` (`provider`, `connect`, `unknown`), `source`, `addressingVerified`;
|
|
138
|
+
- `kind`, `body.text`, `body.selectedButtonId` e contenuti interattivi supportati; il corpo storico resta compatibile.
|
|
139
|
+
|
|
140
|
+
`sessionId` identifica la connessione che ha osservato l’evento; `messageSessionId` quella della prima archiviazione del messaggio. `archiveId` identifica il numero attraverso le riconnessioni. Callback di sessioni chiuse/estranee sono scartate. Un’origine o timestamp incompleto è esplicito e il consumer deve negare azioni automatiche se non verificabile.
|
|
141
|
+
|
|
142
|
+
La selezione normalizzata produce **`message.interactive_response`**, con una ricevuta durevole unica `(messageId, kind)` nella stessa transazione di messaggio/evento/consegne. Funziona anche se `message.received` aveva già deduplicato lo stesso provider ID; callback duplicate o contraddittorie non producono altre selezioni. Se la normalizzazione arriva per prima, vengono emessi i due eventi distinti. L’ordine di consegna non è garantito. Le ricevute degli eventi ordinari storici vengono adottate dalla migrazione senza alterare l’evento originale.
|
|
143
|
+
|
|
144
|
+
Il consumer deve persistere la deduplica per event ID, verificare installazione/sessione/archivio, verso in ingresso, mittente/destinatario, timestamp e correlazione del pulsante al proprio piano/revisione/scadenza. Per selezioni usare `message.interactive_response`; non applicare lo stesso comando anche da `message.received`. Il provider non conosce conto, agenda o appuntamento ALORA. I formati SDK `WhatsAppPayload.kind='interactive'`, pulsanti reply/list e `InteractiveResponse` esistenti sono riusati.
|
package/INTEGRATION.md
CHANGED
|
@@ -174,3 +174,18 @@ La facciata non risolve da sola DNS/TLS del deployment: issuer canonico, URL cat
|
|
|
174
174
|
L’issuer canonico resta quello approvato: URL di autorizzazione nel browser, confronto `iss`, audience, nonce e PKCE non vengono riscritti né disattivati. Un esempio Docker locale è issuer `http://localhost:8080/realms/eulab` e origine di trasporto `https://nginx`, con CA attendibile e relay privato verso il medesimo Keycloak. Non usare il parametro per collegare un provider diverso dall’issuer approvato.
|
|
175
175
|
|
|
176
176
|
Correzione del 24 ottobre adottata per il problema di raggiungibilità rilevato in ALORA dopo la migrazione. Compilazione/pacchetto aggiornati; il login end-to-end viene riprovato dall’utente, non è dichiarato collaudato da questa modifica.
|
|
177
|
+
|
|
178
|
+
## Candidata 0.11.0 — account squadra
|
|
179
|
+
|
|
180
|
+
La candidata aggiunge `application.team.createUser(sessionId, input)`, usando la stessa istanza e la sessione backend già approvata. L'input contiene il profilo locale persistito (`localUserId`, email, nome/cognome, ruolo operativo e permessi), i `roleIds` esplicitamente scelti e una password iniziale facoltativa. Sorgente e azienda locale derivano dalla configurazione/sessione; lo username è generato se omesso. Non aggiungere un signup parallelo o chiamate amministrative nel browser.
|
|
181
|
+
|
|
182
|
+
Richiede API Connect aggiornata, migrazione 014 e bootstrap degli attributi provider riservati. La creazione conserva le restrizioni di licenza/delega e non sostituisce revisioni o riattivazioni amministrative. Risultato tipizzato `ApplicationTeamUserResult`; errori `ConnectApiError` con `status` e `code`. I rifiuti di business conservano la sessione operatore; nessun reinvio automatico di password o mutazioni dopo esiti incerti. `ssoSetupRequired` segnala eventuali azioni provider ancora necessarie.
|
|
183
|
+
|
|
184
|
+
La distribuzione npm 0.10.0 non contiene questo metodo. Questa candidata non comporta pubblicazione automatica. Specifica completa ed evidenze nel repository Connect: `docs/DELEGATED-ACCOUNTS-STEP-5.md`.
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
## Automazioni appuntamenti — 0.12.0
|
|
188
|
+
|
|
189
|
+
Il contratto server aggiuntivo è in [AUTOMATIONS.md](./AUTOMATIONS.md): `ConnectServer.automations(token)` per consenso/recupero, `ConnectServer.automations()` per worker con credenziale delegata. Richiede schema 015 e API/runner aggiornati insieme. La facciata esistente `services(sessionId, callback)` permette l’autorizzazione iniziale senza esportare token al browser. Persisti grant e segreto webhook cifrati nel backend; al browser proietta soltanto stato, scadenza e motivo sicuro. Non usare refresh token UI per job differiti e non cambiare chiave dopo un esito incerto.
|
|
190
|
+
|
|
191
|
+
La versione 0.12.0 aggiunge `client.automations().withdraw(id, credential, originalInput, originalKey)`. Usa gli stessi dati/chiave di `send`, senza token browser. Una ricevuta `cancelled` preventiva impedisce il commit tardivo di un nuovo invio; `sending`/`sent`/`uncertain` producono `effect_started`, senza annullamento promesso o reinvio. Contratto e unione tipizzata `DelegatedMessageWithdrawal` in [AUTOMATIONS.md](./AUTOMATIONS.md#ritiro-del-singolo-comando-0120-rc2). Nessuna nuova migrazione oltre allo schema 015.
|
package/README.md
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
### Novità 0.12.0
|
|
2
|
+
|
|
3
|
+
- Prima versione stabile della linea 0.12 (contenuto della 0.12.0-rc.2 provata in ALORA).
|
|
4
|
+
- Client browser: le risposte non JSON dei proxy (502/503/504) diventano messaggi chiari invece di errori di parsing.
|
|
5
|
+
|
|
6
|
+
## Automazioni server 0.12.0
|
|
7
|
+
|
|
8
|
+
Delega revocabile, invio/stato e ritiro idempotente del singolo comando sulla stessa outbox, webhook recuperabili: [contratto API/SDK](./AUTOMATIONS.md). Richiede schema Connect 015; candidato locale, non pubblicato. Le credenziali restano nel backend; le API manuali e bot esistenti restano disponibili.
|
|
9
|
+
|
|
1
10
|
## Facciata applicativa 0.10.0
|
|
2
11
|
|
|
3
12
|
`@eulab/connect/application` esporta `ConnectApplication` e lo store PostgreSQL condiviso. Una sola istanza governa discovery, migrazione/attivazione, recupero password, OIDC/PKCE, cookie/handoff, sessioni cifrate e rinnovi concorrenti. I metodi 0.9.0 restano compatibili.
|
|
@@ -61,3 +70,7 @@ if (lookup.status === 'not_found') {
|
|
|
61
70
|
`loginContext` non autentica l’utente e restituisce un contesto solo per collegamenti espliciti autorizzati alla sorgente. `submit` accetta `Idempotency-Key` stabili: la stessa chiave con lo stesso body restituisce la pratica esistente, con un body diverso produce un errore 409 e non sostituisce la credenziale. `ConnectOnboardingError.status` conserva il codice HTTP (401/403/409/...) per la gestione consumer. La password transitoria non viene mai restituita, registrata o inclusa nei tipi di risposta.
|
|
62
71
|
|
|
63
72
|
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.
|
|
73
|
+
|
|
74
|
+
### Candidata 0.11.0: creazione account delegata
|
|
75
|
+
|
|
76
|
+
La facciata server espone `application.team.createUser(sessionId, {localUser, roleIds, initialPassword?})`. Il consumer fornisce un profilo con ID locale già persistito; lo SDK ricava sorgente/azienda dalla sessione e configura il mirror completo senza esporre credenziali nel browser. Servono API aggiornata, migrazione 014, bootstrap provider e `team.manage` effettivo. Errori di business tipizzati conservano la sessione; esiti incerti richiedono verifica e azione esplicita sullo stesso ID. Vedi `INTEGRATION.md` e la consegna `docs/DELEGATED-ACCOUNTS-STEP-5.md` nel repository. Il metodo non è disponibile nella distribuzione 0.10.0.
|
package/dist/application.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { ConnectOnboardingSource, ConnectServer } from './server.js';
|
|
2
|
+
import type { ApplicationTeamUserInput, ApplicationTeamUserResult } from './server.js';
|
|
3
|
+
export { ConnectApiError } from './server.js';
|
|
4
|
+
export type { ApplicationTeamUserInput, ApplicationTeamUserResult } from './server.js';
|
|
2
5
|
import type { AuthorizedConnectContext, OnboardingRequestStatus, AppOnboardingActivationRequest, OnboardingNextAction, DeploymentMetadata } from './server.js';
|
|
3
6
|
import type { FunctionMatrix } from './functions.js';
|
|
4
7
|
import type { ConnectApplicationStore, ConnectStoreTransaction } from './application-store.js';
|
|
@@ -208,5 +211,8 @@ export declare class ConnectApplication {
|
|
|
208
211
|
};
|
|
209
212
|
/** All existing Connect services share this authenticated server session. No callback is retried. */
|
|
210
213
|
services<T>(sessionId: string, operation: (client: ConnectServer, accessToken: string) => Promise<T>): Promise<T>;
|
|
214
|
+
readonly team: {
|
|
215
|
+
createUser: (sessionId: string, input: ApplicationTeamUserInput) => Promise<ApplicationTeamUserResult>;
|
|
216
|
+
};
|
|
211
217
|
diagnose(email?: string): Promise<ConnectDiagnosticReport>;
|
|
212
218
|
}
|
package/dist/application.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes, createCipheriv, createDecipheriv, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { createRemoteJWKSet, jwtVerify } from 'jose';
|
|
3
|
-
import { ConnectOnboardingSource, ConnectOnboardingError, ConnectServer } from './server.js';
|
|
3
|
+
import { ConnectOnboardingSource, ConnectOnboardingError, ConnectServer, ConnectApiError } from './server.js';
|
|
4
|
+
export { ConnectApiError } from './server.js';
|
|
4
5
|
export * from './application-store.js';
|
|
5
6
|
export const connectConsentVersion = '2026-10-21-mandatory-v1';
|
|
6
7
|
export class ConnectApplicationError extends Error {
|
|
@@ -138,7 +139,7 @@ export class ConnectApplication {
|
|
|
138
139
|
}
|
|
139
140
|
catch (e) {
|
|
140
141
|
if (e instanceof ConnectOnboardingError)
|
|
141
|
-
fail(e.status === 409 ? 'invalid_context' : e.status >= 500 || e.status === 0 ? 'provider_unavailable' : 'access_denied');
|
|
142
|
+
fail(e.status === 409 ? 'invalid_context' : e.status >= 500 || e.status === 429 || e.status === 0 ? 'provider_unavailable' : 'access_denied');
|
|
142
143
|
return fail('provider_unavailable');
|
|
143
144
|
} }
|
|
144
145
|
async current(email, expected) {
|
|
@@ -156,8 +157,8 @@ export class ConnectApplication {
|
|
|
156
157
|
a = await this.client(context).permissions(token);
|
|
157
158
|
}
|
|
158
159
|
catch (cause) {
|
|
159
|
-
const
|
|
160
|
-
const
|
|
160
|
+
const status = cause instanceof ConnectApiError ? String(cause.status) : cause instanceof Error ? cause.message.match(/^Connect (\d{3}):/)?.[1] : undefined;
|
|
161
|
+
const error = new ConnectApplicationError(!status || status === '429' || Number(status) >= 500 ? 'provider_unavailable' : 'access_denied');
|
|
161
162
|
error.authorizationDetail = status === '401' ? 'http_401' : status === '403' ? 'http_403' : status ? 'http_other' : 'transport';
|
|
162
163
|
throw error;
|
|
163
164
|
}
|
|
@@ -314,6 +315,7 @@ export class ConnectApplication {
|
|
|
314
315
|
const s = await this.read(tx, id);
|
|
315
316
|
if (!s || s.expiresAt <= Date.now())
|
|
316
317
|
return { error: 'session_expired' };
|
|
318
|
+
let rotatingGrantStarted = false;
|
|
317
319
|
try {
|
|
318
320
|
const intentId = 'refresh:' + digest(sessionId + ':' + s.generation);
|
|
319
321
|
const interrupted = await tx.get(intentId);
|
|
@@ -326,23 +328,39 @@ export class ConnectApplication {
|
|
|
326
328
|
// The intent survives a crash/rollback and is checked on every session use.
|
|
327
329
|
await this.put(tx, intentId, { pending: true }, this.ttl);
|
|
328
330
|
await tx.checkpoint();
|
|
331
|
+
rotatingGrantStarted = true;
|
|
329
332
|
s.tokens = await this.grant({ grant_type: 'refresh_token', refresh_token: s.tokens.refresh_token });
|
|
330
333
|
s.refreshedAt = Date.now();
|
|
331
334
|
s.generation = opaque();
|
|
332
335
|
// The new generation supersedes the durable intent only on commit.
|
|
333
336
|
}
|
|
334
337
|
await this.verifyAccess(s.context, s.tokens.access_token);
|
|
338
|
+
}
|
|
339
|
+
catch (e) {
|
|
340
|
+
// Deny this request without destroying a valid session for a transient read failure.
|
|
341
|
+
// After a rotating grant starts, retain the existing fail-closed invalidation.
|
|
342
|
+
if (!(e instanceof ConnectApplicationError && e.code === 'provider_unavailable' && !rotatingGrantStarted))
|
|
343
|
+
await tx.remove(id);
|
|
344
|
+
return { error: e instanceof ConnectApplicationError ? e.code : 'access_denied' };
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
335
347
|
const value = await fn(s);
|
|
336
348
|
await tx.put(id, this.seal(id, s), s.expiresAt);
|
|
337
349
|
return { value };
|
|
338
350
|
}
|
|
339
|
-
catch (
|
|
340
|
-
|
|
341
|
-
|
|
351
|
+
catch (error) {
|
|
352
|
+
if (error instanceof ConnectApiError && error.status === 401) {
|
|
353
|
+
await tx.remove(id);
|
|
354
|
+
return { error: 'session_expired' };
|
|
355
|
+
}
|
|
356
|
+
await tx.put(id, this.seal(id, s), s.expiresAt);
|
|
357
|
+
return { operationError: error };
|
|
342
358
|
}
|
|
343
359
|
});
|
|
344
360
|
if ('error' in result)
|
|
345
361
|
return fail(result.error);
|
|
362
|
+
if ('operationError' in result)
|
|
363
|
+
throw result.operationError;
|
|
346
364
|
// Old intents expire with their session; no unsafe cleanup race between processes.
|
|
347
365
|
return result.value;
|
|
348
366
|
}
|
|
@@ -380,6 +398,14 @@ export class ConnectApplication {
|
|
|
380
398
|
}) };
|
|
381
399
|
/** All existing Connect services share this authenticated server session. No callback is retried. */
|
|
382
400
|
async services(sessionId, operation) { return this.withSession(sessionId, false, s => operation(this.client(s.context), s.tokens.access_token)); }
|
|
401
|
+
team = { createUser: async (sessionId, input) => this.withSession(sessionId, false, s => {
|
|
402
|
+
const u = input.localUser;
|
|
403
|
+
return this.client(s.context).mirrorApplicationUser(s.tokens.access_token, {
|
|
404
|
+
localUserId: u.localUserId, username: u.username || 'app-' + digest(JSON.stringify([this.config.sourceId, s.context.binding.installationId, u.localUserId])).slice(0, 40), email: u.email, displayName: [u.firstName, u.lastName].join(' '),
|
|
405
|
+
...(input.initialPassword === undefined ? {} : { initialPassword: input.initialPassword, ...(input.initialPasswordTemporary === undefined ? {} : { initialPasswordTemporary: input.initialPasswordTemporary }) }),
|
|
406
|
+
application: { sourceId: this.config.sourceId, localTenantId: s.context.tenant.id, firstName: u.firstName, lastName: u.lastName, role: u.role, permissions: u.permissions, roleIds: input.roleIds }
|
|
407
|
+
});
|
|
408
|
+
}) };
|
|
383
409
|
async diagnose(email) {
|
|
384
410
|
const checks = [{ code: 'configuration', status: 'ok' }];
|
|
385
411
|
const sso = await this.loadSettings();
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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,47 @@ 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
|
+
}
|
|
26
69
|
export type OnboardingRequestState = 'pending' | 'approved' | 'migrating' | 'completed' | 'rejected' | 'expired' | 'failed';
|
|
27
70
|
export type OnboardingNextAction = 'wait' | 'sign_in' | 'choose_connect_password' | 'resubmit' | 'contact_admin' | 'closed';
|
|
28
71
|
export interface OnboardingRequestStatus {
|
|
@@ -245,6 +288,21 @@ export declare class ConnectServer {
|
|
|
245
288
|
state: "available" | "queued";
|
|
246
289
|
}>;
|
|
247
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
|
+
};
|
|
248
306
|
registerFunctions(url?: string): Promise<any>;
|
|
249
307
|
/**
|
|
250
308
|
* Crea o recupera l'identità centrale collegata all'utente locale.
|
|
@@ -254,7 +312,11 @@ export declare class ConnectServer {
|
|
|
254
312
|
* Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
|
|
255
313
|
* Le chiamate esistenti senza il campo mantengono il comportamento precedente.
|
|
256
314
|
*/
|
|
315
|
+
requestTeamPasswordReset(accessToken: string, subject: string): Promise<{
|
|
316
|
+
requested: true;
|
|
317
|
+
}>;
|
|
257
318
|
mirrorUser(user: LocalUserProfile): Promise<MirroredUser>;
|
|
319
|
+
mirrorApplicationUser(accessToken: string, user: ApplicationMirrorInput): Promise<ApplicationTeamUserResult>;
|
|
258
320
|
teamOverview(accessToken: string): Promise<TeamOverview>;
|
|
259
321
|
teamUsers(accessToken: string): Promise<TeamUser[]>;
|
|
260
322
|
teamRoles(accessToken: string): Promise<TeamRole[]>;
|
package/dist/server.js
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
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
|
+
}
|
|
5
17
|
/** Errore del contratto sorgente: lo stato HTTP resta disponibile al chiamante. */
|
|
6
18
|
export class ConnectOnboardingError extends Error {
|
|
7
19
|
status;
|
|
@@ -75,7 +87,7 @@ export class ConnectServer {
|
|
|
75
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) });
|
|
76
88
|
const result = await response.json();
|
|
77
89
|
if (!response.ok)
|
|
78
|
-
throw new
|
|
90
|
+
throw new ConnectApiError(response.status, result);
|
|
79
91
|
return result;
|
|
80
92
|
}
|
|
81
93
|
functionUrl(feature, path) {
|
|
@@ -88,6 +100,8 @@ export class ConnectServer {
|
|
|
88
100
|
}
|
|
89
101
|
authorize(accessToken, permission) { return this.request('/v1/authorize', 'POST', { installationId: this.config.installationId, permission }, accessToken); }
|
|
90
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); }
|
|
91
105
|
registerFunctions(url) { const source = url || this.config.catalogUrl || (this.config.domain ? this.config.domain + (this.config.basePath || '') + functionCatalogPath : undefined); if (!source)
|
|
92
106
|
throw new Error('URL funzioni o dominio richiesto'); return this.request('/v1/catalog-source', 'POST', { url: source }); }
|
|
93
107
|
/**
|
|
@@ -98,7 +112,18 @@ export class ConnectServer {
|
|
|
98
112
|
* Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
|
|
99
113
|
* Le chiamate esistenti senza il campo mantengono il comportamento precedente.
|
|
100
114
|
*/
|
|
115
|
+
requestTeamPasswordReset(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/password-reset', 'POST', {}, accessToken); }
|
|
101
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
|
+
}
|
|
102
127
|
teamOverview(accessToken) { return this.request('/v1/team', 'GET', undefined, accessToken); }
|
|
103
128
|
teamUsers(accessToken) { return this.request('/v1/team/users', 'GET', undefined, accessToken); }
|
|
104
129
|
teamRoles(accessToken) { return this.request('/v1/team/roles', 'GET', undefined, accessToken); }
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
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
4
|
|
|
5
|
-
1. Estrarre il tarball SDK e copiare questa cartella fuori dal repository. Installare con `npm install @eulab/connect@/percorso/eulab-connect-0.
|
|
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
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
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
8
|
4. `npm run check` controlla discovery e sorgente, senza scritture. `npm start`, aprire `http://127.0.0.1:55179`.
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
"type":"module",
|
|
5
5
|
"engines":{"node":">=22"},
|
|
6
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.
|
|
7
|
+
"dependencies":{"@eulab/connect":"file:../../eulab-connect-0.11.0.tgz","pg":"8.23.0"}
|
|
8
8
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eulab/connect",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "SDK EULab Connect per browser e server: SSO, permessi e WhatsApp",
|
|
5
5
|
"author": "EULAB",
|
|
6
6
|
"type": "module",
|
|
@@ -34,9 +34,15 @@
|
|
|
34
34
|
"!dist/**/*.map",
|
|
35
35
|
"examples",
|
|
36
36
|
"migrations",
|
|
37
|
-
"INTEGRATION.md"
|
|
37
|
+
"INTEGRATION.md",
|
|
38
|
+
"AUTOMATIONS.md"
|
|
38
39
|
],
|
|
39
40
|
"dependencies": {
|
|
40
41
|
"jose": "^6.2.12"
|
|
42
|
+
},
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/Eulab-EugenioRenna/connect.git",
|
|
46
|
+
"directory": "packages/sdk"
|
|
41
47
|
}
|
|
42
48
|
}
|