Bundle: redb-route / demo/As4OutboxDemo (demo.As4OutboxDemo.txt), 7 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/demo/As4OutboxDemo/As4Module/As4Module.config.json Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Module/As4Module.config.json ---- { "ContextName": "as4", "AutoStart": true } Path: redb-route/demo/As4OutboxDemo/As4Module/As4Module.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Module/As4Module.csproj ---- net10.0 enable enable As4Module false As4Module <_TpkgStaging>$(IntermediateOutputPath)tpkg <_TpkgFile>$(MSBuildThisFileDirectory)output\$(TsakModuleName).tpkg Path: redb-route/demo/As4OutboxDemo/As4Module/InitRoute.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Module/InitRoute.cs ---- using System.Security.Cryptography.X509Certificates; using redb.Route.Abstractions; // IRouteContext, IExchange using redb.Route.As4; // As4Component, As4ConnectionFactory, As4Partner, As4Headers, exceptions using redb.Route.As4.Fluent; // As4.Send / As4.Receive using redb.Route.Components; // AddIdempotentRepository using redb.Route.Core; // RouteContext using redb.Route.File; // FileComponent, FileDsl, FileHeaders using redb.Route.Processors; // InMemoryIdempotentRepository namespace As4Module; /// /// Tsak module entry point: an AS4 outbox and inbox. /// /// The worker discovers it by convention (a public static class InitRoute with a public static /// main(IRouteContext)) and calls it once when the module loads; the debug host (As4Worker/Program.cs) calls the /// very same method. /// /// /// {AS4_DEMO_DIR}/outbox/* --file--> AS4 send to partner "demo-partner" --receipt--> moved to sent/ /// | not delivered after 3 redeliveries --> moved to failed/ /// AS4 receive :4090/as4/in --> duplicates dropped --> {AS4_DEMO_DIR}/inbox/{original file name} /// /// /// The node sends to its own receiver (the partner is ourselves, with our certificate), so the demo runs with nothing /// else installed. For a real partner, give its party id, service, action and certificates, and /// point the send URI at its access point. /// /// public static class InitRoute { /// Port of the AS4 receiver (the AS4 connector's default). public const int Port = 4090; /// Password of the demo PFX the debug host generates in certs/node.pfx. public const string PfxPassword = "demo"; public static IRouteContext main(IRouteContext context) { // The working folder: certs/node.pfx, outbox/, sent/, failed/, inbox/. Named explicitly: a path relative to the // current directory would depend on where the worker was started from. var dir = Environment.GetEnvironmentVariable("AS4_DEMO_DIR") ?? throw new InvalidOperationException("Set AS4_DEMO_DIR to the demo folder (certs/node.pfx, outbox/, inbox/)."); string Sub(string name) => Path.Combine(dir, name); // Where the outbox sends: the partner's access point. The demo partner is ourselves, so by default our own // receiver; set AS4_DEMO_PARTNER_URL to send elsewhere (a closed port shows the redeliveries and failed/). var partnerUrl = Environment.GetEnvironmentVariable("AS4_DEMO_PARTNER_URL") is { Length: > 0 } url ? url : $"http://127.0.0.1:{Port}/as4/in"; // Our key: signs messages and receipts, decrypts what the partner encrypts for us. var node = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(dir, "certs", "node.pfx"), PfxPassword); // The partner's public certificate: here our own, since the demo partner is ourselves. var partner = X509CertificateLoader.LoadCertificate(node.Export(X509ContentType.Cert)); context.AddComponent(new As4Component()); context.AddComponent(new FileComponent()); // ── The node (our access point) and its one agreement ──────────────────── context.AddToRegistry("node", new As4ConnectionFactory { OurPartyId = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:redb-demo", ExternalHostName = "as4.redb-demo.example", // host part of our message ids SigningCertificate = node, DecryptionCertificates = { node }, Partners = { new As4Partner { Name = "demo-partner", PartyId = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:redb-demo", Service = "urn:redb:demo:services:documents", Action = "Deliver", PartnerSigningCertificates = { partner }, // verifies the partner's signatures PartnerEncryptionCertificate = partner, // we encrypt payloads for the partner }, }, }); // Remembers received message ids: a resend is answered with a receipt and not delivered twice. In memory for the // demo; behind a load balancer, or to survive a restart, register the redb or SQL repository instead. context.AddIdempotentRepository("as4-in", new InMemoryIdempotentRepository(TimeSpan.FromDays(7))); ((RouteContext)context).AddRoutes(r => { // ── No receipt, or an ebMS error: three redeliveries of the same message, then failed/ ── // A redelivery sends the same bytes (same message id, same signature), so the partner detects the duplicate. r.OnException() .MaximumRedeliveries(3) .RedeliveryDelay(TimeSpan.FromSeconds(2)) .UseExponentialBackOff() .Log("AS4 not delivered: ${header.redbFile.Name} (${header.redbAs4.messageId})"); // The partner's access point unreachable (refused, DNS, TLS): the same policy. r.OnException() .MaximumRedeliveries(3) .RedeliveryDelay(TimeSpan.FromSeconds(2)) .UseExponentialBackOff() .Log("AS4 not delivered, partner unreachable: ${header.redbFile.Name} (${header.redbAs4.messageId})"); r.OnException() .Log("AS4 refused by the partner: ${header.redbFile.Name} (${header.redbAs4.messageId})"); // ── Outbox: every file dropped into outbox/ is sent as one AS4 message ────── // Delivered: moved to sent/. Not delivered (the exchange failed after the redeliveries): moved to failed/. r.From(FileDsl.Read(Sub("outbox")).Delay(1000).MoveTo(Sub("sent")).MoveFailed(Sub("failed"))) .RouteId("as4-outbox") // eDelivery four-corner properties: mandatory on every message. .SetHeader(As4Headers.OriginalSender, "urn:redb:demo:c1") .SetHeader(As4Headers.FinalRecipient, "urn:redb:demo:c4") // Any other redbAs4.property.* header travels as an eb:Property: the receiver restores the file name. .SetHeader(As4Headers.PropertyPrefix + "fileName", e => e.In.GetHeader(FileHeaders.FileName)) .Process(e => e.In.ContentType ??= ContentTypeOf(e.In.GetHeader(FileHeaders.FileName))) .To(As4.Send(partnerUrl).ConnectionFactory("node").Partner("demo-partner").Timeout(30000)) .Log("AS4 sent ${header.redbFile.Name}: message ${header.redbAs4.messageId}, receipt ${header.redbAs4.receiptMessageId}"); // ── Inbox: our access point; one URL for every partner of the node ──────── r.From(As4.Receive("/as4/in").Port(Port).ConnectionFactory("node").IdempotentRepository("as4-in")) .RouteId("as4-inbox") .Log("AS4 received from ${header.redbAs4.partner}: ${header.redbAs4.property.fileName} (${header.redbAs4.messageId})") .To(FileDsl.Write(Sub("inbox")).AutoCreate().FileName("${header.redbAs4.property.fileName}")); }); return context; } // The payload's media type travels in its eb:PartInfo; a file carries none, so it is taken from the extension. private static string ContentTypeOf(string? fileName) => Path.GetExtension(fileName)?.ToLowerInvariant() switch { ".xml" => "application/xml", ".json" => "application/json", ".txt" => "text/plain", ".pdf" => "application/pdf", _ => "application/octet-stream", }; } Path: redb-route/demo/As4OutboxDemo/As4Module/manifest.json Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Module/manifest.json ---- { "Name": "As4Module", "Version": "1.0.0", "EntryPoints": ["As4Module.dll"], "Dependencies": [] } Path: redb-route/demo/As4OutboxDemo/As4Worker/As4Worker.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Worker/As4Worker.csproj ---- Exe net10.0 enable enable As4Worker false Path: redb-route/demo/As4OutboxDemo/As4Worker/Program.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/As4Worker/Program.cs ---- // ============================================================================ // As4Worker — a debug host for the As4Module Tsak module. // // What the Tsak worker does, in the smallest possible way: // 1) prepare the demo folder: a self-signed certificate (DEMO ONLY) and outbox/, inbox/; // 2) hand a RouteContext to As4Module.InitRoute.main — the SAME entry point the worker calls; // 3) drop one sample document into outbox/, so the first round trip happens by itself. // // Then drop any file into as4-demo/outbox: it is signed, encrypted and sent over AS4, the receiver verifies // it and writes it to as4-demo/inbox, and the signed receipt is logged. // ============================================================================ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Core; // RouteContext namespace As4Worker; public static class Program { public static async Task Main(string[] args) { // ── The demo folder next to the exe (not the current directory: that depends on where you start it) ── var dir = args.Length > 0 ? Path.GetFullPath(args[0]) : Path.Combine(AppContext.BaseDirectory, "as4-demo"); foreach (var sub in new[] { "certs", "outbox", "sent", "failed", "inbox" }) Directory.CreateDirectory(Path.Combine(dir, sub)); EnsureDemoCertificate(Path.Combine(dir, "certs", "node.pfx")); Environment.SetEnvironmentVariable("AS4_DEMO_DIR", dir); // ── DI: console logging ── var services = new ServiceCollection(); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); var sp = services.BuildServiceProvider(); // ── Build a route context and call the module entry point ── var ctx = new RouteContext(sp, contextId: "as4-worker"); ctx.AddService(typeof(ILoggerFactory), sp.GetRequiredService()); As4Module.InitRoute.main(ctx); // <- the exact method the Tsak worker calls await ctx.Start(); // ── One sample document, so the first round trip happens by itself ── var sample = Path.Combine(dir, "outbox", $"invoice-{DateTime.Now:HHmmss}.xml"); await File.WriteAllTextAsync(sample, "INV-001120.00"); Console.WriteLine(); Console.WriteLine($"As4Worker running. AS4 receiver: http://localhost:{As4Module.InitRoute.Port}/as4/in"); Console.WriteLine($" drop files into {Path.Combine(dir, "outbox")}"); Console.WriteLine($" received land in {Path.Combine(dir, "inbox")}"); Console.WriteLine($" sent are moved to {Path.Combine(dir, "sent")}, undelivered moved to {Path.Combine(dir, "failed")}"); Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); var stop = new ManualResetEventSlim(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Set(); }; stop.Wait(); await ctx.DisposeAsync(); } // DEMO ONLY: a self-signed RSA certificate that signs and decrypts for both sides of the loopback. A real node holds // the certificate its PKI (or the network's, e.g. PEPPOL) issued, and the partner's certificate is the partner's. private static void EnsureDemoCertificate(string path) { if (File.Exists(path)) return; using var rsa = RSA.Create(2048); var request = new CertificateRequest("CN=redb-demo AS4 node", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension( X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, critical: false)); using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(2)); File.WriteAllBytes(path, certificate.Export(X509ContentType.Pfx, As4Module.InitRoute.PfxPassword)); Console.WriteLine($"Generated a self-signed demo certificate: {path}"); } } Path: redb-route/demo/As4OutboxDemo/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/As4OutboxDemo/README.md ---- # As4OutboxDemo — an AS4 outbox and inbox as a redb.Route module + a debug host Files dropped into a folder are sent as AS4 messages (eDelivery AS4 1.16: signed, encrypted, compressed); the receiver verifies them, drops duplicates, writes the document to another folder, and answers with a signed receipt that the sender verifies. Two projects, one entry point: `InitRoute.main` is called by both the Tsak worker and the debug host, so the route code is never duplicated (the layout of [EchoWorkerDemo](../EchoWorkerDemo)). ``` As4OutboxDemo/ ├─ As4Module/ <- the module (class library -> As4Module.tpkg) │ ├─ InitRoute.cs <- main(IRouteContext): the node, the agreement, 2 routes │ ├─ manifest.json <- { Name, Version, EntryPoints: ["As4Module.dll"] } │ └─ As4Module.csproj <- + the PackTpkg target (zips manifest + DLL) └─ As4Worker/ <- the debug host (exe) ├─ Program.cs <- demo folder + self-signed certificate + InitRoute.main(ctx) + Start └─ As4Worker.csproj ``` ## What it does ``` as4-demo/outbox/* ──file──> AS4 send to "demo-partner" ──signed receipt──> moved to as4-demo/sent/ │ not delivered after 3 redeliveries / ebMS error ──> moved to as4-demo/failed/ AS4 receive :4090/as4/in ──duplicates dropped──> as4-demo/inbox/ ``` | Route | What it shows | |---|---| | `as4-outbox` | `file:` consumer → the eDelivery four-corner properties (`originalSender`, `finalRecipient`) → the file name as an `eb:Property` → `As4.Send(...)`; the receipt id is on the exchange after the send. | | `as4-inbox` | `As4.Receive(...)` with an `IIdempotentRepository` (mandatory: a resend gets its receipt again and is not delivered twice) → `file:` producer, the name restored from the `eb:Property`. | | `OnException` | `As4ReceiptException` (no receipt, bad receipt) and `HttpRequestException` (the access point unreachable): three redeliveries of **the same bytes** (same message id and signature, so the partner detects the duplicate); `As4ErrorSignalException` (the partner refused): no redelivery. The handlers only log; the exchange then fails and the file consumer moves the file to `failed/` (`MoveFailed`), a delivered one to `sent/` (`MoveTo`). | The node sends to **its own** receiver: the partner is ourselves, with our certificate, so the demo runs with nothing else installed. Every step is real (XML Signature over the attachments, AES-128-GCM, RSA-OAEP, gzip, the receipt's non-repudiation digests); only the other party is missing. To watch the failure path, send to a closed port: ```powershell $env:AS4_DEMO_PARTNER_URL = "http://127.0.0.1:4099/as4/in"; dotnet run --project As4Worker # Retries exhausted for HttpRequestException after 3 attempts # AS4 not delivered, partner unreachable: invoice-....xml (...) -> the file is in as4-demo/failed/ ``` ## Debug (no Tsak) ```bash dotnet run --project As4Worker ``` On first start the host creates `as4-demo/` next to the exe (`certs/node.pfx` a self-signed demo certificate, `outbox/`, `sent/`, `failed/`, `inbox/`) and drops a sample `invoice-HHmmss.xml` into `outbox/`. Within a second: ``` AS4 received from demo-partner: invoice-001808.xml (613355fa-...@as4.redb-demo.example) AS4 sent invoice-001808.xml: message 613355fa-...@as4.redb-demo.example, receipt 5e825a25-... ``` Drop any file into `as4-demo/outbox`; it arrives in `as4-demo/inbox` under its own name. A folder of your choice: `dotnet run --project As4Worker -- D:\as4-demo`. ## From the demo to a real partner In `InitRoute.cs`: 1. **Our node**: `OurPartyId` (the id the network assigned, e.g. a PEPPOL participant id), `ExternalHostName`, and our certificate from our PKI instead of the self-signed one (`certs/node.pfx`, password `InitRoute.PfxPassword`). 2. **The partner**: its `PartyId`, the `Service` and `Action` you agreed on, and its certificates (`PartnerSigningCertificates`, `PartnerEncryptionCertificate`). 3. **The send URI**: the partner's access point, `AS4_DEMO_PARTNER_URL` (default: our own receiver). 4. **The duplicate store**: a redb or SQL `IIdempotentRepository` instead of the in-memory one, so ids survive a restart and are shared across nodes. The options and what the connector refuses are in the [connector README](../../redb.Route.As4/README.md). ## Build the .tpkg and deploy to a worker ```bash dotnet build As4Module -c Debug # -> As4Module/output/As4Module.tpkg (inside: As4Module.dll + manifest.json + As4Module.config.json) ``` Copy the `.tpkg` into the Tsak worker's `modules/` folder, set `AS4_DEMO_DIR` for the worker (the folder with `certs/node.pfx`, `outbox/`, `inbox/`), and the worker picks the module up by hot-reload. The `.tpkg` carries only the module DLL: `redb.Route.As4` and `redb.Route.File` come from the worker's shared libraries. `redb.Route.As4` is on NuGet; this module references the sources of the repository, and a standalone copy can take the package instead.