diff --git a/docs/maintainers/versioning.md b/docs/maintainers/versioning.md index 2af7685c..0f36011d 100644 --- a/docs/maintainers/versioning.md +++ b/docs/maintainers/versioning.md @@ -41,6 +41,15 @@ right branch. Backport changes explicitly when they apply to older releases. 5. Validates links, API provenance, signing examples, redirects and the output of all other versions before deploying atomically to Pages. +The moving aliases follow Nextcloud's documentation convention: `/latest/` +redirects to the unreleased `/main/`, while `/stable/` redirects to the +latest published stable major from `versions.json.current_stable`. Both +support deep HTML paths, including `/stable/developer_manual/api/openapi.html`. +The matching `openapi.json` and `openapi.provenance.json` are also available +under each alias. Publish updates the aliases atomically on full and partial +releases. For reproducible integrations, pin the exact numeric version and +confirm the OpenAPI provenance: these aliases can change on release. + Stable application releases are discovered dynamically, not maintained in a fixed list. EOL dates and policy remain in `versioning/lifecycle.json`. The API version is always taken from the application manifest, not from the diff --git a/examples/n8n/README.md b/examples/n8n/README.md new file mode 100644 index 00000000..ab14df56 --- /dev/null +++ b/examples/n8n/README.md @@ -0,0 +1,191 @@ + + + +# 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. + +[Import the workflow](libresign-external-signature.json). For equivalent cURL +and PHP flows, reuse the existing +[`external-email-signers` examples](../external-email-signers/) rather than +copying their implementation. **The JSON contains a small synthetic PDF, but +no account credential or live signer address.** + +## Select the installed LibreSign release + +`/ocs/v2.php/apps/libresign/api/v1` is the common **protocol prefix**, not +an application major version. The workflow's `Configure` node selects the +following exact request shape: + +| Installed LibreSign | `identifyMethods[]` | Completion signal | +| --- | --- | --- | +| 13 or 14 | `mandatory: 1` | OCS polling | +| 15 | `requirement: "required"` | OCS polling | +| Development (`main`) | `requirement: "required"` | OCS polling; optional native events | + +Start with the [stable integration guide](https://docs.libresign.coop/stable/developer_manual/integration/index.html) +and [stable OpenAPI](https://docs.libresign.coop/stable/developer_manual/api/openapi.html). +The `/stable/` alias always follows the **newest released** LibreSign version, +not the version installed on your server. **If your installation is older, +select its exact LibreSign major** on the +[documentation version chooser](https://docs.libresign.coop/) before using +payloads, endpoints or OpenAPI schemas. `/latest/` is the **unreleased** +development documentation, following Nextcloud's convention; it is not a +replacement for stable documentation. + +The [version-specific request fixtures](../external-email-signers/) +(`request-13.json`, `request-14.json`, `request-15.json`, +`request-main.json`) remain the source for the matching request body. +This example intentionally omits `callback`, `signatureFlow`, and +experimental policy fields. + +## Prerequisites — use a disposable environment + +1. An **isolated Nextcloud** installation with the matching LibreSign release, + correct signing-certificate setup, writable storage, and an email identify + method plus a permitted signing method (for example `clickToSign`). + Configure an **inbox you control** or a test-only SMTP sink such as Mailpit. + Never send this example to real recipients or use production services. +2. An **authorized integration account** that can create signature requests, + view their state, and read the target signed file in Nextcloud Files. + Create a revocable **App Password** from Nextcloud **Personal settings → + Security**. Do not use a signer's credentials or the regular account password. +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. + +## Import and configure + +1. In n8n open **Workflows → Import from File** and select + [`libresign-external-signature.json`](libresign-external-signature.json). + 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**. + 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 + *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** + invitation and complete signing under the installed policy. The n8n run + awaits the file status; it does **not** impersonate a signer. +5. After success, **Verify PDF bytes** outputs the binary property `signedPdf` + and metadata including `fileId`, `fileUuid`, `downloadedBytes`, and + `cryptographicSignatureVerified: false`. Use a separate trusted PDF + signature verifier; checking `%PDF-` only verifies basic file format. + +### What is sent and when + +```text +POST /request-signature (notify: 0; exactly one external email signer) + -> OCS status + fileId/fileUuid +POST /notify/signers (one explicit invitation request, not delivery proof) + -> 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 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 +``` + +A `fileId` is **not** the file UUID or a signer-scoped signing UUID. The +`GET /file/list` response is authorization-filtered: a missing row can mean +missing permissions, not deletion. Status `3` is a candidate completion +state for this **single document** only. Do not generalize this example to +envelopes, mixed rejection policies, or multi-signer workflows without also +checking child documents and each required signer. + +### Failure behavior and security + +- n8n's HTTP Request nodes do **not** follow redirects, do **not** accept + arbitrary HTTP errors as success, and do **not** automatically retry POSTs. + A timeout after creation or notification has an **ambiguous outcome**; + reconcile the existing file ID/UUID before any manual retry. +- HTTP `401` means authentication failure; `403` means insufficient permission; + `404` may be missing or inaccessible; `412` can indicate the absent + `OCS-APIRequest: true` header; `422` can indicate policy/input rejection. + The Code nodes also reject an unsuccessful `ocs.meta.status` even if the + transport returned HTTP 2xx. Inspect safe error metadata without logging + App Passwords, invitation URLs, request bodies, or signer PII. +- Polling is bounded (`20 × 30 s` by default; edit the values) and stops with + an error instead of claiming completion when the budget expires. An actual + document completion may occur between checks; use independent periodic + reconciliation in longer-running systems. +- The original and final PDF, exported execution data, metadata, and binary + may be retained by n8n. Restrict access, configure execution-data pruning, + and follow your retention policy. Keep n8n's credential encryption key + protected and revoke credentials when the integration is decommissioned. +- 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. + +## Development: optional native event receiver + +The `main` development documentation publishes native LibreSign event classes +for Nextcloud **Webhook Listeners**, notably +`OCA\Libresign\Events\SigningRequestCompletedEvent` and +`OCA\Libresign\Events\SigningRequestCanceledEvent`. See the +[development event catalog](https://docs.libresign.coop/latest/developer_manual/webhooks/event-catalog.html) and +[Webhook Listeners configuration](https://docs.libresign.coop/latest/developer_manual/webhooks/configuration.html). + +A production-oriented alternative may receive those events with n8n's +**Webhook** node, configured with HTTPS and **Header Auth** or **Basic Auth** +(the receiver secret is an n8n credential, not part of the workflow export). +Authenticate the sender, store/deduplicate `event.eventId`, check +`event.contractVersion`, correlate `event.requestUuid` with a previously +created workflow, then **re-query OCS as the authorized requester** to +confirm the current status before deciding to download. Do not trust arrival +order, assume exactly-once delivery, or treat an event as a PDF access token. +Nextcloud background Cron/worker scheduling must be operational. + +**Stable LibreSign 13–15 do not publish that native signing-completion +contract.** This importable example intentionally uses polling on every +release, including `main`, and does not require a proprietary callback. +Event delivery and receiver authentication require separate integration +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. + +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), +[n8n HTTP Request](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest/), +[n8n Wait](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.wait/), +[n8n Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/), +[Nextcloud WebDAV](https://docs.nextcloud.com/server/stable/developer_manual/client_apis/WebDAV/basic.html). + +**Navigation follow-up, not part of this PR:** once front C finishes editing +its versioned integration landing pages, add a link to this example from the +relevant architecture and external-email-signers guides on `main`, +`stable13`, `stable14`, and `stable15`, using independently reviewed version +links. Do not backport an event receiver to stable branches. diff --git a/examples/n8n/libresign-external-signature.json b/examples/n8n/libresign-external-signature.json new file mode 100644 index 00000000..4682d254 --- /dev/null +++ b/examples/n8n/libresign-external-signature.json @@ -0,0 +1,530 @@ +{ + "name": "LibreSign C2 - external email signature (polling)", + "nodes": [ + { + "id": "c2-manual-trigger", + "name": "Manual trigger", + "type": "n8n-nodes-base.manualTrigger", + "typeVersion": 1, + "position": [ + 0, + 240 + ], + "parameters": {}, + "notes": "Run only against an isolated Nextcloud + LibreSign instance.", + "notesInFlow": false + }, + { + "id": "c2-configure", + "name": "Configure", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 240, + 240 + ], + "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} }];" + }, + "notes": "Edit public parameters here; never paste App Password in this node.", + "notesInFlow": false + }, + { + "id": "c2-prepare-request", + "name": "Prepare request", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 490, + 240 + ], + "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');\nlet url;\ntry { url = new URL(c.baseUrl); } catch { throw new Error('Invalid Nextcloud URL'); }\nif (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('Use an HTTPS Nextcloud origin with no credentials, path or query');\nif (url.hostname.endsWith('.invalid') || url.hostname === 'example.com') throw new Error('Replace the placeholder Nextcloud host');\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: url.origin, requestBody } }];" + } + }, + { + "id": "c2-create-request", + "name": "Create request", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 740, + 240 + ], + "parameters": { + "method": "POST", + "url": "={{ $('Prepare request').first().json.baseUrl + '/ocs/v2.php/apps/libresign/api/v1' + '/request-signature' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "OCS-APIRequest", + "value": "true" + }, + { + "name": "Accept", + "value": "application/json" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "options": { + "timeout": 30000, + "redirect": { + "redirect": { + "followRedirects": false + } + } + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify($('Prepare request').first().json.requestBody) }}" + }, + "notes": "Assign the same dedicated Nextcloud Generic HTTP Basic Auth credential after import. Do not enable automatic retries.", + "notesInFlow": false + }, + { + "id": "c2-verify-created", + "name": "Verify created", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 990, + 240 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const o = $input.first().json;\nif (o?.ocs?.meta?.status !== 'ok' || !o.ocs.data) throw new Error('LibreSign did not accept creation (OCS envelope)');\nconst { id, uuid } = o.ocs.data;\nif (!Number.isSafeInteger(id) || id < 1 || typeof uuid !== 'string' || !uuid) throw new Error('Creation lacks a safe file ID and UUID');\nreturn [{ json: { fileId: id, fileUuid: uuid } }];" + } + }, + { + "id": "c2-invite-signer-once", + "name": "Invite signer once", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 1240, + 240 + ], + "parameters": { + "method": "POST", + "url": "={{ $('Prepare request').first().json.baseUrl + '/ocs/v2.php/apps/libresign/api/v1' + '/notify/signers' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "OCS-APIRequest", + "value": "true" + }, + { + "name": "Accept", + "value": "application/json" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "options": { + "timeout": 30000, + "redirect": { + "redirect": { + "followRedirects": false + } + } + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify({ fileId: $('Verify created').first().json.fileId, signers: [{ email: $('Prepare request').first().json.signerEmail }] }) }}" + }, + "notes": "Assign the same dedicated Nextcloud Generic HTTP Basic Auth credential after import. Do not enable automatic retries.", + "notesInFlow": false + }, + { + "id": "c2-verify-invite-accepted", + "name": "Verify invite accepted", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 1490, + 240 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const o = $input.first().json;\nif (o?.ocs?.meta?.status !== 'ok' || o.ocs.data === undefined || o.ocs.data === null) throw new Error('LibreSign did not accept notification request');\n// API acknowledgement is NOT proof of email delivery. Never blindly retry.\nreturn [{ json: { notificationSubmitted: true, deliveryConfirmed: false } }];" + } + }, + { + "id": "c2-prepare-bounded-attempts", + "name": "Prepare bounded attempts", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 1740, + 240 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const c = $('Prepare request').first().json;\nreturn Array.from({ length: c.maxAttempts }, (_, i) => ({ json: { attempt: i + 1 } }));" + } + }, + { + "id": "c2-poll-attempts", + "name": "Poll attempts", + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [ + 1990, + 240 + ], + "parameters": { + "batchSize": 1, + "options": {} + }, + "notes": "Output 1 processes a poll. Output 0 is intentionally unused; final success exits from Signed? directly.", + "notesInFlow": false + }, + { + "id": "c2-get-file-state", + "name": "Get file state", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 2240, + 240 + ], + "parameters": { + "method": "GET", + "url": "={{ $('Prepare request').first().json.baseUrl + '/ocs/v2.php/apps/libresign/api/v1' + '/file/list' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "OCS-APIRequest", + "value": "true" + }, + { + "name": "Accept", + "value": "application/json" + } + ] + }, + "options": { + "timeout": 30000, + "redirect": { + "redirect": { + "followRedirects": false + } + } + }, + "sendQuery": true, + "queryParameters": { + "parameters": [ + { + "name": "details", + "value": "={{ $('Prepare request').first().json.version === 'main' ? 'true' : '1' }}" + }, + { + "name": "fileIds[]", + "value": "={{ $('Verify created').first().json.fileId }}" + } + ] + } + }, + "notes": "Assign the same dedicated Nextcloud Generic HTTP Basic Auth credential after import. Do not enable automatic retries.", + "notesInFlow": false + }, + { + "id": "c2-reconcile-file-state", + "name": "Reconcile file state", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 2490, + 240 + ], + "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 } }];" + } + }, + { + "id": "c2-signed-", + "name": "Signed?", + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + 2740, + 240 + ], + "parameters": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 2 + }, + "conditions": { + "combinator": "and", + "conditions": [ + { + "id": "signed-true", + "leftValue": "={{ $json.signed }}", + "rightValue": true, + "operator": { + "type": "boolean", + "operation": "true" + } + } + ] + } + } + }, + { + "id": "c2-wait-before-polling", + "name": "Wait before polling", + "type": "n8n-nodes-base.wait", + "typeVersion": 1.1, + "position": [ + 2740, + 480 + ], + "parameters": { + "resume": "timeInterval", + "amount": "={{ $('Prepare request').first().json.waitSeconds }}", + "unit": "seconds" + }, + "notes": "Not a notification-delivery guarantee. Once the budget is exhausted, fail explicitly.", + "notesInFlow": false + }, + { + "id": "c2-download-signed-pdf", + "name": "Download signed PDF", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 2990, + 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('/'); })() }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpBasicAuth", + "options": { + "timeout": 60000, + "redirect": { + "redirect": { + "followRedirects": false + } + }, + "response": { + "response": { + "responseFormat": "file", + "outputPropertyName": "signedPdf" + } + } + } + }, + "notes": "Use a verified path under the integration account DAV root, with file read access.", + "notesInFlow": false + }, + { + "id": "c2-verify-pdf-bytes", + "name": "Verify PDF bytes", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 3240, + 120 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "const item = $input.first();\nif (!item.binary?.signedPdf) throw new Error('WebDAV did not return a PDF binary');\nconst bytes = await this.helpers.getBinaryDataBuffer(0, 'signedPdf');\nif (bytes.toString('utf8', 0, 5) !== '%PDF-') throw new Error('Authenticated WebDAV response is not a PDF');\nconst { fileId, fileUuid } = $('Verify created').first().json;\nreturn [{ json: { fileId, fileUuid, downloadedBytes: bytes.length, retrieval: 'authorized WebDAV', cryptographicSignatureVerified: false }, binary: item.binary }];" + }, + "notes": "A PDF header is not cryptographic signature verification.", + "notesInFlow": false + } + ], + "connections": { + "Manual trigger": { + "main": [ + [ + { + "node": "Configure", + "type": "main", + "index": 0 + } + ] + ] + }, + "Configure": { + "main": [ + [ + { + "node": "Prepare request", + "type": "main", + "index": 0 + } + ] + ] + }, + "Prepare request": { + "main": [ + [ + { + "node": "Create request", + "type": "main", + "index": 0 + } + ] + ] + }, + "Create request": { + "main": [ + [ + { + "node": "Verify created", + "type": "main", + "index": 0 + } + ] + ] + }, + "Verify created": { + "main": [ + [ + { + "node": "Invite signer once", + "type": "main", + "index": 0 + } + ] + ] + }, + "Invite signer once": { + "main": [ + [ + { + "node": "Verify invite accepted", + "type": "main", + "index": 0 + } + ] + ] + }, + "Verify invite accepted": { + "main": [ + [ + { + "node": "Prepare bounded attempts", + "type": "main", + "index": 0 + } + ] + ] + }, + "Prepare bounded attempts": { + "main": [ + [ + { + "node": "Poll attempts", + "type": "main", + "index": 0 + } + ] + ] + }, + "Poll attempts": { + "main": [ + [], + [ + { + "node": "Get file state", + "type": "main", + "index": 0 + } + ] + ] + }, + "Get file state": { + "main": [ + [ + { + "node": "Reconcile file state", + "type": "main", + "index": 0 + } + ] + ] + }, + "Reconcile file state": { + "main": [ + [ + { + "node": "Signed?", + "type": "main", + "index": 0 + } + ] + ] + }, + "Signed?": { + "main": [ + [ + { + "node": "Download signed PDF", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Wait before polling", + "type": "main", + "index": 0 + } + ] + ] + }, + "Wait before polling": { + "main": [ + [ + { + "node": "Poll attempts", + "type": "main", + "index": 0 + } + ] + ] + }, + "Download signed PDF": { + "main": [ + [ + { + "node": "Verify PDF bytes", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "active": false, + "settings": { + "executionOrder": "v1" + }, + "pinData": {} +} diff --git a/examples/n8n/test-workflow.mjs b/examples/n8n/test-workflow.mjs new file mode 100644 index 00000000..dd8b9c95 --- /dev/null +++ b/examples/n8n/test-workflow.mjs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: CC-BY-3.0 +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +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 $ = name => ({ + first: () => ({ json: references[name] }), + item: { json: references[name] }, + }); + return vm.runInNewContext( + '(async () => { ' + nodes.get(name).parameters.jsCode + ' })()', + { $input, $, URL, Number, Error, Array, String, console, ...extras }, + { timeout: 1000 } + ); +}; +const config = { baseUrl: 'https://nc.example.test', version: '15', + integrationUser: 'integration-user', signerEmail: 'signer@controlled.test', + signedPdfPath: 'Contracts/signed.pdf', 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 }] } } }); + +test('workflow imports as a connected, manual, inactive graph', () => { + assert.equal(workflow.active, false); + assert.equal(nodes.get('Manual trigger').type, 'n8n-nodes-base.manualTrigger'); + assert.equal(nodes.size, workflow.nodes.length); + const names = [...nodes.keys()]; + const reachable = new Set(['Manual trigger']); + for (let i = 0; i < names.length; i++) { + for (const current of [...reachable]) { + for (const port of workflow.connections[current]?.main ?? []) + for (const next of port) reachable.add(next.node); + } + } + assert.deepEqual([...reachable].sort(), names.sort()); +}); +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(http.every(n => n.parameters.authentication === 'genericCredentialType')); + assert(http.every(n => n.parameters.genericAuthType === 'httpBasicAuth')); + assert(http.every(n => !n.parameters.options?.retry)); + assert(http.every(n => n.parameters.options?.redirect?.redirect?.followRedirects === false)); + assert.equal(JSON.stringify(workflow).includes('callback'), false); +}); +test('request payload matches 13/14 vs 15/main versioned identity contracts', async () => { + for (const version of ['13', '14', '15', 'main']) { + const out = (await code('Prepare request', { ...config, version }))[0].json.requestBody; + const identity = out.signers[0].identifyMethods[0]; + assert.equal(identity.method, 'email'); + assert.equal(out.signers[0].notify, 0); + assert.equal(identity.value, config.signerEmail); + assert.deepEqual(Object.keys(identity).sort(), + (['method','value', version === '13' || version === '14' ? 'mandatory' : 'requirement']).sort()); + } +}); +test('request validation rejects placeholders and unsafe WebDAV paths', 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' }, + { maxAttempts: 0 }, + ]) await assert.rejects(code('Prepare request', { ...config, ...bad })); +}); +test('creation/notification require successful OCS envelope', async () => { + const response = { ocs: { meta: { status: 'ok' }, data: { id: 17, uuid: created.fileUuid } } }; + const out = (await code('Verify created', response))[0].json; + assert.equal(out.fileId, 17); + await assert.rejects(code('Verify created', { ocs: { meta: { status: 'failure' }, data: response.ocs.data } })); + const notified = (await code('Verify invite accepted', { ocs: { meta: { status: 'ok' }, data: {} } }))[0].json; + assert.equal(notified.deliveryConfirmed, false); + await assert.rejects(code('Verify invite accepted', { ocs: { meta: { status: 'failure' }, data: {} } })); +}); +test('polling handles pending, terminal, missing, and budget exhaustion', async () => { + const ref = attempt => ({ + 'Verify created': created, + 'Poll attempts': { attempt }, + '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); + 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: [] } } }, ref(1))); +}); +test('file and WebDAV requests use authorization; there is no inferred PDF URL', () => { + 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')); + 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')); +}); diff --git a/tests/test_versioning.py b/tests/test_versioning.py index da2bafea..1c9fa72b 100644 --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -8,8 +8,8 @@ from versioning.catalog import discover, manifest_info, operations, sha256 from versioning.build import legacy_redirects, redirect_html, version_overview -from versioning.publish import assemble -from versioning.verify import inspect_links, verify_site +from versioning.publish import assemble, write_version_aliases +from versioning.verify import inspect_links, verify_site, verify_version_aliases def sample_spec(path: str) -> bytes: @@ -76,6 +76,72 @@ def retrieve(sha, path): class PublicationTests(unittest.TestCase): + def test_moving_aliases_cover_deep_links_openapi_and_preview_prefix(self): + catalog = {"current_stable": "15"} + with tempfile.TemporaryDirectory() as temp, patch.dict("os.environ", { + "LIBRESIGN_DOC_BASE_PATH": "/site-preview/docs-preview/pr-149" + }): + site = Path(temp) + for slug in ("main", "15"): + (site / slug / "index.html").parent.mkdir(parents=True) + (site / slug / "index.html").write_text(slug) + api = site / slug / "developer_manual/api" + api.mkdir(parents=True) + (api / "openapi.html").write_text("API") + (api / "openapi.json").write_text('{"pinned": "' + slug + '"}') + (api / "openapi.provenance.json").write_text('{"branch": "' + slug + '"}') + write_version_aliases(site, catalog) + self.assertEqual(verify_version_aliases(site, catalog), []) + self.assertIn("url=/site-preview/docs-preview/pr-149/main/developer_manual/api/openapi.html", + (site / "latest/developer_manual/api/openapi.html").read_text()) + self.assertIn("url=/site-preview/docs-preview/pr-149/15/developer_manual/api/openapi.html", + (site / "stable/developer_manual/api/openapi.html").read_text()) + self.assertIn("location.search", + (site / "latest/developer_manual/api/openapi.html").read_text()) + self.assertEqual( + (site / "stable/developer_manual/api/openapi.json").read_bytes(), + (site / "15/developer_manual/api/openapi.json").read_bytes(), + ) + (site / "stable/developer_manual/api/openapi.html").unlink() + self.assertTrue(verify_version_aliases(site, catalog)) + + def test_partial_publish_refreshes_stable_alias_after_new_release(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + old, new, output = (root / "old", root / "new", root / "output") + entries = [ + {"slug": "main", "status": "development"}, + {"slug": "15", "status": "current"}, + {"slug": "14", "status": "previous"}, + ] + old.mkdir() + new.mkdir() + (old / "versions.json").write_text(json.dumps({ + "versions": entries, "current_stable": "15", + })) + (new / "versions.json").write_text(json.dumps({ + "versions": entries + [{"slug": "16", "status": "current"}], + "current_stable": "16", + })) + for slug in ("main", "15", "14"): + page = old / slug / "index.html" + page.parent.mkdir() + page.write_text(slug) + (old / "stable/index.html").parent.mkdir() + (old / "stable/index.html").write_text("STALE") + (new / "16/index.html").parent.mkdir() + (new / "16/index.html").write_text("16") + with patch("versioning.publish.legacy_redirects"), patch("versioning.publish.apply_seo"): + result = assemble(new, output, "16", old) + self.assertEqual(result["current_stable"], "16") + # Preview deployments have a site prefix; the alias verifier checks + # the full prefix and the matching versioned target. + self.assertIn("/16/index.html", (output / "stable/index.html").read_text()) + self.assertIn("/main/index.html", (output / "latest/index.html").read_text()) + self.assertNotIn("STALE", (output / "stable/index.html").read_text()) + self.assertTrue((output / "14/index.html").exists()) + self.assertEqual(verify_version_aliases(output, result), []) + def test_updating_15_preserves_existing_13_14_and_main(self): with tempfile.TemporaryDirectory() as temp: folder = Path(temp) diff --git a/versioning/publish.py b/versioning/publish.py index 40fe2c1f..a3ed2ffe 100644 --- a/versioning/publish.py +++ b/versioning/publish.py @@ -7,12 +7,49 @@ import shutil from pathlib import Path -from versioning.build import legacy_redirects +from versioning.build import legacy_redirects, redirect_html from versioning.seo import apply_seo ROOT = Path(__file__).resolve().parent.parent +def write_version_aliases(site: Path, catalog: dict) -> None: + """Publish Nextcloud-style moving aliases without replacing pinned releases. + + GitHub Pages cannot issue server-side rewrite rules. Each HTML URL gets a + small redirect to the real version so that nested links work in previews + as well as production. Only the two OpenAPI JSON files are mirrored to + support clients requesting the contract directly. + """ + current = catalog.get("current_stable") + if not isinstance(current, str) or not current.isdecimal() or current.startswith("0"): + raise ValueError("Cannot create /stable/ without a published stable release") + + for alias, target in (("latest", "main"), ("stable", current)): + source = site / target + if not (source / "index.html").is_file(): + raise ValueError(f"Missing version for /{alias}/: {target}") + destination = site / alias + if destination.is_symlink(): + raise ValueError(f"Unsafe alias destination: {alias}") + if destination.exists(): + shutil.rmtree(destination) + for page in source.rglob("*.html"): + relative = page.relative_to(source) + redirect = destination / relative + redirect.parent.mkdir(parents=True, exist_ok=True) + redirect.write_text( + redirect_html(f"/{target}/{relative.as_posix()}"), + encoding="utf-8", + ) + for filename in ("openapi.json", "openapi.provenance.json"): + source_json = source / "developer_manual" / "api" / filename + if source_json.is_file(): + target_json = destination / "developer_manual" / "api" / filename + target_json.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source_json, target_json) + + def assemble(built: Path, destination: Path, selected: str, existing: Path | None = None) -> dict: incoming = json.loads((built / "versions.json").read_text()) @@ -62,6 +99,7 @@ def assemble(built: Path, destination: Path, selected: str, if candidate.is_file(): shutil.copy2(candidate, destination / filename) legacy_redirects(destination, output_catalog["current_stable"]) + write_version_aliases(destination, output_catalog) (destination / "CNAME").write_text("docs.libresign.coop\n", encoding="utf-8") (destination / ".nojekyll").touch() apply_seo(destination, output_catalog, preview=bool(os.environ.get("LIBRESIGN_PREVIEW_PR"))) diff --git a/versioning/verify.py b/versioning/verify.py index fac1f048..adacbc7f 100644 --- a/versioning/verify.py +++ b/versioning/verify.py @@ -16,6 +16,40 @@ REQUIRED_MANUALS = ("user_manual", "admin_manual", "developer_manual") +def verify_version_aliases(output: Path, catalog: dict) -> list[str]: + """Verify moving aliases resolve to actual, version-pinned pages.""" + errors = [] + current = catalog.get("current_stable") + if not isinstance(current, str) or not current.isdecimal() or current.startswith("0"): + return ["Missing valid current_stable for /stable/"] + prefix = os.environ.get("LIBRESIGN_DOC_BASE_PATH", "").rstrip("/") + for alias, target in (("latest", "main"), ("stable", current)): + source, redirect_root = output / target, output / alias + if not source.is_dir() or not redirect_root.is_dir(): + errors.append(f"Missing /{alias}/ alias source or target") + continue + expected = {p.relative_to(source) for p in source.rglob("*.html")} + actual = {p.relative_to(redirect_root) for p in redirect_root.rglob("*.html")} + if expected != actual: + missing = sorted(str(p) for p in expected - actual) + extra = sorted(str(p) for p in actual - expected) + errors.append(f"/{alias}/ pages missing={missing[:5]} extra={extra[:5]}") + for relative in expected & actual: + path = redirect_root / relative + content = path.read_text(encoding="utf-8") + target_url = f"{prefix}/{target}/{relative.as_posix()}" + if (f"url={target_url}" not in content or + "location.search" not in content or "location.hash" not in content): + errors.append(f"Incorrect /{alias}/ redirect: {relative}") + for filename in ("openapi.json", "openapi.provenance.json"): + relative = Path("developer_manual/api") / filename + pinned = source / relative + moving = redirect_root / relative + if pinned.is_file() and (not moving.is_file() or pinned.read_bytes() != moving.read_bytes()): + errors.append(f"/{alias}/ {filename} differs from {target}") + return errors + + class PageLinks(HTMLParser): def __init__(self) -> None: super().__init__() @@ -157,6 +191,7 @@ def verify_site(output: Path, versions: list[str] | None = None, for page in (output / slug).rglob("*.html"): errors.extend(inspect_links(output, page)) if (output / ".nojekyll").exists(): + errors.extend(verify_version_aliases(output, catalog)) errors.extend(verify_seo(output, catalog, preview=bool(os.environ.get("LIBRESIGN_PREVIEW_PR")))) if errors: