@eulab/connect 0.0.0-stage → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/dist/bot.d.ts +81 -0
- package/dist/bot.js +1 -0
- package/dist/browser.d.ts +245 -0
- package/dist/browser.js +291 -0
- package/dist/functions.d.ts +92 -0
- package/dist/functions.js +8 -0
- package/dist/interactive.d.ts +121 -0
- package/dist/interactive.js +1 -0
- package/dist/realtime.d.ts +44 -0
- package/dist/realtime.js +96 -0
- package/dist/server.d.ts +163 -0
- package/dist/server.js +72 -0
- package/dist/whatsapp.d.ts +150 -0
- package/dist/whatsapp.js +44 -0
- package/package.json +19 -4
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
export declare const functionCatalogPath = "/.well-known/eulab-connect.json";
|
|
2
|
+
export interface AppFunction {
|
|
3
|
+
key: string;
|
|
4
|
+
name: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface FunctionMatrix {
|
|
8
|
+
schemaVersion: 1;
|
|
9
|
+
appId: string;
|
|
10
|
+
version: number;
|
|
11
|
+
functions: AppFunction[];
|
|
12
|
+
}
|
|
13
|
+
export interface AccessResult {
|
|
14
|
+
installationId: string;
|
|
15
|
+
appId: string | null;
|
|
16
|
+
subject: string | null;
|
|
17
|
+
localUserId: string | null;
|
|
18
|
+
canLogin: boolean;
|
|
19
|
+
reason: string;
|
|
20
|
+
functions: AppFunction[];
|
|
21
|
+
catalogVersion: number;
|
|
22
|
+
functionsStatus: 'pending' | 'last_valid' | 'ready';
|
|
23
|
+
}
|
|
24
|
+
export interface ConnectUser {
|
|
25
|
+
subject: string;
|
|
26
|
+
localUserId: string;
|
|
27
|
+
displayName: string;
|
|
28
|
+
roles: {
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
}[];
|
|
32
|
+
}
|
|
33
|
+
export interface TeamFunction {
|
|
34
|
+
key: string;
|
|
35
|
+
name: string;
|
|
36
|
+
delegable: boolean;
|
|
37
|
+
}
|
|
38
|
+
export interface TeamRole {
|
|
39
|
+
id: string;
|
|
40
|
+
name: string;
|
|
41
|
+
permissions: string[];
|
|
42
|
+
}
|
|
43
|
+
export interface TeamUser {
|
|
44
|
+
subject: string;
|
|
45
|
+
localUserId: string;
|
|
46
|
+
displayName: string;
|
|
47
|
+
identityEnabled: boolean;
|
|
48
|
+
membershipEnabled: boolean;
|
|
49
|
+
accessRevoked: boolean;
|
|
50
|
+
roles: {
|
|
51
|
+
id: string;
|
|
52
|
+
name: string;
|
|
53
|
+
}[];
|
|
54
|
+
}
|
|
55
|
+
export interface TeamOverview {
|
|
56
|
+
installationId: string;
|
|
57
|
+
customerId: string;
|
|
58
|
+
appId: string;
|
|
59
|
+
canManage: boolean;
|
|
60
|
+
functions: TeamFunction[];
|
|
61
|
+
delegation: {
|
|
62
|
+
key: string;
|
|
63
|
+
name: string;
|
|
64
|
+
}[];
|
|
65
|
+
roles: TeamRole[];
|
|
66
|
+
users: TeamUser[];
|
|
67
|
+
}
|
|
68
|
+
export interface TeamRoleInput {
|
|
69
|
+
name: string;
|
|
70
|
+
permissions: string[];
|
|
71
|
+
}
|
|
72
|
+
export interface TeamUserAssignment {
|
|
73
|
+
subject: string;
|
|
74
|
+
localUserId: string;
|
|
75
|
+
roleIds: string[];
|
|
76
|
+
accessRestored: boolean;
|
|
77
|
+
}
|
|
78
|
+
export interface TeamRevocation {
|
|
79
|
+
revoked: boolean;
|
|
80
|
+
subject: string;
|
|
81
|
+
localUserId: string;
|
|
82
|
+
identityPreserved: boolean;
|
|
83
|
+
membershipPreserved: boolean;
|
|
84
|
+
otherApplicationsPreserved: boolean;
|
|
85
|
+
}
|
|
86
|
+
export interface TeamRestore {
|
|
87
|
+
restored: boolean;
|
|
88
|
+
subject: string;
|
|
89
|
+
localUserId: string;
|
|
90
|
+
}
|
|
91
|
+
export declare function defineFunctions(input: Omit<FunctionMatrix, 'schemaVersion'>): FunctionMatrix;
|
|
92
|
+
export declare function functionsResponse(matrix: FunctionMatrix): Response;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const functionCatalogPath = '/.well-known/eulab-connect.json';
|
|
2
|
+
export function defineFunctions(input) {
|
|
3
|
+
const validKey = (key) => /^[a-z][a-z0-9_.:-]{0,79}$/.test(key);
|
|
4
|
+
if (!validKey(input.appId) || !Number.isSafeInteger(input.version) || input.version < 1 || input.functions.length > 200 || new Set(input.functions.map(f => f.key)).size !== input.functions.length || input.functions.some(f => !validKey(f.key) || !f.name.trim() || f.name.length > 200 || (f.description?.length || 0) > 1000))
|
|
5
|
+
throw new Error('Matrice funzioni non valida');
|
|
6
|
+
return { schemaVersion: 1, appId: input.appId, version: input.version, functions: input.functions.map(f => ({ ...f })) };
|
|
7
|
+
}
|
|
8
|
+
export function functionsResponse(matrix) { return Response.json(defineFunctions(matrix), { headers: { 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' } }); }
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
export type InteractiveAction = {
|
|
2
|
+
type: 'reply';
|
|
3
|
+
id: string;
|
|
4
|
+
label: string;
|
|
5
|
+
} | {
|
|
6
|
+
type: 'url';
|
|
7
|
+
label: string;
|
|
8
|
+
url: string;
|
|
9
|
+
} | {
|
|
10
|
+
type: 'call';
|
|
11
|
+
label: string;
|
|
12
|
+
phoneNumber: string;
|
|
13
|
+
} | {
|
|
14
|
+
type: 'copy';
|
|
15
|
+
label: string;
|
|
16
|
+
code: string;
|
|
17
|
+
};
|
|
18
|
+
/** Portable documents forwarded to OpenWAUnlocked.sendInteractive. */
|
|
19
|
+
export type InteractiveContent = {
|
|
20
|
+
type: 'buttons';
|
|
21
|
+
body: string;
|
|
22
|
+
footer?: string;
|
|
23
|
+
header?: {
|
|
24
|
+
type: 'text';
|
|
25
|
+
text: string;
|
|
26
|
+
};
|
|
27
|
+
actions: InteractiveAction[];
|
|
28
|
+
} | {
|
|
29
|
+
type: 'list';
|
|
30
|
+
body: string;
|
|
31
|
+
footer?: string;
|
|
32
|
+
title?: string;
|
|
33
|
+
buttonLabel: string;
|
|
34
|
+
sections: {
|
|
35
|
+
title?: string;
|
|
36
|
+
rows: {
|
|
37
|
+
id: string;
|
|
38
|
+
title: string;
|
|
39
|
+
description?: string;
|
|
40
|
+
}[];
|
|
41
|
+
}[];
|
|
42
|
+
};
|
|
43
|
+
export interface InteractiveResponse {
|
|
44
|
+
messageId: string;
|
|
45
|
+
chatId: string;
|
|
46
|
+
senderId: string;
|
|
47
|
+
type: 'reply' | 'list';
|
|
48
|
+
id: string;
|
|
49
|
+
label?: string;
|
|
50
|
+
timestamp?: number;
|
|
51
|
+
}
|
|
52
|
+
export interface CallIdentity {
|
|
53
|
+
id: string;
|
|
54
|
+
sessionId: string;
|
|
55
|
+
generation: string;
|
|
56
|
+
}
|
|
57
|
+
export interface CallSnapshot extends CallIdentity {
|
|
58
|
+
peer: string;
|
|
59
|
+
state: string;
|
|
60
|
+
direction: 'incoming' | 'outgoing';
|
|
61
|
+
video: boolean;
|
|
62
|
+
terminal: boolean;
|
|
63
|
+
observedAt: number;
|
|
64
|
+
}
|
|
65
|
+
export interface CallCapabilities {
|
|
66
|
+
control: boolean;
|
|
67
|
+
audio: boolean;
|
|
68
|
+
video: boolean;
|
|
69
|
+
reason?: {
|
|
70
|
+
code: string;
|
|
71
|
+
message: string;
|
|
72
|
+
status: number;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export type CallActionResult = {
|
|
76
|
+
ok: true;
|
|
77
|
+
status: 'requested';
|
|
78
|
+
callId?: string;
|
|
79
|
+
} | {
|
|
80
|
+
ok: false;
|
|
81
|
+
status: 'unavailable' | 'failed' | 'unknown';
|
|
82
|
+
reason: {
|
|
83
|
+
code: string;
|
|
84
|
+
message: string;
|
|
85
|
+
status: number;
|
|
86
|
+
};
|
|
87
|
+
callId?: string;
|
|
88
|
+
};
|
|
89
|
+
export type ProviderCommand = {
|
|
90
|
+
kind: 'contact.refresh';
|
|
91
|
+
chatId: string;
|
|
92
|
+
} | {
|
|
93
|
+
kind: 'call.inspect';
|
|
94
|
+
} | {
|
|
95
|
+
kind: 'call.start';
|
|
96
|
+
to: string;
|
|
97
|
+
} | {
|
|
98
|
+
kind: 'call.accept' | 'call.reject' | 'call.end';
|
|
99
|
+
call: CallIdentity;
|
|
100
|
+
} | {
|
|
101
|
+
kind: 'call.mute';
|
|
102
|
+
call: CallIdentity;
|
|
103
|
+
muted: boolean;
|
|
104
|
+
};
|
|
105
|
+
export interface ProviderOperation<T = unknown> {
|
|
106
|
+
id: string;
|
|
107
|
+
state: 'queued' | 'running' | 'completed' | 'cancelled' | 'uncertain';
|
|
108
|
+
command: ProviderCommand;
|
|
109
|
+
result: T | null;
|
|
110
|
+
error: string | null;
|
|
111
|
+
created_at: string;
|
|
112
|
+
}
|
|
113
|
+
export interface ConversationContact {
|
|
114
|
+
name: string | null;
|
|
115
|
+
pushName: string | null;
|
|
116
|
+
description: string | null;
|
|
117
|
+
avatar: string | null;
|
|
118
|
+
isBusiness: boolean;
|
|
119
|
+
isGroup: boolean;
|
|
120
|
+
updatedAt?: string;
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Request, WhatsAppSession } from './whatsapp.js';
|
|
2
|
+
export interface WhatsAppRealtimeEvent {
|
|
3
|
+
id: string;
|
|
4
|
+
session_id: string;
|
|
5
|
+
kind: string;
|
|
6
|
+
created_at: string;
|
|
7
|
+
payload: Record<string, any>;
|
|
8
|
+
}
|
|
9
|
+
export interface WhatsAppSnapshot {
|
|
10
|
+
sessions: (WhatsAppSession & {
|
|
11
|
+
qr: string | null;
|
|
12
|
+
})[];
|
|
13
|
+
outbox: {
|
|
14
|
+
id: string;
|
|
15
|
+
session_id: string;
|
|
16
|
+
state: string;
|
|
17
|
+
provider_id: string | null;
|
|
18
|
+
error: string | null;
|
|
19
|
+
created_at: string;
|
|
20
|
+
}[];
|
|
21
|
+
bots: {
|
|
22
|
+
archive_id: string;
|
|
23
|
+
revision: number;
|
|
24
|
+
enabled: boolean;
|
|
25
|
+
}[];
|
|
26
|
+
}
|
|
27
|
+
export type WhatsAppRealtimeStatus = 'connecting' | 'connected' | 'reconnecting' | 'closed' | 'unauthorized' | 'error';
|
|
28
|
+
export interface WhatsAppSubscribeOptions {
|
|
29
|
+
onEvent?: (event: WhatsAppRealtimeEvent) => void;
|
|
30
|
+
onSnapshot?: (snapshot: WhatsAppSnapshot) => void;
|
|
31
|
+
onStatus?: (status: WhatsAppRealtimeStatus) => void;
|
|
32
|
+
onError?: (error: Error) => void;
|
|
33
|
+
reconnect?: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface WhatsAppSubscription {
|
|
36
|
+
close(): void;
|
|
37
|
+
readonly status: WhatsAppRealtimeStatus;
|
|
38
|
+
}
|
|
39
|
+
export interface RealtimeConfig {
|
|
40
|
+
apiUrl: string;
|
|
41
|
+
register?: (close: () => void) => () => void;
|
|
42
|
+
}
|
|
43
|
+
/** Receive only: reconnecting this stream never replays an outbound message. */
|
|
44
|
+
export declare function subscribeWhatsApp(request: Request, root: string, config: RealtimeConfig, options: WhatsAppSubscribeOptions): WhatsAppSubscription;
|
package/dist/realtime.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Receive only: reconnecting this stream never replays an outbound message. */
|
|
2
|
+
export function subscribeWhatsApp(request, root, config, options) {
|
|
3
|
+
let stopped = false, socket, timer, attempt = 0, status = 'connecting';
|
|
4
|
+
const seen = new Set();
|
|
5
|
+
let unregister;
|
|
6
|
+
function call(fn, value) { try {
|
|
7
|
+
fn?.(value);
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
try {
|
|
11
|
+
options.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
12
|
+
}
|
|
13
|
+
catch { }
|
|
14
|
+
} }
|
|
15
|
+
function setStatus(value) { status = value; call(options.onStatus, value); }
|
|
16
|
+
function finish(value) { if (stopped)
|
|
17
|
+
return; stopped = true; clearTimeout(timer); socket?.close(); unregister?.(); setStatus(value); }
|
|
18
|
+
function retry() {
|
|
19
|
+
if (stopped)
|
|
20
|
+
return;
|
|
21
|
+
if (options.reconnect === false || attempt >= 8) {
|
|
22
|
+
finish('error');
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
setStatus('reconnecting');
|
|
26
|
+
timer = setTimeout(() => void connect(), Math.min(1000 * 2 ** attempt++, 15000));
|
|
27
|
+
}
|
|
28
|
+
async function connect() {
|
|
29
|
+
if (stopped)
|
|
30
|
+
return;
|
|
31
|
+
let opened;
|
|
32
|
+
try {
|
|
33
|
+
const ticket = await request(root + '/events/ticket', 'POST');
|
|
34
|
+
if (stopped)
|
|
35
|
+
return;
|
|
36
|
+
if (ticket.path !== '/v1/whatsapp/events')
|
|
37
|
+
throw new Error('Endpoint realtime non valido');
|
|
38
|
+
const url = new URL(config.apiUrl + ticket.path, typeof location === 'undefined' ? undefined : location.origin);
|
|
39
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
40
|
+
throw new Error('URL API HTTP(S) richiesto');
|
|
41
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
42
|
+
socket = opened = new WebSocket(url);
|
|
43
|
+
let authTimer = setTimeout(() => opened.close(), 10000);
|
|
44
|
+
opened.onopen = () => { if (stopped) {
|
|
45
|
+
opened.close();
|
|
46
|
+
return;
|
|
47
|
+
} opened.send(JSON.stringify({ type: 'authenticate', ticket: ticket.ticket })); };
|
|
48
|
+
opened.onmessage = message => {
|
|
49
|
+
if (stopped || socket !== opened || typeof message.data !== 'string')
|
|
50
|
+
return;
|
|
51
|
+
let frame;
|
|
52
|
+
try {
|
|
53
|
+
frame = JSON.parse(message.data);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (frame.type === 'ready') {
|
|
59
|
+
clearTimeout(authTimer);
|
|
60
|
+
attempt = 0;
|
|
61
|
+
setStatus('connected');
|
|
62
|
+
}
|
|
63
|
+
else if (frame.type === 'snapshot' && Array.isArray(frame.sessions) && Array.isArray(frame.outbox) && Array.isArray(frame.bots))
|
|
64
|
+
call(options.onSnapshot, { sessions: frame.sessions, outbox: frame.outbox, bots: frame.bots });
|
|
65
|
+
else if (frame.type === 'event' && typeof frame.event?.id === 'string' && typeof frame.event?.kind === 'string') {
|
|
66
|
+
if (seen.has(frame.event.id))
|
|
67
|
+
return;
|
|
68
|
+
seen.add(frame.event.id);
|
|
69
|
+
if (seen.size > 5000)
|
|
70
|
+
seen.delete(seen.values().next().value);
|
|
71
|
+
call(options.onEvent, frame.event);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
opened.onerror = () => { call(options.onError, new Error('Connessione realtime non disponibile')); };
|
|
75
|
+
opened.onclose = event => { clearTimeout(authTimer); if (stopped || socket !== opened)
|
|
76
|
+
return; if (event.code === 4003) {
|
|
77
|
+
finish('unauthorized');
|
|
78
|
+
return;
|
|
79
|
+
} retry(); };
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (stopped)
|
|
83
|
+
return;
|
|
84
|
+
call(options.onError, error instanceof Error ? error : new Error(String(error)));
|
|
85
|
+
if ([401, 403].includes(error?.status || 0) || /401|403|Accedi|scaduta|revocata|session_expired/.test(String(error)))
|
|
86
|
+
finish('unauthorized');
|
|
87
|
+
else
|
|
88
|
+
retry();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const handle = { close: () => finish('closed'), get status() { return status; } };
|
|
92
|
+
unregister = config.register?.(handle.close);
|
|
93
|
+
setStatus('connecting');
|
|
94
|
+
void connect();
|
|
95
|
+
return handle;
|
|
96
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
export type { InteractiveAction, InteractiveContent, InteractiveResponse, ProviderCommand, ProviderOperation, ConversationContact, CallIdentity, CallSnapshot, CallCapabilities, CallActionResult } from './interactive.js';
|
|
2
|
+
export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js';
|
|
3
|
+
export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
|
|
4
|
+
export type { WhatsAppBotDefinition, WhatsAppBotNode, WhatsAppBotState, WhatsAppBotTurn, WhatsAppBot } from './bot.js';
|
|
5
|
+
export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
|
|
6
|
+
export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser, TeamFunction, TeamRole, TeamUser, TeamOverview, TeamRoleInput, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
|
|
7
|
+
import type { AccessResult, ConnectUser, TeamFunction, TeamOverview, TeamRole, TeamRoleInput, TeamUser, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
|
|
8
|
+
export type { WhatsAppSession, WhatsAppArchive, Conversation, WhatsAppMessage, WhatsAppPayload } from './whatsapp.js';
|
|
9
|
+
export interface LocalUserProfile {
|
|
10
|
+
localUserId: string;
|
|
11
|
+
username: string;
|
|
12
|
+
email: string;
|
|
13
|
+
displayName: string;
|
|
14
|
+
initialPassword?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface MirroredUser {
|
|
17
|
+
installationId: string;
|
|
18
|
+
customerId: string;
|
|
19
|
+
localUserId: string;
|
|
20
|
+
subject: string;
|
|
21
|
+
username?: string;
|
|
22
|
+
created: boolean;
|
|
23
|
+
status: 'created' | 'already_linked' | 'recovered';
|
|
24
|
+
ssoSetupRequired: boolean | null;
|
|
25
|
+
}
|
|
26
|
+
export declare class ConnectServer {
|
|
27
|
+
private readonly config;
|
|
28
|
+
constructor(config: {
|
|
29
|
+
apiUrl: string;
|
|
30
|
+
installationId: string;
|
|
31
|
+
secret: string;
|
|
32
|
+
domain?: string;
|
|
33
|
+
functionFallbackUrl?: string;
|
|
34
|
+
catalogUrl?: string;
|
|
35
|
+
basePath?: string;
|
|
36
|
+
});
|
|
37
|
+
request<T = any>(path: string, method?: string, body?: unknown, accessToken?: string, extra?: Record<string, string>): Promise<T>;
|
|
38
|
+
functionUrl(feature: string, path?: string): string;
|
|
39
|
+
authorize(accessToken: string, permission: string): Promise<{
|
|
40
|
+
allowed: boolean;
|
|
41
|
+
reason: string;
|
|
42
|
+
}>;
|
|
43
|
+
whatsapp(accessToken: string | (() => Promise<string>)): {
|
|
44
|
+
subscribe: (options: import("./realtime.js").WhatsAppSubscribeOptions) => import("./realtime.js").WhatsAppSubscription;
|
|
45
|
+
bot: {
|
|
46
|
+
get: (archiveId: string) => Promise<import("./bot.js").WhatsAppBot>;
|
|
47
|
+
configure: (archiveId: string, definition: import("./bot.js").WhatsAppBotDefinition, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
|
|
48
|
+
activate: (archiveId: string, enabled: boolean, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
|
|
49
|
+
preview: (definition: import("./bot.js").WhatsAppBotDefinition, input: string | import("./bot.js").IVRInput, state?: import("./bot.js").WhatsAppBotState | null, channel?: import("./bot.js").IVRChannel) => Promise<import("./bot.js").WhatsAppBotTurn & {
|
|
50
|
+
sent: false;
|
|
51
|
+
}>;
|
|
52
|
+
};
|
|
53
|
+
ivr: {
|
|
54
|
+
get: (archiveId: string, id: string) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
55
|
+
start: (archiveId: string, callId: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
56
|
+
advance: (archiveId: string, id: string, input: import("./bot.js").IVRInput, expectedTurn: number, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
57
|
+
};
|
|
58
|
+
operations: {
|
|
59
|
+
get: <T = unknown>(id: string) => Promise<import("./interactive.js").ProviderOperation<T>>;
|
|
60
|
+
list: () => Promise<import("./interactive.js").ProviderOperation<unknown>[]>;
|
|
61
|
+
submit: (id: string, command: import("./interactive.js").ProviderCommand, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<unknown>>;
|
|
62
|
+
};
|
|
63
|
+
calls: {
|
|
64
|
+
inspect: (id: string) => Promise<import("./interactive.js").ProviderOperation<{
|
|
65
|
+
capabilities: import("./interactive.js").CallCapabilities;
|
|
66
|
+
active: import("./interactive.js").CallSnapshot | null;
|
|
67
|
+
}>>;
|
|
68
|
+
start: (id: string, to: string, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
|
|
69
|
+
control: (id: string, action: "accept" | "reject" | "end" | "mute", call: import("./interactive.js").CallIdentity, muted?: boolean, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
|
|
70
|
+
};
|
|
71
|
+
refreshContact: (id: string, chatId: string) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").ConversationContact>>;
|
|
72
|
+
sessions: () => Promise<import("./whatsapp.js").WhatsAppSession[]>;
|
|
73
|
+
connect: () => Promise<{
|
|
74
|
+
id: string;
|
|
75
|
+
state: string;
|
|
76
|
+
}>;
|
|
77
|
+
qr: (id: string) => Promise<{
|
|
78
|
+
state: string;
|
|
79
|
+
qr: string | null;
|
|
80
|
+
}>;
|
|
81
|
+
send: (id: string, payload: import("./whatsapp.js").WhatsAppPayload, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
82
|
+
id: string;
|
|
83
|
+
state: string;
|
|
84
|
+
}>;
|
|
85
|
+
test: (id: string, payload: import("./whatsapp.js").WhatsAppPayload) => Promise<{
|
|
86
|
+
valid: boolean;
|
|
87
|
+
kind: string;
|
|
88
|
+
to: string;
|
|
89
|
+
connected: boolean;
|
|
90
|
+
sent: false;
|
|
91
|
+
}>;
|
|
92
|
+
outbox: () => Promise<{
|
|
93
|
+
id: string;
|
|
94
|
+
session_id: string;
|
|
95
|
+
state: string;
|
|
96
|
+
provider_id: string | null;
|
|
97
|
+
error: string | null;
|
|
98
|
+
created_at: string;
|
|
99
|
+
}[]>;
|
|
100
|
+
sendText: (id: string, to: string, text: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
101
|
+
id: string;
|
|
102
|
+
state: string;
|
|
103
|
+
}>;
|
|
104
|
+
reconnect: (id: string) => Promise<any>;
|
|
105
|
+
disconnect: (id: string) => Promise<any>;
|
|
106
|
+
deleteConnection: (id: string) => Promise<{
|
|
107
|
+
removed: boolean;
|
|
108
|
+
state: string;
|
|
109
|
+
}>;
|
|
110
|
+
deleteArchive: (id: string) => Promise<{
|
|
111
|
+
removed: boolean;
|
|
112
|
+
state: string;
|
|
113
|
+
}>;
|
|
114
|
+
archives: () => Promise<import("./whatsapp.js").WhatsAppArchive[]>;
|
|
115
|
+
messages: (id: string, before?: string, chat?: string) => Promise<import("./whatsapp.js").WhatsAppMessage[]>;
|
|
116
|
+
conversations: (id: string) => Promise<import("./whatsapp.js").Conversation[]>;
|
|
117
|
+
media: (archiveId: string, messageId: string) => Promise<{
|
|
118
|
+
data: string | null;
|
|
119
|
+
state: "available" | "queued";
|
|
120
|
+
}>;
|
|
121
|
+
};
|
|
122
|
+
registerFunctions(url?: string): Promise<any>;
|
|
123
|
+
/**
|
|
124
|
+
* Crea o recupera l'identità centrale collegata all'utente locale.
|
|
125
|
+
*
|
|
126
|
+
* `initialPassword` deve provenire da una verifica locale appena conclusa e viene usata
|
|
127
|
+
* soltanto per inizializzare una nuova identità nel provider. Non viene conservata da
|
|
128
|
+
* Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
|
|
129
|
+
* Le chiamate esistenti senza il campo mantengono il comportamento precedente.
|
|
130
|
+
*/
|
|
131
|
+
mirrorUser(user: LocalUserProfile): Promise<MirroredUser>;
|
|
132
|
+
teamOverview(accessToken: string): Promise<TeamOverview>;
|
|
133
|
+
teamUsers(accessToken: string): Promise<TeamUser[]>;
|
|
134
|
+
teamRoles(accessToken: string): Promise<TeamRole[]>;
|
|
135
|
+
teamFunctions(accessToken: string): Promise<TeamFunction[]>;
|
|
136
|
+
createTeamRole(accessToken: string, role: TeamRoleInput): Promise<TeamRole>;
|
|
137
|
+
updateTeamRole(accessToken: string, id: string, role: TeamRoleInput): Promise<TeamRole>;
|
|
138
|
+
deleteTeamRole(accessToken: string, id: string): Promise<{
|
|
139
|
+
removed: boolean;
|
|
140
|
+
}>;
|
|
141
|
+
setTeamUserRoles(accessToken: string, subject: string, roleIds: string[]): Promise<TeamUserAssignment>;
|
|
142
|
+
revokeTeamUser(accessToken: string, subject: string): Promise<TeamRevocation>;
|
|
143
|
+
restoreTeamUser(accessToken: string, subject: string): Promise<TeamRestore>;
|
|
144
|
+
permissions(accessToken: string): Promise<AccessResult>;
|
|
145
|
+
notifications(accessToken: string, options?: {
|
|
146
|
+
unread?: boolean;
|
|
147
|
+
before?: string;
|
|
148
|
+
beforeId?: string;
|
|
149
|
+
limit?: number;
|
|
150
|
+
}): Promise<any>;
|
|
151
|
+
markNotification(accessToken: string, id: string, read?: boolean): Promise<any>;
|
|
152
|
+
markAllNotificationsRead(accessToken: string): Promise<any>;
|
|
153
|
+
accountSecurity(accessToken: string): Promise<any>;
|
|
154
|
+
revokeTrustedDevice(accessToken: string, id: string): Promise<any>;
|
|
155
|
+
sessions(accessToken: string): Promise<any>;
|
|
156
|
+
logoutSession(accessToken: string, id: string): Promise<any>;
|
|
157
|
+
logoutAllSessions(accessToken: string): Promise<any>;
|
|
158
|
+
users(accessToken: string): Promise<ConnectUser[]>;
|
|
159
|
+
requireFunction(accessToken: string, functionKey: string): Promise<void>;
|
|
160
|
+
redeemTechnicalTicket(ticket: string): Promise<any>;
|
|
161
|
+
static pair(apiUrl: string, code: string, domain: string): Promise<any>;
|
|
162
|
+
}
|
|
163
|
+
export declare function verifyWebhook(secret: string, rawBody: string, timestamp: string, received: string, now?: number): boolean;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
|
|
2
|
+
import { functionCatalogPath } from './functions.js';
|
|
3
|
+
import { whatsappClient } from './whatsapp.js';
|
|
4
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
export class ConnectServer {
|
|
6
|
+
config;
|
|
7
|
+
constructor(config) {
|
|
8
|
+
this.config = config;
|
|
9
|
+
}
|
|
10
|
+
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) });
|
|
12
|
+
const result = await response.json();
|
|
13
|
+
if (!response.ok)
|
|
14
|
+
throw new Error(`Connect ${response.status}: ${JSON.stringify(result)}`);
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
functionUrl(feature, path) {
|
|
18
|
+
if (!/^[a-z][a-z0-9_.:-]{0,79}$/.test(feature) || !this.config.domain)
|
|
19
|
+
throw new Error('Dominio o funzione non valido');
|
|
20
|
+
const url = path ? new URL(path, this.config.domain) : new URL(`${(this.config.functionFallbackUrl || this.config.domain + '/eulab/connect/functions').replace(/\/$/, '')}/${encodeURIComponent(feature)}`);
|
|
21
|
+
if (url.origin !== this.config.domain)
|
|
22
|
+
throw new Error('URL funzione esterno al dominio autorizzato');
|
|
23
|
+
return url.href;
|
|
24
|
+
}
|
|
25
|
+
authorize(accessToken, permission) { return this.request('/v1/authorize', 'POST', { installationId: this.config.installationId, permission }, accessToken); }
|
|
26
|
+
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
|
+
registerFunctions(url) { const source = url || this.config.catalogUrl || (this.config.domain ? this.config.domain + (this.config.basePath || '') + functionCatalogPath : undefined); if (!source)
|
|
28
|
+
throw new Error('URL funzioni o dominio richiesto'); return this.request('/v1/catalog-source', 'POST', { url: source }); }
|
|
29
|
+
/**
|
|
30
|
+
* Crea o recupera l'identità centrale collegata all'utente locale.
|
|
31
|
+
*
|
|
32
|
+
* `initialPassword` deve provenire da una verifica locale appena conclusa e viene usata
|
|
33
|
+
* soltanto per inizializzare una nuova identità nel provider. Non viene conservata da
|
|
34
|
+
* Connect, non compare nelle risposte e non viene applicata a identità già esistenti.
|
|
35
|
+
* Le chiamate esistenti senza il campo mantengono il comportamento precedente.
|
|
36
|
+
*/
|
|
37
|
+
mirrorUser(user) { return this.request('/v1/users/mirror', 'POST', user); }
|
|
38
|
+
teamOverview(accessToken) { return this.request('/v1/team', 'GET', undefined, accessToken); }
|
|
39
|
+
teamUsers(accessToken) { return this.request('/v1/team/users', 'GET', undefined, accessToken); }
|
|
40
|
+
teamRoles(accessToken) { return this.request('/v1/team/roles', 'GET', undefined, accessToken); }
|
|
41
|
+
teamFunctions(accessToken) { return this.request('/v1/team/functions', 'GET', undefined, accessToken); }
|
|
42
|
+
createTeamRole(accessToken, role) { return this.request('/v1/team/roles', 'POST', role, accessToken); }
|
|
43
|
+
updateTeamRole(accessToken, id, role) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'PUT', role, accessToken); }
|
|
44
|
+
deleteTeamRole(accessToken, id) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'DELETE', undefined, accessToken); }
|
|
45
|
+
setTeamUserRoles(accessToken, subject, roleIds) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/roles', 'PUT', { roleIds }, accessToken); }
|
|
46
|
+
revokeTeamUser(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject), 'DELETE', undefined, accessToken); }
|
|
47
|
+
restoreTeamUser(accessToken, subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/restore', 'POST', undefined, accessToken); }
|
|
48
|
+
permissions(accessToken) { return this.request('/v1/access', 'GET', undefined, accessToken); }
|
|
49
|
+
notifications(accessToken, options = {}) { const query = new URLSearchParams(); for (const [key, value] of Object.entries(options))
|
|
50
|
+
if (value !== undefined)
|
|
51
|
+
query.set(key, String(value)); return this.request('/v1/notifications?' + query, 'GET', undefined, accessToken); }
|
|
52
|
+
markNotification(accessToken, id, read = true) { return this.request('/v1/notifications/' + encodeURIComponent(id) + '/read', 'PUT', { read }, accessToken); }
|
|
53
|
+
markAllNotificationsRead(accessToken) { return this.request('/v1/notifications/read-all', 'POST', undefined, accessToken); }
|
|
54
|
+
accountSecurity(accessToken) { return this.request('/v1/security/me', 'GET', undefined, accessToken); }
|
|
55
|
+
revokeTrustedDevice(accessToken, id) { return this.request('/v1/security/devices/' + encodeURIComponent(id), 'DELETE', undefined, accessToken); }
|
|
56
|
+
sessions(accessToken) { return this.request('/v1/sessions', 'GET', undefined, accessToken); }
|
|
57
|
+
logoutSession(accessToken, id) { return this.request(`/v1/sessions/${encodeURIComponent(id)}/logout`, 'POST', undefined, accessToken); }
|
|
58
|
+
logoutAllSessions(accessToken) { return this.request('/v1/sessions/logout-all', 'POST', undefined, accessToken); }
|
|
59
|
+
users(accessToken) { return this.request('/v1/users', 'GET', undefined, accessToken); }
|
|
60
|
+
async requireFunction(accessToken, functionKey) { const result = await this.authorize(accessToken, functionKey); if (!result.allowed)
|
|
61
|
+
throw new Error('Funzione non consentita: ' + result.reason); }
|
|
62
|
+
redeemTechnicalTicket(ticket) { return this.request('/v1/technical/redeem', 'POST', { ticket }); }
|
|
63
|
+
static async pair(apiUrl, code, domain) { const r = await fetch(`${apiUrl}/v1/pairing/redeem`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, domain }) }); if (!r.ok)
|
|
64
|
+
throw new Error('Associazione fallita'); return r.json(); }
|
|
65
|
+
}
|
|
66
|
+
export function verifyWebhook(secret, rawBody, timestamp, received, now = Date.now()) {
|
|
67
|
+
if (!/^\d+$/.test(timestamp) || Math.abs(now / 1000 - Number(timestamp)) > 300 || !/^[a-f0-9]{64}$/.test(received))
|
|
68
|
+
return false;
|
|
69
|
+
const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
|
|
70
|
+
return timingSafeEqual(expected, Buffer.from(received, 'hex'));
|
|
71
|
+
}
|
|
72
|
+
// Persist event IDs in the consumer database before applying side effects; signatures alone do not deduplicate events.
|