Compare commits

...

31 Commits

Author SHA1 Message Date
Alexandre
bcc521015b Merge pull request #2876 from alexbelgium/agent/fix-free-games-claimer-build
Fix Free Games Claimer PR build context
2026-07-17 10:03:53 +02:00
Alexandre
6b46611a0b Fix Free Games Claimer PR build context 2026-07-17 09:59:48 +02:00
github-actions
a72e03e88a GitHub bot: changelog [nobuild] 2026-07-17 07:48:27 +00:00
Alexandre
8042ac6786 Update config.yaml 2026-07-17 09:42:27 +02:00
Alexandre
5b7de5907f Update config.yaml 2026-07-17 09:28:29 +02:00
github-actions
0d344ecd6c Github bot : issues linked to readme 2026-07-17 07:27:38 +00:00
Alexandre
f34848ae42 nobuild
Migrate Free Games Claimer to remaster upstream
2026-07-17 09:27:19 +02:00
Alexandre
61627e80bb Merge pull request #2875 from alexbelgium/simplify/claude-desktop
fix(claude_desktop): fix silent TokenSave indexing, simplify startup, bump tokensave
2026-07-17 09:26:19 +02:00
Alexandre
6f693f39dc Validate Free Games Claimer migration 2026-07-17 09:23:51 +02:00
alexbelgium
0397e2b849 fix(claude_desktop): fix silent TokenSave indexing, simplify startup logic, bump tokensave
TokenSave repository indexing was silently processing zero paths on every
boot: bashio::config's read -d '' always returns non-zero, and process
substitution inherits the errexit that the bashio wrapper enables, so
`done < <(bashio::config 'tokensave_project_paths')` died before printing
anything. Fixed by capturing with command substitution first.

Also a simplification pass over the startup scripts — three duplicated
settings.json hook mutators collapse into one helper, two duplicated
CLAUDE.md guidance managers collapse into another, 81-tokensave_repositories.sh
merges into 82's loop, and several dead code paths (apk/pacman installers,
pip3 fallback, the /tmp/claude-desktop-command indirection, a stale
auto_update option, a redundant chown pass) are removed. No change to what
gets configured — Headroom/RTK/TokenSave still auto-apply to every session
type. tokensave bumped 7.2.0 -> 7.4.0 (rtk and headroom-ai were already at
latest). See CHANGELOG.md for full detail.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:22:14 +02:00
Alexandre
865e1c8e6d Run final add-on validation 2026-07-17 09:21:32 +02:00
Alexandre
25945f5a37 Document pinned upstream policy 2026-07-17 09:20:45 +02:00
Alexandre
feaf4f5c92 Document controlled upstream updates 2026-07-17 09:20:10 +02:00
Alexandre
fa83755108 Pause unsafe automatic upstream bumps 2026-07-17 09:19:12 +02:00
Alexandre
101c252b71 Harden remaster build metadata 2026-07-17 09:18:58 +02:00
Alexandre
1f177e26f4 Preserve defaults for existing installs 2026-07-17 09:13:13 +02:00
Alexandre
9232156924 Fix remaster browser profile path 2026-07-17 09:11:01 +02:00
Alexandre
766abd5ec3 Trigger add-on validation 2026-07-17 09:09:59 +02:00
Alexandre
49fbbbf59c Improve legacy store mapping 2026-07-17 09:08:09 +02:00
Alexandre
a55c410b9c Relax legacy config parsing 2026-07-17 09:06:57 +02:00
Alexandre
e32a134ee2 Update Free Games Claimer changelog 2026-07-17 09:04:11 +02:00
Alexandre
0019b52f4a Document remaster migration 2026-07-17 09:03:54 +02:00
Alexandre
a240dd8d00 Track remaster upstream 2026-07-17 09:03:20 +02:00
Alexandre
408f9ee05b Update remaster configuration template 2026-07-17 09:03:12 +02:00
Alexandre
324dc560c2 Migrate legacy claim history 2026-07-17 09:03:00 +02:00
Alexandre
cc8b402942 Adapt launcher for remaster 2026-07-17 09:02:23 +02:00
Alexandre
8eb51526a1 Build Free Games Claimer Remaster 2026-07-17 09:01:50 +02:00
Alexandre
4c068c6792 Configure remaster runtime 2026-07-17 09:01:09 +02:00
Alexandre
476f02924d Switch Free Games Claimer upstream 2026-07-17 09:00:51 +02:00
github-actions
2964b762d1 Github bot : issues linked to readme 2026-07-17 06:37:57 +00:00
github-actions
b942bcf336 Github bot : issues linked to readme 2026-07-17 06:37:33 +00:00
23 changed files with 1070 additions and 735 deletions

View File

@@ -93,6 +93,21 @@ jobs:
- name: ↩️ Checkout
uses: actions/checkout@v7
- name: Copy templates into addon build context
env:
ADDON: ${{ matrix.addon }}
run: |
set -euo pipefail
TEMPLATES_DIR=".templates"
ADDON_DIR="./$ADDON"
# Keep PR builds aligned with the production builder.
for script in ha_automodules.sh ha_autoapps.sh ha_entrypoint.sh bashio-standalone.sh ha_lsio.sh; do
if [ -f "$TEMPLATES_DIR/$script" ]; then
cp "$TEMPLATES_DIR/$script" "$ADDON_DIR/$script"
fi
done
- name: ℹ️ Gather addon info
id: information
uses: frenck/action-addon-information@v1.4

View File

@@ -1,3 +1,5 @@
## source-20260717 (17-07-2026)
- Minor bugs fixed
## source-20260716.02 (16-07-2026)
- Minor bugs fixed
## source-20260716 (16-07-2026)

View File

@@ -127,5 +127,5 @@ slug: birdnet-go-dev
udev: true
url: https://github.com/alexbelgium/hassio-addons
usb: true
version: "source-20260716"
version: "source-20260717"
video: true

View File

