create-freakpunch 0.0.0-stage → 0.2.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 +24 -3
- package/bin/create-freakpunch.mjs +227 -0
- package/files/README.md +19 -0
- package/files/app.config.ts +50 -0
- package/files/locales.ts +10 -0
- package/files/registry.ts +17 -0
- package/package.json +23 -6
- package/template/.dockerignore +17 -0
- package/template/.oxlintrc.json +9 -0
- package/template/AGENTS.md +6 -0
- package/template/BACKEND.md +108 -0
- package/template/CLAUDE.md +297 -0
- package/template/Dockerfile +19 -0
- package/template/_gitignore +26 -0
- package/template/components.json +27 -0
- package/template/design/COMPONENTS.md +145 -0
- package/template/design/DESIGN.md +212 -0
- package/template/design/PATTERNS.md +110 -0
- package/template/index.html +25 -0
- package/template/nginx.conf +32 -0
- package/template/package-lock.json +6484 -0
- package/template/package.json +51 -0
- package/template/public/favicon.svg +1 -0
- package/template/public/robots.txt +2 -0
- package/template/src/app.config.ts +50 -0
- package/template/src/app.roles.ts +24 -0
- package/template/src/components/ui/alert-dialog.tsx +181 -0
- package/template/src/components/ui/avatar.tsx +116 -0
- package/template/src/components/ui/badge.tsx +57 -0
- package/template/src/components/ui/breadcrumb.tsx +130 -0
- package/template/src/components/ui/button.tsx +58 -0
- package/template/src/components/ui/calendar.tsx +277 -0
- package/template/src/components/ui/card.tsx +99 -0
- package/template/src/components/ui/chart.tsx +370 -0
- package/template/src/components/ui/checkbox.tsx +28 -0
- package/template/src/components/ui/combobox.tsx +329 -0
- package/template/src/components/ui/command.tsx +191 -0
- package/template/src/components/ui/dialog.tsx +162 -0
- package/template/src/components/ui/dropdown-menu.tsx +271 -0
- package/template/src/components/ui/empty.tsx +103 -0
- package/template/src/components/ui/field.tsx +236 -0
- package/template/src/components/ui/input-group.tsx +263 -0
- package/template/src/components/ui/input.tsx +45 -0
- package/template/src/components/ui/kbd.tsx +31 -0
- package/template/src/components/ui/label.tsx +17 -0
- package/template/src/components/ui/pagination.tsx +134 -0
- package/template/src/components/ui/popover.tsx +87 -0
- package/template/src/components/ui/radio-group.tsx +35 -0
- package/template/src/components/ui/select.tsx +204 -0
- package/template/src/components/ui/separator.tsx +25 -0
- package/template/src/components/ui/sheet.tsx +139 -0
- package/template/src/components/ui/sidebar.tsx +741 -0
- package/template/src/components/ui/skeleton.tsx +13 -0
- package/template/src/components/ui/sonner.tsx +78 -0
- package/template/src/components/ui/spinner.tsx +42 -0
- package/template/src/components/ui/switch.tsx +29 -0
- package/template/src/components/ui/table.tsx +121 -0
- package/template/src/components/ui/tabs.tsx +191 -0
- package/template/src/components/ui/textarea.tsx +17 -0
- package/template/src/components/ui/toggle-group.tsx +94 -0
- package/template/src/components/ui/toggle.tsx +48 -0
- package/template/src/components/ui/tooltip.tsx +91 -0
- package/template/src/core/api/demo.ts +8 -0
- package/template/src/core/api/http.ts +76 -0
- package/template/src/core/api/mock.ts +88 -0
- package/template/src/core/api/rest.ts +67 -0
- package/template/src/core/api/types.ts +21 -0
- package/template/src/core/audit/audit.service.ts +94 -0
- package/template/src/core/audit/hooks.ts +19 -0
- package/template/src/core/auth/auth-store.ts +52 -0
- package/template/src/core/auth/auth.service.ts +86 -0
- package/template/src/core/auth/can.tsx +39 -0
- package/template/src/core/auth/dev-role-switcher.tsx +64 -0
- package/template/src/core/auth/local-credentials.ts +46 -0
- package/template/src/core/auth/permissions.ts +115 -0
- package/template/src/core/auth/require-auth.tsx +16 -0
- package/template/src/core/auth/require-permission.tsx +24 -0
- package/template/src/core/auth/roles.ts +9 -0
- package/template/src/core/auth/types.ts +20 -0
- package/template/src/core/auth/use-auth.ts +19 -0
- package/template/src/core/company/company.service.ts +94 -0
- package/template/src/core/company/hooks.ts +40 -0
- package/template/src/core/company/password-policy.ts +40 -0
- package/template/src/core/company/types.ts +46 -0
- package/template/src/core/company/use-app-name.ts +7 -0
- package/template/src/core/components/button-link.tsx +14 -0
- package/template/src/core/components/confirm-dialog.tsx +116 -0
- package/template/src/core/components/data-table/data-table.tsx +297 -0
- package/template/src/core/components/data-table/features.ts +24 -0
- package/template/src/core/components/data-table/table-header-cell.tsx +13 -0
- package/template/src/core/components/data-table/toolbar.tsx +100 -0
- package/template/src/core/components/data-table/use-list-url-state.ts +108 -0
- package/template/src/core/components/date-picker.tsx +71 -0
- package/template/src/core/components/file-attachments.tsx +84 -0
- package/template/src/core/components/form-error.tsx +9 -0
- package/template/src/core/components/form-page.tsx +93 -0
- package/template/src/core/components/image-upload.tsx +86 -0
- package/template/src/core/components/page.tsx +75 -0
- package/template/src/core/components/phone-input.tsx +58 -0
- package/template/src/core/components/search-select.tsx +57 -0
- package/template/src/core/components/segmented.tsx +41 -0
- package/template/src/core/components/states.tsx +97 -0
- package/template/src/core/components/status-badge.tsx +26 -0
- package/template/src/core/components/user-avatar.tsx +23 -0
- package/template/src/core/config/runtime.ts +16 -0
- package/template/src/core/config/types.ts +37 -0
- package/template/src/core/i18n/i18n.ts +69 -0
- package/template/src/core/i18n/i18next.d.ts +12 -0
- package/template/src/core/i18n/keys.ts +37 -0
- package/template/src/core/i18n/language-switcher.tsx +45 -0
- package/template/src/core/i18n/types.ts +17 -0
- package/template/src/core/i18n/use-format.ts +31 -0
- package/template/src/core/layout/app-shell.tsx +50 -0
- package/template/src/core/layout/app-sidebar.tsx +285 -0
- package/template/src/core/layout/command-menu.tsx +117 -0
- package/template/src/core/layout/top-bar.tsx +100 -0
- package/template/src/core/lib/csv.ts +27 -0
- package/template/src/core/lib/format.ts +87 -0
- package/template/src/core/lib/phone.ts +50 -0
- package/template/src/core/lib/storage.ts +27 -0
- package/template/src/core/modules/lazy-page.ts +9 -0
- package/template/src/core/modules/navigation.ts +39 -0
- package/template/src/core/modules/types.ts +55 -0
- package/template/src/core/notifications/hooks.ts +84 -0
- package/template/src/core/notifications/notification-center.tsx +251 -0
- package/template/src/core/notifications/notifications.service.ts +132 -0
- package/template/src/core/notifications/types.ts +70 -0
- package/template/src/core/preferences/preferences-store.ts +70 -0
- package/template/src/core/setup/setup-gate.tsx +20 -0
- package/template/src/core/setup/setup.service.ts +101 -0
- package/template/src/core/theme/brand-context.tsx +53 -0
- package/template/src/core/theme/brand.ts +29 -0
- package/template/src/core/theme/theme-context.tsx +62 -0
- package/template/src/core/theme/theme-options.ts +8 -0
- package/template/src/core/theme/theme-toggle.tsx +45 -0
- package/template/src/core/users/hooks.ts +51 -0
- package/template/src/core/users/types.ts +37 -0
- package/template/src/core/users/users.service.ts +167 -0
- package/template/src/hooks/use-mobile.ts +19 -0
- package/template/src/index.css +321 -0
- package/template/src/lib/utils.ts +1 -0
- package/template/src/locales/en/account.ts +180 -0
- package/template/src/locales/en/auth.ts +18 -0
- package/template/src/locales/en/common.ts +151 -0
- package/template/src/locales/en/company.ts +380 -0
- package/template/src/locales/en/dashboard.ts +46 -0
- package/template/src/locales/en/errors.ts +18 -0
- package/template/src/locales/en/notifications.ts +43 -0
- package/template/src/locales/en/settings.ts +25 -0
- package/template/src/locales/en/setup.ts +45 -0
- package/template/src/locales/index.ts +58 -0
- package/template/src/locales/tr/account.ts +184 -0
- package/template/src/locales/tr/auth.ts +22 -0
- package/template/src/locales/tr/common.ts +154 -0
- package/template/src/locales/tr/company.ts +384 -0
- package/template/src/locales/tr/dashboard.ts +50 -0
- package/template/src/locales/tr/errors.ts +22 -0
- package/template/src/locales/tr/notifications.ts +47 -0
- package/template/src/locales/tr/settings.ts +29 -0
- package/template/src/locales/tr/setup.ts +49 -0
- package/template/src/main.tsx +16 -0
- package/template/src/modules/locales.ts +10 -0
- package/template/src/modules/registry.ts +17 -0
- package/template/src/pages/dashboard/dashboard-page.tsx +55 -0
- package/template/src/pages/dashboard/quick-actions.tsx +37 -0
- package/template/src/pages/login-page.tsx +152 -0
- package/template/src/pages/no-access-page.tsx +11 -0
- package/template/src/pages/not-found-page.tsx +61 -0
- package/template/src/pages/settings/account/account.service.ts +128 -0
- package/template/src/pages/settings/account/components/mock-qr.tsx +50 -0
- package/template/src/pages/settings/account/components/password-strength.tsx +38 -0
- package/template/src/pages/settings/account/components/two-factor-dialog.tsx +140 -0
- package/template/src/pages/settings/account/hooks.ts +73 -0
- package/template/src/pages/settings/account/notifications-page.tsx +103 -0
- package/template/src/pages/settings/account/preferences-page.tsx +157 -0
- package/template/src/pages/settings/account/profile-page.tsx +242 -0
- package/template/src/pages/settings/account/security-page.tsx +364 -0
- package/template/src/pages/settings/account/types.ts +37 -0
- package/template/src/pages/settings/company/audit-log-page.tsx +126 -0
- package/template/src/pages/settings/company/branding-page.tsx +278 -0
- package/template/src/pages/settings/company/components/invite-dialog.tsx +106 -0
- package/template/src/pages/settings/company/components/read-only-notice.tsx +13 -0
- package/template/src/pages/settings/company/danger-zone-page.tsx +127 -0
- package/template/src/pages/settings/company/general-page.tsx +234 -0
- package/template/src/pages/settings/company/integrations/api-keys-panel.tsx +170 -0
- package/template/src/pages/settings/company/integrations/hooks.ts +37 -0
- package/template/src/pages/settings/company/integrations/integrations-page.tsx +57 -0
- package/template/src/pages/settings/company/integrations/integrations.service.ts +153 -0
- package/template/src/pages/settings/company/integrations/settings-forms.tsx +299 -0
- package/template/src/pages/settings/company/integrations/webhooks-panel.tsx +179 -0
- package/template/src/pages/settings/company/modules-page.tsx +65 -0
- package/template/src/pages/settings/company/roles-page.tsx +116 -0
- package/template/src/pages/settings/company/security-policies-page.tsx +164 -0
- package/template/src/pages/settings/company/users-page.tsx +262 -0
- package/template/src/pages/settings/settings-layout.tsx +57 -0
- package/template/src/pages/settings/settings-nav.ts +69 -0
- package/template/src/pages/settings/settings-routes.tsx +49 -0
- package/template/src/pages/setup-page.tsx +387 -0
- package/template/src/providers.tsx +68 -0
- package/template/src/router.tsx +59 -0
- package/template/tools/check-design.mjs +73 -0
- package/template/tools/new-module.mjs +90 -0
- package/template/tools/templates/module/api/__id__.mock.ts.tpl +17 -0
- package/template/tools/templates/module/api/__id__.service.ts.tpl +51 -0
- package/template/tools/templates/module/hooks.ts.tpl +57 -0
- package/template/tools/templates/module/index.ts.tpl +44 -0
- package/template/tools/templates/module/locales/en.ts.tpl +51 -0
- package/template/tools/templates/module/locales/tr.ts.tpl +55 -0
- package/template/tools/templates/module/pages/__id__-detail-page.tsx.tpl +103 -0
- package/template/tools/templates/module/pages/__id__-form-page.tsx.tpl +121 -0
- package/template/tools/templates/module/pages/__id__-list-page.tsx.tpl +234 -0
- package/template/tools/templates/module/types.ts.tpl +32 -0
- package/template/tsconfig.app.json +32 -0
- package/template/tsconfig.json +12 -0
- package/template/tsconfig.node.json +23 -0
- package/template/vite.config.ts +47 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { useTranslation } from 'react-i18next'
|
|
2
|
+
import { FlaskConical } from 'lucide-react'
|
|
3
|
+
import { toast } from 'sonner'
|
|
4
|
+
|
|
5
|
+
import { Button } from '@/components/ui/button'
|
|
6
|
+
import {
|
|
7
|
+
DropdownMenu,
|
|
8
|
+
DropdownMenuContent,
|
|
9
|
+
DropdownMenuGroup,
|
|
10
|
+
DropdownMenuLabel,
|
|
11
|
+
DropdownMenuRadioGroup,
|
|
12
|
+
DropdownMenuRadioItem,
|
|
13
|
+
DropdownMenuTrigger,
|
|
14
|
+
} from '@/components/ui/dropdown-menu'
|
|
15
|
+
import { fullName } from '@/core/users/types'
|
|
16
|
+
import { authService } from './auth.service'
|
|
17
|
+
import { roles, type Role } from './roles'
|
|
18
|
+
import { useSession } from './use-auth'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Development only (rendered behind `import.meta.env.DEV`, so it is removed
|
|
22
|
+
* from production builds): sign in as the mock user of another role.
|
|
23
|
+
*/
|
|
24
|
+
export function DevRoleSwitcher() {
|
|
25
|
+
const { t } = useTranslation()
|
|
26
|
+
const role = useSession()?.user.role
|
|
27
|
+
|
|
28
|
+
async function switchTo(next: Role) {
|
|
29
|
+
try {
|
|
30
|
+
const session = await authService.switchRole(next)
|
|
31
|
+
toast.info(t('shell.devSwitched', { name: fullName(session.user), role: t(`roles.${next as 'owner'}`) }))
|
|
32
|
+
} catch (e) {
|
|
33
|
+
toast.error(e instanceof Error ? e.message : String(e))
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<DropdownMenu>
|
|
39
|
+
<DropdownMenuTrigger
|
|
40
|
+
render={
|
|
41
|
+
<Button variant="outline" size="sm" aria-label={t('shell.devRole')} className="gap-1.5 border-dashed">
|
|
42
|
+
<FlaskConical className="text-warning" />
|
|
43
|
+
<span className="tabular-nums text-[11px] uppercase">{role ? t(`roles.${role as 'owner'}`) : '—'}</span>
|
|
44
|
+
</Button>
|
|
45
|
+
}
|
|
46
|
+
/>
|
|
47
|
+
<DropdownMenuContent align="end" className="w-56">
|
|
48
|
+
<DropdownMenuGroup>
|
|
49
|
+
<DropdownMenuLabel className="flex flex-col gap-0.5">
|
|
50
|
+
<span className="label-caps">{t('shell.devRole')}</span>
|
|
51
|
+
<span className="text-xs font-normal text-muted-foreground">{t('shell.devRoleHint')}</span>
|
|
52
|
+
</DropdownMenuLabel>
|
|
53
|
+
<DropdownMenuRadioGroup value={role} onValueChange={(v) => void switchTo(v as Role)}>
|
|
54
|
+
{roles.map((r) => (
|
|
55
|
+
<DropdownMenuRadioItem key={r} value={r}>
|
|
56
|
+
{t(`roles.${r as 'owner'}`)}
|
|
57
|
+
</DropdownMenuRadioItem>
|
|
58
|
+
))}
|
|
59
|
+
</DropdownMenuRadioGroup>
|
|
60
|
+
</DropdownMenuGroup>
|
|
61
|
+
</DropdownMenuContent>
|
|
62
|
+
</DropdownMenu>
|
|
63
|
+
)
|
|
64
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ApiError } from '@/core/api/http'
|
|
2
|
+
import { storage } from '@/core/lib/storage'
|
|
3
|
+
|
|
4
|
+
const KEY = 'mock:credentials'
|
|
5
|
+
const ITERATIONS = 210_000
|
|
6
|
+
|
|
7
|
+
type StoredPassword = { salt: string; hash: string }
|
|
8
|
+
|
|
9
|
+
const toHex = (bytes: ArrayBuffer | Uint8Array) =>
|
|
10
|
+
Array.from(new Uint8Array(bytes as ArrayBuffer), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
11
|
+
const fromHex = (hex: string) => Uint8Array.from(hex.match(/.{2}/g) ?? [], (h) => parseInt(h, 16))
|
|
12
|
+
|
|
13
|
+
async function derive(password: string, salt: Uint8Array) {
|
|
14
|
+
// crypto.subtle only exists on https and localhost.
|
|
15
|
+
if (!crypto.subtle) throw new ApiError(400, 'insecure_context')
|
|
16
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits'])
|
|
17
|
+
const bits = await crypto.subtle.deriveBits(
|
|
18
|
+
{ name: 'PBKDF2', hash: 'SHA-256', salt: salt as BufferSource, iterations: ITERATIONS },
|
|
19
|
+
key,
|
|
20
|
+
256,
|
|
21
|
+
)
|
|
22
|
+
return toHex(bits)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const readAll = () => storage.get<Record<string, StoredPassword>>(KEY) ?? {}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Passwords for local mode (no backend yet). Only a salted hash is kept, but it
|
|
29
|
+
* lives in this browser, so this keeps the panel usable while building and is
|
|
30
|
+
* NOT real security. A real backend owns passwords.
|
|
31
|
+
*/
|
|
32
|
+
export const localCredentials = {
|
|
33
|
+
/** Whether any account exists on this browser. */
|
|
34
|
+
any: () => Object.keys(readAll()).length > 0,
|
|
35
|
+
|
|
36
|
+
async set(userId: string, password: string) {
|
|
37
|
+
const salt = crypto.getRandomValues(new Uint8Array(16))
|
|
38
|
+
storage.set(KEY, { ...readAll(), [userId]: { salt: toHex(salt), hash: await derive(password, salt) } })
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
async verify(userId: string, password: string) {
|
|
42
|
+
const stored = readAll()[userId]
|
|
43
|
+
if (!stored) return false
|
|
44
|
+
return (await derive(password, fromHex(stored.salt))) === stored.hash
|
|
45
|
+
},
|
|
46
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { appConfig } from '@/app.config'
|
|
2
|
+
import { customPermissions, customRoles, type CustomRole } from '@/app.roles'
|
|
3
|
+
import { moduleRegistry, type ModuleId } from '@/modules/registry'
|
|
4
|
+
import { roles, type coreRoles, type Role } from './roles'
|
|
5
|
+
|
|
6
|
+
export { roles, type Role }
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Roles and permissions: the single place that maps roles to what they can do.
|
|
10
|
+
*
|
|
11
|
+
* ⚠️ UI checks are NOT security. `Can`, `useCan`, hidden nav items and route
|
|
12
|
+
* guards only keep the interface tidy; anyone can bypass them in the browser.
|
|
13
|
+
* The backend must enforce every permission on every request.
|
|
14
|
+
*
|
|
15
|
+
* Permission strings are designed to be reused 1:1 as Spring Security
|
|
16
|
+
* authorities (e.g. `@PreAuthorize("hasAuthority('products.delete')")`) or as
|
|
17
|
+
* scopes in a Node.js API, so keep them stable: `<resource>.<action>`.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Every module gets these four permissions: `products.view`, `products.create`, … */
|
|
21
|
+
export const moduleActions = ['view', 'create', 'edit', 'delete'] as const
|
|
22
|
+
export type ModuleAction = (typeof moduleActions)[number]
|
|
23
|
+
export type ModulePermission = `${ModuleId}.${ModuleAction}`
|
|
24
|
+
|
|
25
|
+
export const corePermissions = [
|
|
26
|
+
'dashboard.view',
|
|
27
|
+
'settings.company.view',
|
|
28
|
+
'settings.company.edit',
|
|
29
|
+
'users.view',
|
|
30
|
+
'users.manage',
|
|
31
|
+
'roles.view',
|
|
32
|
+
'audit.view',
|
|
33
|
+
'integrations.manage',
|
|
34
|
+
'company.transfer',
|
|
35
|
+
'company.delete',
|
|
36
|
+
] as const
|
|
37
|
+
export type CorePermission = (typeof corePermissions)[number]
|
|
38
|
+
|
|
39
|
+
/** Project-specific permissions from src/app.roles.ts, e.g. `orders.refund`. */
|
|
40
|
+
export type CustomPermission = (typeof customPermissions)[number]['id']
|
|
41
|
+
|
|
42
|
+
export type Permission = CorePermission | ModulePermission | CustomPermission
|
|
43
|
+
|
|
44
|
+
/** Danger zone: only the Owner. */
|
|
45
|
+
const ownerOnly: readonly CorePermission[] = ['company.transfer', 'company.delete']
|
|
46
|
+
|
|
47
|
+
const customIds = (customPermissions as readonly { id: string }[]).map((p) => p.id as CustomPermission)
|
|
48
|
+
const extraRoles = Object.fromEntries(
|
|
49
|
+
Object.entries(customRoles as Record<string, CustomRole>).map(([id, role]) => [id, role.permissions]),
|
|
50
|
+
) as Record<string, readonly Permission[]>
|
|
51
|
+
|
|
52
|
+
const moduleIds = (Object.keys(moduleRegistry) as ModuleId[]).filter((id) => appConfig.modules[id])
|
|
53
|
+
const modulePermissions = (actions: readonly ModuleAction[]): ModulePermission[] =>
|
|
54
|
+
moduleIds.flatMap((id) => actions.map((action) => `${id}.${action}` as const))
|
|
55
|
+
|
|
56
|
+
const builtInPermissions: Record<(typeof coreRoles)[number], readonly Permission[]> = {
|
|
57
|
+
/** Everything. Exactly one Owner; can't be removed or demoted, only transfer ownership. */
|
|
58
|
+
owner: [...corePermissions, ...modulePermissions(moduleActions), ...customIds],
|
|
59
|
+
/** Everything except the danger zone. Can't edit the Owner (see canManageUser). */
|
|
60
|
+
admin: [...corePermissions.filter((p) => !ownerOnly.includes(p)), ...modulePermissions(moduleActions), ...customIds],
|
|
61
|
+
/** Create/edit/delete in modules; no company settings. */
|
|
62
|
+
editor: ['dashboard.view', ...modulePermissions(moduleActions)],
|
|
63
|
+
/** Read-only. */
|
|
64
|
+
viewer: ['dashboard.view', ...modulePermissions(['view'])],
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Built-in roles plus the project-defined ones (src/app.roles.ts). */
|
|
68
|
+
export const rolePermissions = { ...builtInPermissions, ...extraRoles } as Record<Role, readonly Permission[]>
|
|
69
|
+
|
|
70
|
+
const sets = Object.fromEntries(roles.map((r) => [r, new Set(rolePermissions[r])])) as Record<Role, Set<Permission>>
|
|
71
|
+
|
|
72
|
+
export function hasPermission(role: Role | undefined, permission: Permission) {
|
|
73
|
+
return role ? (sets[role]?.has(permission) ?? false) : false
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Owner rules for user management (in addition to `users.manage`):
|
|
78
|
+
* nobody changes the Owner's role or status (ownership is transferred in the
|
|
79
|
+
* danger zone), and nobody manages themselves from the users table.
|
|
80
|
+
*/
|
|
81
|
+
export function canManageUser(actor: { id: string; role: Role } | null, target: { id: string; role: Role }) {
|
|
82
|
+
if (!actor || !hasPermission(actor.role, 'users.manage')) return false
|
|
83
|
+
if (target.role === 'owner') return false
|
|
84
|
+
return actor.id !== target.id
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Translation key segment for a custom permission (dots would split the key). */
|
|
88
|
+
export const customResourceId = (id: string) => `custom_${id.replaceAll('.', '_')}`
|
|
89
|
+
|
|
90
|
+
/** Rows of the read-only permission matrix (Settings → Roles & permissions). */
|
|
91
|
+
export const matrixActions = ['view', 'create', 'edit', 'delete', 'manage'] as const
|
|
92
|
+
export type MatrixAction = (typeof matrixActions)[number]
|
|
93
|
+
|
|
94
|
+
export type MatrixRow = {
|
|
95
|
+
/** Module id or core resource id; label is `settings:roles.resources.<id>` or the module nav label. */
|
|
96
|
+
id: string
|
|
97
|
+
module?: ModuleId
|
|
98
|
+
actions: Partial<Record<MatrixAction, Permission>>
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const permissionMatrix: MatrixRow[] = [
|
|
102
|
+
{ id: 'dashboard', actions: { view: 'dashboard.view' } },
|
|
103
|
+
...moduleIds.map((id) => ({
|
|
104
|
+
id,
|
|
105
|
+
module: id,
|
|
106
|
+
actions: { view: `${id}.view`, create: `${id}.create`, edit: `${id}.edit`, delete: `${id}.delete` } as const,
|
|
107
|
+
})),
|
|
108
|
+
{ id: 'companySettings', actions: { view: 'settings.company.view', edit: 'settings.company.edit' } },
|
|
109
|
+
{ id: 'users', actions: { view: 'users.view', manage: 'users.manage' } },
|
|
110
|
+
{ id: 'roles', actions: { view: 'roles.view' } },
|
|
111
|
+
{ id: 'audit', actions: { view: 'audit.view' } },
|
|
112
|
+
{ id: 'integrations', actions: { manage: 'integrations.manage' } },
|
|
113
|
+
{ id: 'company', actions: { manage: 'company.transfer', delete: 'company.delete' } },
|
|
114
|
+
...customIds.map((id) => ({ id: customResourceId(id), actions: { manage: id } })),
|
|
115
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ReactNode } from 'react'
|
|
2
|
+
import { Navigate, useLocation } from 'react-router'
|
|
3
|
+
|
|
4
|
+
import { useSession } from './use-auth'
|
|
5
|
+
|
|
6
|
+
/** Redirects to /login (remembering where the user wanted to go) when signed out. */
|
|
7
|
+
export function RequireAuth({ children }: { children: ReactNode }) {
|
|
8
|
+
const session = useSession()
|
|
9
|
+
const location = useLocation()
|
|
10
|
+
|
|
11
|
+
if (!session) {
|
|
12
|
+
const redirect = location.pathname + location.search
|
|
13
|
+
return <Navigate to={`/login?redirect=${encodeURIComponent(redirect)}`} replace />
|
|
14
|
+
}
|
|
15
|
+
return children
|
|
16
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ReactNode } from 'react'
|
|
2
|
+
import { Navigate, useLocation, useMatches } from 'react-router'
|
|
3
|
+
|
|
4
|
+
import type { RouteHandle } from '@/core/modules/types'
|
|
5
|
+
import { usePermissions } from './can'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Route guard for the app shell: every matched route's `handle.permission`
|
|
9
|
+
* must be granted, otherwise redirect to the "no access" page.
|
|
10
|
+
* UI only — the backend must reject the same requests.
|
|
11
|
+
*/
|
|
12
|
+
export function RequirePermissions({ children }: { children: ReactNode }) {
|
|
13
|
+
const matches = useMatches()
|
|
14
|
+
const { can } = usePermissions()
|
|
15
|
+
const location = useLocation()
|
|
16
|
+
|
|
17
|
+
const denied = matches.some((m) => {
|
|
18
|
+
const permission = (m.handle as RouteHandle | undefined)?.permission
|
|
19
|
+
return permission !== undefined && !can(permission)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
if (denied) return <Navigate to="/app/no-access" replace state={{ from: location.pathname }} />
|
|
23
|
+
return children
|
|
24
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { customRoles } from '@/app.roles'
|
|
2
|
+
|
|
3
|
+
/** The four built-in roles plus any from src/app.roles.ts. Kept light so low-level code (auth-store) can import it. */
|
|
4
|
+
export const coreRoles = ['owner', 'admin', 'editor', 'viewer'] as const
|
|
5
|
+
export type Role = (typeof coreRoles)[number] | Extract<keyof typeof customRoles, string>
|
|
6
|
+
|
|
7
|
+
export const roles = [...coreRoles, ...Object.keys(customRoles)] as Role[]
|
|
8
|
+
|
|
9
|
+
export const isRole = (value: unknown): value is Role => roles.includes(value as Role)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { User } from '@/core/users/types'
|
|
2
|
+
import type { Role } from './permissions'
|
|
3
|
+
|
|
4
|
+
export type { User }
|
|
5
|
+
|
|
6
|
+
export type Session = {
|
|
7
|
+
user: User
|
|
8
|
+
/** Bearer token sent by core/api/http.ts. Absent in cookie mode, where the browser sends the session cookie. */
|
|
9
|
+
token?: string
|
|
10
|
+
expiresAt: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type Credentials = { email: string; password: string }
|
|
14
|
+
|
|
15
|
+
export interface AuthService {
|
|
16
|
+
login(credentials: Credentials): Promise<Session>
|
|
17
|
+
logout(): Promise<void>
|
|
18
|
+
/** Development only: sign in as the first active mock user with this role. */
|
|
19
|
+
switchRole(role: Role): Promise<Session>
|
|
20
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { useSyncExternalStore } from 'react'
|
|
2
|
+
|
|
3
|
+
import { authStore } from './auth-store'
|
|
4
|
+
import { authService } from './auth.service'
|
|
5
|
+
|
|
6
|
+
export function useSession() {
|
|
7
|
+
return useSyncExternalStore(authStore.subscribe, authStore.getSession)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function useAuth() {
|
|
11
|
+
const session = useSession()
|
|
12
|
+
return {
|
|
13
|
+
session,
|
|
14
|
+
user: session?.user ?? null,
|
|
15
|
+
isAuthenticated: session !== null,
|
|
16
|
+
login: authService.login,
|
|
17
|
+
logout: authService.logout,
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { appConfig } from '@/app.config'
|
|
2
|
+
import { demoSeed } from '@/core/api/demo'
|
|
3
|
+
import { ApiError } from '@/core/api/http'
|
|
4
|
+
import { createMockDocument, delay } from '@/core/api/mock'
|
|
5
|
+
import { auditService } from '@/core/audit/audit.service'
|
|
6
|
+
import { authStore } from '@/core/auth/auth-store'
|
|
7
|
+
import { storage } from '@/core/lib/storage'
|
|
8
|
+
import { defaultPasswordPolicy } from './password-policy'
|
|
9
|
+
import type { CompanyBranding, CompanyGeneral, CompanySettings, Currency, SecurityPolicies } from './types'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Company-wide settings. A real backend implements this with `http`
|
|
13
|
+
* (GET /company, PUT /company/general …) and writes the audit log itself.
|
|
14
|
+
*/
|
|
15
|
+
export interface CompanyService {
|
|
16
|
+
get(): Promise<CompanySettings>
|
|
17
|
+
updateGeneral(input: CompanyGeneral): Promise<CompanySettings>
|
|
18
|
+
updateBranding(input: CompanyBranding): Promise<CompanySettings>
|
|
19
|
+
updateSecurity(input: SecurityPolicies): Promise<CompanySettings>
|
|
20
|
+
/** Danger zone: `confirmName` must equal the company name. */
|
|
21
|
+
deleteCompany(confirmName: string): Promise<void>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Empty company settings with the given values filled in; used by the setup wizard. */
|
|
25
|
+
export const createCompanySettings = (general?: Partial<CompanyGeneral>, branding?: Partial<CompanyBranding>): CompanySettings => ({
|
|
26
|
+
general: {
|
|
27
|
+
name: appConfig.name,
|
|
28
|
+
legalName: '',
|
|
29
|
+
taxOffice: '',
|
|
30
|
+
taxNumber: '',
|
|
31
|
+
address: '',
|
|
32
|
+
contactEmail: '',
|
|
33
|
+
defaultLanguage: 'en',
|
|
34
|
+
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
35
|
+
currency: appConfig.currency as Currency,
|
|
36
|
+
...general,
|
|
37
|
+
},
|
|
38
|
+
branding: { brand: appConfig.brand, ...branding },
|
|
39
|
+
security: {
|
|
40
|
+
requireTwoFactor: false,
|
|
41
|
+
password: { ...defaultPasswordPolicy, expiryDays: 0 },
|
|
42
|
+
sessionTimeout: 480,
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
function createMockCompanyService(): CompanyService {
|
|
47
|
+
const doc = createMockDocument('company', () => createCompanySettings(demoSeed<Partial<CompanyGeneral>>('companyGeneral')))
|
|
48
|
+
const assertOwnerOrAdmin = () => {
|
|
49
|
+
const role = authStore.getSession()?.user.role
|
|
50
|
+
if (role !== 'owner' && role !== 'admin') throw new ApiError(403, 'forbidden')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
async get() {
|
|
55
|
+
await delay(150, 300)
|
|
56
|
+
return doc.get()
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
async updateGeneral(general) {
|
|
60
|
+
await delay()
|
|
61
|
+
assertOwnerOrAdmin()
|
|
62
|
+
auditService.record('generalUpdated', general.name)
|
|
63
|
+
return doc.save({ ...doc.get(), general })
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
async updateBranding(branding) {
|
|
67
|
+
await delay()
|
|
68
|
+
assertOwnerOrAdmin()
|
|
69
|
+
auditService.record('brandingUpdated', doc.get().general.name)
|
|
70
|
+
return doc.save({ ...doc.get(), branding })
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
async updateSecurity(security) {
|
|
74
|
+
await delay()
|
|
75
|
+
assertOwnerOrAdmin()
|
|
76
|
+
auditService.record('securityUpdated', doc.get().general.name)
|
|
77
|
+
return doc.save({ ...doc.get(), security })
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
async deleteCompany(confirmName) {
|
|
81
|
+
await delay(600, 900)
|
|
82
|
+
if (authStore.getSession()?.user.role !== 'owner') throw new ApiError(403, 'forbidden')
|
|
83
|
+
if (confirmName !== doc.get().general.name) throw new ApiError(400, 'confirmation_mismatch')
|
|
84
|
+
// Demo: wipe every mock table and setting stored by this app, then sign out.
|
|
85
|
+
for (const key of Object.keys(localStorage)) {
|
|
86
|
+
if (key.startsWith('fp:mock:') || key === 'fp:brand') storage.remove(key.slice(3))
|
|
87
|
+
}
|
|
88
|
+
authStore.clear()
|
|
89
|
+
window.location.assign(import.meta.env.BASE_URL)
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const companyService: CompanyService = createMockCompanyService()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
2
|
+
|
|
3
|
+
import { auditKeys } from '@/core/audit/hooks'
|
|
4
|
+
import { companyService } from './company.service'
|
|
5
|
+
import { defaultPasswordPolicy } from './password-policy'
|
|
6
|
+
import type { CompanyBranding, CompanyGeneral, CompanySettings, SecurityPolicies } from './types'
|
|
7
|
+
|
|
8
|
+
export const companyKeys = { all: ['company'] as const }
|
|
9
|
+
|
|
10
|
+
export function useCompanySettings() {
|
|
11
|
+
return useQuery({ queryKey: companyKeys.all, queryFn: () => companyService.get(), staleTime: 5 * 60_000 })
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function useCompanyMutation<T>(fn: (input: T) => Promise<CompanySettings>) {
|
|
15
|
+
const qc = useQueryClient()
|
|
16
|
+
return useMutation({
|
|
17
|
+
mutationFn: fn,
|
|
18
|
+
onSuccess: (data) => {
|
|
19
|
+
qc.setQueryData(companyKeys.all, data)
|
|
20
|
+
return qc.invalidateQueries({ queryKey: auditKeys.all })
|
|
21
|
+
},
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const useUpdateGeneral = () => useCompanyMutation((input: CompanyGeneral) => companyService.updateGeneral(input))
|
|
26
|
+
export const useUpdateBranding = () => useCompanyMutation((input: CompanyBranding) => companyService.updateBranding(input))
|
|
27
|
+
export const useUpdateSecurity = () => useCompanyMutation((input: SecurityPolicies) => companyService.updateSecurity(input))
|
|
28
|
+
|
|
29
|
+
/** Danger zone. The mock wipes local data, signs out and reloads to the landing page. */
|
|
30
|
+
export const useDeleteCompany = () =>
|
|
31
|
+
useMutation({ mutationFn: (confirmName: string) => companyService.deleteCompany(confirmName) })
|
|
32
|
+
|
|
33
|
+
/** The password rules and 2FA requirement that apply to the current user. */
|
|
34
|
+
export function useSecurityPolicy() {
|
|
35
|
+
const security = useCompanySettings().data?.security
|
|
36
|
+
return {
|
|
37
|
+
password: security?.password ?? defaultPasswordPolicy,
|
|
38
|
+
requireTwoFactor: security?.requireTwoFactor ?? false,
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Company password rules (Settings → Company → Security policies). */
|
|
2
|
+
export type PasswordPolicy = {
|
|
3
|
+
minLength: number
|
|
4
|
+
requireUppercase: boolean
|
|
5
|
+
requireNumber: boolean
|
|
6
|
+
requireSymbol: boolean
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const defaultPasswordPolicy: PasswordPolicy = {
|
|
10
|
+
minLength: 10,
|
|
11
|
+
requireUppercase: true,
|
|
12
|
+
requireNumber: true,
|
|
13
|
+
requireSymbol: false,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type PasswordRule = 'minLength' | 'uppercase' | 'number' | 'symbol'
|
|
17
|
+
|
|
18
|
+
/** Rules that apply under this policy, each with whether `password` meets it. */
|
|
19
|
+
export function checkPassword(policy: PasswordPolicy, password: string) {
|
|
20
|
+
const rules: { rule: PasswordRule; met: boolean }[] = [
|
|
21
|
+
{ rule: 'minLength', met: password.length >= policy.minLength },
|
|
22
|
+
]
|
|
23
|
+
if (policy.requireUppercase) rules.push({ rule: 'uppercase', met: /[A-ZÇĞİÖŞÜ]/.test(password) })
|
|
24
|
+
if (policy.requireNumber) rules.push({ rule: 'number', met: /\d/.test(password) })
|
|
25
|
+
if (policy.requireSymbol) rules.push({ rule: 'symbol', met: /[^\p{L}\d\s]/u.test(password) })
|
|
26
|
+
return { rules, valid: rules.every((r) => r.met) }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 0 (too weak) … 4 (strong): length plus character variety, minus obvious patterns. */
|
|
30
|
+
export function passwordStrength(password: string): 0 | 1 | 2 | 3 | 4 {
|
|
31
|
+
if (!password) return 0
|
|
32
|
+
let score = 0
|
|
33
|
+
if (password.length >= 8) score++
|
|
34
|
+
if (password.length >= 12) score++
|
|
35
|
+
const variety = [/[a-zçğıöşü]/, /[A-ZÇĞİÖŞÜ]/, /\d/, /[^\p{L}\d\s]/u].filter((re) => re.test(password)).length
|
|
36
|
+
if (variety >= 3) score++
|
|
37
|
+
if (variety === 4 && password.length >= 14) score++
|
|
38
|
+
if (/^(.)\1+$/.test(password) || /^(password|parola|123456|qwerty)/i.test(password)) score = 0
|
|
39
|
+
return Math.min(4, score) as 0 | 1 | 2 | 3 | 4
|
|
40
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Language } from '@/core/i18n/types'
|
|
2
|
+
import type { BrandSetting } from '@/core/theme/brand'
|
|
3
|
+
import type { PasswordPolicy } from './password-policy'
|
|
4
|
+
|
|
5
|
+
export const currencies = ['TRY', 'USD', 'EUR', 'GBP'] as const
|
|
6
|
+
export type Currency = (typeof currencies)[number]
|
|
7
|
+
|
|
8
|
+
export type CompanyGeneral = {
|
|
9
|
+
name: string
|
|
10
|
+
legalName: string
|
|
11
|
+
taxOffice: string
|
|
12
|
+
/** VKN: 10 digits. */
|
|
13
|
+
taxNumber: string
|
|
14
|
+
address: string
|
|
15
|
+
contactEmail: string
|
|
16
|
+
/** E.164. */
|
|
17
|
+
contactPhone?: string
|
|
18
|
+
defaultLanguage: Language
|
|
19
|
+
timeZone: string
|
|
20
|
+
currency: Currency
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type CompanyBranding = {
|
|
24
|
+
/** Image URLs (data URLs in mock mode). */
|
|
25
|
+
logoLight?: string
|
|
26
|
+
logoDark?: string
|
|
27
|
+
favicon?: string
|
|
28
|
+
brand: BrandSetting
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const passwordExpiryOptions = [0, 30, 60, 90, 180] as const
|
|
32
|
+
export const sessionTimeoutOptions = [15, 30, 60, 240, 480, 1440, 10080] as const
|
|
33
|
+
export const minLengthOptions = [8, 10, 12, 14, 16] as const
|
|
34
|
+
|
|
35
|
+
export type SecurityPolicies = {
|
|
36
|
+
requireTwoFactor: boolean
|
|
37
|
+
password: PasswordPolicy & { expiryDays: (typeof passwordExpiryOptions)[number] }
|
|
38
|
+
/** Minutes of inactivity before sign-out. */
|
|
39
|
+
sessionTimeout: (typeof sessionTimeoutOptions)[number]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type CompanySettings = {
|
|
43
|
+
general: CompanyGeneral
|
|
44
|
+
branding: CompanyBranding
|
|
45
|
+
security: SecurityPolicies
|
|
46
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { appConfig } from '@/app.config'
|
|
2
|
+
import { useCompanySettings } from './hooks'
|
|
3
|
+
|
|
4
|
+
/** The company name from setup and Settings → General; falls back to app.config.ts. */
|
|
5
|
+
export function useAppName() {
|
|
6
|
+
return useCompanySettings().data?.general.name || appConfig.name
|
|
7
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ComponentProps } from 'react'
|
|
2
|
+
import { Link, type LinkProps } from 'react-router'
|
|
3
|
+
|
|
4
|
+
import { Button } from '@/components/ui/button'
|
|
5
|
+
|
|
6
|
+
/** A SortUI Button that navigates with React Router. */
|
|
7
|
+
export function ButtonLink({
|
|
8
|
+
to,
|
|
9
|
+
replace,
|
|
10
|
+
state,
|
|
11
|
+
...props
|
|
12
|
+
}: Omit<ComponentProps<typeof Button>, 'render' | 'nativeButton'> & Pick<LinkProps, 'to' | 'replace' | 'state'>) {
|
|
13
|
+
return <Button {...props} nativeButton={false} render={<Link to={to} replace={replace} state={state} />} />
|
|
14
|
+
}
|