@memberjunction/server 6.1.0-edge.6 → 6.1.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.
Files changed (177) hide show
  1. package/README.md +24 -9
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/config.d.ts +36 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +9 -0
  6. package/dist/config.js.map +1 -1
  7. package/dist/entitySubclasses/MJEntityPermissionEntityServer.server.d.ts +30 -0
  8. package/dist/entitySubclasses/MJEntityPermissionEntityServer.server.d.ts.map +1 -1
  9. package/dist/entitySubclasses/MJEntityPermissionEntityServer.server.js +58 -5
  10. package/dist/entitySubclasses/MJEntityPermissionEntityServer.server.js.map +1 -1
  11. package/dist/generated/graphql-schemas/__mj.d.ts +2842 -2144
  12. package/dist/generated/graphql-schemas/__mj.d.ts.map +1 -1
  13. package/dist/generated/graphql-schemas/__mj.js +5334 -2143
  14. package/dist/generated/graphql-schemas/__mj.js.map +1 -1
  15. package/dist/generic/ResolverBase.d.ts +119 -4
  16. package/dist/generic/ResolverBase.d.ts.map +1 -1
  17. package/dist/generic/ResolverBase.js +264 -11
  18. package/dist/generic/ResolverBase.js.map +1 -1
  19. package/dist/generic/RunViewResolver.d.ts.map +1 -1
  20. package/dist/generic/RunViewResolver.js +26 -2
  21. package/dist/generic/RunViewResolver.js.map +1 -1
  22. package/dist/generic/refusalExtensions.d.ts +52 -0
  23. package/dist/generic/refusalExtensions.d.ts.map +1 -0
  24. package/dist/generic/refusalExtensions.js +16 -0
  25. package/dist/generic/refusalExtensions.js.map +1 -0
  26. package/dist/index.d.ts +9 -3
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +115 -91
  29. package/dist/index.js.map +1 -1
  30. package/dist/resolvers/EntityRecordNameResolver.d.ts +34 -5
  31. package/dist/resolvers/EntityRecordNameResolver.d.ts.map +1 -1
  32. package/dist/resolvers/EntityRecordNameResolver.js +64 -7
  33. package/dist/resolvers/EntityRecordNameResolver.js.map +1 -1
  34. package/dist/resolvers/RealtimeClientSessionResolver.d.ts +10 -2
  35. package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -1
  36. package/dist/resolvers/RealtimeClientSessionResolver.js +80 -4
  37. package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -1
  38. package/dist/rest/RealtimeSdpBrokerHandler.d.ts +23 -0
  39. package/dist/rest/RealtimeSdpBrokerHandler.d.ts.map +1 -0
  40. package/dist/rest/RealtimeSdpBrokerHandler.js +78 -0
  41. package/dist/rest/RealtimeSdpBrokerHandler.js.map +1 -0
  42. package/dist/serverExtensionReservedRoots.d.ts.map +1 -1
  43. package/dist/serverExtensionReservedRoots.js +2 -3
  44. package/dist/serverExtensionReservedRoots.js.map +1 -1
  45. package/package.json +92 -92
  46. package/src/__tests__/EntityRecordNameResolver.fieldSecurity.test.ts +118 -0
  47. package/src/__tests__/RealtimeClientSessionResolver.test.ts +20 -0
  48. package/src/__tests__/RealtimeSdpBrokerHandler.test.ts +191 -0
  49. package/src/__tests__/ResolverBase.filterEscaping.test.ts +63 -0
  50. package/src/__tests__/ResolverBase.readableFieldsTransport.test.ts +106 -0
  51. package/src/__tests__/generatedGraphQLSchema.structural.test.ts +46 -0
  52. package/src/__tests__/resolverBase.fls.test.ts +483 -0
  53. package/src/__tests__/resolverBase.recordChangesFls.test.ts +358 -0
  54. package/src/__tests__/resolverBase.refusalExtensions.test.ts +101 -0
  55. package/src/__tests__/serverExtensionReservedRoots.test.ts +79 -11
  56. package/src/config.ts +12 -0
  57. package/src/entitySubclasses/MJEntityPermissionEntityServer.server.ts +65 -6
  58. package/src/generated/graphql-schemas/__mj.ts +6590 -4287
  59. package/src/generic/ResolverBase.ts +313 -10
  60. package/src/generic/RunViewResolver.ts +28 -2
  61. package/src/generic/refusalExtensions.ts +59 -0
  62. package/src/index.ts +137 -100
  63. package/src/resolvers/EntityRecordNameResolver.ts +74 -8
  64. package/src/resolvers/RealtimeClientSessionResolver.ts +128 -2
  65. package/src/rest/RealtimeSdpBrokerHandler.ts +101 -0
  66. package/src/serverExtensionReservedRoots.ts +2 -3
  67. package/dist/resolvers/RingCentralTelephonyResolver.d.ts +0 -27
  68. package/dist/resolvers/RingCentralTelephonyResolver.d.ts.map +0 -1
  69. package/dist/resolvers/RingCentralTelephonyResolver.js +0 -87
  70. package/dist/resolvers/RingCentralTelephonyResolver.js.map +0 -1
  71. package/dist/resolvers/TeamsMeetingsResolver.d.ts +0 -28
  72. package/dist/resolvers/TeamsMeetingsResolver.d.ts.map +0 -1
  73. package/dist/resolvers/TeamsMeetingsResolver.js +0 -91
  74. package/dist/resolvers/TeamsMeetingsResolver.js.map +0 -1
  75. package/dist/resolvers/TelephonyResolver.d.ts +0 -26
  76. package/dist/resolvers/TelephonyResolver.d.ts.map +0 -1
  77. package/dist/resolvers/TelephonyResolver.js +0 -86
  78. package/dist/resolvers/TelephonyResolver.js.map +0 -1
  79. package/dist/resolvers/VonageTelephonyResolver.d.ts +0 -26
  80. package/dist/resolvers/VonageTelephonyResolver.d.ts.map +0 -1
  81. package/dist/resolvers/VonageTelephonyResolver.js +0 -86
  82. package/dist/resolvers/VonageTelephonyResolver.js.map +0 -1
  83. package/dist/telephony/RingCentralTelephonyService.d.ts +0 -115
  84. package/dist/telephony/RingCentralTelephonyService.d.ts.map +0 -1
  85. package/dist/telephony/RingCentralTelephonyService.js +0 -262
  86. package/dist/telephony/RingCentralTelephonyService.js.map +0 -1
  87. package/dist/telephony/TeamsMeetingsRouter.d.ts +0 -40
  88. package/dist/telephony/TeamsMeetingsRouter.d.ts.map +0 -1
  89. package/dist/telephony/TeamsMeetingsRouter.js +0 -112
  90. package/dist/telephony/TeamsMeetingsRouter.js.map +0 -1
  91. package/dist/telephony/TeamsMeetingsService.d.ts +0 -113
  92. package/dist/telephony/TeamsMeetingsService.d.ts.map +0 -1
  93. package/dist/telephony/TeamsMeetingsService.js +0 -196
  94. package/dist/telephony/TeamsMeetingsService.js.map +0 -1
  95. package/dist/telephony/TwilioTelephonyRouter.d.ts +0 -36
  96. package/dist/telephony/TwilioTelephonyRouter.d.ts.map +0 -1
  97. package/dist/telephony/TwilioTelephonyRouter.js +0 -143
  98. package/dist/telephony/TwilioTelephonyRouter.js.map +0 -1
  99. package/dist/telephony/TwilioTelephonyService.d.ts +0 -95
  100. package/dist/telephony/TwilioTelephonyService.d.ts.map +0 -1
  101. package/dist/telephony/TwilioTelephonyService.js +0 -193
  102. package/dist/telephony/TwilioTelephonyService.js.map +0 -1
  103. package/dist/telephony/VonageTelephonyRouter.d.ts +0 -41
  104. package/dist/telephony/VonageTelephonyRouter.d.ts.map +0 -1
  105. package/dist/telephony/VonageTelephonyRouter.js +0 -201
  106. package/dist/telephony/VonageTelephonyRouter.js.map +0 -1
  107. package/dist/telephony/VonageTelephonyService.d.ts +0 -90
  108. package/dist/telephony/VonageTelephonyService.d.ts.map +0 -1
  109. package/dist/telephony/VonageTelephonyService.js +0 -191
  110. package/dist/telephony/VonageTelephonyService.js.map +0 -1
  111. package/dist/telephony/calendar-scheduler.d.ts +0 -67
  112. package/dist/telephony/calendar-scheduler.d.ts.map +0 -1
  113. package/dist/telephony/calendar-scheduler.js +0 -133
  114. package/dist/telephony/calendar-scheduler.js.map +0 -1
  115. package/dist/telephony/index.d.ts +0 -29
  116. package/dist/telephony/index.d.ts.map +0 -1
  117. package/dist/telephony/index.js +0 -38
  118. package/dist/telephony/index.js.map +0 -1
  119. package/dist/telephony/media-upgrade-router.d.ts +0 -47
  120. package/dist/telephony/media-upgrade-router.d.ts.map +0 -1
  121. package/dist/telephony/media-upgrade-router.js +0 -72
  122. package/dist/telephony/media-upgrade-router.js.map +0 -1
  123. package/dist/telephony/ringcentral-runtime.d.ts +0 -14
  124. package/dist/telephony/ringcentral-runtime.d.ts.map +0 -1
  125. package/dist/telephony/ringcentral-runtime.js +0 -18
  126. package/dist/telephony/ringcentral-runtime.js.map +0 -1
  127. package/dist/telephony/teams-meetings-runtime.d.ts +0 -16
  128. package/dist/telephony/teams-meetings-runtime.d.ts.map +0 -1
  129. package/dist/telephony/teams-meetings-runtime.js +0 -20
  130. package/dist/telephony/teams-meetings-runtime.js.map +0 -1
  131. package/dist/telephony/teamsAcsMediaRegistry.d.ts +0 -69
  132. package/dist/telephony/teamsAcsMediaRegistry.d.ts.map +0 -1
  133. package/dist/telephony/teamsAcsMediaRegistry.js +0 -118
  134. package/dist/telephony/teamsAcsMediaRegistry.js.map +0 -1
  135. package/dist/telephony/telephony-runtime.d.ts +0 -14
  136. package/dist/telephony/telephony-runtime.d.ts.map +0 -1
  137. package/dist/telephony/telephony-runtime.js +0 -18
  138. package/dist/telephony/telephony-runtime.js.map +0 -1
  139. package/dist/telephony/twilioMediaRegistry.d.ts +0 -60
  140. package/dist/telephony/twilioMediaRegistry.d.ts.map +0 -1
  141. package/dist/telephony/twilioMediaRegistry.js +0 -106
  142. package/dist/telephony/twilioMediaRegistry.js.map +0 -1
  143. package/dist/telephony/vonage-runtime.d.ts +0 -14
  144. package/dist/telephony/vonage-runtime.d.ts.map +0 -1
  145. package/dist/telephony/vonage-runtime.js +0 -18
  146. package/dist/telephony/vonage-runtime.js.map +0 -1
  147. package/dist/telephony/vonageMediaRegistry.d.ts +0 -78
  148. package/dist/telephony/vonageMediaRegistry.d.ts.map +0 -1
  149. package/dist/telephony/vonageMediaRegistry.js +0 -158
  150. package/dist/telephony/vonageMediaRegistry.js.map +0 -1
  151. package/src/__tests__/media-upgrade-router.test.ts +0 -43
  152. package/src/__tests__/teams-meetings-service.test.ts +0 -65
  153. package/src/__tests__/teamsAcsMediaRegistry.test.ts +0 -82
  154. package/src/__tests__/twilio-telephony-service.test.ts +0 -23
  155. package/src/__tests__/twilioMediaRegistry.test.ts +0 -103
  156. package/src/__tests__/vonageMediaRegistry.test.ts +0 -180
  157. package/src/resolvers/RingCentralTelephonyResolver.ts +0 -64
  158. package/src/resolvers/TeamsMeetingsResolver.ts +0 -68
  159. package/src/resolvers/TelephonyResolver.ts +0 -63
  160. package/src/resolvers/VonageTelephonyResolver.ts +0 -63
  161. package/src/telephony/RingCentralTelephonyService.ts +0 -342
  162. package/src/telephony/TeamsMeetingsRouter.ts +0 -143
  163. package/src/telephony/TeamsMeetingsService.ts +0 -268
  164. package/src/telephony/TwilioTelephonyRouter.ts +0 -184
  165. package/src/telephony/TwilioTelephonyService.ts +0 -261
  166. package/src/telephony/VonageTelephonyRouter.ts +0 -239
  167. package/src/telephony/VonageTelephonyService.ts +0 -259
  168. package/src/telephony/calendar-scheduler.ts +0 -176
  169. package/src/telephony/index.ts +0 -43
  170. package/src/telephony/media-upgrade-router.ts +0 -79
  171. package/src/telephony/ringcentral-runtime.ts +0 -22
  172. package/src/telephony/teams-meetings-runtime.ts +0 -24
  173. package/src/telephony/teamsAcsMediaRegistry.ts +0 -152
  174. package/src/telephony/telephony-runtime.ts +0 -22
  175. package/src/telephony/twilioMediaRegistry.ts +0 -137
  176. package/src/telephony/vonage-runtime.ts +0 -22
  177. package/src/telephony/vonageMediaRegistry.ts +0 -200