@@ -1,3 +1,16 @@
## 1.32 (17-07-2026)
- Bump `tokensave` from 7.2.0 to 7.4.0 (`rtk` was already pinned to its current latest GitHub release, `v0.43.0`; `headroom-ai` is intentionally installed unpinned from PyPI, so it already tracks latest at every build and had nothing to bump). Reviewed the intervening 7.3.0/7.4.0 release notes against every tokensave surface this add-on drives (`install --agent claude --git-hook yes`, `uninstall --agent claude`, `sync`, `init`, `doctor --agent claude`, `gain --all --range 30d`, and the `mcp__tokensave__*` tool set granted in `settings.json`): no flag, output shape, or MCP tool name used here changed. Directly relevant fixes carried along: `tokensave sync` auto-migrates a v12 database (missing the trait-dispatch caller cache) to v13 as a normal part of syncing, which the add-on's corruption-quarantine logic won't mistake for corruption since the schema migration doesn't produce a "malformed"/"not a database" error; and `install`/`uninstall`'s JSON writer now resolves a symlinked `~/.claude/settings.json` before its atomic rename instead of replacing the symlink with a plain file, so a dotfiles-managed settings file survives untouched.
- Fix startup TokenSave repository preparation silently doing nothing: both `81-tokensave_repositories.sh` and the indexing loop in `82-claude_tools.sh` read `tokensave_project_paths` through `done < <(bashio::config ...)`, but `bashio::config` begins with a `read -d ''` heredoc that always returns non-zero, and a process substitution inherits the `errexit` enabled by the bashio wrapper itself — so the subshell died before printing and every boot iterated over an empty list (no `safe.directory` persistence, no startup `sync`/`init`; command substitutions were unaffected because subshells drop `errexit` when `inherit_errexit` is off, which is why every other option lookup worked). Repositories only got indexed when tokensave's own git hooks or a manual `tokensave init` happened to run. The list is now captured with a command substitution first and the loop reads from the captured variable (here-string); same fix applied to `claude-tools-doctor.sh`. The indexing loop also moved ahead of the MCP-registration merge, and the merge now re-tightens the 0600 mode on the token-bearing configs even on no-change boots — a first-time `tokensave init` rewrites `~/.claude.json` itself at default permissions, which previously could leave the stored Home Assistant token world-readable until the next registration change.
- Simplification pass over the startup logic: every remaining line now serves a live purpose, with no change to what gets configured — Headroom (proxy routing, MCP registration, CLAUDE.md guidance, PostToolUse auto-compression, dashboard exposure), RTK (global files + PreToolUse hook), and TokenSave (full agent integration + per-repo indexing) are still applied automatically to every new session type (terminal, Desktop cowork/dispatch, cron).
- `82-claude_tools.sh`: the three hand-rolled `~/.claude/settings.json` hook mutators (rtk add, rtk remove, headroom PostToolUse) are replaced by one shared `manage_settings_hook` helper using the proven strip-then-re-append pass (same dedup/matcher-migration semantics; additionally no longer creates an empty `settings.json` when asked to remove a hook from a machine that never had one). The two copy-pasted CLAUDE.md guidance managers (headroom, ha-api-helper) collapse into one `manage_claude_md_block` helper producing byte-identical blocks, so existing installs are recognized without a rewrite.
- `81-tokensave_repositories.sh` is merged into the TokenSave loop of `82-claude_tools.sh`: the same path list was parsed twice with identical trimming/validation only so `safe.directory` could be persisted before repository detection ran as root. Detection now runs directly as the runtime user with a one-shot `safe.directory` override (the persisted entry is still written for tokensave's git hooks and Claude sessions), removing the duplicate loop and the root-reads-abc-gitconfig coupling. The battle-tested defensive sync/init block (flock, retries, corruption quarantine, init sentinel) is unchanged.
- The `/tmp/claude-desktop-command` indirection is gone: `82-claude_tools.sh` wrote the default launch command to a file that only `defaults/autostart` read, with the identical default hardcoded as its fallback — nothing else ever wrote it. `autostart` now launches Claude Desktop directly (keyring bootstrap unchanged).
- `82-claude_tools.sh` no longer ends with its own recursive chown of `~/.claude`, `~/.claude.json`, and `~/.config/Claude`: `84-claude_runtime_ownership.sh` already reconciles exactly those paths after all Claude configuration scripts have run.
- `83-claude_permissions.sh` drops the hidden `.addon-permission-mode.json` state file in favor of the same managed-value semantics used for `ANTHROPIC_BASE_URL`: `auto`/`bypass` set `permissions.defaultMode`, `strict` removes it only while it still holds an add-on-managed value (`auto`/`bypassPermissions`), and a hand-set custom value is never deleted. The old restore-from-state behavior could resurrect a stale value recorded on the first managed boot; the stale state file is cleaned up on upgrade.
- `80-configuration.sh` sheds branches that were unreachable in this image: `apk`/`pacman` installers (the base is Debian), the `pip3` fallback (`uv` is always baked in), and the no-op timezone error path (invalid `TZ` values are now actually detected against `/usr/share/zoneinfo` before the symlink is written).
- Remove the dead `auto_update` option from `config.yaml` and the README: its schema entry was removed back in 1.22 and `81-claude_update.sh` has updated Claude Desktop unconditionally (best-effort, offline-safe) ever since; the README now states that behavior instead of documenting a switch that did nothing.
## 1.31 (16-07-2026)
- Pin the LinuxServer selkies base image to a fixed version (`…-debianbookworm-45960cc3-ls113`) instead of the rolling `…-debianbookworm` tag. The rolling tag is rebuilt continuously (and itself installs selkies "latest" at base-build time), so the desktop/stream runtime could change under the add-on with no change to its own files — builds are now reproducible and the base only moves when this value is bumped deliberately. The pinned tags resolve to exactly the image the rolling tag currently points at (amd64 `sha256:6a4d5154…`, aarch64 `sha256:90914dfd…`).

View File

@@ -11,7 +11,7 @@ ARG BUILD_FROM
ARG BUILD_VERSION
ARG RTK_VERSION="v0.43.0"
ARG RTK_COMMIT="5a7880d404db8364d602f2ecdc41dd790f64013f"
ARG TOKENSAVE_VERSION="7.2.0"
ARG TOKENSAVE_VERSION="7.4.0"
# The upstream aarch64 release is cross-built on ubuntu-latest and requires
# GLIBC 2.39. Build the pinned source on Bookworm instead so it is compatible

View File

@@ -70,7 +70,8 @@ Git synchronization hooks. A repository is indexed only when it is listed in
approval, or explicit full bypass for trusted installations.
- Automatic non-root runtime enforcement for bypass mode, including root-console
wrapper launches.
- Optional runtime Claude Desktop updates from Anthropic's apt repository.
- Best-effort Claude Desktop update from Anthropic's apt repository at every
startup (skipped silently when offline).
- Optional extra apt and pip package installation (pip installs use `uv`).
- Baked-in `git`, GitHub CLI (`gh`), `ripgrep`, `jq`, `shellcheck`, `yamllint`,
`hadolint`, and `actionlint`.
@@ -95,7 +96,6 @@ Git synchronization hooks. A repository is indexed only when it is listed in
| `PASSWORD` | | Optional password for direct Selkies ports. |
| `DRINODE` | | Optional GPU device override for Selkies. |
| `DNS_server` | `8.8.8.8` | DNS server used by the standard DNS module. |
| `auto_update` | `true` | Upgrade `claude-desktop` from Anthropic's apt repository at startup. |
| `permission_mode` | `auto` | Claude Code permission policy: `strict`, `auto`, or `bypass`. |
| `install_headroom` | `true` | Register Headroom MCP and run the supervised local proxy. |
| `headroom_wrap_claude_code` | `true` | Route PATH-based Claude Code launches through the already-running Headroom proxy. |

View File

@@ -39,7 +39,6 @@ options:
data_location: /data/data
additional_apps: ""
additional_pip: ""
auto_update: true
github_email: ""
enable_ha_mcp: false
ha_mcp_url: http://homeassistant:8123/api/mcp
@@ -111,5 +110,5 @@ slug: claude_desktop
tmpfs: true
udev: true
url: https://github.com/alexbelgium/hassio-addons
version: "1.31"
version: "1.32"
video: true

View File

@@ -12,23 +12,7 @@ export GNOME_KEYRING_CONTROL SSH_AUTH_SOCK
dbus-update-activation-environment --all >/dev/null 2>&1 || true
# --password-store=gnome-libsecret forces Electron onto the libsecret backend instead of
# falling back to plaintext (and warning that the sign-in will not be saved).
CLAUDE_DESKTOP_COMMAND_FILE="/tmp/claude-desktop-command"
DEFAULT_CLAUDE_DESKTOP_COMMAND="claude-desktop --no-sandbox --disable-dev-shm-usage --password-store=gnome-libsecret"
if [ -s "$CLAUDE_DESKTOP_COMMAND_FILE" ]; then
CLAUDE_DESKTOP_COMMAND="$(cat "$CLAUDE_DESKTOP_COMMAND_FILE")"
else
CLAUDE_DESKTOP_COMMAND="$DEFAULT_CLAUDE_DESKTOP_COMMAND"
fi
# Headroom is intentionally not injected into the Desktop process. Claude Desktop overrides
# ANTHROPIC_BASE_URL, so Desktop uses the registered Headroom MCP tools instead.
# Launch the configured command. If a custom/wrapped command fails to start, fall back to
# the plain Claude Desktop launch so the app always comes up for the user.
if ! sh -c "$CLAUDE_DESKTOP_COMMAND"; then
if [ "$CLAUDE_DESKTOP_COMMAND" != "$DEFAULT_CLAUDE_DESKTOP_COMMAND" ]; then
echo "autostart: '$CLAUDE_DESKTOP_COMMAND' failed; falling back to default Claude Desktop launch" >&2
exec sh -c "$DEFAULT_CLAUDE_DESKTOP_COMMAND"
fi
fi
# falling back to plaintext (and warning that the sign-in will not be saved). Headroom is
# intentionally not injected into the Desktop process: Claude Desktop force-overrides
# ANTHROPIC_BASE_URL (headroom #869), so Desktop uses the registered Headroom MCP tools.
exec claude-desktop --no-sandbox --disable-dev-shm-usage --password-store=gnome-libsecret

View File

@@ -1,58 +1,48 @@
#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
# shellcheck disable=SC2015
set -e
# The image is Debian-based (apt) and always ships uv, so those are the only installers used.
if bashio::config.has_value 'additional_apps'; then
bashio::log.info "Installing additional apps :"
NEWAPPS=$(bashio::config 'additional_apps')
if command -v "apt-get" &> /dev/null; then
apt-get update -o Acquire::http::Timeout=10 -o Acquire::https::Timeout=10 &> /dev/null || bashio::log.warning "Unable to update apt package lists"
fi
for packagestoinstall in ${NEWAPPS//,/ }; do
apt-get update -o Acquire::http::Timeout=10 -o Acquire::https::Timeout=10 &> /dev/null || bashio::log.warning "Unable to update apt package lists"
for packagestoinstall in $(bashio::config 'additional_apps' | tr ',' ' '); do
bashio::log.green "... $packagestoinstall"
if command -v "apk" &> /dev/null; then
apk add --no-cache "$packagestoinstall" &> /dev/null || (bashio::log.fatal "Error : $packagestoinstall not found")
elif command -v "apt-get" &> /dev/null; then
apt-get install -yqq --no-install-recommends "$packagestoinstall" &> /dev/null || (bashio::log.fatal "Error : $packagestoinstall not found")
elif command -v "pacman" &> /dev/null; then
pacman --noconfirm -S "$packagestoinstall" &> /dev/null || (bashio::log.fatal "Error : $packagestoinstall not found")
fi
apt-get install -yqq --no-install-recommends "$packagestoinstall" &> /dev/null || bashio::log.fatal "Error : $packagestoinstall not found"
done
fi
if bashio::config.has_value 'additional_pip'; then
for p in $(bashio::config 'additional_pip' | tr ',' ' '); do
bashio::log.green "... pip: $p"
# Prefer uv (much faster resolver/installer); fall back to pip3 when unavailable.
if command -v uv &> /dev/null; then
uv pip install --system --break-system-packages "$p" || bashio::log.fatal "Error: pip package $p failed"
else
pip3 install --break-system-packages "$p" || bashio::log.fatal "Error: pip package $p failed"
fi
uv pip install --system --break-system-packages "$p" || bashio::log.fatal "Error: pip package $p failed"
done
fi
if bashio::config.has_value 'TZ'; then
TIMEZONE=$(bashio::config 'TZ')
bashio::log.info "Setting timezone to $TIMEZONE"
ln -snf /usr/share/zoneinfo/"$TIMEZONE" /etc/localtime
echo "$TIMEZONE" > /etc/timezone
fi || (bashio::log.fatal "Error : $TIMEZONE not found. Here is a list of valid timezones : https://manpages.ubuntu.com/manpages/focal/man3/DateTime::TimeZone::Catalog.3pm.html")
if [ -f "/usr/share/zoneinfo/$TIMEZONE" ]; then
bashio::log.info "Setting timezone to $TIMEZONE"
ln -snf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
echo "$TIMEZONE" > /etc/timezone
else
bashio::log.fatal "Error : $TIMEZONE not found. Here is a list of valid timezones : https://manpages.ubuntu.com/manpages/focal/man3/DateTime::TimeZone::Catalog.3pm.html"
fi
fi
if bashio::config.has_value 'KEYBOARD'; then
KEYBOARD=$(bashio::config 'KEYBOARD')
bashio::log.info "Setting keyboard to $KEYBOARD"
if [ -d /var/run/s6/container_environment ]; then printf "%s" "$KEYBOARD" > /var/run/s6/container_environment/KEYBOARD; fi
grep -qxF "KEYBOARD=\"$KEYBOARD\"" ~/.bashrc 2>/dev/null || printf "%s\n" "KEYBOARD=\"$KEYBOARD\"" >> ~/.bashrc
fi || true
grep -qxF "KEYBOARD=\"$KEYBOARD\"" ~/.bashrc 2> /dev/null || printf "%s\n" "KEYBOARD=\"$KEYBOARD\"" >> ~/.bashrc
fi
if bashio::config.has_value 'PASSWORD'; then
bashio::log.info "Setting password to the value defined in options"
PASSWORD=$(bashio::config 'PASSWORD')
passwd -d abc
echo -e "$PASSWORD\n$PASSWORD" | passwd abc
elif ! bashio::config.has_value 'PASSWORD' && { [[ -n "$(bashio::addon.port "3000")" ]] || [[ -n "$(bashio::addon.port "3001")" ]] }; then
elif [[ -n "$(bashio::addon.port "3000")" ]] || [[ -n "$(bashio::addon.port "3001")" ]]; then
bashio::log.warning "SEVERE RISK IDENTIFIED"
bashio::log.warning "You are opening an external port but your password is not defined"
bashio::log.warning "You risk being hacked ! Please disable the external ports, or use a password"

View File

@@ -1,42 +0,0 @@
#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
set -e
set -o pipefail
if ! bashio::config.true 'install_tokensave' || ! command -v git > /dev/null 2>&1; then
exit 0
fi
declare -A REPOS_SEEN=()
# bashio::config prints its result without a trailing newline, so the last record arrives
# with read returning non-zero; the extra test keeps that final path in the loop.
while IFS= read -r configured_path || [ -n "$configured_path" ]; do
configured_path="${configured_path#"${configured_path%%[![:space:]]*}"}"
configured_path="${configured_path%"${configured_path##*[![:space:]]}"}"
if [ -z "$configured_path" ] || [ "$configured_path" = "null" ]; then
continue
fi
case "$configured_path" in
/*) ;;
*) continue ;;
esac
[ -d "$configured_path" ] || continue
# The one-shot safe.directory override is used only to discover the repository root.
# Persist the resolved root in the shared runtime user's Git config before 82-claude_tools.sh
# performs normal repository detection, avoiding Git's dubious-ownership rejection.
repo_root="$(s6-setuidgid abc env HOME="$HOME" \
git -c safe.directory='*' -C "$configured_path" rev-parse --show-toplevel 2> /dev/null || true)"
[ -n "$repo_root" ] && [ "$repo_root" != "/" ] || continue
[[ -z "${REPOS_SEEN[$repo_root]:-}" ]] || continue
REPOS_SEEN[$repo_root]=1
if ! s6-setuidgid abc env HOME="$HOME" git config --global --get-all safe.directory \
| grep -Fxq -- "$repo_root"; then
s6-setuidgid abc env HOME="$HOME" git config --global --add safe.directory "$repo_root"
bashio::log.info "Marked TokenSave repository as safe for Git: ${repo_root}"
fi
# bashio::config prints list options one entry per line ("null" when the key is absent);
# bashio::config.array only exists in the repo's standalone bashio, not in the real bashio here.
done < <(bashio::config 'tokensave_project_paths')

View File

@@ -3,19 +3,125 @@
set -e
set -o pipefail
# 20-folders.sh already remapped abc to the effective runtime identity (never root in bypass
# mode), so follow abc instead of re-reading the raw PUID/PGID options here.
RUNTIME_UID="$(id -u abc)"
RUNTIME_GID="$(id -g abc)"
mkdir -p "$HOME/.claude"
CLAUDE_MD="$HOME/.claude/CLAUDE.md"
run_as_runtime_user() {
s6-setuidgid abc env HOME="$HOME" "$@"
}
CLAUDE_DESKTOP_COMMAND_FILE="/tmp/claude-desktop-command"
DEFAULT_CLAUDE_DESKTOP_COMMAND='claude-desktop --no-sandbox --disable-dev-shm-usage --password-store=gnome-libsecret'
printf '%s\n' "$DEFAULT_CLAUDE_DESKTOP_COMMAND" > "$CLAUDE_DESKTOP_COMMAND_FILE"
# Managed, idempotent guidance block in the user's global CLAUDE.md, delimited by
# "<!-- BEGIN/END <name> (managed by claude_desktop addon) -->" markers. `add` appends the
# block (body on stdin) unless the marker is already present; `remove` strips the whole
# block, surrounding blank padding included, and leaves everything else untouched.
manage_claude_md_block() {
local name="$1" action="$2"
local begin="<!-- BEGIN ${name} (managed by claude_desktop addon) -->"
if [ "$action" = "add" ]; then
if ! { [ -f "$CLAUDE_MD" ] && grep -qF "$begin" "$CLAUDE_MD"; }; then
bashio::log.info "Adding ${name} guidance to CLAUDE.md"
mkdir -p "$(dirname "$CLAUDE_MD")"
{
[ -s "$CLAUDE_MD" ] && printf '\n'
printf '%s\n' "$begin"
cat
printf '%s\n' "<!-- END ${name} (managed by claude_desktop addon) -->"
} >> "$CLAUDE_MD"
fi
elif [ -f "$CLAUDE_MD" ] && grep -qF "$begin" "$CLAUDE_MD"; then
bashio::log.info "Removing ${name} guidance from CLAUDE.md"
CLAUDE_MD="$CLAUDE_MD" BLOCK_NAME="$name" python3 - <<'PY' || bashio::log.warning "Unable to remove the ${name} guidance automatically"
import os
import re
from pathlib import Path
path = Path(os.environ["CLAUDE_MD"])
name = re.escape(os.environ["BLOCK_NAME"])
text = path.read_text(encoding="utf-8")
pattern = re.compile(
rf"\n*<!-- BEGIN {name} \(managed by claude_desktop addon\) -->.*?"
rf"<!-- END {name} \(managed by claude_desktop addon\) -->\n?",
re.DOTALL,
)
new = pattern.sub("", text)
if new != text:
path.write_text(new, encoding="utf-8")
PY
fi
}
# Managed hook entry in ~/.claude/settings.json (settings hooks apply to terminal, cowork,
# dispatch and cron sessions alike). The managed command is stripped everywhere first and
# re-appended when adding, so one pass handles removal, de-duplication, and matcher migration
# on upgrades; hooks owned by other tools (e.g. tokensave's own entries) are preserved, and
# the final text comparison keeps the write idempotent across boots.
manage_settings_hook() {
# manage_settings_hook <event> <matcher> <command> <add|remove>
HOOK_EVENT="$1" HOOK_MATCHER="$2" HOOK_COMMAND="$3" HOOK_ACTION="$4" \
python3 - <<'PY' || bashio::log.warning "Unable to update the $1 hook for '$3'"
import json
import os
from pathlib import Path
event = os.environ["HOOK_EVENT"]
matcher = os.environ["HOOK_MATCHER"]
command = os.environ["HOOK_COMMAND"]
action = os.environ["HOOK_ACTION"]
path = Path.home() / ".claude" / "settings.json"
original = path.read_text() if path.exists() else None
if original is None and action != "add":
raise SystemExit(0)
try:
data = json.loads(original) if original is not None else {}
if not isinstance(data, dict):
data = {}
except Exception:
if action != "add":
raise SystemExit(0)
path.rename(path.with_suffix(path.suffix + ".bak"))
original = None
data = {}
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
entries = hooks.get(event) if isinstance(hooks.get(event), list) else []
filtered = []
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
filtered.append(entry)
continue
kept = [
item
for item in entry["hooks"]
if not (isinstance(item, dict) and item.get("command") == command)
]
if len(kept) != len(entry["hooks"]):
if not kept:
continue
entry = dict(entry)
entry["hooks"] = kept
filtered.append(entry)
entries = filtered
if action == "add":
entries.append({"matcher": matcher, "hooks": [{"type": "command", "command": command}]})
if entries:
hooks[event] = entries
else:
hooks.pop(event, None)
if hooks:
data["hooks"] = hooks
else:
data.pop("hooks", None)
serialized = json.dumps(data, indent=2) + "\n"
if serialized != original:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(serialized)
PY
}
# Headroom's proxy routing works by setting ANTHROPIC_BASE_URL, which the Claude Desktop
# Electron app force-overrides to the production endpoint (headroom #869). Desktop therefore
@@ -57,6 +163,136 @@ elif command -v tokensave &> /dev/null; then
|| bashio::log.warning "tokensave Claude Code integration removal failed"
fi
# Initialize or incrementally sync only explicitly configured repositories. TokenSave deliberately
# requires one-time per-project opt-in; an empty list therefore has no startup or storage cost.
# Runs before the MCP registration merge below on purpose: a first-time `tokensave init` also
# rewrites ~/.claude.json itself (at default permissions), and the merge afterwards reconciles
# the managed entries and re-tightens the file mode around the stored HA token.
if $TOKENSAVE_ENABLED; then
declare -A TOKENSAVE_REPOS_SEEN=()
# Capture the list BEFORE looping: bashio::config's internals trip the errexit that
# process substitution inherits from the bashio wrapper (a `read -d ''` that always
# returns non-zero), so `done < <(bashio::config ...)` silently fed the loop an EMPTY
# list — the startup index/sync never ran. Command substitution runs without errexit
# (inherit_errexit is off), making this form reliable. bashio::config prints list
# entries one per line, without a trailing newline and as "null" when the key is absent
# (bashio::config.array only exists in the repo's standalone bashio, not the real one
# here); the `|| [ -n ... ]` test keeps the final unterminated record in the loop.
TOKENSAVE_PROJECT_PATHS="$(bashio::config 'tokensave_project_paths')"
while IFS= read -r configured_path || [ -n "$configured_path" ]; do
# Trim surrounding whitespace while preserving spaces inside paths.
configured_path="${configured_path#"${configured_path%%[![:space:]]*}"}"
configured_path="${configured_path%"${configured_path##*[![:space:]]}"}"
if [ -z "$configured_path" ] || [ "$configured_path" = "null" ]; then
continue
fi
case "$configured_path" in
/*) ;;
*)
bashio::log.warning "Skipping non-absolute tokensave_project_paths entry: ${configured_path}"
continue
;;
esac
if [ ! -d "$configured_path" ]; then
bashio::log.warning "Skipping missing TokenSave project path: ${configured_path}"
continue
fi
# The one-shot safe.directory override is used only to discover the repository root.
repo_root="$(run_as_runtime_user git -c safe.directory='*' -C "$configured_path" rev-parse --show-toplevel 2> /dev/null || true)"
if [ -z "$repo_root" ] || [ "$repo_root" = "/" ]; then
bashio::log.warning "Skipping TokenSave path that is not a supported Git repository: ${configured_path}"
continue
fi
if [[ -n "${TOKENSAVE_REPOS_SEEN[$repo_root]:-}" ]]; then
continue
fi
TOKENSAVE_REPOS_SEEN[$repo_root]=1
# Persist the resolved root in the runtime user's Git config so the sync/init below,
# tokensave's git hooks, and Claude sessions all pass Git's dubious-ownership check.
if ! run_as_runtime_user git config --global --get-all safe.directory \
| grep -Fxq -- "$repo_root"; then
run_as_runtime_user git config --global --add safe.directory "$repo_root"
bashio::log.info "Marked TokenSave repository as safe for Git: ${repo_root}"
fi
bashio::log.info "Preparing TokenSave index: ${repo_root}"
# Prepare the per-repo semantic graph defensively so a hard add-on stop or storage
# hiccup can never leave a broken index that fails every subsequent boot:
# * a startup-scoped flock serializes against an overlapping restart (and any git
# post-commit/checkout sync hook that fires mid-boot); waits up to 60s for the
# other writer to finish rather than silently skipping, since a held lock clears
# itself the moment its holder exits or dies (the kernel releases flock on exit);
# * an existing index is refreshed with a cheap incremental `sync`, retried a few
# times because SQLITE_BUSY under lock contention is transient, not corruption;
# * quarantine is reserved for sync failures whose stderr actually names database
# corruption (SQLite's own "malformed"/"not a database"/"disk image" wording) or
# a half-written index from an interrupted `init` (sentinel-flagged). Any other
# failure (permissions, disk full, missing binary, ...) leaves the existing index
# untouched and simply retries on the next start — corruption should self-heal,
# a transient environment problem should not nuke a healthy graph;
# * `init` is bracketed by a sentinel file so an interrupted full build is detected
# as incomplete on the next start and rebuilt rather than trusted.
# All file operations run as the abc runtime user because the repo `.tokensave`
# directory is not covered by the startup ownership pass.
# shellcheck disable=SC2016 # single-quoted on purpose: $1/$db/etc. expand in the abc shell
run_as_runtime_user bash -c '
set -o pipefail
repo_root="$1"
ts_dir="$repo_root/.tokensave"
db="$ts_dir/tokensave.db"
lock="$ts_dir/.startup.lock"
initflag="$ts_dir/.init-incomplete"
mkdir -p "$ts_dir"
exec 9>"$lock"
if ! flock -w 60 9; then
echo "TokenSave: index still locked for $repo_root after 60s; skipping startup sync" >&2
exit 0
fi
is_corruption() {
printf "%s" "$1" | grep -qiE "malformed|not a database|file is encrypted|disk image|database.*corrupt"
}
quarantine() {
stamp="$(date +%Y%m%d-%H%M%S)"
bdir="$ts_dir/corrupt-$stamp"
mkdir -p "$bdir"
for f in "$db" "$db-wal" "$db-shm"; do
[ -e "$f" ] && mv -f "$f" "$bdir/" 2>/dev/null || true
done
echo "TokenSave: quarantined suspect index to $bdir" >&2
}
if [ -f "$db" ] && [ ! -f "$initflag" ]; then
attempt=1
while :; do
sync_err="$(tokensave sync "$repo_root" 2>&1 1>/dev/null)" && exit 0
[ "$attempt" -ge 3 ] && break
echo "TokenSave: sync attempt $attempt failed for $repo_root; retrying" >&2
attempt=$((attempt + 1))
sleep 2
done
if is_corruption "$sync_err"; then
echo "TokenSave: sync failed after retries for $repo_root (corruption detected); rebuilding index" >&2
quarantine
else
echo "TokenSave: sync failed after retries for $repo_root (no corruption signature); leaving index in place, will retry next start" >&2
echo "TokenSave: last sync error: $sync_err" >&2
exit 1
fi
elif [ -f "$db" ]; then
echo "TokenSave: previous init did not finish for $repo_root; rebuilding index" >&2
quarantine
fi
: > "$initflag"
tokensave init "$repo_root" && { rm -f "$initflag"; exit 0; }
echo "TokenSave: init failed for $repo_root; will retry on next start" >&2
exit 1
' _ "$repo_root" \
|| bashio::log.warning "TokenSave preparation failed for ${repo_root}"
done <<< "$TOKENSAVE_PROJECT_PATHS"
fi
HA_MCP_ENABLED=false
HA_MCP_URL=""
HA_MCP_TOKEN=""
@@ -157,144 +393,24 @@ for config_var, stdio_type in (("CLAUDE_DESKTOP_CONFIG", False), ("CLAUDE_CODE_C
elif existing is not None and is_managed(name, existing):
del servers[name]
changed = True
if not changed:
continue
if servers:
data["mcpServers"] = servers
else:
data.pop("mcpServers", None)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n")
# The Home Assistant long-lived access token is stored here in clear text.
path.chmod(0o600)
if changed:
if servers:
data["mcpServers"] = servers
else:
data.pop("mcpServers", None)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n")
# The Home Assistant long-lived access token is stored here in clear text. Enforced even
# on no-change boots because tokensave's own writes can recreate the file with default
# permissions between merges.
if path.exists():
path.chmod(0o600)
PY
# Initialize or incrementally sync only explicitly configured repositories. TokenSave deliberately
# requires one-time per-project opt-in; an empty list therefore has no startup or storage cost.
if $TOKENSAVE_ENABLED; then
declare -A TOKENSAVE_REPOS_SEEN=()
# bashio::config prints its result without a trailing newline, so the last record arrives
# with read returning non-zero; the extra test keeps that final path in the loop.
while IFS= read -r configured_path || [ -n "$configured_path" ]; do
# Trim surrounding whitespace while preserving spaces inside paths.
configured_path="${configured_path#"${configured_path%%[![:space:]]*}"}"
configured_path="${configured_path%"${configured_path##*[![:space:]]}"}"
if [ -z "$configured_path" ] || [ "$configured_path" = "null" ]; then
continue
fi
case "$configured_path" in
/*) ;;
*)
bashio::log.warning "Skipping non-absolute tokensave_project_paths entry: ${configured_path}"
continue
;;
esac
if [ ! -d "$configured_path" ]; then
bashio::log.warning "Skipping missing TokenSave project path: ${configured_path}"
continue
fi
repo_root="$(git -C "$configured_path" rev-parse --show-toplevel 2> /dev/null || true)"
if [ -z "$repo_root" ] || [ "$repo_root" = "/" ]; then
bashio::log.warning "Skipping TokenSave path that is not a supported Git repository: ${configured_path}"
continue
fi
if [[ -n "${TOKENSAVE_REPOS_SEEN[$repo_root]:-}" ]]; then
continue
fi
TOKENSAVE_REPOS_SEEN[$repo_root]=1
bashio::log.info "Preparing TokenSave index: ${repo_root}"
# Prepare the per-repo semantic graph defensively so a hard add-on stop or storage
# hiccup can never leave a broken index that fails every subsequent boot:
# * a startup-scoped flock serializes against an overlapping restart (and any git
# post-commit/checkout sync hook that fires mid-boot); waits up to 60s for the
# other writer to finish rather than silently skipping, since a held lock clears
# itself the moment its holder exits or dies (the kernel releases flock on exit);
# * an existing index is refreshed with a cheap incremental `sync`, retried a few
# times because SQLITE_BUSY under lock contention is transient, not corruption;
# * quarantine is reserved for sync failures whose stderr actually names database
# corruption (SQLite's own "malformed"/"not a database"/"disk image" wording) or
# a half-written index from an interrupted `init` (sentinel-flagged). Any other
# failure (permissions, disk full, missing binary, ...) leaves the existing index
# untouched and simply retries on the next start — corruption should self-heal,
# a transient environment problem should not nuke a healthy graph;
# * `init` is bracketed by a sentinel file so an interrupted full build is detected
# as incomplete on the next start and rebuilt rather than trusted.
# All file operations run as the abc runtime user because the repo `.tokensave`
# directory is not covered by this script's final ownership pass.
# shellcheck disable=SC2016 # single-quoted on purpose: $1/$db/etc. expand in the abc shell
run_as_runtime_user bash -c '
set -o pipefail
repo_root="$1"
ts_dir="$repo_root/.tokensave"
db="$ts_dir/tokensave.db"
lock="$ts_dir/.startup.lock"
initflag="$ts_dir/.init-incomplete"
mkdir -p "$ts_dir"
exec 9>"$lock"
if ! flock -w 60 9; then
echo "TokenSave: index still locked for $repo_root after 60s; skipping startup sync" >&2
exit 0
fi
is_corruption() {
printf "%s" "$1" | grep -qiE "malformed|not a database|file is encrypted|disk image|database.*corrupt"
}
quarantine() {
stamp="$(date +%Y%m%d-%H%M%S)"
bdir="$ts_dir/corrupt-$stamp"
mkdir -p "$bdir"
for f in "$db" "$db-wal" "$db-shm"; do
[ -e "$f" ] && mv -f "$f" "$bdir/" 2>/dev/null || true
done
echo "TokenSave: quarantined suspect index to $bdir" >&2
}
if [ -f "$db" ] && [ ! -f "$initflag" ]; then
attempt=1
while :; do
sync_err="$(tokensave sync "$repo_root" 2>&1 1>/dev/null)" && exit 0
[ "$attempt" -ge 3 ] && break
echo "TokenSave: sync attempt $attempt failed for $repo_root; retrying" >&2
attempt=$((attempt + 1))
sleep 2
done
if is_corruption "$sync_err"; then
echo "TokenSave: sync failed after retries for $repo_root (corruption detected); rebuilding index" >&2
quarantine
else
echo "TokenSave: sync failed after retries for $repo_root (no corruption signature); leaving index in place, will retry next start" >&2
echo "TokenSave: last sync error: $sync_err" >&2
exit 1
fi
elif [ -f "$db" ]; then
echo "TokenSave: previous init did not finish for $repo_root; rebuilding index" >&2
quarantine
fi
: > "$initflag"
tokensave init "$repo_root" && { rm -f "$initflag"; exit 0; }
echo "TokenSave: init failed for $repo_root; will retry on next start" >&2
exit 1
' _ "$repo_root" \
|| bashio::log.warning "TokenSave preparation failed for ${repo_root}"
# bashio::config prints list options one entry per line ("null" when the key is absent);
# bashio::config.array only exists in the repo's standalone bashio, not in the real bashio here.
done < <(bashio::config 'tokensave_project_paths')
fi
# Guide Claude to actually use the Headroom compression tools so the MCP integration produces
# real savings when transparent proxying is unavailable. Managed, idempotent block appended to
# the user's global CLAUDE.md; removed when Headroom is disabled.
CLAUDE_MD="$HOME/.claude/CLAUDE.md"
HEADROOM_GUIDE_BEGIN="<!-- BEGIN headroom (managed by claude_desktop addon) -->"
# real savings when transparent proxying is unavailable.
if $HEADROOM_ENABLED; then
mkdir -p "$(dirname "$CLAUDE_MD")"
if ! { [ -f "$CLAUDE_MD" ] && grep -qF "$HEADROOM_GUIDE_BEGIN" "$CLAUDE_MD"; }; then
bashio::log.info "Adding headroom usage guidance to CLAUDE.md"
{
[ -s "$CLAUDE_MD" ] && printf '\n'
cat <<'MD'
<!-- BEGIN headroom (managed by claude_desktop addon) -->
manage_claude_md_block headroom add <<'MD'
## Headroom context compression
A local Headroom proxy (127.0.0.1:8787) backs the `headroom` MCP tools. To save context tokens:
@@ -304,28 +420,9 @@ search results, JSON/config dumps, big command outputs, roughly >500 tokens —
the raw content. Call `mcp__headroom__headroom_retrieve` with that hash when you need the full
original back. Skip compression for error/stack-trace output (Headroom deliberately protects it)
and for small or one-off content. Use `mcp__headroom__headroom_stats` to check savings.
<!-- END headroom (managed by claude_desktop addon) -->
MD
} >> "$CLAUDE_MD"
fi
elif [ -f "$CLAUDE_MD" ] && grep -qF "$HEADROOM_GUIDE_BEGIN" "$CLAUDE_MD"; then
bashio::log.info "Removing headroom usage guidance from CLAUDE.md"
CLAUDE_MD="$CLAUDE_MD" python3 - <<'PY' || bashio::log.warning "Unable to remove headroom guidance automatically"
import os
import re
from pathlib import Path
path = Path(os.environ["CLAUDE_MD"])
text = path.read_text()
pattern = re.compile(
r"\n*<!-- BEGIN headroom \(managed by claude_desktop addon\) -->.*?"
r"<!-- END headroom \(managed by claude_desktop addon\) -->\n?",
re.DOTALL,
)
new = pattern.sub("", text)
if new != text:
path.write_text(new)
PY
else
manage_claude_md_block headroom remove
fi
# Route every Claude Code session through the Headroom proxy via the `env` block in the user's
@@ -386,8 +483,7 @@ if changed:
PY
# Compress large tool outputs automatically in every Claude Code session via a managed
# PostToolUse hook (settings.json hooks apply to terminal, cowork, dispatch and cron sessions
# alike). Desktop-spawned sessions pin ANTHROPIC_BASE_URL to the production endpoint
# PostToolUse hook. Desktop-spawned sessions pin ANTHROPIC_BASE_URL to the production endpoint
# (headroom #869) so the proxy never sees their traffic, and the CLAUDE.md guidance above only
# helps when the model remembers to call the MCP tools. The hook closes that gap: outputs over
# ~4000 chars from Bash/Grep/Glob/WebFetch are compressed with Headroom's rule-based pipeline
@@ -405,84 +501,12 @@ if $HEADROOM_ENABLED && bashio::config.true 'headroom_auto_compress'; then
bashio::log.warning "headroom-posttooluse-compress.py --self-test failed; not registering the auto-compression hook"
fi
fi
HEADROOM_HOOK_ACTION="$HEADROOM_HOOK_ACTION" HEADROOM_HOOK_CMD="$HEADROOM_HOOK_CMD" \
HEADROOM_HOOK_MATCHER="Bash|Grep|Glob|WebFetch" \
python3 - <<'PY' || bashio::log.warning "Unable to manage the Headroom auto-compression hook"
import json
import os
from pathlib import Path
action = os.environ["HEADROOM_HOOK_ACTION"]
command = os.environ["HEADROOM_HOOK_CMD"]
matcher = os.environ["HEADROOM_HOOK_MATCHER"]
path = Path.home() / ".claude" / "settings.json"
original = path.read_text() if path.exists() else None
try:
data = json.loads(original) if original is not None else {}
if not isinstance(data, dict):
data = {}
except Exception:
if action != "add":
raise SystemExit(0)
path.rename(path.with_suffix(path.suffix + ".bak"))
original = None
data = {}
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
entries = hooks.get("PostToolUse") if isinstance(hooks.get("PostToolUse"), list) else []
# Strip the managed command everywhere first, then re-append when enabled: the same pass
# handles removal, de-duplication, and matcher migration on version upgrades. The final
# text comparison keeps the write idempotent across boots.
filtered = []
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
filtered.append(entry)
continue
kept = [
item
for item in entry["hooks"]
if not (isinstance(item, dict) and item.get("command") == command)
]
if len(kept) != len(entry["hooks"]):
if not kept:
continue
entry = dict(entry)
entry["hooks"] = kept
filtered.append(entry)
entries = filtered
if action == "add":
entries.append({"matcher": matcher, "hooks": [{"type": "command", "command": command}]})
if entries:
hooks["PostToolUse"] = entries
else:
hooks.pop("PostToolUse", None)
if hooks:
data["hooks"] = hooks
else:
data.pop("hooks", None)
serialized = json.dumps(data, indent=2) + "\n"
if serialized != original:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(serialized)
PY
manage_settings_hook PostToolUse "Bash|Grep|Glob|WebFetch" "$HEADROOM_HOOK_CMD" "$HEADROOM_HOOK_ACTION"
# Tell Claude Code that it can configure Home Assistant over the Core API via the shipped
# `ha-cli` helper (no /config filesystem mount needed). Managed, idempotent block appended to
# the user's global CLAUDE.md; removed when the helper is disabled. Mirrors the headroom block.
HA_HELPER_GUIDE_BEGIN="<!-- BEGIN ha-api-helper (managed by claude_desktop addon) -->"
# `ha-cli` helper (no /config filesystem mount needed).
if bashio::config.true 'enable_ha_api_helper'; then
mkdir -p "$(dirname "$CLAUDE_MD")"
if ! { [ -f "$CLAUDE_MD" ] && grep -qF "$HA_HELPER_GUIDE_BEGIN" "$CLAUDE_MD"; }; then
bashio::log.info "Adding Home Assistant API helper guidance to CLAUDE.md"
{
[ -s "$CLAUDE_MD" ] && printf '\n'
cat <<'MD'
<!-- BEGIN ha-api-helper (managed by claude_desktop addon) -->
manage_claude_md_block ha-api-helper add <<'MD'
## Configuring Home Assistant
You can configure this Home Assistant instance through its Core API using the `ha-cli`
@@ -502,120 +526,25 @@ Rules: run `ha-cli config` first to confirm connectivity; **read the current obj
the user the intended change, then wait for confirmation** before any create/update/delete or
any state-changing `call`; after writing, read the object back and reload if needed
(e.g. `ha-cli call automation.reload`).
<!-- END ha-api-helper (managed by claude_desktop addon) -->
MD
} >> "$CLAUDE_MD"
fi
elif [ -f "$CLAUDE_MD" ] && grep -qF "$HA_HELPER_GUIDE_BEGIN" "$CLAUDE_MD"; then
bashio::log.info "Removing Home Assistant API helper guidance from CLAUDE.md"
CLAUDE_MD="$CLAUDE_MD" python3 - <<'PY' || bashio::log.warning "Unable to remove Home Assistant API helper guidance automatically"
import os
import re
from pathlib import Path
path = Path(os.environ["CLAUDE_MD"])
text = path.read_text(encoding="utf-8")
pattern = re.compile(
r"\n*<!-- BEGIN ha-api-helper \(managed by claude_desktop addon\) -->.*?"
r"<!-- END ha-api-helper \(managed by claude_desktop addon\) -->\n?",
re.DOTALL,
)
new = pattern.sub("", text)
if new != text:
path.write_text(new, encoding="utf-8")
PY
else
manage_claude_md_block ha-api-helper remove
fi
if bashio::config.true 'install_rtk'; then
if command -v rtk &> /dev/null; then
bashio::log.info "Configuring rtk Claude Code integration"
# `rtk init -g` writes ~/.claude/RTK.md and its @RTK.md include in CLAUDE.md, but in
# non-interactive mode it deliberately refuses to patch settings.json, so the hook
# entry that actually rewrites Bash commands is registered here.
run_as_runtime_user env RTK_NONINTERACTIVE=1 rtk init -g \
|| bashio::log.warning "rtk global files configuration failed"
python3 - <<'PY' || bashio::log.warning "Unable to configure rtk hook automatically"
import json
from pathlib import Path
path = Path.home() / ".claude" / "settings.json"
try:
data = json.loads(path.read_text()) if path.exists() else {}
if not isinstance(data, dict):
data = {}
except Exception:
if path.exists():
path.rename(path.with_suffix(path.suffix + ".bak"))
data = {}
hooks = data.setdefault("hooks", {})
pre = hooks.setdefault("PreToolUse", [])
rtk_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": "rtk hook claude"}]}
if not any("rtk hook claude" in json.dumps(entry) for entry in pre if isinstance(entry, dict)):
pre.append(rtk_entry)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n")
PY
manage_settings_hook PreToolUse Bash "rtk hook claude" add
else
bashio::log.warning "rtk is not available"
fi
elif [ -f "$HOME/.claude/settings.json" ]; then
bashio::log.info "Removing the add-on-managed rtk Claude Code hook"
python3 - <<'PY' || bashio::log.warning "Unable to remove rtk hook automatically"
import json
from pathlib import Path
path = Path.home() / ".claude" / "settings.json"
data = json.loads(path.read_text())
if not isinstance(data, dict):
raise TypeError("Claude settings must contain a JSON object")
hooks = data.get("hooks")
if not isinstance(hooks, dict):
raise SystemExit(0)
entries = hooks.get("PreToolUse")
if not isinstance(entries, list):
raise SystemExit(0)
changed = False
filtered_entries = []
for entry in entries:
if not isinstance(entry, dict) or entry.get("matcher") != "Bash":
filtered_entries.append(entry)
continue
commands = entry.get("hooks")
if not isinstance(commands, list):
filtered_entries.append(entry)
continue
filtered_commands = [
command
for command in commands
if not (
isinstance(command, dict)
and command.get("type") == "command"
and command.get("command") == "rtk hook claude"
)
]
if len(filtered_commands) == len(commands):
filtered_entries.append(entry)
continue
changed = True
if filtered_commands:
updated_entry = dict(entry)
updated_entry["hooks"] = filtered_commands
filtered_entries.append(updated_entry)
if changed:
if filtered_entries:
hooks["PreToolUse"] = filtered_entries
else:
hooks.pop("PreToolUse", None)
if hooks:
data["hooks"] = hooks
else:
data.pop("hooks", None)
path.write_text(json.dumps(data, indent=2) + "\n")
PY
else
manage_settings_hook PreToolUse Bash "rtk hook claude" remove
fi
if bashio::config.true 'install_caveman'; then
@@ -631,10 +560,5 @@ else
find "$HOME/.claude" -maxdepth 4 -iname '*caveman*' -exec rm -rf {} + 2> /dev/null || true
fi
# Startup configuration runs as root, while Claude Desktop runs as abc. Return managed
# persistent files to the effective runtime UID/GID after all writes complete.
for managed_path in "$HOME/.claude" "$HOME/.claude.json" "$HOME/.config/Claude"; do
if [ -e "$managed_path" ]; then
chown -R -- "${RUNTIME_UID}:${RUNTIME_GID}" "$managed_path" || bashio::log.warning "Unable to set ownership on $managed_path"
fi
done
# Ownership of everything written above is reconciled by 84-claude_runtime_ownership.sh after
# the remaining Claude configuration scripts have run.

View File

@@ -3,31 +3,31 @@
set -e
set -o pipefail
# 20-folders.sh already remapped abc to the effective runtime identity (never root in bypass
# mode), so follow abc instead of re-reading the raw PUID/PGID options here.
RUNTIME_UID="$(id -u abc)"
RUNTIME_GID="$(id -g abc)"
PERMISSION_MODE="$(bashio::config 'permission_mode')"
SETTINGS_PATH="$HOME/.claude/settings.json"
STATE_PATH="$HOME/.claude/.addon-permission-mode.json"
case "$PERMISSION_MODE" in
strict|auto|bypass) ;;
strict | auto | bypass) ;;
*)
bashio::log.warning "Unknown permission_mode '${PERMISSION_MODE}'; falling back to strict"
PERMISSION_MODE="strict"
;;
esac
# Managed-value semantics, matching the ANTHROPIC_BASE_URL handling in 82-claude_tools.sh:
# auto/bypass set permissions.defaultMode to the add-on-managed value, and strict removes it
# only while it still holds one of those managed values — a defaultMode the user set by hand
# is never deleted. Ownership of the written file is reconciled by 84-claude_runtime_ownership.sh.
mkdir -p "$(dirname "$SETTINGS_PATH")"
PERMISSION_MODE="$PERMISSION_MODE" SETTINGS_PATH="$SETTINGS_PATH" STATE_PATH="$STATE_PATH" python3 - <<'PY'
PERMISSION_MODE="$PERMISSION_MODE" SETTINGS_PATH="$SETTINGS_PATH" python3 - <<'PY'
import json
import os
from pathlib import Path
MANAGED_VALUES = {"auto", "bypassPermissions"}
mode = os.environ["PERMISSION_MODE"]
settings_path = Path(os.environ["SETTINGS_PATH"])
state_path = Path(os.environ["STATE_PATH"])
try:
settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}
@@ -38,33 +38,14 @@ except (OSError, json.JSONDecodeError):
if not isinstance(settings, dict):
settings = {}
try:
state = json.loads(state_path.read_text()) if state_path.exists() else None
except (OSError, json.JSONDecodeError):
state = None
if not isinstance(state, dict):
state = None
permissions = settings.get("permissions")
if not isinstance(permissions, dict):
permissions = {}
if mode == "strict":
# Restore the value that existed before the add-on first managed this setting.
if state is not None:
if state.get("previous_exists"):
permissions["defaultMode"] = state.get("previous_value")
else:
permissions.pop("defaultMode", None)
state_path.unlink(missing_ok=True)
if permissions.get("defaultMode") in MANAGED_VALUES:
permissions.pop("defaultMode")
else:
if state is None:
state = {
"previous_exists": "defaultMode" in permissions,
"previous_value": permissions.get("defaultMode"),
}
state_path.write_text(json.dumps(state, indent=2) + "\n")
state_path.chmod(0o600)
permissions["defaultMode"] = "auto" if mode == "auto" else "bypassPermissions"
if permissions:
@@ -76,6 +57,9 @@ settings_path.write_text(json.dumps(settings, indent=2) + "\n")
settings_path.chmod(0o600)
PY
# Drop the state file older add-on versions used to remember the pre-add-on defaultMode.
rm -f "$HOME/.claude/.addon-permission-mode.json"
case "$PERMISSION_MODE" in
strict)
bashio::log.info "Claude Code permission mode: strict (normal prompts)"
@@ -87,8 +71,3 @@ case "$PERMISSION_MODE" in
bashio::log.warning "Claude Code permission mode: bypass (permission checks disabled for mounted data and available tools)"
;;
esac
chown -- "${RUNTIME_UID}:${RUNTIME_GID}" "$SETTINGS_PATH" 2> /dev/null || true
if [ -e "$STATE_PATH" ]; then
chown -- "${RUNTIME_UID}:${RUNTIME_GID}" "$STATE_PATH" 2> /dev/null || true
fi

View File

@@ -56,7 +56,6 @@ else:
print(f"permissions.defaultMode: {permissions.get('defaultMode', '<upstream default>')}")
else:
print("permissions: INVALID")
print(f"managed-state marker: {(Path.home() / '.claude/.addon-permission-mode.json').exists()}")
PY
section "MCP registrations (environment values redacted)"
@@ -149,6 +148,9 @@ section "TokenSave"
if bashio::config.true 'install_tokensave'; then
tokensave doctor --agent claude || true
tokensave gain --all --range 30d || true
# Capture before looping — see the matching comment in 82-claude_tools.sh: feeding the
# loop straight from `< <(bashio::config ...)` yields an empty list under errexit.
TOKENSAVE_PROJECT_PATHS="$(bashio::config 'tokensave_project_paths')"
while IFS= read -r configured_path || [ -n "$configured_path" ]; do
if [ -z "$configured_path" ] || [ "$configured_path" = "null" ]; then
continue
@@ -161,7 +163,7 @@ if bashio::config.true 'install_tokensave'; then
else
echo "${repo_root}: NOT INITIALIZED"
fi
done < <(bashio::config 'tokensave_project_paths')
done <<< "$TOKENSAVE_PROJECT_PATHS"
else
echo "disabled"
fi

View File

@@ -1,20 +1,60 @@
- Added support for configuring extra environment variables via the `env_vars` add-on option alongside config.yaml. See https://github.com/alexbelgium/hassio-addons/wiki/Add-Environment-variables-to-your-Addon-2 for details.
## 2.0.1 (2026-07-17)
- Aligned the pull-request build context with the production builder by copying
the shared Home Assistant helper scripts before building the add-on.
- Fixed aarch64 and amd64 PR validation failing on unresolved Dockerfile
`COPY` instructions. Runtime and migration behavior are unchanged.
## 2.0.0 (2026-07-17)
- Replaced the abandoned `vogler/free-games-claimer` upstream with
`P-Adamiec/Free-Games-Claimer-Remaster`.
- Reworked the image build for the remaster's Python, Chromium, TurboVNC, and
noVNC runtime on both amd64 and aarch64.
- Preserved the previous default one-shot behavior and Epic, Prime Gaming, and
GOG store selection.
- Kept noVNC on port 6080 for upgrade compatibility.
- Added `RUN_ONCE` and `STORES` options while retaining `CMD_ARGUMENTS` as a
deprecated compatibility input.
- Added an automatic, idempotent migration of legacy Epic, Prime Gaming, and
GOG JSON claim history into the remaster SQLite database.
- Preserved legacy files for rollback and documented the required one-time
Chromium login when a Firefox session cannot be migrated.
- Pinned the reviewed upstream source commit and paused generic automatic
updates so the add-on's independent `2.x` version cannot regress to `1.x`.
- Updated the configuration template, upstream metadata, and documentation.
- Added support for configuring extra environment variables via the `env_vars`
add-on option.
## 1.8 (2025-05-17)
- Update to latest version from vogler/free-games-claimer (changelog : https://github.com/vogler/free-games-claimer/releases)
- Update to latest version from vogler/free-games-claimer (changelog: https://github.com/vogler/free-games-claimer/releases)
## 1.7 (2025-03-08)
- Update to latest version from vogler/free-games-claimer (changelog : https://github.com/vogler/free-games-claimer/releases)
- Update to latest version from vogler/free-games-claimer (changelog: https://github.com/vogler/free-games-claimer/releases)
## 1.6-6 (2024-12-29)
- Minor bugs fixed
## 1.6-5 (2024-12-13)
- Minor bugs fixed
## 1.6-4 (2024-12-07)
- ⚠ MAJOR CHANGE : switch to the new config logic from homeassistant. Your configuration files will have migrated from /config/hassio_addons/free_games_claimer in a folder only accessible from my Filebrowser addon called /addon_configs/db21ed7f_free_games_claimer. This avoids the addon to mess with your homeassistant configuration folder, and allows to backup the options. For more information, see here : https://developers.home-assistant.io/blog/2023/11/06/public-addon-config/
- Major change: switch to the new Home Assistant add-on configuration logic.
Configuration files were migrated from
`/config/hassio_addons/free_games_claimer` to the private add-on configuration
directory available through compatible file browser add-ons.
## 1.6-3 (2024-12-05)
- Minor bugs fixed
## 1.6-2 (2024-12-05)
- Minor bugs fixed
## 1.6 (2023-12-30)
@@ -28,18 +68,23 @@
## 1.4 (2023-05-27)
- Update to latest version from vogler/free-games-claimer
## 1.4-5 (2023-05-26)
- Minor bugs fixed
## 1.4-4 (2023-05-26)
- Minor bugs fixed
## 1.4-3 (2023-05-26)
- Minor bugs fixed
## 1.4-2 (2023-05-25)
- Minor bugs fixed
## NOT_WORKING (2023-05-22)
- Minor bugs fixed

View File

@@ -1,91 +1,14 @@
#============================#
# ALEXBELGIUM'S DOCKERFILE #
#============================#
# _.------.
# _.-` ('>.-`"""-.
# '.--'` _'` _ .--.)
# -' '-.-';` `
# ' - _.' ``'--.
# '---` .-'""`
# /`
#=== Home Assistant Addon ===#
#=== Home Assistant Add-on ===#
#################
# 1 Build Image #
#################
ARG BUILD_FROM
ARG BUILD_VERSION
ARG BUILD_FROM="debian:bookworm-slim"
FROM ${BUILD_FROM}
##################
# 2 Modify Image #
##################
# Set S6 wait time
ENV S6_CMD_WAIT_FOR_SERVICES=1 \
S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0 \
S6_SERVICES_GRACETIME=0
##################
# 3 Install apps #
##################
# Add rootfs
COPY rootfs/ /
RUN find . -type f \( -name "*.sh" -o -name "run" -o -name "finish" \) -print -exec chmod +x {} \;
# Uses /bin for compatibility purposes
# hadolint ignore=DL4005
RUN if [ ! -f /bin/sh ] && [ -f /usr/bin/sh ]; then ln -s /usr/bin/sh /bin/sh; fi && \
if [ ! -f /bin/bash ] && [ -f /usr/bin/bash ]; then ln -s /usr/bin/bash /bin/bash; fi
# Modules
ARG MODULES="00-banner.sh 01-custom_script.sh"
# Automatic modules download
COPY ha_automodules.sh /ha_automodules.sh
RUN chmod 744 /ha_automodules.sh && /ha_automodules.sh "$MODULES" && rm /ha_automodules.sh
# Manual apps
ENV PACKAGES=""
# Automatic apps & bashio
COPY ha_autoapps.sh /ha_autoapps.sh
RUN chmod 744 /ha_autoapps.sh && /ha_autoapps.sh "$PACKAGES" && rm /ha_autoapps.sh
################
# 4 Entrypoint #
################
# Add entrypoint
ENV S6_STAGE2_HOOK=/ha_entrypoint.sh
COPY ha_entrypoint.sh /ha_entrypoint.sh
RUN chmod 777 /ha_entrypoint.sh
# Install bashio
COPY bashio-standalone.sh /usr/local/lib/bashio-standalone.sh
RUN chmod 0755 /usr/local/lib/bashio-standalone.sh
RUN \
# Change data folder
sed -i "s|/fgc|/data|g" /usr/local/bin/docker-entrypoint.sh && \
# Run scripts only once
sed -i "1a if [ -f /done ]; then exit 0; fi && touch /done" /ha_entrypoint.sh && \
sed -i "s=x11vnc=[[ \"\$(ps aux | grep \"x11vnc\" | grep -v grep)\" ]] || x11vnc=g" /usr/local/bin/docker-entrypoint.sh && \
# Update playwright
npx playwright install-deps && \
npx playwright install
WORKDIR /data
ENTRYPOINT [ "/usr/bin/env" ]
CMD [ "/ha_entrypoint.sh" ]
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
############
# 5 Labels #
############
ARG DEBIAN_FRONTEND="noninteractive"
ARG BUILD_ARCH
ARG BUILD_DATE
ARG BUILD_DESCRIPTION
@@ -93,28 +16,143 @@ ARG BUILD_NAME
ARG BUILD_REF
ARG BUILD_REPOSITORY
ARG BUILD_VERSION
ENV BUILD_VERSION="${BUILD_VERSION}"
ARG UPSTREAM_REPOSITORY="P-Adamiec/Free-Games-Claimer-Remaster"
ARG UPSTREAM_REF="cca4992354215cef8807b748575af797606627f4"
ENV S6_CMD_WAIT_FOR_SERVICES="1" \
S6_CMD_WAIT_FOR_SERVICES_MAXTIME="0" \
S6_SERVICES_GRACETIME="0" \
VNC_PORT="5900" \
NOVNC_PORT="6080" \
WIDTH="1280" \
HEIGHT="720" \
DEPTH="24" \
SHOW="1" \
COMMIT="${UPSTREAM_REF}" \
BRANCH="main" \
NOW="${BUILD_DATE}"
# Install the dependencies used by Free Games Claimer Remaster. The upstream
# Dockerfile supports both amd64 (Google Chrome) and arm64 (Chromium), so the
# add-on keeps its existing multi-architecture support.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
dos2unix \
gnupg \
gzip \
jq \
python3 \
python3-pip \
tar \
tini \
&& mkdir -p /etc/apt/keyrings \
&& curl --proto "=https" --tlsv1.2 -fsSL https://packagecloud.io/dcommander/virtualgl/gpgkey \
| gpg --dearmor -o /etc/apt/trusted.gpg.d/VirtualGL.gpg \
&& curl --proto "=https" --tlsv1.2 -fsSL https://packagecloud.io/dcommander/turbovnc/gpgkey \
| gpg --dearmor -o /etc/apt/trusted.gpg.d/TurboVNC.gpg \
&& curl --proto "=https" --tlsv1.2 -fsSL https://raw.githubusercontent.com/VirtualGL/repo/main/VirtualGL.list \
> /etc/apt/sources.list.d/VirtualGL.list \
&& curl --proto "=https" --tlsv1.2 -fsSL https://raw.githubusercontent.com/TurboVNC/repo/main/TurboVNC.list \
> /etc/apt/sources.list.d/TurboVNC.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
novnc \
ratpoison \
turbovnc \
virtualgl \
websockify \
libasound2 \
libatk-bridge2.0-0 \
libatk1.0-0 \
libatspi2.0-0 \
libcairo2 \
libcups2 \
libgbm1 \
libnspr4 \
libnss3 \
libpango-1.0-0 \
libxcomposite1 \
libxdamage1 \
libxfixes3 \
libxkbcommon0 \
&& if [ "$(dpkg --print-architecture)" = "amd64" ]; then \
curl -fsSL https://dl.google.com/linux/linux_signing_key.pub \
| gpg --dearmor -o /etc/apt/keyrings/google-chrome.gpg; \
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/google-chrome.gpg] https://dl.google.com/linux/chrome/deb/ stable main" \
> /etc/apt/sources.list.d/google-chrome.list; \
apt-get update; \
apt-get install -y --no-install-recommends google-chrome-stable; \
else \
apt-get install -y --no-install-recommends chromium; \
fi \
&& ln -sf /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html \
&& ln -sf /usr/bin/python3 /usr/bin/python \
&& apt-get purge -y gnupg \
&& apt-get autoremove -y \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /var/cache/* /var/tmp/* /tmp/* /usr/share/doc/*
# Install a deterministic snapshot of the replacement upstream. Updating the
# upstream reference is intentionally explicit so image contents cannot change
# without an add-on version bump.
WORKDIR /fgc
RUN curl --proto "=https" --tlsv1.2 -fsSL \
"https://github.com/${UPSTREAM_REPOSITORY}/archive/${UPSTREAM_REF}.tar.gz" \
-o /tmp/free-games-claimer-remaster.tar.gz \
&& tar -xzf /tmp/free-games-claimer-remaster.tar.gz --strip-components=1 -C /fgc \
&& python3 -m pip install --no-cache-dir --break-system-packages -r requirements.txt \
&& dos2unix ./*.sh \
&& chmod +x ./*.sh \
&& cp docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh \
&& chmod 0755 /usr/local/bin/docker-entrypoint.sh \
&& rm -f /tmp/free-games-claimer-remaster.tar.gz \
&& rm -rf /fgc/data \
&& ln -s /data /fgc/data
# Add Home Assistant integration files and shared helper modules.
COPY rootfs/ /
RUN find /etc/cont-init.d /usr/local/bin -type f -name "*.sh" -exec chmod 0755 {} + \
&& chmod 0755 /usr/local/bin/migrate_vogler_data.py
ARG MODULES="00-banner.sh 01-custom_script.sh"
COPY ha_automodules.sh /ha_automodules.sh
RUN chmod 0755 /ha_automodules.sh \
&& /ha_automodules.sh "${MODULES}" \
&& rm /ha_automodules.sh
ENV PACKAGES=""
COPY ha_autoapps.sh /ha_autoapps.sh
RUN chmod 0755 /ha_autoapps.sh \
&& /ha_autoapps.sh "${PACKAGES}" \
&& rm /ha_autoapps.sh
ENV S6_STAGE2_HOOK="/ha_entrypoint.sh"
COPY ha_entrypoint.sh /ha_entrypoint.sh
COPY bashio-standalone.sh /usr/local/lib/bashio-standalone.sh
RUN chmod 0755 /ha_entrypoint.sh /usr/local/lib/bashio-standalone.sh
EXPOSE 5900 6080
ENTRYPOINT ["/usr/bin/env"]
CMD ["/ha_entrypoint.sh"]
LABEL \
io.hass.name="${BUILD_NAME}" \
io.hass.description="${BUILD_DESCRIPTION}" \
io.hass.arch="${BUILD_ARCH}" \
io.hass.type="addon" \
io.hass.version=${BUILD_VERSION} \
io.hass.version="${BUILD_VERSION}" \
maintainer="alexbelgium (https://github.com/alexbelgium)" \
org.opencontainers.image.title="${BUILD_NAME}" \
org.opencontainers.image.description="${BUILD_DESCRIPTION}" \
org.opencontainers.image.vendor="Home Assistant Add-ons" \
org.opencontainers.image.authors="alexbelgium (https://github.com/alexbelgium)" \
org.opencontainers.image.licenses="MIT" \
org.opencontainers.image.url="https://github.com/alexbelgium" \
org.opencontainers.image.licenses="AGPL-3.0" \
org.opencontainers.image.url="https://github.com/${BUILD_REPOSITORY}" \
org.opencontainers.image.source="https://github.com/${BUILD_REPOSITORY}" \
org.opencontainers.image.documentation="https://github.com/${BUILD_REPOSITORY}/blob/main/README.md" \
org.opencontainers.image.created=${BUILD_DATE} \
org.opencontainers.image.revision=${BUILD_REF} \
org.opencontainers.image.version=${BUILD_VERSION}
####################
# 6 HealthcheckNOT #
####################
# Can't be implemented as container is optimized for memory usage, so the webserver and Node are spun down during idle
org.opencontainers.image.documentation="https://github.com/${BUILD_REPOSITORY}/blob/master/free_games_claimer/README.md" \
org.opencontainers.image.created="${BUILD_DATE}" \
org.opencontainers.image.revision="${BUILD_REF}" \
org.opencontainers.image.version="${BUILD_VERSION}" \
io.hass.upstream="https://github.com/${UPSTREAM_REPOSITORY}/tree/${UPSTREAM_REF}"

View File

@@ -1,128 +1,164 @@
## &#9888; VNC not working on several machines. Please use config.env to execute the script
# Home Assistant add-on: Free Games Claimer
# Home assistant add-on: Free Games Claimer
I maintain this and other Home Assistant add-ons in my free time: keeping up with upstream changes, HA changes, and testing on real hardware takes a lot of time (and some money). I use around 5-10 of my >110 addons so regularly I install test machines (and purchase some test services such as vpn) that I don't use myself to troubleshoot and improve the addons
If this add-on saves you time or makes your setup easier, I would be very grateful for your support!
I maintain this and other Home Assistant add-ons in my free time. Keeping up
with upstream changes, Home Assistant changes, and testing on real hardware
takes a significant amount of time.
[![Buy me a coffee][donation-badge]](https://www.buymeacoffee.com/alexbelgium)
[![Donate via PayPal][paypal-badge]](https://www.paypal.com/donate/?hosted_button_id=DZFULJZTP3UQA)
## Addon informations
## Add-on information
![Version](https://img.shields.io/badge/dynamic/yaml?label=Version&query=%24.version&url=https%3A%2F%2Fraw.githubusercontent.com%2Falexbelgium%2Fhassio-addons%2Fmaster%2Ffree_games_claimer%2Fconfig.yaml)
![Ingress](https://img.shields.io/badge/dynamic/yaml?label=Ingress&query=%24.ingress&url=https%3A%2F%2Fraw.githubusercontent.com%2Falexbelgium%2Fhassio-addons%2Fmaster%2Ffree_games_claimer%2Fconfig.yaml)
![Arch](https://img.shields.io/badge/dynamic/yaml?color=success&label=Arch&query=%24.arch&url=https%3A%2F%2Fraw.githubusercontent.com%2Falexbelgium%2Fhassio-addons%2Fmaster%2Ffree_games_claimer%2Fconfig.yaml)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/9c6cf10bdbba45ecb202d7f579b5be0e)](https://www.codacy.com/gh/alexbelgium/hassio-addons/dashboard?utm_source=github.com&utm_medium=referral&utm_content=alexbelgium/hassio-addons&utm_campaign=Badge_Grade)
[![GitHub Super-Linter](https://img.shields.io/github/actions/workflow/status/alexbelgium/hassio-addons/weekly-supelinter.yaml?label=Lint%20code%20base)](https://github.com/alexbelgium/hassio-addons/actions/workflows/weekly-supelinter.yaml)
[![Builder](https://img.shields.io/github/actions/workflow/status/alexbelgium/hassio-addons/onpush_builder.yaml?label=Builder)](https://github.com/alexbelgium/hassio-addons/actions/workflows/onpush_builder.yaml)
[donation-badge]: https://img.shields.io/badge/Buy%20me%20a%20coffee-%23d32f2f?logo=buy-me-a-coffee&style=flat&logoColor=white
[paypal-badge]: https://img.shields.io/badge/Donate%20via%20PayPal-0070BA?logo=paypal&style=flat&logoColor=white
_Thanks to everyone having starred my repo! To star it click on the image below, then it will be on top right. Thanks!_
[![Stargazers repo roster for @alexbelgium/hassio-addons](https://raw.githubusercontent.com/alexbelgium/hassio-addons/master/.github/stars2.svg)](https://github.com/alexbelgium/hassio-addons/stargazers)
![downloads evolution](https://raw.githubusercontent.com/alexbelgium/hassio-addons/master/free_games_claimer/stats.png)
## About
[Free Games Claimer](https://github.com/vogler/free-games-claimer) : Claims free games periodically on
This add-on is based on
[Free Games Claimer Remaster](https://github.com/P-Adamiec/Free-Games-Claimer-Remaster).
It can claim free games from:
- Epic Games Store
- Amazon Prime Gaming
- GOG
- Live Games with Gold - planned
- Steam
- GamerPower-supported stores, when explicitly enabled
This addon is based on the docker image https://github.com/vogler/free-games-claimer
For compatibility with previous add-on releases, the default store selection
remains Epic Games, Prime Gaming, and GOG.
## Configuration
## Web interface
Webui can be found at <http://homeassistant:6080> (NoVNC interface - currently has issues on some machines).
The noVNC interface remains available on port `6080`:
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `CMD_ARGUMENTS` | str | `node epic-games ; node prime-gaming ; node gog` | Commands to run for claiming games |
| `CONFIG_LOCATION` | str | `/config/config.env` | Location of the configuration file |
### Example Configuration
```yaml
CMD_ARGUMENTS: "node epic-games ; node prime-gaming ; node gog"
CONFIG_LOCATION: "/config/config.env"
```text
http://homeassistant:6080
```
### Environment Configuration
It can be used for initial sign-in, CAPTCHA handling, or other manual browser
interaction. Set `VNC_PASSWORD` in `config.env` to protect the VNC session.
All main configuration is done via the `config.env` file located at `/config/addons_config/free_games_claimer/config.env`.
## Add-on options
If this file doesn't exist, it will be created at first boot with default settings.
| Option | Default | Description |
|--------|---------|-------------|
| `CONFIG_LOCATION` | `/config/config.env` | Persistent environment configuration file |
| `RUN_ONCE` | `true` | Run all selected claimers once, then stop the add-on as previous releases did |
| `STORES` | empty | Optional comma-separated override, such as `epic,prime,gog,steam` |
| `CMD_ARGUMENTS` | `node epic-games ; node prime-gaming ; node gog` | Deprecated compatibility option; recognized legacy command names are converted to `STORES` |
| `env_vars` | `[]` | Additional environment variables passed to the add-on |
### Required Environment Variables
### Run modes
Add these to your `config.env` file:
With `RUN_ONCE: true`, the add-on performs one claiming pass and stops. This is
the default and preserves the behavior of the former vogler-based add-on.
With `RUN_ONCE: false`, the remaster remains running and uses its internal
scheduler. Set `SCHEDULER_HOURS` in `config.env` to control the interval.
## Environment configuration
The add-on keeps its configuration in `CONFIG_LOCATION`, which defaults to
`/config/config.env`. From Home Assistant this is stored in the add-on's
private `addon_configs` directory and can be edited with a compatible file
browser add-on.
A template is created on first start. Common examples are:
```env
# Epic Games Store
# Preserve the former default selection
STORES=epic,prime,gog
# Epic Games
EG_EMAIL=your-email@example.com
EG_PASSWORD=your-password
EG_OTPKEY=
# Amazon Prime Gaming
PG_EMAIL=your-amazon-email@example.com
PG_PASSWORD=your-amazon-password
PG_PASSWORD=your-password
PG_OTPKEY=
# GOG (optional)
# GOG
GOG_EMAIL=your-gog-email@example.com
GOG_PASSWORD=your-gog-password
GOG_PASSWORD=your-password
# Notifications (optional)
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
EMAIL_USER=notifications@example.com
EMAIL_PASS=your-app-password
EMAIL_TO=recipient@example.com
# Optional Steam support
STEAM_USERNAME=your-steam-username
STEAM_PASSWORD=your-password
# Optional notifications
NOTIFY=tgram://bot-token/chat-id
# DISCORD_WEBHOOK=https://discord.com/api/webhooks/...
```
### Additional Options
Existing variables such as `EG_EMAIL`, `EG_PASSWORD`, `PG_EMAIL`,
`PG_PASSWORD`, `PG_OTPKEY`, `GOG_EMAIL`, `GOG_PASSWORD`, `SHOW`, `WIDTH`,
`HEIGHT`, `TIMEOUT`, `LOGIN_TIMEOUT`, `DRYRUN`, and `NOTIFY` remain compatible.
See the
[upstream configuration reference](https://github.com/P-Adamiec/Free-Games-Claimer-Remaster#configuration)
for all available settings.
For complete configuration options and advanced settings, see: https://github.com/vogler/free-games-claimer#configuration--options
## Upgrade from version 1.8
### Important Notes
Version 2.0 changes the application engine from
`vogler/free-games-claimer` (Node.js, Playwright, and Firefox) to
`P-Adamiec/Free-Games-Claimer-Remaster` (Python, nodriver, and Chromium).
The add-on performs the following migration automatically on first start:
- **VNC Issues**: The NoVNC web interface is currently not working reliably on several machines
- **Recommended**: Use the `config.env` file for configuration instead of the web interface
- **Security**: Store credentials securely and consider using app-specific passwords where available
1. The existing `config.env` remains at the same configured location.
2. Legacy `epic-games.json`, `prime-gaming.json`, and `gog.json` claim history
is imported into the remaster SQLite database at `/data/fgc.db`.
3. Existing database rows are detected and are not duplicated if migration is
retried.
4. A pre-migration database backup is created when an existing `fgc.db` is
present.
5. All old files remain under `/data/data` for rollback or manual recovery.
### Custom Scripts and Environment Variables
Browser sessions cannot be converted because the old add-on used a shared
Firefox profile while the remaster uses separate Chromium profiles per store.
Credentials remain available through `config.env`, but accounts that require
interactive authentication may need a one-time login through noVNC after the
upgrade. The old Firefox profile is retained and is never deleted.
This addon supports custom scripts and environment variables through the `addon_config` mapping:
The external noVNC port remains `6080`, although the standalone remaster image
normally uses port `7080`.
- **Custom scripts**: See [Running Custom Scripts in Addons](https://github.com/alexbelgium/hassio-addons/wiki/Running-custom-scripts-in-Addons)
- **env_vars option**: Use the add-on `env_vars` option to pass extra environment variables (uppercase or lowercase names). See https://github.com/alexbelgium/hassio-addons/wiki/Add-Environment-variables-to-your-Addon-2 for details.
## Upstream update policy
The image is built from an explicit upstream commit in the Dockerfile. This
keeps amd64 and aarch64 images reproducible and prevents an upstream branch or
container tag from changing without an add-on review and version bump.
The repository updater is intentionally paused for this add-on because the
add-on uses its own `2.x` version series while the replacement upstream uses a
`1.x` version series. An automatic replacement would risk a Home Assistant
version regression and would not safely update the pinned commit. A maintainer
upstream update must therefore update `UPSTREAM_REF`, `upstream_version`, the
add-on version, and `CHANGELOG.md` together.
## Installation
The installation of this add-on is pretty straightforward and not different in comparison to installing any other add-on.
1. Add this add-on repository to the Home Assistant add-on store.
2. Install **Free Games Claimer**.
3. Configure the add-on options as needed.
4. Start the add-on and review its log.
5. Open noVNC if an account needs manual authentication.
1. Add my add-ons repository to your home assistant instance (in supervisor addons store at top right, or click button below if you have configured my HA)
[![Open your Home Assistant instance and show the add add-on repository dialog with a specific repository URL pre-filled.](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https%3A%2F%2Fgithub.com%2Falexbelgium%2Fhassio-addons)
1. Install this add-on.
1. Click the `Save` button to store your configuration.
1. Set the add-on options to your preferences
1. Start the add-on.
1. Check the logs of the add-on to see if everything went well.
1. Open the webUI and adapt the software options
[![Open your Home Assistant instance and show the add add-on repository dialog with a specific repository URL pre-filled.](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https%3A%2F%2Fgithub.com%2Falexbelgium%2Fhassio-addons)
## Custom scripts and environment variables
- [Running custom scripts in add-ons](https://github.com/alexbelgium/hassio-addons/wiki/Running-custom-scripts-in-Addons)
- [Passing environment variables to an add-on](https://github.com/alexbelgium/hassio-addons/wiki/Add-Environment-variables-to-your-Addon-2)
## Support
Create an issue on github
[repository]: https://github.com/alexbelgium/hassio-addons
Open an issue in the
[add-on repository](https://github.com/alexbelgium/hassio-addons/issues).

View File

@@ -1,6 +1,6 @@
{
"build_from": {
"aarch64": "ghcr.io/vogler/free-games-claimer:latest",
"amd64": "ghcr.io/vogler/free-games-claimer:latest"
"aarch64": "debian:bookworm-slim",
"amd64": "debian:bookworm-slim"
}
}

View File

@@ -1,9 +1,8 @@
# Free Games Claimer Remaster
arch:
- aarch64
- amd64
description:
automatically claims free games on the Epic Games Store, Amazon Prime
Gaming and GOG
description: "Automatically claims free games from Epic Games Store, Amazon Prime Gaming, GOG, Steam, and optional GamerPower-supported stores"
devices:
- /dev/dri
- /dev/dri/card0
@@ -73,25 +72,29 @@ init: false
map:
- addon_config:rw
- homeassistant_config:rw
name: Free Games Claimer (NoVNC not working)
name: Free Games Claimer
options:
env_vars: []
CMD_ARGUMENTS: node epic-games ; node prime-gaming ; node gog
STORES: ""
RUN_ONCE: true
CONFIG_LOCATION: /config/config.env
ports:
5900/tcp: null
6080/tcp: 6080
ports_description:
5900/tcp: VNC port
6080/tcp: NOVNC port
6080/tcp: noVNC web interface
schema:
env_vars:
- name: match(^[A-Za-z0-9_]+$)
value: str?
CMD_ARGUMENTS: str
CMD_ARGUMENTS: str?
STORES: str?
RUN_ONCE: bool
CONFIG_LOCATION: str
slug: free_games_claimer
udev: true
url: https://github.com/alexbelgium/hassio-addons
version: "1.8"
version: "2.0.1"
webui: "[PROTO:ssl]://[HOST]:[PORT:6080]"

View File

@@ -1,85 +1,152 @@
#!/usr/bin/env bashio
# shellcheck shell=bash
set -e
set -eo pipefail
##############
# Initialize #
##############
CONFIG_FILE="/config/config.env"
if bashio::config.has_value 'CONFIG_LOCATION'; then
CONFIG_FILE="$(bashio::config 'CONFIG_LOCATION')"
fi
CONFIG_DIR="$(dirname "${CONFIG_FILE}")"
RUNTIME_CONFIG="/data/config.env"
CONFIG_HOME="$(bashio::config "CONFIG_LOCATION")"
CONFIG_HOME="$(dirname "$CONFIG_HOME")"
mkdir -p "${CONFIG_DIR}" /data
# Use new config file
if [ ! -f "$CONFIG_HOME/config.env" ]; then
# Copy default config.env
cp /templates/config.env "$CONFIG_HOME/"
chmod 755 "$CONFIG_HOME/config.env"
bashio::log.warning "A default config.env file was copied to $CONFIG_HOME. Please customize according to https://github.com/vogler/free-games-claimer/tree/main#configuration--options and restart the add-on"
# Recover from an old add-on bug that could create config.env as a directory.
if [ -d "${CONFIG_FILE}" ]; then
bashio::log.warning "Found a directory at ${CONFIG_FILE}; replacing it with a configuration file"
rm -rf "${CONFIG_FILE}"
fi
if [ ! -f "${CONFIG_FILE}" ]; then
install -m 0600 /templates/config.env "${CONFIG_FILE}"
bashio::log.warning \
"Created ${CONFIG_FILE}. Add account credentials there and restart the add-on if automatic login is required."
else
bashio::log.info "Using existing config.env file in $CONFIG_HOME. Please customize according to https://github.com/vogler/free-games-claimer/tree/main#configuration--options and restart the add-on"
bashio::log.info "Using configuration from ${CONFIG_FILE}"
fi
# Remove erroneous folder named config.env (bug fix for looping issue)
if [ -d "$CONFIG_HOME/config.env" ]; then
bashio::log.warning "Found directory named config.env, deleting it..."
rm -rf "$CONFIG_HOME/config.env" # Fix: Ensures directory removal even if it exists
cp /templates/config.env "$CONFIG_HOME/config.env" # Recreate as a valid file
chmod 755 "$CONFIG_HOME/config.env"
fi
# The remaster reads /fgc/data/config.env. /fgc/data is linked to Home
# Assistant's persistent /data volume by the Dockerfile.
install -m 0600 "${CONFIG_FILE}" "${RUNTIME_CONFIG}"
sed -i 's/\r$//' "${RUNTIME_CONFIG}"
# Copy new file
mkdir -p /data/data
cp "$CONFIG_HOME/config.env" /data/data/
# Permissions
chmod -R 755 "$CONFIG_HOME"
# Export variables
# Export values needed by the VNC entrypoint as well as by the Python app.
set -a
echo ""
bashio::log.info "Sourcing variables from $CONFIG_HOME/config.env"
cp "$CONFIG_HOME"/config.env /config.env
# Remove previous instance
sed -i "s|export ||g" /config.env
# Add export for non empty lines
sed -i '/\S/s/^/export /' /config.env
# Delete lines starting with #
sed -i '/export #/d' /config.env
# Get variables
# shellcheck source=/dev/null
source /config.env
rm /config.env
source "${RUNTIME_CONFIG}"
set +a
##############
# Launch App #
##############
# The Home Assistant port mapping is intentionally kept at 6080 for a seamless
# upgrade from the previous add-on, even though the new upstream defaults to 7080.
if [ -n "${NOVNC_PORT:-}" ] && [ "${NOVNC_PORT}" != "6080" ]; then
bashio::log.warning "NOVNC_PORT=${NOVNC_PORT} is not supported by the add-on port mapping; using 6080"
fi
export NOVNC_PORT="6080"
export VNC_PORT="5900"
# Go to folder
cd /data || true
# Absolute paths from the former image pointed to its Firefox profile. The
# replacement uses Chromium profiles and must start with a separate directory.
if [ "${BROWSER_DIR:-}" = "/data/data/browser" ]; then
bashio::log.warning "Remapping legacy Firefox BROWSER_DIR to the remaster Chromium profile directory"
export BROWSER_DIR="data/browser"
fi
if [ "${SCREENSHOTS_DIR:-}" = "/data/data/screenshots" ]; then
export SCREENSHOTS_DIR="/fgc/data/screenshots"
fi
# Fetch commands
CMD_ARGUMENTS="$(bashio::config "CMD_ARGUMENTS")"
IFS=';'
read -ar strarr <<< "$CMD_ARGUMENTS"
append_store() {
local store="${1}"
local current="${2}"
# Sanitizes commands
trim() {
local var="$*"
var="${var#"${var%%[![:space:]]*}"}"
var="${var%"${var##*[![:space:]]}"}"
printf '%s' "$var"
if [[ ",${current}," == *",${store},"* ]]; then
printf '%s' "${current}"
elif [ -n "${current}" ]; then
printf '%s,%s' "${current}" "${store}"
else
printf '%s' "${store}"
fi
}
# Add docker-entrypoint command
for val in "${strarr[@]}"; do
val="$(trim "$val")"
echo " "
bashio::log.info "Starting the app with arguments \"$val\""
echo " "
echo "$val" | xargs docker-entrypoint.sh || true
done
legacy_commands_to_stores() {
local commands="${1}"
local selected=""
local command=""
local normalized=""
local command_list=()
bashio::log.info "All actions concluded. Stopping in 10 seconds."
sleep 10
bashio::addon.stop
IFS=';' read -ra command_list <<< "${commands}"
for command in "${command_list[@]}"; do
normalized="${command,,}"
case "${normalized}" in
*epic-games*|*epicgames*|*" epic"*|epic*)
selected="$(append_store "epic" "${selected}")"
;;
*prime-gaming*|*primegaming*|*" prime"*|prime*|*" amazon"*|amazon*)
selected="$(append_store "prime" "${selected}")"
;;
*steam-games*|*" steam"*|steam*)
selected="$(append_store "steam" "${selected}")"
;;
*gamerpower*)
selected="$(append_store "gamerpower" "${selected}")"
;;
*" gog"*|gog*)
selected="$(append_store "gog" "${selected}")"
;;
esac
done
printf '%s' "${selected}"
}
# A non-empty STORES add-on option takes priority. Otherwise retain a STORES
# value from config.env, then fall back to translating the legacy commands.
STORES_OPTION=""
if bashio::config.has_value 'STORES'; then
STORES_OPTION="$(bashio::config 'STORES')"
fi
if [ -n "${STORES_OPTION}" ]; then
export STORES="${STORES_OPTION}"
elif [ -z "${STORES:-}" ]; then
CMD_ARGUMENTS=""
if bashio::config.has_value 'CMD_ARGUMENTS'; then
CMD_ARGUMENTS="$(bashio::config 'CMD_ARGUMENTS')"
fi
STORES="$(legacy_commands_to_stores "${CMD_ARGUMENTS}")"
export STORES="${STORES:-epic,prime,gog}"
fi
bashio::log.info "Enabled stores: ${STORES:-epic,prime,gog}"
# Import claim history from vogler/free-games-claimer once. Legacy files and
# browser data are retained under /data/data for rollback and manual recovery.
/usr/local/bin/migrate_vogler_data.py
APP_COMMAND=(python3 /fgc/main.py)
RUN_ONCE="true"
if bashio::config.has_value 'RUN_ONCE' && ! bashio::config.true 'RUN_ONCE'; then
RUN_ONCE="false"
fi
if [ "${RUN_ONCE}" = "true" ]; then
APP_COMMAND+=(--once)
bashio::log.info "Starting a single claiming run (legacy-compatible mode)"
set +e
/usr/local/bin/docker-entrypoint.sh "${APP_COMMAND[@]}"
exit_code=$?
set -e
if [ "${exit_code}" -ne 0 ]; then
bashio::log.error "Free Games Claimer exited with status ${exit_code}"
else
bashio::log.info "Claiming run completed"
fi
bashio::log.info "Stopping the add-on"
sleep 2
bashio::addon.stop
exit "${exit_code}"
fi
bashio::log.info "Starting the built-in scheduler"
exec /usr/local/bin/docker-entrypoint.sh "${APP_COMMAND[@]}"

View File

@@ -1,7 +1,39 @@
HEIGHT=1280
LOGIN_TIMEOUT=180
NOTIFY_TITLE='Free Games Claimer'
# List of environment variables, see : https://github.com/vogler/free-games-claimer#configuration--options
# Free Games Claimer Remaster configuration
# Complete option reference:
# https://github.com/P-Adamiec/Free-Games-Claimer-Remaster#configuration
# Browser and noVNC
SHOW=1
TIMEOUT=60
WIDTH=1280
HEIGHT=720
TIMEOUT=60
LOGIN_TIMEOUT=180
VNC_LOGIN_TIMEOUT=180
NOVNC_PORT=6080
# Keep the previous add-on's default stores. Add steam or gamerpower if wanted.
STORES=epic,prime,gog
# Used only when RUN_ONCE is disabled in the add-on options.
SCHEDULER_HOURS=12
# Common credentials can be used as fallbacks for all stores.
# EMAIL=
# PASSWORD=
# Store-specific credentials take priority over EMAIL/PASSWORD.
# EG_EMAIL=
# EG_PASSWORD=
# EG_OTPKEY=
# EG_PARENTALPIN=
# PG_EMAIL=
# PG_PASSWORD=
# PG_OTPKEY=
# GOG_EMAIL=
# GOG_PASSWORD=
# STEAM_USERNAME=
# STEAM_PASSWORD=
# Notifications (Apprise or Discord)
# NOTIFY=
# DISCORD_WEBHOOK=

View File

@@ -0,0 +1,248 @@
#!/usr/bin/env python3
"""Migrate legacy vogler/free-games-claimer JSON history to the remaster DB."""
from __future__ import annotations
import json
import os
import shutil
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator
DATA_DIR = Path(os.environ.get("FGC_DATA_DIR", "/data"))
LEGACY_DIR = DATA_DIR / "data"
DATABASE = DATA_DIR / "fgc.db"
MARKER = DATA_DIR / ".vogler-remaster-migrated-v1.json"
BACKUP = DATA_DIR / "fgc.db.pre-vogler-migration"
SOURCES = {
"epic": "epic-games.json",
"prime": "prime-gaming.json",
"gog": "gog.json",
}
def log(message: str) -> None:
print(f"[legacy migration] {message}", flush=True)
def locate_source(filename: str) -> Path | None:
"""Prefer the old nested data directory, with a root fallback."""
for candidate in (LEGACY_DIR / filename, DATA_DIR / filename):
if candidate.is_file():
return candidate
return None
def normalize_timestamp(value: Any) -> str:
if isinstance(value, str) and value.strip():
raw = value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(raw)
if parsed.tzinfo is not None:
parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
return parsed.isoformat(sep=" ", timespec="seconds")
except ValueError:
pass
return datetime.now(timezone.utc).replace(tzinfo=None).isoformat(
sep=" ", timespec="seconds"
)
def clean(value: Any, *, default: str = "", limit: int | None = None) -> str:
result = default if value is None else str(value)
if limit is not None:
result = result[:limit]
return result
def iter_records(store: str, payload: Any, source: Path) -> Iterator[dict[str, Any]]:
if not isinstance(payload, dict):
raise ValueError(f"{source} does not contain a JSON object")
for user, games in payload.items():
if not isinstance(games, dict):
continue
for legacy_id, value in games.items():
record = value if isinstance(value, dict) else {}
title = clean(record.get("title"), default=clean(legacy_id), limit=512)
game_id = clean(legacy_id, default=title, limit=256)
if not game_id:
game_id = title[:256] or "unknown"
legacy_store = record.get("store")
extra = {
"migration_source": str(source),
"legacy_store": legacy_store,
"legacy_time": record.get("time") or record.get("timestamp"),
}
extra = {key: val for key, val in extra.items() if val not in (None, "")}
yield {
"store": store,
"user": clean(user, default="unknown", limit=128) or "unknown",
"game_id": game_id,
"title": title or game_id,
"url": clean(record.get("url"), limit=None) or None,
"status": clean(record.get("status"), default="unknown", limit=64)
or "unknown",
"code": clean(record.get("code"), limit=128) or None,
"extra": json.dumps(extra, ensure_ascii=False) if extra else None,
"created_at": normalize_timestamp(
record.get("time") or record.get("timestamp")
),
}
def ensure_schema(connection: sqlite3.Connection) -> None:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS claimed_games (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
store VARCHAR(32) NOT NULL,
user VARCHAR(128) NOT NULL,
game_id VARCHAR(256) NOT NULL,
title VARCHAR(512) NOT NULL,
url TEXT,
status VARCHAR(64) NOT NULL DEFAULT 'unknown',
code VARCHAR(128),
extra TEXT,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS ix_claimed_games_store ON claimed_games (store);
CREATE INDEX IF NOT EXISTS ix_claimed_games_user ON claimed_games (user);
CREATE INDEX IF NOT EXISTS ix_claimed_games_game_id ON claimed_games (game_id);
"""
)
def migrate() -> int:
DATA_DIR.mkdir(parents=True, exist_ok=True)
if MARKER.exists():
log("Legacy claim history was already migrated")
return 0
sources = {
store: source
for store, filename in SOURCES.items()
if (source := locate_source(filename)) is not None
}
legacy_browser = LEGACY_DIR / "browser"
if not sources:
if legacy_browser.exists():
log(
"Legacy Firefox browser data was found but cannot be converted to "
"the remaster Chromium profile; a one-time login may be required"
)
MARKER.write_text(
json.dumps(
{
"migrated_at": datetime.now(timezone.utc).isoformat(),
"imported": 0,
"sources": [],
},
indent=2,
),
encoding="utf-8",
)
log("No legacy claim-history files were found")
return 0
if DATABASE.exists() and not BACKUP.exists():
shutil.copy2(DATABASE, BACKUP)
log(f"Backed up the existing database to {BACKUP}")
imported = 0
skipped = 0
errors: list[str] = []
try:
with sqlite3.connect(DATABASE) as connection:
ensure_schema(connection)
for store, source in sources.items():
try:
payload = json.loads(source.read_text(encoding="utf-8"))
source_imported = 0
for record in iter_records(store, payload, source):
exists = connection.execute(
"""
SELECT 1 FROM claimed_games
WHERE store = ? AND user = ? AND game_id = ?
LIMIT 1
""",
(record["store"], record["user"], record["game_id"]),
).fetchone()
if exists:
skipped += 1
continue
connection.execute(
"""
INSERT INTO claimed_games (
store, user, game_id, title, url, status, code,
extra, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record["store"],
record["user"],
record["game_id"],
record["title"],
record["url"],
record["status"],
record["code"],
record["extra"],
record["created_at"],
record["created_at"],
),
)
imported += 1
source_imported += 1
connection.commit()
log(f"Imported {source_imported} record(s) from {source}")
except (OSError, ValueError, json.JSONDecodeError, sqlite3.Error) as err:
connection.rollback()
message = f"Failed to import {source}: {err}"
errors.append(message)
log(message)
except sqlite3.Error as err:
log(f"Database migration failed: {err}")
return 1
if legacy_browser.exists():
log(
"Legacy Firefox browser data remains in /data/data/browser. It is "
"not compatible with Chromium, so use noVNC for a one-time login if needed."
)
if errors:
log("Migration was incomplete and will be retried on the next start")
return 0
MARKER.write_text(
json.dumps(
{
"migrated_at": datetime.now(timezone.utc).isoformat(),
"imported": imported,
"skipped_existing": skipped,
"sources": [str(path) for path in sources.values()],
},
indent=2,
),
encoding="utf-8",
)
log(f"Migration complete: {imported} imported, {skipped} already present")
return 0
if __name__ == "__main__":
sys.exit(migrate())

View File

@@ -1,10 +1,11 @@
{
"dockerhub_by_date": true,
"dockerhub_by_date": false,
"dockerhub_list_size": 2,
"last_update": "17-05-2025",
"last_update": "17-07-2026",
"paused": true,
"repository": "alexbelgium/hassio-addons",
"slug": "free_games_claimer",
"source": "github",
"upstream_repo": "vogler/free-games-claimer",
"upstream_version": "1.8"
"upstream_repo": "P-Adamiec/Free-Games-Claimer-Remaster",
"upstream_version": "1.1"
}

View File

@@ -1,5 +1,4 @@
## &#9888; Open Issue : [🐛 [qBittorrent] Cant update to 5.2.3 (opened 2026-07-09)](https://github.com/alexbelgium/hassio-addons/issues/2836) by [@tschoehuijs](https://github.com/tschoehuijs)
## &#9888; Open Request : [✨ [REQUEST] transmission, document where torrent files are stored (opened 2026-07-14)](https://github.com/alexbelgium/hassio-addons/issues/2852) by [@bilogic](https://github.com/bilogic)
## &#9888; Open Request : [✨ [REQUEST] qbittorrent (opened 2025-10-11)](https://github.com/alexbelgium/hassio-addons/issues/2139) by [@nyok92](https://github.com/nyok92)
# Hass.io Add-ons: Tor with bridges
[![Donate][donation-badge]](https://www.buymeacoffee.com/alexbelgium)