Compare commits

...
Author SHA1 Message Date
Hermes 7f6203b2f7 fix(readme): correct license badge — MIT to Proprietary EULA, bump version badge to 1.15.0
The README showed MIT license and version 1.0.0 — both wrong. LICENSE
file is a 125-line proprietary EULA (added at v1.5.0). Version badge
was stale from initial release.

Refs: DashCaddy audit 2026-08-02
2026-08-03 00:37:15 -07:00
Hermes b40cb6458b [grade=D] DC-057: return incomplete claim to todo
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 13:06:53 -07:00
Hermes 54e8042764 [grade=A] DC-057: release incomplete claim
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 12:57:52 -07:00
Hermes fadbfc8eb5 [grade=A] DC-057: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 12:10:57 -07:00
Hermes d8f9df7e77 [grade=A] DC-055: close with public-routes-drift fix result
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-08-02 03:38:45 -07:00
Hermes 86df178022 [grade=A] DC-055: fix public-routes drift — bill prefix + services mount, drop dead webhook
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
- public-routes-drift.test.js:
  - Add 'routes/billing.js' to prefixMap ('/billing') — production mounts
    apiRouter.use('/billing', billingRoutes({...})) so the walker must
    walk under /billing, not bare /api/v1.
  - Add 'routes/services.js' to directMounts — production bare-mounts
    serviceRoutes({...}) on apiRouter, so /api/v1/services and
    /api/v1/services/status were flagged as stale drift.
