create-mohit-next 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -2
- package/index.js +399 -0
- package/lib/features.js +358 -0
- package/lib/scaffold.js +471 -0
- package/package.json +40 -4
- package/templates/common/_editorconfig +12 -0
- package/templates/common/_gitattributes +5 -0
- package/templates/common/_github/dependabot.yml +14 -0
- package/templates/common/_github/workflows/ci.yml +66 -0
- package/templates/common/_husky/commit-msg +1 -0
- package/templates/common/_husky/pre-commit +1 -0
- package/templates/common/_nvmrc +1 -0
- package/templates/common/_prettierignore +15 -0
- package/templates/common/commitlint.config.mjs +10 -0
- package/templates/next/AGENTS.md +9 -0
- package/templates/next/Dockerfile +48 -0
- package/templates/next/README.md +328 -0
- package/templates/next/_dockerignore +13 -0
- package/templates/next/_env.example +20 -0
- package/templates/next/_gitignore +50 -0
- package/templates/next/docker-compose.yml +33 -0
- package/templates/next/e2e/rbac.spec.ts +69 -0
- package/templates/next/e2e/server.mjs +35 -0
- package/templates/next/eslint.config.mjs +33 -0
- package/templates/next/next.config.ts +47 -0
- package/templates/next/package.json +68 -0
- package/templates/next/playwright.config.ts +30 -0
- package/templates/next/public/robots.txt +6 -0
- package/templates/next/scripts/seed.ts +111 -0
- package/templates/next/src/app/(app)/admin/audit/page.tsx +99 -0
- package/templates/next/src/app/(app)/admin/page.tsx +92 -0
- package/templates/next/src/app/(app)/dashboard/page.tsx +120 -0
- package/templates/next/src/app/(app)/error.tsx +28 -0
- package/templates/next/src/app/(app)/layout.tsx +58 -0
- package/templates/next/src/app/(app)/loading.tsx +5 -0
- package/templates/next/src/app/(app)/reports/page.tsx +128 -0
- package/templates/next/src/app/(app)/settings/page.tsx +66 -0
- package/templates/next/src/app/(auth)/forgot-password/page.tsx +17 -0
- package/templates/next/src/app/(auth)/layout.tsx +18 -0
- package/templates/next/src/app/(auth)/login/page.tsx +18 -0
- package/templates/next/src/app/(auth)/register/page.tsx +18 -0
- package/templates/next/src/app/(auth)/reset-password/page.tsx +18 -0
- package/templates/next/src/app/api/account/password/route.ts +45 -0
- package/templates/next/src/app/api/account/route.ts +25 -0
- package/templates/next/src/app/api/account/sessions/route.ts +12 -0
- package/templates/next/src/app/api/admin/audit/route.ts +13 -0
- package/templates/next/src/app/api/admin/users/[id]/route.ts +61 -0
- package/templates/next/src/app/api/admin/users/route.ts +18 -0
- package/templates/next/src/app/api/auth/forgot-password/route.ts +47 -0
- package/templates/next/src/app/api/auth/login/route.ts +43 -0
- package/templates/next/src/app/api/auth/logout/route.ts +21 -0
- package/templates/next/src/app/api/auth/me/route.ts +21 -0
- package/templates/next/src/app/api/auth/register/route.ts +74 -0
- package/templates/next/src/app/api/auth/resend-verification/route.ts +25 -0
- package/templates/next/src/app/api/auth/reset-password/route.ts +43 -0
- package/templates/next/src/app/api/auth/verify-email/route.ts +29 -0
- package/templates/next/src/app/api/health/route.ts +27 -0
- package/templates/next/src/app/favicon.ico +0 -0
- package/templates/next/src/app/forbidden/page.tsx +47 -0
- package/templates/next/src/app/layout.tsx +55 -0
- package/templates/next/src/app/not-found.tsx +20 -0
- package/templates/next/src/app/opengraph-image.tsx +49 -0
- package/templates/next/src/app/page.tsx +165 -0
- package/templates/next/src/app/robots.ts +15 -0
- package/templates/next/src/app/sitemap.ts +13 -0
- package/templates/next/src/app/verify-email/page.tsx +23 -0
- package/templates/next/src/components/admin/user-actions.tsx +124 -0
- package/templates/next/src/components/admin/users-data-table.tsx +221 -0
- package/templates/next/src/components/admin/users-table.tsx +67 -0
- package/templates/next/src/components/auth/auth-card.tsx +41 -0
- package/templates/next/src/components/auth/can.tsx +34 -0
- package/templates/next/src/components/auth/forgot-password-form.tsx +76 -0
- package/templates/next/src/components/auth/form-field.tsx +40 -0
- package/templates/next/src/components/auth/login-form.tsx +87 -0
- package/templates/next/src/components/auth/password-input.tsx +43 -0
- package/templates/next/src/components/auth/register-form.tsx +117 -0
- package/templates/next/src/components/auth/reset-password-form.tsx +80 -0
- package/templates/next/src/components/auth/session-refresher.tsx +44 -0
- package/templates/next/src/components/auth/verify-email-banner.tsx +43 -0
- package/templates/next/src/components/auth/verify-email-status.tsx +44 -0
- package/templates/next/src/components/layout/nav-links.tsx +37 -0
- package/templates/next/src/components/layout/navbar.tsx +27 -0
- package/templates/next/src/components/layout/page-header.tsx +21 -0
- package/templates/next/src/components/layout/sidebar.tsx +83 -0
- package/templates/next/src/components/layout/skeletons.tsx +57 -0
- package/templates/next/src/components/layout/user-menu.tsx +118 -0
- package/templates/next/src/components/logo.tsx +16 -0
- package/templates/next/src/components/motion/fade-in.tsx +19 -0
- package/templates/next/src/components/providers/user-provider.tsx +60 -0
- package/templates/next/src/components/reports/animated-bar.tsx +24 -0
- package/templates/next/src/components/reports/role-chart.tsx +61 -0
- package/templates/next/src/components/reports/signups-chart.tsx +64 -0
- package/templates/next/src/components/role-badge.tsx +11 -0
- package/templates/next/src/components/settings/password-form.tsx +80 -0
- package/templates/next/src/components/settings/profile-form.tsx +63 -0
- package/templates/next/src/components/settings/sessions-card.tsx +70 -0
- package/templates/next/src/components/theme-toggle.tsx +61 -0
- package/templates/next/src/config/rbac.test.ts +89 -0
- package/templates/next/src/config/rbac.ts +170 -0
- package/templates/next/src/config/site.ts +4 -0
- package/templates/next/src/lib/api.ts +179 -0
- package/templates/next/src/lib/audit.ts +66 -0
- package/templates/next/src/lib/auth.ts +50 -0
- package/templates/next/src/lib/dal.ts +63 -0
- package/templates/next/src/lib/db.ts +35 -0
- package/templates/next/src/lib/email-templates.ts +55 -0
- package/templates/next/src/lib/email.ts +53 -0
- package/templates/next/src/lib/env.ts +90 -0
- package/templates/next/src/lib/http.ts +57 -0
- package/templates/next/src/lib/password-strength.test.ts +20 -0
- package/templates/next/src/lib/password-strength.ts +24 -0
- package/templates/next/src/lib/rate-limit.test.ts +47 -0
- package/templates/next/src/lib/rate-limit.ts +70 -0
- package/templates/next/src/lib/redirect.test.ts +23 -0
- package/templates/next/src/lib/redirect.ts +21 -0
- package/templates/next/src/lib/session.ts +71 -0
- package/templates/next/src/lib/theme.ts +32 -0
- package/templates/next/src/lib/tokens.ts +63 -0
- package/templates/next/src/lib/users.ts +196 -0
- package/templates/next/src/lib/validations/account.ts +20 -0
- package/templates/next/src/lib/validations/auth.test.ts +39 -0
- package/templates/next/src/lib/validations/auth.ts +66 -0
- package/templates/next/src/lib/validations/user.ts +13 -0
- package/templates/next/src/models/audit-log.ts +33 -0
- package/templates/next/src/models/auth-token.ts +26 -0
- package/templates/next/src/models/user.ts +35 -0
- package/templates/next/src/proxy.ts +57 -0
- package/templates/next/src/styles/app.css +1092 -0
- package/templates/next/src/types/user.ts +13 -0
- package/templates/next/tsconfig.json +34 -0
- package/templates/next/vitest.config.mts +13 -0
- package/templates/styles/css.css +580 -0
- package/templates/styles/shadcn.css +142 -0
- package/templates/styles/tailwind.css +140 -0
- package/templates/ui/css/components/alert-dialog.tsx +172 -0
- package/templates/ui/css/components/avatar.tsx +17 -0
- package/templates/ui/css/components/badge.tsx +18 -0
- package/templates/ui/css/components/button.tsx +41 -0
- package/templates/ui/css/components/card.tsx +33 -0
- package/templates/ui/css/components/dropdown-menu.tsx +230 -0
- package/templates/ui/css/components/input.tsx +7 -0
- package/templates/ui/css/components/label.tsx +7 -0
- package/templates/ui/css/components/native-select.tsx +23 -0
- package/templates/ui/css/components/skeleton.tsx +7 -0
- package/templates/ui/css/components/slot.tsx +30 -0
- package/templates/ui/css/components/table.tsx +31 -0
- package/templates/ui/css/utils.ts +16 -0
- package/templates/ui/shadcn/components/alert-dialog.tsx +199 -0
- package/templates/ui/shadcn/components/avatar.tsx +111 -0
- package/templates/ui/shadcn/components/badge.tsx +44 -0
- package/templates/ui/shadcn/components/button.tsx +66 -0
- package/templates/ui/shadcn/components/card.tsx +87 -0
- package/templates/ui/shadcn/components/dropdown-menu.tsx +268 -0
- package/templates/ui/shadcn/components/input.tsx +18 -0
- package/templates/ui/shadcn/components/label.tsx +20 -0
- package/templates/ui/shadcn/components/native-select.tsx +54 -0
- package/templates/ui/shadcn/components/skeleton.tsx +13 -0
- package/templates/ui/shadcn/components/table.tsx +115 -0
- package/templates/ui/shadcn/utils.ts +1 -0
- package/templates/ui/tailwind/components/alert-dialog.tsx +177 -0
- package/templates/ui/tailwind/components/avatar.tsx +36 -0
- package/templates/ui/tailwind/components/badge.tsx +29 -0
- package/templates/ui/tailwind/components/button.tsx +65 -0
- package/templates/ui/tailwind/components/card.tsx +70 -0
- package/templates/ui/tailwind/components/dropdown-menu.tsx +236 -0
- package/templates/ui/tailwind/components/input.tsx +17 -0
- package/templates/ui/tailwind/components/label.tsx +16 -0
- package/templates/ui/tailwind/components/native-select.tsx +32 -0
- package/templates/ui/tailwind/components/skeleton.tsx +13 -0
- package/templates/ui/tailwind/components/slot.tsx +34 -0
- package/templates/ui/tailwind/components/table.tsx +56 -0
- package/templates/ui/tailwind/utils.ts +1 -0
- package/templates/vite/Dockerfile +29 -0
- package/templates/vite/README.md +142 -0
- package/templates/vite/_dockerignore +14 -0
- package/templates/vite/_env.example +8 -0
- package/templates/vite/_gitignore +37 -0
- package/templates/vite/e2e/app.spec.ts +41 -0
- package/templates/vite/index.html +32 -0
- package/templates/vite/nginx.conf +26 -0
- package/templates/vite/package.json +61 -0
- package/templates/vite/playwright.config.ts +27 -0
- package/templates/vite/public/favicon.svg +1 -0
- package/templates/vite/src/App.test.tsx +28 -0
- package/templates/vite/src/App.tsx +26 -0
- package/templates/vite/src/components/home.tsx +121 -0
- package/templates/vite/src/components/layout/root-layout.tsx +18 -0
- package/templates/vite/src/components/layout/site-footer.tsx +10 -0
- package/templates/vite/src/components/layout/site-header.tsx +49 -0
- package/templates/vite/src/components/theme-toggle.tsx +90 -0
- package/templates/vite/src/env.ts +36 -0
- package/templates/vite/src/lib/theme.ts +26 -0
- package/templates/vite/src/main.tsx +13 -0
- package/templates/vite/src/pages/about.tsx +52 -0
- package/templates/vite/src/pages/not-found.tsx +33 -0
- package/templates/vite/src/router.ts +24 -0
- package/templates/vite/src/styles/app.css +281 -0
- package/templates/vite/src/test/setup.ts +21 -0
- package/templates/vite/tsconfig.app.json +31 -0
- package/templates/vite/tsconfig.json +7 -0
- package/templates/vite/tsconfig.node.json +23 -0
- package/templates/vite/vite.config.ts +30 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import mongoose from "mongoose";
|
|
4
|
+
|
|
5
|
+
import { env } from "@/lib/env";
|
|
6
|
+
|
|
7
|
+
type MongooseCache = {
|
|
8
|
+
conn: typeof mongoose | null;
|
|
9
|
+
promise: Promise<typeof mongoose> | null;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Cache the connection on globalThis so hot reloads in development (and
|
|
14
|
+
* concurrent requests in production) reuse one connection pool instead of
|
|
15
|
+
* opening a new one each time.
|
|
16
|
+
*/
|
|
17
|
+
const globalForMongoose = globalThis as typeof globalThis & { __mongoose?: MongooseCache };
|
|
18
|
+
const cached: MongooseCache = (globalForMongoose.__mongoose ??= { conn: null, promise: null });
|
|
19
|
+
|
|
20
|
+
export async function connectDB(): Promise<typeof mongoose> {
|
|
21
|
+
if (cached.conn) return cached.conn;
|
|
22
|
+
|
|
23
|
+
cached.promise ??= mongoose.connect(env().MONGODB_URI, {
|
|
24
|
+
bufferCommands: false,
|
|
25
|
+
serverSelectionTimeoutMS: 5_000,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
cached.conn = await cached.promise;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
cached.promise = null; // allow the next request to retry
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
return cached.conn;
|
|
35
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import { siteConfig } from "@/config/site";
|
|
4
|
+
import type { Email } from "@/lib/email";
|
|
5
|
+
|
|
6
|
+
function escapeHtml(value: string): string {
|
|
7
|
+
return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function layout(title: string, body: string, action: { label: string; url: string }) {
|
|
11
|
+
return `<!doctype html>
|
|
12
|
+
<html>
|
|
13
|
+
<body style="margin:0;padding:24px;background:#f5f5f5;font-family:system-ui,-apple-system,sans-serif;color:#171717">
|
|
14
|
+
<div style="max-width:480px;margin:0 auto;background:#fff;border-radius:12px;padding:32px">
|
|
15
|
+
<h1 style="margin:0 0 16px;font-size:20px">${escapeHtml(title)}</h1>
|
|
16
|
+
${body}
|
|
17
|
+
<p style="margin:24px 0">
|
|
18
|
+
<a href="${escapeHtml(action.url)}" style="display:inline-block;background:#171717;color:#fff;text-decoration:none;padding:10px 16px;border-radius:8px;font-weight:600">${escapeHtml(action.label)}</a>
|
|
19
|
+
</p>
|
|
20
|
+
<p style="margin:0;font-size:12px;color:#737373">If the button doesn't work, paste this link into your browser:<br>${escapeHtml(action.url)}</p>
|
|
21
|
+
</div>
|
|
22
|
+
<p style="text-align:center;font-size:12px;color:#a3a3a3">${escapeHtml(siteConfig.name)}</p>
|
|
23
|
+
</body>
|
|
24
|
+
</html>`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function passwordResetEmail(to: string, name: string, url: string): Email {
|
|
28
|
+
const greeting = `Hi ${name},`;
|
|
29
|
+
const line = "We received a request to reset your password. This link expires in 1 hour.";
|
|
30
|
+
const ignore = "If you didn't ask for this, you can ignore this email.";
|
|
31
|
+
return {
|
|
32
|
+
to,
|
|
33
|
+
subject: `Reset your ${siteConfig.name} password`,
|
|
34
|
+
text: `${greeting}\n\n${line}\n\n${url}\n\n${ignore}`,
|
|
35
|
+
html: layout(
|
|
36
|
+
"Reset your password",
|
|
37
|
+
`<p>${escapeHtml(greeting)}</p><p>${line}</p><p style="color:#737373">${ignore}</p>`,
|
|
38
|
+
{ label: "Reset password", url },
|
|
39
|
+
),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function verificationEmail(to: string, name: string, url: string): Email {
|
|
44
|
+
const greeting = `Hi ${name},`;
|
|
45
|
+
const line = `Please confirm your email address for ${siteConfig.name}. This link expires in 24 hours.`;
|
|
46
|
+
return {
|
|
47
|
+
to,
|
|
48
|
+
subject: `Verify your email for ${siteConfig.name}`,
|
|
49
|
+
text: `${greeting}\n\n${line}\n\n${url}`,
|
|
50
|
+
html: layout("Verify your email", `<p>${escapeHtml(greeting)}</p><p>${escapeHtml(line)}</p>`, {
|
|
51
|
+
label: "Verify email",
|
|
52
|
+
url,
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import { env } from "@/lib/env";
|
|
4
|
+
|
|
5
|
+
export type Email = {
|
|
6
|
+
to: string;
|
|
7
|
+
subject: string;
|
|
8
|
+
text: string;
|
|
9
|
+
html: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Sends an email with Resend (https://resend.com) using its REST API.
|
|
14
|
+
* Without RESEND_API_KEY the email is printed to the server console instead,
|
|
15
|
+
* so password resets and verification work out of the box in development.
|
|
16
|
+
*/
|
|
17
|
+
export async function sendEmail(email: Email): Promise<void> {
|
|
18
|
+
const { RESEND_API_KEY, EMAIL_FROM } = env();
|
|
19
|
+
|
|
20
|
+
if (!RESEND_API_KEY) {
|
|
21
|
+
console.info(
|
|
22
|
+
[
|
|
23
|
+
"",
|
|
24
|
+
"┌─ Email (set RESEND_API_KEY to send for real) ─────────────",
|
|
25
|
+
`│ To: ${email.to}`,
|
|
26
|
+
`│ Subject: ${email.subject}`,
|
|
27
|
+
"│",
|
|
28
|
+
...email.text.split("\n").map((line) => `│ ${line}`),
|
|
29
|
+
"└───────────────────────────────────────────────────────────",
|
|
30
|
+
"",
|
|
31
|
+
].join("\n"),
|
|
32
|
+
);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const res = await fetch("https://api.resend.com/emails", {
|
|
37
|
+
method: "POST",
|
|
38
|
+
headers: {
|
|
39
|
+
Authorization: `Bearer ${RESEND_API_KEY}`,
|
|
40
|
+
"Content-Type": "application/json",
|
|
41
|
+
},
|
|
42
|
+
body: JSON.stringify({
|
|
43
|
+
from: EMAIL_FROM,
|
|
44
|
+
to: email.to,
|
|
45
|
+
subject: email.subject,
|
|
46
|
+
text: email.text,
|
|
47
|
+
html: email.html,
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
50
|
+
if (!res.ok) {
|
|
51
|
+
throw new Error(`Resend responded ${res.status}: ${await res.text()}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// @feature env
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Server environment variables, validated with zod.
|
|
6
|
+
*
|
|
7
|
+
* Validation is lazy (on first use, not at import time) so `next build` and
|
|
8
|
+
* the Docker build work without any secrets present. Never import this from
|
|
9
|
+
* a Client Component: these values must stay on the server.
|
|
10
|
+
*/
|
|
11
|
+
const envSchema = z.object({
|
|
12
|
+
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
|
|
13
|
+
MONGODB_URI: z
|
|
14
|
+
.string({ error: "MONGODB_URI is required" })
|
|
15
|
+
.regex(/^mongodb(\+srv)?:\/\//, "MONGODB_URI must start with mongodb:// or mongodb+srv://"),
|
|
16
|
+
JWT_SECRET: z
|
|
17
|
+
.string({ error: "JWT_SECRET is required" })
|
|
18
|
+
.min(32, "JWT_SECRET must be at least 32 characters long"),
|
|
19
|
+
/** Public URL of the app, used for absolute links (emails, sitemap). */
|
|
20
|
+
APP_URL: z.url().default("http://localhost:3000"),
|
|
21
|
+
// @feature email
|
|
22
|
+
/** Optional: without it, emails are printed to the server console. */
|
|
23
|
+
RESEND_API_KEY: z.string().optional(),
|
|
24
|
+
EMAIL_FROM: z.string().default("onboarding@resend.dev"),
|
|
25
|
+
// @end email
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export type Env = z.infer<typeof envSchema>;
|
|
29
|
+
|
|
30
|
+
let cached: Env | undefined;
|
|
31
|
+
|
|
32
|
+
export function env(): Env {
|
|
33
|
+
if (cached) return cached;
|
|
34
|
+
const parsed = envSchema.safeParse(process.env);
|
|
35
|
+
if (!parsed.success) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Invalid environment variables (check .env.local):\n${z.prettifyError(parsed.error)}`,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
cached = parsed.data;
|
|
41
|
+
return cached;
|
|
42
|
+
}
|
|
43
|
+
// @end env
|
|
44
|
+
// @feature !env
|
|
45
|
+
/**
|
|
46
|
+
* Server environment variables.
|
|
47
|
+
*
|
|
48
|
+
* Read lazily (on first use) so `next build` works without any secrets.
|
|
49
|
+
* Never import this from a Client Component.
|
|
50
|
+
*/
|
|
51
|
+
export type Env = {
|
|
52
|
+
NODE_ENV: string;
|
|
53
|
+
MONGODB_URI: string;
|
|
54
|
+
JWT_SECRET: string;
|
|
55
|
+
APP_URL: string;
|
|
56
|
+
// @feature email
|
|
57
|
+
RESEND_API_KEY?: string;
|
|
58
|
+
EMAIL_FROM: string;
|
|
59
|
+
// @end email
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function required(name: string): string {
|
|
63
|
+
const value = process.env[name];
|
|
64
|
+
if (!value) throw new Error(`Missing environment variable ${name} (check .env.local)`);
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let cached: Env | undefined;
|
|
69
|
+
|
|
70
|
+
export function env(): Env {
|
|
71
|
+
cached ??= {
|
|
72
|
+
NODE_ENV: process.env.NODE_ENV ?? "development",
|
|
73
|
+
MONGODB_URI: required("MONGODB_URI"),
|
|
74
|
+
JWT_SECRET: required("JWT_SECRET"),
|
|
75
|
+
APP_URL: process.env.APP_URL ?? "http://localhost:3000",
|
|
76
|
+
// @feature email
|
|
77
|
+
RESEND_API_KEY: process.env.RESEND_API_KEY,
|
|
78
|
+
EMAIL_FROM: process.env.EMAIL_FROM ?? "onboarding@resend.dev",
|
|
79
|
+
// @end email
|
|
80
|
+
};
|
|
81
|
+
return cached;
|
|
82
|
+
}
|
|
83
|
+
// @end !env
|
|
84
|
+
|
|
85
|
+
export const isProduction = () => process.env.NODE_ENV === "production";
|
|
86
|
+
|
|
87
|
+
/** Absolute app URL without a trailing slash. Safe to call at build time. */
|
|
88
|
+
export function appUrl(): string {
|
|
89
|
+
return (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
|
|
90
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ApiErrorBody } from "@/lib/api";
|
|
2
|
+
|
|
3
|
+
/** Error thrown by apiFetch for non-2xx responses, carrying the API's error shape. */
|
|
4
|
+
export class HttpError extends Error {
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly code?: string;
|
|
7
|
+
readonly details?: unknown;
|
|
8
|
+
|
|
9
|
+
constructor(status: number, message: string, code?: string, details?: unknown) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "HttpError";
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.details = details;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Field errors from a 422 VALIDATION_ERROR response, if any. */
|
|
18
|
+
get fieldErrors(): Record<string, string[] | undefined> | undefined {
|
|
19
|
+
return this.code === "VALIDATION_ERROR" && this.details && typeof this.details === "object"
|
|
20
|
+
? (this.details as Record<string, string[] | undefined>)
|
|
21
|
+
: undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type ApiFetchInit = Omit<RequestInit, "body"> & { json?: unknown };
|
|
26
|
+
|
|
27
|
+
/** Small fetch wrapper for the app's JSON API (client or server). */
|
|
28
|
+
export async function apiFetch<T>(
|
|
29
|
+
url: string,
|
|
30
|
+
{ json, headers, ...init }: ApiFetchInit = {},
|
|
31
|
+
): Promise<T> {
|
|
32
|
+
const res = await fetch(url, {
|
|
33
|
+
...init,
|
|
34
|
+
headers: {
|
|
35
|
+
Accept: "application/json",
|
|
36
|
+
...(json !== undefined && { "Content-Type": "application/json" }),
|
|
37
|
+
...headers,
|
|
38
|
+
},
|
|
39
|
+
body: json !== undefined ? JSON.stringify(json) : undefined,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const data = (await res.json().catch(() => null)) as (T & Partial<ApiErrorBody>) | null;
|
|
43
|
+
if (!res.ok) {
|
|
44
|
+
const error = data?.error;
|
|
45
|
+
throw new HttpError(
|
|
46
|
+
res.status,
|
|
47
|
+
error?.message ?? res.statusText ?? "Request failed",
|
|
48
|
+
error?.code,
|
|
49
|
+
error?.details,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return data as T;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function getErrorMessage(error: unknown, fallback = "Something went wrong"): string {
|
|
56
|
+
return error instanceof Error && error.message ? error.message : fallback;
|
|
57
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { getPasswordStrength } from "./password-strength";
|
|
4
|
+
|
|
5
|
+
describe("getPasswordStrength", () => {
|
|
6
|
+
it("is empty for an empty password", () => {
|
|
7
|
+
expect(getPasswordStrength("")).toEqual({ score: 0, label: "" });
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it("rates short passwords as weak", () => {
|
|
11
|
+
expect(getPasswordStrength("Ab1!").score).toBe(1);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it("rewards length and variety", () => {
|
|
15
|
+
expect(getPasswordStrength("password").score).toBeLessThan(
|
|
16
|
+
getPasswordStrength("Correct-Horse-42").score,
|
|
17
|
+
);
|
|
18
|
+
expect(getPasswordStrength("Correct-Horse-Battery-42").label).toBe("Strong");
|
|
19
|
+
});
|
|
20
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type PasswordStrength = {
|
|
2
|
+
/** 0 (empty) to 4 (strong). */
|
|
3
|
+
score: 0 | 1 | 2 | 3 | 4;
|
|
4
|
+
label: "" | "Weak" | "Fair" | "Good" | "Strong";
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
const LABELS = ["", "Weak", "Fair", "Good", "Strong"] as const;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A quick, dependency-free estimate for UI feedback only. The real rule
|
|
11
|
+
* (minimum length) is enforced by the zod schema on the server.
|
|
12
|
+
*/
|
|
13
|
+
export function getPasswordStrength(password: string): PasswordStrength {
|
|
14
|
+
if (!password) return { score: 0, label: "" };
|
|
15
|
+
let points = 0;
|
|
16
|
+
if (password.length >= 8) points++;
|
|
17
|
+
if (password.length >= 12) points++;
|
|
18
|
+
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) points++;
|
|
19
|
+
if (/\d/.test(password)) points++;
|
|
20
|
+
if (/[^A-Za-z0-9]/.test(password)) points++;
|
|
21
|
+
if (password.length < 8) points = Math.min(points, 1);
|
|
22
|
+
const score = Math.max(1, Math.min(4, points)) as PasswordStrength["score"];
|
|
23
|
+
return { score, label: LABELS[score] };
|
|
24
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { getClientIp, rateLimit, resetRateLimits } from "./rate-limit";
|
|
4
|
+
|
|
5
|
+
afterEach(() => {
|
|
6
|
+
resetRateLimits();
|
|
7
|
+
vi.useRealTimers();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
describe("rateLimit", () => {
|
|
11
|
+
it("allows requests up to the limit, then blocks", () => {
|
|
12
|
+
const options = { limit: 3, windowMs: 60_000 };
|
|
13
|
+
expect(rateLimit("k", options).success).toBe(true);
|
|
14
|
+
expect(rateLimit("k", options).success).toBe(true);
|
|
15
|
+
expect(rateLimit("k", options).remaining).toBe(0);
|
|
16
|
+
const blocked = rateLimit("k", options);
|
|
17
|
+
expect(blocked.success).toBe(false);
|
|
18
|
+
expect(blocked.retryAfterMs).toBeGreaterThan(0);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("tracks keys separately", () => {
|
|
22
|
+
const options = { limit: 1, windowMs: 60_000 };
|
|
23
|
+
expect(rateLimit("a", options).success).toBe(true);
|
|
24
|
+
expect(rateLimit("b", options).success).toBe(true);
|
|
25
|
+
expect(rateLimit("a", options).success).toBe(false);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("resets after the window", () => {
|
|
29
|
+
vi.useFakeTimers();
|
|
30
|
+
const options = { limit: 1, windowMs: 1_000 };
|
|
31
|
+
expect(rateLimit("k", options).success).toBe(true);
|
|
32
|
+
expect(rateLimit("k", options).success).toBe(false);
|
|
33
|
+
vi.advanceTimersByTime(1_001);
|
|
34
|
+
expect(rateLimit("k", options).success).toBe(true);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe("getClientIp", () => {
|
|
39
|
+
it("uses the first X-Forwarded-For address", () => {
|
|
40
|
+
const req = new Request("http://x", { headers: { "x-forwarded-for": "1.2.3.4, 10.0.0.1" } });
|
|
41
|
+
expect(getClientIp(req)).toBe("1.2.3.4");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("falls back to 'unknown'", () => {
|
|
45
|
+
expect(getClientIp(new Request("http://x"))).toBe("unknown");
|
|
46
|
+
});
|
|
47
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixed-window rate limiting, kept in memory.
|
|
3
|
+
*
|
|
4
|
+
* Good for a single server instance (and for development). When you run
|
|
5
|
+
* several instances (serverless, multiple containers), swap the Map for a
|
|
6
|
+
* shared store such as Redis / Upstash so all instances see the same counts.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
type Bucket = { count: number; resetAt: number };
|
|
10
|
+
|
|
11
|
+
const globalForRateLimit = globalThis as typeof globalThis & {
|
|
12
|
+
__rateLimitBuckets?: Map<string, Bucket>;
|
|
13
|
+
};
|
|
14
|
+
const buckets: Map<string, Bucket> = (globalForRateLimit.__rateLimitBuckets ??= new Map());
|
|
15
|
+
|
|
16
|
+
export type RateLimitOptions = {
|
|
17
|
+
/** Max requests allowed per window. */
|
|
18
|
+
limit: number;
|
|
19
|
+
/** Window length in milliseconds. */
|
|
20
|
+
windowMs: number;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type RateLimitResult = {
|
|
24
|
+
success: boolean;
|
|
25
|
+
remaining: number;
|
|
26
|
+
/** Milliseconds until the window resets. */
|
|
27
|
+
retryAfterMs: number;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function sweep(now: number) {
|
|
31
|
+
// Cheap housekeeping so the map can't grow forever.
|
|
32
|
+
if (buckets.size < 10_000) return;
|
|
33
|
+
for (const [key, bucket] of buckets) if (bucket.resetAt <= now) buckets.delete(key);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function rateLimit(key: string, { limit, windowMs }: RateLimitOptions): RateLimitResult {
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
sweep(now);
|
|
39
|
+
let bucket = buckets.get(key);
|
|
40
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
41
|
+
bucket = { count: 0, resetAt: now + windowMs };
|
|
42
|
+
buckets.set(key, bucket);
|
|
43
|
+
}
|
|
44
|
+
bucket.count += 1;
|
|
45
|
+
return {
|
|
46
|
+
success: bucket.count <= limit,
|
|
47
|
+
remaining: Math.max(0, limit - bucket.count),
|
|
48
|
+
retryAfterMs: Math.max(0, bucket.resetAt - now),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Best-effort client IP (behind a proxy, make sure it sets X-Forwarded-For). */
|
|
53
|
+
export function getClientIp(req: Request): string {
|
|
54
|
+
const forwarded = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
|
|
55
|
+
return forwarded || req.headers.get("x-real-ip") || "unknown";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Clears all counters (useful in tests). */
|
|
59
|
+
export function resetRateLimits() {
|
|
60
|
+
buckets.clear();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Per-endpoint limits. Tune these for your app. */
|
|
64
|
+
export const RATE_LIMITS = {
|
|
65
|
+
login: { limit: 10, windowMs: 15 * 60_000 },
|
|
66
|
+
loginPerEmail: { limit: 20, windowMs: 60 * 60_000 },
|
|
67
|
+
register: { limit: 10, windowMs: 60 * 60_000 },
|
|
68
|
+
passwordReset: { limit: 5, windowMs: 15 * 60_000 },
|
|
69
|
+
sensitive: { limit: 5, windowMs: 15 * 60_000 },
|
|
70
|
+
} satisfies Record<string, RateLimitOptions>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { safeRedirectPath } from "./redirect";
|
|
4
|
+
|
|
5
|
+
describe("safeRedirectPath", () => {
|
|
6
|
+
it("keeps same-origin paths", () => {
|
|
7
|
+
expect(safeRedirectPath("/reports")).toBe("/reports");
|
|
8
|
+
expect(safeRedirectPath("/admin?tab=1#top")).toBe("/admin?tab=1#top");
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("blocks open redirects", () => {
|
|
12
|
+
expect(safeRedirectPath("https://evil.com")).toBe("/dashboard");
|
|
13
|
+
expect(safeRedirectPath("//evil.com")).toBe("/dashboard");
|
|
14
|
+
expect(safeRedirectPath("/\\evil.com")).toBe("/dashboard");
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it("falls back for empty values and guest-only pages", () => {
|
|
18
|
+
expect(safeRedirectPath(null)).toBe("/dashboard");
|
|
19
|
+
expect(safeRedirectPath("")).toBe("/dashboard");
|
|
20
|
+
expect(safeRedirectPath("/login")).toBe("/dashboard");
|
|
21
|
+
expect(safeRedirectPath(undefined, "/home")).toBe("/home");
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { AFTER_LOGIN_PATH, isGuestOnlyRoute } from "@/config/rbac";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Validates a `?next=` redirect target. Only same-origin relative paths are
|
|
5
|
+
* allowed, which prevents open redirects like `?next=//evil.com`.
|
|
6
|
+
*/
|
|
7
|
+
export function safeRedirectPath(
|
|
8
|
+
value: string | null | undefined,
|
|
9
|
+
fallback = AFTER_LOGIN_PATH,
|
|
10
|
+
): string {
|
|
11
|
+
if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
|
|
12
|
+
return fallback;
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(value, "http://localhost");
|
|
16
|
+
if (url.origin !== "http://localhost" || isGuestOnlyRoute(url.pathname)) return fallback;
|
|
17
|
+
return url.pathname + url.search + url.hash;
|
|
18
|
+
} catch {
|
|
19
|
+
return fallback;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { jwtVerify, SignJWT } from "jose";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
import { ROLES, type Role } from "@/config/rbac";
|
|
5
|
+
import { env, isProduction } from "@/lib/env";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Stateless session tokens (JWT, HS256) stored in an httpOnly cookie.
|
|
9
|
+
*
|
|
10
|
+
* Used by the proxy (optimistic checks) and the server. It has no Node-only or
|
|
11
|
+
* `server-only` imports so it can run anywhere server code runs.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const SESSION_COOKIE = "session";
|
|
15
|
+
export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days, in seconds
|
|
16
|
+
|
|
17
|
+
const ALGORITHM = "HS256";
|
|
18
|
+
|
|
19
|
+
const payloadSchema = z.object({
|
|
20
|
+
sub: z.string().min(1),
|
|
21
|
+
role: z.enum(ROLES),
|
|
22
|
+
name: z.string(),
|
|
23
|
+
// Token version: bumping it in the DB signs out every existing session.
|
|
24
|
+
ver: z.number().int().nonnegative().default(0),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export type SessionPayload = {
|
|
28
|
+
/** User id */
|
|
29
|
+
sub: string;
|
|
30
|
+
role: Role;
|
|
31
|
+
name: string;
|
|
32
|
+
/** Must match the user's tokenVersion in the database (checked by the DAL). */
|
|
33
|
+
ver: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
function getKey() {
|
|
37
|
+
return new TextEncoder().encode(env().JWT_SECRET);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function signSession(payload: SessionPayload): Promise<string> {
|
|
41
|
+
return new SignJWT({ role: payload.role, name: payload.name, ver: payload.ver })
|
|
42
|
+
.setProtectedHeader({ alg: ALGORITHM })
|
|
43
|
+
.setSubject(payload.sub)
|
|
44
|
+
.setIssuedAt()
|
|
45
|
+
.setExpirationTime(`${SESSION_MAX_AGE}s`)
|
|
46
|
+
.sign(getKey());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Returns the session payload, or null if the token is missing, invalid or expired. */
|
|
50
|
+
export async function verifySession(
|
|
51
|
+
token: string | undefined | null,
|
|
52
|
+
): Promise<SessionPayload | null> {
|
|
53
|
+
if (!token) return null;
|
|
54
|
+
try {
|
|
55
|
+
const { payload } = await jwtVerify(token, getKey(), { algorithms: [ALGORITHM] });
|
|
56
|
+
const parsed = payloadSchema.safeParse(payload);
|
|
57
|
+
return parsed.success ? parsed.data : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function sessionCookieOptions() {
|
|
64
|
+
return {
|
|
65
|
+
httpOnly: true,
|
|
66
|
+
secure: isProduction(),
|
|
67
|
+
sameSite: "lax" as const,
|
|
68
|
+
path: "/",
|
|
69
|
+
maxAge: SESSION_MAX_AGE,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const THEME_STORAGE_KEY = "theme";
|
|
2
|
+
export const THEMES = ["light", "dark", "system"] as const;
|
|
3
|
+
export type Theme = (typeof THEMES)[number];
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Runs in <head> before first paint so the page never flashes the wrong theme.
|
|
7
|
+
* "system" (or nothing saved) follows the OS setting, including live changes.
|
|
8
|
+
* See node_modules/next/dist/docs/01-app/02-guides/preventing-flash-before-hydration.md
|
|
9
|
+
*/
|
|
10
|
+
export const themeScript = `(function(){try{var k="${THEME_STORAGE_KEY}",m=window.matchMedia("(prefers-color-scheme: dark)");function a(){var t=localStorage.getItem(k);document.documentElement.classList.toggle("dark",t==="dark"||((!t||t==="system")&&m.matches))}a();m.addEventListener("change",a);window.addEventListener("storage",function(e){if(e.key===k)a()})}catch(e){}})()`;
|
|
11
|
+
|
|
12
|
+
export function readTheme(): Theme {
|
|
13
|
+
try {
|
|
14
|
+
const value = localStorage.getItem(THEME_STORAGE_KEY);
|
|
15
|
+
return value === "light" || value === "dark" ? value : "system";
|
|
16
|
+
} catch {
|
|
17
|
+
return "system";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Saves the preference and applies it immediately. */
|
|
22
|
+
export function applyTheme(theme: Theme) {
|
|
23
|
+
try {
|
|
24
|
+
localStorage.setItem(THEME_STORAGE_KEY, theme);
|
|
25
|
+
} catch {
|
|
26
|
+
// Storage unavailable (private mode): the choice just won't persist.
|
|
27
|
+
}
|
|
28
|
+
const dark =
|
|
29
|
+
theme === "dark" ||
|
|
30
|
+
(theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
|
|
31
|
+
document.documentElement.classList.toggle("dark", dark);
|
|
32
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
|
|
5
|
+
import { connectDB } from "@/lib/db";
|
|
6
|
+
import { sendEmail } from "@/lib/email";
|
|
7
|
+
import { passwordResetEmail, verificationEmail } from "@/lib/email-templates";
|
|
8
|
+
import { appUrl } from "@/lib/env";
|
|
9
|
+
import { AuthToken, type AuthTokenType } from "@/models/auth-token";
|
|
10
|
+
|
|
11
|
+
export const TOKEN_TTL: Record<AuthTokenType, number> = {
|
|
12
|
+
"password-reset": 60 * 60 * 1000, // 1 hour
|
|
13
|
+
"email-verification": 24 * 60 * 60 * 1000, // 24 hours
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function hashToken(token: string): string {
|
|
17
|
+
return crypto.createHash("sha256").update(token).digest("hex");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Creates a one-time token and returns the raw value (send it to the user).
|
|
22
|
+
* Any previous token of the same type for that user stops working.
|
|
23
|
+
*/
|
|
24
|
+
export async function createToken(userId: string, type: AuthTokenType): Promise<string> {
|
|
25
|
+
await connectDB();
|
|
26
|
+
const token = crypto.randomBytes(32).toString("base64url");
|
|
27
|
+
await AuthToken.deleteMany({ userId, type });
|
|
28
|
+
await AuthToken.create({
|
|
29
|
+
userId,
|
|
30
|
+
type,
|
|
31
|
+
tokenHash: hashToken(token),
|
|
32
|
+
expiresAt: new Date(Date.now() + TOKEN_TTL[type]),
|
|
33
|
+
});
|
|
34
|
+
return token;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Verifies and deletes a token in one step. Returns the user id, or null if invalid/expired. */
|
|
38
|
+
export async function consumeToken(token: string, type: AuthTokenType): Promise<string | null> {
|
|
39
|
+
if (!token || token.length > 200) return null;
|
|
40
|
+
await connectDB();
|
|
41
|
+
const doc = await AuthToken.findOneAndDelete({
|
|
42
|
+
tokenHash: hashToken(token),
|
|
43
|
+
type,
|
|
44
|
+
expiresAt: { $gt: new Date() },
|
|
45
|
+
}).lean();
|
|
46
|
+
return doc ? String(doc.userId) : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type Recipient = { id: string; name: string; email: string };
|
|
50
|
+
|
|
51
|
+
/** Creates a verification token and emails the link (GET /api/auth/verify-email?token=...). */
|
|
52
|
+
export async function sendVerificationEmail(user: Recipient): Promise<void> {
|
|
53
|
+
const token = await createToken(user.id, "email-verification");
|
|
54
|
+
const url = `${appUrl()}/api/auth/verify-email?token=${encodeURIComponent(token)}`;
|
|
55
|
+
await sendEmail(verificationEmail(user.email, user.name, url));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Creates a password-reset token and emails the link to /reset-password. */
|
|
59
|
+
export async function sendPasswordResetEmail(user: Recipient): Promise<void> {
|
|
60
|
+
const token = await createToken(user.id, "password-reset");
|
|
61
|
+
const url = `${appUrl()}/reset-password?token=${encodeURIComponent(token)}`;
|
|
62
|
+
await sendEmail(passwordResetEmail(user.email, user.name, url));
|
|
63
|
+
}
|