Actions.ts overview
Form actions for the credential flows. credentialAction copies every Set-Cookie onto event.cookies, redirects only through safeRedirect, tells wrong credentials, throttling and service failure apart, and returns CredentialPending for a 202. SvelteKit’s redirect and fail are passed in, so the package does not depend on SvelteKit.
Exports Grouped by Category
- actions
- cookies
- models
- ActionEvent (interface)
- CookieOptions (interface)
- CredentialActionOptions (type alias)
- CredentialFailure (interface)
- CredentialFailureKind (type alias)
- CredentialPending (interface)
- CredentialRejected (interface)
- CredentialRequestOptions (interface)
- CredentialResult (type alias)
- CredentialSignedIn (interface)
- Kit (interface)
- RemoteFormKit (interface)
- RemoteKit (interface)
- remote functions
actions
credentialAction
Build a form action for a credential flow.
The action submits the form through submitCredential. On a session it redirects (303) to the validated target, with the Set-Cookie headers relayed. On a 202 (no session issued: a second factor is pending, or the address must be verified first) it returns the CredentialPending without redirecting. Otherwise it returns fail(status, CredentialFailure), with a status per CredentialFailureKind.
Example
import { deepStrictEqual } from "node:assert"
import { credentialAction } from "@thomasfosterau/effect-auth-sveltekit/Actions"
const kit = {
redirect: (status: 303, location: string): never => {
throw { status, location }
},
fail: <Data>(status: number, data: Data) => ({ status, data })
}
const signIn = credentialAction(kit, {
fetch: async () => new Response(null, { status: 429, headers: { "retry-after": "30" } }),
endpoint: "https://auth.internal/api/auth/sessions",
// Sign in with a password credential: a `sessions` document.
body: (form) => ({
data: {
type: "sessions",
attributes: {
credential: {
method: "password",
email: String(form.get("email") ?? ""),
password: String(form.get("password") ?? "")
}
}
}
}),
fields: (form) => ({ email: String(form.get("email") ?? "") }),
fallback: "/"
})
const form = new FormData()
form.set("email", "ada@example.com")
form.set("password", "hunter2")
const result = await signIn({
request: new Request("https://app.example/login", { method: "POST", body: form }),
url: new URL("https://app.example/login?redirect=/dashboard"),
getClientAddress: () => "203.0.113.9",
cookies: { set: () => undefined }
})
deepStrictEqual(result, {
status: 429,
data: {
kind: "rate-limited",
message: "Too many attempts. Please wait and try again.",
retryAfterSeconds: 30,
fields: { email: "ada@example.com" }
}
})
Signature
declare const credentialAction: <Failure, Fields>(
kit: Kit<Failure, Fields>,
options: CredentialActionOptions<Fields>
) => (event: ActionEvent) => Promise<Failure | CredentialPending<Fields>>
Since v0.1.0
submitCredential
Submit a credential to the auth handler on behalf of one request: the core the form-action and remote-function helpers share.
It POSTs options.body(input) to endpoint, forwarding the browser’s Origin and User-Agent so the handler’s CSRF check sees the real client, and the client address (clientAddress, by default event.getClientAddress()) in one header for its rate limits. The browser’s own X-Forwarded-For and CF-Connecting-IP are dropped unless forwardClientIpHeaders is on. On a 202 (no session issued: a second factor is pending, or the address must be verified first) it answers CredentialPending; a 202 whose body is not the handler’s pending document counts as unavailable. On any other 2xx it relays the Set-Cookie headers onto event.cookies and answers CredentialSignedIn with the safeRedirect-validated target. Otherwise it answers CredentialRejected. It never throws for the handler’s answer: a failing fetch is unavailable too.
Signature
declare const submitCredential: <Input, Fields>(
event: ActionEvent,
input: Input,
options: CredentialRequestOptions<Input, Fields>
) => Promise<CredentialResult<Fields>>
Since v0.2.0
cookies
parseSetCookie
Parse one Set-Cookie header into a name, a value and SvelteKit cookie options. Returns None for a header with no name= pair.
Signature
declare const parseSetCookie: (
header: string
) => Option.Option<{ readonly name: string; readonly value: string; readonly options: CookieOptions }>
Since v0.1.0
models
ActionEvent (interface)
The part of SvelteKit’s RequestEvent a credential action reads and writes. @sveltejs/kit’s RequestEvent satisfies it.
Signature
export interface ActionEvent {
readonly request: Request
readonly url: URL
/** The client's address as the SvelteKit adapter knows it. */
readonly getClientAddress: () => string
readonly cookies: {
readonly set: (name: string, value: string, options: CookieOptions) => void
}
}
Since v0.1.0
CookieOptions (interface)
The cookie attributes relayed from a Set-Cookie header, in the shape SvelteKit’s cookies.set takes. path is always present: SvelteKit requires it.
Signature
export interface CookieOptions {
path: string
domain?: string
maxAge?: number
expires?: Date
httpOnly?: boolean
secure?: boolean
sameSite?: "strict" | "lax" | "none"
partitioned?: boolean
}
Since v0.1.0
CredentialActionOptions (type alias)
Options for credentialAction: CredentialRequestOptions over the submitted FormData.
Signature
type CredentialActionOptions<Fields> = CredentialRequestOptions<FormData, Fields>
Since v0.1.0
CredentialFailure (interface)
What a failed credential action returns through SvelteKit’s fail: the kind, a message for the form, the seconds to wait for a 429 when the handler said, and whatever form fields the action echoes back.
Signature
export interface CredentialFailure<Fields> {
readonly kind: CredentialFailureKind
readonly message: string
readonly retryAfterSeconds: number | null
readonly fields: Fields
}
Since v0.1.0
CredentialFailureKind (type alias)
Why a credential action failed:
invalid: the handler answered400or401(bad input, or wrong credentials).rate-limited: the handler answered429.unavailable: anything else (a 5xx, or the call failing outright).
Signature
type CredentialFailureKind = "invalid" | "rate-limited" | "unavailable"
Since v0.1.0
CredentialPending (interface)
What a credential action returns, as a successful action result, when the handler answered 202 Accepted: it took the credential but issued no session. Either secondFactor is the challenge to redeem (POST /second-factor-challenges/verifications, citing token), or it is null and needsEmailVerification says the address must be verified first (a sign-up under antiEnumeration always answers this way). fields is what CredentialActionOptions.fields echoes back.
Signature
export interface CredentialPending<Fields> {
readonly kind: "pending"
readonly secondFactor: {
/** The challenge token: the id of the `second-factor-challenges` resource. */
readonly token: string
/** When the challenge lapses, as the handler's ISO 8601 timestamp. */
readonly expiresAt: string
} | null
readonly needsEmailVerification: boolean
readonly fields: Fields
}
Since v0.1.0
CredentialRejected (interface)
The handler refused the credential or failed: the form failure, and the status a form action reports it with (one per CredentialFailureKind).
Signature
export interface CredentialRejected<Fields> {
readonly kind: "failed"
readonly status: number
readonly failure: CredentialFailure<Fields>
}
Since v0.2.0
CredentialRequestOptions (interface)
Options for submitCredential and the helpers built on it, for a credential submitted as an Input: the submitted FormData for a form action, or whatever a remote function receives.
Signature
export interface CredentialRequestOptions<Input, Fields> {
/**
* Send the request to the auth handler: the service binding's `fetch`, or
* the in-process handler.
*/
readonly fetch: (request: Request) => Promise<Response>
/** The auth endpoint to POST to, as an absolute URL (for example `https://auth.internal/api/auth/sessions`). */
readonly endpoint: string
/**
* The body to send, built from the submitted input: for the auth handler's
* credential flows, a JSON:API document (`POST /sessions` takes a `sessions`
* document whose `credential` attribute names the method).
*/
readonly body: (input: Input) => Schema.Json
/**
* The body's media type. Default `application/vnd.api+json`, what the auth
* handler's credential flows accept; pass `application/json` for an endpoint
* that takes plain JSON.
*/
readonly contentType?: string
/** The input fields to echo back on failure (never the password). */
readonly fields: (input: Input) => Fields
/**
* The post-sign-in target the client asked for, before validation. Default:
* the {@link CredentialRequestOptions.redirectParam} query parameter of
* `event.url`. A remote function's event is the remote call's, not the
* page's, so read the target from the input there (a hidden field, say).
* Whatever it returns goes through `safeRedirect`.
*/
readonly target?: (input: Input, event: ActionEvent) => string | null
/** The query parameter that carries the post-sign-in target. Default `redirect`. */
readonly redirectParam?: string
/** Where to go when the target is missing or unsafe. */
readonly fallback: string
/** Override the message per failure kind. */
readonly messages?: Partial<Record<CredentialFailureKind, string>>
/**
* The client's address, sent to the auth handler in
* {@link CredentialRequestOptions.clientAddressHeader}. Default
* `event.getClientAddress()`; no header is sent when it answers `undefined`
* or throws (an adapter that cannot tell). Configure the auth handler to
* trust that one header, for example
* `trustedProxy: ClientIP.trustedHeader("x-forwarded-for")`.
*/
readonly clientAddress?: (event: ActionEvent) => string | undefined
/** The header the client address is sent in. Default `x-forwarded-for`. */
readonly clientAddressHeader?: string
/**
* Forward the browser's own `x-forwarded-for` and `cf-connecting-ip` too.
* Default `false`: off Cloudflare the browser chose their values. Turn it on
* only when an edge in front of the app sets them; the client address
* header still carries `clientAddress`'s answer.
*/
readonly forwardClientIpHeaders?: boolean
}
Since v0.2.0
CredentialResult (type alias)
What submitCredential answers: a session (cookies relayed), a pending next step (no session yet), or a failure.
Signature
type CredentialResult<Fields> = CredentialSignedIn | CredentialPending<Fields> | CredentialRejected<Fields>
Since v0.2.0
CredentialSignedIn (interface)
The handler issued a session: its Set-Cookie headers are already relayed onto event.cookies, and location is the validated target to go to.
Signature
export interface CredentialSignedIn {
readonly kind: "signed-in"
readonly location: string
}
Since v0.2.0
Kit (interface)
SvelteKit’s redirect and fail, passed in so this package doesn’t import @sveltejs/kit. Pass { redirect, fail } from @sveltejs/kit.
Signature
export interface Kit<Failure, Fields> {
readonly redirect: (status: 303, location: string) => never
readonly fail: (status: number, data: CredentialFailure<Fields>) => Failure
}
Since v0.1.0
RemoteFormKit (interface)
RemoteKit plus SvelteKit’s redirect (from @sveltejs/kit), for a remote form(), which may redirect.
Signature
export interface RemoteFormKit extends RemoteKit {
readonly redirect: (status: 303, location: string) => never
}
Since v0.2.0
RemoteKit (interface)
SvelteKit’s getRequestEvent (from $app/server), passed in so this package doesn’t import SvelteKit: what a remote function reads its request event from.
Signature
export interface RemoteKit {
readonly getRequestEvent: () => ActionEvent
}
Since v0.2.0
remote functions
credentialCommand
Build the handler of a SvelteKit remote command() for a credential flow.
A command cannot redirect, so it answers the whole CredentialResult: on signed-in the cookies are already set, and the caller navigates to location itself (goto(result.location)); pending and failed are as for credentialForm.
Example
import { deepStrictEqual } from "node:assert"
import { credentialCommand } from "@thomasfosterau/effect-auth-sveltekit/Actions"
const signIn = credentialCommand(
{
getRequestEvent: () => ({
request: new Request("https://app.example/_app/remote/sign-in", { method: "POST" }),
url: new URL("https://app.example/_app/remote/sign-in"),
getClientAddress: () => "203.0.113.9",
cookies: { set: () => undefined }
})
},
{
fetch: async () => new Response(null, { status: 429, headers: { "retry-after": "30" } }),
endpoint: "https://auth.internal/api/auth/sessions",
body: (input: { readonly email: string; readonly password: string }) => ({
data: { type: "sessions", attributes: { credential: { method: "password", ...input } } }
}),
fields: (input) => ({ email: input.email }),
fallback: "/"
}
)
deepStrictEqual(await signIn({ email: "ada@example.com", password: "hunter2" }), {
kind: "failed",
status: 429,
failure: {
kind: "rate-limited",
message: "Too many attempts. Please wait and try again.",
retryAfterSeconds: 30,
fields: { email: "ada@example.com" }
}
})
Signature
declare const credentialCommand: <Input, Fields>(
kit: RemoteKit,
options: CredentialRequestOptions<Input, Fields>
) => (input: Input) => Promise<CredentialResult<Fields>>
Since v0.2.0
credentialForm
Build the handler of a SvelteKit remote form() for a credential flow.
The same submission as credentialAction, through submitCredential, with a remote function’s envelope: the event comes from getRequestEvent(), a session redirects (303) to the validated target, and everything else is the form’s result (form.result on the page): the CredentialPending next step, or the CredentialFailure, whose kind tells wrong credentials (invalid) from throttling (rate-limited) and faults (unavailable). Input is whatever the remote form hands its handler (FormData, or the validated object of a schema’d form).
The event of a remote call is not the page’s, so pass CredentialRequestOptions.target to read the post-sign-in target from the input.
Example
import { deepStrictEqual, rejects } from "node:assert"
import { credentialForm } from "@thomasfosterau/effect-auth-sveltekit/Actions"
const relayed: Array<string> = []
const kit = {
// `getRequestEvent` from `$app/server` and `redirect` from `@sveltejs/kit`.
getRequestEvent: () => ({
request: new Request("https://app.example/_app/remote/sign-in", { method: "POST" }),
url: new URL("https://app.example/_app/remote/sign-in"),
getClientAddress: () => "203.0.113.9",
cookies: { set: (name: string) => void relayed.push(name) }
}),
redirect: (status: 303, location: string): never => {
throw { status, location }
}
}
const handler = (response: Response) =>
credentialForm(kit, {
fetch: async () => response,
endpoint: "https://auth.internal/api/auth/sessions",
body: (form: FormData) => ({
data: {
type: "sessions",
attributes: {
credential: {
method: "password",
email: String(form.get("email") ?? ""),
password: String(form.get("password") ?? "")
}
}
}
}),
fields: (form) => ({ email: String(form.get("email") ?? "") }),
target: (form) => String(form.get("redirect") ?? ""),
fallback: "/"
})
const form = new FormData()
form.set("email", "ada@example.com")
form.set("password", "hunter2")
form.set("redirect", "/dashboard")
// In `sign-in.remote.ts`: `export const signIn = form(handler(...))`.
const session = new Headers({ "set-cookie": "__Host-session=tok; Path=/; HttpOnly; Secure" })
await rejects(handler(new Response("{}", { status: 201, headers: session }))(form), {
status: 303,
location: "/dashboard"
})
deepStrictEqual(relayed, ["__Host-session"])
deepStrictEqual(await handler(new Response(null, { status: 401 }))(form), {
kind: "invalid",
message: "Invalid email or password.",
retryAfterSeconds: null,
fields: { email: "ada@example.com" }
})
Signature
declare const credentialForm: <Input, Fields>(
kit: RemoteFormKit,
options: CredentialRequestOptions<Input, Fields>
) => (input: Input) => Promise<CredentialPending<Fields> | CredentialFailure<Fields>>
Since v0.2.0