diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 163adae8..4de0d351 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -25,6 +25,7 @@ on: - 'conf.py' - 'requirements.txt' - 'tests/**' + - 'examples/n8n/**' permissions: contents: read @@ -57,6 +58,19 @@ jobs: - name: Test version selection navigation run: node --test tests/js/*.test.mjs + - name: Test n8n workflow graph, Code nodes and WebDAV discovery + run: node --test examples/n8n/test-workflow.mjs + + - name: Import workflow using real n8n 2.47.3 + run: | + mkdir -p "$RUNNER_TEMP/libresign-n8n-ci" + chmod 777 "$RUNNER_TEMP/libresign-n8n-ci" + docker run --rm \ + -v "$PWD/examples/n8n:/work:ro" \ + -v "$RUNNER_TEMP/libresign-n8n-ci:/home/node/.n8n" \ + docker.n8n.io/n8nio/n8n:2.47.3 import:workflow \ + --input=/work/libresign-external-signature.json + - name: Build every Sphinx version independently run: python -m versioning.build --output _build diff --git a/examples/n8n/README.md b/examples/n8n/README.md index ab14df56..ffd54fa8 100644 --- a/examples/n8n/README.md +++ b/examples/n8n/README.md @@ -4,11 +4,14 @@ # LibreSign + n8n: external signer (C2) This is an **importable n8n workflow** using public LibreSign OCS v1 requests and -an authenticated Nextcloud WebDAV download. It creates a **single-document, -one-email-signer** request, asks LibreSign to send the invitation, polls a -bounded number of times, and downloads an **already identified, authorized** -signed PDF. No custom n8n node, callback URL, direct database access, or -new LibreSign endpoint is needed. +authenticated Nextcloud WebDAV discovery and download. It creates a +**single-document, one-email-signer** request, asks LibreSign to send the +invitation, polls a bounded number of times, then identifies the signed PDF +in the requester's own Nextcloud Files folder. It matches the OCS source +``nodeId`` to WebDAV ``oc:fileid`` and requires **exactly one other PDF in +that folder** before downloading the returned DAV path. No filename guess, +custom n8n node, callback URL, database access, or new LibreSign endpoint is +needed. Ambiguous or inaccessible files stop the workflow. [Import the workflow](libresign-external-signature.json). For equivalent cURL and PHP flows, reuse the existing @@ -58,13 +61,14 @@ experimental policy fields. 3. An n8n installation providing the built-in Manual Trigger, Code, HTTP Request, Loop Over Items, If, and Wait nodes. No community node, npm package, or public incoming webhook is required. -4. For the **final download**, determine the actual signed PDF's *relative* - path under the integration account's authenticated WebDAV folder. - Discover it with Nextcloud Files or an authenticated WebDAV `PROPFIND`. - **Do not assume that the uploaded filename is the signed filename** or - derive a path from a LibreSign file ID, UUID, node ID, or invitation link. - When the path is unknown in advance, test request/notification/status first - and configure the final download only after the path is verified. +4. For **automatic final download**, the integration account needs to list + its ``LibreSign/`` folder (the default local LibreSign file location), read + the request's original PDF, and read the completed PDF. The example uses + **authenticated WebDAV `PROPFIND`** to identify one eligible PDF sibling. + It does not construct a filename from any LibreSign ID, UUID or invitation + link. If the installation uses a custom folder, grants different access, + or keeps more than one non-source PDF beside the original, discovery will + stop for review rather than download an arbitrary file. ## Import and configure @@ -73,14 +77,15 @@ experimental policy fields. It is disabled by default and begins with a **Manual Trigger**. 2. Create a **Generic HTTP Basic Auth** credential in n8n: username is the Nextcloud integration account; password is its **App Password**. Associate - *that same credential* with these four HTTP Request nodes: **Create request**, - **Invite signer once**, **Get file state**, **Download signed PDF**. + *that same credential* with all six HTTP Request nodes: **Create request**, + **Invite signer once**, **Get file state**, **List LibreSign folders**, + **Inspect folder files**, **Download signed PDF**. Credentials are deliberately **not** bound or exported in the JSON. 3. Edit only the public parameters in the **Configure** Code node: `baseUrl` (HTTPS Nextcloud origin, without `/ocs`), `version` (`13`, `14`, `15`, or `main`), `integrationUser`, `signerEmail` (a real **controlled test - inbox**), `signedPdfPath` (verified path relative to the DAV user root), - `maxAttempts`, and `waitSeconds`. Replace `pdfBase64` when testing your own + inbox**), `maxSearchFolders` (limit on the number of request folders scanned, + default 50, maximum 250), `maxAttempts`, and `waitSeconds`. Replace `pdfBase64` when testing your own *synthetic* PDF. The built-in sample is a one-page PDF without personal data. 4. Ensure Nextcloud's email/notification background jobs work. Click **Execute Workflow**. Open the controlled mailbox, follow the **LibreSign-issued** @@ -100,10 +105,15 @@ POST /notify/signers (one explicit invitation request, not delive -> accepted for processing GET /file/list?details=1&fileIds[]=ID (13/14/15; main uses details=true) -> file status 0/1/2: wait and retry, at most maxAttempts - -> file status 3: authorized WebDAV GET using a verified path + -> file status 3: authorized WebDAV discovery, then authenticated GET -> file status 4, unknown status, OCS/HTTP error, or timeout: stop -GET /remote.php/dav/files/USER/VERIFIED-PATH (authenticated, same HTTPS origin) - -> binary field signedPdf, PDF header check +PROPFIND /remote.php/dav/files/USER/LibreSign/ (authenticated, Depth: 1) + -> list request folders; reject unbounded or unsafe paths +PROPFIND /remote.php/dav/files/USER/LibreSign/REQUEST-FOLDER/ (authenticated, Depth: 1) + -> find the original PDF by comparing OCS source nodeId to DAV oc:fileid + -> require exactly one other non-empty PDF sibling and keep its actual DAV href +GET ACTUAL-AUTHORIZED-DAV-HREF (authenticated, same HTTPS origin) + -> binary field signedPdf, PDF header check; independent PDF signature verification ``` A `fileId` is **not** the file UUID or a signer-scoped signing UUID. The @@ -136,12 +146,18 @@ checking child documents and each required signer. - The workflow only lets LibreSign send invitations. `POST /notify/signers` being accepted is **not** SMTP delivery or receipt confirmation; do not send your own guessed signer URL or blindly re-send notifications. -- The workflow does **not** promise a guaranteed final signed-file path or - generic `GET /file/download/{id}`: no such universal authorized endpoint - is established by the reviewed public OpenAPI. Use WebDAV only with file - read rights and the **verified completed file** path. `GET - /file/validate/file_id/{fileId}` supplies authorization-checked metadata, - not a PDF file download or automatic certificate-chain validation. +- The workflow does **not** promise a universal file-ID download endpoint or + signed filename: no such contract is established in the reviewed LibreSign + OpenAPI. After checking status ``3``, it lists the **requester's own** DAV + folder, matches the OCS source node ID to the returned DAV ``oc:fileid``, + and downloads only an **unambiguous, non-empty PDF sibling** under the same + folder. It stops when DAV access is denied, the folder cannot be found, the + root contains more than `maxSearchFolders` subfolders, or there are zero or + multiple candidate PDFs. This intentionally narrow discovery is **not a + generalized resolver** for envelope/parallel signers, custom storage, or + unlimited folders. It does not validate the PDF's cryptographic signature. + `GET /file/validate/file_id/{fileId}` supplies authorization-checked + metadata, not a PDF binary or automatic certificate-chain validation. ## Development: optional native event receiver @@ -171,11 +187,20 @@ verification; they are not represented as already tested here. ## Verification and evidence `node --test examples/n8n/test-workflow.mjs` runs dependency-free, synthetic -contract tests for the export, Code-node success/failure cases, status -transitions and authorization boundary. This tests **our export and logic**, -not n8n runtime import, a live Nextcloud, SMTP delivery, legal identity, -cryptographic signing, or a real WebDAV completion path. Execute that E2E -scenario in a disposable installation before using this in any real workflow. +contract tests for the export, Code-node success/failure cases, WebDAV +folder and file-ID correlation, ambiguity rejection, status transitions and +authorization boundaries. This tests **the export and its logic**, not n8n +runtime import, a live Nextcloud, SMTP delivery, legal identity, or +cryptographic signing. The discovery and final GET were also executed on a +**disposable Nextcloud 35 / LibreSign 15.0.12 / n8n 2.47.3 installation** with +one already signed synthetic PDF: the 21-node graph successfully retrieved +47,799 PDF bytes through authenticated WebDAV; `pdfsig` independently +confirmed a cryptographically valid signature from the test-only CA. The +creation, invitation, SMTP, external signing and polling were verified on +that installation in a separate earlier run. This is **not** an uninterrupted +end-to-end n8n run nor evidence of runtime compatibility with releases 13, 14, +or development. Revalidate in the target disposable release before using it +for live documents. References: [LibreSign stable API guide](https://docs.libresign.coop/stable/developer_manual/api/external-email-signers.html), [stable integration lifecycle](https://docs.libresign.coop/stable/developer_manual/integration/lifecycle.html), diff --git a/examples/n8n/libresign-external-signature.json b/examples/n8n/libresign-external-signature.json index 294877fa..16d0db68 100644 --- a/examples/n8n/libresign-external-signature.json +++ b/examples/n8n/libresign-external-signature.json @@ -25,7 +25,7 @@ ], "parameters": { "mode": "runOnceForAllItems", - "jsCode": "// Edit these example values before running. Never add a password here.\nreturn [{ json: {\n baseUrl: 'https://nextcloud.example.invalid',\n version: '15', // '13', '14', '15' or 'main' (development)\n integrationUser: 'integration-user',\n signerEmail: 'signer@example.invalid', // replace with a mailbox YOU control\n signedPdfPath: 'Contracts/synthetic-n8n-signed.pdf', // verified relative WebDAV path, not an ID\n maxAttempts: 20,\n waitSeconds: 30,\n pdfBase64: 'JVBERi0xLjQKJVN5bnRoZXRpYyBMaWJyZVNpZ24gbjhuIGZpeHR1cmUKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvUmVzb3VyY2VzIDw8IC9Gb250IDw8IC9GMSA0IDAgUiA+PiA+PiAvQ29udGVudHMgNSAwIFIgPj4KZW5kb2JqCjQgMCBvYmoKPDwgL1R5cGUgL0ZvbnQgL1N1YnR5cGUgL1R5cGUxIC9CYXNlRm9udCAvSGVsdmV0aWNhID4+CmVuZG9iago1IDAgb2JqCjw8IC9MZW5ndGggODMgPj4Kc3RyZWFtCkJUIC9GMSAxNiBUZiA3MiA3MjAgVGQgKFN5bnRoZXRpYyBMaWJyZVNpZ24gbjhuIGNvbnRyYWN0IC0gbm8gcGVyc29uYWwgZGF0YSkgVGogRVQKZW5kc3RyZWFtCmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwNDIgMDAwMDAgbiAKMDAwMDAwMDA5MSAwMDAwMCBuIAowMDAwMDAwMTQ4IDAwMDAwIG4gCjAwMDAwMDAyNzQgMDAwMDAgbiAKMDAwMDAwMDM0NCAwMDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDYgL1Jvb3QgMSAwIFIgPj4Kc3RhcnR4cmVmCjQ3NgolJUVPRgo=', // public, one-page synthetic fixture\n} }];" + "jsCode": "// Edit these example values before running. Never add a password here.\nreturn [{ json: {\n baseUrl: 'https://nextcloud.example.invalid',\n version: '15', // '13', '14', '15' or 'main' (development)\n integrationUser: 'integration-user',\n signerEmail: 'signer@example.invalid', // replace with a mailbox YOU control\n maxSearchFolders: 50, // bounded WebDAV discovery, set 1 to 250 if needed\n maxAttempts: 20,\n waitSeconds: 30,\n pdfBase64: 'JVBERi0xLjQKJVN5bnRoZXRpYyBMaWJyZVNpZ24gbjhuIGZpeHR1cmUKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvUmVzb3VyY2VzIDw8IC9Gb250IDw8IC9GMSA0IDAgUiA+PiA+PiAvQ29udGVudHMgNSAwIFIgPj4KZW5kb2JqCjQgMCBvYmoKPDwgL1R5cGUgL0ZvbnQgL1N1YnR5cGUgL1R5cGUxIC9CYXNlRm9udCAvSGVsdmV0aWNhID4+CmVuZG9iago1IDAgb2JqCjw8IC9MZW5ndGggODMgPj4Kc3RyZWFtCkJUIC9GMSAxNiBUZiA3MiA3MjAgVGQgKFN5bnRoZXRpYyBMaWJyZVNpZ24gbjhuIGNvbnRyYWN0IC0gbm8gcGVyc29uYWwgZGF0YSkgVGogRVQKZW5kc3RyZWFtCmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwNDIgMDAwMDAgbiAKMDAwMDAwMDA5MSAwMDAwMCBuIAowMDAwMDAwMTQ4IDAwMDAwIG4gCjAwMDAwMDAyNzQgMDAwMDAgbiAKMDAwMDAwMDM0NCAwMDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDYgL1Jvb3QgMSAwIFIgPj4Kc3RhcnR4cmVmCjQ3NgolJUVPRgo=', // public, one-page synthetic fixture\n} }];" }, "notes": "Edit public parameters here; never paste App Password in this node.", "notesInFlow": false @@ -41,7 +41,7 @@ ], "parameters": { "mode": "runOnceForAllItems", - "jsCode": "const c = $input.first().json;\nif (!['13', '14', '15', 'main'].includes(c.version)) throw new Error('Choose LibreSign 13, 14, 15 or main');\n// n8n Code nodes do not expose the URL constructor. Accept only an HTTPS origin.\nconst match = /^https:\\/\\/([a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\\[[0-9a-f:.]+\\])(?::([0-9]{1,5}))?\\/?$/i.exec(c.baseUrl);\nif (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) throw new Error('Use an HTTPS Nextcloud origin with no credentials, path or query');\nconst hostname = match[1].toLowerCase();\nif (!hostname.startsWith('[') && hostname.split('.').some(label => !label || label.startsWith('-') || label.endsWith('-'))) throw new Error('Invalid Nextcloud hostname');\nif (hostname.endsWith('.invalid') || hostname === 'example.com') throw new Error('Replace the placeholder Nextcloud host');\nconst baseUrl = 'https://' + hostname + (match[2] ? ':' + Number(match[2]) : '');\nif (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(c.signerEmail) || /@(?:example\\.(?:test|invalid|com|org|net))$/i.test(c.signerEmail)) throw new Error('Use an inbox under your control');\nif (!/^[A-Za-z0-9_.@-]+$/.test(c.integrationUser)) throw new Error('Use a simple integration account ID; URL-encode it for DAV');\nif (typeof c.signedPdfPath !== 'string' || !c.signedPdfPath || c.signedPdfPath.startsWith('/') || c.signedPdfPath.split('/').some(p => !p || p === '.' || p === '..' || p.includes('\\\\') || p.includes('?') || p.includes('#'))) throw new Error('Set a verified relative WebDAV PDF path');\nif (!Number.isInteger(c.maxAttempts) || c.maxAttempts < 1 || c.maxAttempts > 120) throw new Error('maxAttempts must be 1 to 120');\nif (!Number.isInteger(c.waitSeconds) || c.waitSeconds < 5 || c.waitSeconds > 3600) throw new Error('waitSeconds must be 5 to 3600');\nif (typeof c.pdfBase64 !== 'string' || !c.pdfBase64.startsWith('JVBERi0')) throw new Error('Provide a base64-encoded synthetic PDF');\nconst method = { method: 'email', value: c.signerEmail };\nif (c.version === '13' || c.version === '14') method.mandatory = 1;\nelse method.requirement = 'required';\nconst requestBody = { name: 'Synthetic service agreement', status: 1, file: { name: 'synthetic-n8n.pdf', base64: c.pdfBase64 }, signers: [{ displayName: 'External Test Signer', notify: 0, identifyMethods: [method] }] };\nreturn [{ json: { ...c, baseUrl, requestBody } }];" + "jsCode": "const c = $input.first().json;\nif (!['13', '14', '15', 'main'].includes(c.version)) throw new Error('Choose LibreSign 13, 14, 15 or main');\n// n8n Code nodes do not expose the URL constructor. Accept only an HTTPS origin.\nconst match = /^https:\\/\\/([a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\\[[0-9a-f:.]+\\])(?::([0-9]{1,5}))?\\/?$/i.exec(c.baseUrl);\nif (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) throw new Error('Use an HTTPS Nextcloud origin with no credentials, path or query');\nconst hostname = match[1].toLowerCase();\nif (!hostname.startsWith('[') && hostname.split('.').some(label => !label || label.startsWith('-') || label.endsWith('-'))) throw new Error('Invalid Nextcloud hostname');\nif (hostname.endsWith('.invalid') || hostname === 'example.com') throw new Error('Replace the placeholder Nextcloud host');\nconst baseUrl = 'https://' + hostname + (match[2] ? ':' + Number(match[2]) : '');\nif (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(c.signerEmail) || /@(?:example\\.(?:test|invalid|com|org|net))$/i.test(c.signerEmail)) throw new Error('Use an inbox under your control');\nif (!/^[A-Za-z0-9_.@-]+$/.test(c.integrationUser)) throw new Error('Use a simple integration account ID; URL-encode it for DAV');\nif (!Number.isInteger(c.maxSearchFolders) || c.maxSearchFolders < 1 || c.maxSearchFolders > 250) throw new Error('maxSearchFolders must be 1 to 250');\nif (!Number.isInteger(c.maxAttempts) || c.maxAttempts < 1 || c.maxAttempts > 120) throw new Error('maxAttempts must be 1 to 120');\nif (!Number.isInteger(c.waitSeconds) || c.waitSeconds < 5 || c.waitSeconds > 3600) throw new Error('waitSeconds must be 5 to 3600');\nif (typeof c.pdfBase64 !== 'string' || !c.pdfBase64.startsWith('JVBERi0')) throw new Error('Provide a base64-encoded synthetic PDF');\nconst method = { method: 'email', value: c.signerEmail };\nif (c.version === '13' || c.version === '14') method.mandatory = 1;\nelse method.requirement = 'required';\nconst requestBody = { name: 'Synthetic service agreement', status: 1, file: { name: 'synthetic-n8n.pdf', base64: c.pdfBase64 }, signers: [{ displayName: 'External Test Signer', notify: 0, identifyMethods: [method] }] };\nreturn [{ json: { ...c, baseUrl, requestBody } }];\n" } }, { @@ -257,7 +257,7 @@ ], "parameters": { "mode": "runOnceForAllItems", - "jsCode": "const o = $input.first().json;\nif (o?.ocs?.meta?.status !== 'ok' || !Array.isArray(o?.ocs?.data?.data)) throw new Error('Status check failed or returned an invalid OCS envelope');\nconst { fileId, fileUuid } = $('Verify created').first().json;\nconst row = o.ocs.data.data.find(x => String(x.id) === String(fileId) && x.uuid === fileUuid);\nif (!row) throw new Error('File not returned: missing permission, unavailable, or filtered; not proof of deletion');\nconst status = Number(row.status);\nif (![0, 1, 2, 3, 4].includes(status)) throw new Error('Unknown file status; manual reconciliation required');\nif (status === 4) throw new Error('Signing request was deleted/terminated');\nconst attempt = $('Poll attempts').item.json.attempt;\nif (status !== 3 && attempt >= $('Prepare request').first().json.maxAttempts) throw new Error('Polling limit reached; reconcile before creating anything again');\nreturn [{ json: { signed: status === 3, status, attempt, fileId, fileUuid } }];" + "jsCode": "const o = $input.first().json;\nif (o?.ocs?.meta?.status !== 'ok' || !Array.isArray(o?.ocs?.data?.data)) throw new Error('Status check failed or returned an invalid OCS envelope');\nconst { fileId, fileUuid } = $('Verify created').first().json;\nconst row = o.ocs.data.data.find(x => String(x.id) === String(fileId) && x.uuid === fileUuid);\nif (!row) throw new Error('File not returned: missing permission, unavailable, or filtered; not proof of deletion');\nconst status = Number(row.status);\nif (![0, 1, 2, 3, 4].includes(status)) throw new Error('Unknown file status; manual reconciliation required');\nif (status === 4) throw new Error('Signing request was deleted/terminated');\nconst sourceNodeId = Number(row.nodeId);\nif (status === 3 && (!Number.isSafeInteger(sourceNodeId) || sourceNodeId < 1)) throw new Error('Signed file state lacks a valid source nodeId');\nconst attempt = $('Poll attempts').item.json.attempt;\nif (status !== 3 && attempt >= $('Prepare request').first().json.maxAttempts) throw new Error('Polling limit reached; reconcile before creating anything again');\nreturn [{ json: { signed: status === 3, status, attempt, fileId, fileUuid, sourceNodeId } }];" } }, { @@ -315,12 +315,12 @@ "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ - 2990, + 4490, 120 ], "parameters": { "method": "GET", - "url": "={{ (() => { const c = $('Prepare request').first().json; return c.baseUrl + '/remote.php/dav/files/' + encodeURIComponent(c.integrationUser) + '/' + c.signedPdfPath.split('/').map(encodeURIComponent).join('/'); })() }}", + "url": "={{ $('Prepare request').first().json.baseUrl + $json.signedDavHref }}", "authentication": "genericCredentialType", "genericAuthType": "httpBasicAuth", "options": { @@ -347,7 +347,7 @@ "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ - 3240, + 4740, 120 ], "parameters": { @@ -356,6 +356,172 @@ }, "notes": "A PDF header is not cryptographic signature verification.", "notesInFlow": false + }, + { + "id": "qa-list-ls", + "name": "List LibreSign folders", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 2990, + 120 + ], + "parameters": { + "method": "PROPFIND", + "url": "={{ $('Prepare request').first().json.baseUrl + '/remote.php/dav/files/' + encodeURIComponent($('Prepare request').first().json.integrationUser) + '/LibreSign/' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "options": { + "timeout": 30000, + "webdavMethods": true, + "redirect": { + "redirect": { + "followRedirects": false + } + }, + "response": { + "response": { + "responseFormat": "text", + "outputPropertyName": "data" + } + } + }, + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Depth", + "value": "1" + }, + { + "name": "Content-Type", + "value": "application/xml" + } + ] + }, + "sendBody": true, + "contentType": "raw", + "rawContentType": "application/xml", + "body": "" + }, + "notes": "Use a verified path under the integration account DAV root, with file read access.", + "notesInFlow": false + }, + { + "id": "qa-parse-folders", + "name": "Parse folder XML", + "type": "n8n-nodes-base.xml", + "typeVersion": 1, + "position": [ + 3240, + 120 + ], + "parameters": { + "mode": "xmlToJson", + "dataPropertyName": "data", + "options": { + "explicitArray": false, + "explicitRoot": true, + "ignoreAttrs": true + } + } + }, + { + "id": "qa-choose-folders", + "name": "Choose folders", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 3490, + 120 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const c = $('Prepare request').first().json;\nconst prefix = '/remote.php/dav/files/' + encodeURIComponent(c.integrationUser) + '/LibreSign/';\nconst o = $input.first().json;\nconst root = o['d:multistatus'] ?? o['multistatus'];\nif (!root) throw new Error('Invalid WebDAV folder multistatus');\nconst list = v => v == null ? [] : Array.isArray(v) ? v : [v];\nconst records = list(root['d:response'] ?? root['response']);\nconst hrefs = records.map(r => r['d:href'] ?? r['href']).filter(v => typeof v === 'string');\nconst isSafeFolder = h => {\n if (!h.startsWith(prefix) || !h.endsWith('/') || h === prefix || /[?#]/.test(h)) return false;\n const tail = h.slice(prefix.length);\n const parts = tail.split('/').filter(Boolean);\n return parts.length === 1 && !parts.some(p => p === '.' || p === '..' || /%(?:2e|2f|5c|00)/i.test(p));\n};\nconst folders = hrefs.filter(isSafeFolder);\nif (folders.length === 0 || folders.length > c.maxSearchFolders || new Set(folders).size !== folders.length) throw new Error('No bounded, unique LibreSign DAV folders found');\nreturn folders.map(h => ({ json: { folderHref: h } }));" + } + }, + { + "id": "qa-list-files", + "name": "Inspect folder files", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 3740, + 120 + ], + "parameters": { + "method": "PROPFIND", + "url": "={{ $('Prepare request').first().json.baseUrl + $json.folderHref }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "options": { + "timeout": 30000, + "webdavMethods": true, + "redirect": { + "redirect": { + "followRedirects": false + } + }, + "response": { + "response": { + "responseFormat": "text", + "outputPropertyName": "data" + } + } + }, + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Depth", + "value": "1" + }, + { + "name": "Content-Type", + "value": "application/xml" + } + ] + }, + "sendBody": true, + "contentType": "raw", + "rawContentType": "application/xml", + "body": "" + }, + "notes": "Use a verified path under the integration account DAV root, with file read access.", + "notesInFlow": false + }, + { + "id": "qa-parse-files", + "name": "Parse file XML", + "type": "n8n-nodes-base.xml", + "typeVersion": 1, + "position": [ + 3990, + 120 + ], + "parameters": { + "mode": "xmlToJson", + "dataPropertyName": "data", + "options": { + "explicitArray": false, + "explicitRoot": true, + "ignoreAttrs": true + } + } + }, + { + "id": "qa-resolve-signed", + "name": "Resolve signed PDF", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 4240, + 120 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const c = $('Prepare request').first().json;\nconst prefix = '/remote.php/dav/files/' + encodeURIComponent(c.integrationUser) + '/LibreSign/';\nconst safeHref = h => {\n if (typeof h !== 'string' || !h.startsWith(prefix) || /[?#]/.test(h)) return false;\n const tail = h.slice(prefix.length);\n const parts = tail.split('/').filter(Boolean);\n return parts.length > 0 && !parts.some(p => p === '.' || p === '..' || /%(?:2e|2f|5c|00)/i.test(p));\n};\nconst nodeId = String($('Reconcile file state').first().json.sourceNodeId);\nif (!/^\\d+$/.test(nodeId) || nodeId === '0') throw new Error('OCS does not expose a valid authorized source nodeId');\nconst list = v => v == null ? [] : Array.isArray(v) ? v : [v];\nconst fileGroups = $input.all().map(i => {\n const root = i.json['d:multistatus'] ?? i.json.multistatus;\n if (!root) throw new Error('Invalid WebDAV file multistatus');\n return list(root['d:response'] ?? root.response).map(r => {\n const href = r['d:href'] ?? r.href;\n const propstat = list(r['d:propstat'] ?? r.propstat);\n const good = propstat.find(p => String(p['d:status'] ?? p.status).includes('200'));\n const prop = good?.['d:prop'] ?? good?.prop ?? {};\n return { href, fileid: String(prop['oc:fileid'] ?? prop.fileid ?? ''), type: String(prop['d:getcontenttype'] ?? prop.getcontenttype ?? ''), size: Number(prop['d:getcontentlength'] ?? prop.getcontentlength ?? 0) };\n });\n});\nconst related = fileGroups.filter(items => items.some(i => i.fileid === nodeId));\nif (related.length !== 1) throw new Error('Cannot uniquely associate an authorized DAV folder with OCS source nodeId');\nconst items=related[0];\nconst original = items.filter(i => i.fileid === nodeId && safeHref(i.href) && !i.href.endsWith('/'));\nif (original.length !== 1) throw new Error('Original document is ambiguous');\nconst folder = String(original[0].href).replace(/[^/]+$/, '');\nif (!folder.startsWith(prefix)) throw new Error('Original DAV path outside LibreSign root');\nconst candidates=items.filter(x => x.fileid !== nodeId && safeHref(x.href) && x.href.startsWith(folder) && x.href !== folder && !x.href.endsWith('/') && x.type === 'application/pdf' && x.size > 0);\nif (candidates.length !== 1) throw new Error('Expected exactly one non-source PDF in the signed document folder');\nconst target = candidates[0].href;\nif (!target.startsWith(prefix) || target.includes('?') || target.includes('#') || /%2f|%5c|%2e%2e/i.test(target)) throw new Error('Unsafe WebDAV target');\nreturn [{ json: { signedDavHref: target, sourceNodeId: Number(nodeId), candidateCount: candidates.length } }];" + } } ], "connections": { @@ -485,7 +651,7 @@ "main": [ [ { - "node": "Download signed PDF", + "node": "List LibreSign folders", "type": "main", "index": 0 } @@ -520,6 +686,72 @@ } ] ] + }, + "List LibreSign folders": { + "main": [ + [ + { + "node": "Parse folder XML", + "type": "main", + "index": 0 + } + ] + ] + }, + "Parse folder XML": { + "main": [ + [ + { + "node": "Choose folders", + "type": "main", + "index": 0 + } + ] + ] + }, + "Choose folders": { + "main": [ + [ + { + "node": "Inspect folder files", + "type": "main", + "index": 0 + } + ] + ] + }, + "Inspect folder files": { + "main": [ + [ + { + "node": "Parse file XML", + "type": "main", + "index": 0 + } + ] + ] + }, + "Parse file XML": { + "main": [ + [ + { + "node": "Resolve signed PDF", + "type": "main", + "index": 0 + } + ] + ] + }, + "Resolve signed PDF": { + "main": [ + [ + { + "node": "Download signed PDF", + "type": "main", + "index": 0 + } + ] + ] } }, "active": false, diff --git a/examples/n8n/test-workflow.mjs b/examples/n8n/test-workflow.mjs index 4b1f05b8..fbfa800d 100644 --- a/examples/n8n/test-workflow.mjs +++ b/examples/n8n/test-workflow.mjs @@ -8,7 +8,8 @@ import vm from 'node:vm'; const workflow = JSON.parse(fs.readFileSync(new URL('./libresign-external-signature.json', import.meta.url), 'utf8')); const nodes = new Map(workflow.nodes.map(n => [n.name, n])); const code = (name, input, references = {}, extras = {}) => { - const $input = { first: () => ({ json: input }) }; + const items = (Array.isArray(input) ? input : [input]).map(json => ({ json })); + const $input = { first: () => items[0], all: () => items }; const $ = name => ({ first: () => ({ json: references[name] }), item: { json: references[name] }, @@ -21,11 +22,11 @@ const code = (name, input, references = {}, extras = {}) => { }; const config = { baseUrl: 'https://nc.example.test', version: '15', integrationUser: 'integration-user', signerEmail: 'signer@controlled.test', - signedPdfPath: 'Contracts/signed.pdf', maxAttempts: 3, waitSeconds: 5, + maxSearchFolders: 50, maxAttempts: 3, waitSeconds: 5, pdfBase64: 'JVBERi0xLjQKc3ludGhldGlj' }; const created = { fileId: 17, fileUuid: 'synthetic-uuid' }; const row = status => ({ ocs: { meta: { status: 'ok' }, - data: { data: [{ id: 17, uuid: 'synthetic-uuid', status }] } } }); + data: { data: [{ id: 17, uuid: 'synthetic-uuid', status, nodeId: 100 }] } } }); test('workflow imports as a connected, manual, inactive graph', () => { assert.equal(workflow.active, false); @@ -44,7 +45,7 @@ test('workflow imports as a connected, manual, inactive graph', () => { test('export contains no authentication material and does not automatically retry POST', () => { assert.equal(workflow.nodes.some(n => n.credentials), false); const http = workflow.nodes.filter(n => n.type === 'n8n-nodes-base.httpRequest'); - assert.equal(http.length, 4); + assert.equal(http.length, 6); assert(http.every(n => n.parameters.authentication === 'genericCredentialType')); assert(http.every(n => n.parameters.genericAuthType === 'httpBasicAuth')); assert(http.every(n => !n.parameters.options?.retry)); @@ -62,13 +63,13 @@ test('request payload matches 13/14 vs 15/main versioned identity contracts', as (['method','value', version === '13' || version === '14' ? 'mandatory' : 'requirement']).sort()); } }); -test('request validation rejects placeholders and unsafe WebDAV paths', async () => { +test('request validation rejects placeholders and unbounded WebDAV discovery', async () => { for (const bad of [ { baseUrl: 'http://nc.example.test' }, { baseUrl: 'https://nextcloud.example.invalid' }, { signerEmail: 'signer@example.invalid' }, - { signedPdfPath: '../secret.pdf' }, - { signedPdfPath: 'Contracts//signed.pdf' }, + { maxSearchFolders: 0 }, + { maxSearchFolders: 251 }, { maxAttempts: 0 }, ]) await assert.rejects(code('Prepare request', { ...config, ...bad })); }); @@ -100,21 +101,105 @@ test('polling handles pending, terminal, missing, and budget exhaustion', async 'Prepare request': config, }); assert.equal((await code('Reconcile file state', row(1), ref(1)))[0].json.signed, false); - assert.equal((await code('Reconcile file state', row(3), ref(2)))[0].json.signed, true); + const signed = (await code('Reconcile file state', row(3), ref(2)))[0].json; + assert.equal(signed.signed, true); + assert.equal(signed.sourceNodeId, 100); await assert.rejects(code('Reconcile file state', row(1), ref(3))); await assert.rejects(code('Reconcile file state', row(4), ref(1))); await assert.rejects(code('Reconcile file state', row(9), ref(1))); + await assert.rejects(code('Reconcile file state', { ocs: { meta: { status: 'ok' }, + data: { data: [{ id: 17, uuid: created.fileUuid, status: 3 }] } } }, ref(1))); await assert.rejects(code('Reconcile file state', { ocs: { meta: { status: 'ok' }, data: { data: [] } } }, ref(1))); }); -test('file and WebDAV requests use authorization; there is no inferred PDF URL', () => { +const davRoot = '/remote.php/dav/files/integration-user/LibreSign/'; +const folderHref = davRoot + '2026-11-11_Synthetic%20service%20agreement/'; +const davFile = (href, fileid, size = 659) => ({ + 'd:href': href, + 'd:propstat': { 'd:status': 'HTTP/1.1 200 OK', 'd:prop': { + 'oc:fileid': String(fileid), 'd:getcontenttype': 'application/pdf', + 'd:getcontentlength': String(size), + } }, +}); +const davFolder = (files) => ({ 'd:multistatus': { 'd:response': [ + { 'd:href': folderHref, 'd:propstat': { 'd:status': 'HTTP/1.1 200 OK', + 'd:prop': { 'oc:fileid': '99', 'd:resourcetype': { 'd:collection': '' } } } }, + ...files, +] } }); +const source = davFile(folderHref + 'synthetic.pdf', 100); +const final = davFile(folderHref + 'synthetic.signed_1.pdf', 101, 47799); +const davRefs = { 'Prepare request': config, 'Reconcile file state': { sourceNodeId: 100 } }; + +test('PROPFIND nodes use the same credential and parse WebDAV XML', () => { + const http = workflow.nodes.filter(n => n.type === 'n8n-nodes-base.httpRequest'); + const dav = http.filter(n => n.parameters.method === 'PROPFIND'); + assert.equal(dav.length, 2); + for (const n of dav) { + const p = n.parameters; + assert.equal(p.genericAuthType, 'httpBasicAuth'); + assert.equal(p.contentType, 'raw'); + assert.equal(p.rawContentType, 'application/xml'); + assert(p.body.includes('oc:fileid')); + assert(p.headerParameters.parameters.some(x => x.name === 'Depth' && x.value === '1')); + assert.equal(p.options.redirect.redirect.followRedirects, false); + } + assert.equal(nodes.get('Parse folder XML').type, 'n8n-nodes-base.xml'); + assert.equal(nodes.get('Parse file XML').type, 'n8n-nodes-base.xml'); +}); + +test('WebDAV discovery accepts only bounded, direct, same-root folders', async () => { + const folders = { 'd:multistatus': { 'd:response': [ + { 'd:href': davRoot }, { 'd:href': folderHref }, + { 'd:href': davRoot + 'foreign.pdf' }, + { 'd:href': '/remote.php/dav/files/another-user/LibreSign/other/' }, + { 'd:href': davRoot + '%2e%2e/' }, + ] } }; + const found = await code('Choose folders', folders, { 'Prepare request': config }, { URL: undefined }); + assert.equal(found.length, 1); + assert.equal(found[0].json.folderHref, folderHref); + await assert.rejects(code('Choose folders', folders, { 'Prepare request': { ...config, maxSearchFolders: 0 } })); + await assert.rejects(code('Choose folders', { 'd:multistatus': { 'd:response': [ + { 'd:href': folderHref }, { 'd:href': folderHref }, + ] } }, { 'Prepare request': config })); + await assert.rejects(code('Choose folders', { 'd:multistatus': { 'd:response': [ + { 'd:href': folderHref }, { 'd:href': davRoot + 'second/' }, + ] } }, { 'Prepare request': { ...config, maxSearchFolders: 1 } })); + const unsafe = (await code('Choose folders', { 'd:multistatus': { 'd:response': [ + { 'd:href': davRoot + '../' }, { 'd:href': davRoot + '%2e%2e/' }, + { 'd:href': folderHref }, + ] } }, { 'Prepare request': config })); + assert.equal(unsafe.length, 1); + assert.equal(unsafe[0].json.folderHref, folderHref); +}); + +test('download path is learned from original oc:fileid and one authorized PDF sibling', async () => { + const output = (await code('Resolve signed PDF', [davFolder([source, final])], davRefs, { URL: undefined }))[0].json; + assert.equal(output.signedDavHref, final['d:href']); + assert.equal(output.sourceNodeId, 100); + assert.equal(output.candidateCount, 1); const download = nodes.get('Download signed PDF').parameters; - assert(download.url.includes('signedPdfPath')); - assert(download.url.includes('remote.php/dav/files')); - assert(download.url.includes('encodeURIComponent')); - assert(download.url.includes('integrationUser')); + assert(download.url.includes('signedDavHref')); + assert(!download.url.includes('signedPdfPath')); +}); + +test('WebDAV discovery rejects wrong identity, missing signature, and ambiguous sibling', async () => { + const r = name => code('Resolve signed PDF', [davFolder(name)], davRefs, { URL: undefined }); + await assert.rejects(r([source])); + await assert.rejects(r([final])); + await assert.rejects(r([source, final, davFile(folderHref + 'unexpected.pdf', 105, 1200)])); + await assert.rejects(code('Resolve signed PDF', [davFolder([source, final])], + { ...davRefs, 'Reconcile file state': { sourceNodeId: 200 } })); + await assert.rejects(r([source, davFile(folderHref + '%2e%2e.pdf', 101, 50)])); + await assert.rejects(r([source, davFile(folderHref + '../unexpected.pdf', 101, 50)])); +}); + +test('API and WebDAV requests retain authorization boundaries and no guessed endpoint', () => { const get = nodes.get('Get file state').parameters; assert(get.url.includes('/file/list')); assert(get.queryParameters.parameters.some(p => p.name === 'fileIds[]')); assert(nodes.get('Invite signer once').parameters.url.includes('/notify/signers')); assert(nodes.get('Create request').parameters.url.includes('/request-signature')); + assert(nodes.get('List LibreSign folders').parameters.url.includes('remote.php/dav/files')); + assert(nodes.get('Inspect folder files').parameters.url.includes('folderHref')); + assert.equal(JSON.stringify(workflow).includes('/file/download/'), false); + assert.equal(JSON.stringify(workflow).includes('signedPdfPath'), false); });