Untrusted input
A request can send any fields, so take only the ones you want, and reject values you can’t use.
At a glance
| To | Write |
|---|---|
| take only the fields you want | Account.permit(await request.json(), "email", "handle") |
| return a 400 for a value you can’t use | catch TypeError and SyntaxError |
| query with a value from a request | check typeof token === "string" first |
| widen a query | rewhere and unscope, with names you chose |
The Models
The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:
import { ApplicationRecord } from "./application-record";
export class Account extends ApplicationRecord {}import { ApplicationRecord } from "./application-record";
// Its token is NULL once the invitation is accepted.
export class Invitation extends ApplicationRecord {}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: a77f61266d3a
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** accounts — last changed by 0001_create_tables.sql */
export const accounts = {
id: { type: "string", null: false, generateId: true },
email: { type: "string", null: false },
handle: { type: "string", null: false },
plan: "string",
seats: "integer",
} as const;
/** invitations — last changed by 0001_create_tables.sql */
export const invitations = {
id: { type: "string", null: false, generateId: true },
email: { type: "string", null: false },
token: "string",
acceptedAt: "datetime",
} as const;
/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
adapter: d1({ binding: "DB" }),
tables: {
accounts: { attributes: accounts, primaryKey: "id" },
invitations: { attributes: invitations, primaryKey: "id" },
},
models: { Account: "accounts", Invitation: "invitations" },
});
declare module "../models/account" {
interface Account extends TableAttributes<typeof accounts, (typeof Account)["attributes"]> {}
}
declare module "../models/invitation" {
interface Invitation
extends TableAttributes<typeof invitations, (typeof Invitation)["attributes"]> {}
}CREATE TABLE accounts (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
handle TEXT NOT NULL,
plan TEXT,
seats INTEGER
);
CREATE TABLE invitations (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
token TEXT,
accepted_at DATETIME
);CREATE TABLE accounts (
id UUID PRIMARY KEY,
email TEXT NOT NULL,
handle TEXT NOT NULL,
plan TEXT,
seats INTEGER
);
CREATE TABLE invitations (
id UUID PRIMARY KEY,
email TEXT NOT NULL,
token TEXT,
accepted_at TIMESTAMPTZ
);Permitting fields
Only permit the fields you want from a request:
import { class AccountAccount } from "./models/account";
export async function function signUp(request: Request): Promise<Account>signUp(request: Request<unknown, CfProperties<unknown>>request: interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>The **`Request`** interface of the Fetch API represents a resource request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)Request) {
const const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "email" | "handle">>
permitted = class AccountAccount.Model.permit<typeof Account, "email" | "handle">(this: typeof Account, input: unknown, ...names: ("email" | "handle")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "email" | "handle">>
Only the named attributes of untrusted input (a JSON body, `FormData` or
`URLSearchParams`):
`User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
dropped, and each value is cast as assigning it would be.permit(await request: Request<unknown, CfProperties<unknown>>request.Body.json<unknown>(): Promise<unknown> (+1 overload)[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)json(), "email", "handle"); // drops plan and seats
return class AccountAccount.create<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<Account> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or
not it was saved (check `isPersisted()`).create(const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "email" | "handle">>
permitted);
}Permitted values are cast to their attribute’s types, so "42" becomes 42 for an integer. Attribute types lists what each type accepts. A page number from a query string can go straight to paginate, which casts it too.
Using a schema library
If you validate requests with a schema library such as Zod or Valibot, pass the parsed result to the Model:
import { z } from "zod";
const SignUp = z.object({ email: z.string(), handle: z.string().min(3) });
const fields = SignUp.parse(await request.json());
const account = await Account.create(fields);
Returning a 400
A value that can’t be cast throws a TypeError, and a body that isn’t JSON throws a SyntaxError. Return a 400 for either:
import { class AccountAccount } from "./models/account";
export async function function updateAccount(request: Request): Promise<Response>updateAccount(request: Request<unknown, CfProperties<unknown>>request: interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>The **`Request`** interface of the Fetch API represents a resource request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)Request): interface Promise<T>Represents the completion of an asynchronous operationPromise<Response> {
const const account: Accountaccount = await class AccountAccount.OverloadedStatics.find: <typeof Account>(this: typeof Account, id: string | number) => Promise<Account> (+2 overloads)find(new var URL: new (url: string | URL, base?: string | URL) => URLThe **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)URL(request: Request<unknown, CfProperties<unknown>>request.Request<unknown, CfProperties<unknown>>.url: stringThe **`url`** read-only property of the Request interface contains the URL of the request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)url).URL.searchParams: URLSearchParamsThe **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)searchParams.URLSearchParams.get(name: string): string | nullThe **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)get("id") ?? "");
let let permitted: anypermitted;
try {
let permitted: anypermitted = class AccountAccount.Model.permit<typeof Account, "handle" | "seats">(this: typeof Account, input: unknown, ...names: ("handle" | "seats")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "handle" | "seats">>
Only the named attributes of untrusted input (a JSON body, `FormData` or
`URLSearchParams`):
`User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
dropped, and each value is cast as assigning it would be.permit(await request: Request<unknown, CfProperties<unknown>>request.Body.json<unknown>(): Promise<unknown> (+1 overload)[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)json(), "handle", "seats");
} catch (function (local var) error: unknownerror) {
if (function (local var) error: unknownerror instanceof var SyntaxError: SyntaxErrorConstructorSyntaxError || function (local var) error: unknownerror instanceof var TypeError: TypeErrorConstructorTypeError) {
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("Bad request", { ResponseInit.status?: number | undefinedstatus: 400 });
}
throw function (local var) error: unknownerror;
}
await const account: Accountaccount.Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.update(let permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly handle: {
readonly type: "string";
readonly null: false;
};
readonly plan: "string";
readonly seats: "integer";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "handle" | "seats">>
permitted);
return var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response.function json(data: any, init?: ResponseInit): ResponseThe **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)json(const account: Accountaccount);
}Querying with request values
Check that a value is a string before you query with it. An accepted invitation’s token is NULL, so an unchecked null would find one:
import { class InvitationInvitation } from "./models/invitation";
export async function function accept(request: Request): Promise<Response>accept(request: Request<unknown, CfProperties<unknown>>request: interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>The **`Request`** interface of the Fetch API represents a resource request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)Request): interface Promise<T>Represents the completion of an asynchronous operationPromise<Response> {
const { const token: stringtoken } = await request: Request<unknown, CfProperties<unknown>>request.Body.json<{
token: string;
}>(): Promise<{
token: string;
}> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)json<{ token: stringtoken: string }>();
if (typeof const token: stringtoken !== "string" || const token: stringtoken === "") {
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("Send the invitation's token", { ResponseInit.status?: number | undefinedstatus: 400 });
}
const const invitation: Invitation | nullinvitation = await class InvitationInvitation.findBy<typeof Invitation>(this: typeof Invitation, conditions: SafeSql | Conditions<Invitation>): Promise<Invitation | null>The first record matching `conditions` (in no particular order), or null.findBy({ token?: string | readonly (string | null)[] | Comparison<string> | null | undefinedtoken });
if (const invitation: Invitation | nullinvitation === null) return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("No such invitation", { ResponseInit.status?: number | undefinedstatus: 404 });
await const invitation: Invitationinvitation.Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
readonly token: "string";
readonly acceptedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.update({ token?: string | null | undefinedtoken: null, acceptedAt?: Date | null | undefinedacceptedAt: new var Date: DateConstructor
new () => Date (+4 overloads)
Date() });
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response(`Welcome, ${const invitation: Invitationinvitation.email: stringemail}`);
}JSON can send null or a list. findBy({ token: null }) matches rows whose token is NULL, and findBy({ token: [first, second] }) matches a row with either token.
findOrCreateBy, findOrInitializeBy, and createOrFindBy refuse a list. They throw a TypeError before they query, since their attributes become the new record’s values.
Rewriting queries
Pass rewhere and unscope the attribute names and values you chose, never a request’s. They widen a query, where where only narrows one, so Post.where({ published: true }).rewhere(await request.json()) would find any post the body names.
An association’s link to its owner always stays. user.posts().rewhere({ userId: 2 }) finds nothing, since no post belongs to both users.
Security lists what Active Record protects against, and what it leaves to your app.