{
  "name": "Copy postmortems to Confluence",
  "nodes": [
    {
      "name": "Tellagen webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [0, 0],
      "webhookId": "tellagen-postmortem",
      "parameters": {
        "httpMethod": "POST",
        "path": "tellagen-postmortem",
        "responseMode": "responseNode",
        "options": {
          "rawBody": true
        }
      }
    },
    {
      "name": "Check the signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [220, 0],
      "parameters": {
        "jsCode": "const crypto = require(\"crypto\");\nconst item = $input.first();\nconst h = item.json.headers;\nconst raw = Buffer.from(item.binary.data.data, \"base64\").toString(\"utf8\");\nconst age = Math.abs(Date.now() / 1000 - Number(h[\"webhook-timestamp\"]));\nconst mac = crypto.createHmac(\"sha256\", $env.WEBHOOK_SECRET).update(`${h[\"webhook-id\"]}.${h[\"webhook-timestamp\"]}.${raw}`).digest();\nconst ok = age < 300 && String(h[\"webhook-signature\"]).split(\" \").some((part) => {\n  const given = Buffer.from(part.replace(/^v1,/, \"\"), \"base64\");\n  return part.startsWith(\"v1,\") && given.length === mac.length && crypto.timingSafeEqual(given, mac);\n});\nif (!ok) throw new Error(\"Wrong signature\");\nconst seen = $getWorkflowStaticData(\"global\");\nseen.ids = seen.ids || [];\nconst event = JSON.parse(raw);\nconst skip = seen.ids.includes(h[\"webhook-id\"]) || ![\"postmortem.published\", \"postmortem.content_changed\"].includes(event.type);\nif (!skip) seen.ids = [...seen.ids.slice(-199), h[\"webhook-id\"]];\nreturn [{ json: { event, skip } }];"
      }
    },
    {
      "name": "Render",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [880, 0],
      "parameters": {
        "url": "={{ $env.TELLAGEN_API }}/api/v1/postmortems/{{ $json.event.data.version.id }}/render?format=confluence_storage",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.TELLAGEN_KEY }}"
            }
          ]
        }
      }
    },
    {
      "name": "Copy to Confluence",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1100, 0],
      "parameters": {
        "jsCode": "const { event } = $(\"Check the signature\").first().json;\nconst render = $input.first().json;\nconst wiki = $env.CONFLUENCE + \"/wiki\";\nconst call = (method, path, body) => this.helpers.httpRequest({ method, url: wiki + path, body, json: true, headers: { Authorization: \"Bearer \" + $env.CONFLUENCE_TOKEN } });\nconst title = `${event.resource.incident_reference} postmortem`;\nconst found = (await call(\"GET\", `/api/v2/pages?spaceId=${$env.SPACE_ID}&title=${encodeURIComponent(title)}`)).results[0];\nconst page = found || await call(\"POST\", \"/api/v2/pages\", { spaceId: $env.SPACE_ID, parentId: $env.PARENT_ID, title, body: { representation: \"storage\", value: \"<p>Copying from Tellagen.</p>\" } });\nfor (const file of render.attachments.filter((a) => a.kind !== \"chart_numbers\")) {\n  const bytes = await this.helpers.httpRequest({ url: file.url, encoding: \"arraybuffer\", returnFullResponse: false });\n  await this.helpers.httpRequest({\n    method: \"PUT\", url: `${wiki}/rest/api/content/${page.id}/child/attachment`,\n    headers: { Authorization: \"Bearer \" + $env.CONFLUENCE_TOKEN, \"X-Atlassian-Token\": \"no-check\" },\n    formData: { file: { value: Buffer.from(bytes), options: { filename: file.name, contentType: file.content_type } } },\n  });\n}\nconst current = (await call(\"GET\", `/api/v2/pages/${page.id}`)).version.number;\nconst updated = await call(\"PUT\", `/api/v2/pages/${page.id}`, { id: page.id, status: \"current\", title, body: { representation: \"storage\", value: render.body }, version: { number: current + 1, message: `Tellagen v${event.data.version.label}` } });\nawait call(\"POST\", `/api/v2/pages/${page.id}/properties`, { key: \"editor\", value: \"v2\" }).catch(() => {});\nreturn [{ json: { incident_id: event.resource.incident_id, version_id: event.data.version.id, url: updated._links.base + updated._links.webui, content_sha256: render.content_sha256 } }];"
      }
    },
    {
      "name": "Report the copy",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1320, 0],
      "parameters": {
        "method": "PUT",
        "url": "={{ $env.TELLAGEN_API }}/api/v1/incidents/{{ $json.incident_id }}/postmortem/external-copies/wiki",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.TELLAGEN_KEY }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ url: $json.url, system: 'Confluence', version_id: $json.version_id, content_sha256: $json.content_sha256 }) }}"
      }
    },
    {
      "name": "Answer 204",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [440, 0],
      "parameters": {
        "respondWith": "noData",
        "options": {
          "responseCode": 204
        }
      }
    },
    {
      "name": "Only new events",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [660, 0],
      "parameters": {
        "jsCode": "return $input.all().filter((item) => !item.json.skip);"
      }
    },
    {
      "name": "Tellagen check",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [0, 240],
      "webhookId": "tellagen-postmortem-check",
      "parameters": {
        "httpMethod": "OPTIONS",
        "path": "tellagen-postmortem",
        "responseMode": "responseNode"
      }
    },
    {
      "name": "Prove consent",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [220, 240],
      "parameters": {
        "jsCode": "const crypto = require(\"crypto\");\nconst challenge = $input.first().json.headers[\"tellagen-webhook-challenge\"];\nif (typeof challenge !== \"string\" || !/^[A-Za-z0-9+/]{43}=$/.test(challenge)) throw new Error(\"Bad challenge\");\nconst proof = crypto.createHmac(\"sha256\", $env.WEBHOOK_SECRET).update(\"tellagen-webhook-verification-v1:\" + challenge).digest(\"base64\");\nreturn [{ json: { proof } }];"
      }
    },
    {
      "name": "Answer the check",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [440, 240],
      "parameters": {
        "respondWith": "noData",
        "options": {
          "responseCode": 204,
          "responseHeaders": {
            "entries": [
              {
                "name": "Tellagen-Webhook-Proof",
                "value": "={{ $json.proof }}"
              }
            ]
          }
        }
      }
    }
  ],
  "connections": {
    "Tellagen webhook": {
      "main": [
        [
          {
            "node": "Check the signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check the signature": {
      "main": [
        [
          {
            "node": "Answer 204",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Answer 204": {
      "main": [
        [
          {
            "node": "Only new events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Only new events": {
      "main": [
        [
          {
            "node": "Render",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Render": {
      "main": [
        [
          {
            "node": "Copy to Confluence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Copy to Confluence": {
      "main": [
        [
          {
            "node": "Report the copy",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tellagen check": {
      "main": [
        [
          {
            "node": "Prove consent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prove consent": {
      "main": [
        [
          {
            "node": "Answer the check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}
