Stricter URL widget validation

This commit is contained in:
Kalle
2026-09-06 11:49:33 +03:00
parent 0461374771
commit 99f2de3bee
2 changed files with 43 additions and 7 deletions

29
app/form/fields.test.ts Normal file
View File

@@ -0,0 +1,29 @@
import * as v from "valibot";
import { describe, expect, test } from "vitest";
import { textField, textFieldOptional } from "./fields";
describe("textField", () => {
const schema = textField({ validate: "url", maxLength: 150 });
test.each([
["https://sendou.ink", true, "https URL"],
["http://sendou.ink", true, "http URL"],
["javascript:alert(1)", false, "javascript URL"],
["JavaScript:alert(1)", false, "javascript URL with mixed case protocol"],
["data:text/html,<script>alert(1)</script>", false, "data URL"],
["not a url", false, "not a URL at all"],
])("%s -> %s (%s)", (input, expected) => {
expect(v.safeParse(schema, input).success).toBe(expected);
});
});
describe("textFieldOptional", () => {
const schema = textFieldOptional({ validate: "url", maxLength: 150 });
test.each([
["https://sendou.ink", true, "https URL"],
["javascript:alert(1)", false, "javascript URL"],
])("%s -> %s (%s)", (input, expected) => {
expect(v.safeParse(schema, input).success).toBe(expected);
});
});

View File

@@ -40,6 +40,18 @@ import type {
TrophyOption,
} from "./types";
const httpUrlSchema = v.pipe(
v.string(),
v.url(),
v.check((value) => {
try {
return ["http:", "https:"].includes(new URL(value).protocol);
} catch {
return false;
}
}, "Only http(s) URLs are allowed."),
);
export const formRegistry = new WeakMap<object, FormField>();
/** Clones the schema first so shared instances (e.g. `id`, `stageId`) each get their own registry entry. */
@@ -155,12 +167,7 @@ export function textFieldOptional(
): v.GenericSchema<string | null, string | null> {
// validated as a plain string, so unlike other optional text fields it has no null fallback and its key stays required
if (args.validate === "url") {
return registerTextField(
v.pipe(v.string(), v.url()),
args,
false,
false,
) as never;
return registerTextField(httpUrlSchema, args, false, false) as never;
}
return registerTextField(
@@ -174,7 +181,7 @@ export function textFieldOptional(
export function textField(args: TextFieldArgs): v.GenericSchema<string> {
const schema =
args.validate === "url"
? v.pipe(v.string(), v.url())
? httpUrlSchema
: safeStringSchema({ min: args.minLength, max: args.maxLength });
return registerTextField(schema, args, true, false) as never;