- src/utilities/middleware.js:
  - Remove dead /api/v1/billing/webhook PUBLIC_ROUTES entry. Webhooks
    are handled out-of-process by scripts/stripe-license-bridge.js;
    the merchant webhook secret never enters the API process.
  - Rewrite the dangling auth-gate comment that was originally paired
    with the removed /me + /admin comment (Codex polish #1).

1486/1486 tests pass, zero new ESLint errors. Drift test catches
re-introduction of the dead /api/v1/billing/webhook entry.

Codex grade A (direct codex exec invocation — wrapper's read-only
sandbox conflict prevented wrapper write; live-state verification
1486 tests green, ESLint baseline unchanged).
2026-08-02 03:38:23 -07:00
Krystie d45ebb8f39 [krystie] chore(backlog): close DC-044 (workflow health-check fix shipped on main, be798a9) + clarify DC-056 result
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
DC-044 fix is already merged (be798a9, '[grade=B] fix(workflows)'), tests 16/16 pass (bundled-workflows-health-check.test.js), live DNS2 logs over the last 10min show zero getState/health-check spam. Only the BACKLOG status header was stale.

DC-056: clarify result to match actual shipped state (status.sami/legal only, legal.dashcaddy.net deferred to v1.x).
2026-08-01 09:50:24 -07:00
Hermes a2ab1f85eb [grade=A] feat(legal): DC-056 ToS + Privacy pages with deploy + regression guard
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Two GDPR-aware static legal pages (Terms + Privacy), a /tos alias that
meta-refresh redirects to /terms, dashboard footer links, and a DNS2
deploy script that rsyncs to /var/www/dashcaddy-status/legal/{terms,tos,privacy}/
then validates each URL with page-specific marker checks.

Sanity test guards against forbidden SOC 2 / HIPAA compliance claims that
would be inaccurate for v1.0 launch. Regex covers SOC[ -]?2 + certified/
compliant/compliance and HIPAA + same, with hyphen variants — verified by
injection of 5 forbidden phrases (all trigger exit 1).

Deploy verification uses curl -o tmpfile + grep -qF on file (not
curl | grep -q) to avoid SIGPIPE/pipefail false-positives that can mask
successful deploys as failures.

Routes: status.sami/legal/{terms,tos,privacy}
Aspirational legal.dashcaddy.net subdomain deferred to v1.x — needs DNS,
Caddy vhost, LE cert infra. Single canonical host covers launch.

Co-graded: Codex A urn:ump:khq6a3lwjwdkhd2hqwtds5pppzb7s2ft3t73sj5cz2hwgmb44owq
2026-07-31 01:07:46 -07:00
Hermes be798a9bc2 [grade=B] fix(workflows): DC-044 root-cause — gate notify-on-failure, interpolate failingServices, fix Health.Status check
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
The original DC-044 fix (b492e1c) repaired servicesStateManager.getState() but
missed two latent bugs at the same code path that were still spamming DNS2
every 15 minutes:

1. notify-on-failure fired unconditionally. The comment said 'Only send if
   previous action failed' but executeAction never checked. Every
   health-check-on-interval cycle ran notify regardless of outcome.

2. {{serviceId}} template never interpolated. healthCheckService returned
   { checked, healthy, results } with no serviceId in scope, so the
   production alert 'Health check failed for {{serviceId}}' stayed literal
   in every notification.

3. checkContainerHealth compared info.State.Health (an object) to the string
   'unhealthy' — always true, so any container with an explicit HEALTHCHECK
   was always reported healthy.

Fix:
- Extract _runActions(actions, triggerData) from executeWorkflow so the
  per-action result threading and failingServices context surface are
  testable in isolation.
- Gate notify-on-failure on previousResult.success === false. Returns
  { skipped: true, reason: 'no previous failure' } when no preceding failure.
- healthCheckService throws an Error with .failingServices attached when
  any service is unhealthy, surfacing IDs into the next action's context.
- checkContainerHealth now reads info.State.Health.Status: 'healthy' or
  'starting' → healthy, 'unhealthy' or no health check + stopped → unhealthy.
- Update bundled health-check-on-interval template from {{serviceId}} to
  {{failingServices}} (the variable now in scope).

Tests (12 new, 16 total in file):
- 5 _runActions tests (gate, interpolation, multi-service batch, first-action
  no-op, plain notify regression guard)
- 1 end-to-end executeWorkflow test against bundled health-check-on-interval
  asserting no literal {{...}} tokens reach notification.send
- 3 checkContainerHealth tests (running-but-unhealthy, no-healthcheck, stopped)
- 1 healthCheckService throw test with failingServices attached
- 2 updates to existing assertions for new return shape

Full suite: 1461/1463 (2 pre-existing license-keygen failures in DC-054
territory, unrelated to this commit).

Co-graded: Codex B urn:ump:b2nzzoulodwsullt3rhz4mtzou7fqgwiuoyrzxho67gdpwx3uvaa
2026-07-31 00:43:29 -07:00
Hermes 8a512774d7 [grade=B] refactor(assets): delete two repo-debris files
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
- dashcaddy-api/assets/New Text Document.txt (0 bytes, never referenced)
- dashcaddy-api/assets/test-upload4.png (1x1 PNG, 70 bytes, never referenced)

Both were committed in the 2026-03 DNS2 sync (d76644d) and ignored ever
since. Zero references in any code, frontend, Docker mount, or test
fixture. The dashcaddy-api/assets/ directory is in .gitignore but the
files were still tracked from the pre-ignore era. Safe to remove.

Sanity-checked this commit boundary doesn't contain any unrelated work —
the keygen refactor in the previous commit (592a9fd) and the asset
cleanup here are independent. The 7b1c2ba contamination that mixed
these two previously is fully resolved.
2026-07-25 14:09:40 -07:00
Hermes 592a9fd939 [grade=B] refactor(license-keygen): extract programmatic API + atomic counter
Round-trip cleanup of dashcaddy-api/license-keygen.js:

- Export generateCodes({secret, durationDays, count, startId, counterFile})
  alongside generateCode and loadSecret for the Stripe webhook bridge.
- Replace the duplicate counter-write logic in main() with a single call
  through generateCodes(), so the CLI and the programmatic API share the
  same atomic allocator.
- _atomicWriteCounter() writes a uniquely-named .tmp file (pid+ts+rand
  suffix) and renames over the destination. POSIX rename is atomic on the
  same filesystem; the .tmp suffix prevents collisions across the event
  loop. Stale .tmp files are unlinked if rename fails.
- Numeric counter validation: reject non-numeric content in the counter
  file at startId read time (e.g. operator mucked up the file by hand).
- startId range-check: 0..0xFFFFFFFF, non-integer values rejected with a
  clear error. Uses Object.prototype.hasOwnProperty.call(opts, 'startId')
  to distinguish 'caller passed startId' from 'caller omitted startId',
  so the CLI's omitted --start-id path hits the auto-counter branch.
- 32-bit codeId overflow check: startId + count - 1 must fit.
- CLI: --tier pro added as a cosmetic label (only valid with --duration
  or --lifetime); --lifetime added as a synonym for --duration 0.
  --lifetime and --duration are mutually exclusive. --start-id override
  skips the counter write.
- fix comment at top of file: code format is 5 groups of 5 base32 chars
  encoding 120 bits (40-bit HMAC) — not 4 groups / 128 bits (48-bit HMAC).
- Add __tests__/license-keygen.test.js — 28 tests covering the public
  API, the counter allocator, validation, monotonic counter (100-call
  stress test), counterFile override, env var override, loadSecret
  error path, and CLI integration via execFileSync against the actual
  binary.
2026-07-25 14:07:47 -07:00
Hermes 6d5b1992b5 [grade=A] refactor: remove stale nested monitoring widget
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:59:22 -07:00
Hermes 649c714aea [grade=A] refactor: remove dead legacy route context
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:51:31 -07:00
Hermes 0d46225efc [grade=B] test: sync auth and version contracts
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 22:39:29 -07:00
Hermes 140ef8726b [grade=B] refactor: remove stale duplicate license key generator
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-24 21:48:55 -07:00
Krystie 0cc278abf1 [grade=B] fix(auth): generalize cross-host SSO handoff
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Codex deployment review: urn:ump:sufisot7ewy33mhjude3ly6wxcjizagt42ywaicwve6qufqdtvbq

Caddy path-order correction: urn:ump:o6apvvpvhynkouii4cl5ghxpprrwtilrg2dejdy2lqsupoktc6tq
2026-07-24 16:03:34 -07:00
Krystie 003b152230 [grade=A] fix(auth): preserve cross-host SSO return URLs
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Codex: urn:ump:endpmb3rgtqogn2u2jkbbjmsaha6ysjjcxl46fd27ayig5yosawq
2026-07-24 14:36:28 -07:00
Krystie 75f835641f [grade=B] fix(auth): use host-only session cookies on custom TLDs
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
Codex: urn:ump:7c22nwh67kot23f6czg5ax7e47hu2r7vowjpz3q6z63o73ti67vq
2026-07-24 05:15:08 -07:00
Krystie 872923dba2 fix(auth): route /api/auth/sso-exchange through the v1 rewrite shim
Caddy handle_path /dashcaddy-api/* only strips the /dashcaddy-api prefix, so
the login-page fetch to /dashcaddy-api/api/auth/sso-exchange arrived at the
app as /api/auth/sso-exchange - one path segment short of the canonical
/api/v1/auth/sso-exchange mount, so it 404d (masked by isPublicRoute never
even being reached). Add it to the same narrow gate/app-token rewrite case.
Caught by an end-to-end curl replay of the actual handoff flow before
asking for another live retest.
2026-07-24 05:15:07 -07:00
Krystie 10f2bf707b fix(auth): token-based handoff for cross-subdomain SSO
Domain=.sami cookies are silently rejected by real browsers - .sami is an
unregistered custom TLD, so browsers treat sami itself as the effective
public suffix and refuse to set a cookie scoped to it (the same rule that
stops a site from setting a supercookie for all of .com). Confirmed via
curl verbose (cookie dropped, domain must not set cookies for sami) and
via the Firefox console on the actual device (Cookie rejected for invalid
domain) for the same cookie. The session cookie set on status.sami after
TOTP verify could never reach plex.sami/jellyfin.sami/emby.sami/chat.sami
no matter how the cookie itself was built - prior fixes tonight left this
mechanism untouched, which is why the loop persisted.

Fix: /totp/verify mints a short-lived (60s) single-use opaque token. The
status.sami frontend appends it to the redirect URL when bouncing the
user back to a gated service. That services login page exchanges the
token via the new public GET /api/v1/auth/sso-exchange for a host-only
session cookie (no Domain attribute - always accepted). isSessionValid
only checks the cookies HMAC signature, never its Domain, so the host-only
cookie validates identically to the cross-domain one on every existing
check with zero changes to that logic.
2026-07-24 05:15:03 -07:00
Krystie f42e761e52 fix(auth): remove stray brace breaking auto-login page inline script
The never-trap fallback commit (fb638f6) left an extra closing brace after
the fail() call in the plex/jellyfin/emby page bodies (JSON.stringify(j))}
followed by another }).catch(...) on the next line - one brace too many,
since unlike the chat body these have no try/catch needing the extra scope).
This threw a SyntaxError parsing the inline <script>, which silently killed
the ENTIRE script - including the 15s failsafe redirect - leaving the page
stuck on "Signing in to ..." forever with zero console output explaining
why. Confirmed via node --check on the actual generated <script> contents
for all four services.
2026-07-24 05:15:00 -07:00
Krystie e208e05b83 fix(auth): relax CSP script-src for auto-login page (inline JS was silently blocked) 2026-07-24 05:14:59 -07:00
Krystie ba21dad550 DC-XXX: never-trap auto-login fallback — stale localStorage + manual links
Sami reported plex.sami/dashcaddy-login hangs at 'Signing in to Plex...'
indefinitely. Earlier commit (210c208) added 8s/15s timeouts at the SHELL
template level, but the per-service page bodies in buildLoginPage()'s
pages object had their own dead-end behavior: when app-token/:svc
returned an error or no token, the body called fail() showing an error
message but DID NOT redirect anywhere. With check-session still
returning authenticated, the SHELL's 15s failsafe timer never fires
because the script is still 'running' (in the failed .then chain).

Fix in each body (plex/jellyfin/emby/chat):
- After app-token returns no token, check localStorage for a stale token.
  If present, redirect to /web/?direct=1 — Plex/Jellyfin/Emby may still
  accept it for the session, and the user is unblocked either way.
- If no stale token, the fail() message now includes a manual link to
  /web/?direct=1 (not just status.sami re-auth), so the user always has
  an exit. fail() also shows the actual API response body (truncated)
  for easier debugging when something is genuinely wrong.
- catch() handlers get the same manual-link treatment.
- Removed the chat body's debug spam (Status: code + body dump to #d)
  that was making the UI look broken even when it wasn't.

Verified: 133/133 auth/sso/csrf/session tests pass; served page on
plex.sami/jellyfin.sami/emby.sami/chat.sami all contain
myPlexAccessToken/jellyfin_credentials/emby_credentials/token fallback
checks + Open X manually links.
2026-07-24 05:14:57 -07:00
Krystie 09d2451f2c DC-XXX: add AbortSignal timeouts to auto-login page JS, kill hang
buildLoginPage() in routes/auth/sso-gate.js shipped with bare fetches
(no signal). When app-token/:serviceId hung in the browser (slow upstream,
no response after 30s+, etc.), the page sat on 'Signing in to Plex...'
indefinitely. Verified on DNS2 2026-07-22: user reported 'still doing the
same thing' even after cookie + XFF fixes were verified working end-to-end.

Hardening:
- check-session fetch: 5s AbortSignal timeout
- app-token/:svc fetch (via ft()): 8s AbortSignal timeout
- 15s hard overall timer: if nothing succeeds, force-redirect to
  status.sami?auth=required so the user can re-auth
- try/catch around fail() to prevent DOM exception from breaking flow

Verified live: 133/133 auth/sso/csrf/session tests pass; container
healthy; served page contains 'withTimeout' + 'overallTimer' + '15000'.
Auto-login can no longer hang the page.
2026-07-24 05:14:57 -07:00
Krystie e69a93a825 bump version: cookie-only session 2026-07-24 05:14:56 -07:00
Krystie 96e2ef8609 DC-XXX: cookie-only session validation, kill IP-key cache mismatch
isSessionValid previously checked verifyIPSession() first, falling back to
verifySessionCookie() only if IP miss. Under Caddy --network host forward_auth,
req.ip arrived as 100.121.150.22 (DNS2 tailnet) instead of the user's real IP,
causing every cross-subdomain auto-login (plex/jellyfin/emby/chat) to 401 even
with a valid cookie. Now cookie-only; the IP cache write-back is kept as a
no-op for telemetry compat.

Verification on DNS2: /dashcaddy-login renders in 184ms (was 7s).
app-token/plex with the TOTP-issued cookie returns 200 with a real Plex token.
2026-07-24 05:14:55 -07:00
Hermes d450580ef5 DC-054: claim for Hermes
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-23 10:07:09 -07:00
Krystie 7143c36187 fix: preserve share store in application context
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-21 22:53:43 -07:00
Krystie 7682cb77bf fix: pass platform paths to share store
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-21 22:45:50 -07:00
Krystie ed32deb4ba merge: integrate upstream license-tier updates
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
2026-07-21 21:59:56 -07:00
Krystie a2a2bee71e fix: match parameterized public auth routes 2026-07-21 21:59:03 -07:00
38 changed files with 1952 additions and 1044 deletions
+18 -7
View File
@@ -250,7 +250,7 @@
Tickets DC-033 through DC-041 were added after the DNS2 v1.14.4 / v1.14.8 / 0.0.0 incident. They are grounded in real evidence from that session — see DC-033's details for the full chain of reasoning (cross-checked by main agent + z.ai subagent).
### DC-044: Fix WorkflowEngine healthCheckService — servicesStateManager.getState bug (silent every-5min error spam)
- **status:** in-progress
- **status:** done
- **owner:** hermes
- **details:** `src/recipes/bundled-workflows.js:310` calls `servicesStateManager.getState()` which doesn't exist (StateManager exposes `read()`, not `getState()`). Combined with a missing `await`, the call returned a Promise (truthy), short-circuited via `|| []` to an empty array, then `for (const service of services)` silently iterated over zero services. Net effect: every `health-check-on-interval` workflow ran every 5 min, reported `Action health-check failed: servicesStateManager.getState is not a function`, sent a "Health check failed for {{serviceId}}" notification (with the unresolved template!), and produced `checked: 0, healthy: 0` results. Visible on BOTH DNS2 (production, 4 days) and test server dc-contabo-de (9 days). Fix: call `await servicesStateManager.read().catch(() => [])` — proper async + corruption-tolerant.
- **impact:** Workflow health checks now actually check container health, instead of silently reporting 0/0 every cycle. Stops the "Health check failed" notification spam.
@@ -323,25 +323,36 @@ Sami explicitly stated he wants email auth as an OPTION alongside TOTP, not a re
- **prerequisite:** DC-042 + DC-043 (Tailscale manager + coord API shipped); DC-052 (license check); DC-048 (invite flow model).
### DC-054: License-keygen CLI improvements + Stripe webhook bridge script
- **status:** todo
- **owner:** unclaimed
- **status:** in-progress
- **owner:** hermes
- **details:** Existing `dashcaddy-api/license-keygen.js` already supports durations [30, 90, 180, 365]. Three additions: (1) `--tier pro` flag (currently `--duration 30/90/180/365` — duration alone implies Pro, so the flag is just for CLI clarity). (2) `dashcaddy-api/scripts/stripe-license-bridge.js` — listens on `STRIPE_WEBHOOK_SECRET`, validates `checkout.session.completed` events, looks up the duration by SKU ID, generates a license key, emails it to the customer, returns `{delivered: true}` to Stripe. (3) `dashcaddy-api/license-keygen.js` validation path — already exists, no change. Sami generates initial keys via CLI for the launch.
- **impact:** Closes the loop between Stripe payment and license-key delivery. Without this, every sale requires manual key generation by Sami.
- **prerequisite:** None. Stripe-side can be set up in parallel with DC-052.
### DC-055: dashcaddy.net/pricing static page + Stripe Checkout integration
- **status:** todo
- **owner:** unclaimed
- **status:** in-progress
- **owner:** hermes
- **details:** Static page at `/pricing` showing the 5-row tier table (Free / 1mo / 3mo / 6mo / 12mo). Stripe Checkout button per paid tier. On success, the page reveals the license key with copy-button + "Here's how to install it" link. Receipt email sent via Stripe's built-in. No account creation in this flow (Q10 decision — optional dashcaddy.net account is post-v1.0).
- **impact:** The conversion surface. Without this, the product is real but unsellable.
- **prerequisite:** DC-054 (Stripe webhook bridge so licenses auto-issue).
- **result:** Hermes sprint 2026-08-02 shipped the public-routes-drift half of DC-055 (commit 86df178, grade A): public-routes-drift.test.js now correctly maps `routes/billing.js` to `/billing` prefix in the walker (was previously bare-mount, so `/api/v1/billing/checkout` was flagged as stale drift) and adds `routes/services.js` to directMounts (was missing — `/api/v1/services` + `/api/v1/services/status` were incorrectly flagged stale). Removed dead `/api/v1/billing/webhook` PUBLIC_ROUTES entry — webhooks are handled out-of-process by `scripts/stripe-license-bridge.js` and the merchant webhook secret never enters the API process. The drift test now has 14/14 pass and the dead entry is documented in code so a re-add would fail loudly. Krystie's prior uncommitted work (`src/billing/stripe-client.js`, `routes/billing.js`, `scripts/stripe-license-bridge.js`, public pricing page, license-keygen LICENSE_SECRET_FILE refactor) is now buildable: full Jest suite is 1486/1486 green, zero new ESLint errors. Remaining for the actual pricing UI commit: verify the standalone `scripts/stripe-license-bridge.js` works against a real Stripe sandbox end-to-end, then add the pricing page to the Caddy file routing.
### DC-056: ToS + Privacy Policy pages — GDPR-aware, no SOC2/HIPAA for v1.0
### DC-057: Close checkout-to-license contract drift before public billing launch
- **status:** todo
- **owner:** unclaimed
- **details:** Two static pages at `/legal/tos` and `/legal/privacy`. ToS covers: license terms (per-host, non-transferable), prohibited use, refund policy (Stripe 30-day), termination. Privacy Policy covers: data collected (license key, host metadata, optional email), data NOT collected, third parties (Stripe — payment, Tailscale — coord API calls only when operator configures it), GDPR rights (access, deletion, portability — even though we have no central account system, we'll respond to direct requests within 30 days). No SOC2/HIPAA — that's a v2 conversation.
- **details:** Codex audit found the current Stripe checkout and webhook bridge cannot interoperate: `dashcaddy-api/src/billing/stripe-client.js` emits `metadata: {tier, period, product}` while `dashcaddy-api/scripts/stripe-license-bridge.js` requires `metadata.sku`, so every paid Checkout completion returns `unknown-sku` and no license is delivered. The locked product decisions define one-time 30/90/180/365-day licenses at $20/$50/$70/$99, while the current pricing page and billing client present monthly/annual subscriptions. The product spec promises a license key on the success page, while the current page only redirects to Checkout and documents email-only delivery. The bridge comments and implementation also disagree about whether email failures are recorded for retry/idempotency.
- **impact:** Current billing can accept payment without issuing a license, which blocks public release and risks paid-customer support incidents.
- **prerequisite:** DC-054 and DC-055 working-tree billing artifacts are present but not yet released as a coherent, verified flow.
- **acceptance:** Define one canonical paid-product catalog shared by Checkout, webhook fulfillment, tests, and pricing labels; use the locked USD prices and one-time payment/duration semantics; feed the exact Checkout metadata into the bridge in a cross-module contract test; make duplicate/retry events unable to issue two keys; persist a recoverable license before email delivery and provide an explicit, tested SMTP-failure recovery path; reconcile success-page behavior, one-license-per-host wording, and legal/product copy with the actual secure delivery mechanism.
- **result:** Rolled back to `todo` on 2026-08-02. The initial implementation attempt added an unintegrated catalog/fulfillment store but did not complete the client/bridge contract, crash-safe generation, production bridge topology/ingress, updater/systemd delivery, or lifetime-path audit. Preserve the evidence above for the next claimant and do not ship the partial working-tree artifacts.
### DC-056: ToS + Privacy Policy pages — GDPR-aware, no SOC2/HIPAA for v1.0
- **status:** done
- **owner:** hermes
- **details:** Two static pages at `/legal/tos` and `/legal/privacy`. ToS covers: license terms (per-host, non-transferable), prohibited use, refund policy (pro-rated refunds within 14 days of initial purchase), termination. Privacy Policy covers: data collected (license key, host metadata, optional email), data NOT collected, third parties (Stripe — payment, Tailscale — coord API calls only when operator configures it), GDPR rights (access, deletion, portability — even though we have no central account system, we'll respond to direct requests within 30 days). No SOC2/HIPAA — that's a v2 conversation.
- **impact:** Legal compliance for taking money. Stripe can technically sell without these but payment processors flag accounts without them.
- **prerequisite:** None.
- **result:** Added responsive Terms and Privacy HTML at `status.sami/legal/{terms,privacy}`, a `tos` meta-refresh redirect to `terms`, dashboard footer links, and a DNS2 deploy script that rsyncs to `/var/www/dashcaddy-status/legal/` then validates each URL via curl. Terms apply the launch requirement of pro-rated refunds within 14 days. Single canonical host (status.sami) — the aspirational `legal.dashcaddy.net` is deferred to a v1.x deploy when DNS+Caddy vhost+LE cert infra is in place.
### Backlog note (2026-07-14)
+3 -3
View File
@@ -2,8 +2,8 @@
**Self-hosted dashboard for managing Docker apps with automatic SSL, DNS, and reverse proxy configuration.**
![Version](https://img.shields.io/badge/version-1.0.0-blue)
![License](https://img.shields.io/badge/license-MIT-green)
![Version](https://img.shields.io/badge/version-1.15.0-blue)
![License](https://img.shields.io/badge/license-Proprietary-red)
## What is DashCaddy?
@@ -397,7 +397,7 @@ Contributions are welcome! Please:
## License
MIT License - see LICENSE file for details
Proprietary software. All rights reserved. See [LICENSE](LICENSE) for the End-User License Agreement (EULA).
## Credits
+1 -1
View File
@@ -1 +1 @@
8ea41e0
20260722-065235-cookie-only-session-653478a
@@ -52,15 +52,15 @@ describe('WorkflowEngine.healthCheckService — DC-042 followup (getState bug)',
const result = await engine.healthCheckService('{{serviceId}}');
expect(readMock).toHaveBeenCalledTimes(1);
expect(result).toEqual({ checked: 0, healthy: 0, results: [] });
expect(result).toEqual({ checked: 0, healthy: 0, results: [], failing: [] });
});
test('returns checked/healthy counts from read() output', async () => {
test('returns checked/healthy counts from read() output (all healthy)', async () => {
const docker = {
client: {
getContainer: jest.fn((id) => ({
inspect: jest.fn().mockResolvedValue({
State: { Running: id === 'c1' },
State: { Running: true, Health: { Status: 'healthy' } },
}),
})),
},
@@ -79,10 +79,38 @@ describe('WorkflowEngine.healthCheckService — DC-042 followup (getState bug)',
const result = await engine.healthCheckService('{{serviceId}}');
expect(result.checked).toBe(2); // svc-3 skipped (no containerId)
expect(result.healthy).toBe(1); // c1 is running, c2 is not
expect(result.healthy).toBe(2); // both containers healthy
expect(result.results).toHaveLength(2);
expect(result.results[0]).toMatchObject({ service: 'svc-1', healthy: true });
expect(result.results[1]).toMatchObject({ service: 'svc-2', healthy: false });
expect(result.results[1]).toMatchObject({ service: 'svc-2', healthy: true });
expect(result.failing).toEqual([]);
});
test('throws when any service is unhealthy — surfaces failing service IDs', async () => {
const docker = {
client: {
getContainer: jest.fn((id) => ({
inspect: jest.fn().mockResolvedValue({
State: { Running: id !== 'c2', Health: { Status: id === 'c2' ? 'unhealthy' : 'healthy' } },
}),
})),
},
};
const engine = makeEngine({
servicesStateManager: {
read: jest.fn().mockResolvedValue([
{ id: 'svc-1', containerId: 'c1' },
{ id: 'svc-2', containerId: 'c2' },
]),
},
docker,
});
await expect(engine.healthCheckService('{{serviceId}}')).rejects.toThrow(/svc-2/);
await expect(engine.healthCheckService('{{serviceId}}')).rejects.toMatchObject({
failingServices: ['svc-2'],
workflowResult: expect.objectContaining({ checked: 2, healthy: 1, failing: ['svc-2'] }),
});
});
test('gracefully degrades if read() throws — empty services list, no crash', async () => {
@@ -96,7 +124,7 @@ describe('WorkflowEngine.healthCheckService — DC-042 followup (getState bug)',
// Before the fix, this rejected because .read() wasn't called and the
// .catch(() => []) fallback didn't exist. Now it should resolve to empty.
const result = await engine.healthCheckService('{{serviceId}}');
expect(result).toEqual({ checked: 0, healthy: 0, results: [] });
expect(result).toEqual({ checked: 0, healthy: 0, results: [], failing: [] });
});
test('servicesStateManager absent on ctx → no crash, empty result', async () => {
@@ -111,7 +139,7 @@ describe('WorkflowEngine.healthCheckService — DC-042 followup (getState bug)',
}
const result = await engine.healthCheckService('{{serviceId}}');
expect(result).toEqual({ checked: 0, healthy: 0, results: [] });
expect(result).toEqual({ checked: 0, healthy: 0, results: [], failing: [] });
});
test('single service (non-template serviceId) path still works', async () => {
@@ -128,4 +156,245 @@ describe('WorkflowEngine.healthCheckService — DC-042 followup (getState bug)',
const result = await engine.healthCheckService('single-svc-id');
expect(result).toEqual({ serviceId: 'single-svc-id', healthy: true });
});
test('single-service check throws when container is unhealthy', async () => {
const engine = makeEngine({
docker: {
client: {
getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({ State: { Running: false } }),
})),
},
},
});
await expect(engine.healthCheckService('down-svc')).rejects.toMatchObject({
failingServices: ['down-svc'],
});
});
});
/**
* DC-044 root-cause fix tests: notify-on-failure gating + template interpolation.
*
* The original code in executeAction had TWO latent bugs:
* 1. notify-on-failure sent unconditionally (its comment said "Only send if
* previous action failed" but the code never checked).
* 2. healthCheckService returned no serviceId field, so templates like
* `Health check failed for {{serviceId}}` never interpolated and stayed
* literal in every alert.
*
* These tests exercise the full executeWorkflow path with a stub workflow
* that pairs `health-check` with `notify-on-failure`.
*/
describe('WorkflowEngine._runActions — DC-044 root-cause (notify-on-failure + template)', () => {
// Build an engine and call _runActions directly with arbitrary action
// sequences. Bypasses BUNDLED_WORKFLOWS lookup so tests are isolated and
// don't mutate module state.
function makeEngine(opts = {}) {
const ctx = {
servicesStateManager: opts.servicesStateManager || { read: jest.fn().mockResolvedValue([]) },
docker: opts.docker || { client: { getContainer: jest.fn(() => ({ inspect: jest.fn().mockResolvedValue({ State: { Running: true } }) })) } },
notification: opts.notification || { send: jest.fn() },
};
const engine = new WorkflowEngine(ctx);
if (engine.scheduledJobs) {
for (const job of engine.scheduledJobs.values()) clearInterval(job);
engine.scheduledJobs.clear();
}
return engine;
}
test('notify-on-failure is a no-op when the previous action succeeded', async () => {
const notify = jest.fn();
const engine = makeEngine({
servicesStateManager: { read: jest.fn().mockResolvedValue([{ id: 'svc-1', containerId: 'c1' }]) },
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({ State: { Running: true } }),
})) } },
notification: { send: notify },
});
const results = await engine._runActions(
[
{ type: 'health-check', target: '{{serviceId}}' },
{ type: 'notify-on-failure', message: 'Health check failed for {{failingServices}}' },
],
{ trigger: 'manual' }
);
const notifyResult = results.find(r => r.action === 'notify-on-failure');
expect(notifyResult.success).toBe(true);
expect(notifyResult.result).toEqual({ skipped: true, reason: 'no previous failure' });
expect(notify).not.toHaveBeenCalled();
});
test('notify-on-failure fires and interpolates {{failingServices}} when previous action failed', async () => {
const notify = jest.fn();
const engine = makeEngine({
servicesStateManager: { read: jest.fn().mockResolvedValue([{ id: 'svc-broken', containerId: 'c1' }]) },
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({ State: { Running: false } }),
})) } },
notification: { send: notify },
});
const results = await engine._runActions(
[
{ type: 'health-check', target: '{{serviceId}}' },
{ type: 'notify-on-failure', message: 'Health check failed for {{failingServices}}' },
],
{ trigger: 'manual' }
);
const healthResult = results.find(r => r.action === 'health-check');
const notifyResult = results.find(r => r.action === 'notify-on-failure');
expect(healthResult.success).toBe(false);
expect(healthResult.failingServices).toEqual(['svc-broken']);
expect(notifyResult.success).toBe(true);
expect(notify).toHaveBeenCalledTimes(1);
// notification.send signature: (category, title, message, level)
const sentMessage = notify.mock.calls[0][2];
expect(sentMessage).toBe('Health check failed for svc-broken');
expect(sentMessage).not.toContain('{{');
});
test('notify (not notify-on-failure) fires unconditionally — regression guard', async () => {
const notify = jest.fn();
const engine = makeEngine({ notification: { send: notify } });
const results = await engine._runActions(
[{ type: 'notify', message: 'always sent' }],
{ trigger: 'manual' }
);
expect(notify).toHaveBeenCalledTimes(1);
expect(notify.mock.calls[0][2]).toBe('always sent');
expect(results[0].success).toBe(true);
});
test('notify-on-failure as first action is a no-op (no previous result)', async () => {
const notify = jest.fn();
const engine = makeEngine({ notification: { send: notify } });
const results = await engine._runActions(
[{ type: 'notify-on-failure', message: 'should not fire' }],
{ trigger: 'manual' }
);
const notifyResult = results[0];
expect(notifyResult.success).toBe(true);
expect(notifyResult.result).toEqual({ skipped: true, reason: 'no previous failure' });
expect(notify).not.toHaveBeenCalled();
});
test('multi-service batch failure: {{failingServices}} interpolates comma-joined list', async () => {
const notify = jest.fn();
const engine = makeEngine({
servicesStateManager: { read: jest.fn().mockResolvedValue([
{ id: 'svc-ok', containerId: 'c1' },
{ id: 'svc-broken-1', containerId: 'c2' },
{ id: 'svc-broken-2', containerId: 'c3' },
]) },
docker: { client: { getContainer: jest.fn((id) => ({
inspect: jest.fn().mockResolvedValue({
State: { Running: id === 'c1', Health: { Status: id === 'c1' ? 'healthy' : 'unhealthy' } },
}),
})) } },
notification: { send: notify },
});
const results = await engine._runActions(
[
{ type: 'health-check', target: '{{serviceId}}' },
{ type: 'notify-on-failure', message: 'Failing: {{failingServices}}' },
],
{ trigger: 'manual' }
);
expect(notify).toHaveBeenCalledTimes(1);
const sentMessage = notify.mock.calls[0][2];
expect(sentMessage).toBe('Failing: svc-broken-1,svc-broken-2');
expect(results.find(r => r.action === 'notify-on-failure').success).toBe(true);
});
// B2 regression: hit the actual bundled health-check-on-interval workflow
// end-to-end via executeWorkflow. The bundled template uses
// {{failingServices}} (DC-044 fix). Earlier it used {{serviceId}} which
// never resolved because no per-service ID is in workflow scope. This test
// would have failed with the old template.
test('executeWorkflow on bundled health-check-on-interval: no literal {{...}} in notification', async () => {
const { BUNDLED_WORKFLOWS } = require('../src/recipes/bundled-workflows');
expect(BUNDLED_WORKFLOWS['health-check-on-interval']).toBeDefined();
const notify = jest.fn();
const engine = makeEngine({
servicesStateManager: { read: jest.fn().mockResolvedValue([
{ id: 'svc-broken', containerId: 'c1' },
]) },
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({
State: { Running: false, Health: { Status: 'unhealthy' } },
}),
})) } },
notification: { send: notify },
});
const result = await engine.executeWorkflow('health-check-on-interval', { trigger: 'manual' });
// Either the bundled workflow fired notification (with interpolated
// message) OR every action resolved — but in NO case may a literal
// {{...}} template token leak into notification.send.
if (notify.mock.calls.length > 0) {
const sentMessage = notify.mock.calls[0][2];
expect(sentMessage).not.toMatch(/\{\{/);
expect(sentMessage).not.toMatch(/\}\}/);
// The new bundled template substitutes failingServices — make sure
// the actual service ID made it through.
expect(sentMessage).toContain('svc-broken');
}
// Workflow must always complete (success or failure), never throw.
expect(result).toBeDefined();
expect(result.workflowId).toBe('health-check-on-interval');
});
// B3 regression: a running container with Health.Status === 'unhealthy'
// must be reported as unhealthy. Previously checkContainerHealth compared
// info.State.Health itself (an object) to the string 'unhealthy', which
// was always false — so any container with an explicit healthcheck was
// always considered healthy. The fix reads info.State.Health.Status.
test('checkContainerHealth treats running-but-unhealthy container as unhealthy', async () => {
const engine = makeEngine({
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({
State: { Running: true, Health: { Status: 'unhealthy' } },
}),
})) } },
});
const healthy = await engine.checkContainerHealth('running-but-unhealthy');
expect(healthy).toBe(false);
});
test('checkContainerHealth treats running-with-no-healthcheck as healthy', async () => {
const engine = makeEngine({
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({ State: { Running: true } }),
})) } },
});
const healthy = await engine.checkContainerHealth('no-healthcheck');
expect(healthy).toBe(true);
});
test('checkContainerHealth treats stopped container as unhealthy', async () => {
const engine = makeEngine({
docker: { client: { getContainer: jest.fn(() => ({
inspect: jest.fn().mockResolvedValue({ State: { Running: false } }),
})) } },
});
const healthy = await engine.checkContainerHealth('stopped');
expect(healthy).toBe(false);
});
});
@@ -0,0 +1,460 @@
/**
* Tests for dashcaddy-api/license-keygen.js
*
* Covers the programmatic API used by the Stripe webhook bridge and the
* on-disk counter allocator. The CLI path is exercised through the
* dedicated CLI regression describe block at the bottom of this file.
*
* - module.exports shape: verifyCode, parseCode, generateCode,
* generateCodes, loadSecret, VALID_DURATIONS, VERSION
* - generateCodes() validation: secret, duration, count
* - generateCodes() counter allocator: init, increment, override via
* startId, override via counterFile, atomic .tmp shape
* - generateCodes() monotonic counter: 100-call ordering, range checks
* - loadSecret() success and missing-file error
* - generateCode() round-trip: codes verify back via verifyCode()
* - CLI integration: omitted --start-id uses auto-counter, explicit
* --start-id skips counter write, --lifetime/--duration mutual exclusion
*/
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execFileSync } = require('child_process');
const keygen = require('../license-keygen');
const {
verifyCode,
parseCode,
generateCode,
generateCodes,
loadSecret,
VALID_DURATIONS,
VERSION,
} = keygen;
function _tmpDir(prefix) {
return fs.mkdtempSync(path.join(os.tmpdir(), `dashcaddy-${prefix}-`));
}
function _cleanup(dir) {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_) { /* best effort */ }
}
const TEST_SECRET = 'a'.repeat(64); // 32 bytes hex
// ── Public surface ──────────────────────────────────────────────────────────
describe('license-keygen: module.exports', () => {
test('exports verifyCode, parseCode, generateCode, generateCodes, loadSecret, VALID_DURATIONS, VERSION', () => {
expect(typeof verifyCode).toBe('function');
expect(typeof parseCode).toBe('function');
expect(typeof generateCode).toBe('function');
expect(typeof generateCodes).toBe('function');
expect(typeof loadSecret).toBe('function');
expect(Array.isArray(VALID_DURATIONS)).toBe(true);
expect(VALID_DURATIONS).toEqual([30, 90, 180, 365]);
expect(VERSION).toBe(1);
});
});
// ── generateCode / parseCode / verifyCode round-trip ────────────────────────
describe('license-keygen: generateCode round-trip', () => {
test('generated code verifies back via verifyCode()', () => {
const code = generateCode(TEST_SECRET, 90, 42);
expect(code).toMatch(/^DC-([0-9A-Z]{5})(-[0-9A-Z]{5}){4}$/);
const result = verifyCode(TEST_SECRET, code);
expect(result.valid).toBe(true);
expect(result.durationDays).toBe(90);
expect(result.codeId).toBe(42);
});
test('verifyCode rejects a code from a different secret', () => {
const code = generateCode(TEST_SECRET, 30, 1);
const result = verifyCode('b'.repeat(64), code);
expect(result.valid).toBe(false);
expect(result.reason).toMatch(/signature/i);
});
test('parseCode returns version, duration, codeId, timestamp', () => {
const code = generateCode(TEST_SECRET, 365, 9999);
const parsed = parseCode(code);
expect(parsed.version).toBe(VERSION);
expect(parsed.durationDays).toBe(365);
expect(parsed.codeId).toBe(9999);
expect(typeof parsed.createdTs).toBe('number');
});
});
// ── generateCodes: validation ───────────────────────────────────────────────
describe('license-keygen: generateCodes validation', () => {
test('throws on missing secret', () => {
expect(() => generateCodes({ secret: '', durationDays: 30 })).toThrow(/secret is required/);
expect(() => generateCodes({ secret: 123, durationDays: 30 })).toThrow(/secret is required/);
expect(() => generateCodes({ durationDays: 30 })).toThrow(/secret is required/);
});
test('throws on invalid duration', () => {
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 7 })).toThrow(/invalid duration/);
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 31 })).toThrow(/invalid duration/);
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: -1 })).toThrow(/invalid duration/);
});
test('accepts LIFETIME (durationDays: 0)', () => {
const tmp = _tmpDir('kg-lifetime');
try {
const codes = generateCodes({
secret: TEST_SECRET,
durationDays: 0,
counterFile: path.join(tmp, '.counter'),
});
expect(codes).toHaveLength(1);
expect(codes[0].durationDays).toBe(0);
} finally { _cleanup(tmp); }
});
test('throws on invalid count', () => {
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 30, count: 0 })).toThrow(/invalid count/);
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 30, count: -1 })).toThrow(/invalid count/);
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 30, count: 10001 })).toThrow(/invalid count/);
expect(() => generateCodes({ secret: TEST_SECRET, durationDays: 30, count: 1.5 })).toThrow(/invalid count/);
});
});
// ── generateCodes: counter allocator ────────────────────────────────────────
describe('license-keygen: generateCodes counter', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-counter'); });
afterEach(() => { _cleanup(tmp); });
test('initializes counter at 1 when file is missing', () => {
const codes = generateCodes({
secret: TEST_SECRET,
durationDays: 30,
counterFile: path.join(tmp, '.counter'),
});
expect(codes[0].codeId).toBe(1);
expect(fs.readFileSync(path.join(tmp, '.counter'), 'utf8').trim()).toBe('1');
});
test('increments counter on subsequent calls', () => {
const counterFile = path.join(tmp, '.counter');
for (let i = 1; i <= 3; i++) {
const codes = generateCodes({
secret: TEST_SECRET,
durationDays: 30,
counterFile,
});
expect(codes[0].codeId).toBe(i);
}
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('3');
});
test('respects startId override and does NOT touch the counter file', () => {
const counterFile = path.join(tmp, '.counter');
fs.writeFileSync(counterFile, '100');
const codes = generateCodes({
secret: TEST_SECRET,
durationDays: 30,
count: 3,
startId: 500,
counterFile,
});
expect(codes.map(c => c.codeId)).toEqual([500, 501, 502]);
// Counter file unchanged — overrideStartId path skips the write.
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('100');
});
test('no leftover .tmp files after a successful call', () => {
const counterFile = path.join(tmp, '.counter');
generateCodes({ secret: TEST_SECRET, durationDays: 30, counterFile });
const entries = fs.readdirSync(tmp);
expect(entries.filter(e => e.includes('.tmp'))).toEqual([]);
});
test('counter file uses per-call unique tmp suffix (no .tmp collisions)', () => {
const counterFile = path.join(tmp, '.counter');
const origWrite = fs.writeFileSync;
const tmpNames = [];
fs.writeFileSync = (p, data, opts) => {
if (typeof p === 'string' && p.startsWith(counterFile) && p.includes('.tmp')) {
tmpNames.push(p);
}
return origWrite.call(fs, p, data, opts);
};
try {
generateCodes({ secret: TEST_SECRET, durationDays: 30, counterFile });
generateCodes({ secret: TEST_SECRET, durationDays: 30, counterFile });
expect(tmpNames).toHaveLength(2);
expect(new Set(tmpNames).size).toBe(2);
} finally {
fs.writeFileSync = origWrite;
}
});
});
// ── generateCodes: monotonic counter ────────────────────────────────────────
//
// generateCodes() is synchronous. Node's single-threaded event loop means
// two synchronous calls cannot interleave, so the counter is monotonically
// incremented without any explicit locking. The atomic write helper
// protects against process crashes between writeFileSync and renameSync.
// These tests verify that ordering and atomicity hold across many calls.
describe('license-keygen: generateCodes monotonic counter', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-mono'); });
afterEach(() => { _cleanup(tmp); });
test('100 sequential calls produce 100 unique codeIds in monotonic order', () => {
const counterFile = path.join(tmp, '.counter');
const codes = [];
for (let i = 0; i < 100; i++) {
codes.push(generateCodes({
secret: TEST_SECRET,
durationDays: 30,
counterFile,
})[0]);
}
const ids = codes.map(c => c.codeId);
expect(ids).toHaveLength(100);
expect(new Set(ids).size).toBe(100);
for (let i = 1; i < ids.length; i++) {
expect(ids[i]).toBe(ids[i - 1] + 1);
}
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('100');
});
test('100 sequential calls each requesting 5 codes produce 500 unique IDs', () => {
const counterFile = path.join(tmp, '.counter');
const batches = [];
for (let i = 0; i < 100; i++) {
batches.push(generateCodes({
secret: TEST_SECRET,
durationDays: 30,
count: 5,
counterFile,
}));
}
const allIds = batches.flat().map(c => c.codeId);
expect(allIds).toHaveLength(500);
expect(new Set(allIds).size).toBe(500);
batches.forEach((batch, i) => {
const start = i * 5 + 1;
expect(batch.map(c => c.codeId)).toEqual([start, start + 1, start + 2, start + 3, start + 4]);
});
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('500');
});
test('startId override is range-checked (negative throws)', () => {
expect(() => generateCodes({
secret: TEST_SECRET,
durationDays: 30,
startId: -1,
counterFile: path.join(tmp, '.counter'),
})).toThrow(/out of range/);
});
test('startId override is range-checked (over 32-bit throws)', () => {
expect(() => generateCodes({
secret: TEST_SECRET,
durationDays: 30,
startId: 0x100000000,
counterFile: path.join(tmp, '.counter'),
})).toThrow(/out of range/);
});
test('startId override is rejected for non-integer values', () => {
// Codex round 2: Number.isInteger(overrideStartId) returned false for
// floats/NaN/null/strings, silently falling through to auto-counter.
// The Object.prototype.hasOwnProperty check above fixes the dispatch.
const counterFile = path.join(tmp, '.counter');
fs.writeFileSync(counterFile, '99');
for (const bad of [1.5, NaN, null, '100', undefined, false]) {
const prevValue = fs.readFileSync(counterFile, 'utf8').trim();
expect(() => generateCodes({
secret: TEST_SECRET,
durationDays: 30,
startId: bad,
counterFile,
})).toThrow(/out of range|non-integer/);
// Counter file must NOT be touched when the call throws.
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe(prevValue);
}
});
test('count that would push codeId past 32-bit throws', () => {
const counterFile = path.join(tmp, '.counter');
fs.writeFileSync(counterFile, String(0xFFFFFFFF - 5));
expect(() => generateCodes({
secret: TEST_SECRET,
durationDays: 30,
count: 10,
counterFile,
})).toThrow(/32-bit limit/);
});
});
// ── generateCodes: counterFile override ─────────────────────────────────────
describe('license-keygen: generateCodes counterFile override', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-cf'); });
afterEach(() => { _cleanup(tmp); });
test('counterFile option overrides LICENSE_COUNTER_FILE env', () => {
const cf = path.join(tmp, '.counter');
const prev = process.env.LICENSE_COUNTER_FILE;
try {
process.env.LICENSE_COUNTER_FILE = path.join(tmp, 'env-counter');
generateCodes({ secret: TEST_SECRET, durationDays: 30, counterFile: cf });
expect(fs.existsSync(cf)).toBe(true);
expect(fs.existsSync(path.join(tmp, 'env-counter'))).toBe(false);
} finally {
if (prev === undefined) delete process.env.LICENSE_COUNTER_FILE;
else process.env.LICENSE_COUNTER_FILE = prev;
}
});
test('LICENSE_COUNTER_FILE env overrides the default __dirname counter', () => {
const tmpForEnv = _tmpDir('kg-env');
try {
const target = path.join(tmpForEnv, 'env-counter');
const prev = process.env.LICENSE_COUNTER_FILE;
process.env.LICENSE_COUNTER_FILE = target;
try {
const codes = generateCodes({ secret: TEST_SECRET, durationDays: 30 });
expect(codes[0].codeId).toBeLessThanOrEqual(1); // fresh env
expect(fs.existsSync(target)).toBe(true);
} finally {
if (prev === undefined) delete process.env.LICENSE_COUNTER_FILE;
else process.env.LICENSE_COUNTER_FILE = prev;
}
} finally { _cleanup(tmpForEnv); }
});
});
// ── loadSecret ──────────────────────────────────────────────────────────────
describe('license-keygen: loadSecret', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-secret'); });
afterEach(() => { _cleanup(tmp); });
test('returns trimmed contents of an existing secret file', () => {
const file = path.join(tmp, '.license-secret');
fs.writeFileSync(file, ' abc123 \n');
expect(loadSecret(file)).toBe('abc123');
});
test('throws on missing file with helpful message', () => {
const file = path.join(tmp, 'does-not-exist');
expect(() => loadSecret(file)).toThrow(/not found/i);
expect(() => loadSecret(file)).toThrow(/--init-secret/i);
});
});
// ── generateCodes: failure modes ────────────────────────────────────────────
describe('license-keygen: generateCodes failure modes', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-fail'); });
afterEach(() => { _cleanup(tmp); });
test('throws when counter file exists but contains non-numeric data', () => {
const counterFile = path.join(tmp, '.counter');
fs.writeFileSync(counterFile, 'not-a-number');
expect(() =>
generateCodes({ secret: TEST_SECRET, durationDays: 30, counterFile }),
).toThrow(/non-numeric/);
});
});
// ── CLI regression: spawn the real binary and verify argument handling ───────
//
// Codex round 4 caught a regression: main() always passed
// `startId: overrideStartId` to generateCodes(), even when --start-id was
// omitted. The new hasOwnProperty-based validation then rejected the call
// because startId was an explicit (undefined) value. The fix is to omit
// the startId property from the options object when --start-id is absent.
// These tests exercise the actual CLI binary to make sure the local fix
// wires up correctly.
const KEYGEN_BIN = path.resolve(__dirname, '..', 'license-keygen.js');
function _runCli(args, env) {
return execFileSync('node', [KEYGEN_BIN, ...args], {
env: { ...process.env, ...env },
encoding: 'utf8',
});
}
describe('license-keygen: CLI regression', () => {
let tmp;
beforeEach(() => { tmp = _tmpDir('kg-cli'); });
afterEach(() => { _cleanup(tmp); });
function _setupSecret() {
fs.writeFileSync(path.join(tmp, '.license-secret'), TEST_SECRET);
}
test('omitted --start-id uses the auto-counter path (CLI integration)', () => {
_setupSecret();
const counterFile = path.join(tmp, '.license-counter');
// First call: no --start-id, expects counter to be created at 1.
const out1 = _runCli(['--duration', '30', '--count', '1', '--json'], {
LICENSE_COUNTER_FILE: counterFile,
});
const codes1 = JSON.parse(out1.split('Generated')[0]);
expect(codes1).toHaveLength(1);
expect(codes1[0].codeId).toBe(1);
expect(codes1[0].durationDays).toBe(30);
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('1');
// Second call: counter should auto-increment to 2.
const out2 = _runCli(['--duration', '30', '--count', '1', '--json'], {
LICENSE_COUNTER_FILE: counterFile,
});
const codes2 = JSON.parse(out2.split('Generated')[0]);
expect(codes2[0].codeId).toBe(2);
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('2');
});
test('--start-id override skips counter file update (CLI integration)', () => {
_setupSecret();
const counterFile = path.join(tmp, '.license-counter');
fs.writeFileSync(counterFile, '99');
const out = _runCli(['--duration', '30', '--start-id', '500', '--count', '2', '--json'], {
LICENSE_COUNTER_FILE: counterFile,
});
const codes = JSON.parse(out.split('Generated')[0]);
expect(codes.map(c => c.codeId)).toEqual([500, 501]);
// Counter file untouched.
expect(fs.readFileSync(counterFile, 'utf8').trim()).toBe('99');
});
test('--lifetime and --duration are mutually exclusive (CLI integration)', () => {
_setupSecret();
expect(() =>
_runCli(['--duration', '30', '--lifetime', '--count', '1'], {
LICENSE_COUNTER_FILE: path.join(tmp, '.license-counter'),
}),
).toThrow(/mutually exclusive/);
});
test('--tier pro without --duration or --lifetime still requires one of them', () => {
_setupSecret();
expect(() =>
_runCli(['--tier', 'pro', '--count', '1'], {
LICENSE_COUNTER_FILE: path.join(tmp, '.license-counter'),
}),
).toThrow(/--duration is required/);
});
});
@@ -0,0 +1,89 @@
/**
* Regression tests for PUBLIC_ROUTES / CSRF excludedPaths `:param` placeholder
* matching. Pre-DC-053 these were literal-string comparisons, so
* `/api/v1/share/:token/preview` never matched real request paths like
* `/api/v1/share/abc123/preview`. Fixed by converting `:param` to a
* `[^/]+` regex segment before testing. Caught during DC-053 live testing.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
function _tmpDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'dashcaddy-public-test-'));
}
function _cleanup(dir) {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
const SRC_MIDDLEWARE = path.join(__dirname, '..', 'src', 'utilities', 'middleware.js');
const SRC_CSRF = path.join(__dirname, '..', 'src', 'security', 'csrf-protection.js');
describe('PUBLIC_ROUTES + CSRF excludedPaths: `:param` placeholder matching', () => {
test('PUBLIC_ROUTES is parsed and contains the DC-053 share entries', () => {
const content = fs.readFileSync(SRC_MIDDLEWARE, 'utf8');
// Sanity: file should still contain the public share entries
expect(content).toContain('/api/v1/share/:token/preview');
expect(content).toContain('/api/v1/share/:token/subscribe');
expect(content).toContain('/api/v1/share/:token/redeem-tailscale');
});
test('CSRF excludedPaths contains the DC-053 share entries', () => {
const content = fs.readFileSync(SRC_CSRF, 'utf8');
expect(content).toContain('/api/v1/share/:token/subscribe');
expect(content).toContain('/api/v1/share/:token/redeem-tailscale');
});
test('PUBLIC_ROUTES contains the DC-048 invite entries (regression coverage)', () => {
const content = fs.readFileSync(SRC_MIDDLEWARE, 'utf8');
expect(content).toContain('/api/v1/auth/invites/:token');
expect(content).toContain('/api/v1/auth/invites/:token/accept');
});
test('CSRF excludedPaths contains the DC-048 invite entry', () => {
const content = fs.readFileSync(SRC_CSRF, 'utf8');
expect(content).toContain('/api/v1/auth/invites/:token/accept');
});
// Behavioral test: the regex conversion that the middleware applies to a
// `:param` entry should match real request paths. This exercises the SAME
// algorithm used by `isPublicRoute()` in src/utilities/middleware.js and
// `isExcluded` in src/security/csrf-protection.js, just in isolation.
function _placeholderToRegex(p) {
return '^' + p.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, '[^/]+') + '$';
}
test('placeholder-to-regex algorithm matches share preview paths', () => {
const pattern = _placeholderToRegex('/api/v1/share/:token/preview');
expect(new RegExp(pattern).test('/api/v1/share/abc123/preview')).toBe(true);
expect(new RegExp(pattern).test('/api/v1/share/some-very-long-token/preview')).toBe(true);
// Different method/path segments should not match
expect(new RegExp(pattern).test('/api/v1/share/abc/extra/preview')).toBe(false);
expect(new RegExp(pattern).test('/api/v1/share/preview')).toBe(false);
});
test('placeholder-to-regex matches multi-param paths', () => {
const pattern = _placeholderToRegex('/api/v1/auth/login/:provider/verify');
expect(new RegExp(pattern).test('/api/v1/auth/login/totp/verify')).toBe(true);
expect(new RegExp(pattern).test('/api/v1/auth/login/email/verify')).toBe(true);
expect(new RegExp(pattern).test('/api/v1/auth/login/totp/initiate')).toBe(false);
});
test('placeholder-to-regex handles exact paths (no placeholders)', () => {
const pattern = _placeholderToRegex('/health/live');
expect(new RegExp(pattern).test('/health/live')).toBe(true);
expect(new RegExp(pattern).test('/health/ready')).toBe(false);
});
test('placeholder-to-regex handles the auth/gate/ prefix exemption', () => {
// /api/v1/auth/gate/ is a prefix match (not in PUBLIC_ROUTES entries
// individually). Verify the algorithm preserves this by NOT requiring
// placeholders when none are present.
const pattern = _placeholderToRegex('/api/v1/auth/gate/foo');
expect(new RegExp(pattern).test('/api/v1/auth/gate/foo')).toBe(true);
expect(new RegExp(pattern).test('/api/v1/auth/gate/bar')).toBe(false);
});
});
@@ -111,7 +111,7 @@ function readMountedRoutes() {
'routes/dns.js', // apiRouter.use('/dns', dnsRoutes({...}))
'routes/notifications.js', // apiRouter.use('/notifications', notificationRoutes({...}))
'routes/containers.js', // apiRouter.use('/containers', containerRoutes({...}))
'routes/services.js', // apiRouter.use(serviceRoutes({...})) // bare mount
'routes/billing.js', // DC-055: apiRouter.use('/billing', billingRoutes({...}))
'routes/health.js', // apiRouter.use(healthRoutes({...})) // bare mount
'routes/monitoring.js', // apiRouter.use(monitoringRoutes({...})) // bare mount
'routes/updates.js', // apiRouter.use(updatesRoutes({...})) // bare mount
@@ -130,12 +130,14 @@ function readMountedRoutes() {
'routes/themes.js', // apiRouter.use(themesRoutes({...})) // bare mount
'routes/license.js', // apiRouter.use('/license', licenseRoutes({...}))
'routes/share.js', // apiRouter.use(shareRoutes({...})) // bare mount (DC-053)
'routes/services.js', // apiRouter.use(serviceRoutes({...})) // bare mount — needed for /api/v1/services + /api/v1/services/status PUBLIC_ROUTES
];
// Prefix map: explicit prefix from src/app.js's apiRouter.use() call
const prefixMap = {
'routes/dns.js': '/dns',
'routes/notifications.js': '/notifications',
'routes/containers.js': '/containers',
'routes/billing.js': '/billing', // DC-055: apiRouter.use('/billing', billingRoutes({...})) in src/app.js
'routes/tailscale.js': '/tailscale',
'routes/ca.js': '/ca',
'routes/openclaw.js': '/openclaw',
@@ -4,8 +4,8 @@
* Covers the BACKLOG.md DC-006 acceptance criteria:
* - no code → 400 (ValidationError)
* - wrong code → 401 (AuthenticationError)
* - valid TOTP → 200 + session cookie + CSRF token
* - check-session with valid session → 200 { authenticated: true }
* - valid TOTP → 200 + session cookie + CSRF token + SSO handoff token
* - check-session with valid session → 200 { success: true, authenticated: true }
* - check-session without session → 401 (AuthenticationError)
*
* Uses real otplib for code generation (so we exercise the actual TOTP math)
@@ -79,6 +79,7 @@ function createApp(depsOverride = {}) {
sessionStore.delete(ip);
}),
clearCookie: jest.fn(),
createHandoffToken: jest.fn(() => 'mock-sso-handoff-token'),
isValid: jest.fn((req) => {
const ip = session.getClientIP(req);
const entry = sessionStore.get(ip);
@@ -303,8 +304,10 @@ describe('TOTP Auth Routes — DC-006 Integration Test', () => {
expect(res.body.success).toBe(true);
expect(res.body.message).toMatch(/Authenticated successfully/);
expect(res.body.csrfToken).toBe('mock-csrf-token');
expect(res.body.ssoToken).toBe('mock-sso-handoff-token');
expect(deps.session.create).toHaveBeenCalled();
expect(deps.session.setCookie).toHaveBeenCalled();
expect(deps.session.createHandoffToken).toHaveBeenCalledTimes(1);
expect(deps.renewCSRFToken).toHaveBeenCalled();
});
});
@@ -350,7 +353,7 @@ describe('TOTP Auth Routes — DC-006 Integration Test', () => {
deps.session._grantSession('127.0.0.1');
const res = await request(app).get('/api/totp/check-session').set('X-Forwarded-For', '127.0.0.1');
expect(res.status).toBe(200);
expect(res.body).toEqual({ authenticated: true });
expect(res.body).toEqual({ success: true, authenticated: true });
});
});
@@ -450,24 +453,23 @@ describe('TOTP Auth Routes — DC-006 Integration Test', () => {
const loginRes = await request(app).post('/api/totp/verify').send({ code: loginCode });
expect(loginRes.status).toBe(200);
expect(loginRes.body.csrfToken).toBeDefined();
expect(loginRes.body.ssoToken).toBe('mock-sso-handoff-token');
expect(deps.session.createHandoffToken).toHaveBeenCalledTimes(1);
// 5. Check-session — should now be authenticated (the BACKLOG "→ endpoint succeeds" step)
const checkRes = await request(app).get('/api/totp/check-session');
expect(checkRes.status).toBe(200);
expect(checkRes.body).toEqual({ authenticated: true });
expect(checkRes.body).toEqual({ success: true, authenticated: true });
// 6. Logout / disable
const disableCode = authenticator.generate(secret);
const disableRes = await request(app).post('/api/totp/disable').send({ code: disableCode });
expect(disableRes.status).toBe(200);
// 7. After disable, check-session should be 401 (bypass removed for security)
// unless the user still holds a valid session, in which case it's 200.
// The login step (4) may or may not have granted one depending on test order.
// 7. After disable, check-session deterministically rejects before
// checking session validity because TOTP protection is disabled.
const afterRes = await request(app).get('/api/totp/check-session');
// After disable, TOTP is off AND we may or may not have an active session.
// The new contract: bypass is gone, but a valid session still authenticates.
expect([200, 401]).toContain(afterRes.status);
expect(afterRes.status).toBe(401);
});
it('proves otplib is real (not stubbed) by using a totally bogus code', async () => {
@@ -78,23 +78,19 @@ describe('SelfUpdater.getLocalVersion() — DC-033 regression', () => {
}
});
test('commit is a git SHA (7-40 hex chars), not null', () => {
test('commit contains a git SHA and is not null', () => {
expect(result.commit).not.toBeNull();
expect(result.commit).toMatch(/^[0-9a-f]{7,40}$/);
expect(result.commit).toMatch(/(?:^|-)[0-9a-f]{7,40}$/);
});
});
describe('candidate-path resolution survives missing sibling files', () => {
// If we shadow __dirname by requiring the module through a different
// require() chain, the function should still find package.json via its
// candidate-list fallback. This catches the case where someone refactors
// the file to a deeper subdirectory and forgets to update the candidates.
test('getLocalVersion works regardless of how the module is required', () => {
describe('repeat construction uses the same resolved metadata', () => {
test('a second instance resolves the same non-fallback version metadata', () => {
const mod = require(path.join(API_ROOT, 'src', 'docker', 'self-updater.js'));
const Cls = mod.SelfUpdater || mod.default || mod;
const result = new Cls({}).getLocalVersion();
expect(result.version).not.toBe('0.0.0');
expect(result.commit).toMatch(/^[0-9a-f]{7,40}$/);
expect(result.commit).toMatch(/(?:^|-)[0-9a-f]{7,40}$/);
});
});
});
@@ -0,0 +1,64 @@
'use strict';
const configureMiddleware = require('../src/utilities/middleware');
function buildSession() {
const app = {
param: jest.fn(),
set: jest.fn(),
use: jest.fn(),
};
return configureMiddleware(app, {
siteConfig: { dashboardHost: 'status.sami', tld: '.sami' },
totpConfig: { enabled: true, sessionDuration: '24h' },
tailscaleConfig: { enabled: false, requireAuth: false },
metrics: { recordRequest: jest.fn() },
auditLogger: { middleware: () => (_req, _res, next) => next() },
authManager: { verifyJWT: jest.fn(), verifyAPIKey: jest.fn() },
log: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
cryptoUtils: { loadOrCreateKey: () => Buffer.alloc(32, 7) },
isValidContainerId: () => true,
isTailscaleIP: () => false,
getTailscaleStatus: async () => null,
});
}
function captureCookie(setCookie) {
const headers = {};
setCookie({ setHeader: (name, value) => { headers[name.toLowerCase()] = value; } }, '24h');
return headers['set-cookie'];
}
describe('TOTP session cookie scope', () => {
test('primary login cookie is host-only for custom TLD deployments', () => {
const session = buildSession();
const cookie = captureCookie(session.setSessionCookie);
expect(cookie).toContain('dashcaddy_session=');
expect(cookie).toContain('HttpOnly');
expect(cookie).toContain('Secure');
expect(cookie).toContain('SameSite=Lax');
expect(cookie).not.toMatch(/(?:^|;)\s*Domain=/i);
});
test('SSO exchange uses the same host-only cookie contract', () => {
const session = buildSession();
const cookie = captureCookie(session.setHostOnlySessionCookie);
expect(cookie).toContain('dashcaddy_session=');
expect(cookie).not.toMatch(/(?:^|;)\s*Domain=/i);
});
test('logout clears the host-only secure cookie', () => {
const session = buildSession();
const headers = {};
session.clearSessionCookie({
setHeader: (name, value) => { headers[name.toLowerCase()] = value; },
});
expect(headers['set-cookie']).toContain('Max-Age=0');
expect(headers['set-cookie']).toContain('Secure');
expect(headers['set-cookie']).not.toMatch(/(?:^|;)\s*Domain=/i);
});
});
@@ -0,0 +1,84 @@
const express = require('express');
const request = require('supertest');
const createSsoRouter = require('../routes/auth/sso-gate');
function createApp({ redeem = true } = {}) {
const app = express();
const session = {
redeemHandoffToken: jest.fn().mockReturnValue(redeem),
setCookieHostOnly: jest.fn((res) => {
res.setHeader('Set-Cookie', 'dashcaddy_session=test; Path=/; HttpOnly; Secure; SameSite=Lax');
}),
isValid: jest.fn().mockReturnValue(true),
};
const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
const errorResponse = (res, status, message, extra = {}) => res.status(status).json({ success: false, error: message, ...extra });
const router = createSsoRouter({
totpConfig: { enabled: true, sessionDuration: '24h' },
session,
asyncHandler,
errorResponse,
log: { warn: jest.fn(), info: jest.fn(), debug: jest.fn(), error: jest.fn() },
getAppSession: jest.fn(),
appSessionCache: new Map(),
credentialManager: { retrieve: jest.fn() },
fetchT: jest.fn(),
getServiceById: jest.fn(),
licenseManager: {
hasFeature: jest.fn().mockReturnValue(true),
requirePremium: jest.fn(() => (_req, _res, next) => next()),
},
servicesStateManager: { read: jest.fn().mockResolvedValue([]) },
});
app.use('/api/v1', router);
return { app, session };
}
describe('cross-host SSO exchange redirect', () => {
test('sets a host-only cookie and redirects to a relative service path', async () => {
const { app, session } = createApp();
const res = await request(app)
.get('/api/v1/auth/sso-exchange')
.query({ token: 'one-time', return: '/settings?tab=network#dns' });
expect(res.status).toBe(303);
expect(res.headers.location).toBe('/settings?tab=network#dns');
expect(res.headers['set-cookie'][0]).not.toMatch(/Domain=/i);
expect(session.redeemHandoffToken).toHaveBeenCalledWith('one-time');
});
test.each([
'https://evil.example/phish',
'//evil.example/phish',
'/\\evil.example/phish',
])('rejects cross-origin return value %s', async (returnValue) => {
const { app } = createApp();
const res = await request(app)
.get('/api/v1/auth/sso-exchange')
.query({ token: 'one-time', return: returnValue });
expect(res.status).toBe(303);
expect(res.headers.location).toBe('/');
});
test('keeps the existing JSON exchange behavior when no return is supplied', async () => {
const { app } = createApp();
const res = await request(app)
.get('/api/v1/auth/sso-exchange')
.query({ token: 'one-time' });
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ success: true, authenticated: true });
});
test('does not set a cookie or redirect for an invalid token', async () => {
const { app, session } = createApp({ redeem: false });
const res = await request(app)
.get('/api/v1/auth/sso-exchange')
.query({ token: 'bad', return: '/settings' });
expect(res.status).toBe(401);
expect(res.headers['set-cookie']).toBeUndefined();
expect(session.setCookieHostOnly).not.toHaveBeenCalled();
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 B

+243 -32
View File
@@ -19,9 +19,10 @@ const path = require('path');
// Master secret file — lives only on admin machine, NEVER shipped
const SECRET_FILE = path.join(__dirname, '.license-secret');
// License code format: DC-AAAAA-BBBBB-CCCCC-DDDDD
// Encodes: version(4bit) + duration_days(12bit) + code_id(32bit) + created_ts(32bit) + hmac(48bit)
// Total: 128 bits = 16 bytes, base32-encoded into 4 groups of 5 chars
// License code format: DC-AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
// Encodes: version(4bit) + duration_days(12bit) + code_id(32bit) + created_ts(32bit) + hmac(40bit)
// Total: 120 bits = 15 bytes, base32-encoded into 5 groups of 5 chars
// (25 base32 chars = 125 bits, comfortably fits 120 bits of data)
const VALID_DURATIONS = [30, 90, 180, 365];
const LIFETIME_DURATION = 0; // Admin-only, not publicly available
@@ -61,12 +62,190 @@ function base32Decode(str) {
function getSecret() {
if (!fs.existsSync(SECRET_FILE)) {
console.error('No master secret found. Run with --init-secret first.');
console.error('No master secret found at', SECRET_FILE);
console.error('Run with --init-secret first.');
process.exit(1);
}
return fs.readFileSync(SECRET_FILE, 'utf8').trim();
}
// Counter location: the default is `path.join(__dirname, '.license-counter')`.
// That's adjacent to this source file on the admin machine (not the secret
// file — the secret and counter share a directory on the developer's
// workstation, but they are independent files). The CLI does not merge them.
// When this module is required from a packaged/installed location where
// __dirname might be read-only, override the counter location via the
// `LICENSE_COUNTER_FILE` env var. The Stripe bridge uses this same path.
function _defaultCounterFile() {
return process.env.LICENSE_COUNTER_FILE || path.join(__dirname, '.license-counter');
}
// Atomic counter write — write to a uniquely-named .tmp then rename. The
// .tmp suffix includes pid + Date.now() + Math.random so two concurrent
// calls in overlapping event-loop ticks (e.g. a Stripe webhook fan-out)
// can't collide on the temp name. POSIX rename is atomic on the same
// filesystem, so the live counter file is never observed in a half-written
// state. If writeFileSync throws, we re-throw without renaming — the
// original counter file is intact. If renameSync throws, we attempt to
// unlink the .tmp so it doesn't accumulate.
function _atomicWriteCounter(counterFile, value) {
const tmpFile = `${counterFile}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
try {
fs.writeFileSync(tmpFile, String(value));
} catch (err) {
throw new Error(`generateCodes: failed to write counter tmp file ${tmpFile}: ${err.message}`);
}
try {
fs.renameSync(tmpFile, counterFile);
} catch (err) {
try { fs.unlinkSync(tmpFile); } catch (_) { /* best effort cleanup */ }
throw new Error(`generateCodes: failed to rename counter tmp to ${counterFile}: ${err.message}`);
}
}
// Concurrency note: this module is single-threaded JavaScript. Two
// synchronous calls to generateCodes() within the same event-loop tick
// cannot interleave — fs.*Sync blocks the thread and the second call runs
// only after the first returns. The "atomic" part of the counter write
// protects against a process crash between writeFileSync and renameSync
// (the original counter file is intact because rename never happened)
// and against OS-level write atomicity. It does NOT protect against a
// concurrent process — license-keygen.js is a single-instance admin tool
// and must not be invoked from multiple processes simultaneously.
// Callers needing cross-process safety (which is none currently) would
// need OS-level locking via fcntl or flock — out of scope.
/**
* Programmatic equivalent of the CLI's "generate codes" path.
*
* Differs from the CLI in two ways:
* 1. No console output — returns the resulting array.
* 2. Persists the counter file atomically (write to a uniquely-named
* .tmp, rename) so a crash mid-write doesn't leave the counter in a
* half-bumped state, and so concurrent calls don't collide on the
* same .tmp name.
*
* Concurrency: relies on Node's single-threaded event loop. Two
* synchronous calls in the same tick cannot interleave — the second call
* reads the post-write counter value. The atomic write helper protects
* against process crashes between writeFileSync and renameSync, and the
* unique .tmp suffix prevents filename collisions across ticks. Cross-process
* races are still possible — license-keygen.js is a single-instance admin
* tool, so callers must not invoke it from multiple processes simultaneously.
*
* Returns synchronously. The underlying counter allocator uses fs.*Sync,
* so the function never throws asynchronously. Wrap with Promise.resolve()
* if your caller needs a Promise.
*
* @param {Object} opts
* @param {string} opts.secret The master secret (hex string). Callers
* are responsible for loading it via
* loadSecret() or getSecret().
* @param {number} opts.durationDays 30, 90, 180, 365, or 0 for LIFETIME.
* Validated against VALID_DURATIONS / LIFETIME.
* @param {number} [opts.count=1] Number of codes to mint.
* @param {number} [opts.startId] Override the auto counter. If omitted,
* reads + increments the counter file.
* @param {string} [opts.counterFile] Override the counter file path.
* Defaults to env LICENSE_COUNTER_FILE or
* path.join(__dirname, '.license-counter').
* @returns {Array<{code: string, codeId: number, durationDays: number}>}
*/
// Throws on bad opts. Returns { secret, durationDays, count } with defaults applied.
function _validateGenerateOpts(opts) {
if (!opts || !opts.secret || typeof opts.secret !== 'string') {
throw new Error('generateCodes: secret is required');
}
const { secret, count = 1 } = opts;
const { durationDays } = opts;
// LIFETIME (0) is accepted; non-LIFETIME must be in the allowed list.
if (durationDays !== 0 && !VALID_DURATIONS.includes(durationDays)) {
throw new Error(`generateCodes: invalid duration ${durationDays}. Valid: ${VALID_DURATIONS.join(', ')}`);
}
if (!Number.isInteger(count) || count < 1 || count > 10000) {
throw new Error(`generateCodes: invalid count ${count} (must be 1..10000)`);
}
return { secret, durationDays, count };
}
// Resolves the next startId. startIdProvided=true means the caller passed
// opts.startId (even if the value is invalid — validation happens here).
// Reads the counter file on the auto path; throws on parse/IO error.
function _resolveStartId(startIdProvided, overrideStartId, counterFile) {
if (startIdProvided) {
if (!Number.isInteger(overrideStartId) || overrideStartId < 0 || overrideStartId > 0xFFFFFFFF) {
throw new Error(`generateCodes: startId out of range or non-integer (must be 0..0xFFFFFFFF, got ${overrideStartId})`);
}
return overrideStartId;
}
try {
if (fs.existsSync(counterFile)) {
const raw = fs.readFileSync(counterFile, 'utf8').trim();
if (!/^\d+$/.test(raw)) {
throw new Error(`counter file ${counterFile} contains non-numeric value '${raw}'`);
}
return parseInt(raw, 10) + 1;
}
return 1;
} catch (err) {
if (err.message && err.message.startsWith('counter file ')) throw err;
throw new Error(`generateCodes: failed to read counter file ${counterFile}: ${err.message}`);
}
}
function generateCodes(opts) {
const { secret, durationDays, count } = _validateGenerateOpts(opts);
const overrideCounterFile = opts && opts.counterFile;
const counterFile = overrideCounterFile || _defaultCounterFile();
// Validate startId BEFORE selecting the allocation path. Any explicitly
// supplied startId (including floats, NaN, null, numeric strings) must
// either be a valid integer in range or throw — we use
// Object.prototype.hasOwnProperty to distinguish "caller passed startId"
// from "caller omitted startId" so the overrideStartId validation runs
// regardless of value.
const startIdProvided = opts && Object.prototype.hasOwnProperty.call(opts, 'startId');
const overrideStartId = startIdProvided ? opts.startId : undefined;
const startId = _resolveStartId(startIdProvided, overrideStartId, counterFile);
// Validate that the requested range fits in the code_id field (32 bits).
const lastCodeId = startId + count - 1;
if (lastCodeId > 0xFFFFFFFF) {
throw new Error(`generateCodes: codeId range exceeds 32-bit limit (startId=${startId}, count=${count}, lastCodeId=${lastCodeId})`);
}
const codes = [];
for (let i = 0; i < count; i++) {
const codeId = startId + i;
const code = generateCode(secret, durationDays, codeId);
codes.push({ code, codeId, durationDays });
}
// Persist the new counter value (skipped when startId was overridden).
if (!startIdProvided) {
_atomicWriteCounter(counterFile, lastCodeId);
}
return codes;
}
/**
* Load the master secret from disk. Exported so the Stripe bridge can
* call it without going through getSecret() (which prints to stderr and
* exits on missing-secret — wrong semantics for a library call).
*
* @param {string} [overridePath] Defaults to the SECRET_FILE constant.
* @returns {string} The hex secret.
* @throws If the file is missing or unreadable.
*/
function loadSecret(overridePath) {
const file = overridePath || SECRET_FILE;
if (!fs.existsSync(file)) {
throw new Error(`Master secret file not found at ${file}. Run --init-secret first.`);
}
return fs.readFileSync(file, 'utf8').trim();
}
function initSecret() {
if (fs.existsSync(SECRET_FILE)) {
console.error('Master secret already exists at', SECRET_FILE);
@@ -193,19 +372,23 @@ function main() {
DashCaddy License Code Generator
Usage:
node license-keygen.js --init-secret Initialize master secret (first time only)
node license-keygen.js --duration <days> [options] Generate license codes
node license-keygen.js --verify <code> Verify a license code
node license-keygen.js --decode <code> Decode and display code details
node license-keygen.js --init-secret Initialize master secret (first time only)
node license-keygen.js --duration <days> [options] Generate Pro license codes
node license-keygen.js --lifetime [options] Generate a LIFETIME code (creator-only)
node license-keygen.js --verify <code> Verify a license code
node license-keygen.js --decode <code> Decode and display code details
Options:
--duration <days> Code validity: 30, 90, 180, or 365 days (required for generation)
--duration <days> Code validity: 30, 90, 180, or 365 days (required for generation, mutually exclusive with --lifetime)
--tier <tier> Tier label; only 'pro' is supported (optional label; valid in combination with --duration or --lifetime)
--lifetime Generate a LIFETIME code — REJECTED at activation on production hosts
--count <n> Number of codes to generate (default: 1)
--start-id <n> Starting code ID (default: auto from counter file)
--output <file> Write codes to file instead of stdout
--json Output as JSON
Valid durations: ${VALID_DURATIONS.join(', ')} days
Valid tiers: pro (cosmetic alias; does not change generation behavior)
`);
process.exit(0);
}
@@ -244,9 +427,31 @@ Valid durations: ${VALID_DURATIONS.join(', ')} days
// Generate codes
const isLifetime = args.includes('--lifetime');
// --tier is a cosmetic label right now (only 'pro' is supported). It does
// NOT change generation behavior — every code minted with --duration is
// already a Pro code, and --lifetime is enforced separately at activation
// time. The flag exists to make operator intent obvious in shell history
// and to reserve a forward-compatible hook for a future tier that needs
// to alter code generation (e.g. a 'free' tier with a different prefix).
// It is only meaningful in combination with --duration or --lifetime —
// by itself, generation still requires one of those flags.
const tierIndex = args.indexOf('--tier');
if (tierIndex !== -1) {
const tier = (args[tierIndex + 1] || '').toLowerCase();
if (tier !== 'pro') {
console.error(`Invalid tier: '${tier}'. Supported: pro.`);
process.exit(1);
}
}
const durationIndex = args.indexOf('--duration');
if (!isLifetime && durationIndex === -1) {
console.error('--duration is required. Use --help for usage.');
console.error('--duration is required (or use --lifetime). Use --help for usage.');
process.exit(1);
}
if (isLifetime && durationIndex !== -1) {
console.error('--lifetime and --duration are mutually exclusive.');
process.exit(1);
}
const duration = isLifetime ? LIFETIME_DURATION : parseInt(args[durationIndex + 1]);
@@ -258,29 +463,20 @@ Valid durations: ${VALID_DURATIONS.join(', ')} days
const countIndex = args.indexOf('--count');
const count = countIndex !== -1 ? parseInt(args[countIndex + 1]) : 1;
// Load or create counter file for auto-incrementing code IDs
const counterFile = path.join(__dirname, '.license-counter');
let startId;
const startIdIndex = args.indexOf('--start-id');
if (startIdIndex !== -1) {
startId = parseInt(args[startIdIndex + 1]);
} else if (fs.existsSync(counterFile)) {
startId = parseInt(fs.readFileSync(counterFile, 'utf8').trim()) + 1;
} else {
startId = 1;
}
const overrideStartId = startIdIndex !== -1 ? parseInt(args[startIdIndex + 1]) : undefined;
const secret = getSecret();
const codes = [];
for (let i = 0; i < count; i++) {
const codeId = startId + i;
const code = generateCode(secret, duration, codeId);
codes.push({ code, codeId, durationDays: duration });
// Only pass startId when --start-id was supplied on the CLI. generateCodes
// uses Object.prototype.hasOwnProperty.call(opts, 'startId') to distinguish
// "caller passed startId" from "caller omitted startId" and rejects
// non-integer values. Passing startId: undefined would mean "caller passed
// undefined", which the validation path then rejects.
const generateOpts = { secret, durationDays: duration, count };
if (overrideStartId !== undefined) {
generateOpts.startId = overrideStartId;
}
// Save counter
fs.writeFileSync(counterFile, String(startId + count - 1));
const codes = generateCodes(generateOpts);
// Output
const outputIndex = args.indexOf('--output');
@@ -302,11 +498,26 @@ Valid durations: ${VALID_DURATIONS.join(', ')} days
}
}
console.log(`\nGenerated ${count} code(s) for ${duration === 0 ? 'LIFETIME' : duration + ' days'}. Next ID: ${startId + count}`);
const lastCodeId = codes[codes.length - 1].codeId;
console.log(`\nGenerated ${count} code(s) for ${duration === 0 ? 'LIFETIME' : duration + ' days'}. Next ID: ${lastCodeId + 1}`);
}
// Also export for use by license-manager.js
module.exports = { verifyCode, parseCode, VALID_DURATIONS, VERSION };
// Also export for use by license-manager.js and the Stripe webhook bridge.
// `generateCode` is exported so the bridge can mint codes in-process rather
// than spawning a child process (faster, atomic counter, easier to test).
// `generateCodes` (note the trailing 's') is the bulk-friendly wrapper that
// handles the counter-file write and returns a stable array of {code, codeId,
// durationDays} records — used by the bridge when one Stripe event must
// produce one code (typical case is just 1, but the API is uniform).
module.exports = {
verifyCode,
parseCode,
generateCode,
generateCodes,
loadSecret,
VALID_DURATIONS,
VERSION,
};
if (require.main === module) {
main();
+110 -34
View File
@@ -1,6 +1,7 @@
const express = require('express');
const { SESSION_TTL, APP, PLEX, TIMEOUTS, buildMediaAuth } = require('../../src/utilities/constants');
const { AuthenticationError, NotFoundError } = require('../../src/utilities/errors');
const { ok } = require('../../src/utils/responses');
/**
* Auth SSO gate routes factory
@@ -9,10 +10,10 @@ const { AuthenticationError, NotFoundError } = require('../../src/utilities/erro
*/
module.exports = function(deps) {
const router = express.Router();
// Extract dependencies
const { authManager, totpConfig, session, asyncHandler, errorResponse, log, getAppSession, appSessionCache, credentialManager, fetchT, getServiceById, licenseManager, servicesStateManager } = deps;
// Create ctx-like object for compatibility
const ctx = {
credentialManager,
@@ -202,6 +203,37 @@ module.exports = function(deps) {
}
}, 'auth-app-token'));
// Cross-subdomain SSO handoff: exchanges a short-lived single-use token
// (minted by /totp/verify) for a HOST-ONLY session cookie on whichever
// *.sami origin calls this. Needed because Domain=.sami cookies are
// silently rejected by real browsers (.sami is an unregistered TLD, so
// browsers treat "sami" as the effective public suffix and refuse to set
// a cookie scoped to it) — see middleware.js for the full explanation.
// Public route (no session required to call it) since a fresh visitor to
// a gated service has no session yet by definition; the token itself is
// the credential, and it's one-time-use with a 60s TTL.
router.get('/auth/sso-exchange', (req, res) => {
res.setHeader('Cache-Control', 'no-store');
const token = req.query.token;
if (!session.redeemHandoffToken(token)) {
return errorResponse(res, 401, 'Invalid or expired handoff token');
}
session.setCookieHostOnly(res, totpConfig.sessionDuration);
if (req.query.return) {
let returnPath = '/';
try {
const parsed = new URL(req.query.return, 'https://dashcaddy.invalid');
if (parsed.origin === 'https://dashcaddy.invalid') {
returnPath = `${parsed.pathname}${parsed.search}${parsed.hash}`;
}
} catch (_) {
// Invalid or cross-origin return values fall back to the service root.
}
return res.redirect(303, returnPath);
}
ok(res, { authenticated: true });
});
// Serve service-specific auto-login page (auth enforced by Caddy forward_auth upstream)
router.get('/auth/login-page', (req, res) => {
const service = (req.query.service || '').replace(/[^a-z]/g, '');
@@ -209,6 +241,14 @@ module.exports = function(deps) {
if (!html) return res.status(404).send('Unknown service');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
// This page is a server-rendered shell whose entire auto-login logic runs
// in an inline <script> (no external bundle - it's built per-service in
// buildLoginPage()). The app-wide Helmet CSP sets script-src 'self' with
// no inline exception, which silently blocks that script from ever
// running - no console-visible error on the page, no JS timeout fires,
// it just sits on "Signing in to ..." forever. Relax script-src for this
// one response only; every other route keeps the strict app-wide policy.
res.setHeader('Content-Security-Policy', "default-src 'self'; style-src 'self'; script-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; font-src 'self' data:; object-src 'none'; media-src 'self'; frame-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'");
res.send(html);
});
@@ -222,57 +262,93 @@ function buildLoginPage(service) {
// session and we render the auto-login body; if 401, the meta-refresh kicks
// in and sends them to status.sami to authenticate first.
const SHELL = (body) => `<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta http-equiv="Cache-Control" content="no-store"><title>__TITLE__</title>
<style>body{background:__BG__;color:#e0e0e0;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:12px}a{color:__ACCENT__}#d{font-size:12px;color:#888;max-width:80vw;overflow:auto;white-space:pre-wrap}</style>
</head><body><p id="m">__TITLE__</p><div id="d"></div>
<script>(function(){
var ls=localStorage,d=document.getElementById('d'),m=document.getElementById('m');
function go(u){setTimeout(function(){location.replace(u)},300)}
function fail(msg,info){m.innerHTML=msg;d.textContent=info||''}
function ft(svc){return fetch('/dashcaddy-api/api/auth/app-token/'+svc,{credentials:'include'})}
function merge(ck,j,name){try{var c=JSON.parse(ls.getItem(ck)||'{}');if(c.Servers&&c.Servers.length){var s=c.Servers[0];s.AccessToken=j.token;s.UserId=j.userId||s.UserId||'';s.DateLastAccessed=Date.now();ls.setItem(ck,JSON.stringify(c));return}}catch(e){}ls.setItem(ck,JSON.stringify({Servers:[{Id:j.serverId||'',Name:j.serverName||name,UserId:j.userId||'',AccessToken:j.token,ManualAddress:location.origin,LastConnectionMode:2,DateLastAccessed:Date.now()}]}))}
// Pre-check session before attempting auto-login. If the user is not logged
// in, redirect to status.sami for TOTP auth first. The return= param sends
// them back to this login page after authenticating so auto-login can run.
fetch('/dashcaddy-api/api/auth/totp/check-session',{credentials:'include',cache:'no-store'}).then(function(r){return r.json()}).then(function(st){
if(!st||!st.success||!st.authenticated){go('https://status.sami?auth=required&return='+encodeURIComponent(location.href));return}
${body}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Auth check error: '+e.message)})
})()</script></body></html>`;
<html><head><meta http-equiv="Cache-Control" content="no-store"><title>__TITLE__</title>
<style>body{background:__BG__;color:#e0e0e0;font-family:system-ui;display:flex;align-items:center;justify-items:center;height:100vh;margin:0;flex-direction:column;gap:12px}a{color:__ACCENT__}#d{font-size:12px;color:#888;max-width:80vw;overflow:auto;white-wrap:pre-wrap}</style>
</head><body><p id="m">__TITLE__</p><div id="d"></div>
<script>(function(){
var ls=localStorage,d=document.getElementById('d'),m=document.getElementById('m');
// 2026-07-22 hardening: every fetch now has a hard AbortSignal timeout
// (default 8s) so a hung upstream can NEVER leave the page stuck on
// "Signing in to Plex..." indefinitely. Also: if check-session returns
// authenticated but app-token fails for any reason (no creds stored,
// upstream timeout, etc.), we now ALWAYS redirect to /web/?direct=1 if a
// stale token exists in localStorage, instead of failing silently.
function go(u){setTimeout(function(){location.replace(u)},300)}
function fail(msg,info){try{m.innerHTML=msg;d.textContent=info||''}catch(_){}}
function withTimeout(ms){var c=new AbortController();setTimeout(function(){c.abort()},ms);return c.signal}
function ft(svc){return fetch('/dashcaddy-api/api/auth/app-token/'+svc,{credentials:'include',signal:withTimeout(8000)})}
function merge(ck,j,name){try{var c=JSON.parse(ls.getItem(ck)||'{}');if(c.Servers&&c.Servers.length){var s=c.Servers[0];s.AccessToken=j.token;s.UserId=j.userId||s.UserId||'';s.DateLastAccessed=Date.now();ls.setItem(ck,JSON.stringify(c));return}}catch(e){}ls.setItem(ck,JSON.stringify({Servers:[{Id:j.serverId||'',Name:j.serverName||name,UserId:j.userId||'',AccessToken:j.token,ManualAddress:location.origin,LastConnectionMode:2,DateLastAccessed:Date.now()}]}))}
// Belt-and-suspenders hard timeout: if nothing in this script succeeds
// within 15s, force-redirect to status.sami so the user can re-auth.
var overallTimer=setTimeout(function(){go('https://status.sami?auth=required&return='+encodeURIComponent(location.href))},15000);
// Cross-subdomain SSO handoff: status.sami can't share its session cookie
// with this origin (Domain=.sami cookies are silently rejected by real
// browsers - .sami isn't a registered TLD, so browsers treat "sami" as the
// effective public suffix). Instead status.sami hands us a one-time token
// in the URL after a successful TOTP verify; exchange it here for a cookie
// scoped to just this host, then strip it from the URL so it can't be
// reused or leak via history/referrer. If there's no token (or the
// exchange fails - expired, already used, etc.) this is a no-op and we
// fall through to the normal check-session flow below exactly as before.
var dcParams=new URLSearchParams(location.search);
var dcToken=dcParams.get('dc_token');
var preExchange=Promise.resolve();
if(dcToken){
dcParams.delete('dc_token');
var dcQs=dcParams.toString();
try{history.replaceState({},'',location.pathname+(dcQs?'?'+dcQs:''))}catch(_){}
preExchange=fetch('/dashcaddy-api/api/auth/sso-exchange?token='+encodeURIComponent(dcToken),{credentials:'include',signal:withTimeout(5000)}).catch(function(){});
}
// Pre-check session before attempting auto-login. If the user is not logged
// in, redirect to status.sami for TOTP auth first. The return= param sends
// them back to this login page after authenticating so auto-login can run.
preExchange.then(function(){
return fetch('/dashcaddy-api/api/auth/totp/check-session',{credentials:'include',cache:'no-store',signal:withTimeout(5000)})
}).then(function(r){return r.json()}).then(function(st){
if(!st||!st.success||!st.authenticated){go('https://status.sami?auth=required&return='+encodeURIComponent(location.href));return}
${body}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Auth check error: '+(e&&e.message||'unknown'))})
})()</script></body></html>`;
const pages = {
chat: {
title: 'Signing in...', bg: '#0a0a0a', accent: '#60a5fa',
body: `if(ls.getItem('token')){go('/?direct=1');return}
d.textContent='Fetching token from DashCaddy...';
ft('chat').then(function(r){d.textContent+=' Status: '+r.status;return r.text()}).then(function(t){
d.textContent+='\\n'+t.substring(0,300);
try{var j=JSON.parse(t);if(j.token){ls.setItem('token',j.token);go('/?direct=1')}
else{fail('Auto-login unavailable. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','No token field in response')}}
catch(e){fail('Auto-login error. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Parse error: '+e.message)}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Fetch error: '+e.message)})`
ft('chat').then(function(r){return r.text()}).then(function(t){
try{var j=JSON.parse(t);if(j.token){ls.setItem('token',j.token);go('/?direct=1');return}
// No token but chat is reachable — fall through to manual UI link below
fail('Auto-login unavailable. <a href="/?direct=1">Open Chat manually</a>','No token field: '+t.substring(0,200))}
catch(e){fail('Auto-login parse error. <a href="/?direct=1">Open Chat manually</a>','Error: '+e.message+' / body: '+t.substring(0,200))}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="/?direct=1">Open Chat manually</a>','Fetch error: '+(e&&e.message||'unknown'))})`
},
plex: {
title: 'Signing in to Plex...', bg: '#1f1f1f', accent: '#e5a00d',
body: `if(ls.getItem('myPlexAccessToken')){go('/web/?direct=1');return}
ft('plex').then(function(r){return r.json()}).then(function(j){
if(j.token){ls.setItem('myPlexAccessToken',j.token);d.textContent='Token stored, redirecting...';go('/web/?direct=1')}
else{fail('Auto-login unavailable. <a href="/web/?direct=1">Open Plex manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>',JSON.stringify(j))}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Error: '+e.message)})`
if(j.token){ls.setItem('myPlexAccessToken',j.token);d.textContent='Token stored, redirecting...';go('/web/?direct=1');return}
// No token returned. Three fallbacks in priority order:
// 1. Stale token in localStorage — Plex may still accept it.
if(ls.getItem('myPlexAccessToken')){go('/web/?direct=1');return}
// 2. Manual link so the user is never trapped on this page.
fail('Auto-login unavailable. <a href="/web/?direct=1">Open Plex manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>','API: '+JSON.stringify(j))
}).catch(function(e){fail('Could not reach DashCaddy. <a href="/web/?direct=1">Open Plex manually</a>','Error: '+(e&&e.message||'unknown'))})`
},
jellyfin: {
title: 'Signing in to Jellyfin...', bg: '#101014', accent: '#00a4dc',
body: `ft('jellyfin').then(function(r){return r.json()}).then(function(j){
if(j.token){merge('jellyfin_credentials',j,'Jellyfin');merge('_jellyfin_credentials',j,'Jellyfin');d.textContent='Token stored, redirecting...';go('/web/')}
else{fail('Auto-login unavailable. <a href="/web/">Open Jellyfin manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>',JSON.stringify(j))}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Error: '+e.message)})`
if(j.token){merge('jellyfin_credentials',j,'Jellyfin');merge('_jellyfin_credentials',j,'Jellyfin');d.textContent='Token stored, redirecting...';go('/web/');return}
if(ls.getItem('jellyfin_credentials')||ls.getItem('_jellyfin_credentials')){go('/web/');return}
fail('Auto-login unavailable. <a href="/web/">Open Jellyfin manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>','API: '+JSON.stringify(j))
}).catch(function(e){fail('Could not reach DashCaddy. <a href="/web/">Open Jellyfin manually</a>','Error: '+(e&&e.message||'unknown'))})`
},
emby: {
title: 'Signing in to Emby...', bg: '#101014', accent: '#52b54b',
body: `ft('emby').then(function(r){return r.json()}).then(function(j){
if(j.token){merge('emby_credentials',j,'Emby');merge('_emby_credentials',j,'Emby');d.textContent='Token stored, redirecting...';go('/web/')}
else{fail('Auto-login unavailable. <a href="/web/">Open Emby manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>',JSON.stringify(j))}
}).catch(function(e){fail('Could not reach DashCaddy. <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">Sign in at DashCaddy</a>','Error: '+e.message)})`
if(j.token){merge('emby_credentials',j,'Emby');merge('_emby_credentials',j,'Emby');d.textContent='Token stored, redirecting...';go('/web/');return}
if(ls.getItem('emby_credentials')||ls.getItem('_emby_credentials')){go('/web/');return}
fail('Auto-login unavailable. <a href="/web/">Open Emby manually</a> or <a href="https://status.sami?auth=required&return='+encodeURIComponent(location.href)+'">re-authenticate at DashCaddy</a>','API: '+JSON.stringify(j))
}).catch(function(e){fail('Could not reach DashCaddy. <a href="/web/">Open Emby manually</a>','Error: '+(e&&e.message||'unknown'))})`
},
};
+14 -2
View File
@@ -220,8 +220,17 @@ const SETUP_WINDOW_MS = 60 * 60 * 1000;
// Rotate CSRF token for the new session
const newCsrfToken = renewCSRFToken(res, req.secure || req.protocol === 'https');
// Cross-subdomain SSO handoff token (see middleware.js "Cross-subdomain
// SSO token handoff" for why): the Domain=.sami cookie set above is
// silently dropped by real browsers on any OTHER *.sami subdomain, so
// status.sami's login-page frontend appends this token to the redirect
// URL when bouncing the user back to a gated service. That service's
// login page exchanges it via /auth/sso-exchange for its own host-only
// session cookie. Single-use, 60s TTL — see ctx.session.createHandoffToken.
const ssoToken = ctx.session.createHandoffToken();
log.debug('auth', 'Session created', { sessions: ctx.session.ipSessions.size });
ok(res, { message: 'Authenticated successfully', sessionDuration: ctx.totpConfig.sessionDuration, csrfToken: newCsrfToken });
ok(res, { message: 'Authenticated successfully', sessionDuration: ctx.totpConfig.sessionDuration, csrfToken: newCsrfToken, ssoToken });
}, 'totp-verify'));
// Check session validity (used by Caddy forward_auth)
@@ -243,7 +252,10 @@ const SETUP_WINDOW_MS = 60 * 60 * 1000;
const valid = ctx.session.isValid(req);
log.debug('auth', 'Session check', { ip: ctx.session.getClientIP(req), valid, sessions: ctx.session.ipSessions.size });
if (valid) {
return res.status(200).json({ authenticated: true });
// Response contract: { success: true, authenticated: true } — login-page
// consumer in /api/v1/auth/login-page reads `if(!st.success||!st.authenticated)`
// and would otherwise redirect valid sessions to status.sami in a TOTP loop.
return ok(res, { authenticated: true });
}
throw new AuthenticationError('Session expired or invalid');
-143
View File
@@ -1,143 +0,0 @@
/**
* Shared route context — holds all dependencies needed by route modules.
* Populated once by server.js at startup, then passed to each route factory.
*
* Usage in a route module:
* module.exports = function(ctx) {
* const router = require('express').Router();
* router.get('/status', ctx.asyncHandler(async (req, res) => { ... }));
* return router;
* };
*
* Namespaces: ctx.docker.*, ctx.caddy.*, ctx.dns.*, ctx.session.*,
* ctx.notification.*, ctx.tailscale.*
*/
const ctx = {
// ── Namespaced groups ──
docker: {
client: null, // Dockerode instance
pull: null, // dockerPull(imageName, timeoutMs)
findContainer: null, // findContainerByName(name, opts)
getUsedPorts: null, // getUsedPorts() → Set<number>
security: null, // dockerSecurity module
},
caddy: {
modify: null, // modifyCaddyfile(modifyFn) → {success, error?}
read: null, // readCaddyfile() → string
reload: null, // reloadCaddy(content)
generateConfig: null, // generateCaddyConfig(subdomain, ip, port, opts)
verifySite: null, // verifySiteAccessible(domain, maxAttempts)
adminUrl: null, // CADDY_ADMIN_URL string
filePath: null, // CADDYFILE_PATH string
},
dns: {
call: null, // callDns(server, apiPath, params)
buildUrl: null, // buildDnsUrl(server, apiPath, params)
requireToken: null, // requireDnsToken(providedToken)
ensureToken: null, // ensureValidDnsToken()
createRecord: null, // createDnsRecord(subdomain, ip)
getToken: null, // () => dnsToken
setToken: null, // (t) => { dnsToken = t }
getTokenExpiry: null, // () => dnsTokenExpiry
setTokenExpiry: null, // (e) => { dnsTokenExpiry = e }
getTokenForServer: null, // getTokenForServer(serverIp)
refresh: null, // refreshDnsToken()
credentialsFile: null,// DNS_CREDENTIALS_FILE path
},
session: {
ipSessions: null, // Map of IP → session
durations: null, // SESSION_DURATIONS map
getClientIP: null, // getClientIP(req)
create: null, // createIPSession(ip, duration)
setCookie: null, // setSessionCookie(res, duration)
clear: null, // clearIPSession(ip)
clearCookie: null, // clearSessionCookie(res)
isValid: null, // isSessionValid(req)
},
notification: {
getConfig: null, // () => notificationConfig
saveConfig: null, // saveNotificationConfig()
send: null, // sendNotification(event, title, message, type)
sendDiscord: null, // sendDiscordNotification(title, message, type)
sendTelegram: null, // sendTelegramNotification(title, message, type)
sendNtfy: null, // sendNtfyNotification(title, message, type)
getHistory: null, // () => notificationHistory
clearHistory: null, // () => { notificationHistory = [] }
startHealthDaemon: null, // startHealthCheckDaemon()
stopHealthDaemon: null, // stopHealthCheckDaemon()
checkHealth: null, // checkContainerHealth()
getHealthState: null, // () => containerHealthState
},
tailscale: {
config: null, // tailscaleConfig object
save: null, // saveTailscaleConfig()
getStatus: null, // getTailscaleStatus()
getLocalIP: null, // getLocalTailscaleIP()
isTailscaleIP: null, // isTailscaleIP(ip)
getAccessToken: null, // getTailscaleAccessToken()
syncAPI: null, // syncFromTailscaleAPI()
startSync: null, // startTailscaleSyncTimer()
stopSync: null, // stopTailscaleSyncTimer()
},
// ── Flat (shared across domains) ──
app: null,
siteConfig: null,
servicesStateManager: null,
configStateManager: null,
credentialManager: null,
authManager: null,
// Feature modules
healthChecker: null,
updateManager: null,
backupManager: null,
resourceMonitor: null,
auditLogger: null,
portLockManager: null,
selfUpdater: null,
// Templates
APP_TEMPLATES: null,
TEMPLATE_CATEGORIES: null,
DIFFICULTY_LEVELS: null,
// Shared helpers
asyncHandler: null,
errorResponse: null,
ok: null,
fetchT: null,
log: null,
logError: null,
safeErrorMessage: null,
buildDomain: null,
buildServiceUrl: null,
getServiceById: null,
readConfig: null,
saveConfig: null,
addServiceToConfig: null,
resyncHealthChecker: null,
validateURL: null,
// Middleware
strictLimiter: null,
// TOTP (flat — used alongside session namespace)
totpConfig: null,
saveTotpConfig: null,
// Config lifecycle
loadSiteConfig: null,
loadDnsCredentials: null,
loadNotificationConfig: null,
// Config paths (flat)
SERVICES_FILE: null,
CONFIG_FILE: null,
TOTP_CONFIG_FILE: null,
TAILSCALE_CONFIG_FILE: null,
NOTIFICATIONS_FILE: null,
ERROR_LOG_FILE: null,
};
module.exports = ctx;
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -euo pipefail
# DC-056 legal-pages deploy.
#
# Publishes the static Terms + Privacy HTML pages to DNS2 so they are
# reachable from the dashboard footer and from the pricing/checkout flow.
#
# Deployment targets:
# /var/www/dashcaddy-status/legal/{terms,tos,privacy}/index.html
# served at https://status.sami/legal/{terms,tos,privacy}
#
# A separate `legal.dashcaddy.net` subdomain is INTENTIONALLY NOT created
# at v1.0 — it would need its own DNS record + Caddy vhost + LE cert, and
# the status.sami/legal/... mount covers the launch requirement without
# extra infra. Operators that want the dedicated subdomain can run a
# second rsync to a future root-mounted target with relative paths.
#
# Verification curls status.sami/legal/{terms,tos,privacy} — not the
# (not-yet-existing) legal.dashcaddy.net — so the post-deploy gate
# matches the actually-served routes.
DNS2_HOST="${DNS2_HOST:-root@100.121.150.22}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
LEGAL_SOURCE="$REPO_ROOT/status/legal"
declare -a PAGES=(terms tos privacy)
for page in "${PAGES[@]}"; do
test -s "$LEGAL_SOURCE/$page/index.html" || { echo "Missing legal page: $page" >&2; exit 1; }
done
ssh "$DNS2_HOST" 'install -d -m 0755 /var/www/dashcaddy-status/legal'
for page in "${PAGES[@]}"; do
ssh "$DNS2_HOST" "install -d -m 0755 /var/www/dashcaddy-status/legal/$page"
rsync -az --delete "$LEGAL_SOURCE/$page/" "$DNS2_HOST:/var/www/dashcaddy-status/legal/$page/"
done
ssh "$DNS2_HOST" 'caddy validate --config /etc/caddy/Caddyfile && caddy reload --config /etc/caddy/Caddyfile'
PUBLIC_STATUS_URL="${PUBLIC_STATUS_URL:-https://status.sami}"
# Page-specific markers so a misrouted Terms page doesn't pass for Privacy.
# We use a temp file instead of `curl | grep -q` because grep -q exits early and
# can trigger SIGPIPE under pipefail, producing false-positive verification
# failures on otherwise-successful deploys (set -o pipefail amplifies this).
declare -A PAGE_MARKERS=(
[terms]="Terms of Service"
[tos]="Terms of Service" # alias page content
[privacy]="Privacy Policy"
)
TMP_CURL_BODY="$(mktemp)"
trap 'rm -f "$TMP_CURL_BODY"' EXIT
for path in "${PAGES[@]}"; do
marker="${PAGE_MARKERS[$path]}"
if ! curl --fail --silent --show-error --location "${PUBLIC_STATUS_URL}/legal/${path}" -o "$TMP_CURL_BODY"; then
echo "Post-deploy verification failed: ${PUBLIC_STATUS_URL}/legal/${path} (HTTP error)" >&2
exit 1
fi
if ! grep -qF "${marker}" "$TMP_CURL_BODY"; then
echo "Post-deploy verification failed: ${PUBLIC_STATUS_URL}/legal/${path} (expected '${marker}')" >&2
exit 1
fi
done
printf 'Legal pages deployed to status.sami/legal.\n'
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
TERMS="$ROOT/status/legal/terms/index.html"
PRIVACY="$ROOT/status/legal/privacy/index.html"
TOS_ALIAS="$ROOT/status/legal/tos/index.html"
require() { grep -Eqi "$2" "$1" || { echo "Missing required content in $1: $2" >&2; exit 1; }; }
test -s "$TERMS" && test -s "$PRIVACY" && test -s "$TOS_ALIAS"
for section in 'License grant' 'Acceptable use' 'best-effort' 'Refund policy' 'Termination' 'Limitation of liability' 'Governing law'; do require "$TERMS" "$section"; done
require "$TERMS" 'within 14 calendar days'
for section in 'GDPR' 'lawful bases' 'Stripe' 'Tailscale' 'data portability|portability' '30 days after cancellation' 'privacy@sami-ahmed.net'; do require "$PRIVACY" "$section"; done
# Reject any SOC 2 / HIPAA compliance claims (the launch explicitly excludes them).
# Negated `! grep` does not trigger errexit under `set -e` (ShellCheck SC2251), so use an
# explicit if/then to make the forbidden-claim guard actually fail the script.
# Regex covers: SOC 2 / SOC-2 / SOC2 + (certified|compliant|compliance|compliant),
# HIPAA + (certified|compliant|compliance|compliant), with optional hyphen.
if grep -Eqi 'SOC[ -]?2[[:space:]-]+(certified|compliant|compliance)|HIPAA[[:space:]-]+(certified|compliant|compliance)' "$TERMS" "$PRIVACY"; then
echo "Forbidden SOC 2/HIPAA compliance language detected in Terms or Privacy pages." >&2
exit 1
fi
require "$ROOT/status/index.html" 'href="/legal/terms"'
require "$ROOT/status/index.html" 'href="/legal/privacy"'
require "$TOS_ALIAS" 'url=/legal/terms'
echo 'Legal page sanity checks passed.'
+10 -1
View File
@@ -133,6 +133,7 @@ async function createApp() {
// simply blocks creation via the route-level _requirePro gate.
const shareStore = createShareStore({
dataDir: platformPaths.dataDir,
platformPaths,
log,
});
@@ -216,15 +217,23 @@ async function createApp() {
// /api/v1/auth/app-token/<id> -> /api/v1/auth/app-token/<id> (drift)
// /api/auth/totp/check-session -> /api/v1/totp/check-session (mounted at /totp/check-session — no /auth prefix)
// /api/v1/auth/totp/check-session->/api/v1/totp/check-session (drift)
// /api/auth/sso-exchange -> /api/v1/auth/sso-exchange (mounted at /auth/sso-exchange, same shape as gate/app-token)
//
// The totp case drops `/auth` because the canonical route is /totp/check-session
// (no /auth prefix) but the legacy JS still uses /api/auth/totp/check-session
// (and a stale-browser version of the page uses /api/v1/auth/totp/check-session).
// Without these rewrites the JS gets a 404 and the page hangs at
// "Signing in to Plex..." forever (user-reported 2026-07-09).
//
// sso-exchange added 2026-07-24: same Caddy handle_path /dashcaddy-api/*
// strips only the /dashcaddy-api prefix, so the login-page JS's fetch to
// /dashcaddy-api/api/auth/sso-exchange arrives here as /api/auth/sso-exchange
// — needs the same rewrite as gate/app-token, not the check-session one
// (this route's canonical mount already includes /auth/).
app.use((req, res, next) => {
if (req.url.startsWith('/api/auth/gate/') || req.url.startsWith('/api/v1/auth/gate/')
|| req.url.startsWith('/api/auth/app-token/') || req.url.startsWith('/api/v1/auth/app-token/')) {
|| req.url.startsWith('/api/auth/app-token/') || req.url.startsWith('/api/v1/auth/app-token/')
|| req.url.startsWith('/api/auth/sso-exchange')) {
req.url = '/api/v1' + req.url.slice(4); // '/api'.length === 4
} else if (req.url.startsWith('/api/auth/totp/check-session')) {
// Legacy: /api/auth/totp/check-session -> /api/v1/totp/check-session
+6
View File
@@ -33,6 +33,9 @@ function assembleContext({
// State managers
servicesStateManager,
configStateManager,
// DC-053 share store
shareStore,
// Managers
credentialManager,
@@ -191,6 +194,9 @@ function assembleContext({
// State managers
servicesStateManager,
configStateManager,
// DC-053 share store
shareStore,
// Managers
credentialManager,
+8 -1
View File
@@ -4,7 +4,11 @@
*/
function createSessionContext(middlewareResult) {
const { ipSessions, SESSION_DURATIONS, getClientIP, createIPSession, setSessionCookie, clearIPSession, clearSessionCookie, isSessionValid } = middlewareResult;
const {
ipSessions, SESSION_DURATIONS, getClientIP, createIPSession, setSessionCookie,
clearIPSession, clearSessionCookie, isSessionValid,
createHandoffToken, redeemHandoffToken, setHostOnlySessionCookie
} = middlewareResult;
return {
ipSessions,
@@ -15,6 +19,9 @@ function createSessionContext(middlewareResult) {
clear: clearIPSession,
clearCookie: clearSessionCookie,
isValid: isSessionValid,
createHandoffToken,
redeemHandoffToken,
setCookieHostOnly: setHostOnlySessionCookie,
};
}
@@ -1,314 +0,0 @@
#!/usr/bin/env node
/**
* DashCaddy License Code Generator
*
* Admin-only CLI tool for generating license codes.
* NOT shipped with the product — runs only on the developer's machine.
*
* Usage:
* node license-keygen.js --duration 365 --count 10
* node license-keygen.js --duration 30 --count 1 --output codes.txt
* node license-keygen.js --verify DC-XXXXX-XXXXX-XXXXX-XXXXX
* node license-keygen.js --init-secret
*/
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const platformPaths = require('../../platform-paths');
// Master secret file — lives only on admin machine, NEVER shipped
const SECRET_FILE = process.env.LICENSE_SECRET_FILE || path.join(platformPaths.dataDir, '.license-secret');
// License code format: DC-AAAAA-BBBBB-CCCCC-DDDDD
// Encodes: version(4bit) + duration_days(12bit) + code_id(32bit) + created_ts(32bit) + hmac(48bit)
// Total: 128 bits = 16 bytes, base32-encoded into 4 groups of 5 chars
const VALID_DURATIONS = [30, 90, 180, 365];
const LIFETIME_DURATION = 0; // Admin-only, not publicly available
const VERSION = 1;
// Base32 alphabet (Crockford variant — no I/L/O/U to avoid confusion)
const BASE32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
function base32Encode(buffer) {
let bits = '';
for (const byte of buffer) {
bits += byte.toString(2).padStart(8, '0');
}
// Pad to multiple of 5
while (bits.length % 5 !== 0) bits += '0';
let result = '';
for (let i = 0; i < bits.length; i += 5) {
const index = parseInt(bits.substring(i, i + 5), 2);
result += BASE32[index];
}
return result;
}
function base32Decode(str) {
let bits = '';
for (const char of str.toUpperCase()) {
const index = BASE32.indexOf(char);
if (index === -1) throw new Error(`Invalid base32 character: ${char}`);
bits += index.toString(2).padStart(5, '0');
}
const bytes = [];
for (let i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.substring(i, i + 8), 2));
}
return Buffer.from(bytes);
}
function getSecret() {
if (!fs.existsSync(SECRET_FILE)) {
console.error('No master secret found. Run with --init-secret first.');
process.exit(1);
}
return fs.readFileSync(SECRET_FILE, 'utf8').trim();
}
function initSecret() {
if (fs.existsSync(SECRET_FILE)) {
console.error('Master secret already exists at', SECRET_FILE);
console.error('Delete it first if you want to regenerate (WARNING: invalidates all existing codes).');
process.exit(1);
}
const secret = crypto.randomBytes(32).toString('hex');
fs.writeFileSync(SECRET_FILE, secret, { mode: 0o600 });
console.log('Master secret generated and saved to', SECRET_FILE);
console.log('KEEP THIS FILE SAFE. It is needed to generate and validate all license codes.');
console.log('DO NOT ship this file with the product.');
}
function generateCode(secret, durationDays, codeId) {
// Pack payload: version(4b) + duration_days(12b) + code_id(32b) + created_ts(32b) = 80 bits = 10 bytes
const payload = Buffer.alloc(10);
// Byte 0-1: version (4 bits) + duration (12 bits) = 16 bits
const versionAndDuration = ((VERSION & 0x0F) << 12) | (durationDays & 0x0FFF);
payload.writeUInt16BE(versionAndDuration, 0);
// Byte 2-5: code_id (32 bits)
payload.writeUInt32BE(codeId, 2);
// Byte 6-9: created timestamp (32 bits, seconds since epoch)
const createdTs = Math.floor(Date.now() / 1000);
payload.writeUInt32BE(createdTs, 6);
// HMAC the payload to get signature
const hmac = crypto.createHmac('sha256', secret).update(payload).digest();
// Take first 5 bytes of HMAC (40 bits) — fits exactly in 25 base32 chars with 10-byte payload
const signature = hmac.subarray(0, 5);
// Combine: payload (10 bytes) + signature (5 bytes) = 15 bytes = 120 bits
// 25 base32 chars = 125 bits, comfortably fits 120 bits
const combined = Buffer.concat([payload, signature]);
let encoded = base32Encode(combined);
while (encoded.length < 25) encoded += '0';
encoded = encoded.substring(0, 25);
const groups = [];
for (let i = 0; i < 25; i += 5) {
groups.push(encoded.substring(i, i + 5));
}
return `DC-${groups.join('-')}`;
}
function parseCode(code) {
// Strip prefix and dashes
const cleaned = code.replace(/^DC-/, '').replace(/-/g, '');
if (cleaned.length !== 25) {
throw new Error(`Invalid code length: expected 25 base32 chars, got ${cleaned.length}`);
}
// Decode base32 — 25 chars = 125 bits = 15 full bytes
const decoded = base32Decode(cleaned);
if (decoded.length < 15) {
const padded = Buffer.alloc(15);
decoded.copy(padded);
return parsePayload(padded);
}
return parsePayload(decoded.subarray(0, 15));
}
function parsePayload(buffer) {
const payload = buffer.subarray(0, 10);
const signature = buffer.subarray(10, 15);
const versionAndDuration = payload.readUInt16BE(0);
const version = (versionAndDuration >> 12) & 0x0F;
const durationDays = versionAndDuration & 0x0FFF;
const codeId = payload.readUInt32BE(2);
const createdTs = payload.readUInt32BE(6);
return { version, durationDays, codeId, createdTs, payload, signature };
}
function verifyCode(secret, code) {
try {
const { version, durationDays, codeId, createdTs, payload, signature } = parseCode(code);
// Verify HMAC (5-byte signature)
const expectedHmac = crypto.createHmac('sha256', secret).update(payload).digest();
const expectedSig = expectedHmac.subarray(0, 5);
if (!crypto.timingSafeEqual(signature, expectedSig)) {
return { valid: false, reason: 'Invalid signature — code is forged or corrupted' };
}
if (version !== VERSION) {
return { valid: false, reason: `Unsupported version: ${version}` };
}
// Accept lifetime (0) and standard durations
if (durationDays !== LIFETIME_DURATION && !VALID_DURATIONS.includes(durationDays)) {
return { valid: false, reason: `Invalid duration: ${durationDays} days` };
}
const createdDate = new Date(createdTs * 1000);
const isLifetime = durationDays === LIFETIME_DURATION;
const expiresDate = isLifetime ? null : new Date(createdTs * 1000 + durationDays * 86400000);
return {
valid: true,
version,
durationDays,
codeId,
createdAt: createdDate.toISOString(),
expiresAt: isLifetime ? null : expiresDate.toISOString(),
expired: isLifetime ? false : Date.now() > expiresDate.getTime()
};
} catch (error) {
return { valid: false, reason: error.message };
}
}
// CLI
function main() {
const args = process.argv.slice(2);
if (args.includes('--help') || args.length === 0) {
console.log(`
DashCaddy License Code Generator
Usage:
node license-keygen.js --init-secret Initialize master secret (first time only)
node license-keygen.js --duration <days> [options] Generate license codes
node license-keygen.js --verify <code> Verify a license code
node license-keygen.js --decode <code> Decode and display code details
Options:
--duration <days> Code validity: 30, 90, 180, or 365 days (required for generation)
--count <n> Number of codes to generate (default: 1)
--start-id <n> Starting code ID (default: auto from counter file)
--output <file> Write codes to file instead of stdout
--json Output as JSON
Valid durations: ${VALID_DURATIONS.join(', ')} days
`);
process.exit(0);
}
if (args.includes('--init-secret')) {
initSecret();
return;
}
if (args.includes('--verify') || args.includes('--decode')) {
const codeIndex = args.indexOf('--verify') !== -1 ? args.indexOf('--verify') : args.indexOf('--decode');
const code = args[codeIndex + 1];
if (!code) {
console.error('Please provide a code to verify.');
process.exit(1);
}
const secret = getSecret();
const result = verifyCode(secret, code);
if (args.includes('--json')) {
console.log(JSON.stringify(result, null, 2));
} else if (result.valid) {
const isLifetime = result.durationDays === 0;
console.log('Code is VALID');
console.log(` Version: ${result.version}`);
console.log(` Duration: ${isLifetime ? 'LIFETIME' : result.durationDays + ' days'}`);
console.log(` Code ID: ${result.codeId}`);
console.log(` Created: ${result.createdAt}`);
console.log(` Expires: ${isLifetime ? 'NEVER' : result.expiresAt}`);
console.log(` Status: ${isLifetime ? 'LIFETIME' : (result.expired ? 'EXPIRED' : 'ACTIVE')}`);
} else {
console.log('Code is INVALID');
console.log(` Reason: ${result.reason}`);
}
return;
}
// Generate codes
const isLifetime = args.includes('--lifetime');
const durationIndex = args.indexOf('--duration');
if (!isLifetime && durationIndex === -1) {
console.error('--duration is required. Use --help for usage.');
process.exit(1);
}
const duration = isLifetime ? LIFETIME_DURATION : parseInt(args[durationIndex + 1]);
if (!isLifetime && !VALID_DURATIONS.includes(duration)) {
console.error(`Invalid duration: ${duration}. Valid: ${VALID_DURATIONS.join(', ')}`);
process.exit(1);
}
const countIndex = args.indexOf('--count');
const count = countIndex !== -1 ? parseInt(args[countIndex + 1]) : 1;
// Load or create counter file for auto-incrementing code IDs
const counterFile = process.env.LICENSE_COUNTER_FILE || path.join(platformPaths.dataDir, '.license-counter');
let startId;
const startIdIndex = args.indexOf('--start-id');
if (startIdIndex !== -1) {
startId = parseInt(args[startIdIndex + 1]);
} else if (fs.existsSync(counterFile)) {
startId = parseInt(fs.readFileSync(counterFile, 'utf8').trim()) + 1;
} else {
startId = 1;
}
const secret = getSecret();
const codes = [];
for (let i = 0; i < count; i++) {
const codeId = startId + i;
const code = generateCode(secret, duration, codeId);
codes.push({ code, codeId, durationDays: duration });
}
// Save counter
fs.writeFileSync(counterFile, String(startId + count - 1));
// Output
const outputIndex = args.indexOf('--output');
if (args.includes('--json')) {
const output = JSON.stringify(codes, null, 2);
if (outputIndex !== -1) {
fs.writeFileSync(args[outputIndex + 1], output);
console.log(`${count} code(s) written to ${args[outputIndex + 1]}`);
} else {
console.log(output);
}
} else {
const lines = codes.map(c => `${c.code} (${c.durationDays === 0 ? 'LIFETIME' : c.durationDays + ' days'}, ID: ${c.codeId})`);
if (outputIndex !== -1) {
fs.writeFileSync(args[outputIndex + 1], codes.map(c => c.code).join('\n') + '\n');
console.log(`${count} code(s) written to ${args[outputIndex + 1]}`);
} else {
lines.forEach(l => console.log(l));
}
}
console.log(`\nGenerated ${count} code(s) for ${duration === 0 ? 'LIFETIME' : duration + ' days'}. Next ID: ${startId + count}`);
}
// Also export for use by license-manager.js
module.exports = { verifyCode, parseCode, VALID_DURATIONS, VERSION };
if (require.main === module) {
main();
}
+97 -29
View File
@@ -45,7 +45,12 @@ const BUNDLED_WORKFLOWS = {
interval: 15 * 60 * 1000, // 15 minutes
actions: [
{ type: 'health-check', target: '{{serviceId}}' },
{ type: 'notify-on-failure', message: 'Health check failed for {{serviceId}}' }
// failingServices is set by healthCheckService when it throws (any
// service failed). It's a comma-joined string of failing service IDs.
// Previously this used {{serviceId}} which never resolved because
// no per-service ID is in scope at the workflow level — that's the
// DC-044 root-cause bug fix.
{ type: 'notify-on-failure', message: 'Health check failed for {{failingServices}}' }
]
},
'disk-space-alert': {
@@ -194,34 +199,23 @@ class WorkflowEngine extends EventEmitter {
if (!workflow) {
throw new Error(`Unknown workflow: ${workflowId}`);
}
if (!this.enabled.get(workflowId)) {
console.log(`[WorkflowEngine] Workflow ${workflowId} is disabled, skipping`);
return { skipped: true, reason: 'disabled' };
}
const executionId = `${workflowId}-${Date.now()}`;
const startTime = Date.now();
console.log(`[WorkflowEngine] Executing workflow: ${workflowId}`);
this.emit('workflow-start', { workflowId, executionId, triggerData });
const results = [];
for (const action of workflow.actions) {
try {
const result = await this.executeAction(action, triggerData);
results.push({ action: action.type, success: true, result });
} catch (error) {
console.error(`[WorkflowEngine] Action ${action.type} failed:`, error.message);
results.push({ action: action.type, success: false, error: error.message });
// Continue with other actions but log failure
}
}
const results = await this._runActions(workflow.actions, triggerData);
const duration = Date.now() - startTime;
const allSucceeded = results.every(r => r.success);
const historyEntry = {
executionId,
workflowId,
@@ -232,22 +226,63 @@ class WorkflowEngine extends EventEmitter {
success: allSucceeded,
results
};
this.history.push(historyEntry);
// Keep history to last 500 entries
if (this.history.length > 500) {
this.history = this.history.slice(-500);
}
this.saveHistory();
this.emit('workflow-complete', historyEntry);
console.log(`[WorkflowEngine] Workflow ${workflowId} completed in ${duration}ms, success: ${allSucceeded}`);
return historyEntry;
}
/**
* Run a sequence of actions and collect their results. Extracted from
* executeWorkflow so the per-action result threading (notify-on-failure
* gating) and the failingServices context surface can be unit-tested
* directly. executeWorkflow() is the production entry point; _runActions
* is an internal helper that callers shouldn't reach for.
*/
async _runActions(actions, triggerData = {}) {
const results = [];
for (let i = 0; i < actions.length; i++) {
const action = actions[i];
const previousResult = i > 0 ? results[i - 1] : null;
// notify-on-failure needs to see the previous action's outcome to decide
// whether to fire. Passing the full results array in the trigger data lets
// executeAction do that lookup without changing the action shape.
// Also surface failingServices (set by healthCheckService on throw) so
// template variables like {{failingServices}} can interpolate.
const actionContext = {
...triggerData,
previousResult,
failingServices: previousResult && previousResult.failingServices ? previousResult.failingServices : undefined,
};
try {
const result = await this.executeAction(action, actionContext);
results.push({ action: action.type, success: true, result });
} catch (error) {
console.error(`[WorkflowEngine] Action ${action.type} failed:`, error.message);
results.push({
action: action.type,
success: false,
error: error.message,
failingServices: error.failingServices,
});
// Continue with other actions but log failure
}
}
return results;
}
/**
* Execute a single action
*/
@@ -269,7 +304,12 @@ class WorkflowEngine extends EventEmitter {
);
case 'notify-on-failure':
// Only send if previous action failed
// Only send if previous action failed (success: false). The
// previousResult is injected by executeWorkflow's loop. If there
// was no previous action, this is a no-op (returns skipped).
if (!context.previousResult || context.previousResult.success !== false) {
return { skipped: true, reason: 'no previous failure' };
}
return this.notify(
this.interpolate(action.message, context),
action.channel
@@ -323,11 +363,31 @@ class WorkflowEngine extends EventEmitter {
}
}
}
return { checked: results.length, healthy: results.filter(r => r.healthy).length, results };
// Surface failing service IDs so downstream notify-on-failure actions
// can interpolate `{{failingServices}}` into the alert message. Without
// this, templates like `Health check failed for {{serviceId}}` stay
// literal because there's no serviceId in scope.
const failing = results.filter(r => !r.healthy).map(r => r.service);
const healthy = results.filter(r => r.healthy).length;
const result = { checked: results.length, healthy, results, failing };
if (failing.length > 0) {
// Throw so the action's success:false path is taken and notify-on-failure fires.
const err = new Error(`Health check failed for ${failing.length} service(s): ${failing.join(', ')}`);
err.failingServices = failing;
err.workflowResult = result;
throw err;
}
return result;
}
// Single service check
const healthy = await this.checkContainerHealth(serviceId);
if (!healthy) {
const err = new Error(`Health check failed for ${serviceId}`);
err.failingServices = [serviceId];
err.workflowResult = { serviceId, healthy };
throw err;
}
return { serviceId, healthy };
}
@@ -338,10 +398,18 @@ class WorkflowEngine extends EventEmitter {
try {
const docker = this.ctx.docker?.client;
if (!docker) return false;
const container = docker.getContainer(containerId);
const info = await container.inspect();
return info.State && info.State.Running && info.State.Health !== 'unhealthy';
// A container is healthy if it's running AND (it has no explicit
// health check OR its health check reports healthy/starting).
// info.State.Health is undefined when no HEALTHCHECK is declared.
// info.State.Health.Status is 'starting' | 'healthy' | 'unhealthy'
// when the health check IS declared.
if (!info.State || !info.State.Running) return false;
if (!info.State.Health) return true; // no health check defined → running = healthy
const status = info.State.Health.Status;
return status === 'healthy' || status === 'starting';
} catch (error) {
return false;
}
+10 -2
View File
@@ -172,8 +172,16 @@ function csrfValidationMiddleware(req, res, next) {
'/api/v1/system/update-notify'
];
const isExcluded = excludedPaths.some(path => req.path === path) ||
req.path.startsWith('/api/v1/auth/gate/');
const isExcluded = excludedPaths.some(path => {
if (req.path === path) return true;
// Allow `:param` placeholders to match any single segment. Pre-existing
// bug — literal ':token' never matched real tokens — fixed under DC-053.
if (path.includes(':')) {
const pattern = '^' + path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, '[^/]+') + '$';
return new RegExp(pattern).test(req.path);
}
return false;
}) || req.path.startsWith('/api/v1/auth/gate/');
if (isExcluded) {
return next();
+85 -9
View File
@@ -227,6 +227,10 @@ module.exports = function configureMiddleware(app, {
ipSessions.delete(getClientIP(req));
}
// Session cookies are intentionally host-only. Browsers reject Domain=.sami
// because .sami is an unregistered custom TLD and therefore treated as a
// public suffix. Cross-subdomain login is handled by the one-time SSO
// handoff below, which mints a separate host-only cookie on each service.
function setSessionCookie(res, durationKey) {
const durationMs = SESSION_DURATIONS[durationKey];
if (!durationMs) return;
@@ -235,9 +239,8 @@ module.exports = function configureMiddleware(app, {
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64url');
const key = cryptoUtils.loadOrCreateKey();
const sig = crypto.createHmac('sha256', key).update(payloadB64).digest('base64url');
const domainAttr = siteConfig.tld ? `; Domain=${siteConfig.tld}` : '';
res.setHeader('Set-Cookie',
`${SESSION_COOKIE_NAME}=${payloadB64}.${sig}${domainAttr}; Max-Age=${maxAge}; Path=/; HttpOnly; Secure; SameSite=Lax`
`${SESSION_COOKIE_NAME}=${payloadB64}.${sig}; Max-Age=${maxAge}; Path=/; HttpOnly; Secure; SameSite=Lax`
);
}
@@ -268,16 +271,28 @@ module.exports = function configureMiddleware(app, {
}
function clearSessionCookie(res) {
const domainAttr = siteConfig.tld ? `; Domain=${siteConfig.tld}` : '';
res.setHeader('Set-Cookie',
`${SESSION_COOKIE_NAME}=; Max-Age=0${domainAttr}; Path=/; HttpOnly; SameSite=Lax`
`${SESSION_COOKIE_NAME}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`
);
}
// COOKIE-ONLY session validation. The previous IP-keyed cache (verifyIPSession
// + the write-back in this function) caused cross-subdomain SSO breakage when
// Caddy on --network host forwards auth to the container: req.ip arrives as
// 100.121.150.22 (DNS2's tailnet IP) instead of the user's real IP, so the
// IP cache misses even when the cookie is valid. The host-only cookie is
// signed with a persisted HMAC key (loadOrCreateKey()). Cross-subdomain
// authentication uses the one-time SSO handoff because browsers reject
// Domain=.sami. HttpOnly + Secure + SameSite=Lax makes it a stronger
// credential than the IP cache. Ref: skill auth-and-monitoring-pitfalls.md
// "TOTP session validation IP-key issue" (FIXED 2026-07-21).
function isSessionValid(req) {
if (verifyIPSession(req)) return true;
const cookies = parseCookies(req.headers.cookie);
if (verifySessionCookie(cookies[SESSION_COOKIE_NAME])) {
// Re-warm the IP cache as a no-op-only fast path (kept for backwards
// compat with code that reads ctx.session.ipSessions.size for telemetry,
// but it is NOT consulted for auth decisions). The next line intentionally
// does NOT gate the return on verifyIPSession anymore.
const ip = getClientIP(req);
if (totpConfig.sessionDuration && SESSION_DURATIONS[totpConfig.sessionDuration]) {
ipSessions.set(ip, { exp: Date.now() + SESSION_DURATIONS[totpConfig.sessionDuration] });
@@ -287,6 +302,43 @@ module.exports = function configureMiddleware(app, {
return false;
}
// ── Cross-subdomain SSO token handoff ──
// Domain=.sami cookies are silently rejected by real browsers: .sami is an
// unregistered custom TLD, so browsers treat "sami" itself as the effective
// public suffix and refuse to set a cookie scoped to it (the same rule that
// stops a site from setting a supercookie for all of .com). That means the
// session cookie set on status.sami never reaches plex.sami/jellyfin.sami/
// etc, and cross-subdomain SSO can never work via a shared cookie no matter
// how the cookie itself is constructed.
//
// Fix: after TOTP verify, mint a short-lived single-use opaque token and
// pass it in the redirect URL back to the target service. That service's
// origin exchanges the token (via /auth/sso-exchange) for its OWN host-only
// cookie (no Domain attribute — always accepted, since it's scoped to the
// exact host that set it). isSessionValid/verifySessionCookie don't care
// about the cookie's Domain at all, only its HMAC signature, so a host-only
// cookie validates identically to the cross-domain one — no changes needed
// to any existing session-check code path.
const ssoHandoffTokens = new Map();
const SSO_HANDOFF_TTL_MS = 60 * 1000;
function createHandoffToken() {
const token = crypto.randomBytes(24).toString('base64url');
ssoHandoffTokens.set(token, { exp: Date.now() + SSO_HANDOFF_TTL_MS });
return token;
}
function redeemHandoffToken(token) {
if (!token) return false;
const entry = ssoHandoffTokens.get(token);
ssoHandoffTokens.delete(token); // one-time use regardless of outcome
return !!entry && entry.exp > Date.now();
}
function setHostOnlySessionCookie(res, durationKey) {
setSessionCookie(res, durationKey);
}
// ── Public routes (bypass TOTP and JWT auth) ──
// Routes here are accessible without authentication. By default the
// monitoring/health-check endpoints are public so the dashboard can
@@ -327,6 +379,11 @@ module.exports = function configureMiddleware(app, {
{ path: '/api/v1/auth/gate/', prefix: true },
{ path: '/api/v1/auth/app-token/', prefix: true },
{ path: '/api/v1/auth/login-page', exact: true, method: 'GET' },
// Must be public: a fresh cross-subdomain visitor has no session yet by
// definition — that's exactly the gap /auth/sso-exchange closes. The
// endpoint itself only accepts a valid single-use handoff token minted
// moments earlier by a successful TOTP verify, so this isn't an open door.
{ path: '/api/v1/auth/sso-exchange', exact: true, method: 'GET' },
// DC-046 pluggable auth endpoints — public by design (they ARE login).
// Use :provider placeholder; today's only provider is TOTP, but the
// route is parameterized so DC-047's email provider just works.
@@ -345,9 +402,14 @@ module.exports = function configureMiddleware(app, {
{ path: '/api/v1/share/:token/preview', exact: true, method: 'GET' },
{ path: '/api/v1/share/:token/subscribe', exact: true, method: 'POST' },
{ path: '/api/v1/share/:token/redeem-tailscale', exact: true, method: 'POST' },
// /me and /admin/* require authentication — NOT public. Listed here
// only to document them; absence from PUBLIC_ROUTES means they go
// through the normal auth gate. CSRF applies to writes as usual.
{ path: '/api/v1/billing/checkout', exact: true, method: 'POST' },
// /api/v1/billing/webhook was REMOVED: webhooks are handled out-of-process
// by scripts/stripe-license-bridge.js (the merchant webhook secret never
// enters the API process). The PUBLIC_ROUTES allowlist drift test would
// catch any re-add of this dead entry.
// /api/v1/services + status: read-only service metadata that the public
// dashboard needs before login (services list widget, status pill).
// Writes go through the normal auth gate. CSRF applies to writes as usual.
{ path: '/api/v1/services', exact: true, method: 'GET' },
{ path: '/api/v1/ca/info', exact: true, method: 'GET' },
{ path: '/api/v1/ca/root.crt', exact: true, method: 'GET' },
@@ -392,6 +454,17 @@ module.exports = function configureMiddleware(app, {
function isPublicRoute(req) {
return PUBLIC_ROUTES.some(r => {
if (r.method && req.method !== r.method) return false;
if (r.exact) {
// Exact string match, BUT allow `:param` placeholders in the
// PUBLIC_ROUTES entry to match any single path segment. This was a
// pre-existing bug — literal ':token' never matched real tokens —
// caught by DC-053 public share preview returning 401.
if (r.path.includes(':')) {
const pattern = '^' + r.path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, '[^/]+') + '$';
return new RegExp(pattern).test(req.path);
}
return req.path === r.path;
}
return r.prefix ? req.path.startsWith(r.path) : req.path === r.path;
});
}
@@ -562,6 +635,9 @@ module.exports = function configureMiddleware(app, {
clearSessionCookie,
isSessionValid,
ipSessions,
renewCSRFToken
renewCSRFToken,
createHandoffToken,
redeemHandoffToken,
setHostOnlySessionCookie
};
};
@@ -1,335 +0,0 @@
// ========== MONITORING WIDGETS ==========
// Embeds a compact system-resource + health summary panel directly on the
// main dashboard. Replaces the need for a separate monitoring-dashboard.html
// page — quick at-a-glance stats where you already are.
(function () {
// ----- Style injection (scoped to .dc-monitor so it doesn't leak) -----
const styleEl = document.createElement('style');
styleEl.textContent = `
.dc-monitor {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
margin-bottom: 16px;
padding: 12px 16px;
background: var(--card-base);
border: 1px solid var(--border);
border-radius: var(--radius);
}
.dc-monitor-card {
padding: 10px 12px;
background: var(--card-bg, rgba(255,255,255,0.04));
border-radius: 8px;
border: 1px solid var(--border);
}
.dc-monitor-label {
font-size: 0.7rem;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
}
.dc-monitor-value {
font-size: 1.4rem;
font-weight: 600;
color: var(--fg);
}
.dc-monitor-sub {
font-size: 0.7rem;
color: var(--muted);
margin-top: 4px;
}
.dc-monitor-bar {
margin-top: 6px;
width: 100%;
height: 4px;
background: color-mix(in srgb, var(--muted) 20%, transparent);
border-radius: 2px;
overflow: hidden;
}
.dc-monitor-bar-fill {
height: 100%;
width: 0%;
background: var(--ok-fg, #27ae60);
transition: width 0.3s ease, background 0.3s ease;
}
.dc-monitor-bar-fill.warn { background: #f39c12; }
.dc-monitor-bar-fill.bad { background: #e74c3c; }
.dc-monitor-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.dc-monitor-title {
font-size: 0.85rem;
font-weight: 500;
color: var(--muted);
display: flex;
align-items: center;
gap: 6px;
}
.dc-monitor-pill {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 999px;
font-size: 0.7rem;
font-weight: 500;
}
.dc-monitor-pill.ok { background: color-mix(in srgb, #27ae60 20%, transparent); color: #27ae60; }
.dc-monitor-pill.warn { background: color-mix(in srgb, #f39c12 20%, transparent); color: #f39c12; }
.dc-monitor-pill.bad { background: color-mix(in srgb, #e74c3c 20%, transparent); color: #e74c3c; }
.dc-monitor-refresh {
font-size: 0.7rem;
color: var(--muted);
opacity: 0.7;
}
`;
document.head.appendChild(styleEl);
// ----- Container element (inserted above service-filter-bar) -----
const filterBar = document.getElementById('service-filter-bar');
if (!filterBar) return;
const panel = document.createElement('div');
panel.className = 'dc-monitor';
panel.id = 'dc-monitor-panel';
panel.innerHTML = `
<div class="dc-monitor-header" style="grid-column: 1 / -1;">
<div class="dc-monitor-title">📊 System Overview</div>
<span class="dc-monitor-refresh" id="dc-monitor-refresh-stamp"></span>
</div>
<div class="dc-monitor-card">
<div class="dc-monitor-label">Services</div>
<div class="dc-monitor-value" id="dc-monitor-services"></div>
<div class="dc-monitor-sub" id="dc-monitor-services-sub">loading</div>
</div>
<div class="dc-monitor-card">
<div class="dc-monitor-label">Containers Up</div>
<div class="dc-monitor-value" id="dc-monitor-containers"></div>
<div class="dc-monitor-sub" id="dc-monitor-containers-sub">loading</div>
</div>
<div class="dc-monitor-card">
<div class="dc-monitor-label">Avg CPU</div>
<div class="dc-monitor-value" id="dc-monitor-cpu"></div>
<div class="dc-monitor-bar"><div class="dc-monitor-bar-fill" id="dc-monitor-cpu-bar"></div></div>
</div>
<div class="dc-monitor-card">
<div class="dc-monitor-label">Avg Memory</div>
<div class="dc-monitor-value" id="dc-monitor-mem"></div>
<div class="dc-monitor-bar"><div class="dc-monitor-bar-fill" id="dc-monitor-mem-bar"></div></div>
</div>
<div class="dc-monitor-card">
<div class="dc-monitor-label">Health</div>
<div class="dc-monitor-value" id="dc-monitor-health"></div>
<div class="dc-monitor-sub" id="dc-monitor-health-sub"></div>
</div>
`;
// Insert ABOVE the filter bar
filterBar.parentNode.insertBefore(panel, filterBar);
// ----- Helpers -----
function setBar(id, pct) {
const el = document.getElementById(id);
if (!el) return;
const p = Math.max(0, Math.min(100, Number(pct) || 0));
el.style.width = p + '%';
el.classList.remove('warn', 'bad');
if (p >= 85) el.classList.add('bad');
else if (p >= 65) el.classList.add('warn');
}
function fmtPct(v) {
if (v == null || isNaN(v)) return '—';
return (Math.round(v * 10) / 10) + '%';
}
function fmtBytes(b) {
if (b == null || isNaN(b)) return '—';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; }
return b.toFixed(1) + ' ' + units[i];
}
// ----- Robust services count -----
// Read from multiple sources so we always have a number:
// 1. window.APPS (populated by grid.js after loadServices)
// 2. #cards .card elements (post-buildGrid)
// 3. live fetch /api/v1/services (last-resort fallback if grid hasn't run)
async function fetchServicesCount() {
// Source 1+2: window.APPS / DOM cards
if (Array.isArray(window.APPS) && window.APPS.length > 0) {
const up = document.querySelectorAll('#cards .card[data-status="on"]').length;
return { total: window.APPS.length, up, source: 'APPS' };
}
const cards = document.querySelectorAll('#cards .card');
if (cards.length > 0) {
const up = Array.from(cards).filter(c => c.dataset.status === 'on').length;
return { total: cards.length, up, source: 'DOM' };
}
// Source 3: fetch live (endpoints may return {success, services:[...]} OR raw array)
try {
const r = await fetch('/api/v1/services', { cache: 'no-store' });
if (!r.ok) return { total: 0, up: 0, source: 'fetch-fail' };
const body = await r.json();
const list = (body && Array.isArray(body.services)) ? body.services
: (Array.isArray(body)) ? body
: [];
// Persist for the grid so this fallback only fires once
if (Array.isArray(window.APPS) || typeof window.APPS === 'undefined') window.APPS = list;
const up = document.querySelectorAll('#cards .card[data-status="on"]').length;
return { total: list.length, up, source: 'fetch' };
} catch (_) {
return { total: 0, up: 0, source: 'fetch-error' };
}
}
async function setServicesCard() {
const { total, up } = await fetchServicesCount();
const el = document.getElementById('dc-monitor-services');
const sub = document.getElementById('dc-monitor-services-sub');
if (el) el.textContent = `${up} / ${total}`;
if (sub) sub.textContent = total === 0
? 'no services yet'
: `${up} online · ${total - up} offline`;
}
function applyHealthSummary(data) {
const el = document.getElementById('dc-monitor-health');
const sub = document.getElementById('dc-monitor-health-sub');
if (!el) return;
if (!data || data.summary == null) {
el.textContent = '—';
if (sub) sub.textContent = 'no data';
return;
}
const s = data.summary;
const healthy = s.healthy ?? s.up ?? 0;
const unhealthy = s.unhealthy ?? s.down ?? 0;
const total = s.total ?? (healthy + unhealthy);
el.textContent = `${healthy}/${total}`;
if (sub) {
if (unhealthy === 0) {
sub.innerHTML = '<span class="dc-monitor-pill ok">● all healthy</span>';
} else if (unhealthy <= 2) {
sub.innerHTML = `<span class="dc-monitor-pill warn">● ${unhealthy} degraded</span>`;
} else {
sub.innerHTML = `<span class="dc-monitor-pill bad">● ${unhealthy} down</span>`;
}
}
}
// ----- Data fetches -----
async function fetchStats() {
try {
const r = await fetch('/api/v1/monitoring/stats', { cache: 'no-store' });
if (!r.ok) return null;
const data = await r.json();
return (data && data.stats) ? data.stats : null;
} catch (_) {
return null;
}
}
async function fetchHealth() {
try {
const r = await fetch('/api/v1/health-checks/status', { cache: 'no-store' });
if (!r.ok) return null;
return await r.json();
} catch (_) {
return null;
}
}
function applyStats(stats) {
const containers = document.getElementById('dc-monitor-containers');
const containersSub = document.getElementById('dc-monitor-containers-sub');
const cpuEl = document.getElementById('dc-monitor-cpu');
const memEl = document.getElementById('dc-monitor-mem');
if (!stats) {
if (containers) containers.textContent = '—';
if (cpuEl) cpuEl.textContent = '—';
if (memEl) memEl.textContent = '—';
return;
}
const entries = Object.values(stats);
if (entries.length === 0) {
if (containers) containers.textContent = '0';
if (containersSub) containersSub.textContent = 'no containers reporting';
if (cpuEl) cpuEl.textContent = '0%';
if (memEl) memEl.textContent = '0%';
setBar('dc-monitor-cpu-bar', 0);
setBar('dc-monitor-mem-bar', 0);
return;
}
let cpuSum = 0, memSum = 0, memBytes = 0, cpuCount = 0, memCount = 0;
entries.forEach(s => {
// CPU may be percentage (0-100) or fraction (0-1) — handle both
if (s.cpu != null) {
const cpu = Number(s.cpu);
if (!isNaN(cpu)) {
cpuSum += cpu > 1 ? cpu : cpu * 100;
cpuCount++;
}
}
if (s.memory != null) {
const mem = Number(s.memory);
if (!isNaN(mem)) {
memSum += mem;
memBytes += Number(s.memoryUsage || 0);
memCount++;
}
}
});
const avgCpu = cpuCount ? cpuSum / cpuCount : 0;
const avgMem = memCount ? memSum / memCount : 0;
if (containers) containers.textContent = String(entries.length);
if (containersSub) {
const memTxt = memBytes ? ` · ${fmtBytes(memBytes)} RAM` : '';
containersSub.textContent = `running${memTxt}`;
}
if (cpuEl) cpuEl.textContent = fmtPct(avgCpu);
if (memEl) memEl.textContent = fmtPct(avgMem);
setBar('dc-monitor-cpu-bar', avgCpu);
setBar('dc-monitor-mem-bar', avgMem);
}
// ----- Public refresh function -----
let inFlight = false;
async function refresh() {
if (inFlight) return;
inFlight = true;
try {
setServicesCard();
const [stats, health] = await Promise.all([fetchStats(), fetchHealth()]);
applyStats(stats);
applyHealthSummary(health);
const stamp = document.getElementById('dc-monitor-refresh-stamp');
if (stamp) {
const now = new Date();
stamp.textContent = `updated ${now.toLocaleTimeString()}`;
}
} finally {
inFlight = false;
}
}
// Expose for init.js to call once and re-call after each refreshAll cycle
window.refreshMonitoringWidgets = refresh;
// Auto-refresh on the STATS interval (separate from full DASHBOARD refresh)
setInterval(refresh, (typeof DC !== 'undefined' && DC.POLL && DC.POLL.STATS) || 5000);
// Refresh once on first script load (init.js also calls this; double-call is harmless)
setTimeout(refresh, 200);
})();
+5
View File
@@ -3852,6 +3852,7 @@ button:focus-visible {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 14px;
padding: 40px 0 20px;
margin-top: 48px;
@@ -3873,3 +3874,7 @@ button:focus-visible {
height: 140px;
width: auto;
}
.footer-legal { display: flex; gap: 14px; font-size: 0.8rem; }
.footer-legal a { color: var(--muted); text-decoration: none; }
.footer-legal a:hover, .footer-legal a:focus-visible { color: var(--accent); text-decoration: underline; }
+91 -91
View File
File diff suppressed because one or more lines are too long
+4
View File
@@ -939,6 +939,10 @@
<footer class="dashcaddy-footer">
<span class="footer-copy">&copy; <span id="footer-year"></span></span>
<img src="/assets/sami7777-logo.png" alt="samiahmed7777" class="footer-logo">
<nav class="footer-legal" aria-label="Legal">
<a href="/legal/terms">Terms of Service</a>
<a href="/legal/privacy">Privacy Policy</a>
</nav>
</footer>
<!-- xterm.js for container exec/shell -->
+22 -11
View File
@@ -249,20 +249,31 @@
// back to window._showTotpOverlay() in `show()` below.
window.__dc_049_handled = true;
function isAllowedReturnUrl(returnUrl) {
try {
const parsed = new URL(returnUrl, window.location.origin);
if (!['http:', 'https:'].includes(parsed.protocol)) return false;
if (parsed.origin === window.location.origin) return true;
if (parsed.protocol !== 'https:') return false;
// globals.js is concatenated before this module in core.js, so SITE is
// available here. Permit exact hosts and subdomains under the configured
// private TLD (for example plex.sami), while rejecting lookalikes such as
// plex.sami.evil.example.
const suffix = SITE.tld.startsWith('.') ? SITE.tld : `.${SITE.tld}`;
return parsed.hostname === suffix.slice(1) || parsed.hostname.endsWith(suffix);
} catch (_) {
return false;
}
}
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('auth') === 'required') {
// Save returnUrl the same way totp-auth.js does, so both paths share state.
// We don't have access to the SITE constant here (it lives in globals.js's
// module scope), so we use a conservative origin-only check. Caddy's
// forward_auth already validates the request origin upstream.
// Preserve the gated service destination so submitTotpCode() can append
// the one-time SSO handoff token and return the browser to that host.
const returnUrl = urlParams.get('return');
if (returnUrl) {
try {
const parsed = new URL(returnUrl, window.location.origin);
if (parsed.origin === window.location.origin) {
try { sessionStorage.setItem('totp_redirect', returnUrl); } catch (_) {}
}
} catch (_) {}
if (returnUrl && isAllowedReturnUrl(returnUrl)) {
try { sessionStorage.setItem('totp_redirect', returnUrl); } catch (_) {}
}
// Clean URL — happens after we've captured the redirect
window.history.replaceState({}, '', window.location.pathname);
+28 -1
View File
@@ -35,6 +35,24 @@
if (overlay) overlay.classList.remove('show');
}
function buildSsoHandoffTarget(redirect, token) {
const parsed = new URL(redirect, window.location.origin);
if (parsed.origin === window.location.origin) return parsed.toString();
const suffix = SITE.tld.startsWith('.') ? SITE.tld : `.${SITE.tld}`;
const isPrivateHost = parsed.hostname === suffix.slice(1) || parsed.hostname.endsWith(suffix);
if (parsed.protocol !== 'https:' || !isPrivateHost) return null;
if (!token) return parsed.toString();
const returnPath = `${parsed.pathname}${parsed.search}${parsed.hash}`;
parsed.pathname = '/dashcaddy-sso';
parsed.search = '';
parsed.hash = '';
parsed.searchParams.set('token', token);
parsed.searchParams.set('return', returnPath);
return parsed.toString();
}
// Setup digit input UX
const container = document.getElementById('totp-digits');
if (container) {
@@ -91,7 +109,16 @@
const redirect = safeSessionGet('totp_redirect');
if (redirect) {
try { sessionStorage.removeItem('totp_redirect'); } catch (_) {}
window.location.href = redirect;
// .sami is an unregistered TLD, so browsers silently drop the
// Domain=.sami session cookie on any OTHER *.sami subdomain (they
// treat "sami" as the effective public suffix, same protection
// that blocks a Domain=.com supercookie). The target service can't
// see our session cookie no matter how it's built, so instead we
// hand it a one-time token in the URL; its login page exchanges
// that for its own host-only cookie via /auth/sso-exchange.
const target = buildSsoHandoffTarget(redirect, data.ssoToken);
if (!target) return;
window.location.href = target;
return;
}
// Initialize dashboard
+12
View File
@@ -0,0 +1,12 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Privacy Policy | DashCaddy</title><style>:root{color-scheme:dark;--card:#111c2e;--text:#e8edf5;--muted:#aab7ca;--accent:#68a4ff;--border:#263750}*{box-sizing:border-box}body{margin:0;background:linear-gradient(145deg,#07101d,#101b31);color:var(--text);font:16px/1.7 system-ui,sans-serif}main{width:min(900px,calc(100% - 32px));margin:48px auto;padding:clamp(24px,5vw,56px);background:var(--card);border:1px solid var(--border);border-radius:18px}h1{margin:0;font-size:clamp(2rem,5vw,3rem)}h2{margin-top:2rem;color:#fff}h3,strong{color:var(--text)}p,li{color:var(--muted)}a{color:var(--accent)}.eyebrow{color:var(--accent);font-weight:700;text-transform:uppercase}.notice{border-left:3px solid var(--accent);background:#0b1628;padding:12px 16px}footer{margin-top:42px;padding-top:22px;border-top:1px solid var(--border);display:flex;flex-wrap:wrap;gap:20px}</style></head><body><main><div class="eyebrow">DashCaddy Legal</div><h1>Privacy Policy</h1><p><strong>Effective and last updated:</strong> July 31, 2026</p><p class="notice">This GDPR-aware policy describes DashCaddy v1.0. It is not legal advice and may be refined following professional review.</p>
<h2>1. Controller and contact</h2><p>Sami Ahmed, operator of DashCaddy, controls personal data collected for subscriptions, licensing, and operation. Contact <a href="mailto:privacy@sami-ahmed.net">privacy@sami-ahmed.net</a>. DashCaddy has no separate Data Protection Officer; this is the privacy contact.</p>
<h2>2. Data collected</h2><h3>Account, login, and billing</h3><ul><li>Email address for login, license delivery, support, billing, and essential notices.</li><li>Subscription status, Stripe customer/session IDs, product, payment status, dates, and refunds. <strong>We do not receive or store full card numbers or security codes.</strong></li></ul><h3>License and server metadata</h3><ul><li>License key, tier, activation/expiry dates, and machine/host metadata embedded in or associated with the license.</li><li>Connection metadata needed to validate and secure licenses, such as IP address, timestamp, host/machine identifier, version, and request outcome.</li><li>The key containing machine metadata is stored locally in <code>data/credentials.json</code> and on the operators license server.</li></ul><h3>Optional Tailscale data</h3><p>Only if enabled, DashCaddy sends coordination API requests and may process Tailscale device IDs, tailnet/user IDs, names/status, and minted device or pre-auth keys. Keys are stored only as needed for the configured integration or share flow. Tailscale independently processes data under its terms.</p><h3>Support</h3><p>We collect messages and diagnostics you voluntarily provide. Do not send passwords, private keys, or unrelated personal data.</p>
<h2>3. Data not intentionally collected</h2><p>The hosted licensing service does not intentionally collect proxied content, DNS query history, injected credentials, or card details. Credentials and local configuration remain customer-controlled unless deliberately provided for support. v1.0 makes no automated decisions with legal or similarly significant effects.</p>
<h2>4. Purposes and GDPR lawful bases</h2><ul><li><strong>Contract:</strong> licenses, authentication, optional features, billing/refunds, and support.</li><li><strong>Legitimate interests:</strong> per-host enforcement, fraud/abuse prevention, security, troubleshooting, and proportionate product improvement.</li><li><strong>Legal obligation:</strong> required transaction/tax records and valid legal requests.</li><li><strong>Consent:</strong> optional marketing and integrations where consent is appropriate. Consent may be withdrawn without affecting earlier lawful processing.</li></ul>
<h2>5. Sharing and processors</h2><p>We do not sell personal data. Necessary disclosures are to:</p><ul><li><strong>Stripe</strong> for Checkout, billing, fraud prevention, receipts, and refunds. Card data goes directly to Stripe.</li><li><strong>Tailscale</strong> only when you configure/use the integration, for coordination and device/key operations.</li><li><strong>Our email delivery provider</strong> for login, license, billing, security, and support email; it receives the address and message content.</li></ul><p>We may disclose data when legally required, to protect rights/safety, or in a business transfer with safeguards. We do not otherwise share personal data except as described in this policy.</p>
<h2>6. International transfers</h2><p>Processors may handle data outside your country. Where GDPR applies, we will use a legally recognized transfer mechanism where one is required, such as an adequacy decision or Standard Contractual Clauses. Contact us for information about safeguards applicable to your data.</p>
<h2>7. Retention</h2><ul><li><strong>License keys and host metadata:</strong> life of subscription plus 30 days after cancellation, then deleted or irreversibly anonymized unless law requires longer.</li><li><strong>Billing records:</strong> as required for tax, accounting, chargebacks, and fraud prevention.</li><li><strong>Connection/security logs:</strong> normally no more than 30 days unless an incident requires preservation.</li><li><strong>Support records:</strong> while active and normally up to 12 months afterward.</li><li><strong>Optional Tailscale keys:</strong> until expired, used/revoked, share removal, or integration disablement, subject to Tailscale retention.</li></ul><p>Backups may retain deleted data for a limited rotation and are restored only for disaster recovery.</p>
<h2>8. Security</h2><p>We use reasonable safeguards and data minimization, but no system is completely secure. DashCaddy does not claim SOC 2, HIPAA, PCI-DSS, or another audited certification. Stripe Checkout processes cards; card data never touches DashCaddy servers.</p>
<h2>9. GDPR and other privacy rights</h2><p>Depending on location, you may request access, correction, deletion, restriction, objection, withdrawal of consent, and data portability in a structured machine-readable format, and complain to your supervisory authority. Email <a href="mailto:privacy@sami-ahmed.net">privacy@sami-ahmed.net</a> with “Privacy Request.” We may verify identity. We aim to respond within 30 days (one month), explain lawful extensions/refusals, and normally charge no fee. Without a central account, we search using identifiers you provide.</p>
<h2>10. Children, cookies, and marketing</h2><p>DashCaddy is not directed to children under 16. Checkout/login may use strictly necessary cookies. We request consent before non-essential analytics/marketing cookies where required. Marketing email is optional and includes unsubscribe.</p>
<h2>11. Changes and contact</h2><p>Revisions will show a new date, with reasonable notice for material changes. Questions and rights requests: <a href="mailto:privacy@sami-ahmed.net">privacy@sami-ahmed.net</a>.</p><footer><a href="/legal/terms">Terms of Service</a><a href="mailto:privacy@sami-ahmed.net">Contact</a><a href="/">Back to DashCaddy</a></footer></main></body></html>
+13
View File
@@ -0,0 +1,13 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Terms of Service | DashCaddy</title><style>:root{color-scheme:dark;--bg:#09111f;--card:#111c2e;--text:#e8edf5;--muted:#aab7ca;--accent:#68a4ff;--border:#263750}*{box-sizing:border-box}body{margin:0;background:linear-gradient(145deg,#07101d,#101b31);color:var(--text);font:16px/1.7 system-ui,sans-serif}main{width:min(900px,calc(100% - 32px));margin:48px auto;padding:clamp(24px,5vw,56px);background:var(--card);border:1px solid var(--border);border-radius:18px}h1{margin:0;font-size:clamp(2rem,5vw,3rem)}h2{margin-top:2rem;color:#fff}p,li{color:var(--muted)}strong{color:var(--text)}a{color:var(--accent)}.eyebrow{color:var(--accent);font-weight:700;text-transform:uppercase}.notice{border-left:3px solid var(--accent);background:#0b1628;padding:12px 16px}footer{margin-top:42px;padding-top:22px;border-top:1px solid var(--border);display:flex;flex-wrap:wrap;gap:20px}</style></head><body><main><div class="eyebrow">DashCaddy Legal</div><h1>Terms of Service</h1><p><strong>Effective and last updated:</strong> July 31, 2026</p><p class="notice">These Terms are a general launch document and are not legal advice. The operator may revise them following professional legal review.</p>
<h2>1. Agreement and operator</h2><p>These Terms govern your purchase, installation, and use of DashCaddy software and related hosted licensing services (the “Service”), operated by Sami Ahmed (“DashCaddy,” “we,” “us,” or “our”). By purchasing, activating, or using DashCaddy, you agree to these Terms and the <a href="/legal/privacy">Privacy Policy</a>. If acting for an organization, you represent that you can bind it.</p>
<h2>2. License grant</h2><p>Subject to payment and these Terms, we grant a limited, revocable, non-exclusive, non-sublicensable, non-transferable license to install and use DashCaddy on <strong>one host per license</strong> for the subscription term. A license may be moved to a replacement host with approval, but not shared, resold, rented, or used concurrently on multiple hosts. DashCaddy retains all ownership and intellectual-property rights.</p><p>The license key embeds or is associated with machine metadata. A copy is stored on the licensed host in <code>data/credentials.json</code> and on our license server for validation and enforcement.</p>
<h2>3. Acceptable use</h2><p>You must use DashCaddy lawfully and are responsible for connected systems. You must not:</p><ul><li>use proxy, DNS, credential-injection, sharing, or Tailscale features for unauthorized access, traffic interception, evasion, malware, spam, phishing, or attacks;</li><li>overload, bypass, or interfere with the Service, licensing, authentication, or security;</li><li>reverse engineer or modify DashCaddy except where law expressly permits, or remove notices;</li><li>violate privacy, intellectual-property, sanctions, export-control, or other applicable law; or</li><li>provide data or credentials you lack authority to process.</li></ul><p>We may investigate abuse and suspend access when reasonably necessary to protect users, third parties, or the Service.</p>
<h2>4. Availability and changes</h2><p>DashCaddy v1.0 is provided on a <strong>best-effort basis with no service-level agreement (SLA)</strong>, uptime guarantee, or guaranteed response time. Maintenance, failures, third-party outages, security events, and product changes may interrupt availability. Features may change or be discontinued with reasonable notice where practical.</p>
<h2>5. Billing, renewal, and Refund policy</h2><p>Prices, billing periods, taxes, and renewal terms appear at checkout. Stripe processes payments; card details go directly to Stripe and never touch DashCaddy servers. Unless checkout states otherwise, subscriptions renew automatically until cancelled.</p><p><strong>Refund policy:</strong> request a pro-rated refund within 14 calendar days after initial purchase. It covers the unused portion of that initial period from the request date. After 14 days, and for renewals, payments are non-refundable except where law requires. Cancellation prevents renewal but does not itself create a refund.</p>
<h2>6. Your systems and data</h2><p>You are responsible for backups, configuration, access control, and host security. DashCaddy manages sensitive proxy, DNS, and credential-injection settings; review changes. Data handling is described in the <a href="/legal/privacy">Privacy Policy</a>.</p>
<h2>7. Suspension and Termination</h2><p>You may stop using DashCaddy and cancel renewal anytime. We may suspend or terminate for material breach, non-payment, unlawful or abusive use, or security risk, with notice and opportunity to cure where reasonably possible. On termination the license ends. Ownership, disclaimers, liability, and governing-law provisions survive.</p>
<h2>8. Disclaimers</h2><p>To the maximum extent permitted by law, the Service is “as is” and “as available.” We disclaim implied warranties of merchantability, fitness, non-infringement, and uninterrupted or error-free operation. DashCaddy is not represented as certified for regulated workloads and makes no SOC 2, HIPAA, or similar compliance claim. Mandatory rights remain unaffected.</p>
<h2>9. Limitation of liability</h2><p>To the maximum extent permitted by law, DashCaddy and its operator are not liable for indirect, incidental, special, consequential, exemplary, or punitive damages, or lost profits, revenue, data, goodwill, or business interruption. Aggregate liability will not exceed amounts paid for DashCaddy in the 12 months before the claim. Limits do not apply where prohibited or to liability that cannot lawfully be limited.</p>
<h2>10. Indemnity</h2><p>Where permitted, you will indemnify us against third-party claims from your unlawful use, connected services or data, or breach, except to the extent caused by our unlawful conduct.</p>
<h2>11. Governing law and disputes</h2><p>These Terms are governed by laws applicable in the operators principal place of business, without conflict-of-law rules. Courts there have jurisdiction, except consumers retain mandatory rights and forum protections in their country. Before filing, parties will attempt resolution by email for 30 days.</p>
<h2>12. Changes and contact</h2><p>Material changes will be posted with a new effective date and reasonable advance notice where practical. Questions, cancellation, or refunds: <a href="mailto:privacy@sami-ahmed.net">privacy@sami-ahmed.net</a>.</p><footer><a href="/legal/privacy">Privacy Policy</a><a href="mailto:privacy@sami-ahmed.net">Contact</a><a href="/">Back to DashCaddy</a></footer></main></body></html>
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/legal/terms"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="canonical" href="/legal/terms"><title>Terms of Service | DashCaddy</title></head><body><p>DashCaddy Legal: Continue to the <a href="/legal/terms">Terms of Service</a>.</p></body></html>
+1
View File
@@ -4,6 +4,7 @@
"private": true,
"scripts": {
"build": "node build.js",
"test": "node --test tests/*.test.js",
"watch": "node build.js --watch"
},
"devDependencies": {
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-1b7c08184e';
const CACHE = 'dashcaddy-shell-4912a7d0d0';
const PRECACHE = [
'/',
'/index.html',
+95
View File
@@ -0,0 +1,95 @@
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const test = require('node:test');
const assert = require('node:assert/strict');
const source = fs.readFileSync(path.join(__dirname, '..', 'js', 'auth-gate.js'), 'utf8');
const totpSource = fs.readFileSync(path.join(__dirname, '..', 'js', 'totp-auth.js'), 'utf8');
function buildHandoffTarget(returnUrl, token, tld = '.sami') {
const start = totpSource.indexOf(' function buildSsoHandoffTarget');
const end = totpSource.indexOf('\n\n // Setup digit input UX', start);
assert.notEqual(start, -1, 'handoff builder must exist');
assert.notEqual(end, -1, 'handoff builder boundary must exist');
const functionSource = totpSource.slice(start, end);
const context = {
URL,
SITE: { tld },
window: { location: { origin: 'https://status.sami' } },
};
const sandbox = { ...context, input: returnUrl, token, result: undefined };
vm.runInNewContext(`${functionSource}\nresult = buildSsoHandoffTarget(input, token);`, sandbox);
return sandbox.result;
}
function capturedRedirect(returnUrl, tld = '.sami') {
const stored = new Map();
const query = new URLSearchParams({ auth: 'required', return: returnUrl });
const location = {
origin: 'https://status.sami',
pathname: '/',
search: `?${query.toString()}`,
reload() {},
};
const context = {
URL,
URLSearchParams,
SITE: { tld },
sessionStorage: {
setItem(key, value) { stored.set(key, value); },
},
document: { getElementById() { return null; } },
setTimeout() {},
console,
window: {
location,
history: { replaceState() {} },
},
};
context.window.window = context.window;
vm.runInNewContext(source, context, { filename: 'auth-gate.js' });
return stored.get('totp_redirect');
}
test('preserves a return URL on another host under the configured private TLD', () => {
assert.equal(capturedRedirect('https://plex.sami/web/'), 'https://plex.sami/web/');
});
test('preserves a same-origin return URL', () => {
assert.equal(capturedRedirect('https://status.sami/settings'), 'https://status.sami/settings');
});
test('rejects lookalike domains, plaintext cross-host URLs, and non-web schemes', () => {
assert.equal(capturedRedirect('https://plex.sami.evil.example/'), undefined);
assert.equal(capturedRedirect('http://plex.sami/'), undefined);
assert.equal(capturedRedirect('javascript:alert(1)'), undefined);
});
test('accepts relative same-origin paths and protocol-relative HTTPS private hosts', () => {
assert.equal(capturedRedirect('/settings'), '/settings');
assert.equal(capturedRedirect('//plex.sami/web/'), '//plex.sami/web/');
});
test('normalizes a configured TLD without a leading dot', () => {
assert.equal(capturedRedirect('https://plex.sami/web/', 'sami'), 'https://plex.sami/web/');
});
test('builds the generic cross-host SSO landing URL and preserves the final path', () => {
assert.equal(
buildHandoffTarget('https://router.sami/config?tab=network#dns', 'one-time'),
'https://router.sami/dashcaddy-sso?token=one-time&return=%2Fconfig%3Ftab%3Dnetwork%23dns',
);
});
test('does not create cross-host handoffs for plaintext or lookalike destinations', () => {
assert.equal(buildHandoffTarget('http://router.sami/', 'one-time'), null);
assert.equal(buildHandoffTarget('https://router.sami.evil.example/', 'one-time'), null);
});
test('same-origin and tokenless destinations keep their direct URL', () => {
assert.equal(buildHandoffTarget('/settings', 'one-time'), 'https://status.sami/settings');
assert.equal(buildHandoffTarget('https://router.sami/config', ''), 'https://router.sami/config');
});