Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nk-auth-form-gated-paths.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ingram-tech/nk-auth": minor
---

`FORM_GATED_AUTH_PATHS`: the Better Auth endpoints a site serves through nk-forms (sign-up, password reset request, verification resend). Pass them as `disabledPaths` so the raw HTTP routes cannot bypass the bot gate and per-address limits; server-side `auth.api.*` calls keep working. The README now sends the set-password link server-side to the session's own address.
21 changes: 16 additions & 5 deletions packages/nk-auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -781,16 +781,27 @@ export default async function Security() {

**Set a password without a current one.** A social-only user has no current
password to verify, so the re-auth is an emailed reset link — clicking it proves
account ownership. Trigger it with the standard client call; there is no separate
"set password" endpoint:
account ownership. Send it server-side, from a session-gated route or server
action, to the session's own address; there is no separate "set password"
endpoint:

```ts
await authClient.requestPasswordReset({
email,
redirectTo: "/reset-password", // your token-consumer page (below)
"use server";
const user = await requireUser();
await auth.api.requestPasswordReset({
body: { email: user.email, redirectTo: "/reset-password" }, // your token-consumer page (below)
});
```

**Close the raw endpoints the forms wrap.** A site that serves sign-up and
forgot-password through `@ingram-tech/nk-forms` passes
`disabledPaths: [...FORM_GATED_AUTH_PATHS]` to `betterAuth()`. Otherwise
`POST /auth/sign-up/email`, `/auth/request-password-reset` and
`/auth/send-verification-email` skip the bot gate and the per-address limits,
and anyone can loop them at a victim's inbox. The forms keep working:
`disabledPaths` gates HTTP only, not `auth.api.*`. That is also why the
set-password link above is sent server-side, not through `authClient`.

Better Auth's reset endpoint **creates** the credential when the user has none,
so the same flow both resets a forgotten password and sets a first one. That
guarantee is pinned by `reset-password.test.ts` against a real instance, so a
Expand Down
61 changes: 61 additions & 0 deletions packages/nk-auth/src/form-gated.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { betterAuth } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory";
import { describe, expect, it } from "vitest";
import { FORM_GATED_AUTH_PATHS } from "./options.js";

// Pins the Better Auth behaviour FORM_GATED_AUTH_PATHS relies on: disabled
// paths refuse HTTP while the server-side API still runs.
describe("FORM_GATED_AUTH_PATHS", () => {
const sent: string[] = [];
const store: Record<string, Record<string, unknown>[]> = {
user: [
{
id: "u1",
name: "User",
email: "user@example.com",
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
},
],
account: [],
session: [],
verification: [],
};
const auth = betterAuth({
baseURL: "http://localhost:3000",
secret: "test-secret-at-least-32-chars-long-000",
database: memoryAdapter(store),
disabledPaths: [...FORM_GATED_AUTH_PATHS],
emailAndPassword: {
enabled: true,
sendResetPassword: async ({ user }) => {
sent.push(user.email);
},
},
emailVerification: { sendVerificationEmail: async () => {} },
});

it.each(FORM_GATED_AUTH_PATHS)("answers 404 over HTTP on %s", async (path) => {
const response = await auth.handler(
new Request(`http://localhost:3000/api/auth${path}`, {
method: "POST",
headers: {
"content-type": "application/json",
origin: "http://localhost:3000",
},
body: JSON.stringify({
email: "user@example.com",
password: "x".repeat(12),
name: "X",
}),
}),
);
expect(response.status).toBe(404);
});

it("still serves the server-side API", async () => {
await auth.api.requestPasswordReset({ body: { email: "user@example.com" } });
expect(sent).toEqual(["user@example.com"]);
});
});
1 change: 1 addition & 0 deletions packages/nk-auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
type AuthEmailMessage,
type AuthEmailUser,
bcryptPassword,
FORM_GATED_AUTH_PATHS,
makeEmailSenders,
makePasskeyOptions,
type PasskeyConfig,
Expand Down
15 changes: 15 additions & 0 deletions packages/nk-auth/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ export { uuidGenerateId } from "./id.js";
* presets live in `./jwt` and `./organization`. See the package README.
*/

/**
* Better Auth endpoints a site serves through `@ingram-tech/nk-forms` (bot gate,
* per-client and per-address limits). Pass them as `disabledPaths` so the raw
* HTTP routes answer 404 and cannot bypass the form. The forms' server-side
* `auth.api.*` calls keep working: Better Auth checks `disabledPaths` in its
* HTTP router only. A signed-in "send me a set-password link" then goes through
* a session-gated route that calls `auth.api.requestPasswordReset` for the
* session's own email.
*/
export const FORM_GATED_AUTH_PATHS: readonly string[] = [
"/sign-up/email",
"/request-password-reset",
"/send-verification-email",
];

/**
* `emailAndPassword.password` config that hashes/verifies with bcrypt.
*
Expand Down