Z-Ray (two better than X)

Z-Ray Engine Architecture & Documentation

The Z-Ray Engine is a minimalist, zero-backend flat-file content management system and technical publishing platform. Rather than relying on external static site generators (like Hugo, Jekyll, or Astro) or heavy server-side runtimes (like WordPress, Node.js, or Ghost), Z-Ray executes natively inside the Caddy v2 web server using its built-in Go templating engine, Goldmark Markdown parser, and Chroma syntax highlighter.


1. Design Philosophy

Modern web publishing often falls into two extremes:

  1. Dynamic CMS Platforms (WordPress, Ghost, Django): Require databases, runtime application servers, background daemons, security patching, and significant memory footprints.
  2. Static Site Generators (SSGs): Require local build steps, complex CLI tooling, node_modules dependencies, and CI/CD deployment pipelines just to publish a minor typo fix.

Z-Ray eliminates both.


2. Directory Structure

The site architecture separates engine layout, reusable components, and content into isolated directories:

example.com/
├── layout.html          # Master HTML shell & Caddy routing controller
├── style.css            # Responsive monospace terminal stylesheet
├── includes/
│   └── menu.html        # Reusable navigation bar partial
└── content/
    ├── index.md         # Home page (served at /)
    ├── projects.md      # Projects directory (served at /projects)
    ├── notes.md         # Dynamic notes index (served at /notes)
    └── notes/           # Individual notes and documentation
        ├── customize-header.md
        ├── markdown-reference.md
        └── z-ray-engine.md

3. How It Works: The Request Lifecycle

