Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f6203b2f7 | ||
|
|
b40cb6458b | ||
|
|
54e8042764 | ||
|
|
fadbfc8eb5 | ||
|
|
d8f9df7e77 | ||
|
|
86df178022 | ||
|
|
d45ebb8f39 | ||
|
|
a2ab1f85eb | ||
|
|
be798a9bc2 | ||
|
|
8a512774d7 | ||
|
|
592a9fd939 | ||
|
|
6d5b1992b5 | ||
|
|
649c714aea | ||
|
|
0d46225efc | ||
|
|
140ef8726b | ||
|
|
0cc278abf1 | ||
|
|
003b152230 | ||
|
|
75f835641f | ||
|
|
872923dba2 | ||
|
|
10f2bf707b | ||
|
|
f42e761e52 | ||
|
|
e208e05b83 | ||
|
|
ba21dad550 | ||
|
|
09d2451f2c | ||
|
|
e69a93a825 | ||
|
|
96e2ef8609 | ||
|
|
d450580ef5 | ||
|
|
7143c36187 | ||
|
|
7682cb77bf |
+18
-7
@@ -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)
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
**Self-hosted dashboard for managing Docker apps with automatic SSL, DNS, and reverse proxy configuration.**
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## 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 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
@@ -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 |
+240
-29
@@ -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);
|
||||
@@ -194,18 +373,22 @@ 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 --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();
|
||||
|
||||
@@ -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
|
||||
@@ -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){
|
||||
<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.message)})
|
||||
})()</script></body></html>`;
|
||||
${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'))})`
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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;
|
||||
Executable
+57
@@ -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'
|
||||
Executable
+24
@@ -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.'
|
||||
@@ -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
|
||||
|
||||
@@ -34,6 +34,9 @@ function assembleContext({
|
||||
servicesStateManager,
|
||||
configStateManager,
|
||||
|
||||
// DC-053 share store
|
||||
shareStore,
|
||||
|
||||
// Managers
|
||||
credentialManager,
|
||||
authManager,
|
||||
@@ -192,6 +195,9 @@ function assembleContext({
|
||||
servicesStateManager,
|
||||
configStateManager,
|
||||
|
||||
// DC-053 share store
|
||||
shareStore,
|
||||
|
||||
// Managers
|
||||
credentialManager,
|
||||
authManager,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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': {
|
||||
@@ -206,18 +211,7 @@ class WorkflowEngine extends EventEmitter {
|
||||
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);
|
||||
@@ -248,6 +242,47 @@ class WorkflowEngine extends EventEmitter {
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -341,7 +401,15 @@ class WorkflowEngine extends EventEmitter {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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' },
|
||||
@@ -573,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);
|
||||
|
||||
})();
|
||||
@@ -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; }
|
||||
|
||||
Vendored
+91
-91
File diff suppressed because one or more lines are too long
@@ -939,6 +939,10 @@
|
||||
<footer class="dashcaddy-footer">
|
||||
<span class="footer-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
@@ -249,20 +249,31 @@
|
||||
// back to window._showTotpOverlay() in `show()` below.
|
||||
window.__dc_049_handled = true;
|
||||
|
||||
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.
|
||||
const returnUrl = urlParams.get('return');
|
||||
if (returnUrl) {
|
||||
function isAllowedReturnUrl(returnUrl) {
|
||||
try {
|
||||
const parsed = new URL(returnUrl, window.location.origin);
|
||||
if (parsed.origin === window.location.origin) {
|
||||
try { sessionStorage.setItem('totp_redirect', returnUrl); } catch (_) {}
|
||||
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;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.get('auth') === 'required') {
|
||||
// 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 && 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
@@ -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
|
||||
|
||||
@@ -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 operator’s 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>
|
||||
@@ -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 operator’s 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>
|
||||
@@ -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>
|
||||
@@ -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
@@ -1,4 +1,4 @@
|
||||
const CACHE = 'dashcaddy-shell-1b7c08184e';
|
||||
const CACHE = 'dashcaddy-shell-4912a7d0d0';
|
||||
const PRECACHE = [
|
||||
'/',
|
||||
'/index.html',
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
Reference in New Issue
Block a user