9 Commits

Author SHA1 Message Date
ryan
613784a1cc feat: set browser tab title and favicon from customer branding
All checks were successful
CI / ci (pull_request) Successful in 27s
CI / e2e (pull_request) Successful in 1m15s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:15:32 +00:00
ryan
bc8613bbbc feat: password reset flow with welcome emails
All checks were successful
CI / ci (pull_request) Successful in 27s
CI / e2e (pull_request) Successful in 1m0s
- POST /auth/forgot-password with welcome/reset email templates
- POST /auth/reset-password with Zod validation, 4-hour tokens
- Per-email rate limiting (3/hr) via Valkey, no user enumeration
- Login page "Forgot password?" toggle with inline form
- /reset-password page for setting new password from email link
- Initial user seed sends welcome email instead of requiring password
- CLI script for force-resetting passwords via kubectl exec
- APP_URL env var in chart, removed INITIAL_USER_PASSWORD

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:09:23 +00:00
Ryan Moon
a1dc4b0e47 feat: seed company record from BUSINESS_NAME env var on first startup
All checks were successful
Build & Release / build (push) Successful in 19s
2026-04-05 11:49:51 -05:00
81de80abb9 Merge pull request 'fix: regenerate route tree to include reports/daily route' (#8) from feature/login-branding into main
All checks were successful
Build & Release / build (push) Successful in 16s
Reviewed-on: #8
2026-04-05 16:25:46 +00:00
ryan
75c7c28f73 fix: generate route tree in CI and Docker build
All checks were successful
CI / ci (pull_request) Successful in 23s
CI / e2e (pull_request) Successful in 1m1s
Ensures routeTree.gen.ts is always fresh so stale checked-in copies
don't break the frontend build or lint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:24:08 +00:00
ryan
99fdaaa05a fix: regenerate route tree to include reports/daily route
All checks were successful
CI / ci (pull_request) Successful in 21s
CI / e2e (pull_request) Successful in 55s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:22:20 +00:00
6870aea1a5 Merge pull request 'feat: show customer branding on login page' (#7) from feature/login-branding into main
Some checks failed
Build & Release / build (push) Failing after 37s
Reviewed-on: #7
2026-04-05 16:19:32 +00:00
ryan
e589ff02f0 fix: remove unused imports to pass lint
All checks were successful
CI / ci (pull_request) Successful in 22s
CI / e2e (pull_request) Successful in 59s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:17:42 +00:00
ryan
da4b765b14 feat: show customer branding on login page
Some checks failed
CI / ci (pull_request) Failing after 20s
CI / e2e (pull_request) Has been skipped
Adds public /v1/store/branding and /v1/store/logo endpoints so the
login page can display the customer's name and logo without auth,
with "Powered by LunarFront" underneath — matching the sidebar style.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:14:07 +00:00
17 changed files with 612 additions and 65 deletions

View File

@@ -21,6 +21,10 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
- name: Generate route tree
working-directory: packages/admin
run: bunx @tanstack/router-cli generate
- name: Lint - name: Lint
run: bun run lint run: bun run lint

View File

@@ -16,6 +16,7 @@ COPY packages/admin ./packages/admin
COPY package.json ./ COPY package.json ./
COPY tsconfig.base.json ./ COPY tsconfig.base.json ./
WORKDIR /app/packages/admin WORKDIR /app/packages/admin
RUN bunx @tanstack/router-cli generate
RUN bun run build RUN bun run build
FROM nginx:alpine FROM nginx:alpine

View File

@@ -93,18 +93,14 @@ spec:
secretKeyRef: secretKeyRef:
name: lunarfront-secrets name: lunarfront-secrets
key: business-name key: business-name
- name: APP_URL
value: "https://{{ .Values.ingress.host }}"
- name: INITIAL_USER_EMAIL - name: INITIAL_USER_EMAIL
valueFrom: valueFrom:
secretKeyRef: secretKeyRef:
name: lunarfront-secrets name: lunarfront-secrets
key: initial-user-email key: initial-user-email
optional: true optional: true
- name: INITIAL_USER_PASSWORD
valueFrom:
secretKeyRef:
name: lunarfront-secrets
key: initial-user-password
optional: true
- name: INITIAL_USER_FIRST_NAME - name: INITIAL_USER_FIRST_NAME
valueFrom: valueFrom:
secretKeyRef: secretKeyRef:

View File

@@ -14,3 +14,11 @@ interface LoginResponse {
export async function login(email: string, password: string): Promise<LoginResponse> { export async function login(email: string, password: string): Promise<LoginResponse> {
return api.post<LoginResponse>('/v1/auth/login', { email, password }) return api.post<LoginResponse>('/v1/auth/login', { email, password })
} }
export async function forgotPassword(email: string): Promise<{ message: string }> {
return api.post<{ message: string }>('/v1/auth/forgot-password', { email })
}
export async function resetPassword(token: string, newPassword: string): Promise<{ message: string }> {
return api.post<{ message: string }>('/v1/auth/reset-password', { token, newPassword })
}

View File

@@ -4,7 +4,6 @@ import { posMutations, posKeys, type Transaction } from '@/api/pos'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { X, Banknote, CreditCard, FileText, Ban, UserRound, Tag } from 'lucide-react' import { X, Banknote, CreditCard, FileText, Ban, UserRound, Tag } from 'lucide-react'
import { toast } from 'sonner' import { toast } from 'sonner'

View File

@@ -100,7 +100,6 @@ function useStoreLogo(companyId?: string) {
} }
export function POSReceipt({ data, size = 'thermal', footerText, config }: POSReceiptProps) { export function POSReceipt({ data, size = 'thermal', footerText, config }: POSReceiptProps) {
const { transaction: txn, company, location } = data
const isThermal = size === 'thermal' const isThermal = size === 'thermal'
if (!isThermal) { if (!isThermal) {

View File

@@ -9,6 +9,7 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root' import { Route as rootRouteImport } from './routes/__root'
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
import { Route as PosRouteImport } from './routes/pos' import { Route as PosRouteImport } from './routes/pos'
import { Route as LoginRouteImport } from './routes/login' import { Route as LoginRouteImport } from './routes/login'
import { Route as AuthenticatedRouteImport } from './routes/_authenticated' import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
@@ -27,6 +28,7 @@ import { Route as AuthenticatedFilesIndexRouteImport } from './routes/_authentic
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index' import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new' import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId' import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
import { Route as AuthenticatedReportsDailyRouteImport } from './routes/_authenticated/reports/daily'
import { Route as AuthenticatedRepairsTemplatesRouteImport } from './routes/_authenticated/repairs/templates' import { Route as AuthenticatedRepairsTemplatesRouteImport } from './routes/_authenticated/repairs/templates'
import { Route as AuthenticatedRepairsNewRouteImport } from './routes/_authenticated/repairs/new' import { Route as AuthenticatedRepairsNewRouteImport } from './routes/_authenticated/repairs/new'
import { Route as AuthenticatedRepairsTicketIdRouteImport } from './routes/_authenticated/repairs/$ticketId' import { Route as AuthenticatedRepairsTicketIdRouteImport } from './routes/_authenticated/repairs/$ticketId'
@@ -57,6 +59,11 @@ import { Route as AuthenticatedAccountsAccountIdMembersRouteImport } from './rou
import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments' import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments'
import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId' import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
const ResetPasswordRoute = ResetPasswordRouteImport.update({
id: '/reset-password',
path: '/reset-password',
getParentRoute: () => rootRouteImport,
} as any)
const PosRoute = PosRouteImport.update({ const PosRoute = PosRouteImport.update({
id: '/pos', id: '/pos',
path: '/pos', path: '/pos',
@@ -152,6 +159,12 @@ const AuthenticatedRolesRoleIdRoute =
path: '/roles/$roleId', path: '/roles/$roleId',
getParentRoute: () => AuthenticatedRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any)
const AuthenticatedReportsDailyRoute =
AuthenticatedReportsDailyRouteImport.update({
id: '/reports/daily',
path: '/reports/daily',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedRepairsTemplatesRoute = const AuthenticatedRepairsTemplatesRoute =
AuthenticatedRepairsTemplatesRouteImport.update({ AuthenticatedRepairsTemplatesRouteImport.update({
id: '/repairs/templates', id: '/repairs/templates',
@@ -330,6 +343,7 @@ export interface FileRoutesByFullPath {
'/': typeof AuthenticatedIndexRoute '/': typeof AuthenticatedIndexRoute
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/pos': typeof PosRoute '/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/help': typeof AuthenticatedHelpRoute '/help': typeof AuthenticatedHelpRoute
'/profile': typeof AuthenticatedProfileRoute '/profile': typeof AuthenticatedProfileRoute
'/settings': typeof AuthenticatedSettingsRoute '/settings': typeof AuthenticatedSettingsRoute
@@ -344,6 +358,7 @@ export interface FileRoutesByFullPath {
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute '/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/repairs/new': typeof AuthenticatedRepairsNewRoute '/repairs/new': typeof AuthenticatedRepairsNewRoute
'/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute '/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
'/reports/daily': typeof AuthenticatedReportsDailyRoute
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/roles/new': typeof AuthenticatedRolesNewRoute '/roles/new': typeof AuthenticatedRolesNewRoute
'/accounts/': typeof AuthenticatedAccountsIndexRoute '/accounts/': typeof AuthenticatedAccountsIndexRoute
@@ -377,6 +392,7 @@ export interface FileRoutesByFullPath {
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/pos': typeof PosRoute '/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/help': typeof AuthenticatedHelpRoute '/help': typeof AuthenticatedHelpRoute
'/profile': typeof AuthenticatedProfileRoute '/profile': typeof AuthenticatedProfileRoute
'/settings': typeof AuthenticatedSettingsRoute '/settings': typeof AuthenticatedSettingsRoute
@@ -391,6 +407,7 @@ export interface FileRoutesByTo {
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute '/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/repairs/new': typeof AuthenticatedRepairsNewRoute '/repairs/new': typeof AuthenticatedRepairsNewRoute
'/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute '/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
'/reports/daily': typeof AuthenticatedReportsDailyRoute
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/roles/new': typeof AuthenticatedRolesNewRoute '/roles/new': typeof AuthenticatedRolesNewRoute
'/accounts': typeof AuthenticatedAccountsIndexRoute '/accounts': typeof AuthenticatedAccountsIndexRoute
@@ -426,6 +443,7 @@ export interface FileRoutesById {
'/_authenticated': typeof AuthenticatedRouteWithChildren '/_authenticated': typeof AuthenticatedRouteWithChildren
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/pos': typeof PosRoute '/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/_authenticated/help': typeof AuthenticatedHelpRoute '/_authenticated/help': typeof AuthenticatedHelpRoute
'/_authenticated/profile': typeof AuthenticatedProfileRoute '/_authenticated/profile': typeof AuthenticatedProfileRoute
'/_authenticated/settings': typeof AuthenticatedSettingsRoute '/_authenticated/settings': typeof AuthenticatedSettingsRoute
@@ -441,6 +459,7 @@ export interface FileRoutesById {
'/_authenticated/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute '/_authenticated/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/_authenticated/repairs/new': typeof AuthenticatedRepairsNewRoute '/_authenticated/repairs/new': typeof AuthenticatedRepairsNewRoute
'/_authenticated/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute '/_authenticated/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
'/_authenticated/reports/daily': typeof AuthenticatedReportsDailyRoute
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute '/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute '/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
@@ -477,6 +496,7 @@ export interface FileRouteTypes {
| '/' | '/'
| '/login' | '/login'
| '/pos' | '/pos'
| '/reset-password'
| '/help' | '/help'
| '/profile' | '/profile'
| '/settings' | '/settings'
@@ -491,6 +511,7 @@ export interface FileRouteTypes {
| '/repairs/$ticketId' | '/repairs/$ticketId'
| '/repairs/new' | '/repairs/new'
| '/repairs/templates' | '/repairs/templates'
| '/reports/daily'
| '/roles/$roleId' | '/roles/$roleId'
| '/roles/new' | '/roles/new'
| '/accounts/' | '/accounts/'
@@ -524,6 +545,7 @@ export interface FileRouteTypes {
to: to:
| '/login' | '/login'
| '/pos' | '/pos'
| '/reset-password'
| '/help' | '/help'
| '/profile' | '/profile'
| '/settings' | '/settings'
@@ -538,6 +560,7 @@ export interface FileRouteTypes {
| '/repairs/$ticketId' | '/repairs/$ticketId'
| '/repairs/new' | '/repairs/new'
| '/repairs/templates' | '/repairs/templates'
| '/reports/daily'
| '/roles/$roleId' | '/roles/$roleId'
| '/roles/new' | '/roles/new'
| '/accounts' | '/accounts'
@@ -572,6 +595,7 @@ export interface FileRouteTypes {
| '/_authenticated' | '/_authenticated'
| '/login' | '/login'
| '/pos' | '/pos'
| '/reset-password'
| '/_authenticated/help' | '/_authenticated/help'
| '/_authenticated/profile' | '/_authenticated/profile'
| '/_authenticated/settings' | '/_authenticated/settings'
@@ -587,6 +611,7 @@ export interface FileRouteTypes {
| '/_authenticated/repairs/$ticketId' | '/_authenticated/repairs/$ticketId'
| '/_authenticated/repairs/new' | '/_authenticated/repairs/new'
| '/_authenticated/repairs/templates' | '/_authenticated/repairs/templates'
| '/_authenticated/reports/daily'
| '/_authenticated/roles/$roleId' | '/_authenticated/roles/$roleId'
| '/_authenticated/roles/new' | '/_authenticated/roles/new'
| '/_authenticated/accounts/' | '/_authenticated/accounts/'
@@ -622,10 +647,18 @@ export interface RootRouteChildren {
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
LoginRoute: typeof LoginRoute LoginRoute: typeof LoginRoute
PosRoute: typeof PosRoute PosRoute: typeof PosRoute
ResetPasswordRoute: typeof ResetPasswordRoute
} }
declare module '@tanstack/react-router' { declare module '@tanstack/react-router' {
interface FileRoutesByPath { interface FileRoutesByPath {
'/reset-password': {
id: '/reset-password'
path: '/reset-password'
fullPath: '/reset-password'
preLoaderRoute: typeof ResetPasswordRouteImport
parentRoute: typeof rootRouteImport
}
'/pos': { '/pos': {
id: '/pos' id: '/pos'
path: '/pos' path: '/pos'
@@ -752,6 +785,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport
parentRoute: typeof AuthenticatedRoute parentRoute: typeof AuthenticatedRoute
} }
'/_authenticated/reports/daily': {
id: '/_authenticated/reports/daily'
path: '/reports/daily'
fullPath: '/reports/daily'
preLoaderRoute: typeof AuthenticatedReportsDailyRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/repairs/templates': { '/_authenticated/repairs/templates': {
id: '/_authenticated/repairs/templates' id: '/_authenticated/repairs/templates'
path: '/repairs/templates' path: '/repairs/templates'
@@ -1004,6 +1044,7 @@ interface AuthenticatedRouteChildren {
AuthenticatedRepairsTicketIdRoute: typeof AuthenticatedRepairsTicketIdRoute AuthenticatedRepairsTicketIdRoute: typeof AuthenticatedRepairsTicketIdRoute
AuthenticatedRepairsNewRoute: typeof AuthenticatedRepairsNewRoute AuthenticatedRepairsNewRoute: typeof AuthenticatedRepairsNewRoute
AuthenticatedRepairsTemplatesRoute: typeof AuthenticatedRepairsTemplatesRoute AuthenticatedRepairsTemplatesRoute: typeof AuthenticatedRepairsTemplatesRoute
AuthenticatedReportsDailyRoute: typeof AuthenticatedReportsDailyRoute
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
@@ -1047,6 +1088,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
AuthenticatedRepairsTicketIdRoute: AuthenticatedRepairsTicketIdRoute, AuthenticatedRepairsTicketIdRoute: AuthenticatedRepairsTicketIdRoute,
AuthenticatedRepairsNewRoute: AuthenticatedRepairsNewRoute, AuthenticatedRepairsNewRoute: AuthenticatedRepairsNewRoute,
AuthenticatedRepairsTemplatesRoute: AuthenticatedRepairsTemplatesRoute, AuthenticatedRepairsTemplatesRoute: AuthenticatedRepairsTemplatesRoute,
AuthenticatedReportsDailyRoute: AuthenticatedReportsDailyRoute,
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute, AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute, AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute, AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
@@ -1090,6 +1132,7 @@ const rootRouteChildren: RootRouteChildren = {
AuthenticatedRoute: AuthenticatedRouteWithChildren, AuthenticatedRoute: AuthenticatedRouteWithChildren,
LoginRoute: LoginRoute, LoginRoute: LoginRoute,
PosRoute: PosRoute, PosRoute: PosRoute,
ResetPasswordRoute: ResetPasswordRoute,
} }
export const routeTree = rootRouteImport export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren) ._addFileChildren(rootRouteChildren)

View File

@@ -1,11 +1,29 @@
import { createRootRoute, Outlet } from '@tanstack/react-router' import { createRootRoute, Outlet } from '@tanstack/react-router'
import { Toaster } from 'sonner' import { Toaster } from 'sonner'
import { useEffect } from 'react'
export const Route = createRootRoute({ export const Route = createRootRoute({
component: RootLayout, component: RootLayout,
}) })
function RootLayout() { function RootLayout() {
useEffect(() => {
fetch('/v1/store/branding')
.then((r) => r.ok ? r.json() : null)
.then((data: { name: string | null; hasLogo: boolean } | null) => {
if (!data) return
if (data.name) document.title = data.name
if (data.hasLogo) {
const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
?? document.createElement('link')
link.rel = 'icon'
link.href = '/v1/store/logo'
document.head.appendChild(link)
}
})
.catch(() => {})
}, [])
return ( return (
<> <>
<Outlet /> <Outlet />

View File

@@ -1,7 +1,12 @@
import { useState } from 'react' import { useState, useEffect } from 'react'
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router' import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
import { useAuthStore } from '@/stores/auth.store' import { useAuthStore } from '@/stores/auth.store'
import { login } from '@/api/auth' import { login, forgotPassword } from '@/api/auth'
interface Branding {
name: string | null
hasLogo: boolean
}
export const Route = createFileRoute('/login')({ export const Route = createFileRoute('/login')({
beforeLoad: () => { beforeLoad: () => {
@@ -20,6 +25,16 @@ function LoginPage() {
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [branding, setBranding] = useState<Branding | null>(null)
const [forgotMode, setForgotMode] = useState(false)
const [forgotSent, setForgotSent] = useState(false)
useEffect(() => {
fetch('/v1/store/branding')
.then((r) => r.ok ? r.json() : null)
.then((data) => { if (data) setBranding(data) })
.catch(() => {})
}, [])
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
@@ -48,45 +63,128 @@ function LoginPage() {
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }} style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
> >
<div className="text-center mb-8"> <div className="text-center mb-8">
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>LunarFront</h1> {branding?.hasLogo ? (
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p> <img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
</div> ) : (
<form onSubmit={handleSubmit} className="space-y-4"> <h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)} )}
<button {branding?.name ? (
type="submit" <p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
disabled={loading} ) : (
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50" <p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }} )}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }} </div>
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }} {forgotMode ? (
> forgotSent ? (
{loading ? 'Signing in...' : 'Sign in'} <div className="text-center space-y-4">
</button> <p className="text-sm" style={{ color: '#b0bec5' }}>If an account exists with that email, you will receive a password reset link.</p>
</form> <button
onClick={() => { setForgotMode(false); setForgotSent(false); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Back to sign in
</button>
</div>
) : (
<form onSubmit={async (e) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await forgotPassword(email)
setForgotSent(true)
} catch (err) {
setError(err instanceof Error ? err.message : 'Something went wrong')
} finally {
setLoading(false)
}
}} className="space-y-4">
<p className="text-sm" style={{ color: '#b0bec5' }}>Enter your email and we'll send you a reset link.</p>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Sending...' : 'Send reset link'}
</button>
<div className="text-center">
<button
type="button"
onClick={() => { setForgotMode(false); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Back to sign in
</button>
</div>
</form>
)
) : (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Signing in...' : 'Sign in'}
</button>
<div className="text-center">
<button
type="button"
onClick={() => { setForgotMode(true); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Forgot password?
</button>
</div>
</form>
)}
</div> </div>
</div> </div>
) )

View File

@@ -0,0 +1,154 @@
import { useState, useEffect } from 'react'
import { createFileRoute, Link } from '@tanstack/react-router'
import { resetPassword } from '@/api/auth'
interface Branding {
name: string | null
hasLogo: boolean
}
export const Route = createFileRoute('/reset-password')({
component: ResetPasswordPage,
})
function ResetPasswordPage() {
const { token } = Route.useSearch() as { token?: string }
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [success, setSuccess] = useState(false)
const [branding, setBranding] = useState<Branding | null>(null)
useEffect(() => {
fetch('/v1/store/branding')
.then((r) => r.ok ? r.json() : null)
.then((data) => { if (data) setBranding(data) })
.catch(() => {})
}, [])
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setError('')
if (!token) {
setError('Missing reset token. Please use the link from your email.')
return
}
if (password !== confirmPassword) {
setError('Passwords do not match')
return
}
if (password.length < 12) {
setError('Password must be at least 12 characters')
return
}
setLoading(true)
try {
await resetPassword(token, password)
setSuccess(true)
} catch (err) {
setError(err instanceof Error ? err.message : 'Reset failed. The link may have expired.')
} finally {
setLoading(false)
}
}
return (
<div
className="flex min-h-screen items-center justify-center"
style={{ background: 'linear-gradient(135deg, #0f1724 0%, #142038 100%)' }}
>
<div
className="w-full max-w-sm rounded-xl border p-8 shadow-2xl"
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
>
<div className="text-center mb-8">
{branding?.hasLogo ? (
<img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
) : (
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
)}
{branding?.name ? (
<p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
) : (
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
)}
</div>
{success ? (
<div className="text-center space-y-4">
<p style={{ color: '#81c784' }}>Password reset successfully.</p>
<Link
to="/login"
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
>
Sign in
</Link>
</div>
) : !token ? (
<div className="text-center space-y-4">
<p style={{ color: '#e57373' }}>Invalid reset link. Please request a new one.</p>
<Link
to="/login"
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
>
Back to sign in
</Link>
</div>
) : (
<>
<h2 className="text-lg font-semibold text-center mb-4" style={{ color: '#d8dfe9' }}>Set new password</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>New password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={12}
placeholder="At least 12 characters"
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Confirm password</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Resetting...' : 'Reset password'}
</button>
<div className="text-center">
<Link to="/login" className="text-xs" style={{ color: '#6b7a8d' }}>
Back to sign in
</Link>
</div>
</form>
</>
)}
</div>
</div>
)
}

View File

@@ -38,21 +38,56 @@ import { ModuleService } from './services/module.service.js'
import { AppConfigService } from './services/config.service.js' import { AppConfigService } from './services/config.service.js'
import { SettingsService } from './services/settings.service.js' import { SettingsService } from './services/settings.service.js'
import { users } from './db/schema/users.js' import { users } from './db/schema/users.js'
import { companies } from './db/schema/stores.js'
import { EmailService } from './services/email.service.js'
import bcrypt from 'bcryptjs' import bcrypt from 'bcryptjs'
async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) { async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) {
const email = process.env.INITIAL_USER_EMAIL const email = process.env.INITIAL_USER_EMAIL
const password = process.env.INITIAL_USER_PASSWORD
const firstName = process.env.INITIAL_USER_FIRST_NAME const firstName = process.env.INITIAL_USER_FIRST_NAME
const lastName = process.env.INITIAL_USER_LAST_NAME const lastName = process.env.INITIAL_USER_LAST_NAME
if (!email || !password || !firstName || !lastName) return if (!email || !firstName || !lastName) return
const existing = await app.db.select({ id: users.id }).from(users).limit(1) const existing = await app.db.select({ id: users.id }).from(users).limit(1)
if (existing.length > 0) return if (existing.length > 0) return
const passwordHash = await bcrypt.hash(password, 10) // Create user with a random password — they'll set their real one via the welcome email
await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' }) const tempPassword = crypto.randomUUID()
const passwordHash = await bcrypt.hash(tempPassword, 10)
const [user] = await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' }).returning({ id: users.id })
app.log.info({ email }, 'Initial admin user created') app.log.info({ email }, 'Initial admin user created')
// Send welcome email with password setup link
try {
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const appUrl = process.env.APP_URL ?? `https://${process.env.HOSTNAME ?? 'localhost'}`
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
const storeName = store?.name ?? process.env.BUSINESS_NAME ?? 'LunarFront'
await EmailService.send(app.db, {
to: email,
subject: `Welcome to ${storeName} — Set your password`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${firstName},</p>
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
})
app.log.info({ email }, 'Welcome email sent to initial user')
} catch (err) {
app.log.error({ email, error: (err as Error).message }, 'Failed to send welcome email — user can use forgot password')
}
} }
async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) { async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) {
@@ -73,6 +108,17 @@ async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) {
app.log.info('Email settings seeded from environment') app.log.info('Email settings seeded from environment')
} }
async function seedCompany(app: Awaited<ReturnType<typeof buildApp>>) {
const name = process.env.BUSINESS_NAME
if (!name) return
const existing = await app.db.select({ id: companies.id }).from(companies).limit(1)
if (existing.length > 0) return
await app.db.insert(companies).values({ name })
app.log.info({ name }, 'Company seeded from environment')
}
export async function buildApp() { export async function buildApp() {
const app = Fastify({ const app = Fastify({
logger: { logger: {
@@ -209,6 +255,11 @@ export async function buildApp() {
} catch (err) { } catch (err) {
app.log.error({ err }, 'Failed to seed email settings') app.log.error({ err }, 'Failed to seed email settings')
} }
try {
await seedCompany(app)
} catch (err) {
app.log.error({ err }, 'Failed to seed company')
}
}) })
return app return app

View File

@@ -1,8 +1,10 @@
import type { FastifyPluginAsync } from 'fastify' import type { FastifyPluginAsync } from 'fastify'
import { eq } from 'drizzle-orm' import { eq } from 'drizzle-orm'
import bcrypt from 'bcryptjs' import bcrypt from 'bcryptjs'
import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from '@lunarfront/shared/schemas' import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from '@lunarfront/shared/schemas'
import { users } from '../../db/schema/users.js' import { users } from '../../db/schema/users.js'
import { companies } from '../../db/schema/stores.js'
import { EmailService } from '../../services/email.service.js'
const SALT_ROUNDS = 10 const SALT_ROUNDS = 10
@@ -151,24 +153,22 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
const [user] = await app.db.select({ id: users.id, email: users.email }).from(users).where(eq(users.id, userId)).limit(1) const [user] = await app.db.select({ id: users.id, email: users.email }).from(users).where(eq(users.id, userId)).limit(1)
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } }) if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
// Generate a signed reset token that expires in 1 hour const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '1h' })
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}` const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated') request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
return reply.send({ resetLink, expiresIn: '1 hour' }) return reply.send({ resetLink, expiresIn: '4 hours' })
}) })
// Reset password with token // Reset password with token
app.post('/auth/reset-password', async (request, reply) => { app.post('/auth/reset-password', async (request, reply) => {
const { token, newPassword } = request.body as { token?: string; newPassword?: string } const parsed = ResetPasswordSchema.safeParse(request.body)
if (!token || !newPassword) { if (!parsed.success) {
return reply.status(400).send({ error: { message: 'token and newPassword are required', statusCode: 400 } }) return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
if (newPassword.length < 12) {
return reply.status(400).send({ error: { message: 'Password must be at least 12 characters', statusCode: 400 } })
} }
const { token, newPassword } = parsed.data
try { try {
const payload = app.jwt.verify<{ userId: string; purpose: string }>(token) const payload = app.jwt.verify<{ userId: string; purpose: string }>(token)
if (payload.purpose !== 'password-reset') { if (payload.purpose !== 'password-reset') {
@@ -185,6 +185,86 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
} }
}) })
// Forgot password / resend welcome — public, always returns success (no user enumeration)
// Pass ?type=welcome for welcome emails, defaults to reset
app.post('/auth/forgot-password', rateLimitConfig, async (request, reply) => {
const parsed = ForgotPasswordSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const { email } = parsed.data
const isWelcome = (request.query as { type?: string }).type === 'welcome'
// Rate limit per email — max 3 emails per hour
const emailKey = `pwd-reset:${email.toLowerCase()}`
const count = await app.redis.incr(emailKey)
if (count === 1) await app.redis.expire(emailKey, 3600)
if (count > 3) {
return reply.send({ message: 'If an account exists with that email, you will receive an email.' })
}
// Always return success — don't reveal whether the email exists
const [user] = await app.db.select({ id: users.id, firstName: users.firstName }).from(users).where(eq(users.email, email)).limit(1)
if (user) {
try {
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const appUrl = process.env.APP_URL ?? 'http://localhost:5173'
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
const storeName = store?.name ?? 'LunarFront'
if (isWelcome) {
await EmailService.send(app.db, {
to: email,
subject: `Welcome to ${storeName} — Set your password`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${user.firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
})
} else {
await EmailService.send(app.db, {
to: email,
subject: `Reset your password — ${storeName}`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
<p style="color: #555;">We received a request to reset your password. Click the button below to choose a new one:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Reset Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If you didn't request this, you can safely ignore this email.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${user.firstName}, reset your password here: ${resetLink} — This link expires in 4 hours.`,
})
}
request.log.info({ userId: user.id, type: isWelcome ? 'welcome' : 'reset' }, 'Password email sent')
} catch (err) {
request.log.error({ email, error: (err as Error).message }, 'Failed to send password email')
}
}
return reply.send({ message: 'If an account exists with that email, you will receive a password reset link.' })
})
// Get current user profile // Get current user profile
app.get('/auth/me', { preHandler: [app.authenticate] }, async (request, reply) => { app.get('/auth/me', { preHandler: [app.authenticate] }, async (request, reply) => {
const [user] = await app.db const [user] = await app.db

View File

@@ -1,9 +1,43 @@
import type { FastifyPluginAsync } from 'fastify' import type { FastifyPluginAsync } from 'fastify'
import { eq } from 'drizzle-orm' import { eq } from 'drizzle-orm'
import { companies, locations } from '../../db/schema/stores.js' import { companies, locations } from '../../db/schema/stores.js'
import { files } from '../../db/schema/files.js'
import { ValidationError } from '../../lib/errors.js' import { ValidationError } from '../../lib/errors.js'
export const storeRoutes: FastifyPluginAsync = async (app) => { export const storeRoutes: FastifyPluginAsync = async (app) => {
// --- Public branding (no auth — used on login page) ---
app.get('/store/branding', async (_request, reply) => {
const [store] = await app.db.select({
name: companies.name,
logoFileId: companies.logoFileId,
}).from(companies).limit(1)
if (!store) return reply.send({ name: null, hasLogo: false })
return reply.send({ name: store.name, hasLogo: !!store.logoFileId })
})
app.get('/store/logo', async (_request, reply) => {
const [store] = await app.db.select({ logoFileId: companies.logoFileId }).from(companies).limit(1)
if (!store?.logoFileId) return reply.status(404).send({ error: { message: 'No logo configured', statusCode: 404 } })
const [file] = await app.db.select().from(files).where(eq(files.id, store.logoFileId)).limit(1)
if (!file) return reply.status(404).send({ error: { message: 'Logo file not found', statusCode: 404 } })
try {
const data = await app.storage.get(file.path)
const ext = file.path.split('.').pop()?.toLowerCase()
const contentTypeMap: Record<string, string> = {
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', svg: 'image/svg+xml',
}
return reply
.header('Content-Type', contentTypeMap[ext ?? ''] ?? 'application/octet-stream')
.header('Cache-Control', 'public, max-age=3600')
.send(data)
} catch {
return reply.status(404).send({ error: { message: 'Logo file not readable', statusCode: 404 } })
}
})
// --- Company / Store Settings --- // --- Company / Store Settings ---
app.get('/store', { preHandler: [app.authenticate, app.requirePermission('settings.view')] }, async (request, reply) => { app.get('/store', { preHandler: [app.authenticate, app.requirePermission('settings.view')] }, async (request, reply) => {

View File

@@ -0,0 +1,51 @@
#!/usr/bin/env bun
/**
* Force-reset a user's password from the command line.
*
* Usage:
* bun run packages/backend/src/scripts/reset-password.ts <email> <new-password>
*
* From a customer pod:
* kubectl exec -n customer-tvs deploy/customer-tvs-backend -- \
* bun run src/scripts/reset-password.ts user@example.com NewPassword123!
*/
import postgres from 'postgres'
import { drizzle } from 'drizzle-orm/postgres-js'
import { eq } from 'drizzle-orm'
import bcrypt from 'bcryptjs'
import { users } from '../db/schema/users.js'
const [email, newPassword] = process.argv.slice(2)
if (!email || !newPassword) {
console.error('Usage: bun run reset-password.ts <email> <new-password>')
process.exit(1)
}
if (newPassword.length < 12) {
console.error('Error: Password must be at least 12 characters')
process.exit(1)
}
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) {
console.error('Error: DATABASE_URL is not set')
process.exit(1)
}
const sql = postgres(databaseUrl)
const db = drizzle(sql)
const [user] = await db.select({ id: users.id, email: users.email }).from(users).where(eq(users.email, email)).limit(1)
if (!user) {
console.error(`Error: No user found with email "${email}"`)
await sql.end()
process.exit(1)
}
const hash = await bcrypt.hash(newPassword, 10)
await db.update(users).set({ passwordHash: hash, updatedAt: new Date() }).where(eq(users.id, user.id))
console.log(`Password reset for ${email} (user ${user.id})`)
await sql.end()

View File

@@ -1,4 +1,4 @@
import { eq, and, sql, gte, lt } from 'drizzle-orm' import { eq, and, gte, lt } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js' import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import { transactions, drawerSessions, drawerAdjustments, registers } from '../db/schema/pos.js' import { transactions, drawerSessions, drawerAdjustments, registers } from '../db/schema/pos.js'
import { locations } from '../db/schema/stores.js' import { locations } from '../db/schema/stores.js'

View File

@@ -27,3 +27,14 @@ export const SetPinSchema = z.object({
pin: z.string().min(4).max(6).regex(/^\d+$/, 'PIN must be digits only'), pin: z.string().min(4).max(6).regex(/^\d+$/, 'PIN must be digits only'),
}) })
export type SetPinInput = z.infer<typeof SetPinSchema> export type SetPinInput = z.infer<typeof SetPinSchema>
export const ForgotPasswordSchema = z.object({
email: z.string().email(),
})
export type ForgotPasswordInput = z.infer<typeof ForgotPasswordSchema>
export const ResetPasswordSchema = z.object({
token: z.string().min(1),
newPassword: z.string().min(12, 'Password must be at least 12 characters').max(128),
})
export type ResetPasswordInput = z.infer<typeof ResetPasswordSchema>

View File

@@ -1,8 +1,8 @@
export { PaginationSchema } from './pagination.schema.js' export { PaginationSchema } from './pagination.schema.js'
export type { PaginationInput, PaginatedResponse } from './pagination.schema.js' export type { PaginationInput, PaginatedResponse } from './pagination.schema.js'
export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from './auth.schema.js' export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from './auth.schema.js'
export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput } from './auth.schema.js' export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput, ForgotPasswordInput, ResetPasswordInput } from './auth.schema.js'
export { export {
BillingMode, BillingMode,