Kod örnekleri

Örnek dosyaları indir (ZIP)

cloudflared.example.yml
# Yalnızca çevrimdışı ingress doğrulaması için; tünel kimliği içermez.
# Yerel yönetilen bir tünelde bunun üstüne tünel UUID ve credential dosyası gelir.
ingress:
  - hostname: events.example
    path: '^/webhook/alinan-olay$'
    service: http://127.0.0.1:8787
  - service: http_status:404
n8n.env.example
# Yalnızca bu örnekteki güven sınırı için. Alanlar temsili ve çözümlenmez.
N8N_EDITOR_BASE_URL=https://editor.example/
WEBHOOK_URL=https://events.example/
N8N_PROXY_HOPS=1
# Aynı ağ ad alanında çalışan örnek için; konteyner topolojisine kopyalamayın.
N8N_LISTEN_ADDRESS=127.0.0.1
N8N_PORT=5678
proxy.mjs
// Loopback referansı; n8n kendi Header Auth kontrolünü ayrıca yapar.
import { createServer, request } from 'node:http';
import { pathToFileURL } from 'node:url';

export const host = 'events.example';
export const route = '/webhook/alinan-olay';
export const authHeader = 'x-webhook-key';
export const limit = 16 * 1024;

export function makeProxy(upstreamPort = 5678) {
  return createServer({ requestTimeout: 10_000, headersTimeout: 5_000 }, (req, res) => {
    const finish = status => {
      if (res.headersSent) return res.destroy();
      res.writeHead(status, { connection: 'close', 'cache-control': 'no-store' });
      res.end();
    };
    if (req.headers.host !== host || req.url !== route) return finish(404);
    if (req.method !== 'POST') return finish(405);
    const key = req.headersDistinct[authHeader];
    if (key?.length !== 1 || !/^[A-Za-z0-9_-]{32,128}$/.test(key[0])) return finish(403);
    if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json') return finish(415);
    if (req.headers['content-encoding'] || req.headers['transfer-encoding']) return finish(400);
    const rawLength = req.headers['content-length'];
    if (!rawLength || !/^\d+$/.test(rawLength)) return finish(411);
    const length = Number(rawLength);
    if (length > limit) return finish(413);
    const body = [];
    let bytes = 0;
    req.on('data', buffer => {
      bytes += buffer.length;
      if (bytes <= limit) body.push(buffer);
      else { finish(413); req.destroy(); }
    });
    req.on('end', () => {
      if (res.headersSent) return;
      if (bytes !== length) return finish(400);
      const raw = Buffer.concat(body);
      try {
        const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
        if (value === null || Array.isArray(value) || typeof value !== 'object') return finish(400);
      } catch { return finish(400); }
      const upstream = request({ host: '127.0.0.1', port: upstreamPort, path: route, method: 'POST', timeout: 5_000,
        headers: { host, 'content-type': 'application/json', 'content-length': bytes, [authHeader]: key[0],
          'x-forwarded-host': host, 'x-forwarded-proto': 'https', 'x-forwarded-for': req.socket.remoteAddress } }, reply => {
        res.writeHead(reply.statusCode, { 'cache-control': 'no-store', 'content-type': 'application/json' });
        reply.on('error', () => res.destroy());
        reply.pipe(res);
      });
      upstream.on('timeout', () => upstream.destroy());
      upstream.on('error', () => finish(502));
      res.on('close', () => upstream.destroy());
      upstream.end(raw);
    });
  }).setTimeout(10_000, socket => socket.destroy());
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  makeProxy().listen(8787, '127.0.0.1', () => console.log('Yalnız loopback: 127.0.0.1:8787'));
}
proxy.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createServer, request } from 'node:http';
import { randomBytes } from 'node:crypto';
import { once } from 'node:events';
import { readFile } from 'node:fs/promises';
import { makeProxy, host, route, authHeader, limit } from './proxy.mjs';

const listen = async server => { server.listen(0, '127.0.0.1'); await once(server, 'listening'); return server.address().port; };
const response = (port, overrides = {}) => new Promise((resolve, reject) => {
  const payload = overrides.body ?? '{"event":"demo"}';
  const req = request({ hostname: '127.0.0.1', port, method: overrides.method ?? 'POST', path: overrides.path ?? route,
    headers: { host, 'content-length': Buffer.byteLength(payload), 'content-type': 'application/json', ...overrides.headers } }, reply => {
    reply.on('error', reject); reply.resume(); reply.on('end', () => resolve(reply.statusCode));
  });
  req.on('error', reject); req.end(payload);
});