When a visitor requests a URL (such as https://example.com/notes/z-ray-engine), the engine follows a strict multi-stage lifecycle:

[ Client Request: /notes/z-ray-engine ]
[ Caddy Web Server: Rewrite to /layout.html ]
[ 1. URL Path Normalization & Cleaning ]
   - Extracts .OriginalReq.URL.Path
   - Strips trailing slashes via trimSuffix
   - Maps "/" or empty paths to "/index"
[ 2. File Resolution & Traversal Defense ]
   - Translates path to: /content/notes/z-ray-engine.md
   - Enforces strict directory boundary (blocks /../)
   - Checks file existence on disk via fileExists
[ 3. Ingestion & SSTI Isolation ]
   - Standard Posts/Notes: Read raw text safely via readFile
   - Index/Notes Hub: Executed dynamically via include
[ 4. Frontmatter & Markdown Processing ]
   - splitFrontMatter divides YAML metadata from body
   - Extracts title, date, description, and draft status
   - markdown parses body via Goldmark into semantic HTML
[ 5. Master Layout Injection ]
   - Injects canonical tags, Open Graph meta, and title
   - Renders header, navigation (includes/menu.html), and article
   - Returns complete HTTP/2 or HTTP/3 response

4. Frontmatter Specification

Every Markdown document authored for Z-Ray can supply a YAML frontmatter block enclosed by triple dashes (---) at the top of the file.

Schema Definition

---
title: "Your Post Title"
date: "YYYY-MM-DD"
description: "A 140-160 character summary for search engines and social cards."
draft: false
---

Supported Fields

Field Type Required? Purpose
title string Yes Injected into <title>, Open Graph tags, and the top <h1>.
date string Optional Publication date (ISO format YYYY-MM-DD). Drives the notes index sorting and note timestamp.
description string Recommended Meta description for SEO, Google search snippets, and Open Graph cards.
draft boolean Optional If true, the post is hidden from the /notes index listing.

5. Master Layout Controller (layout.html)

layout.html acts as the brain of the Z-Ray engine. Below is the hardened routing and rendering pipeline:

<!-- Clean and normalize incoming path -->
{{$rawPath := .OriginalReq.URL.Path}}
{{$path := clean $rawPath}}
{{$path = trimSuffix "/" $path}}

{{if or (eq $path "") (eq $path "/index")}}
    {{$path = "/index"}}
{{end}}

<!-- Strict boundary check: disallow directory traversal -->
{{$isSafe := not (hasPrefix "/../" $path)}}
{{$mdFile := printf "/content%s.md" $path}}
{{$exists := and $isSafe (fileExists $mdFile)}}

{{$title := "404 - Not Found"}}
{{$body := ""}}
{{$date := ""}}
{{$desc := ""}}
{{$isPost := and (hasPrefix "/notes/" $path) (ne $path "/notes/")}}

{{if $exists}}
    <!-- Safe ingestion: readFile protects standard posts against SSTI -->
    {{if eq $path "/notes"}}
        {{$doc := splitFrontMatter (include $mdFile)}}
        {{$title = "Notes"}}
        {{if and $doc.Meta $doc.Meta.title}}{{$title = $doc.Meta.title}}{{end}}
        {{if and $doc.Meta $doc.Meta.description}}{{$desc = $doc.Meta.description}}{{end}}
        {{$body = $doc.Body}}
    {{else}}
        {{$doc := splitFrontMatter (readFile $mdFile)}}
        {{$title = "Example Site"}}
        {{if $doc.Meta}}
            {{if $doc.Meta.title}}{{$title = $doc.Meta.title}}{{end}}
            {{if $doc.Meta.date}}{{$date = $doc.Meta.date}}{{end}}
            {{if $doc.Meta.description}}{{$desc = $doc.Meta.description}}{{end}}
        {{end}}
        {{$body = $doc.Body}}
    {{end}}
{{end}}

6. Dynamic Index Generation (content/notes.md)

The notes listing hub at /notes dynamically crawls the content/notes/ directory on disk at request time, extracts note metadata, filters drafts, and renders the feed:

<ul id="notes-list">
{{range $file := listFiles "/content/notes"}}
{{if ne $file (trimSuffix ".md" $file)}}
{{$mdPath := printf "/content/notes/%s" $file}}
{{$doc := splitFrontMatter (readFile $mdPath)}}
{{if and $doc.Meta (not $doc.Meta.draft)}}
{{$title := "Untitled"}}{{if $doc.Meta.title}}{{$title = $doc.Meta.title}}{{end}}
{{$date := "Unknown"}}{{if $doc.Meta.date}}{{$date = $doc.Meta.date}}{{end}}
{{$cleanLink := printf "/notes/%s" (trimSuffix ".md" $file)}}

<li data-date="{{$date | html}}">
    <time datetime="{{$date | html}}"><strong>{{$date | html}}</strong></time> - <a href="{{$cleanLink}}">{{$title | html}}</a>
</li>
{{end}}
{{end}}
{{end}}
</ul>

Zero-CLS Client-Side Sorting

Because standard Caddy templates do not provide a built-in cross-platform date sorting primitive, notes.md includes an optimized, non-destructive sorting routine:

(() => {
  const list = document.getElementById('notes-list');
  if (!list) return;

  const items = Array.from(list.children);
  items.sort((a, b) => {
    const dateA = Date.parse(a.dataset.date) || 0;
    const dateB = Date.parse(b.dataset.date) || 0;
    if (dateB !== dateA) return dateB - dateA; // Newest first
    return a.textContent.localeCompare(b.textContent); // Alphabetical tie-breaker
  });

  // Batched DOM relocation: zero layout shift, no innerHTML destruction
  list.append(...items);
})();

7. Security Architecture & Threat Defenses

Threat Vector Defense Mechanism
Server-Side Template Injection (SSTI) Standard posts are read via readFile (raw string bytes), completely preventing arbitrary execution of Caddy template tags ({{ .Env }}) embedded inside Markdown prose or code blocks.
Path Traversal (../) User paths are normalized with clean and strictly tested with not (hasPrefix "/../" $path) before file system lookup.
Stored Cross-Site Scripting (XSS) All user-defined frontmatter variables are escaped through Go's `
Direct File Leaking Hidden files (.DS_Store, .git), component partials (/includes/*), and raw Markdown sources (/content/*, *.md) are blocked in the web server configuration.
Ghost Route Exposure Partials are kept outside the /content root in includes/menu.html so internal components cannot be routed as standalone pages.

8. Authoring Workflow: Publishing New Content

Publishing a new transmission or page is as simple as adding a Markdown file.

Adding a Note

  1. Create a new file in content/notes/ (e.g. content/notes/my-note.md).
  2. Add frontmatter with title, date, and description.
  3. Write your post in standard Markdown.
  4. The note is instantly available at /notes/my-note and automatically indexed at /notes.

Adding a Top-Level Page

  1. Create a file directly in content/ (e.g. content/about.md).
  2. Add frontmatter and write your content.
  3. The page is instantly live at /about.
  4. Add a link to includes/menu.html if you wish to feature it in the header navigation.

9. Production Caddyfile Configuration

For high performance, HTTPS automation, and defense-in-depth, deploy Z-Ray with this Caddyfile configuration:

example.com, *.example.com {
    tls {
        dns cloudflare {env.CLOUDFLARE_API_TOKEN}
    }

    root * /var/www/example.com

    # Block hidden files, component includes, and raw markdown sources
    @blocked {
        path */.*
        path /includes/*
        path /content/*
        path *.md
    }
    respond @blocked 404

    # Security Headers
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
        Referrer-Policy "strict-origin-when-cross-origin"
        Permissions-Policy "camera=(), microphone=(), geolocation=()"
        Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; object-src 'none'; base-uri 'self';"
    }

    # Transparent compression
    encode gzip zstd

    # Z-Ray Template Engine
    templates

    # Catch virtual routes and rewrite internally to the layout engine;
    # real files on disk (like style.css or images) are served directly.
    handle {
        try_files {path} /layout.html
    }

    file_server
}