mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
Merge remote-tracking branch 'origin/main' into feat/onboarding-wizard
This commit is contained in:
commit
8ed46eef58
49 files changed
+3199
-307
No files matched your search
@@ -120,4 +120,41 @@ describe("Nightscout exact-origin policy", () => {
|
||||
reasonCode: "invalid_origin",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a loopback Nightscout grant working exactly as before", () => {
|
||||
// A host-networking self-host lists http://localhost:1337; the shared
|
||||
// floor must not turn that into a failed sync on upgrade.
|
||||
expect(parseNightscoutPrivateOrigins("http://localhost:1337")).toEqual(
|
||||
new Set(["http://localhost:1337"]),
|
||||
);
|
||||
expect(
|
||||
evaluateNightscoutOrigin(
|
||||
"http://localhost:1337",
|
||||
parseNightscoutPrivateOrigins("http://localhost:1337"),
|
||||
),
|
||||
).toMatchObject({ allowed: true, privateOriginApproved: true });
|
||||
expect(
|
||||
parseNightscoutPrivateOrigins("http://127.0.0.1:1337, http://[::1]:1337"),
|
||||
).toEqual(new Set(["http://127.0.0.1:1337", "http://[::1]:1337"]));
|
||||
});
|
||||
|
||||
it("names the entry and the reason when a metadata grant is listed, without its token (M2)", () => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
parseNightscoutPrivateOrigins(
|
||||
"https://cgm.lan, http://169.254.169.254:1337/?token=SECRET123",
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(Error);
|
||||
const message = (caught as Error).message;
|
||||
expect((caught as Error).name).toBe("NightscoutOriginConfigError");
|
||||
expect(message).toContain(
|
||||
'NIGHTSCOUT_PRIVATE_ORIGINS entry "http://169.254.169.254:1337/"',
|
||||
);
|
||||
expect(message).toMatch(/link-local.*cannot be granted/);
|
||||
expect(message).not.toContain("SECRET123");
|
||||
expect(message).not.toContain("token=");
|
||||
});
|
||||
});
|
||||
@@ -1,89 +1,62 @@
|
||||
import { z } from "zod/v4";
|
||||
import { isPublicUrl } from "@/lib/validations/notifications";
|
||||
import {
|
||||
canonicalOrigin,
|
||||
evaluateOriginGrant,
|
||||
INVALID_ORIGIN,
|
||||
parsePrivateOrigins,
|
||||
PRIVATE_ORIGIN_NOT_APPROVED_CODE,
|
||||
type OriginReason,
|
||||
type OriginVerdict,
|
||||
} from "@/lib/private-origin-policy";
|
||||
|
||||
export const NIGHTSCOUT_PRIVATE_ORIGIN_REASON =
|
||||
"private_origin_not_approved" as const;
|
||||
export const NIGHTSCOUT_INVALID_ORIGIN_REASON = "invalid_origin" as const;
|
||||
|
||||
export type NightscoutOriginReason =
|
||||
| typeof NIGHTSCOUT_PRIVATE_ORIGIN_REASON
|
||||
| typeof NIGHTSCOUT_INVALID_ORIGIN_REASON;
|
||||
|
||||
export interface NightscoutOriginVerdict {
|
||||
allowed: boolean;
|
||||
canonicalOrigin: string | null;
|
||||
privateOriginApproved: boolean;
|
||||
reasonCode: NightscoutOriginReason | null;
|
||||
}
|
||||
PRIVATE_ORIGIN_NOT_APPROVED_CODE;
|
||||
export const NIGHTSCOUT_INVALID_ORIGIN_REASON = INVALID_ORIGIN;
|
||||
|
||||
/**
|
||||
* Parse one exact http(s) origin.
|
||||
*
|
||||
* Credentials, paths, queries, and fragments are deliberately forbidden: the
|
||||
* operator grants a complete canonical scheme/host/port trust unit, never a
|
||||
* suffix, wildcard, capability URL, or prefix.
|
||||
* Thrown when `NIGHTSCOUT_PRIVATE_ORIGINS` holds an entry that is not a
|
||||
* grant. The message names the entry (scheme and host only) and the reason,
|
||||
* so the sync ledger and the connect form show the operator what to edit
|
||||
* instead of a bare "invalid entry". Loopback and `localhost` entries stay
|
||||
* valid grants exactly as before #947; the shared floor refuses only the
|
||||
* unspecified address, link-local and the metadata range.
|
||||
*/
|
||||
function canonicalOrigin(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
if (url.username || url.password) return null;
|
||||
if (url.pathname !== "/" || url.search || url.hash) return null;
|
||||
if (!url.hostname || url.hostname.includes("*")) return null;
|
||||
return url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
export class NightscoutOriginConfigError extends Error {
|
||||
constructor(redactedEntry: string, reason: string) {
|
||||
super(
|
||||
`Invalid NIGHTSCOUT_PRIVATE_ORIGINS entry "${redactedEntry}": ${reason}`,
|
||||
);
|
||||
this.name = "NightscoutOriginConfigError";
|
||||
}
|
||||
}
|
||||
|
||||
function sharesApprovedPrivateHostname(
|
||||
origin: string,
|
||||
privateOrigins: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const hostname = new URL(origin).hostname;
|
||||
export type NightscoutOriginReason = OriginReason;
|
||||
|
||||
for (const approvedOrigin of privateOrigins) {
|
||||
const approvedHostname = new URL(approvedOrigin).hostname;
|
||||
if (
|
||||
hostname === approvedHostname ||
|
||||
hostname.endsWith(`.${approvedHostname}`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
export type NightscoutOriginVerdict = OriginVerdict;
|
||||
|
||||
/**
|
||||
* Parse the server-only comma-separated exact-origin allowlist.
|
||||
*
|
||||
* Invalid non-empty entries fail startup/call-site evaluation loudly rather
|
||||
* than being skipped: partial acceptance makes an operator believe a private
|
||||
* integration is protected while silently changing which origin is trusted.
|
||||
* The grammar lives in `@/lib/private-origin-policy` and is shared with
|
||||
* `NOTIFICATION_PRIVATE_ORIGINS`. Invalid non-empty entries fail
|
||||
* startup/call-site evaluation loudly rather than being skipped: partial
|
||||
* acceptance makes an operator believe a private integration is protected
|
||||
* while silently changing which origin is trusted.
|
||||
*/
|
||||
export function parseNightscoutPrivateOrigins(
|
||||
raw: string | undefined,
|
||||
): ReadonlySet<string> {
|
||||
const origins = new Set<string>();
|
||||
for (const entry of (raw ?? "").split(",")) {
|
||||
const trimmed = entry.trim();
|
||||
if (!trimmed) continue;
|
||||
const origin = canonicalOrigin(trimmed);
|
||||
if (!origin) {
|
||||
throw new Error("Invalid NIGHTSCOUT_PRIVATE_ORIGINS entry");
|
||||
}
|
||||
origins.add(origin);
|
||||
}
|
||||
return origins;
|
||||
return parsePrivateOrigins(raw, (redactedEntry, reason) => {
|
||||
throw new NightscoutOriginConfigError(redactedEntry, reason);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one user-supplied Nightscout base URL against server policy.
|
||||
*
|
||||
* Exact operator membership wins before the ordinary public-host verdict so a
|
||||
* private DNS name can be trusted without granting its suffix or sibling
|
||||
* ports. Public origins remain supported without configuration.
|
||||
* A Nightscout base URL is itself a bare origin, so the strict grant grammar
|
||||
* applies to the input as well: a path, query, fragment or credential part
|
||||
* is `invalid_origin`, not merely unapproved.
|
||||
*/
|
||||
export function evaluateNightscoutOrigin(
|
||||
value: string,
|
||||
@@ -98,43 +71,7 @@ export function evaluateNightscoutOrigin(
|
||||
reasonCode: NIGHTSCOUT_INVALID_ORIGIN_REASON,
|
||||
};
|
||||
}
|
||||
|
||||
if (privateOrigins.has(origin)) {
|
||||
return {
|
||||
allowed: true,
|
||||
canonicalOrigin: origin,
|
||||
privateOriginApproved: true,
|
||||
reasonCode: null,
|
||||
};
|
||||
}
|
||||
|
||||
// An exact grant must not accidentally become a hostname suffix grant.
|
||||
// Deny related hosts before the generic public-host fallback: private DNS
|
||||
// names such as cgm.lan may otherwise look syntactically public here.
|
||||
if (sharesApprovedPrivateHostname(origin, privateOrigins)) {
|
||||
return {
|
||||
allowed: false,
|
||||
canonicalOrigin: origin,
|
||||
privateOriginApproved: false,
|
||||
reasonCode: NIGHTSCOUT_PRIVATE_ORIGIN_REASON,
|
||||
};
|
||||
}
|
||||
|
||||
if (isPublicUrl(origin)) {
|
||||
return {
|
||||
allowed: true,
|
||||
canonicalOrigin: origin,
|
||||
privateOriginApproved: false,
|
||||
reasonCode: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
allowed: false,
|
||||
canonicalOrigin: origin,
|
||||
privateOriginApproved: false,
|
||||
reasonCode: NIGHTSCOUT_PRIVATE_ORIGIN_REASON,
|
||||
};
|
||||
return evaluateOriginGrant(origin, privateOrigins);
|
||||
}
|
||||
|
||||
export function configuredNightscoutPrivateOrigins(): ReadonlySet<string> {
|
||||
|
||||
@@ -228,6 +228,63 @@ export function isPublicIp(ip: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a resolved address may be dialled under an operator's
|
||||
* exact-origin grant (`NOTIFICATION_PRIVATE_ORIGINS`,
|
||||
* `NIGHTSCOUT_PRIVATE_ORIGINS`).
|
||||
*
|
||||
* A grant exists so a relay on the operator's own network can be reached, so
|
||||
* RFC1918, CGNAT (a Tailscale address), IPv6 unique-local and loopback stay
|
||||
* grantable: an operator on host networking who lists an exact loopback
|
||||
* origin with its port has made the same deliberate decision as one who
|
||||
* lists a LAN origin. Two classes are refused even when the operator lists a
|
||||
* name that resolves there, because no relay lives on them: the unspecified
|
||||
* address is a resolver misfire, and link-local is the cloud-metadata
|
||||
* endpoint. The transition formats (`::ffff:`, 6to4, NAT64) are unwrapped
|
||||
* first so an IPv6 spelling of those does not slip past the IPv4 verdict.
|
||||
*/
|
||||
export function isOperatorGrantableIp(ip: string): boolean {
|
||||
if (!ip) return false;
|
||||
const lower = ip.toLowerCase();
|
||||
|
||||
const family = isIP(lower);
|
||||
if (family === 4) {
|
||||
const parsed = parseIpv4Strict(lower);
|
||||
if (!parsed) return false;
|
||||
return !isNeverGrantableIpv4(parsed);
|
||||
}
|
||||
|
||||
if (family === 6) {
|
||||
const bytes = parseIpv6Bytes(lower);
|
||||
if (!bytes) return false;
|
||||
|
||||
// Unspecified and link-local IPv6. Unique-local (fc00::/7) and loopback
|
||||
// (::1) deliberately stay out of this list: they are what an operator
|
||||
// on a private or host network lists. `::1` is answered before the
|
||||
// embedded-IPv4 unwrap, which would otherwise read it as the
|
||||
// IPv4-compatible spelling of 0.0.0.1 and refuse it as unspecified.
|
||||
if (bytesEqual(bytes, 0, Array(16).fill(0))) return false;
|
||||
if (bytesEqual(bytes, 0, Array(15).fill(0)) && bytes[15] === 1) {
|
||||
return true;
|
||||
}
|
||||
if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) return false;
|
||||
|
||||
const embedded = embeddedIpv4(bytes);
|
||||
if (embedded && isNeverGrantableIpv4(embedded)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 0/8 and 169.254/16: the ranges no operator grant may open. */
|
||||
function isNeverGrantableIpv4(ip: [number, number, number, number]): boolean {
|
||||
const [a, b] = ip;
|
||||
if (a === 0) return true;
|
||||
if (a === 169 && b === 254) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isPublicUrl(url: string): boolean {
|
||||
try {
|
||||
// Pre-URL guard #1: the WHATWG URL parser interprets leading-zero IPv4
|
||||
@@ -281,41 +338,64 @@ export function isPublicUrl(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export const ntfySettingsSchema = z.object({
|
||||
serverUrl: z
|
||||
.url("Ungültige Server-URL")
|
||||
.max(200)
|
||||
.refine(
|
||||
(url) => isPublicUrl(url),
|
||||
"Server-URL darf nicht auf interne Netzwerke zeigen",
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal("")),
|
||||
topic: z.string().max(100).optional().or(z.literal("")),
|
||||
authToken: z.string().max(200).optional().or(z.literal("")),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
/**
|
||||
* ntfy channel settings. The server URL is user-supplied and must pass the
|
||||
* target predicate at input time. The exported constant carries the plain
|
||||
* public floor (`isPublicUrl`) for the OpenAPI contract; the save route
|
||||
* builds the same shape with `isAllowedNotificationTarget`, which adds the
|
||||
* operator's `NOTIFICATION_PRIVATE_ORIGINS` grant (#947) on top of the floor
|
||||
* without this module having to read the environment.
|
||||
*/
|
||||
export function ntfySettingsSchemaWith(
|
||||
isAllowedTarget: (url: string) => boolean,
|
||||
) {
|
||||
return z.object({
|
||||
serverUrl: z
|
||||
.url("Ungültige Server-URL")
|
||||
.max(200)
|
||||
.refine(
|
||||
isAllowedTarget,
|
||||
"Server-URL darf nicht auf interne Netzwerke zeigen",
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal("")),
|
||||
topic: z.string().max(100).optional().or(z.literal("")),
|
||||
authToken: z.string().max(200).optional().or(z.literal("")),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
}
|
||||
|
||||
export const ntfySettingsSchema = ntfySettingsSchemaWith(isPublicUrl);
|
||||
|
||||
/**
|
||||
* Generic-webhook channel settings (v1.17.1). The URL is user-supplied and
|
||||
* must pass the SSRF floor (`isPublicUrl`) at input time; the dispatcher
|
||||
* re-checks it at fetch time via `safeFetch({ requirePublicHost: true })`. The
|
||||
* optional header name/value carry a shared secret (e.g. Gotify token).
|
||||
* must pass the target predicate at input time; the sender re-checks it at
|
||||
* fetch time through `safeFetch` with the connect-time pin. The exported
|
||||
* constant carries the plain public floor for the OpenAPI contract; the save
|
||||
* route passes `isAllowedNotificationTarget` so an origin the operator listed
|
||||
* in `NOTIFICATION_PRIVATE_ORIGINS` (#947) saves. The optional header
|
||||
* name/value carry a shared secret (e.g. Gotify token).
|
||||
*/
|
||||
export const webhookSettingsSchema = z.object({
|
||||
url: z
|
||||
.url("Ungültige Webhook-URL")
|
||||
.max(500)
|
||||
.refine(
|
||||
(url) => isPublicUrl(url),
|
||||
"Webhook-URL darf nicht auf interne Netzwerke zeigen",
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal("")),
|
||||
headerName: z.string().max(100).optional().or(z.literal("")),
|
||||
headerValue: z.string().max(500).optional().or(z.literal("")),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
export function webhookSettingsSchemaWith(
|
||||
isAllowedTarget: (url: string) => boolean,
|
||||
) {
|
||||
return z.object({
|
||||
url: z
|
||||
.url("Ungültige Webhook-URL")
|
||||
.max(500)
|
||||
.refine(
|
||||
isAllowedTarget,
|
||||
"Webhook-URL darf nicht auf interne Netzwerke zeigen",
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal("")),
|
||||
headerName: z.string().max(100).optional().or(z.literal("")),
|
||||
headerValue: z.string().max(500).optional().or(z.literal("")),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
}
|
||||
|
||||
export const webhookSettingsSchema = webhookSettingsSchemaWith(isPublicUrl);
|
||||
|
||||
/**
|
||||
* Email channel settings (v1.17.1). The SMTP transport is operator-configured;
|
||||
|
||||
Reference in new issue
Block a user