create-micdrop 0.0.0-stage → 0.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 (66) hide show
  1. package/README.md +61 -2
  2. package/dist/index.js +1315 -0
  3. package/package.json +53 -4
  4. package/templates/expo/App.tsx +123 -0
  5. package/templates/expo/README.md +65 -0
  6. package/templates/expo/_env.example +6 -0
  7. package/templates/expo/_gitignore +7 -0
  8. package/templates/expo/app.json +34 -0
  9. package/templates/expo/babel.config.js +6 -0
  10. package/templates/expo/index.ts +4 -0
  11. package/templates/expo/package.json +39 -0
  12. package/templates/expo/server/index.ts +36 -0
  13. package/templates/expo/server/tsconfig.json +14 -0
  14. package/templates/expo/src/serverUrl.ts +20 -0
  15. package/templates/expo/tsconfig.json +8 -0
  16. package/templates/nextjs/README.md +40 -0
  17. package/templates/nextjs/_env.example +9 -0
  18. package/templates/nextjs/_gitignore +7 -0
  19. package/templates/nextjs/app/CallLoader.tsx +10 -0
  20. package/templates/nextjs/app/VoiceCall.tsx +71 -0
  21. package/templates/nextjs/app/globals.css +45 -0
  22. package/templates/nextjs/app/layout.tsx +16 -0
  23. package/templates/nextjs/app/page.tsx +10 -0
  24. package/templates/nextjs/next.config.ts +5 -0
  25. package/templates/nextjs/package.json +34 -0
  26. package/templates/nextjs/server/index.ts +35 -0
  27. package/templates/nextjs/tsconfig.json +25 -0
  28. package/templates/nextjs/tsconfig.server.json +14 -0
  29. package/templates/node/README.md +48 -0
  30. package/templates/node/_env.example +6 -0
  31. package/templates/node/_gitignore +4 -0
  32. package/templates/node/package.json +21 -0
  33. package/templates/node/src/server.ts +34 -0
  34. package/templates/node/tsconfig.json +14 -0
  35. package/templates/phone/README.md +86 -0
  36. package/templates/phone/_env.example +31 -0
  37. package/templates/phone/_gitignore +5 -0
  38. package/templates/phone/package.json +25 -0
  39. package/templates/phone/src/recording.ts +65 -0
  40. package/templates/phone/src/server.ts +212 -0
  41. package/templates/phone/src/webhooks.ts +88 -0
  42. package/templates/phone/telephony/plivo/env.example +6 -0
  43. package/templates/phone/telephony/plivo/setup.md +7 -0
  44. package/templates/phone/telephony/plivo/telephony.ts +111 -0
  45. package/templates/phone/telephony/telnyx/env.example +8 -0
  46. package/templates/phone/telephony/telnyx/setup.md +9 -0
  47. package/templates/phone/telephony/telnyx/telephony.ts +107 -0
  48. package/templates/phone/telephony/twilio/env.example +6 -0
  49. package/templates/phone/telephony/twilio/setup.md +7 -0
  50. package/templates/phone/telephony/twilio/telephony.ts +98 -0
  51. package/templates/phone/telephony/vonage/env.example +7 -0
  52. package/templates/phone/telephony/vonage/setup.md +15 -0
  53. package/templates/phone/telephony/vonage/telephony.ts +105 -0
  54. package/templates/phone/tsconfig.json +14 -0
  55. package/templates/vite-react/README.md +39 -0
  56. package/templates/vite-react/_env.example +2 -0
  57. package/templates/vite-react/_gitignore +4 -0
  58. package/templates/vite-react/index.html +12 -0
  59. package/templates/vite-react/package.json +36 -0
  60. package/templates/vite-react/src/client/App.tsx +75 -0
  61. package/templates/vite-react/src/client/main.tsx +10 -0
  62. package/templates/vite-react/src/client/styles.css +45 -0
  63. package/templates/vite-react/src/server/index.ts +42 -0
  64. package/templates/vite-react/tsconfig.json +16 -0
  65. package/templates/vite-react/tsconfig.server.json +14 -0
  66. package/templates/vite-react/vite.config.ts +23 -0