test('webhook JSON: gerçek başlık doğrulaması istenir; credential taşınmaz', async () => {
  const w = JSON.parse(await readFile(new URL('./webhook-workflow.json', import.meta.url), 'utf8'));
  assert.equal(w.active, false);
  assert.equal(w.nodes.length, 1);
  const [node] = w.nodes;
  assert.equal(node.type, 'n8n-nodes-base.webhook');
  assert.equal(node.parameters.authentication, 'headerAuth');
  assert.equal(node.parameters.httpMethod, 'POST');
  assert.equal(`/webhook/${node.parameters.path}`, route);
  assert.equal(node.parameters.options.responseCode.values.customCode, 202);
  assert.equal(node.credentials, undefined);
});

test('loopback HTTP: izinli ve reddedilen yollar, gövdeler ve iki katman', async t => {
  const secret = randomBytes(32).toString('base64url');
  const received = [];
  const mockN8n = createServer((req, res) => {
    received.push(req.headers);
    req.resume();
    res.writeHead(req.headers[authHeader] === secret ? 202 : 403).end();
  });
  const originPort = await listen(mockN8n);
  t.after(() => mockN8n.close());
  const proxy = makeProxy(originPort);
  const port = await listen(proxy);
  t.after(() => proxy.close());
  const allowed = { [authHeader]: secret };
  for (const [name, expected, options] of [
    ['editör ana makinesi', 404, { headers: { ...allowed, host: 'editor.example' } }],
    ['kök', 404, { path: '/', headers: allowed }],
    ['API', 404, { path: '/rest/workflows', headers: allowed }],
    ['test URL’si', 404, { path: '/webhook-test/alinan-olay', headers: allowed }],
    ['başka webhook', 404, { path: '/webhook/diger', headers: allowed }],
    ['ek yol', 404, { path: `${route}/`, headers: allowed }],
    ['sorgu dizgesi', 404, { path: `${route}?x=1`, headers: allowed }],
    ['GET', 405, { method: 'GET', headers: allowed }],
    ['anahtar yok', 403, {}],
    ['anahtar tekrar ediyor', 403, { headers: { [authHeader]: [secret, secret] } }],
    ['farklı içerik türü', 415, { headers: { ...allowed, 'content-type': 'text/plain' } }],
    ['JSON bozuk', 400, { body: '{', headers: allowed }],
    ['JSON nesne değil', 400, { body: '[1]', headers: allowed }],
    ['gövde büyük', 413, { body: 'x'.repeat(limit + 1), headers: allowed }],
  ]) {
    await t.test(name, async () => assert.equal(await response(port, options), expected));
  }
  assert.equal(received.length, 0);
  await t.test('biçim doğru, anahtar yanlış: origin reddeder', async () => {
    assert.equal(await response(port, { headers: { [authHeader]: randomBytes(32).toString('base64url') } }), 403);
    assert.equal(received.length, 1);
  });
  await t.test('doğru anahtar 202 ve yönlendirme başlıkları vekilden', async () => {
    assert.equal(await response(port, { headers: { ...allowed, 'x-forwarded-host': 'editor.example', 'x-forwarded-for': '203.0.113.17', 'x-forwarded-proto': 'http' } }), 202);
    assert.equal(received.length, 2);
    assert.equal(received[1]['x-forwarded-host'], host);
    assert.equal(received[1]['x-forwarded-for'], '127.0.0.1');
    assert.equal(received[1]['x-forwarded-proto'], 'https');
  });
});
test-ingress.sh
#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
cf=${CLOUDFLARED:-cloudflared}
config=cloudflared.example.yml
"$cf" --version
"$cf" tunnel --config "$config" ingress validate
check() {
  local url=$1 expected=$2 out
  out=$("$cf" tunnel --config "$config" ingress rule "$url" 2>&1)
  if ! grep -Fq "service: $expected" <<< "$out"; then
    printf 'Beklenmeyen kural: %s\n%s\n' "$url" "$out" >&2
    exit 1
  fi
  printf '%s → %s\n' "$url" "$expected"
}
check https://events.example/webhook/alinan-olay http://127.0.0.1:8787
check https://events.example/ http_status:404
check https://events.example/rest/workflows http_status:404
check https://events.example/webhook-test/alinan-olay http_status:404
check https://events.example/webhook/diger http_status:404
check https://events.example/webhook/alinan-olay/ http_status:404
check https://events.example/webhook/alinan-olay-ek http_status:404
check https://editor.example/webhook/alinan-olay http_status:404
webhook-workflow.json
{
  "name": "BAA | Tek olay URL'si (kapalı demo)",
  "active": false,
  "settings": {"executionOrder": "v1"},
  "nodes": [
    {
      "id": "8cd045fb-9c5a-4fb6-9e8b-81e9d5dd4d3a",
      "name": "Olay al (Header Auth)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [0, 0],
      "webhookId": "b19aa2a6-1f86-4309-ad2b-be9956f405bf",
      "parameters": {
        "httpMethod": "POST",
        "path": "alinan-olay",
        "authentication": "headerAuth",
        "responseMode": "onReceived",
        "options": {"responseCode": {"values": {"responseCode": "customCode", "customCode": 202}}}
      }
    }
  ],
  "connections": {},
  "pinData": {}
}