tools: prepare MIT source for public distribution

Ship MIT notices with published outputs and keep runtime credentials, configuration and history out of source archives. Audit working files, staged blobs and reachable history before publication.

Refs #19
This commit is contained in:
Florian Schmidt
2026-11-15 10:59:13 +01:00
parent c02829e2e1
commit cd000437a0
12 changed files with 484 additions and 2 deletions
+2
View File
@@ -0,0 +1,2 @@
tools/proxmox*.sh text eol=lf
tools/proxmox/*.py text eol=lf
+47
View File
@@ -6,3 +6,50 @@ artifacts/
*.user
*.suo
TestResults/
# Local deployment configuration and transport keys. Commit examples, never live values.
**/server.json
**/worker.json
**/server.env
**/worker.env
*.env
**/transport-keys.json
**/dashboard-key
**/worker-key
.env
.env.*
!.env.example
*.key
*.pem
*.pfx
*.p12
**/.ssh/
**/.aws/
**/.azure/
id_rsa
id_ecdsa
id_ed25519
# Provider profiles and FinalToken usage/history are local runtime data.
**/.claude/
**/.codex/
**/auth.json
**/.credentials.json
**/snapshot.json
**/fleet.json
**/history.json
**/history.state.json
**/history.journal.jsonl
**/usage.json
**/profile.json
**/settings.json
/history/
/data/
/state/
/runs/
/logs/
*.log
# Python tooling outputs.
__pycache__/
*.py[cod]
+49
View File
@@ -0,0 +1,49 @@
# Contributing
FinalToken is licensed under [MIT](LICENSE). Contributions should preserve its main question:
will the user's measured provider allowance last until the actual reset?
Read [AGENTS.md](AGENTS.md), [requirements](docs/requirements.md) and the relevant
[recorded decisions](docs/decisions.md) before changing behavior. Core owns forecasting and
history calculations; reuse them in each host. New behavior needs deterministic tests. Use
small synthetic fixtures, never real transcripts, rollout files, credential files or customer data.
## Get the source
When anonymous repository access is enabled, these HTTPS commands need no account/token:
```bash
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
cd FinalToken
```
Update a clean checkout with:
```bash
git pull --ff-only
```
A public repository does not grant push permission. Authenticated Gitea maintenance commands
are separate from read-only clone/pull. Do not embed passwords, tokens or an email/password in
the remote URL. If anonymous access is still disabled, the host must first make it public.
## Build and check
Use the .NET SDK selected by `global.json` and run commands from the repository root:
```text
dotnet build FinalToken.slnx -c Release
dotnet test --solution FinalToken.slnx -c Release
python -B tools/docs/check_docs.py
python -B tools/check_public.py --history
```
For Proxmox tooling, also run `python -B tools/proxmox/test_installer.py`,
`python -B tools/proxmox/test_update.py`, `bash -n tools/proxmox.sh` and
`bash -n tools/proxmox-update.sh`. [Web setup](docs/web-dashboard.md) and [Proxmox setup](docs/proxmox.md)
describe additional integration checks. State exactly what was exercised; mocked provider/Proxmox
tests do not establish that live login, native publishing or CT creation worked.
Use the Gitea issue/branch/review workflow in [AGENTS.md](AGENTS.md#workflow). Keep changes focused
and preserve unrelated work. Contributions do not require granting an agent permission to push
or publish; those actions still need explicit authorization.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 FinalFactory contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+72
View File
@@ -0,0 +1,72 @@
# Preparing a public repository
The repository uses the [MIT license](../LICENSE). Build/runtime dependencies keep their own
licenses. MIT licensing does not change authentication to providers or the running dashboard.
## Anonymous Git reads
After the repository host enables anonymous read access, HTTPS clone/fetch/pull need no login,
email, password or Git token. Use the public URL in [contributing](../CONTRIBUTING.md#get-the-source).
Pushes and maintainer API operations still require their own authorization.
For the Proxmox workflow, clone the published source on the host, then run its installer:
```bash
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
cd FinalToken
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
--domain usage.example.com --email [email protected]
```
For a later update, refresh and deploy the clean checkout with one command:
```bash
bash tools/proxmox-update.sh 201
```
Here `--email` is the intended **provider account identity**, not a Git login. The installer
reads the local checkout; the separate updater fetches its tracking branch first. The branch being cloned must contain the
web/worker/installer changes. A public visibility setting alone does not publish uncommitted work.
## Files to keep local
The ignore rules exclude live deployment configuration, service keys, provider profiles, usage
history, build outputs and screenshots/logs. Keep real configuration outside the checkout when
possible. Example files must use reserved example domains and explicit placeholders.
Ignoring a file does not remove a copy that was already committed.
The dashboard and client still authenticate their transport. Provider authorization goes through
the official CLI on its machine; making source public does not make your running instance or
CLI credentials public. Do not remove dashboard/client authentication to simplify Git downloads.
## Read-only audit
From the repository root:
```text
python -B tools/check_public.py --history
```
This checks Git-listed source files (including non-ignored untracked files), the actual staged
index blobs and reachable local history (source, commit and tag text) for sensitive runtime filenames and recognizable
private-key/provider-token patterns.
It reports paths, line numbers and pattern names, never matching values. Credential/config files
are reported by filename without opening them. Binary/oversized objects are reported as skipped.
The check is a targeted pattern check, not proof that arbitrary secrets are absent.
Index blobs are checked even when the working copy is clean or different. Historical trees are
checked for private filenames even when the same blob also appeared under a harmless name.
The shared path policy in `tools/source_policy.py` also keeps recognized runtime files out of
Proxmox source archives; `.gitignore` alone does not filter a custom deployment archive.
For an independent secret-detector check, use a verified [Gitleaks release](https://github.com/gitleaks/gitleaks).
Scan the candidate source snapshot, staged index and reachable Git history with full redaction.
Keep reports outside the published source, review every finding, and never paste secret values
into issues. A clean detector report is limited to its rules and scanned inputs.
Git author/committer identities and old source remain in history. Review whether those identities
are suitable for publication. Do not silently rewrite attribution/history or delete branches to
hide findings. Any real credential exposure needs revocation and a separately authorized history
cleanup. Re-run the audit after that work and on the actual refs intended for publication.
Publication is a separate action: review the local changes, commit/push with authorization, and
enable anonymous access on the intended host. This cleanup does not change repository visibility.
+171
View File
@@ -0,0 +1,171 @@
"""Read-only publication check. Reports paths/pattern names, never matching secret values."""
import argparse
from dataclasses import dataclass
from pathlib import Path
import re
import subprocess
import sys
from source_policy import is_private_path as sensitive_path
ROOT = Path(__file__).resolve().parent.parent
LIMIT = 2 * 1024 * 1024
PATTERNS = (
("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----")),
("provider token", re.compile(rb"\bsk-(?:ant-|proj-|svcacct-)[A-Za-z0-9_-]{24,}")),
("Git hosting token", re.compile(rb"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})")),
("credential in URL", re.compile(rb"https?://[^\s/:@]+:[^\s/@]+@")),
)
@dataclass(frozen=True)
class Finding:
path: str
kind: str
line: int = 0
def inspect(path, data):
if b"\0" in data[:8192]:
return []
return [Finding(path, kind, data.count(b"\n", 0, match.start()) + 1)
for kind, pattern in PATTERNS for match in pattern.finditer(data)]
def git(root, *arguments, data=None):
return subprocess.run(["git", *arguments], cwd=root, input=data, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True).stdout
def working_tree(root):
names = set(git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").decode("utf-8").split("\0")) - {""}
findings, skipped, scanned = [], [], 0
for name in sorted(names):
path = root / name
if sensitive_path(name):
findings.append(Finding(name, "local configuration/credential/runtime filename"))
elif path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
findings.append(Finding(name, "symlink/outside source tree"))
elif not path.exists():
continue # Removed tracked file; history is checked separately.
elif not path.is_file() or path.stat().st_size > LIMIT:
skipped.append(name)
else:
data = path.read_bytes()
if b"\0" in data[:8192]:
skipped.append(name)
continue
findings.extend(inspect(name, data))
scanned += 1
staged, staged_count, staged_skipped = index(root)
return findings + staged, scanned + staged_count, skipped + staged_skipped
def index(root):
"""Audit actual index blobs, not their potentially different working copies. No staging changes."""
records = git(root, "ls-files", "--stage", "-z").decode("utf-8").split("\0")
findings, skipped, scanned = [], [], 0
for record in filter(None, records):
metadata, name = record.split("\t", 1)
mode, oid, stage = metadata.split()
label = "index:" + name
if sensitive_path(name):
findings.append(Finding(label, "staged local configuration/credential/runtime filename"))
elif stage != "0" or mode not in ("100644", "100755"):
findings.append(Finding(label, "unmerged index, symlink or submodule needs review"))
elif int(git(root, "cat-file", "-s", oid)) > LIMIT:
skipped.append(label)
else:
data = git(root, "cat-file", "blob", oid)
if b"\0" in data[:8192]:
skipped.append(label)
else:
findings.extend(inspect(label, data))
scanned += 1
return findings, scanned, skipped
def historical_private_paths(root):
# rev-list --objects gives only one name hint per blob. A blob can have been
# renamed/copied under a private filename in another tree without changing its id.
private = {}
for commit in git(root, "rev-list", "--all").decode("ascii").splitlines():
for record in git(root, "ls-tree", "-r", "-z", "--full-tree", commit).decode("utf-8").split("\0"):
if not record:
continue
metadata, name = record.split("\t", 1)
if sensitive_path(name):
private.setdefault(metadata.split()[2], set()).add(name)
return private
def history(root):
private = historical_private_paths(root)
objects = {}
for entry in git(root, "rev-list", "--objects", "--all").decode("utf-8").splitlines():
oid, _, name = entry.partition(" ")
objects[oid] = name
findings, skipped, scanned = [], [], 0
metadata = git(root, "cat-file", "--batch-check", data="".join(o + "\n" for o in objects).encode()).decode("ascii")
candidates = []
for row in metadata.splitlines():
oid, kind, size = row.split()
if kind not in ("blob", "commit", "tag"):
continue
name = objects[oid] or "<" + kind + ">"
label = "history:" + oid[:12] + ":" + name
if oid in private or sensitive_path(name):
findings.extend(Finding("history:" + oid[:12] + ":" + p, "historical local configuration/credential/runtime filename")
for p in sorted(private.get(oid, {name})))
elif int(size) > LIMIT:
skipped.append(label)
else:
candidates.append((oid, label))
# One batch process avoids starting Git separately for every historical source blob.
with subprocess.Popen(["git", "cat-file", "--batch"], cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL) as process:
for oid, label in candidates:
process.stdin.write((oid + "\n").encode())
process.stdin.flush()
header = process.stdout.readline().split()
if len(header) != 3 or header[1] not in (b"blob", b"commit", b"tag"):
raise ValueError("Unexpected Git object response")
data = process.stdout.read(int(header[2]))
if process.stdout.read(1) != b"\n":
raise ValueError("Truncated Git object response")
if b"\0" in data[:8192]:
skipped.append(label)
else:
findings.extend(inspect(label, data))
scanned += 1
process.stdin.close()
if process.wait() != 0:
raise ValueError("Git object read failed")
return findings, scanned, skipped
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--history", action="store_true", help="Also inspect reachable Git source, commit and tag text")
args = parser.parse_args(argv)
findings, count, skipped = working_tree(ROOT)
print(f"Worktree/index: {count} text versions scanned; {len(skipped)} binary/oversized versions skipped.")
if args.history:
old, count, old_skipped = history(ROOT)
findings.extend(old)
skipped.extend(old_skipped)
print(f"Reachable history: {count} text objects; {len(old_skipped)} binary/oversized objects skipped.")
print("Git author/committer identities remain unchanged; inspect them before publication.")
for item in findings:
print(f"{item.path}:{item.line}: {item.kind}")
for path in skipped:
print("Not content-scanned: " + path)
print(f"Pattern findings: {len(findings)}. This targeted check cannot prove absence of arbitrary secrets.")
return 1 if findings else 0
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, ValueError, subprocess.CalledProcessError):
print("Publication check could not complete; no source/credential values are printed.", file=sys.stderr)
sys.exit(2)
+1 -1
View File
@@ -10,7 +10,7 @@ import sys
from urllib.parse import unquote, urlsplit
SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"}
SKIP = {".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"}
IDENTIFIER = re.compile(r"\b[RD][0-9]+\b")
LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)")
REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
+1 -1
View File
@@ -69,7 +69,7 @@ class DocumentationCheck(unittest.TestCase):
self.assertEqual(["notes.md:4: missing anchor: #hidden"], check(self.root))
def test_excluded_trees(self):
for directory in (".git", "bin", "obj", ".artifacts", "node_modules"):
for directory in (".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"):
self.write(f"{directory}/notes.md", "R99 [Gone](gone.md)\n")
self.write("nested/.git", "gitdir: elsewhere\n")
self.write("nested/notes.md", "R99\n")
+2
View File
@@ -51,6 +51,8 @@ def main():
else:
shutil.copy2(file, target)
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
shutil.copy2(root / 'LICENSE', output / 'LICENSE')
shutil.copy2(root / 'LICENSE', plugin / 'LICENSE')
manifest_path = plugin / 'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
manifest['Version'] = plugin_version
+14
View File
@@ -0,0 +1,14 @@
"""Shared publication/deployment policy for local runtime files; never read their contents."""
from pathlib import PurePosixPath
PRIVATE_NAMES = {"server.json", "worker.json", "server.env", "worker.env", "transport-keys.json", "dashboard-key", "worker-key",
"auth.json", ".credentials.json", "snapshot.json", "fleet.json", "history.json", "history.state.json",
"history.journal.jsonl", "usage.json", "profile.json", "settings.json", "id_rsa", "id_ecdsa", "id_ed25519"}
def is_private_path(path):
p = PurePosixPath(str(path).replace("\\", "/").lower())
return (p.name in PRIVATE_NAMES or p.name == ".env" or p.name.startswith(".env.") and p.name != ".env.example"
or p.suffix in (".env", ".key", ".pem", ".pfx", ".p12")
or any(part in (".claude", ".codex", ".ssh", ".aws", ".azure") for part in p.parts)
or len(p.parts) > 1 and p.parts[0] in ("data", "state", "logs", "runs", "history"))
+98
View File
@@ -0,0 +1,98 @@
"""Publication guard tests use synthetic values and read-only Git ignore queries."""
import subprocess
import tempfile
from pathlib import Path
import unittest
from unittest.mock import patch
import check_public
class PublicCheckTests(unittest.TestCase):
def test_private_names_are_reported_without_reading_them(self):
for path in ("server.json", "deploy/worker.env", "profiles/.codex/auth.json", "fleet.json", "private.pem", ".env.production"):
with self.subTest(path=path):
self.assertTrue(check_public.sensitive_path(path))
def test_source_and_placeholder_examples_are_allowed(self):
for path in ("server.example.json", "src/FinalToken.Core/HistoryStore.cs", "docs/web-dashboard.md", ".env.example", "LICENSE"):
self.assertFalse(check_public.sensitive_path(path))
def test_matching_values_never_appear_in_findings(self):
synthetic = "sk-" + "ant-" + "x" * 32
findings = check_public.inspect("synthetic.txt", ("header\n" + synthetic).encode())
self.assertEqual(1, len(findings))
self.assertEqual(2, findings[0].line)
self.assertEqual("provider token", findings[0].kind)
self.assertNotIn(synthetic, repr(findings))
def test_private_key_and_url_credentials_are_detected(self):
key = b"-----BEGIN " + b"PRIVATE KEY-----"
url = b"https://" + b"fixture:[email protected]/repo.git"
self.assertEqual({"private key", "credential in URL"}, {f.kind for f in check_public.inspect("fixture", key + b"\n" + url)})
def test_binary_input_is_not_treated_as_source(self):
self.assertEqual([], check_public.inspect("image.png", b"\0" + b"sk-" + b"ant-" + b"x" * 32))
def test_staged_secret_is_found_even_when_working_copy_is_clean(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "source.txt").write_text("clean working copy")
staged = ("sk-" + "proj-" + "x" * 32).encode()
oid = "a" * 40
def fake_git(where, *args, data=None):
if args[0] == "ls-files" and "--stage" in args:
return f"100644 {oid} 0\tsource.txt\0".encode()
if args[0] == "ls-files":
return b"source.txt\0"
if args[:2] == ("cat-file", "-s"):
return str(len(staged)).encode()
if args[:2] == ("cat-file", "blob"):
return staged
self.fail("Unexpected Git read")
with patch.object(check_public, "git", side_effect=fake_git):
findings, _, _ = check_public.working_tree(root)
self.assertTrue(any(f.path.startswith("index:") and f.kind == "provider token" for f in findings))
def test_working_tree_symlink_is_rejected_before_resolving_its_target(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
with patch.object(check_public, "git", return_value=b"link.cs\0"), \
patch.object(check_public, "index", return_value=([], 0, [])), \
patch.object(Path, "is_symlink", return_value=True), patch.object(Path, "read_bytes", side_effect=AssertionError("must not read")):
findings, _, _ = check_public.working_tree(root)
self.assertEqual("symlink/outside source tree", findings[0].kind)
def test_historical_private_name_is_detected_when_same_blob_had_a_public_name(self):
oid = "c" * 40
def fake_git(root, *args, data=None):
if args[0] == "rev-list":
return b"first\nsecond\n"
name = "examples/example.json" if args[-1] == "first" else "auth.json"
return f"100644 blob {oid}\t{name}\0".encode()
with patch.object(check_public, "git", side_effect=fake_git):
paths = check_public.historical_private_paths(Path("unused"))
self.assertEqual({oid: {"auth.json"}}, paths)
def test_staged_private_file_is_reported_without_opening_its_blob(self):
def fake_git(root, *args, data=None):
self.assertEqual("ls-files", args[0])
return ("100644 " + "a" * 40 + " 0\tserver.env\0").encode()
with patch.object(check_public, "git", side_effect=fake_git):
findings, count, _ = check_public.index(Path("unused"))
self.assertEqual(0, count)
self.assertEqual("index:server.env", findings[0].path)
def test_git_ignores_live_runtime_data_but_keeps_examples(self):
paths = ["server.json", "deploy/worker.json", "server.env", ".env.production", "transport-keys.json", "fleet.json",
"snapshot.json", "history.journal.jsonl", "profiles/.codex/auth.json", "private.key", "logs/session.log"]
result = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
input=("\0".join(paths) + "\0").encode(), capture_output=True, check=True)
self.assertEqual(set(paths), set(result.stdout.decode().strip("\0").split("\0")))
examples = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
input=b".env.example\0server.example.json\0LICENSE\0", capture_output=True)
self.assertEqual(1, examples.returncode)
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -7,6 +7,7 @@ import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET
import zipfile
import publish
@@ -28,6 +29,11 @@ class PublishTests(unittest.TestCase):
self.assertIsNotNone(version)
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
self.assertEqual(version + '.0', manifest['Version'])
license_text = (Path(publish.__file__).resolve().parent.parent / 'LICENSE').read_text(encoding='utf-8')
self.assertEqual(license_text, (output / 'LICENSE').read_text(encoding='utf-8'))
self.assertEqual(license_text, (output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/LICENSE').read_text(encoding='utf-8'))
with zipfile.ZipFile(output.with_suffix('.zip')) as bundle:
self.assertEqual(license_text, bundle.read('LICENSE').decode('utf-8'))
if __name__ == '__main__':