@@ -1,342 +0,0 @@
1
- /**
2
- * @fileoverview Orchestrates RingCentral telephony bridge sessions (inbound + outbound) for MJAPI over the
3
- * **SIP softphone** transport.
4
- *
5
- * RingCentral's only product that carries bidirectional call audio is a registered SIP softphone (the
6
- * `ringcentral-softphone` SDK over SIP/TLS + RTP/SRTP) — its WebSocket "Call Streaming" product is
7
- * receive-only and cannot inject the agent's voice. So unlike the Twilio/Vonage ingresses (public webhook
8
- * + media WSS), this service owns a **long-lived SIP registration**: one
9
- * {@link RingCentralSoftphoneHandle} created + registered at boot, shared across all calls. Inbound calls
10
- * arrive as SIP INVITEs on that registration (no HTTP webhook); outbound calls place SIP calls through it.
11
- *
12
- * It does NOT re-implement bridge logic: it resolves the RingCentral provider + the agent identity, opens a
13
- * server-side realtime session via the agent layer's `CreateBridgeRealtimeSession` factory, binds a
14
- * {@link RingCentralSoftphoneCallSdk} (drawing its session from the shared handle) onto the driver, and
15
- * hands everything to `AIBridgeEngine.StartBridgeSession` — the same seam the Twilio/Vonage services use.
16
- *
17
- * @module @memberjunction/server/telephony
18
- */
19
-
20
- import { RunView, UserInfo, IMetadataProvider, Metadata, LogError, LogStatus } from '@memberjunction/core';
21
- import type { MJAIBridgeAgentIdentityEntity, MJAIBridgeProviderEntity } from '@memberjunction/core-entities';
22
- import { UserCache } from '@memberjunction/generic-database-provider';
23
- import { AIBridgeEngine } from '@memberjunction/ai-bridge-server';
24
- import { CreateBridgeRealtimeSession } from '@memberjunction/ai-agents';
25
- import {
26
- BaseTelephonyBridge,
27
- type BridgeNativeSdkBinding,
28
- CARRIER_SAMPLE_RATE_CONFIG_KEY,
29
- DIRECTION_CONFIG_KEY,
30
- FROM_NUMBER_CONFIG_KEY,
31
- INBOUND_CALL_ID_CONFIG_KEY,
32
- } from '@memberjunction/ai-bridge-base';
33
- import {
34
- createRingCentralSoftphone,
35
- RingCentralSoftphoneCallSdk,
36
- type RingCentralSoftphoneConfig,
37
- type RingCentralSoftphoneHandle,
38
- type InboundInviteInfo,
39
- } from '@memberjunction/ai-bridge-ringcentral';
40
- import type { RingCentralTelephonyConfig } from '../config.js';
41
- import { SessionManager } from '../agentSessions/SessionManager.js';
42
-
43
- const RINGCENTRAL_PROVIDER_DRIVER = 'RingCentralBridge';
44
- const AGENT_IDENTITY_ENTITY = 'MJ: AI Bridge Agent Identities';
45
- const PHONE_IDENTITY_TYPE = 'PhoneNumber';
46
-
47
- /** PCM16 carrier rate (Hz) per softphone codec — the rate the bridge resamples to/from the model rate. */
48
- const CODEC_CARRIER_RATE: Record<NonNullable<RingCentralSoftphoneConfig['codec']>, number> = {
49
- 'OPUS/16000': 16000,
50
- 'OPUS/48000/2': 48000,
51
- 'PCMU/8000': 8000,
52
- };
53
-
54
- /** A resolved inbound call's identifying fields (mapped from a RingCentral SIP INVITE). */
55
- export interface InboundCallInput {
56
- /** The SIP `Call-ID` (the per-call id the handle parked the INVITE under + the bridge's inbound id). */
57
- sessionId: string;
58
- /** The caller's number (the INVITE's `From`). */
59
- from: string;
60
- /** The dialed DID (the INVITE's `To`) — resolved to an agent identity. */
61
- to: string;
62
- }
63
-
64
- /** Result of starting an inbound bridge session. */
65
- export interface InboundCallResult {
66
- /** Whether a pinned agent was resolved + a bridge session started. */
67
- accepted: boolean;
68
- /** Why it was rejected (no agent identity for the DID, provider missing, etc.). */
69
- reason?: string;
70
- }
71
-
72
- /** Injectable collaborators (production defaults wired in the constructor; fakes in tests). */
73
- export interface RingCentralTelephonyServiceDeps {
74
- engine?: Pick<AIBridgeEngine, 'ProviderByName' | 'ProviderByDriverClass' | 'StartBridgeSession' | 'Config'>;
75
- sessionFactory?: typeof CreateBridgeRealtimeSession;
76
- sessionManager?: Pick<SessionManager, 'CreateSession'>;
77
- /** Test seam: a factory that builds the softphone handle (inject a fake to avoid the real SIP SDK). */
78
- createHandle?: typeof createRingCentralSoftphone;
79
- }
80
-
81
- /**
82
- * Starts RingCentral bridge sessions over a shared SIP-softphone registration. One instance per server,
83
- * constructed at boot and held by the runtime holder so the outbound `PlaceRingCentralCall` resolver and the
84
- * inbound INVITE coordinator share the same registration.
85
- */
86
- export class RingCentralTelephonyService {
87
- private readonly engine: Pick<AIBridgeEngine, 'ProviderByName' | 'ProviderByDriverClass' | 'StartBridgeSession' | 'Config'>;
88
- private readonly sessionFactory: typeof CreateBridgeRealtimeSession;
89
- private readonly sessionManager: Pick<SessionManager, 'CreateSession'>;
90
- private readonly createHandle: typeof createRingCentralSoftphone;
91
-
92
- /** The shared SIP registration — created + registered by {@link start}; null until then. */
93
- private handle: RingCentralSoftphoneHandle | null = null;
94
-
95
- /** The carrier PCM16 rate for the negotiated codec (set in {@link start}). */
96
- private carrierSampleRate: number = CODEC_CARRIER_RATE['OPUS/16000'];
97
-
98
- constructor(
99
- private readonly config: RingCentralTelephonyConfig,
100
- deps: RingCentralTelephonyServiceDeps = {},
101
- ) {
102
- this.engine = deps.engine ?? AIBridgeEngine.Instance;
103
- this.sessionFactory = deps.sessionFactory ?? CreateBridgeRealtimeSession;
104
- this.sessionManager = deps.sessionManager ?? new SessionManager();
105
- this.createHandle = deps.createHandle ?? createRingCentralSoftphone;
106
- }
107
-
108
- /**
109
- * Creates + registers the shared SIP softphone and wires inbound INVITE handling. Called once at boot
110
- * (fire-and-forget so SIP registration never blocks server startup); logs success/failure. Inbound calls
111
- * only flow once this resolves.
112
- */
113
- public async start(): Promise<void> {
114
- try {
115
- this.carrierSampleRate = CODEC_CARRIER_RATE[this.config.codec ?? 'OPUS/16000'];
116
- this.handle = await this.createHandle(this.toSoftphoneConfig());
117
- this.handle.onInvite((info) => void this.onInboundInvite(info));
118
- await this.handle.register();
119
- LogStatus('[Telephony][RingCentral] softphone telephony started (inbound + outbound ready).');
120
- } catch (e) {
121
- this.handle = null;
122
- LogError(`[Telephony][RingCentral] softphone start failed: ${e instanceof Error ? e.message : String(e)}`);
123
- }
124
- }
125
-
126
- /** Best-effort teardown of the SIP registration (server shutdown). */
127
- public dispose(): void {
128
- this.handle?.dispose();
129
- this.handle = null;
130
- }
131
-
132
- /**
133
- * Resolves the dialed DID to a pinned agent and starts an INBOUND bridge session. The bound
134
- * {@link RingCentralSoftphoneCallSdk} answers the parked INVITE for `sessionId`. Returns
135
- * `{ accepted:false }` (never throws) when no agent identity matches the DID, so the coordinator can
136
- * decline the INVITE cleanly.
137
- */
138
- public async HandleInboundCall(input: InboundCallInput, contextUser: UserInfo, provider: IMetadataProvider): Promise<InboundCallResult> {
139
- try {
140
- const identity = await this.resolveAgentIdentityByPhone(input.to, contextUser);
141
- if (!identity) {
142
- return { accepted: false, reason: `No active agent identity for dialed number '${input.to}'.` };
143
- }
144
- await this.startBridge({
145
- agentID: identity.AgentID,
146
- direction: 'Inbound',
147
- address: input.from,
148
- inboundCallId: input.sessionId,
149
- contextUser,
150
- provider,
151
- });
152
- return { accepted: true };
153
- } catch (e) {
154
- LogError(`[Telephony][RingCentral] inbound call ${input.sessionId} failed: ${e instanceof Error ? e.message : String(e)}`);
155
- return { accepted: false, reason: 'Internal error starting the agent.' };
156
- }
157
- }
158
-
159
- /**
160
- * Places an OUTBOUND call from a given agent identity to a destination number. The bound
161
- * {@link RingCentralSoftphoneCallSdk} places the SIP call through the shared registration; the returned
162
- * SIP `Call-ID` is the bridge's external connection id.
163
- *
164
- * @returns The placed call's SIP `Call-ID`.
165
- */
166
- public async PlaceOutboundCall(agentIdentityId: string, toNumber: string, contextUser: UserInfo, provider: IMetadataProvider): Promise<string> {
167
- const identity = await this.loadAgentIdentity(agentIdentityId, contextUser, provider);
168
- if (!identity) {
169
- throw new Error(`Agent identity '${agentIdentityId}' not found or inactive.`);
170
- }
171
- const session = await this.startBridge({
172
- agentID: identity.AgentID,
173
- direction: 'Outbound',
174
- address: toNumber,
175
- fromNumber: identity.IdentityValue,
176
- contextUser,
177
- provider,
178
- });
179
- return session.RoomKey ?? '';
180
- }
181
-
182
- // ── internals ────────────────────────────────────────────────────────────────
183
-
184
- /** Inbound INVITE coordinator: resolve the server principal, start a bridge, decline if no agent matched. */
185
- private async onInboundInvite(info: InboundInviteInfo): Promise<void> {
186
- const context = this.resolveServerContext();
187
- if (!context) {
188
- LogError('[Telephony][RingCentral] no server context user available; declining inbound call.');
189
- await this.handle?.declineCall(info.callId);
190
- return;
191
- }
192
- const result = await this.HandleInboundCall({ sessionId: info.callId, from: info.from, to: info.to }, context.user, context.provider);
193
- if (!result.accepted) {
194
- LogStatus(`[Telephony][RingCentral] inbound ${info.callId} not accepted: ${result.reason ?? 'unknown'}; declining.`);
195
- await this.handle?.declineCall(info.callId);
196
- }
197
- }
198
-
199
- /** Shared inbound/outbound bridge-start: resolve provider, open the realtime session, bind the SDK, start. */
200
- private async startBridge(args: {
201
- agentID: string;
202
- direction: 'Inbound' | 'Outbound';
203
- address: string;
204
- inboundCallId?: string;
205
- fromNumber?: string;
206
- contextUser: UserInfo;
207
- provider: IMetadataProvider;
208
- }): Promise<{ RoomKey?: string }> {
209
- await this.engine.Config(false, args.contextUser, args.provider);
210
- const ringCentralProvider = this.resolveProvider();
211
-
212
- const agentSession = await this.sessionManager.CreateSession({ agentID: args.agentID, userID: args.contextUser.ID }, args.contextUser, args.provider);
213
- const realtimeSession = await this.sessionFactory({
214
- AgentID: args.agentID,
215
- TargetAgentID: args.agentID,
216
- ContextUser: args.contextUser,
217
- MetadataProvider: args.provider,
218
- AgentSessionID: agentSession.ID,
219
- RoomName: args.address,
220
- });
221
-
222
- const active = await this.engine.StartBridgeSession({
223
- AgentSessionID: agentSession.ID,
224
- AgentID: args.agentID,
225
- TargetAgentID: args.agentID,
226
- Provider: ringCentralProvider,
227
- RealtimeSession: realtimeSession,
228
- Address: args.address,
229
- Direction: args.direction,
230
- Configuration: this.buildSessionConfiguration(args.direction, args.fromNumber, args.inboundCallId),
231
- BindSdk: this.buildBindSdk(),
232
- ContextUser: args.contextUser,
233
- MetadataProvider: args.provider,
234
- });
235
- return { RoomKey: active.RoomKey };
236
- }
237
-
238
- /** Resolves the seeded RingCentral provider row (by driver class, falling back to display name). */
239
- private resolveProvider(): MJAIBridgeProviderEntity {
240
- const provider = this.engine.ProviderByDriverClass(RINGCENTRAL_PROVIDER_DRIVER) ?? this.engine.ProviderByName('RingCentral');
241
- if (!provider) {
242
- throw new Error(`No active 'MJ: AI Bridge Providers' row for the RingCentral bridge (DriverClass '${RINGCENTRAL_PROVIDER_DRIVER}').`);
243
- }
244
- return provider;
245
- }
246
-
247
- /**
248
- * Builds the per-session SDK binding that wires a {@link RingCentralSoftphoneCallSdk} (drawing its
249
- * session from the shared SIP registration handle) onto the telephony driver — overriding the package's
250
- * default unbound SDK. Reads the handle lazily at call time so a call placed during the brief boot window
251
- * before registration fails loudly rather than binding a null handle.
252
- */
253
- public buildBindSdk(): BridgeNativeSdkBinding {
254
- return (driver) => {
255
- const telephony = driver as BaseTelephonyBridge;
256
- telephony.SetSdkFactory(() => new RingCentralSoftphoneCallSdk(this.requireHandle()));
257
- };
258
- }
259
-
260
- /** Returns the live registration handle, or throws if the softphone hasn't registered yet. */
261
- private requireHandle(): RingCentralSoftphoneHandle {
262
- if (!this.handle) {
263
- throw new Error('[Telephony][RingCentral] softphone not registered yet (start() pending or failed).');
264
- }
265
- return this.handle;
266
- }
267
-
268
- /** Assembles the per-session bridge configuration (direction / from-number / inbound-call-id / carrier rate). */
269
- private buildSessionConfiguration(direction: 'Inbound' | 'Outbound', fromNumber?: string, inboundCallId?: string): Record<string, unknown> {
270
- // The engine does NOT forward the top-level Direction into the driver's Configuration; set it here so
271
- // an inbound call answers instead of wrongly taking the outbound-dial path. The carrier rate tells the
272
- // base bridge the SIP leg is wideband (16 kHz for OPUS/16000), not the 8 kHz G.711 default.
273
- const config: Record<string, unknown> = {
274
- [DIRECTION_CONFIG_KEY]: direction,
275
- [CARRIER_SAMPLE_RATE_CONFIG_KEY]: this.carrierSampleRate,
276
- };
277
- if (fromNumber) {
278
- config[FROM_NUMBER_CONFIG_KEY] = fromNumber;
279
- }
280
- if (inboundCallId) {
281
- config[INBOUND_CALL_ID_CONFIG_KEY] = inboundCallId;
282
- }
283
- return config;
284
- }
285
-
286
- /** Maps the server config block to the softphone SDK's SIP-device config (credentials resolved upstream). */
287
- private toSoftphoneConfig(): RingCentralSoftphoneConfig {
288
- return {
289
- domain: this.config.sipDomain,
290
- outboundProxy: this.config.sipOutboundProxy,
291
- username: this.config.sipUsername,
292
- password: this.config.sipPassword,
293
- authorizationId: this.config.sipAuthorizationId,
294
- codec: this.config.codec,
295
- ignoreTlsCertErrors: this.config.ignoreTlsCertErrors,
296
- };
297
- }
298
-
299
- /** Resolves the server-side principal + provider for an inbound call (no MJ JWT on a SIP INVITE). */
300
- private resolveServerContext(): { user: UserInfo; provider: IMetadataProvider } | null {
301
- const user = UserCache.Instance.GetSystemUser() ?? UserCache.Users.find((u) => u.IsActive && u.Type?.trim().toLowerCase() === 'owner') ?? null;
302
- const provider = Metadata.Provider as unknown as IMetadataProvider | undefined; // global-provider-ok: inbound SIP INVITE has no MJ JWT / per-request provider; the server's single default provider is correct
303
- if (!user || !provider) {
304
- return null;
305
- }
306
- return { user, provider };
307
- }
308
-
309
- /** Finds the active agent identity whose phone number matches the dialed DID. */
310
- private async resolveAgentIdentityByPhone(dialedNumber: string, contextUser: UserInfo): Promise<MJAIBridgeAgentIdentityEntity | null> {
311
- const normalized = (dialedNumber ?? '').trim();
312
- if (!normalized) {
313
- return null;
314
- }
315
- const rv = new RunView();
316
- const result = await rv.RunView<MJAIBridgeAgentIdentityEntity>(
317
- {
318
- EntityName: AGENT_IDENTITY_ENTITY,
319
- ExtraFilter: `IdentityType='${PHONE_IDENTITY_TYPE}' AND IdentityValue='${normalized.replace(/'/g, "''")}' AND IsActive=1`,
320
- MaxRows: 1,
321
- ResultType: 'entity_object',
322
- },
323
- contextUser,
324
- );
325
- if (!result.Success) {
326
- LogError(`[Telephony][RingCentral] agent-identity lookup failed: ${result.ErrorMessage}`);
327
- return null;
328
- }
329
- return result.Results?.[0] ?? null;
330
- }
331
-
332
- /** Loads a specific agent identity by id (used by outbound PlaceCall), requiring it be active. */
333
- private async loadAgentIdentity(agentIdentityId: string, contextUser: UserInfo, provider: IMetadataProvider): Promise<MJAIBridgeAgentIdentityEntity | null> {
334
- // Use the request-scoped provider (multi-provider safe), not the global Metadata.
335
- const entity = await provider.GetEntityObject<MJAIBridgeAgentIdentityEntity>(AGENT_IDENTITY_ENTITY, contextUser);
336
- const loaded = await entity.Load(agentIdentityId);
337
- if (!loaded || !entity.IsActive) {
338
- return null;
339
- }
340
- return entity;
341
- }
342
- }
@@ -1,143 +0,0 @@
1
- /**
2
- * @fileoverview Express wiring for the Teams meetings ingress — the Microsoft Graph change-notification webhook.
3
- *
4
- * One public surface (Graph cannot present an MJ JWT — the subscription validation-token handshake + the
5
- * per-notification `clientState` shared secret are the gate):
6
- * - `POST /meetings/teams/notifications` — the Graph change-notification endpoint. Handles BOTH:
7
- * 1. The **subscription-validation handshake**: when Graph creates/renews a subscription it calls this
8
- * URL with `?validationToken=…` and expects the exact token echoed back as `text/plain` 200.
9
- * 2. **Real call/participant notifications**: each carries a `clientState` verified (constant-time)
10
- * against the secret set on subscription creation, then mapped to the meetings service's roster /
11
- * call-ended drive helpers.
12
- *
13
- * Mirrors the Twilio telephony public-router pattern: mount the router BEFORE the unified auth middleware. The
14
- * validation + notification parsing use the offline-complete, unit-tested helpers from the Teams provider
15
- * package (`validateGraphNotification` / `parseCallNotification`); this module is thin HTTP plumbing over them
16
- * and the {@link TeamsMeetingsService}.
17
- *
18
- * The ACS application-hosted-media socket(s) (the audio plane) are owned by the server's native ACS media
19
- * adapter, which attaches transports to the shared {@link TeamsAcsMediaRegistry} — there is no media WSS here
20
- * (unlike Twilio Media Streams), because ACS app-hosted media is negotiated out-of-band by that adapter.
21
- *
22
- * @module @memberjunction/server/telephony
23
- */
24
-
25
- import { Router, json, type Request, type Response } from 'express';
26
- import { LogError, LogStatus } from '@memberjunction/core';
27
- import {
28
- validateGraphNotification,
29
- parseCallNotification,
30
- type GraphChangeNotification,
31
- } from '@memberjunction/ai-bridge-teams';
32
- import type { TeamsMeetingsConfig } from '../config.js';
33
- import { TeamsAcsMediaRegistry } from './teamsAcsMediaRegistry.js';
34
- import { TeamsMeetingsService } from './TeamsMeetingsService.js';
35
-
36
- /** The mount path for the Teams meetings public router. */
37
- export const TEAMS_MEETINGS_MOUNT_PATH = '/meetings/teams';
38
-
39
- /** The minimal shape of a Graph change-notification POST body (the `value[]` batch). */
40
- interface GraphNotificationBatch {
41
- value?: GraphChangeNotification[];
42
- }
43
-
44
- /**
45
- * Builds the Teams meetings handler: the public Graph change-notification router + the shared ACS media
46
- * registry + the meetings service (returned for observability/tests + so server boot can bind the service to
47
- * the runtime holder and hand the registry to the native ACS media adapter).
48
- */
49
- export function createTeamsMeetingsHandler(
50
- config: TeamsMeetingsConfig,
51
- ): {
52
- publicRouter: Router;
53
- registry: TeamsAcsMediaRegistry;
54
- service: TeamsMeetingsService;
55
- } {
56
- const registry = new TeamsAcsMediaRegistry(config.acsSampleRate);
57
- const service = new TeamsMeetingsService(config, registry);
58
- const publicRouter = Router();
59
-
60
- // Graph posts JSON; it also issues the validation handshake as a query-param GET-like POST. Parse JSON but
61
- // tolerate an empty body on the handshake.
62
- publicRouter.post('/notifications', json({ type: () => true }), (req: Request, res: Response) => {
63
- handleGraphNotification(service, config, req, res);
64
- });
65
-
66
- return { publicRouter, registry, service };
67
- }
68
-
69
- /** Handles the Graph webhook: echo the validation token, else verify clientState + drive the service. */
70
- function handleGraphNotification(
71
- service: TeamsMeetingsService,
72
- config: TeamsMeetingsConfig,
73
- req: Request,
74
- res: Response,
75
- ): void {
76
- const validationToken = readValidationToken(req);
77
- if (validationToken !== undefined && validationToken.length > 0 && !isWellFormedValidationToken(validationToken)) {
78
- // Graph's token is a short ASCII sentence plus a request id. Anything else is not Graph, and the
79
- // echo below must never reflect arbitrary bytes.
80
- LogStatus('[Meetings][Teams] notification rejected: malformed-validation-token');
81
- res.status(400).type('text/plain').send('Rejected.');
82
- return;
83
- }
84
- const batch = (req.body ?? {}) as GraphNotificationBatch;
85
- const notifications = Array.isArray(batch.value) ? batch.value : [];
86
- const clientStates = notifications.map((n) => n.clientState);
87
-
88
- const verdict = validateGraphNotification(validationToken, config.notificationClientState ?? '', clientStates);
89
- if (verdict.Kind === 'validation') {
90
- // The subscription-validation handshake: echo the token verbatim as text/plain 200. The token was
91
- // checked by isWellFormedValidationToken above; nosniff makes sure no client reinterprets the echo.
92
- res.status(200).type('text/plain').set('X-Content-Type-Options', 'nosniff').send(verdict.ValidationToken);
93
- return;
94
- }
95
- if (verdict.Kind === 'reject') {
96
- LogStatus(`[Meetings][Teams] notification rejected: ${verdict.Reason}`);
97
- res.status(verdict.Reason === 'empty-validation-token' ? 400 : 403).type('text/plain').send('Rejected.');
98
- return;
99
- }
100
-
101
- dispatchNotifications(service, notifications);
102
- // Graph requires a fast 202 to acknowledge receipt; processing is fire-and-forget.
103
- res.status(202).end();
104
- }
105
-
106
- /** Maps each Graph call/participant notification to the meetings service's roster / call-ended drive helpers. */
107
- function dispatchNotifications(service: TeamsMeetingsService, notifications: GraphChangeNotification[]): void {
108
- for (const notification of notifications) {
109
- try {
110
- const normalized = parseCallNotification(notification);
111
- if (normalized.state === 'terminated') {
112
- service.DriveCallEnded(normalized.callId);
113
- } else if (normalized.participants.length > 0) {
114
- service.DriveParticipantsUpdated(normalized.callId, normalized.participants);
115
- }
116
- } catch (e) {
117
- LogError(`[Meetings][Teams] failed to process notification: ${e instanceof Error ? e.message : String(e)}`);
118
- }
119
- }
120
- }
121
-
122
- /** Upper bound for a Graph validation token; the real one is roughly a hundred characters. */
123
- const MAX_VALIDATION_TOKEN_LENGTH = 1024;
124
-
125
- /** Graph validation tokens are printable ASCII only. */
126
- const PRINTABLE_ASCII = /^[\x20-\x7E]+$/;
127
-
128
- /** True when the token is something Graph could have sent: bounded length, printable ASCII. */
129
- function isWellFormedValidationToken(token: string): boolean {
130
- return token.length <= MAX_VALIDATION_TOKEN_LENGTH && PRINTABLE_ASCII.test(token);
131
- }
132
-
133
- /** Reads the `?validationToken=…` query param (Graph URL-encodes it), when present. */
134
- function readValidationToken(req: Request): string | undefined {
135
- const raw = req.query?.validationToken;
136
- if (typeof raw === 'string') {
137
- return raw;
138
- }
139
- if (Array.isArray(raw) && typeof raw[0] === 'string') {
140
- return raw[0];
141
- }
142
- return undefined;
143
- }