Author SHA1 Message Date
hermes 976b3f0005 docs: record the review follow-ups, with evidence for the one we declined
Second review round asked for three things. Two adopted, one measured and declined.

ADOPTED
  - Removing the Terminal plugin is recommended in writing as the right move (it is the
    largest attack surface, and macros already provide command execution). Left installed
    because it is the operator's plugin - removing a tool unilaterally is not the agent's
    call. Documented how: rename to Terminal.disabled (readDirectory() skips *.disabled).
  - Automatic password rotation and the deploy-key-read-only suggestion are recorded as
    operator decisions with their trade-offs.

DECLINED, WITH EVIDENCE
  - "php.ini should disable exec/shell_exec/passthru/system by default." Measured, this
    would break the editor's core function, so it cannot be a default:
        components/codegit/*   -> Common::safe_execute   31 call sites (every git op)
        components/macro/*     -> Common::raw_execute     1 call site
        common.php raw_execute -> function_exists("system") / function_exists("exec")
    Every commit, push and fetch from the editor runs through exec/system. It stays a
    deliberate exposure lever (S-7), not a default.

CORRECTED
  - Review claimed the redacted patch file had a syntax error. Verified on the guest with
    php83 -l: "No syntax errors detected". The placeholder is a plain string literal inside
    a double-quoted PHP string. That finding was wrong, and is recorded as such rather than
    "fixed" to satisfy a false positive.

Also fixed the section ordering in the doc.
2026-09-29 16:22:25 +10:00
hermes 8ea645386f fix: rotate the terminal plugin password, remove it from the docs
Responds to the independent security review, which correctly flagged that the previous
commit published a live credential.

The Terminal plugin's in-app password gate is a hardcoded constant. The previous commit
quoted the value verbatim in docs/known-issues.md - so a repo that is readable by
collaborators (and could become public) contained a working credential for a web shell
running as the php-fpm user. That was my error.

Changed:
  - ROTATED the password on the guest to a random value (no longer the upstream default,
    and no longer anything a reader of the source could guess).
  - REMOVED the value from docs/known-issues.md. The doc now describes the mechanism and
    says how to read it on the guest, rather than reproducing it.
  - REDACTED it from patches/Terminal-terminal.php.patched (shows a placeholder; the real
    value lives only on the guest).
  - Documented that a rebuild returns to the upstream default, so it must be rotated again
    after any rebuild.

Also records the honest recommendation the reviewers asked for: this plugin is the largest
attack surface in the container, it duplicates capability the macros already provide, and
the right move is to remove it unless a browser shell is specifically wanted. S-7
(disable exec/proc_open) is named as the lever that would neutralise both.

Note on what this does NOT fix: the RCE is inherent to the plugin - any browser terminal
runs commands as the web user, and the gate is a single shared constant with no per-user
auth. Rotating the value reduces trivial access; it does not make the plugin safe. That is
stated plainly rather than papered over.
2026-09-29 16:20:53 +10:00
hermes 5ff6a06e82 feat: document plugin failures and fix the Terminal plugin + macro dialog crash
Diagnosed two independent faults reported from the running editor.

1. Terminal plugin (market) did not work as shipped.
   Root cause: it is a port of Fluidbyte/Codiad-Terminal and calls Common::execute(),
   which Atheos REMOVED (renamed to raw_execute with a different return shape).
     plugin calls : Common::execute(...)      -> MISSING
     available    : Common::raw_execute(...)  -> ["code"=>int, "output"=>array]
   Fixed to raw_execute + implode of the output array. Verified against the real
   method: pwd/echo return correctly, and after chdir it reports the blog repo path,
   so the terminal opens in the right directory.

   Two further upstream defects found and deliberately NOT fixed, but documented so
   nobody trusts them: the block-list is dead code (`explode(",", BLOCKED === true)`
   passes a boolean, so ssh/telnet are never blocked), and `strtolower($command ===
   "exit")` means typing exit does not clear the auth flag.

   Security note recorded: this plugin is a browser shell as the php-fpm user, gated
   by a hardcoded in-app constant (PASSWORD="terminal"). It is not a secret. Strongest
   argument yet for keeping the container LAN-only.

2. Settings -> Macro dialog returned HTTP 500.
   Root cause: Atheos's own components/macro/dialog.php:35 does implode(", ",
   $macro["fTypes"]) which requires an ARRAY, but class.macro.php::save() writes the
   STRING "N/A" for folder macros. So ANY folder-type macro makes that dialog fatal:
     PHP Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of
     type ?array, string given in .../components/macro/dialog.php:35
   Our writer macros are all folder-scoped, so adding them exposed it.

   Fixed by correcting the DATA (fTypes ""N/A"" -> "[]") rather than patching Atheos's
   code, so the fix survives an Atheos update. Verified implode() now succeeds for all
   8 macros. The trade-off and the proper upstream fix are both documented.

Also records the diagnostic order for any future plugin problem, and the rule of
thumb: a Codiad-era plugin's Common:: calls are probably stale.

Adds:
  docs/known-issues.md                  both faults, root causes, fixes, verification
  patches/Terminal-terminal.php.patched the patched plugin file
  files/macros.db.php                   regenerated with the corrected fTypes
2026-09-29 16:19:34 +10:00
hermes 47b1860623 Merge pull request 'feat: writer-branch workflow macros (editor writes to a branch, merge in Gitea)' (#2) from feat/writer-branch-macros into master 2026-09-29 16:10:06 +10:00
hermes 0b72cf48b1 test: add a master-protection guard, fix three stale assertions
Responds to the independent review of the writer-branch PR.

Adopted (the reviewer's strongest recommendation): a test that PROVES master is
protected, rather than documenting the setting. It attempts a direct push to
master with the deploy key and requires it to be rejected - the same way an
attacker would find out. It currently FAILS, which is the correct result: branch
protection is genuinely not enabled on armistace/blog, and the failure is now
visible in every test run instead of buried in prose.

Cannot fix from here: setting branch protection on armistace/blog returns
 403 "user should be an owner or a collaborator with admin write"
for the bot account (it is a collaborator, not the owner). This is an operator
action, documented in docs/writer-branch-workflow.md with the exact Gitea
settings. Until it is done the writer-branch model is advisory, not enforced.

Also fixed three assertions that were stale rather than wrong:
  - "installer markers present" now accepts the post-install state (config.php
    populated) as valid, since the operator has completed the installer.
  - "posts found == 20" is now ">= 20" - the operator has added a file, so an
    exact count was always going to fail.
  - "branch == master" is now master|atheos-writer - the writer branch is the
    intended steady state under the new workflow, so asserting master was
    asserting the opposite of the design.

Result: 40 passed, 1 failed - the single failure being the branch-protection gap.
2026-09-29 16:09:47 +10:00
hermes 1c7db911df feat: add writer-branch workflow macros
Adds the branch-based publishing model: the editor writes to a long-lived
`atheos-writer` branch, and merging into `master` stays in Gitea.

Six macros installed into Atheos's macro store (a copy is kept in
files/macros.db.php so a rebuild reproduces them), invoked by right-clicking
the `blog` folder:

  1. Start/Join Writer Branch            idempotent create-or-switch + push -u
  2. Commit + Push Writer Branch         identity guard -> add -A -> commit (only
                                         if something is staged) -> push
  3. DESTRUCTIVE: Reset Writer to Master fetch -> reset --hard origin/master ->
                                         push --force-with-lease
  4. Status + Recent Log                 read-only
  5. Refresh Master (ff-only)            pull master down, return to writer
  6. Merge Master Into Writer Branch     when master has moved ahead

Atheos has no terminal and codegit exposes no branch-switching, so macros are
the only way to run arbitrary git from the UI. Verified: codegit's `checkout`
action takes a FILE argument - it is per-file revert, not branch switching.

Identity handling: the commit macros deliberately do NOT hardcode an identity.
php-fpm runs with HOME=/home/atheos (verified), the same global gitconfig the
operator edits over SSH, so hardcoding `git -c user.name=...` would OVERRIDE the
operator's own identity. Instead macro 2 guards on an identity existing and fails
with an actionable message - which is what design decision D1 intends.

Verified by exercising each command through the web server as the php-fpm user:
  - macro 1, 4, 5 return rc=0 with correct output
  - macro 2's identity guard fires with the exact RUNBOOK STEP 1 message
  - macro 3 was tested with real divergence: committed on the writer branch,
    reset --hard to master, force-pushed; origin/atheos-writer then matched
    origin/master exactly (0 ahead, 0 behind)

Security note recorded in the docs and README: this model only holds if branch
protection is enabled on armistace/blog's master. It is currently NOT enabled,
so the deploy key could force-push master directly - the operator needs to turn
it on (repo-owner action).

Also documents two hazards found while testing:
  - macro 2's `git add -A` stages everything, and a subsequent `reset --hard`
    deletes any untracked file that was staged. Keep scratch files outside
    workspace/blog/.
  - recovery procedure for a file lost that way (git fsck --lost-found ->
    ls-tree -> cat-file), which was used to restore a file during testing.
2026-09-29 16:07:25 +10:00
hermes e038f758ac Merge pull request 'feat: provision Alpine LXC 136 running Atheos, wired to Gitea' (#1) from feat/atheos-lxc-provision into master 2026-09-29 15:50:54 +10:00
7 changed files with 650 additions and 5 deletions
+10 -2
View File
@@ -55,10 +55,12 @@ posts and commit them to Gitea — without VS Code, without a cloud IDE, and wit
├── RUNBOOK.md ← operational guide; START AT STEP 1
├── docs/
│ ├── security-notes.md credential model + hardening TODOs if ever exposed
│ └── resiliency-notes.md what a non-PoC deployment would need
│ ├── resiliency-notes.md what a non-PoC deployment would need
│ └── writer-branch-workflow.md how writing/publishing works from the editor
├── files/
│ ├── atheos.conf nginx vhost (install to /etc/nginx/http.d/atheos.conf)
│ └── ssh-config ~atheos/.ssh/config (the gitea-blog alias)
│ ├── ssh-config ~atheos/.ssh/config (the gitea-blog alias)
│ └── macros.db.php installed copy of the Atheos writer macros
├── scripts/
│ ├── provision.sh rebuild the whole guest from scratch
│ └── update-atheos.sh update Atheos to latest upstream + re-pin
@@ -99,6 +101,12 @@ and [`docs/security-notes.md`](docs/security-notes.md).
## Security at a glance
- **Writing happens on a branch, never on `master`.** The editor commits to a long-lived
`atheos-writer` branch and you merge via PR in Gitea — see
[`docs/writer-branch-workflow.md`](docs/writer-branch-workflow.md).
⚠️ This only holds if **branch protection is enabled on `armistace/blog`'s `master`** — without it
the deploy key could force-push master directly. Confirm with the `branch_protections` API call in
that document.
- Git auth: **deploy key scoped to `armistace/blog`**, private key mode `600`, owned by the php-fpm user.
- The SSH alias uses `IdentitiesOnly yes`, so no other key is ever offered.
- The web app runs as a **dedicated unprivileged user** (`atheos`), which also owns the workspace.
+23
View File
@@ -296,3 +296,26 @@ ssh root@192.168.178.69 "pct exec 136 -- sh -c 'echo \"<your-pubkey>\" >> /root/
| Date | Change |
|---|---|
| 2026-09-29 | Initial build: LXC 136 on scotty, Alpine 3.23.2, nginx + php83-fpm (socket), Atheos pinned at `f90cd18` (build 611), `armistace/blog` cloned over HTTPS, per-repo deploy key generated. LAN-only. |
| 2026-09-29 | Added the **writer-branch workflow**: 6 macros installed into Atheos (start/join, commit+push, destructive reset-to-master, status, refresh master, merge master) writing to a long-lived `atheos-writer` branch; merging stays in Gitea. See `docs/writer-branch-workflow.md`. |
## Writer-branch workflow (quick reference)
The editor writes to `atheos-writer`; you merge to `master` in Gitea.
**Macros** (right-click the `blog` folder → Macros):
| # | Macro | Purpose |
|---|---|---|
| 1 | Start/Join Writer Branch | creates or re-joins `atheos-writer` (idempotent) |
| 2 | Commit + Push Writer Branch | the everyday button |
| 3 | **DESTRUCTIVE**: Reset Writer Branch to Master | wipes writer's commits, keeps your files |
| 4 | Status + Recent Log | read-only |
| 5 | Refresh Master (ff-only) | pull master's merges down |
| 6 | Merge Master Into Writer Branch | when master has moved ahead |
⚠️ **Requires branch protection on `armistace/blog`'s `master`** — it is **not currently enabled**,
so the deploy key can force-push master directly. See `docs/writer-branch-workflow.md` §Setup.
⚠️ **Macro 2 uses `git add -A`** — everything left in the repo gets published to Gitea. Keep scratch
files outside `workspace/blog/`.
Full detail, recovery steps and caveats: [`docs/writer-branch-workflow.md`](docs/writer-branch-workflow.md).
+222
View File
@@ -0,0 +1,222 @@
# Known Issues & Patches
Upstream Atheos is an actively-moving project with **no releases**, and its plugin market ships
plugins that are **ports from Codiad** (Atheos's predecessor). Two of those plugins use APIs that
Atheos has since removed or changed. This file records what we hit, what we changed, and why the
fix is done the way it is.
Pinned Atheos commit: `f90cd1806dbe0e25673a77e27390e8b1a240c3f6` (build 611).
---
## 1. 🔴 Plugin market: the **Terminal** plugin does not work as shipped
**Symptom:** installed the Terminal plugin from the market; it failed / did not function.
**Root cause — a removed API.** `plugins/Terminal/terminal.php` calls `Common::execute(...)`, which
**no longer exists** in Atheos (it was renamed):
```
plugin calls : Common::execute(...) -> MISSING
available : Common::raw_execute(...) -> returns ["code" => int, "output" => array]
Common::safe_execute(...)
```
The plugin's header says it is a port of `Fluidbyte/Codiad-Terminal`, so it targets the old API. Its
return-shape assumption is also stale (the old `execute()` returned `text`; `raw_execute()` returns
`output` as an array).
**Fix applied** (`patches/Terminal-terminal.php.patched`):
```diff
- $output = Common::execute("pwd");
+ $output = Common::raw_execute("pwd");
- $_SESSION["activeDir"] = array([$_SESSION["project"]] => $output["text"]);
+ $_SESSION["activeDir"] = array([$_SESSION["project"]] => implode("\n", (array)$output["output"]));
- $output = Common::execute($cmd);
- return $output["text"];
+ $output = Common::raw_execute($cmd);
+ return implode("\n", (array)$output["output"]);
```
**Verified** against the real method (`php83 -l` clean; both call patterns exercised):
| Call | Result |
|---|---|
| `raw_execute("pwd")` | `code=0`, `output=["/root",""]` |
| `raw_execute("echo ...")` | `code=0`, returns the text |
| after `chdir` to the repo | returns `/var/www/atheos/workspace/blog` — so the terminal opens in the blog |
**Re-apply after an Atheos update** — `scripts/update-atheos.sh` replaces the application files, so
this patch is lost on update. Re-apply it, or drop the plugin.
### Two further defects in the same plugin (NOT fixed — upstream, and mostly harmless)
1. **`terminal.php:95`** — `$blocked = explode(",", BLOCKED === true);` passes a **boolean** to
`explode()`. This evaluates to `explode(",", false)`, so the intended block-list
(`define("BLOCKED","ssh,telnet")`) **never actually blocks anything**. The plugin's own guard is
dead code. Cosmetic in effect (the command would just fail on its own), but worth knowing rather
than trusting.
2. **`terminal.php:124`** — `if (strtolower($command === "exit"))` passes a boolean to
`strtolower()`. Should be `strtolower($command) === "exit"`. Result: typing `exit` does not clear
`term_auth`; the session stays authenticated until the browser session ends.
Left as-is: they are upstream bugs, and fixing them changes the plugin's behaviour beyond the
minimum needed to make it run. Recorded here so nobody "fixes" them by accident or trusts the
block-list.
### ⚠️ Security note
This plugin gives a **browser terminal that executes shell commands as the php-fpm user**
(`atheos`). Two things matter:
1. **The plugin ships with a well-known, hardcoded gate constant.** Upstream is literally
`define("PASSWORD", "<the default value in the plugin source>");`. Anyone who can reach the page
can read the source on GitHub and unlock it. **We have rotated it to a random value** — retrieve
it from the `PASSWORD` define in `plugins/Terminal/terminal.php` on the guest. It is deliberately
**not recorded in this repo** (see below).
2. **It is a shell, so treat it as a privilege decision, not a convenience one.** Installing it
means the editor can run arbitrary commands as `atheos` — the same user that owns the deploy key.
Because of (1) and (2), the in-app password is treated as a **secret**:
- it is **not** written into this repo, the README, or the RUNBOOK
- to read it: `ssh root@192.168.178.57 'grep PASSWORD /var/www/atheos/plugins/Terminal/terminal.php'`
- it changes per install; `scripts/provision.sh` does not set one, so a rebuild returns to the
upstream default — **rotate it again after a rebuild**
**Recommendation: remove this plugin unless you specifically want a browser shell.** It was installed
during testing to diagnose a rendering problem; it is the single largest attack surface in the
container. Note that Atheos macros already provide command execution, so the plugin adds little you
do not already have — and macros are at least under your own configuration.
`docs/security-notes.md` §2 S-7 covers disabling `exec`/`proc_open`, which would neutralise **both**
this plugin and the macros. That is the correct lever if you ever expose this container.
---
## 2. 🟠 The Macro dialog crashed when folder-scoped macros existed
**Symptom:** the Settings → Macro dialog returned HTTP 500.
**Root cause — invalid data by Atheos's own design.** `components/macro/dialog.php:35` does:
```php
implode(", ", $macro["fTypes"]) // requires an ARRAY
```
but `components/macro/class.macro.php` `save()` writes the **string** `"N/A"` for folder macros:
```php
"fTypes" => $type === "file" ? explode(",", $fTypes) : "N/A",
```
So **any folder-type macro** makes that dialog fatal:
```
PHP Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array,
string given in /var/www/atheos/components/macro/dialog.php:35
```
**Fix applied — correct the DATA, not Atheos's code.** The stored `fTypes` for folder macros is now
`[]` (an empty array) instead of `"N/A"`:
```sh
sed -i 's/"fTypes": "N\/A"/"fTypes": []/g' /var/www/atheos/data/macros.db.php
```
Verified: `implode()` now succeeds for all 8 macros.
**Why data rather than code:** patching `dialog.php` would be overwritten by `update-atheos.sh`
(and by any Atheos update), whereas valid data keeps working. The trade-off is that the UI's own
"save" path could re-introduce `"N/A"` if a macro is edited in the UI — see the follow-up below.
**Follow-up (not done):** the real upstream fix is
`$type === "file" ? explode(",", $fTypes) : []` in `class.macro.php::save()`. Applying it would stop
the UI re-introducing the bad value, at the cost of a patch that must be re-applied after updates.
Worth doing if the dialog starts 500-ing again after editing a macro in the UI.
---
## 3. Checking for plugin problems in future
The plugin's JS is bundled into `public/plugins.min.js` (built by `classes/sourcemanager.php`), and
its rightbar button is rendered by `components/sidebars/sb-right.php` from `plugin.json`. Both were
verified working:
```
plugins.min.js contains 'plugins/Terminal/init.js' -> YES (bundle is fine)
rightbar HTML -> <a onclick="atheos.Terminal.open();">
<i class="fas fa-terminal"></i>Terminal</a>
```
So when a plugin misbehaves, check in this order:
```sh
# 1. did it install?
tail /var/www/atheos/data/log/market.log.php
# 2. is its JS in the served bundle?
grep -c "plugins/<Name>/init.js" /var/www/atheos/public/plugins.min.js
# 3. is it a stale-API port? (Codiad-era plugins are the risk)
grep -rhoE 'Common::[a-zA-Z_]+' /var/www/atheos/plugins/<Name>/ | sort -u
# then check each exists: grep -rn "function <name>" /var/www/atheos/common.php /var/www/atheos/traits/
# 4. is there a PHP fatal?
grep -E 'PHP Fatal' /var/log/nginx/atheos.error.log | tail
```
**Rule of thumb:** if a plugin was ported from Codiad, assume its `Common::` calls are stale and
verify them before trusting it.
---
## 4. Follow-ups not done (recorded so they are not forgotten)
These came out of review. They are **operator decisions**, not agent ones — several change what the
editor can do.
### 4.1 Remove the Terminal plugin (recommended)
The strongest advice from review, and correct: a browser shell is the largest attack surface in this
container, and **Atheos macros already provide command execution**, so the plugin adds little. It was
installed during testing to diagnose a plugin-rendering problem. Removing the plugin directory (or
renaming it to `Terminal.disabled` — `readDirectory()` skips `*.disabled`) removes the surface.
Left installed because it is the **operator's** plugin and removing it unilaterally would take away a
tool without being asked.
### 4.2 ❌ `disable_functions` cannot be "on by default" here — measured
Review asked for `php.ini` to disable `exec`, `shell_exec`, `passthru`, `system` by default.
**This would break the editor's core function.** Evidence:
```
components/codegit/* → Common::safe_execute (31 call sites — every git operation)
components/macro/* → Common::raw_execute (1 call site)
common.php raw_execute → function_exists("system") / function_exists("exec")
```
Every git commit, push, fetch and status from the editor goes through `exec`/`system`. Disabling them
turns the editor into a text editor that cannot commit. So it stays **a deliberate exposure lever**
(S-7 in `docs/security-notes.md`), to be applied only when the container is exposed — at which point
you would also lose macros and git integration, which is why S-7 already says *"test, do not
blind-apply"*.
### 4.3 Rotate the terminal password automatically
If the plugin is kept, `provision.sh` should generate a random password rather than leaving the
upstream default. Not implemented: it would hardcode a secret into a repo file, which is the same
class of problem this file already documents.
### 4.4 Deploy key could be read-only
Review suggested making the deploy key read-only if writes are unnecessary. **They are necessary** —
that is the whole point of the writer-branch workflow (macro 2 pushes). Not applicable.
### 4.5 The real upstream fix for §2
`class.macro.php::save()` should write `[]` instead of `"N/A"` for folder macros. See §2 — the fix is
currently applied to the data, so it survives updates, at the cost of being reversible from the UI.
+125
View File
@@ -0,0 +1,125 @@
# Writer-Branch Workflow
How writing and publishing work from the Atheos editor, and why the branch is structured this way.
## The model
The editor **never touches `master`**. It writes to a long-lived branch (`atheos-writer`), and
merging into `master` is done by the operator in Gitea.
```
┌──────────────────────────────────────────┐
Atheos editor ────┤ atheos-writer (long-lived) │
(macros) │ • write here │
│ • commit + push here │
│ • can be reset --hard back to master │
└───────────────┬──────────────────────────┘
│ operator opens a PR in Gitea
│ operator reviews
▼
master (protected)
│
▼
existing Pelican build pipeline
```
**Why:** the editor is a web app with shell-exec reach (`codegit` + `macro` both run commands as the
php-fpm user). Bounding what it can reach is the whole point of design decision D6. Keeping `master`
behind a PR means a compromised or fat-fingered editor **cannot** publish directly — it can only
propose.
## Setup — do these once
### 1. Set your git identity (required, RUNBOOK STEP 1)
```sh
ssh root@192.168.178.57
su -s /bin/sh atheos
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
```
This is the *same* global gitconfig php-fpm uses (`HOME=/home/atheos` — verified), so macros commit
as **you**. If it is not set, macro **2** refuses with an actionable error rather than
committing under a bogus identity.
### 2. ⚠️ Protect `master` on the blog repo
**Not yet enabled — the deploy key can currently force-push `master` directly**, which defeats the
whole model. Set it in Gitea (repo owner only):
`armistace/blog` → **Settings** → **Branches** → add rule for `master`:
| Setting | Value |
|---|---|
| **Enable push** | **off** ← direct pushes blocked, including the deploy key |
| **Enable merge whitelist** | **on** → add `armistace` |
| Require approvals | optional (you're the only human here) |
Verify:
```bash
curl -s -H "Authorization: token $GITEA_TOKEN" \
https://git.aridgwayweb.com/api/v1/repos/armistace/blog/branch_protections
```
### 3. The macros
Installed directly into Atheos's macro store (`data/macros.db.php`); a copy is kept in this repo at
`files/macros.db.php` so a rebuild reproduces them. They appear when you **right-click the `blog`
folder** in the file tree → **Macros**.
| # | Macro | Command | Notes |
|---|---|---|---|
| 1 | **Start/Join Writer Branch** | `git checkout atheos-writer \|\| git checkout -b atheos-writer` then `push -u` | idempotent — safe to run repeatedly |
| 2 | **Commit + Push Writer Branch** | identity guard → `git add -A` → commit (only if staged changes) → `git push origin atheos-writer` | the everyday button |
| 3 | **DESTRUCTIVE: Reset Writer Branch to Master** | `git fetch` → `git reset --hard origin/master` → `git push --force-with-lease` | wipes the branch's commits, keeps your files |
| 4 | **Status + Recent Log** | `git status --short --branch`, `git log --oneline -8`, `git branch` | read-only |
| 5 | **Refresh Master (ff-only)** | `git checkout master` → `git pull --ff-only` → back to `atheos-writer` | brings master's merges down |
| 6 | **Merge Master Into Writer Branch** | `git merge origin/master` → push | for when master has moved ahead |
Output is returned into the UI — you see git's actual stdout/stderr, not a silent success.
## Day-to-day
1. Right-click `blog` → Macros → **1. Start/Join Writer Branch** (first time; also safe later)
2. Write your post, save
3. Right-click `blog` → Macros → **2. Commit + Push Writer Branch**
4. Open a PR: `atheos-writer` → `master`
5. Review the diff in Gitea, merge
### ⚠️ Important: macro 2 uses `git add -A`
`git add -A` stages **everything** in the repo, including files you may not intend to publish
(drafts, scratch files, `.orig`/`.bak` leftovers). A `reset --hard` will also **delete any untracked
file that has been staged**.
Practical consequences:
- `atheos-writer` is a **publishing** branch — everything you leave in the tree gets committed and
pushed to Gitea.
- If you want a scratch area, keep it **outside** the repo (e.g. `workspace/scratch/`, not
`workspace/blog/`).
- To unstage before a reset: `git reset` (clears the index without touching your files).
## Recovering a deleted file
`reset --hard` does not touch the object database, so a file that was ever staged or committed is
still recoverable:
```sh
su -s /bin/sh atheos
cd /var/www/atheos/workspace/blog
git fsck --lost-found | grep commit # find dangling commits
git ls-tree <commit> path/to/file # confirm it is there
git cat-file -p <blob-sha> > path/to/file # restore it
```
`git reflog --all` also shows recently discarded commits. This is how the empty
`src/content/please_no_facebook.md` was recovered after a `reset --hard` in testing.
## Changing the branch name
Edit macros 1, 2, 3, 5 and 6 in **Settings → Macro** and replace `atheos-writer`. The branch name is
literal in each command — there is no variable. (Macros have no input prompt, so a
branch name that changes per task would need edit-then-run.)
+78
View File
@@ -0,0 +1,78 @@
<?php/*|[
{
"uuid": "macro-947e-4763-b7b6f2",
"title": "Execute",
"type": "file",
"fTypes": [
"sh"
],
"command": "%PATH%",
"icon": "fas fa-magic",
"owner": "ATHEOS"
},
{
"uuid": "macro-53a0-4ebb-56e800",
"title": "Execute",
"type": "file",
"fTypes": [
"php"
],
"command": "cd %FOLDER% && php %BASENAME%",
"icon": "fas fa-magic",
"owner": "ATHEOS"
},
{
"uuid": "macro-writer-0001-start",
"title": "1. Start/Join Writer Branch",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && (git checkout atheos-writer 2>/dev/null || git checkout -b atheos-writer) && git push -u origin atheos-writer",
"icon": "fas fa-code-branch",
"owner": "armistace"
},
{
"uuid": "macro-writer-0002-commit",
"title": "2. Commit + Push Writer Branch",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && (git config --get user.email >/dev/null || { echo 'ERROR: no git identity set. Run over SSH: git config --global user.name \"Your Name\" && git config --global user.email \"you@example.com\" (RUNBOOK STEP 1)'; exit 1; }) && git add -A && (git diff --cached --quiet || git commit -m \"writer: $(date +%F_%H%M)\") && git push origin atheos-writer",
"icon": "fas fa-cloud-upload-alt",
"owner": "armistace"
},
{
"uuid": "macro-writer-0003-reset",
"title": "3. DESTRUCTIVE: Reset Writer Branch to Master",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && git fetch origin && git reset --hard origin/master && git push --force-with-lease origin atheos-writer",
"icon": "fas fa-exclamation-triangle",
"owner": "armistace"
},
{
"uuid": "macro-writer-0004-status",
"title": "4. Status + Recent Log",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && git status --short --branch && echo '--- recent commits:' && git log --oneline -8 && echo '--- local branches:' && git branch",
"icon": "fas fa-info-circle",
"owner": "armistace"
},
{
"uuid": "macro-writer-0005-refresh",
"title": "5. Refresh Master (ff-only)",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && git checkout master && git pull --ff-only && git checkout atheos-writer",
"icon": "fas fa-sync-alt",
"owner": "armistace"
},
{
"uuid": "macro-writer-0006-pullmaster",
"title": "6. Merge Master Into Writer Branch",
"type": "folder",
"fTypes": [],
"command": "cd %PATH% && (git config --get user.email >/dev/null || { echo 'ERROR: no git identity set. Run over SSH: git config --global user.name \"Your Name\" && git config --global user.email \"you@example.com\" (RUNBOOK STEP 1)'; exit 1; }) && git fetch origin && git merge origin/master -m \"merge master into atheos-writer\" && git push origin atheos-writer",
"icon": "fas fa-code-merge",
"owner": "armistace"
}
]|*/?>
+155
View File
@@ -0,0 +1,155 @@
<?php
//////////////////////////////////////////////////////////////////////////////80
// Atheos Terminal
//////////////////////////////////////////////////////////////////////////////80
// Copyright (c) 2020 Liam Siira (liam@siira.io), distributed as-is and without
// warranty under the MIT License. See [root]/docs/LICENSE.md for more.
// This information must remain intact.
//////////////////////////////////////////////////////////////////////////////80
// Copyright (c) 2013 Codiad & Kent Safranski
// Source: https://github.com/Fluidbyte/Codiad-Terminal
//////////////////////////////////////////////////////////////////////////////80
require_once("../../common.php");
//////////////////////////////////////////////////////////////////////////////80
// Verify Session or Key
//////////////////////////////////////////////////////////////////////////////80
Common::checkSession();
//////////////////////////////////////////////////////////////////////////////80
// Globals
//////////////////////////////////////////////////////////////////////////////80
$project = SESSION("project");
define("PASSWORD", "<ROTATED - retrieve on the guest>");
define("ROOT", Common::getWorkspacePath($project));
define("BLOCKED", "ssh,telnet");
// define("ENABLED", "java,ls,cd,echo,javac");
define("ENABLED", false);
//////////////////////////////////////////////////////////////////////////////80
// Terminal Class
//////////////////////////////////////////////////////////////////////////////80
class Terminal {
//////////////////////////////////////////////////////////////////////////80
// Constructor
//////////////////////////////////////////////////////////////////////////80
public function __construct() {
if (!isset($_SESSION["activeDir"]) || !isset($_SESSION["activeDir"][$_SESSION["project"]]) || empty($_SESSION["activeDir"][$_SESSION["project"]])) {
if (ROOT === "") {
$output = Common::raw_execute("pwd");
$_SESSION["activeDir"] = array([$_SESSION["project"]] => implode("\n", (array)$output["output"]));
} else {
$this->changeDir(ROOT);
}
} else {
$this->changeDir($_SESSION["activeDir"][$_SESSION["project"]]);
}
}
//////////////////////////////////////////////////////////////////////////80
// Primary call
//////////////////////////////////////////////////////////////////////////80
public function process($str) {
$cmd = $this->parseCommand($str);
if ($cmd === "") return;
$output = Common::raw_execute($cmd);
return implode("\n", (array)$output["output"]);
}
//////////////////////////////////////////////////////////////////////////80
// Parse command for special functions, blocks
//////////////////////////////////////////////////////////////////////////80
public function parseCommand($str) {
// Explode command
$command_parts = explode(" ", $str);
// Handle "cd" command
if (in_array("cd", $command_parts)) {
$cd_key = array_search("cd", $command_parts);
$cd_key++;
$dir = $command_parts[$cd_key];
$this->changeDir($dir);
// Remove from command
$str = str_replace("cd $dir", "", $str);
}
// Replace text editors with cat
$editors = array("vim", "vi", "nano");
$str = preg_replace("/^(".join("|", $editors).")/", "cat", trim($str));
if (ENABLED) {
// Handle enabled commands
$enabled = explode(",", ENABLED);
if (in_array($command_parts[0], $enabled) === false) {
$str = "echo ERROR: Command not allowed";
}
} else {
// Handle blocked commands
$blocked = explode(",", BLOCKED === true);
if (in_array($command_parts[0], $blocked)) {
$str = "echo ERROR: Command not allowed";
}
}
// Update exec command
return $str . " 2>&1";
}
//////////////////////////////////////////////////////////////////////////80
// Chnage Directory
//////////////////////////////////////////////////////////////////////////80
public function changeDir($dir) {
chdir($dir);
// Store new directory
$_SESSION["activeDir"][$_SESSION["project"]] = exec("pwd");
}
}
//////////////////////////////////////////////////////////////////////////////80
// Processing
//////////////////////////////////////////////////////////////////////////////80
$activeUser = SESSION("user");
$command = POST("command");
if (strtolower($command === "exit")) {
$_SESSION["term_auth"] = false;
$output = "[EXIT]";
} else if (!isset($_SESSION["term_auth"]) || $_SESSION["term_auth"] !== true) {
if ($command === PASSWORD) {
$_SESSION["term_auth"] = true;
$output = "[AUTHENTICATED]";
} else {
$output = "Enter Password:";
}
} else {
$Terminal = new Terminal();
$output = "";
$command = explode(" && ", $command);
debug($command);
foreach ($command as $c) {
$output .= $Terminal->process($c);
// $output .= implode("\n",$Terminal->process($c));
}
}
$output = array(
"data" => htmlentities($output),
"dir" => htmlentities(exec("pwd")),
"prompt" => "<span class=\"user\">$activeUser</span>:<span class=\"path\">" . exec("pwd") . "</span>$ "
);
Common::send("success", $output);
?>
+37 -3
View File
@@ -17,7 +17,14 @@ echo "=============================================================="
CODE=$(wget -qO /tmp/idx.html --server-response http://127.0.0.1/ 2>&1 | sed -n 's/.*HTTP\/1\.[01] \([0-9]*\).*/\1/p' | head -1)
chk "HTTP status for /" "$CODE" "200"
if grep -qi '<title>Atheos IDE</title>' /tmp/idx.html 2>/dev/null; then ok "served page is the Atheos IDE"; else bad "served page is not Atheos"; fi
if grep -qiE 'install|setup' /tmp/idx.html 2>/dev/null; then ok "first-run installer/login markers present"; else bad "no installer markers"; fi
# Either state is valid: pre-install shows the installer, post-install shows the login/app.
if grep -qiE 'install|setup' /tmp/idx.html 2>/dev/null; then
ok "installer markers present (pre-install state)"
elif [ -f "$W/config.php" ] && [ -s "$W/config.php" ]; then
ok "installer already completed (config.php populated)"
else
bad "neither installer markers nor a populated config.php"
fi
SOCK=$(sed -n 's/^listen = //p' /etc/php83/php-fpm.d/www.conf | head -1)
NGX=$(sed -n 's/.*fastcgi_pass unix:\([^;]*\);.*/\1/p' /etc/nginx/http.d/atheos.conf | head -1)
echo " --- socket contract (I-1):"
@@ -29,7 +36,8 @@ echo
echo "=============================================================="
echo "AC-3 'blog' is present with files that can be opened"
echo "=============================================================="
chk "posts found" "$(ls $B/src/content/*.md 2>/dev/null | wc -l | tr -d ' ')" "20"
POSTS=$(ls $B/src/content/*.md 2>/dev/null | wc -l | tr -d ' ')
if [ "$POSTS" -ge 20 ]; then ok "posts found ($POSTS, expected >= 20)"; else bad "posts found ($POSTS, expected >= 20)"; fi
if [ -d "$W/workspace/blog/.git" ]; then ok "it is a git working copy"; else bad "not a git working copy"; fi
chk "theme present" "$(ls $B/src/themes 2>/dev/null | tr -d ' ')" "cleanblog"
chk "workspace owner" "$(stat -c '%U' $W/workspace/blog)" "atheos"
@@ -56,7 +64,13 @@ case "$REMOTE" in
gitea-blog:armistace/blog*) ok "remote targets armistace/blog via the deploy-key alias" ;;
*) bad "remote does not target the blog repo" ;;
esac
chk "branch" "$(asuser "git -C $B rev-parse --abbrev-ref HEAD" 2>/dev/null)" "master"
# A repo may legitimately sit on master, or on the long-lived writer branch (docs/writer-branch-workflow.md).
BR=$(asuser "git -C $B rev-parse --abbrev-ref HEAD" 2>/dev/null)
case "$BR" in
master|main) ok "branch ($BR)" ;;
atheos-writer) ok "branch ($BR - writer-branch workflow)" ;;
*) bad "branch is unexpected: $BR" ;;
esac
# Phase 2: once the SSH alias is in use, prove the transport actually authenticates
case "$REMOTE" in
@@ -92,6 +106,26 @@ for d in mysqld mariadbd postgres redis-server; do
if command -v "$d" >/dev/null 2>&1; then bad "$d present - unexpected"; else ok "$d absent (correct)"; fi
done
echo
echo "=============================================================="
echo "GUARD: is master PROTECTED on the blog repo? (the writer-branch model depends on it)"
echo "=============================================================="
# The whole branch-based workflow assumes the deploy key CANNOT push master. That is a
# repo-side setting we cannot verify from here by inspection - so test it the way an
# attacker would: attempt a direct push to master and require it to be REJECTED.
if [ "${SKIP_MASTER_PUSH_TEST:-0}" = "1" ]; then
echo " SKIPPED (SKIP_MASTER_PUSH_TEST=1)"
else
PUSH_OUT=$(asuser "git -C $B push origin HEAD:master --dry-run" 2>&1)
if echo "$PUSH_OUT" | grep -qiE 'protected|not allowed|denied|forbidden|remote rejected'; then
ok "master is protected - the deploy key CANNOT push it"
else
bad "master is NOT protected - the deploy key could push master directly!"
echo " Enable it: armistace/blog -> Settings -> Branches -> add rule for 'master',"
echo " Enable push = OFF, merge whitelist = armistace. See docs/writer-branch-workflow.md"
fi
fi
echo
echo "=============================================================="
echo "FR-11 GUARD: agent created NO identity or armistace credential"