@@ -0,0 +1,88 @@
1
+ // What the telephony provider sends the server, and how the server trusts it.
2
+ // https://micdrop.dev/docs/transports/telephony#securing-the-webhooks
3
+
4
+ import { createHmac } from 'node:crypto'
5
+ import type { IncomingHttpHeaders } from 'node:http'
6
+
7
+ export interface WebhookRequest {
8
+ /** The address the provider called, parsed */
9
+ url: URL
10
+ /** The same address, as the provider signed it */
11
+ href: string
12
+ method: string
13
+ headers: IncomingHttpHeaders
14
+ /** The raw body, as the provider signed it */
15
+ body: string
16
+ }
17
+
18
+ export interface WebhookAnswer {
19
+ contentType: string
20
+ body: string
21
+ }
22
+
23
+ /** A route of the provider: answers with a document, or with nothing */
24
+ export type Webhook = (request: WebhookRequest) => Promise<WebhookAnswer | void>
25
+
26
+ /** A call the server places, with `POST /call` */
27
+ export interface OutboundCall {
28
+ /** Number to call, in E.164 format */
29
+ to: string
30
+ /** Number of your account that calls */
31
+ from: string
32
+ /** Public host of this server */
33
+ host: string
34
+ }
35
+
36
+ /**
37
+ * Checks that each webhook comes from the provider, by its signature. On by
38
+ * default, VERIFY_SIGNATURES=false turns it off while you try things out.
39
+ */
40
+ export const verifySignatures = process.env.VERIFY_SIGNATURES !== 'false'
41
+
42
+ /** Reads a header of the request */
43
+ export function header(
44
+ headers: IncomingHttpHeaders,
45
+ name: string
46
+ ): string | undefined {
47
+ const value = headers[name.toLowerCase()]
48
+ return Array.isArray(value) ? value[0] : value
49
+ }
50
+
51
+ /**
52
+ * Reads a variable the signature checks need, and says how to set it when it
53
+ * is missing
54
+ */
55
+ export function signingSecret(name: string, why: string): string {
56
+ const value = process.env[name]
57
+ if (verifySignatures && !value) {
58
+ throw new Error(
59
+ `${name} is missing: ${why}. Set it in .env, or set VERIFY_SIGNATURES=false to try the server without checking the signatures.`
60
+ )
61
+ }
62
+ return value ?? ''
63
+ }
64
+
65
+ /**
66
+ * The path the provider opens the stream of each call at. With signatures
67
+ * checked, it ends with a secret derived from a secret of the account, which
68
+ * only the signed webhooks reveal, so nobody else can open a call. Every
69
+ * instance of the server derives the same one.
70
+ */
71
+ export function securePath(path: string, secret: string): string {
72
+ if (!verifySignatures || !secret) return path
73
+ const token = createHmac('sha256', secret)
74
+ .update(`micdrop-stream:${path}`)
75
+ .digest('hex')
76
+ .slice(0, 32)
77
+ return `${path}/${token}`
78
+ }
79
+
80
+ /** An XML answer */
81
+ export function xml(body: string): WebhookAnswer {
82
+ return { contentType: 'text/xml', body }
83
+ }
84
+
85
+ /** A JSON answer */
86
+ export function json(value: unknown): WebhookAnswer {
87
+ return { contentType: 'application/json', body: JSON.stringify(value) }
88
+ }
@@ -0,0 +1,6 @@
1
+ # Plivo signs its webhooks with the auth token of the account, and the server
2
+ # checks them. With the auth ID, the server also hangs up, transfers and
3
+ # places calls through the API.
4
+ # https://console.plivo.com/dashboard/
5
+ PLIVO_AUTH_ID=
6
+ PLIVO_AUTH_TOKEN=
@@ -0,0 +1,7 @@
1
+ In the [Plivo console](https://console.plivo.com), create a **Voice
2
+ application** whose **Answer URL** is `https://<PUBLIC_HOST>/plivo/answer`,
3
+ HTTP POST, and link your number to it.
4
+
5
+ Put the auth token of the account in `PLIVO_AUTH_TOKEN`: the server refuses
6
+ the webhooks Plivo did not sign. With `PLIVO_AUTH_ID` too, it hangs up,
7
+ transfers and places calls through the API of Plivo.
@@ -0,0 +1,111 @@
1
+ // Plivo carries the calls: the answer URL of the application returns XML that
2
+ // streams the call to this server.
3
+ // https://micdrop.dev/docs/transports/plivo
4
+
5
+ import {
6
+ plivoCall,
7
+ plivoStreamXml,
8
+ plivoTransferXml,
9
+ PlivoTransport,
10
+ TelephonyCalls,
11
+ TelephonyTransport,
12
+ validatePlivoSignature,
13
+ } from '@micdrop/telephony'
14
+ import type { WebSocket } from 'ws'
15
+ import {
16
+ header,
17
+ OutboundCall,
18
+ securePath,
19
+ signingSecret,
20
+ Webhook,
21
+ WebhookRequest,
22
+ xml,
23
+ } from './webhooks'
24
+
25
+ export const provider = 'Plivo'
26
+
27
+ const authId = process.env.PLIVO_AUTH_ID
28
+ const authToken = signingSecret(
29
+ 'PLIVO_AUTH_TOKEN',
30
+ 'Plivo signs its webhooks with the auth token of your account'
31
+ )
32
+ const credentials = authId && authToken ? { authId, authToken } : undefined
33
+
34
+ /** Hang ups, transfers and outbound calls go through the API of Plivo */
35
+ export const canUseApi = !!credentials
36
+
37
+ // The calls under way, to hand them the results of machine detection
38
+ const calls = new TelephonyCalls()
39
+
40
+ /** Where Plivo opens the stream of each call */
41
+ export const streamPath = securePath('/plivo/stream', authToken)
42
+
43
+ /**
44
+ * Whether Plivo signed a request
45
+ * https://www.plivo.com/docs/voice/concepts/signature-validation
46
+ */
47
+ export function isSigned({ href, method, headers, body }: WebhookRequest) {
48
+ return validatePlivoSignature({
49
+ authToken,
50
+ signature: header(headers, 'X-Plivo-Signature-V3'),
51
+ nonce: header(headers, 'X-Plivo-Signature-V3-Nonce'),
52
+ url: href,
53
+ method,
54
+ params: method === 'POST' ? new URLSearchParams(body) : undefined,
55
+ })
56
+ }
57
+
58
+ /** The status a request it did not sign gets */
59
+ export const refusedStatus = 403
60
+
61
+ /** The webhooks Plivo calls, by path */
62
+ export const webhooks: Record<string, Webhook> = {
63
+ // Answer URL of the application, HTTP POST
64
+ '/plivo/answer': async ({ url, body }) => {
65
+ const form = new URLSearchParams(body)
66
+ return xml(
67
+ plivoStreamXml({
68
+ url: `wss://${url.host}${streamPath}`,
69
+ // Handed back by waitForParams when the stream starts
70
+ parameters: { direction: form.get('Direction') ?? 'inbound' },
71
+ })
72
+ )
73
+ },
74
+
75
+ // What a transfer plays: a dial to the number it asked for
76
+ '/plivo/transfer': async ({ url }) =>
77
+ xml(plivoTransferXml({ to: url.searchParams.get('to') ?? '' })),
78
+
79
+ // Result of the machine detection of an outbound call
80
+ '/plivo/amd': async ({ body }) => {
81
+ calls.plivoMachineDetection(new URLSearchParams(body))
82
+ },
83
+ }
84
+
85
+ export function createTransport(socket: WebSocket): TelephonyTransport {
86
+ const host = process.env.PUBLIC_HOST
87
+ return calls.add(
88
+ new PlivoTransport(socket, {
89
+ ...credentials,
90
+ // Plivo only transfers a call to an XML it fetches
91
+ transferUrl: ({ to }) =>
92
+ `https://${host}/plivo/transfer?to=${encodeURIComponent(to)}`,
93
+ })
94
+ )
95
+ }
96
+
97
+ /**
98
+ * Calls a number, and tells a person from a voicemail as soon as it picks up
99
+ * https://micdrop.dev/docs/transports/outbound-calls
100
+ */
101
+ export const placeCall =
102
+ credentials &&
103
+ (({ to, from, host }: OutboundCall) =>
104
+ plivoCall({
105
+ ...credentials,
106
+ to,
107
+ from,
108
+ answerUrl: `https://${host}/plivo/answer`,
109
+ machineDetection: true,
110
+ machineDetectionUrl: `https://${host}/plivo/amd`,
111
+ }))
@@ -0,0 +1,8 @@
1
+ # Answers the calls, transfers them and hangs up through Call Control
2
+ # https://portal.telnyx.com/#/api-keys
3
+ TELNYX_API_KEY=
4
+ # Telnyx signs its webhooks, and the server checks them with this key
5
+ # https://portal.telnyx.com/#/api-keys/public-key
6
+ TELNYX_PUBLIC_KEY=
7
+ # Optional: the Call Control application, for warm transfers and outbound calls
8
+ TELNYX_CONNECTION_ID=
@@ -0,0 +1,9 @@
1
+ In the [Telnyx portal](https://portal.telnyx.com), create a **Call Control**
2
+ application whose webhook is `https://<PUBLIC_HOST>/telnyx/webhook`, and
3
+ assign your number to it. Put an API key in `TELNYX_API_KEY`: the server
4
+ answers each call, transfers it and hangs up through Call Control.
5
+
6
+ Copy the public key of the account (**Keys & Credentials**, **Public Key**) to
7
+ `TELNYX_PUBLIC_KEY`: the server refuses the webhooks Telnyx did not sign. The
8
+ ID of the application, in `TELNYX_CONNECTION_ID`, lets it make warm transfers
9
+ and place calls.
@@ -0,0 +1,107 @@
1
+ // Telnyx carries the calls: its Call Control webhook tells the server about
2
+ // each new call, which the server answers with a stream to itself.
3
+ // https://micdrop.dev/docs/transports/telnyx
4
+
5
+ import {
6
+ callApi,
7
+ TelephonyCalls,
8
+ TelephonyTransport,
9
+ telnyxCall,
10
+ telnyxStreamOptions,
11
+ TelnyxTransport,
12
+ validateTelnyxSignature,
13
+ } from '@micdrop/telephony'
14
+ import type { WebSocket } from 'ws'
15
+ import {
16
+ header,
17
+ OutboundCall,
18
+ securePath,
19
+ signingSecret,
20
+ Webhook,
21
+ WebhookRequest,
22
+ } from './webhooks'
23
+
24
+ export const provider = 'Telnyx'
25
+
26
+ const apiKey = process.env.TELNYX_API_KEY
27
+ if (!apiKey) throw new Error('TELNYX_API_KEY is missing, set it in .env')
28
+ const publicKey = signingSecret(
29
+ 'TELNYX_PUBLIC_KEY',
30
+ 'Telnyx signs its webhooks, and the server checks them with the public key of your account'
31
+ )
32
+ // The Call Control application, for warm transfers and outbound calls
33
+ const connectionId = process.env.TELNYX_CONNECTION_ID
34
+
35
+ /** Transfers go through Call Control, with the API key */
36
+ export const canUseApi = true
37
+
38
+ // The calls under way, to hand them the machine detection and the steps of a
39
+ // warm transfer
40
+ const calls = new TelephonyCalls()
41
+
42
+ /** Where Telnyx opens the stream of each call */
43
+ export const streamPath = securePath('/telnyx/stream', apiKey)
44
+
45
+ /**
46
+ * Whether Telnyx signed a request
47
+ * https://developers.telnyx.com/docs/messaging/messages/receiving-webhooks
48
+ */
49
+ export function isSigned({ headers, body }: WebhookRequest) {
50
+ return validateTelnyxSignature({
51
+ publicKey,
52
+ signature: header(headers, 'telnyx-signature-ed25519'),
53
+ timestamp: header(headers, 'telnyx-timestamp'),
54
+ body,
55
+ })
56
+ }
57
+
58
+ /** The status a request it did not sign gets */
59
+ export const refusedStatus = 403
60
+
61
+ /** The webhooks Telnyx calls, by path */
62
+ export const webhooks: Record<string, Webhook> = {
63
+ // Webhook of the Call Control application
64
+ '/telnyx/webhook': async ({ url, body }) => {
65
+ const event = JSON.parse(body || '{}')
66
+ // Machine detection and warm transfers report here
67
+ if (calls.telnyxWebhook(event)) return
68
+ const { data } = event
69
+ if (data?.event_type !== 'call.initiated') return
70
+ if (data.payload.direction !== 'incoming') return
71
+ // Answered without holding the webhook, which Telnyx wants quickly
72
+ callApi(
73
+ 'Telnyx answer',
74
+ `https://api.telnyx.com/v2/calls/${encodeURIComponent(data.payload.call_control_id)}/actions/answer`,
75
+ {
76
+ method: 'POST',
77
+ headers: {
78
+ Authorization: `Bearer ${apiKey}`,
79
+ 'Content-Type': 'application/json',
80
+ },
81
+ body: JSON.stringify(
82
+ telnyxStreamOptions({ url: `wss://${url.host}${streamPath}` })
83
+ ),
84
+ }
85
+ ).catch((error) => console.error(error))
86
+ },
87
+ }
88
+
89
+ export function createTransport(socket: WebSocket): TelephonyTransport {
90
+ return calls.add(new TelnyxTransport(socket, { apiKey, connectionId }))
91
+ }
92
+
93
+ /**
94
+ * Calls a number, and tells a person from a voicemail as soon as it picks up
95
+ * https://micdrop.dev/docs/transports/outbound-calls
96
+ */
97
+ export const placeCall = connectionId
98
+ ? ({ to, from, host }: OutboundCall) =>
99
+ telnyxCall({
100
+ apiKey,
101
+ connectionId,
102
+ to,
103
+ from,
104
+ url: `wss://${host}${streamPath}`,
105
+ machineDetection: 'greeting_end',
106
+ })
107
+ : undefined
@@ -0,0 +1,6 @@
1
+ # Twilio signs its webhooks with the auth token of the account, and the server
2
+ # checks them. With the account SID, the server also transfers and places
3
+ # calls through the API.
4
+ # https://console.twilio.com
5
+ TWILIO_ACCOUNT_SID=
6
+ TWILIO_AUTH_TOKEN=
@@ -0,0 +1,7 @@
1
+ In the [Twilio console](https://console.twilio.com), open your number, and
2
+ under **Voice configuration** set **A call comes in** to the webhook
3
+ `https://<PUBLIC_HOST>/twilio/voice`, HTTP POST.
4
+
5
+ Put the auth token of the account in `TWILIO_AUTH_TOKEN`: the server refuses
6
+ the webhooks it did not sign. With `TWILIO_ACCOUNT_SID` too, it transfers and
7
+ places calls through the REST API of Twilio.
@@ -0,0 +1,98 @@
1
+ // Twilio carries the calls: its voice webhook answers with TwiML that streams
2
+ // the call to this server.
3
+ // https://micdrop.dev/docs/transports/twilio
4
+
5
+ import {
6
+ TelephonyCalls,
7
+ TelephonyTransport,
8
+ twilioCall,
9
+ twilioStreamTwiml,
10
+ TwilioTransport,
11
+ validateTwilioSignature,
12
+ } from '@micdrop/telephony'
13
+ import type { WebSocket } from 'ws'
14
+ import {
15
+ header,
16
+ OutboundCall,
17
+ securePath,
18
+ signingSecret,
19
+ Webhook,
20
+ WebhookRequest,
21
+ xml,
22
+ } from './webhooks'
23
+
24
+ export const provider = 'Twilio'
25
+
26
+ const accountSid = process.env.TWILIO_ACCOUNT_SID
27
+ const authToken = signingSecret(
28
+ 'TWILIO_AUTH_TOKEN',
29
+ 'Twilio signs its webhooks with the auth token of your account'
30
+ )
31
+ const credentials =
32
+ accountSid && authToken ? { accountSid, authToken } : undefined
33
+
34
+ /** Transfers and outbound calls go through the REST API of Twilio */
35
+ export const canUseApi = !!credentials
36
+
37
+ // The calls under way, to hand them the results of machine detection
38
+ const calls = new TelephonyCalls()
39
+
40
+ /** Where Twilio opens the stream of each call */
41
+ export const streamPath = securePath('/twilio/stream', authToken)
42
+
43
+ /**
44
+ * Whether Twilio signed a request
45
+ * https://www.twilio.com/docs/usage/security#validating-requests
46
+ */
47
+ export function isSigned({ href, headers, body }: WebhookRequest) {
48
+ return validateTwilioSignature({
49
+ authToken,
50
+ signature: header(headers, 'X-Twilio-Signature'),
51
+ url: href,
52
+ params: new URLSearchParams(body),
53
+ })
54
+ }
55
+
56
+ /** The status a request it did not sign gets */
57
+ export const refusedStatus = 403
58
+
59
+ /** The webhooks Twilio calls, by path */
60
+ export const webhooks: Record<string, Webhook> = {
61
+ // Voice webhook of the number, HTTP POST
62
+ '/twilio/voice': async ({ url, body }) => {
63
+ const form = new URLSearchParams(body)
64
+ return xml(
65
+ twilioStreamTwiml({
66
+ url: `wss://${url.host}${streamPath}`,
67
+ // Handed back by waitForParams when the stream starts
68
+ parameters: { caller: form.get('From') ?? '' },
69
+ })
70
+ )
71
+ },
72
+
73
+ // Result of the machine detection of an outbound call
74
+ '/twilio/amd': async ({ body }) => {
75
+ calls.twilioMachineDetection(new URLSearchParams(body))
76
+ },
77
+ }
78
+
79
+ export function createTransport(socket: WebSocket): TelephonyTransport {
80
+ return calls.add(new TwilioTransport(socket, credentials))
81
+ }
82
+
83
+ /**
84
+ * Calls a number, and tells a person from a voicemail as soon as it picks up
85
+ * https://micdrop.dev/docs/transports/outbound-calls
86
+ */
87
+ export const placeCall =
88
+ credentials &&
89
+ (({ to, from, host }: OutboundCall) =>
90
+ twilioCall({
91
+ ...credentials,
92
+ to,
93
+ from,
94
+ url: `wss://${host}${streamPath}`,
95
+ parameters: { direction: 'outbound' },
96
+ machineDetection: true,
97
+ machineDetectionUrl: `https://${host}/twilio/amd`,
98
+ }))
@@ -0,0 +1,7 @@
1
+ # Vonage signs its webhooks with the signature secret of the account, and the
2
+ # server checks them
3
+ # https://dashboard.nexmo.com/settings
4
+ VONAGE_SIGNATURE_SECRET=
5
+ # Optional: the application and its private key, to transfer and place calls
6
+ VONAGE_APPLICATION_ID=
7
+ VONAGE_PRIVATE_KEY_PATH=
@@ -0,0 +1,15 @@
1
+ In the [Vonage dashboard](https://dashboard.nexmo.com), create an application
2
+ with **Voice** turned on. Set its **Answer URL** to
3
+ `https://<PUBLIC_HOST>/vonage/answer`, HTTP GET, and its **Event URL** to
4
+ `https://<PUBLIC_HOST>/vonage/event`, HTTP POST. Link your number to the
5
+ application.
6
+
7
+ Copy the signature secret of the account, in its
8
+ [settings](https://dashboard.nexmo.com/settings), to `VONAGE_SIGNATURE_SECRET`:
9
+ the server refuses the webhooks Vonage did not sign. Applications created
10
+ before Vonage signed its webhooks by default need **Use signed webhooks**
11
+ turned on in their Voice settings.
12
+
13
+ With `VONAGE_APPLICATION_ID` and the path of the private key of the
14
+ application in `VONAGE_PRIVATE_KEY_PATH`, the server also transfers and places
15
+ calls through the Voice API.
@@ -0,0 +1,105 @@
1
+ // Vonage carries the calls: the answer webhook of the application returns an
2
+ // NCCO that connects the call to a WebSocket of this server.
3
+ // https://micdrop.dev/docs/transports/vonage
4
+
5
+ import { readFileSync } from 'node:fs'
6
+ import {
7
+ TelephonyCalls,
8
+ TelephonyTransport,
9
+ validateVonageSignature,
10
+ vonageCall,
11
+ vonageConnectNcco,
12
+ VonageTransport,
13
+ } from '@micdrop/telephony'
14
+ import type { WebSocket } from 'ws'
15
+ import {
16
+ header,
17
+ json,
18
+ OutboundCall,
19
+ securePath,
20
+ signingSecret,
21
+ Webhook,
22
+ WebhookRequest,
23
+ } from './webhooks'
24
+
25
+ export const provider = 'Vonage'
26
+
27
+ const signatureSecret = signingSecret(
28
+ 'VONAGE_SIGNATURE_SECRET',
29
+ 'Vonage signs its webhooks with the signature secret of your account'
30
+ )
31
+ // The application and its private key, to transfer and place calls
32
+ const applicationId = process.env.VONAGE_APPLICATION_ID
33
+ const privateKeyPath = process.env.VONAGE_PRIVATE_KEY_PATH
34
+ const credentials =
35
+ applicationId && privateKeyPath
36
+ ? { applicationId, privateKey: readFileSync(privateKeyPath, 'utf8') }
37
+ : undefined
38
+
39
+ /** Transfers and outbound calls go through the Voice API */
40
+ export const canUseApi = !!credentials
41
+
42
+ // The calls under way, to hand them the results of machine detection
43
+ const calls = new TelephonyCalls()
44
+
45
+ /** Where Vonage opens the stream of each call */
46
+ export const streamPath = securePath('/vonage/stream', signatureSecret)
47
+
48
+ /**
49
+ * Whether Vonage signed a request
50
+ * https://developer.vonage.com/en/getting-started/concepts/webhooks#decoding-signed-webhooks
51
+ */
52
+ export function isSigned({ headers, body }: WebhookRequest) {
53
+ return validateVonageSignature({
54
+ signatureSecret,
55
+ authorization: header(headers, 'Authorization'),
56
+ body,
57
+ })
58
+ }
59
+
60
+ /**
61
+ * The status a request it did not sign gets. Vonage may send an unsigned
62
+ * callback after an internal error, and tries again on a 5xx, signed this time
63
+ * https://developer.vonage.com/en/voice/voice-api/webhook-reference#signed-webhooks
64
+ */
65
+ export const refusedStatus = 503
66
+
67
+ /** The webhooks Vonage calls, by path */
68
+ export const webhooks: Record<string, Webhook> = {
69
+ // Answer URL of the application, HTTP GET
70
+ '/vonage/answer': async ({ url }) =>
71
+ json(
72
+ vonageConnectNcco({
73
+ url: `wss://${url.host}${streamPath}`,
74
+ // uuid, from and to, handed to the transport as transport.call
75
+ call: Object.fromEntries(url.searchParams),
76
+ eventUrl: `https://${url.host}/vonage/event`,
77
+ })
78
+ ),
79
+
80
+ // Event URL of the application: the status of each call, and the result
81
+ // of machine detection
82
+ '/vonage/event': async ({ body }) => {
83
+ calls.vonageEvent(JSON.parse(body || '{}'))
84
+ },
85
+ }
86
+
87
+ export function createTransport(socket: WebSocket): TelephonyTransport {
88
+ return calls.add(new VonageTransport(socket, credentials))
89
+ }
90
+
91
+ /**
92
+ * Calls a number, and tells a person from a voicemail as soon as it picks up
93
+ * https://micdrop.dev/docs/transports/outbound-calls
94
+ */
95
+ export const placeCall =
96
+ credentials &&
97
+ (({ to, from, host }: OutboundCall) =>
98
+ vonageCall({
99
+ ...credentials,
100
+ to,
101
+ from,
102
+ url: `wss://${host}${streamPath}`,
103
+ machineDetection: true,
104
+ eventUrl: `https://${host}/vonage/event`,
105
+ }))
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "noEmit": true
12
+ },
13
+ "include": ["src"]
14
+ }
@@ -0,0 +1,39 @@
1
+ # {{name}}
2
+
3
+ A voice AI app built with [Micdrop](https://micdrop.dev): a React page built
4
+ with Vite, and a Fastify server that runs the AI over a WebSocket.
5
+
6
+ - [`src/client/App.tsx`](./src/client/App.tsx) starts the call and draws its state
7
+ - [`src/server/index.ts`](./src/server/index.ts) runs each call
8
+ - [`src/server/ai.ts`](./src/server/ai.ts) builds the AI providers
9
+
10
+ ## Run it
11
+
12
+ Fill `.env` with your keys, then:
13
+
14
+ ```bash
15
+ {{run:dev}}
16
+ ```
17
+
18
+ Open http://localhost:5173, start a call and talk. Say goodbye, and the
19
+ assistant hangs up.
20
+
21
+ ## In production
22
+
23
+ `{{run:build}}` writes the page to `dist`, for any static host. `{{run:start}}`
24
+ runs the Fastify server, which answers the calls on `/call`. Serve both behind
25
+ one domain, or point `SERVER_URL` in `src/client/App.tsx` at the server.
26
+
27
+ ## AI providers
28
+
29
+ {{providers}}
30
+
31
+ Swap any of them in `src/server/ai.ts`. The [providers page](https://micdrop.dev/docs/providers)
32
+ lists them all.
33
+
34
+ ## Learn more
35
+
36
+ - [React hooks](https://micdrop.dev/docs/client/react-hooks)
37
+ - [Turn detection](https://micdrop.dev/docs/client/turn-detection): let the user pause mid sentence
38
+ - [Tools](https://micdrop.dev/docs/server/tools): let the assistant call your functions
39
+ - [Auth and parameters](https://micdrop.dev/docs/server/auth-and-parameters): check who connects
@@ -0,0 +1,2 @@
1
+ # Port of the Fastify server
2
+ PORT=3001
@@ -0,0 +1,4 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ .DS_Store
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>{{name}}</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/client/main.tsx"></script>
11
+ </body>
12
+ </html>