Repository navigation
Expand file tree
/
Copy pathFormstepTrigger.node.ts
More file actions
304 lines (279 loc) · 12.2 KB
/
Copy pathFormstepTrigger.node.ts
File metadata and controls
304 lines (279 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import type {
IDataObject,
IHookFunctions,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
IWebhookFunctions,
IWebhookResponseData,
} from 'n8n-workflow'
import { NodeConnectionTypes, NodeOperationError } from 'n8n-workflow'
import {
FORMSTEP_IDLE_WINDOW_OPTIONS,
FORMSTEP_WEBHOOK_EVENTS,
isFormstepIdleWindow,
type FormstepIdleWindow,
type FormstepWebhookEvent,
} from './constants'
import { authenticationProperties, formstepCredentials } from './Authentication'
import type { ListResponse } from './FormstepCatalog'
import { formLocatorProperty, getForms, listSearch } from './FormstepMethods'
import { createFormstepWebhookSecret, verifyFormstepWebhookSignature } from './FormstepWebhookSignature'
import { formstepApiRequest } from './GenericFunctions'
import { isNodeError } from './NodeErrors'
/**
* The events the trigger subscribes to, default first. Each option's action
* doubles as the node's subtitle, so the two can never disagree.
*/
const EVENT_OPTIONS: INodePropertyOptions[] = [
{
name: 'Public Link Submission Created',
value: FORMSTEP_WEBHOOK_EVENTS.submissionCreated,
description:
"Runs when a respondent submits the selected form through its public link (event type submission.completed). An edit after submit runs 'Public Link Submission Updated'; a completed request runs 'Request Completed'.",
},
{
name: 'Public Link Submission Updated',
value: FORMSTEP_WEBHOOK_EVENTS.submissionUpdated,
description:
'Runs when a respondent edits a public-link submission they already sent (event type submission.updated). The form must allow editing after submit.',
},
{
name: 'Public Link Submission Abandoned',
value: FORMSTEP_WEBHOOK_EVENTS.submissionAbandoned,
description:
'Runs when a respondent leaves the selected form, opened through its public link, without submitting it. Needs partial-submission tracking on the workspace.',
},
{
name: 'Request Completed',
value: FORMSTEP_WEBHOOK_EVENTS.requestCompleted,
description:
'Runs when a recipient completes a request for the selected form, with the answers and the outcome (event type request.completed)',
},
{
name: 'Request Expired',
value: FORMSTEP_WEBHOOK_EVENTS.requestExpired,
description: 'Runs when a request for the selected form reaches its expiry without being completed',
},
{
name: 'Request Canceled',
value: FORMSTEP_WEBHOOK_EVENTS.requestCanceled,
description: 'Runs when a request for the selected form is canceled, with the reason when one was given',
},
].map((option) => ({ ...option, action: `On ${option.name.toLowerCase()}` }))
const EVENT_SUBTITLE = `={{ (${JSON.stringify(
Object.fromEntries(EVENT_OPTIONS.map((option) => [option.value, option.action]))
)})[$parameter["event"]] }}`
/** One row of `webhooks.list`. */
interface WebhookSubscription {
subscriptionId: string
targetUrl: string
provider: string
eventType: FormstepWebhookEvent
idleWindow?: FormstepIdleWindow
}
/** What this node wants registered with Formstep, read from its parameters. */
interface Registration {
webhookUrl: string
formId: string
eventType: FormstepWebhookEvent
idleWindow?: FormstepIdleWindow
}
/** The registration the node's parameters describe, or null while the node is not configured. */
function readRegistration(context: IHookFunctions): Registration | null {
const webhookUrl = context.getNodeWebhookUrl('default')
// A dropdown up to version 1.1, a resource locator after that; `extractValue` reads both.
const formId = context.getNodeParameter('formId', '', { extractValue: true }) as string
if (!webhookUrl || !formId) return null
const eventType = context.getNodeParameter('event') as FormstepWebhookEvent
if (eventType !== FORMSTEP_WEBHOOK_EVENTS.submissionAbandoned) return { webhookUrl, formId, eventType }
const idleWindow = context.getNodeParameter('idleWindow')
if (!isFormstepIdleWindow(idleWindow)) {
const allowed = FORMSTEP_IDLE_WINDOW_OPTIONS.map((option) => option.value).join(', ')
throw new NodeOperationError(context.getNode(), `'Consider Abandoned After' must be one of: ${allowed}`, {
description: "Pick one of the listed durations under 'Consider Abandoned After'.",
})
}
return { webhookUrl, formId, eventType, idleWindow }
}
/** A subscription this node's URL and event own, whatever its idle window or secret. */
function isOwnSubscription(subscription: WebhookSubscription, registration: Registration): boolean {
if (subscription.provider !== 'n8n') return false
if (subscription.targetUrl !== registration.webhookUrl) return false
return subscription.eventType === registration.eventType
}
/** The subscription this node registered last, still verifiable and still describing the same event. */
function isCurrentRegistration(subscription: WebhookSubscription, registration: Registration, webhookData: IDataObject): boolean {
if (subscription.subscriptionId !== webhookData.subscriptionId) return false
if (typeof webhookData.webhookSecret !== 'string') return false
return subscription.idleWindow === registration.idleWindow
}
/**
* Formstep delivers events to public HTTPS URLs only. An n8n without a public
* address hands out http://localhost URLs, which Formstep refuses with a bare
* VALIDATION_ERROR; say which n8n settings build the URL instead.
*/
function assertHttpsWebhookUrl(context: IHookFunctions, webhookUrl: string): void {
if (webhookUrl.startsWith('https://')) return
throw new NodeOperationError(context.getNode(), `Formstep sends events to HTTPS addresses only, and this webhook URL is ${webhookUrl}`, {
description:
"Set n8n's WEBHOOK_URL (published workflows) and N8N_EDITOR_BASE_URL ('Execute step') to its public HTTPS address, restart n8n and try again. See https://docs.formstep.io/guides/n8n/install-the-node/#public-address",
})
}
function clearWebhookRegistration(webhookData: IDataObject): void {
delete webhookData.subscriptionId
delete webhookData.webhookSecret
}
export class FormstepTrigger implements INodeType {
description: INodeTypeDescription = {
displayName: 'Formstep Trigger',
name: 'formstepTrigger',
icon: { light: 'file:formstep-logo.svg', dark: 'file:formstep-logo.dark.svg' },
group: ['trigger'],
version: [1, 1.1, 1.2],
defaultVersion: 1.2,
subtitle: EVENT_SUBTITLE,
description:
'Starts the workflow when a Formstep request is completed, expires or is canceled, or when a respondent submits a form through its public link',
defaults: {
name: 'Formstep Trigger',
},
inputs: [],
outputs: [NodeConnectionTypes.Main],
credentials: formstepCredentials,
webhooks: [
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
path: 'formstep',
},
],
triggerPanel: {
header: 'Listening for Formstep events',
executionsHelp: {
inactive:
'While building the workflow, click <em>Execute step</em> and submit the form within two minutes, or complete a request. Expired, canceled and abandoned events arrive later: publish the workflow and check Executions.',
active:
'Events for the selected form trigger this workflow. The webhook stays registered while the workflow is published.',
},
activationHint: 'Publish the workflow to register the webhook with Formstep. Unpublishing removes it.',
},
// Version 1.1 changes only the default Authentication, to an API key. Version 1.2 changes only how the form is picked.
properties: [
...authenticationProperties(1.1),
{
displayName: 'Form Name or ID',
name: 'formId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getForms',
},
displayOptions: { show: { '@version': [{ _cnd: { lt: 1.2 } }] } },
default: '',
required: true,
description: 'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
},
formLocatorProperty('The form whose events start this workflow', { show: { '@version': [{ _cnd: { gte: 1.2 } }] } }),
{
displayName: 'Event',
name: 'event',
type: 'options',
options: EVENT_OPTIONS,
default: 'submission_created',
description:
"Event to subscribe to. Public link submission events cover the public link only; a completed request runs 'Request Completed' instead. Abandoned needs partial-submission tracking.",
},
{
displayName: 'Consider Abandoned After',
name: 'idleWindow',
type: 'options',
displayOptions: {
show: {
event: [FORMSTEP_WEBHOOK_EVENTS.submissionAbandoned],
},
},
options: [...FORMSTEP_IDLE_WINDOW_OPTIONS],
default: '12h',
required: true,
description:
'Runs after the submission has no saved changes for this long. The hourly sweep can add up to one hour.',
},
],
}
methods = { loadOptions: { getForms }, listSearch: { searchForms: listSearch.searchForms } }
webhookMethods = {
default: {
/**
* True when Formstep still holds the subscription this node registered.
* Any other subscription for this node's URL and event — one with no
* stored secret, a different idle window, or a stale duplicate — is
* removed rather than left as a second, unverifiable delivery path.
*/
async checkExists(this: IHookFunctions): Promise<boolean> {
const registration = readRegistration(this)
if (!registration) return false
const webhookData = this.getWorkflowStaticData('node')
const { items } = await formstepApiRequest<ListResponse<WebhookSubscription>>(this, 'webhooks.list', {
formId: registration.formId,
})
let current = false
for (const subscription of items) {
if (!isOwnSubscription(subscription, registration)) continue
if (isCurrentRegistration(subscription, registration, webhookData)) {
current = true
continue
}
await formstepApiRequest(this, 'webhooks.delete', { subscriptionId: subscription.subscriptionId })
}
if (!current) clearWebhookRegistration(webhookData)
return current
},
async create(this: IHookFunctions): Promise<boolean> {
const registration = readRegistration(this)
if (!registration) return false
assertHttpsWebhookUrl(this, registration.webhookUrl)
const webhookSecret = createFormstepWebhookSecret()
const created = await formstepApiRequest<{ subscriptionId: string }>(this, 'webhooks.create', {
formId: registration.formId,
targetUrl: registration.webhookUrl,
provider: 'n8n',
eventType: registration.eventType,
...(registration.idleWindow ? { idleWindow: registration.idleWindow } : {}),
signingSecret: webhookSecret,
})
const webhookData = this.getWorkflowStaticData('node')
webhookData.subscriptionId = created.subscriptionId
webhookData.webhookSecret = webhookSecret
return true
},
async delete(this: IHookFunctions): Promise<boolean> {
const webhookData = this.getWorkflowStaticData('node')
const subscriptionId = webhookData.subscriptionId
if (typeof subscriptionId !== 'string') {
clearWebhookRegistration(webhookData)
return true
}
try {
await formstepApiRequest(this, 'webhooks.delete', { subscriptionId })
} catch (error: unknown) {
// Already gone on the Formstep side is the outcome we wanted.
if (!isNodeError(error) || error.name !== 'NodeApiError' || error.httpCode !== '404') return false
}
clearWebhookRegistration(webhookData)
return true
},
},
}
/** One item per delivery: the Formstep event envelope, untouched, once its signature checks out. */
async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
if (!verifyFormstepWebhookSignature(this)) {
this.getResponseObject().status(401).send('Unauthorized').end()
return { noWebhookResponse: true }
}
const body: IDataObject = this.getBodyData()
return {
workflowData: [this.helpers.returnJsonArray(body)],
}
}
}