Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Add API key rate limiting and read/write scopes (#528)

Brad Barbin7cac9b6451f2
diff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsx
index d40765e972..511865d31e 100644
--- a/apps/academy/app/root.tsx
+++ b/apps/academy/app/root.tsx
@@ -74,6 +74,7 @@ export const meta: MetaFunction = () => {
export async function loader({ request }: LoaderFunctionArgs) {
const {
CARBON_EDITION,
+ CARBON_API_URL,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
SUPABASE_URL,
@@ -123,6 +124,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
challengeAttempts,
env: {
CARBON_EDITION,
+ CARBON_API_URL,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
SUPABASE_URL,
diff --git a/apps/academy/app/styles/docs.css b/apps/academy/app/styles/docs.css
index 432059e06e..51739cefb9 100644
--- a/apps/academy/app/styles/docs.css
+++ b/apps/academy/app/styles/docs.css
@@ -2,72 +2,14 @@
width: 100%;
}
-.Code .prism-code {
+.Code pre {
margin: 0;
- padding: 0.25rem;
- background-color: none;
- white-space: normal;
- word-break: break-word;
-}
-
-.Code .token-line {
+ padding: 0.5rem 0.75rem;
+ background-color: transparent;
font-size: 0.875rem;
line-height: 1.25rem;
}
-.Code .token.function,
-.Code .token.imports,
-.Code .token.keyword.module,
-.Code .token.property-access {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.function,
-.Code .token.keyword.module {
- font-style: normal !important;
-}
-
-.Code .token.console.class-name,
-.Code .token.doc-comment.optional-parameter,
-.Code .token.doc-comment.optional-parameter.punctuation,
-.Code .token.doc-comment.parameter,
-.Code .token.doc-comment.parameter.punctuation,
-.Code .token.operator,
-.Code .token.parameter,
-.Code .token.plain,
-.Code .token.punctuation {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.doc-comment.keyword,
-.Code .token.keyword {
- font-style: normal !important;
-}
-
-.Code .token.string {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.constant {
- font-style: normal !important;
-}
-
-.Code .token.comment {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.number {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.boolean,
-.Code .token.doc-comment.class-name {
- --tw-text-opacity: 1;
-}
-
.Code .codeBlock {
margin-bottom: 0;
overflow: hidden;
diff --git a/apps/erp/app/components/PermissionMatrix.tsx b/apps/erp/app/components/PermissionMatrix.tsx
new file mode 100644
index 0000000000..972f336010
--- /dev/null
+++ b/apps/erp/app/components/PermissionMatrix.tsx
@@ -0,0 +1,98 @@
+import { Checkbox, Table, Tbody, Td, Th, Thead, Tr } from "@carbon/react";
+import type { UsePermissionMatrixReturn } from "~/hooks/usePermissionMatrix";
+import { capitalize } from "~/utils/string";
+
+type PermissionMatrixProps = {
+ /** The return value from usePermissionMatrix */
+ matrix: UsePermissionMatrixReturn;
+ /** Optional section label (default: "Permissions") */
+ label?: string;
+};
+
+const PermissionMatrix = ({
+ matrix,
+ label = "Permissions"
+}: PermissionMatrixProps) => {
+ const {
+ modules,
+ actions,
+ isChecked,
+ toggleCell,
+ toggleRow,
+ toggleAll,
+ allChecked,
+ someChecked,
+ isRowAllChecked,
+ isRowIndeterminate,
+ hasAction
+ } = matrix;
+
+ return (
+ <div className="w-full">
+ {label && (
+ <label className="block text-sm font-medium leading-none mb-2">
+ {label}
+ </label>
+ )}
+ <div className="rounded-md border overflow-hidden">
+ <Table>
+ <Thead>
+ <Tr>
+ <Th className="w-[140px]">
+ <div className="flex items-center gap-2">
+ <Checkbox
+ isChecked={allChecked}
+ isIndeterminate={someChecked && !allChecked}
+ onCheckedChange={() => toggleAll()}
+ />
+ <span>Module</span>
+ </div>
+ </Th>
+ {actions.map((action) => (
+ <Th key={action} className="w-[80px] text-center">
+ <div className="flex flex-col items-center gap-1">
+ <span>{capitalize(action)}</span>
+ </div>
+ </Th>
+ ))}
+ </Tr>
+ </Thead>
+ <Tbody>
+ {modules.map(([mod]) => (
+ <Tr key={mod}>
+ <Td>
+ <div className="flex items-center gap-2">
+ <Checkbox
+ isChecked={isRowAllChecked(mod)}
+ isIndeterminate={isRowIndeterminate(mod)}
+ onCheckedChange={() => toggleRow(mod)}
+ />
+ <span className="text-sm font-medium">
+ {capitalize(mod)}
+ </span>
+ </div>
+ </Td>
+ {actions.map((action) => (
+ <Td key={action} className="text-center">
+ {hasAction(mod, action) ? (
+ <Checkbox
+ isChecked={isChecked(mod, action)}
+ onCheckedChange={() => toggleCell(mod, action)}
+ />
+ ) : (
+ <span className="text-muted-foreground pl-6 block">
+ --
+ </span>
+ )}
+ </Td>
+ ))}
+ </Tr>
+ ))}
+ </Tbody>
+ </Table>
+ </div>
+ </div>
+ );
+};
+
+export default PermissionMatrix;
diff --git a/apps/erp/app/hooks/usePermissionMatrix.ts b/apps/erp/app/hooks/usePermissionMatrix.ts
new file mode 100644
index 0000000000..abebb008ff
--- /dev/null
+++ b/apps/erp/app/hooks/usePermissionMatrix.ts
@@ -0,0 +1,316 @@
+import { useCallback, useMemo, useState } from "react";
+import type { CompanyPermission } from "~/modules/users";
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export type PermissionAction = "view" | "create" | "update" | "delete";
+
+/**
+ * Module definitions: a map of module name to its allowed CRUD actions.
+ * Example: { accounting: ["view", "create", "update"], sales: ["view", "create", "update", "delete"] }
+ */
+export type ModuleDefinition = Record<string, readonly PermissionAction[]>;
+
+export type UsePermissionMatrixOptions = {
+ /** Module definitions: { moduleName: ["view", "create", ...] } */
+ modules: ModuleDefinition;
+ /** Initial permission state as a flat boolean map (e.g. { "sales_view": true }) */
+ initialState?: Record<string, boolean>;
+};
+
+export type UsePermissionMatrixReturn = {
+ /** Current permissions as flat boolean map */
+ permissions: Record<string, boolean>;
+ /** Sorted module entries: [moduleName, actions[]][] */
+ modules: [string, readonly PermissionAction[]][];
+ /** All available actions */
+ actions: readonly PermissionAction[];
+ /** Check if a specific permission is enabled */
+ isChecked: (module: string, action: string) => boolean;
+ /** Toggle a single cell */
+ toggleCell: (module: string, action: string) => void;
+ /** Toggle all actions for a module row */
+ toggleRow: (module: string) => void;
+ /** Toggle all permissions globally */
+ toggleAll: () => void;
+ /** Whether all permissions are checked */
+ allChecked: boolean;
+ /** Whether some (but not all) permissions are checked */
+ someChecked: boolean;
+ /** Whether all actions in a specific module row are checked */
+ isRowAllChecked: (module: string) => boolean;
+ /** Whether some (but not all) actions in a module row are checked */
+ isRowIndeterminate: (module: string) => boolean;
+ /** Whether a module supports a specific action */
+ hasAction: (module: string, action: string) => boolean;
+ /** Set permissions state directly */
+ setPermissions: (permissions: Record<string, boolean>) => void;
+};
+
+// ---------------------------------------------------------------------------
+// Constants
+// ---------------------------------------------------------------------------
+
+const ALL_ACTIONS: readonly PermissionAction[] = [
+ "view",
+ "create",
+ "update",
+ "delete"
+] as const;
+
+/** Modules that should be hidden from all permission UIs */
+const HIDDEN_MODULES = new Set(["messaging", "items", "timecards"]);
+
+// ---------------------------------------------------------------------------
+// Hook
+// ---------------------------------------------------------------------------
+
+export function usePermissionMatrix({
+ modules,
+ initialState
+}: UsePermissionMatrixOptions): UsePermissionMatrixReturn {
+ const sortedModules = useMemo<[string, readonly PermissionAction[]][]>(
+ () =>
+ Object.entries(modules).sort(([a], [b]) => a.localeCompare(b)) as [
+ string,
+ readonly PermissionAction[]
+ ][],
+ [modules]
+ );
+
+ const [permissions, setPermissionsRaw] = useState<Record<string, boolean>>(
+ () => initialState ?? buildDefaultState(modules)
+ );
+
+ const setPermissions = useCallback(
+ (next: Record<string, boolean>) => setPermissionsRaw(next),
+ []
+ );
+
+ // Derived state
+ const allKeys = useMemo(() => Object.keys(permissions), [permissions]);
+ const allChecked = useMemo(
+ () => allKeys.length > 0 && allKeys.every((k) => permissions[k]),
+ [allKeys, permissions]
+ );
+ const someChecked = useMemo(
+ () => allKeys.some((k) => permissions[k]),
+ [allKeys, permissions]
+ );
+
+ const isChecked = useCallback(
+ (mod: string, action: string) => permissions[`${mod}_${action}`] ?? false,
+ [permissions]
+ );
+
+ const hasAction = useCallback(
+ (mod: string, action: string) =>
+ (modules[mod] as readonly string[] | undefined)?.includes(action) ??
+ false,
+ [modules]
+ );
+
+ const toggleCell = useCallback((mod: string, action: string) => {
+ const key = `${mod}_${action}`;
+ setPermissionsRaw((prev) => ({ ...prev, [key]: !prev[key] }));
+ }, []);
+
+ const toggleRow = useCallback(
+ (mod: string) => {
+ setPermissionsRaw((prev) => {
+ const moduleActions = modules[mod] ?? [];
+ const rowKeys = moduleActions.map((a) => `${mod}_${a}`);
+ const allRowChecked = rowKeys.every((k) => prev[k]);
+ const next = { ...prev };
+ for (const k of rowKeys) {
+ next[k] = !allRowChecked;
+ }
+ return next;
+ });
+ },
+ [modules]
+ );
+
+ const toggleAll = useCallback(() => {
+ setPermissionsRaw((prev) => {
+ const keys = Object.keys(prev);
+ const currentAllChecked = keys.length > 0 && keys.every((k) => prev[k]);
+ const next: Record<string, boolean> = {};
+ for (const k of keys) {
+ next[k] = !currentAllChecked;
+ }
+ return next;
+ });
+ }, []);
+
+ const isRowAllChecked = useCallback(
+ (mod: string) => {
+ const moduleActions = modules[mod] ?? [];
+ return (
+ moduleActions.length > 0 &&
+ moduleActions.every((a) => permissions[`${mod}_${a}`])
+ );
+ },
+ [modules, permissions]
+ );
+
+ const isRowIndeterminate = useCallback(
+ (mod: string) => {
+ const moduleActions = modules[mod] ?? [];
+ const some = moduleActions.some((a) => permissions[`${mod}_${a}`]);
+ const all = moduleActions.every((a) => permissions[`${mod}_${a}`]);
+ return some && !all;
+ },
+ [modules, permissions]
+ );
+
+ return {
+ permissions,
+ modules: sortedModules,
+ actions: ALL_ACTIONS,
+ isChecked,
+ toggleCell,
+ toggleRow,
+ toggleAll,
+ allChecked,
+ someChecked,
+ isRowAllChecked,
+ isRowIndeterminate,
+ hasAction,
+ setPermissions
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/** Build a default all-false state from module definitions */
+function buildDefaultState(modules: ModuleDefinition): Record<string, boolean> {
+ const state: Record<string, boolean> = {};
+ for (const [mod, actions] of Object.entries(modules)) {
+ for (const action of actions) {
+ state[`${mod}_${action}`] = false;
+ }
+ }
+ return state;
+}
+
+// ---------------------------------------------------------------------------
+// Adapter: API Key scopes
+// ---------------------------------------------------------------------------
+
+/** Convert flat boolean map → JSONB scopes format { "sales_view": ["<companyId>"], ... } */
+export function toApiKeyScopes(
+ permissions: Record<string, boolean>,
+ companyId: string
+): Record<string, string[]> {
+ const result: Record<string, string[]> = {};
+ for (const [key, enabled] of Object.entries(permissions)) {
+ if (enabled) {
+ result[key] = [companyId];
+ }
+ }
+ return result;
+}
+
+/** Convert JSONB scopes format → flat boolean map (empty scopes = no access) */
+export function fromApiKeyScopes(
+ scopes: Record<string, string[]> | null | undefined,
+ modules: ModuleDefinition
+): Record<string, boolean> {
+ const state = buildDefaultState(modules);
+ if (!scopes || Object.keys(scopes).length === 0) {
+ return state;
+ }
+ for (const key of Object.keys(scopes)) {
+ if (key in state) {
+ state[key] = true;
+ }
+ }
+ return state;
+}
+
+// ---------------------------------------------------------------------------
+// Adapter: CompanyPermission (employee permissions, bulk edit)
+// ---------------------------------------------------------------------------
+
+/** Convert flat boolean map → Record<string, CompanyPermission> */
+export function toCompanyPermissions(
+ permissions: Record<string, boolean>
+): Record<string, CompanyPermission> {
+ const result: Record<string, CompanyPermission> = {};
+ for (const [key, enabled] of Object.entries(permissions)) {
+ const lastUnderscore = key.lastIndexOf("_");
+ if (lastUnderscore === -1) continue;
+ const mod = key.slice(0, lastUnderscore);
+ const action = key.slice(lastUnderscore + 1);
+ if (!result[mod]) {
+ result[mod] = {
+ view: false,
+ create: false,
+ update: false,
+ delete: false
+ };
+ }
+ if (action in result[mod]) {
+ result[mod][action as keyof CompanyPermission] = enabled;
+ }
+ }
+ return result;
+}
+
+/** Convert Record<string, CompanyPermission> → flat boolean map + derived ModuleDefinition */
+export function fromCompanyPermissions(
+ permissions: Record<string, CompanyPermission>
+): { state: Record<string, boolean>; modules: ModuleDefinition } {
+ const state: Record<string, boolean> = {};
+ const modules: ModuleDefinition = {};
+ for (const [mod, perm] of Object.entries(permissions)) {
+ if (HIDDEN_MODULES.has(mod)) continue;
+ const actions: PermissionAction[] = ["view", "create", "update", "delete"];
+ modules[mod] = actions;
+ for (const action of actions) {
+ state[`${mod}_${action}`] = perm[action];
+ }
+ }
+ return { state, modules };
+}
+
+// ---------------------------------------------------------------------------
+// Adapter: Employee type permissions ({ name, permission } shape)
+// ---------------------------------------------------------------------------
+
+/** Convert flat boolean map → Record<string, { name: string; permission: CompanyPermission }> */
+export function toEmployeeTypePermissions(
+ permissions: Record<string, boolean>
+): Record<string, { name: string; permission: CompanyPermission }> {
+ const company = toCompanyPermissions(permissions);
+ const result: Record<
+ string,
+ { name: string; permission: CompanyPermission }
+ > = {};
+ for (const [mod, perm] of Object.entries(company)) {
+ result[mod] = { name: mod, permission: perm };
+ }
+ return result;
+}
+
+/** Convert Record<string, { name: string; permission: CompanyPermission }> → flat boolean map + derived ModuleDefinition */
+export function fromEmployeeTypePermissions(
+ permissions: Record<string, { name: string; permission: CompanyPermission }>
+): { state: Record<string, boolean>; modules: ModuleDefinition } {
+ const state: Record<string, boolean> = {};
+ const modules: ModuleDefinition = {};
+ for (const [mod, data] of Object.entries(permissions)) {
+ if (HIDDEN_MODULES.has(mod)) continue;
+ const actions: PermissionAction[] = ["view", "create", "update", "delete"];
+ modules[mod] = actions;
+ for (const action of actions) {
+ state[`${mod}_${action}`] = data.permission[action];
+ }
+ }
+ return { state, modules };
+}
diff --git a/apps/erp/app/modules/api/ui/ApiDocsContext.tsx b/apps/erp/app/modules/api/ui/ApiDocsContext.tsx
new file mode 100644
index 0000000000..7218534336
--- /dev/null
+++ b/apps/erp/app/modules/api/ui/ApiDocsContext.tsx
@@ -0,0 +1,41 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState
+} from "react";
+
+type ApiDocsConfig = {
+ apiUrl: string;
+ apiKey: string;
+ setApiUrl: (url: string) => void;
+ setApiKey: (key: string) => void;
+};
+
+const ApiDocsContext = createContext<ApiDocsConfig | null>(null);
+
+export function ApiDocsProvider({ children }: { children: React.ReactNode }) {
+ const [apiUrl, setApiUrlState] = useState("");
+ const [apiKey, setApiKeyState] = useState("");
+
+ const setApiUrl = useCallback((url: string) => setApiUrlState(url), []);
+ const setApiKey = useCallback((key: string) => setApiKeyState(key), []);
+
+ const value = useMemo(
+ () => ({ apiUrl, apiKey, setApiUrl, setApiKey }),
+ [apiUrl, apiKey, setApiUrl, setApiKey]
+ );
+
+ return (
+ <ApiDocsContext.Provider value={value}>{children}</ApiDocsContext.Provider>
+ );
+}
+
+export function useApiDocsConfig() {
+ const ctx = useContext(ApiDocsContext);
+ if (!ctx) {
+ throw new Error("useApiDocsConfig must be used within an ApiDocsProvider");
+ }
+ return ctx;
+}
diff --git a/apps/erp/app/modules/api/ui/CodeSnippet.tsx b/apps/erp/app/modules/api/ui/CodeSnippet.tsx
index efb830da08..271d212e32 100644
--- a/apps/erp/app/modules/api/ui/CodeSnippet.tsx
+++ b/apps/erp/app/modules/api/ui/CodeSnippet.tsx
@@ -4,7 +4,7 @@ interface CodeSnippetProps {
selectedLang: "bash" | "js";
snippet: {
title?: string;
- bash: { language?: string; code: string };
+ bash: { language?: string; code: string } | null;
js?: { language?: string; code: string };
};
}
diff --git a/apps/erp/app/modules/api/ui/Snippets.tsx b/apps/erp/app/modules/api/ui/Snippets.tsx
index 12944e79da..ffe26b1d92 100644
--- a/apps/erp/app/modules/api/ui/Snippets.tsx
+++ b/apps/erp/app/modules/api/ui/Snippets.tsx
@@ -1,361 +1,525 @@
+// ─── Types ───────────────────────────────────────────────────────────────────
+
+import { getBrowserEnv } from "@carbon/auth";
+import { Edition } from "@carbon/utils";
+
+const isProxied = getBrowserEnv().CARBON_EDITION === Edition.Cloud;
+const PUBLIC_KEY = getBrowserEnv().SUPABASE_ANON_KEY;
+
+type SnippetLanguage = { language: string; code: string };
+
+type Snippet = {
+ title?: string;
+ bash: SnippetLanguage | null;
+ js?: SnippetLanguage;
+ python?: SnippetLanguage;
+ dart?: SnippetLanguage;
+};
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
+
+// ─── Curl Builder ────────────────────────────────────────────────────────────
+
+const CONTENT_TYPE_HEADER = `"Content-Type: application/json"`;
+
+function authHeader(apiKey?: string): string {
+ return apiKey
+ ? `"Authorization: Bearer ${apiKey}"`
+ : `"Authorization: Bearer $CARBON_API_KEY"`;
+}
+
+function buildCurl(config: {
+ method?: HttpMethod;
+ url: string;
+ body?: string;
+ headers?: string[];
+ range?: string;
+ includeAuth?: boolean;
+ includeContentType?: boolean;
+ prefer?: string;
+ apiKey?: string;
+}): string {
+ const {
+ method,
+ url,
+ body,
+ headers: extraHeaders = [],
+ range,
+ includeAuth = true,
+ includeContentType = false,
+ prefer,
+ apiKey
+ } = config;
+
+ const parts: string[] = [];
+
+ if (method && method !== "GET") {
+ parts.push(`curl -X ${method} '${url}'`);
+ } else {
+ parts.push(`curl '${url}'`);
+ }
+
+ if (includeAuth) {
+ parts.push(`-H ${authHeader(isProxied ? apiKey : "$CARBON_PUBLIC_KEY")}`);
+ if (!isProxied) {
+ parts.push(`-H "carbon-key: ${apiKey ?? "$CARBON_API_KEY"}"`);
+ }
+ }
+
+ if (includeContentType) {
+ parts.push(`-H ${CONTENT_TYPE_HEADER}`);
+ }
+
+ if (prefer) {
+ parts.push(`-H "Prefer: ${prefer}"`);
+ }
+
+ for (const header of extraHeaders) {
+ parts.push(`-H ${header}`);
+ }
+
+ if (range) {
+ parts.push(`-H "Range: ${range}"`);
+ }
+
+ if (body) {
+ parts.push(`-d '${body}'`);
+ }
+
+ return "\n" + parts.join(" \\\n");
+}
+
+// ─── Snippet Helpers ─────────────────────────────────────────────────────────
+
+function defineSnippet(
+ title: string | undefined,
+ languages: Omit<Snippet, "title">
+): Snippet {
+ return { title, ...languages };
+}
+
+function createBashSnippet(code: string): SnippetLanguage {
+ return { language: "bash", code };
+}
+
+function createJsSnippet(code: string): SnippetLanguage {
+ return { language: "js", code };
+}
+
+// ─── Subscription Config + Builder ───────────────────────────────────────────
+
+const SUBSCRIPTION_CONFIGS = {
+ subscribeAll: {
+ event: "*",
+ channel: "custom-all-channel",
+ title: "Subscribe to all events"
+ },
+ subscribeInserts: {
+ event: "INSERT",
+ channel: "custom-insert-channel",
+ title: "Subscribe to inserts"
+ },
+ subscribeUpdates: {
+ event: "UPDATE",
+ channel: "custom-update-channel",
+ title: "Subscribe to updates"
+ },
+ subscribeDeletes: {
+ event: "DELETE",
+ channel: "custom-delete-channel",
+ title: "Subscribe to deletes"
+ }
+} as const;
+
+const REALTIME_BASH_MESSAGE = `# Realtime streams are only supported by our client libraries`;
+
+function createSubscriptionSnippet(
+ config: { event: string; channel: string; title: string },
+ listenerName: string,
+ resourceId: string,
+ filter?: string
+): Snippet {
+ const filterLine = filter ? `, filter: '${filter}'` : "";
+
+ return defineSnippet(config.title, {
+ bash: createBashSnippet(REALTIME_BASH_MESSAGE),
+ js: createJsSnippet(`
+const ${listenerName} = carbon.channel('${config.channel}')
+ .on(
+ 'postgres_changes',
+ { event: '${config.event}', schema: 'public', table: '${resourceId}'${filterLine} },
+ (payload) => {
+ console.log('Change received!', payload)
+ }
+ )
+ .subscribe()`)
+ });
+}
+
+// ─── Auth Config + Builder ───────────────────────────────────────────────────
+
+type AuthConfig = {
+ method: HttpMethod;
+ path: string;
+ title: string;
+ bashBody?: (...args: string[]) => string;
+ jsCode: (...args: string[]) => string;
+ bashHeaders?: string[];
+};
+
+const AUTH_CONFIGS: Record<string, AuthConfig> = {
+ authSignup: {
+ method: "POST",
+ path: "/auth/v1/signup",
+ title: "User signup",
+ bashBody: (_ep, _ak, pw) =>
+ `{\n "email": "[email protected]",\n "password": "${pw}"\n}`,
+ jsCode: (_ep, _ak, pw) => `
+let { data, error } = await carbon.auth.signUp({
+ email: '[email protected]',
+ password: '${pw}'
+})`
+ },
+ authLogin: {
+ method: "POST",
+ path: "/auth/v1/token?grant_type=password",
+ title: "User login",
+ bashBody: (_ep, _ak, pw) =>
+ `{\n "email": "[email protected]",\n "password": "${pw}"\n}`,
+ jsCode: (_ep, _ak, pw) => `
+let { data, error } = await carbon.auth.signInWithPassword({
+ email: '[email protected]',
+ password: '${pw}'
+})`
+ },
+ authMagicLink: {
+ method: "POST",
+ path: "/auth/v1/magiclink",
+ title: "User login",
+ bashBody: () => `{\n "email": "[email protected]"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.signInWithOtp({
+})`
+ },
+ authPhoneSignUp: {
+ method: "POST",
+ path: "/auth/v1/signup",
+ title: "Phone Signup",
+ bashBody: () =>
+ `{\n "phone": "+13334445555",\n "password": "some-password"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.signUp({
+ phone: '+13334445555',
+ password: 'some-password'
+})`
+ },
+ authMobileOTPLogin: {
+ method: "POST",
+ path: "/auth/v1/otp",
+ title: "Phone Login",
+ bashBody: () => `{\n "phone": "+13334445555"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.signInWithOtp({
+ phone: '+13334445555'
+})`
+ },
+ authMobileOTPVerify: {
+ method: "POST",
+ path: "/auth/v1/verify",
+ title: "Verify Pin",
+ bashHeaders: [authHeader()],
+ bashBody: () =>
+ `{\n "type": "sms",\n "phone": "+13334445555",\n "token": "123456"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.verifyOtp({
+ phone: '+13334445555',
+ token: '123456',
+ type: 'sms'
+})`
+ },
+ authInvite: {
+ method: "POST",
+ path: "/auth/v1/invite",
+ title: "Invite User",
+ bashHeaders: [`"Authorization: Bearer USER_TOKEN"`],
+ bashBody: () => `{\n "email": "[email protected]"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.admin.inviteUserByEmail('[email protected]')`
+ },
+ authThirdPartyLogin: {
+ method: "GET",
+ path: "/auth/v1/authorize?provider=github",
+ title: "Third Party Login",
+ bashHeaders: [`"Authorization: Bearer USER_TOKEN"`],
+ jsCode: () => `
+let { data, error } = await carbon.auth.signInWithOAuth({
+ provider: 'github'
+})`
+ },
+ authUser: {
+ method: "GET",
+ path: "/auth/v1/user",
+ title: "Get User",
+ jsCode: () => `
+const { data: { user } } = await carbon.auth.getUser()`
+ },
+ authRecover: {
+ method: "POST",
+ path: "/auth/v1/recover",
+ title: "Password Recovery",
+ bashBody: () => `{\n "email": "[email protected]"\n}`,
+ jsCode: () => `
+let { data, error } = await carbon.auth.resetPasswordForEmail(email)`
+ },
+ authUpdate: {
+ method: "PUT",
+ path: "/auth/v1/user",
+ title: "Update User",
+ bashBody: () =>
+ `{\n "email": "[email protected]",\n "password": "new-password",\n "data": {\n "key": "value"\n }\n}`,
+ jsCode: () => `
+const { data, error } = await carbon.auth.updateUser({
+ email: "[email protected]",
+ password: "new-password",
+ data: { hello: 'world' }
+})`
+ },
+ authLogout: {
+ method: "POST",
+ path: "/auth/v1/logout",
+ title: "User logout",
+ bashHeaders: [CONTENT_TYPE_HEADER, `"Authorization: Bearer USER_TOKEN"`],
+ jsCode: () => `
+let { error } = await carbon.auth.signOut()`
+ }
+};
+
+function createAuthSnippet(
+ configKey: keyof typeof AUTH_CONFIGS,
+ endpoint: string,
+ ...args: string[]
+): Snippet {
+ const config = AUTH_CONFIGS[configKey];
+
+ const useCustomHeaders = !!config.bashHeaders;
+ const body = config.bashBody?.(...args);
+
+ const bashCode = useCustomHeaders
+ ? buildCurl({
+ method: config.method,
+ url: `${endpoint}${config.path}`,
+ includeAuth: false,
+ includeContentType: !!body,
+ headers: config.bashHeaders,
+ body
+ })
+ : buildCurl({
+ method: config.method,
+ url: `${endpoint}${config.path}`,
+ includeContentType: !!body,
+ body
+ });
+
+ return defineSnippet(config.title, {
+ bash: createBashSnippet(bashCode),
+ js: createJsSnippet(config.jsCode(...args))
+ });
+}
+
+// ─── CRUD Config + Builders ──────────────────────────────────────────────────
+
+function createRestUrl(
+ endpoint: string,
+ resourceId: string,
+ query?: string
+): string {
+ const base = `${endpoint}/rest/v1/${resourceId}`;
+ return query ? `${base}?${query}` : base;
+}
+
+function createReadSnippet(config: {
+ title: string;
+ resourceId: string;
+ endpoint: string;
+ select: string;
+ range?: string;
+ filter?: string;
+ jsChain: string;
+ apiKey?: string;
+}): Snippet {
+ const {
+ title,
+ resourceId,
+ endpoint,
+ select,
+ range,
+ filter,
+ jsChain,
+ apiKey
+ } = config;
+
+ const queryParts = [];
+ if (filter) queryParts.push(filter);
+ queryParts.push(`select=${select}`);
+ const query = queryParts.join("&");
+
+ return defineSnippet(title, {
+ bash: createBashSnippet(
+ buildCurl({
+ url: createRestUrl(endpoint, resourceId, query),
+ range,
+ apiKey
+ })
+ ),
+ js: createJsSnippet(jsChain)
+ });
+}
+
+function createWriteSnippet(config: {
+ title: string;
+ method: HttpMethod;
+ resourceId: string;
+ endpoint: string;
+ body: string;
+ prefer?: string;
+ query?: string;
+ jsChain: string;
+ apiKey?: string;
+}): Snippet {
+ const {
+ title,
+ method,
+ resourceId,
+ endpoint,
+ body,
+ prefer,
+ query,
+ jsChain,
+ apiKey
+ } = config;
+
+ return defineSnippet(title, {
+ bash: createBashSnippet(
+ buildCurl({
+ method,
+ url: createRestUrl(endpoint, resourceId, query),
+ includeContentType: true,
+ body,
+ prefer,
+ apiKey
+ })
+ ),
+ js: createJsSnippet(jsChain)
+ });
+}
+
const snippets = {
+ // ── Setup ────────────────────────────────────────────────────────────────
+
endpoint: (endpoint: string) => ({
title: "API URL",
- bash: {
- language: "bash",
- code: `${endpoint}`
- },
- js: {
- language: "bash",
- code: `${endpoint}`
- }
+ bash: createBashSnippet(endpoint),
+ js: { language: "bash", code: endpoint }
}),
+
install: () => ({
title: "Install",
bash: null,
- js: {
- language: "bash",
- code: `npm install --save @supabase/supabase-js`
- }
- }),
- env: ({
- appUrl,
- apiKey,
- publicKey,
- apiUrl,
- companyId
- }: {
- appUrl: string;
- apiKey: string;
- publicKey: string;
- apiUrl: string;
- companyId: string;
- }) => ({
- bash: {
- language: "bash",
- code: `
-export CARBON_API_KEY="${apiKey}"
-
-export CARBON_APP_URL="${appUrl}"
-export CARBON_PUBLIC_KEY="${publicKey}"
-export CARBON_API_URL="${apiUrl}"
-export CARBON_COMPANY_ID="${companyId}"
- `
- },
- js: {
- language: "js",
- code: `
-// .env
-CARBON_API_KEY = "${apiKey}"
-
-CARBON_APP_URL = "${appUrl}"
-CARBON_PUBLIC_KEY = "${publicKey}"
-CARBON_API_URL = "${apiUrl}"
-CARBON_COMPANY_ID = "${companyId}"
- `
- }
+ js: createBashSnippet(`npm install --save @supabase/supabase-js`)
}),
- init: (endpoint: string) => ({
- bash: {
- language: "bash",
- code: `# No client library required for Bash.`
- },
- js: {
- language: "js",
- code: `
+
+ env: ({ apiUrl, apiKey }: { apiUrl: string; apiKey: string }) =>
+ defineSnippet(undefined, {
+ bash: createBashSnippet(
+ [
+ `export CARBON_API_URL="${apiUrl}"`,
+ `export CARBON_API_KEY="${apiKey}"`,
+ !isProxied && `export CARBON_PUBLIC_KEY="${PUBLIC_KEY}`
+ ].join("\n")
+ ),
+ js: createJsSnippet(
+ [
+ `// .env`,
+ `CARBON_API_URL = "${apiUrl}"`,
+ `CARBON_API_KEY = "${apiKey}"`,
+ !isProxied && `CARBON_PUBLIC_KEY = "${PUBLIC_KEY}"`
+ ].join("\n")
+ )
+ }),
+
+ init: (endpoint: string) =>
+ defineSnippet(undefined, {
+ bash: createBashSnippet(`# No client library required for Bash.`),
+ js: createJsSnippet(`
import { createClient } from '@supabase/supabase-js'
-const apiKey = process.env.CARBON_API_KEY
const apiUrl = process.env.CARBON_API_URL
-const publicKey = process.env.CARBON_PUBLIC_KEY
+const apiKey = process.env.CARBON_API_KEY
+${!isProxied ? `const publicKey = process.env.CARBON_PUBLIC_KEY` : ""}
-const carbon = createClient(apiUrl, publicKey, {
+const carbon = createClient(apiUrl, ${
+ !isProxied
+ ? `publicKey, {
global: {
headers: {
"carbon-key": apiKey,
},
},
-});`
- },
- python: {
- language: "python",
- code: `
-import os
-from supabase import create_client, Client
-url: str = os.environ.get("CARBON_API_URL")
-key: str = os.environ.get("CARBON_API_KEY")
-supabase: Client = create_client(url, key)
-`
- },
- dart: {
- language: "dart",
- code: `
-const supabaseUrl = '${endpoint}';
-const supabaseKey = String.fromEnvironment('SUPABASE_KEY');
-Future<void> main() async {
- await Supabase.initialize(url: supabaseUrl, anonKey: supabaseKey);
- runApp(MyApp());
}`
- }
- }),
- authKey: (title: string, varName: string, apikey: string) => ({
- bash: {
- language: "bash",
- code: `${apikey}`
- },
- js: {
- language: "js",
- code: `const ${varName} = '${apikey}'`
- }
- }),
- authKeyExample: (
- defaultApiKey: string,
- endpoint: string,
- { keyName, showBearer = true }: { keyName?: string; showBearer?: boolean }
- ) => ({
- title: "Example usage",
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/' \\
--H "apikey: ${defaultApiKey}" ${
- showBearer
- ? `\\
--H "Authorization: Bearer ${defaultApiKey}"`
- : ""
- }
-`
- },
- js: {
- language: "js",
- code: `
-const SUPABASE_URL = "${endpoint}"
-const carbon = createClient(SUPABASE_URL, process.env.${
- keyName || "SUPABASE_KEY"
- });
-`
- }
- }),
- rpcSingle: ({
- rpcName,
- rpcParams,
- endpoint,
- apiKey,
- showBearer = true
- }: {
- rpcName: string;
- rpcParams: any[];
- endpoint: string;
- apiKey: string;
- showBearer: boolean;
- }) => {
- let rpcList = rpcParams.map((x) => `"${x.name}": "value"`).join(", ");
- let noParams = !rpcParams.length;
- let bashParams = noParams ? "" : `\n-d '{ ${rpcList} }' \\`;
- let jsParams = noParams
- ? ""
- : `, {${
- rpcParams.length
- ? rpcParams
- .map((x) => `\n ${x.name}`)
- .join(`, `)
- .concat("\n ")
- : ""
- }}`;
- return {
- title: "Invoke function ",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/rest/v1/rpc/${rpcName}' \\${bashParams}
--H "Content-Type: application/json" \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon
- .rpc('${rpcName}'${jsParams})
-if (error) console.error(error)
-else console.log(data)
-`
- }
- };
- },
- subscribeAll: (listenerName: string, resourceId: string) => ({
- title: "Subscribe to all events",
- bash: {
- language: "bash",
- code: `# Realtime streams are only supported by our client libraries`
- },
- js: {
- language: "js",
- code: `
-const ${listenerName} = carbon.channel('custom-all-channel')
- .on(
- 'postgres_changes',
- { event: '*', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`
- }
- }),
- subscribeInserts: (listenerName: string, resourceId: string) => ({
- title: "Subscribe to inserts",
- bash: {
- language: "bash",
- code: `# Realtime streams are only supported by our client libraries`
- },
- js: {
- language: "js",
- code: `
-const ${listenerName} = carbon.channel('custom-insert-channel')
- .on(
- 'postgres_changes',
- { event: 'INSERT', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`
- }
- }),
- subscribeUpdates: (listenerName: string, resourceId: string) => ({
- title: "Subscribe to updates",
- bash: {
- language: "bash",
- code: `# Realtime streams are only supported by our client libraries`
- },
- js: {
- language: "js",
- code: `
-const ${listenerName} = carbon.channel('custom-update-channel')
- .on(
- 'postgres_changes',
- { event: 'UPDATE', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`
- }
- }),
- subscribeDeletes: (listenerName: string, resourceId: string) => ({
- title: "Subscribe to deletes",
- bash: {
- language: "bash",
- code: `# Realtime streams are only supported by our client libraries`
- },
- js: {
- language: "js",
- code: `
-const ${listenerName} = carbon.channel('custom-delete-channel')
- .on(
- 'postgres_changes',
- { event: 'DELETE', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`
- }
- }),
- subscribeEq: (
- listenerName: string,
- resourceId: string,
- columnName: string,
- value: string
- ) => ({
- title: "Subscribe to specific rows",
- bash: {
- language: "bash",
- code: `# Realtime streams are only supported by our client libraries`
- },
- js: {
- language: "js",
- code: `
-const ${listenerName} = carbon.channel('custom-filter-channel')
- .on(
- 'postgres_changes',
- { event: '*', schema: 'public', table: '${resourceId}', filter: '${columnName}=eq.${value}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`
- }
- }),
- readAll: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Read all rows",
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=*' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"`
- },
- js: {
- language: "js",
- code: `
+ : `apiKey`
+ });`)
+ }),
+ // ── Read (CRUD) ──────────────────────────────────────────────────────────
+
+ readAll: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createReadSnippet({
+ title: "Read all rows",
+ resourceId,
+ endpoint,
+ select: "*",
+ apiKey,
+ jsChain: `
let { data: ${resourceId}, error } = await carbon
.from('${resourceId}')
.select('*')
`
- }
- }),
+ }),
+
readColumns: ({
title = "Read specific columns",
resourceId,
endpoint,
- apiKey,
- columnName = "some_column,other_column"
+ columnName = "some_column,other_column",
+ apiKey
}: {
title?: string;
resourceId: string;
endpoint: string;
- apiKey: string;
columnName?: string;
- }) => ({
- title,
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=${columnName}' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"`
- },
- js: {
- language: "js",
- code: `
+ apiKey?: string;
+ }) =>
+ createReadSnippet({
+ title,
+ resourceId,
+ endpoint,
+ select: columnName,
+ apiKey,
+ jsChain: `
let { data: ${resourceId}, error } = await carbon
.from('${resourceId}')
.select('${columnName}')
`
- }
- }),
- readForeignTables: (
- resourceId: string,
- endpoint: string,
- apiKey: string
- ) => ({
- title: "Read referenced tables",
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=some_column,other_table(foreign_key)' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ readForeignTables: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createReadSnippet({
+ title: "Read referenced tables",
+ resourceId,
+ endpoint,
+ select: "some_column,other_table(foreign_key)",
+ apiKey,
+ jsChain: `
let { data: ${resourceId}, error } = await carbon
.from('${resourceId}')
.select(\`
@@ -365,45 +529,34 @@ let { data: ${resourceId}, error } = await carbon
)
\`)
`
- }
- }),
- readRange: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "With pagination",
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=*' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Range: 0-9"
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ readRange: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createReadSnippet({
+ title: "With pagination",
+ resourceId,
+ endpoint,
+ select: "*",
+ range: "0-9",
+ apiKey,
+ jsChain: `
let { data: ${resourceId}, error } = await carbon
.from('${resourceId}')
.select('*')
.range(0, 9)
`
- }
- }),
- readFilters: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "With filtering",
- bash: {
- language: "bash",
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?id=eq.1&select=*' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Range: 0-9"
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ readFilters: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createReadSnippet({
+ title: "With filtering",
+ resourceId,
+ endpoint,
+ select: "*",
+ filter: "id=eq.1",
+ range: "0-9",
+ apiKey,
+ jsChain: `
let { data: ${resourceId}, error } = await carbon
.from('${resourceId}')
.select("*")
@@ -422,25 +575,20 @@ let { data: ${resourceId}, error } = await carbon
.contains('array_column', ['array', 'contains'])
.containedBy('array_column', ['contained', 'by'])
`
- }
- }),
- insertSingle: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Insert a row",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--H "Prefer: return=minimal" \\
--d '{ "some_column": "someValue", "other_column": "otherValue" }'
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ // ── Write (CRUD) ─────────────────────────────────────────────────────────
+
+ insertSingle: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createWriteSnippet({
+ title: "Insert a row",
+ method: "POST",
+ resourceId,
+ endpoint,
+ prefer: "return=minimal",
+ body: `{ "some_column": "someValue", "other_column": "otherValue" }`,
+ apiKey,
+ jsChain: `
const { data, error } = await carbon
.from('${resourceId}')
.insert([
@@ -448,24 +596,17 @@ const { data, error } = await carbon
])
.select()
`
- }
- }),
- insertMany: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Insert many rows",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '[{ "some_column": "someValue" }, { "other_column": "otherValue" }]'
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ insertMany: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createWriteSnippet({
+ title: "Insert many rows",
+ method: "POST",
+ resourceId,
+ endpoint,
+ body: `[{ "some_column": "someValue" }, { "other_column": "otherValue" }]`,
+ apiKey,
+ jsChain: `
const { data, error } = await carbon
.from('${resourceId}')
.insert([
@@ -474,360 +615,140 @@ const { data, error } = await carbon
])
.select()
`
- }
- }),
- upsert: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Upsert matching rows",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--H "Prefer: resolution=merge-duplicates" \\
--d '{ "some_column": "someValue", "other_column": "otherValue" }'
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ upsert: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createWriteSnippet({
+ title: "Upsert matching rows",
+ method: "POST",
+ resourceId,
+ endpoint,
+ prefer: "resolution=merge-duplicates",
+ body: `{ "some_column": "someValue", "other_column": "otherValue" }`,
+ apiKey,
+ jsChain: `
const { data, error } = await carbon
.from('${resourceId}')
.upsert({ some_column: 'someValue' })
.select()
`
- }
- }),
- update: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Update matching rows",
- bash: {
- language: "bash",
- code: `
-curl -X PATCH '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--H "Prefer: return=minimal" \\
--d '{ "other_column": "otherValue" }'
-`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ update: (resourceId: string, endpoint: string, apiKey?: string) =>
+ createWriteSnippet({
+ title: "Update matching rows",
+ method: "PATCH",
+ resourceId,
+ endpoint,
+ prefer: "return=minimal",
+ query: "some_column=eq.someValue",
+ body: `{ "other_column": "otherValue" }`,
+ apiKey,
+ jsChain: `
const { data, error } = await carbon
.from('${resourceId}')
.update({ other_column: 'otherValue' })
.eq('some_column', 'someValue')
.select()
`
- }
- }),
- delete: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: "Delete matching rows",
- bash: {
- language: "bash",
- code: `
-curl -X DELETE '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"`
- },
- js: {
- language: "js",
- code: `
+ }),
+
+ delete: (resourceId: string, endpoint: string, apiKey?: string) =>
+ defineSnippet("Delete matching rows", {
+ bash: createBashSnippet(
+ buildCurl({
+ method: "DELETE",
+ url: createRestUrl(endpoint, resourceId, "some_column=eq.someValue"),
+ apiKey
+ })
+ ),
+ js: createJsSnippet(`
const { error } = await carbon
.from('${resourceId}')
.delete()
.eq('some_column', 'someValue')
-`
- }
- }),
- authSignup: (endpoint: string, apiKey: string, randomPassword: string) => ({
- title: "User signup",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/signup' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "${randomPassword}"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signUp({
- email: '[email protected]',
- password: '${randomPassword}'
-})
-`
- }
- }),
- authLogin: (endpoint: string, apiKey: string, randomPassword: string) => ({
- title: "User login",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/token?grant_type=password' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "${randomPassword}"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signInWithPassword({
- email: '[email protected]',
- password: '${randomPassword}'
-})
-`
- }
- }),
- authMagicLink: (endpoint: string, apiKey: string) => ({
- title: "User login",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/magiclink' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signInWithOtp({
-})
-`
- }
- }),
- authPhoneSignUp: (endpoint: string, apiKey: string) => ({
- title: "Phone Signup",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/signup' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "phone": "+13334445555",
- "password": "some-password"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signUp({
- phone: '+13334445555',
- password: 'some-password'
-})
-`
- }
- }),
- authMobileOTPLogin: (endpoint: string, apiKey: string) => ({
- title: "Phone Login",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/otp' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "phone": "+13334445555"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signInWithOtp({
- phone: '+13334445555'
-})
-`
- }
- }),
- authMobileOTPVerify: (endpoint: string, apiKey: string) => ({
- title: "Verify Pin",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/verify' \\
--H "carbon-key: <your_api_key_here>" \\
--H "Content-Type: application/json" \\
--d '{
- "type": "sms",
- "phone": "+13334445555",
- "token": "123456"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.verifyOtp({
- phone: '+13334445555',
- token: '123456',
- type: 'sms'
-})
-`
- }
- }),
- authInvite: (endpoint: string, apiKey: string) => ({
- title: "Invite User",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/invite' \\
--H "carbon-key: <your_api_key_here>" \\
--H "Authorization: Bearer USER_TOKEN" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.admin.inviteUserByEmail('[email protected]')
-`
- }
- }),
- authThirdPartyLogin: (endpoint: string, apiKey: string) => ({
- title: "Third Party Login",
- bash: {
- language: "bash",
- code: `
-curl -X GET '${endpoint}/auth/v1/authorize?provider=github' \\
--H "carbon-key: <your_api_key_here>" \\
--H "Authorization: Bearer USER_TOKEN" \\
--H "Content-Type: application/json"
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.signInWithOAuth({
- provider: 'github'
-})
-`
- }
- }),
- authUser: (endpoint: string, apiKey: string) => ({
- title: "Get User",
- bash: {
- language: "bash",
- code: `
-curl -X GET '${endpoint}/auth/v1/user' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY"
-`
- },
- js: {
- language: "js",
- code: `
-const { data: { user } } = await carbon.auth.getUser()
-`
- }
- }),
- authRecover: (endpoint: string, apiKey: string) => ({
- title: "Password Recovery",
- bash: {
- language: "bash",
- code: `
- curl -X POST '${endpoint}/auth/v1/recover' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`
- },
- js: {
- language: "js",
- code: `
-let { data, error } = await carbon.auth.resetPasswordForEmail(email)
-`
- }
- }),
- authUpdate: (endpoint: string, apiKey: string) => ({
- title: "Update User",
- bash: {
- language: "bash",
- code: `
- curl -X PUT '${endpoint}/auth/v1/user' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "new-password",
- "data": {
- "key": "value"
- }
-}'
-`
- },
- js: {
- language: "js",
- code: `
-const { data, error } = await carbon.auth.updateUser({
- email: "[email protected]",
- password: "new-password",
- data: { hello: 'world' }
-})
-`
- }
- }),
- authLogout: (endpoint: string, apiKey: string) => ({
- title: "User logout",
- bash: {
- language: "bash",
- code: `
-curl -X POST '${endpoint}/auth/v1/logout' \\
--H "carbon-key: <your_api_key_here>" \\
--H "apiKey: CARBON_PUBLIC_KEY" \\
--H "Authorization: Bearer CARBON_PUBLIC_KEY" \\
--H "Content-Type: application/json" \\
--H "Authorization: Bearer USER_TOKEN"
-`
- },
- js: {
- language: "js",
- code: `
-let { error } = await carbon.auth.signOut()
-`
- }
- })
+`)
+ }),
+
+ // ── Subscriptions ────────────────────────────────────────────────────────
+
+ subscribeAll: (listenerName: string, resourceId: string) =>
+ createSubscriptionSnippet(
+ SUBSCRIPTION_CONFIGS.subscribeAll,
+ listenerName,
+ resourceId
+ ),
+
+ subscribeInserts: (listenerName: string, resourceId: string) =>
+ createSubscriptionSnippet(
+ SUBSCRIPTION_CONFIGS.subscribeInserts,
+ listenerName,
+ resourceId
+ ),
+
+ subscribeUpdates: (listenerName: string, resourceId: string) =>
+ createSubscriptionSnippet(
+ SUBSCRIPTION_CONFIGS.subscribeUpdates,
+ listenerName,
+ resourceId
+ ),
+
+ subscribeDeletes: (listenerName: string, resourceId: string) =>
+ createSubscriptionSnippet(
+ SUBSCRIPTION_CONFIGS.subscribeDeletes,
+ listenerName,
+ resourceId
+ ),
+
+ subscribeEq: (
+ listenerName: string,
+ resourceId: string,
+ columnName: string,
+ value: string
+ ) =>
+ createSubscriptionSnippet(
+ {
+ event: "*",
+ channel: "custom-filter-channel",
+ title: "Subscribe to specific rows"
+ },
+ listenerName,
+ resourceId,
+ `${columnName}=eq.${value}`
+ ),
+
+ // ── Auth ─────────────────────────────────────────────────────────────────
+
+ authSignup: (endpoint: string, apiKey: string, randomPassword: string) =>
+ createAuthSnippet("authSignup", endpoint, apiKey, randomPassword),
+
+ authLogin: (endpoint: string, apiKey: string, randomPassword: string) =>
+ createAuthSnippet("authLogin", endpoint, apiKey, randomPassword),
+
+ authMagicLink: (endpoint: string) =>
+ createAuthSnippet("authMagicLink", endpoint),
+
+ authPhoneSignUp: (endpoint: string) =>
+ createAuthSnippet("authPhoneSignUp", endpoint),
+
+ authMobileOTPLogin: (endpoint: string) =>
+ createAuthSnippet("authMobileOTPLogin", endpoint),
+
+ authMobileOTPVerify: (endpoint: string) =>
+ createAuthSnippet("authMobileOTPVerify", endpoint),
+
+ authInvite: (endpoint: string) => createAuthSnippet("authInvite", endpoint),
+
+ authThirdPartyLogin: (endpoint: string) =>
+ createAuthSnippet("authThirdPartyLogin", endpoint),
+
+ authUser: (endpoint: string) => createAuthSnippet("authUser", endpoint),
+
+ authRecover: (endpoint: string) => createAuthSnippet("authRecover", endpoint),
+
+ authUpdate: (endpoint: string) => createAuthSnippet("authUpdate", endpoint),
+
+ authLogout: (endpoint: string) => createAuthSnippet("authLogout", endpoint)
};
export default snippets;
diff --git a/apps/erp/app/modules/api/ui/TableDocs.tsx b/apps/erp/app/modules/api/ui/TableDocs.tsx
index 7cb014e9dd..2848341f32 100644
--- a/apps/erp/app/modules/api/ui/TableDocs.tsx
+++ b/apps/erp/app/modules/api/ui/TableDocs.tsx
@@ -1,4 +1,3 @@
-import { getBrowserEnv } from "@carbon/auth";
import { cn } from "@carbon/react";
import { LuTable2 } from "react-icons/lu";
import { useSwaggerDocs } from "~/hooks/useSwaggerDocs";
@@ -6,16 +5,20 @@ import type { ValidLang } from "~/modules/api";
import { CodeSnippet, Snippets } from "~/modules/api";
import { snakeToCamel } from "~/utils/string";
-const { SUPABASE_ANON_KEY } = getBrowserEnv();
-
type TableDocsProps = {
endpoint: string;
selectedLang: ValidLang;
resourceId: string;
+ apiKey?: string;
};
const functionPath = "rpc/";
-const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
+const TableDocs = ({
+ endpoint,
+ selectedLang,
+ resourceId,
+ apiKey
+}: TableDocsProps) => {
const swaggerDocsSchema = useSwaggerDocs();
const { resources } = Object.entries(swaggerDocsSchema?.paths || {}).reduce<{
resources: Record<
@@ -64,7 +67,12 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
})
);
- if (!swaggerDocsSchema?.paths || !swaggerDocsSchema?.definitions) return null;
+ if (
+ !swaggerDocsSchema?.paths ||
+ !swaggerDocsSchema?.definitions ||
+ !swaggerDocsSchema
+ )
+ return null;
return (
<>
@@ -101,9 +109,9 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
snippet={Snippets.readColumns({
title: `Select ${x.id}`,
resourceId,
- endpoint: endpoint,
- apiKey: SUPABASE_ANON_KEY,
- columnName: x.id
+ endpoint,
+ columnName: x.id,
+ apiKey
})}
/>
</div>
@@ -133,18 +141,14 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.readAll(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.readAll(resourceId, endpoint, apiKey)}
/>
<CodeSnippet
selectedLang={selectedLang}
snippet={Snippets.readColumns({
resourceId,
- endpoint: endpoint,
- apiKey: SUPABASE_ANON_KEY
+ endpoint,
+ apiKey
})}
/>
<CodeSnippet
@@ -152,16 +156,12 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
snippet={Snippets.readForeignTables(
resourceId,
endpoint,
- SUPABASE_ANON_KEY
+ apiKey
)}
/>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.readRange(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.readRange(resourceId, endpoint, apiKey)}
/>
</article>
</div>
@@ -182,11 +182,7 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.readFilters(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.readFilters(resourceId, endpoint, apiKey)}
/>
</article>
</div>
@@ -218,27 +214,15 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.insertSingle(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.insertSingle(resourceId, endpoint, apiKey)}
/>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.insertMany(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.insertMany(resourceId, endpoint, apiKey)}
/>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.upsert(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.upsert(resourceId, endpoint, apiKey)}
/>
</article>
</div>
@@ -272,11 +256,7 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.update(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.update(resourceId, endpoint, apiKey)}
/>
</article>
</div>
@@ -305,11 +285,7 @@ const TableDocs = ({ endpoint, selectedLang, resourceId }: TableDocsProps) => {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.delete(
- resourceId,
- endpoint,
- SUPABASE_ANON_KEY
- )}
+ snippet={Snippets.delete(resourceId, endpoint, apiKey)}
/>
</article>
</div>
diff --git a/apps/erp/app/modules/api/ui/index.ts b/apps/erp/app/modules/api/ui/index.ts
index f5bd8ead5c..8316e114cc 100644
--- a/apps/erp/app/modules/api/ui/index.ts
+++ b/apps/erp/app/modules/api/ui/index.ts
@@ -1,8 +1,16 @@
+import { ApiDocsProvider, useApiDocsConfig } from "./ApiDocsContext";
import CodeSnippet from "./CodeSnippet";
import Snippets from "./Snippets";
import TableDocs from "./TableDocs";
import type { ValidLang } from "./useSelectedLang";
import { useSelectedLang } from "./useSelectedLang";
-export { CodeSnippet, Snippets, TableDocs, useSelectedLang };
+export {
+ ApiDocsProvider,
+ CodeSnippet,
+ Snippets,
+ TableDocs,
+ useApiDocsConfig,
+ useSelectedLang
+};
export type { ValidLang };
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 5ee05ea0f9..a6f89ba2a8 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -25,9 +25,30 @@ export const purchasePriceUpdateTimingTypes = [
"Purchase Order Finalize"
] as const;
+/** All permission modules with their available CRUD actions */
+export const apiKeyPermissionModules = {
+ accounting: ["view", "create", "update"],
+ documents: ["view", "create", "update", "delete"],
+ inventory: ["view", "create", "update", "delete"],
+ invoicing: ["view", "create", "update", "delete"],
+ parts: ["view", "create", "update", "delete"],
+ people: ["view", "create", "update", "delete"],
+ production: ["view", "create", "update", "delete"],
+ purchasing: ["view", "create", "update", "delete"],
+ quality: ["view", "create", "update", "delete"],
+ resources: ["view", "create", "update", "delete"],
+ sales: ["view", "create", "update", "delete"],
+ settings: ["view", "create", "update", "delete"],
+ users: ["view", "create", "update", "delete"]
+} as const;
+
+export type ApiKeyPermissionModule = keyof typeof apiKeyPermissionModules;
+
export const apiKeyValidator = z.object({
id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" })
+ name: z.string().min(1, { message: "Name is required" }),
+ scopes: zfd.text(z.string().optional()),
+ expiresAt: zfd.text(z.string().optional())
});
const company = {
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 577725e58a..a7b0fc7d4e 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -1,9 +1,7 @@
import { SUPABASE_URL } from "@carbon/auth";
-
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import { FunctionRegion } from "@supabase/supabase-js";
-import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
@@ -49,9 +47,7 @@ export async function getApiKeys(
) {
let query = client
.from("apiKey")
- .select("*", {
- count: "exact"
- })
+ .select("*", { count: "exact" })
.eq("companyId", companyId);
if (args?.search) {
@@ -449,23 +445,74 @@ export async function updateMetricSettings(
export async function upsertApiKey(
client: SupabaseClient<Database>,
apiKey:
- | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {
+ | (Omit<z.infer<typeof apiKeyValidator>, "id" | "scopes" | "expiresAt"> & {
createdBy: string;
companyId: string;
+ scopes: Record<string, string[]>;
+ expiresAt?: string;
+ rawKey: string;
+ keyHash: string;
+ keyPreview: string;
})
- | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {
+ | (Omit<z.infer<typeof apiKeyValidator>, "id" | "scopes" | "expiresAt"> & {
id: string;
+ scopes: Record<string, string[]>;
+ expiresAt?: string;
})
) {
if ("createdBy" in apiKey) {
- const key = `crbn_${nanoid()}`;
- return client
+ // Create: store the hash, return the raw key (caller generates both)
+ // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
+ const {
+ scopes,
+ expiresAt,
+ rawKey,
+ keyHash,
+ rateLimit: _rl,
+ rateLimitWindow: _rlw,
+ ...rest
+ } = apiKey as any;
+
+ const result = await client
.from("apiKey")
- .insert({ ...apiKey, key })
- .select("key")
+ .insert(
+ sanitize({
+ ...rest,
+ keyHash,
+ scopes: scopes as any,
+ expiresAt: expiresAt || null
+ }) as any
+ )
+ .select("id")
.single();
+
+ if (result.error) {
+ return { data: null, error: result.error };
+ }
+
+ // Return the raw key (shown to user once, never stored)
+ return { data: { key: rawKey, id: result.data.id }, error: null };
}
- return client.from("apiKey").update(sanitize(apiKey)).eq("id", apiKey.id);
+
+ // Update: update name, scopes, expiration (never the key itself)
+ // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
+ const {
+ scopes,
+ expiresAt,
+ rateLimit: _rl,
+ rateLimitWindow: _rlw,
+ ...rest
+ } = apiKey as any;
+ return client
+ .from("apiKey")
+ .update(
+ sanitize({
+ ...rest,
+ scopes: scopes as any,
+ expiresAt: expiresAt || null
+ }) as any
+ )
+ .eq("id", apiKey.id);
}
export async function updateDigitalQuoteSetting(
diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx
index a3758fda85..a08bd3ec4c 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx
@@ -1,4 +1,4 @@
-import { ValidatedForm } from "@carbon/form";
+import { DateTimePicker, ValidatedForm } from "@carbon/form";
import {
Alert,
AlertTitle,
@@ -16,22 +16,35 @@ import {
ModalTitle,
VStack
} from "@carbon/react";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { LuCheck, LuClipboard, LuLock } from "react-icons/lu";
import { useFetcher } from "react-router";
import type { z } from "zod";
import { Hidden, Input, Submit } from "~/components/Form";
+import PermissionMatrix from "~/components/PermissionMatrix";
import { usePermissions } from "~/hooks";
-import { apiKeyValidator } from "~/modules/settings";
+import {
+ fromApiKeyScopes,
+ toApiKeyScopes,
+ usePermissionMatrix
+} from "~/hooks/usePermissionMatrix";
+import { apiKeyPermissionModules, apiKeyValidator } from "~/modules/settings";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
type ApiKeyFormProps = {
initialValues: z.infer<typeof apiKeyValidator>;
+ companyId?: string;
+ existingScopes?: Record<string, string[]> | null;
onClose: () => void;
};
-const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {
+const ApiKeyForm = ({
+ initialValues,
+ companyId,
+ existingScopes,
+ onClose
+}: ApiKeyFormProps) => {
const permissions = usePermissions();
const fetcher = useFetcher<{ key: string }>();
@@ -40,6 +53,20 @@ const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {
const [key, setKey] = useState<string | null>(null);
+ const initialScopeState = useMemo(
+ () =>
+ isEditing
+ ? fromApiKeyScopes(existingScopes, apiKeyPermissionModules)
+ : fromApiKeyScopes(null, apiKeyPermissionModules),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
+ );
+
+ const matrix = usePermissionMatrix({
+ modules: apiKeyPermissionModules,
+ initialState: initialScopeState
+ });
+
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
if (fetcher.data?.key) {
@@ -47,6 +74,11 @@ const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {
}
}, [fetcher.data, fetcher.state, onClose]);
+ // Serialize scopes to JSONB format for form submission
+ const scopesJsonb = companyId
+ ? JSON.stringify(toApiKeyScopes(matrix.permissions, companyId))
+ : "{}";
+
return (
<>
<Modal
@@ -55,7 +87,7 @@ const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {
if (!open) onClose?.();
}}
>
- <ModalContent>
+ <ModalContent size="xlarge">
<ValidatedForm
validator={apiKeyValidator}
method="post"
@@ -69,10 +101,18 @@ const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {
<ModalHeader>
<ModalTitle>{isEditing ? "Edit" : "New"} API Key</ModalTitle>
</ModalHeader>
- <ModalBody>
+ <ModalBody className="max-h-[70dvh] overflow-y-auto">
<Hidden name="id" />
+ <Hidden name="scopes" value={scopesJsonb} />
<VStack spacing={4}>
<Input name="name" label="Name" />
+
+ <DateTimePicker
+ name="expiresAt"
+ label="Expires At (optional)"
+ />
+
+ <PermissionMatrix matrix={matrix} />
</VStack>
</ModalBody>
<ModalFooter>
diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
index 6cd3767307..5dad35ca92 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
@@ -5,8 +5,10 @@ import { memo, useCallback, useMemo } from "react";
import {
LuCalendar,
LuCode,
+ LuGauge,
LuKey,
LuPencil,
+ LuShield,
LuTag,
LuTrash,
LuUser
@@ -23,6 +25,20 @@ type ApiKeysTableProps = {
count: number;
};
+function getScopeCount(scopes: Record<string, string[]> | null): number {
+ if (!scopes) return 0;
+ return Object.keys(scopes).length;
+}
+
+function formatRateLimit(limit: number, window: string): string {
+ const windowLabels: Record<string, string> = {
+ "1m": "/min",
+ "1h": "/hr",
+ "1d": "/day"
+ };
+ return `${limit}${windowLabels[window] ?? "/hr"}`;
+}
+
const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -42,21 +58,61 @@ const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {
}
},
{
- accessorKey: "key",
+ id: "keyPreview",
header: "Key",
- cell: (item) => (
- <Badge variant="secondary">{item.getValue<string>()}</Badge>
- ),
+ cell: ({ row }) => {
+ const preview = (row.original as any).keyPreview as string | null;
+ return (
+ <span className="font-mono text-sm text-muted-foreground">
+ {preview ? `crbn_•••${preview}` : "crbn_•••••"}
+ </span>
+ );
+ },
meta: {
icon: <LuKey />
}
},
+ {
+ id: "scopes",
+ header: "Scopes",
+ cell: ({ row }) => {
+ const scopes = (row.original as any).scopes as Record<
+ string,
+ string[]
+ > | null;
+ const scopeCount = getScopeCount(scopes);
+ return (
+ <Badge variant="secondary">
+ {scopeCount === 0 ? "No Access" : `${scopeCount} permissions`}
+ </Badge>
+ );
+ },
+ meta: {
+ icon: <LuShield />
+ }
+ },
+ {
+ id: "rateLimit",
+ header: "Rate Limit",
+ cell: ({ row }) => {
+ const limit = (row.original as any).rateLimit as number;
+ const window = (row.original as any).rateLimitWindow as string;
+ return (
+ <span className="text-sm text-muted-foreground">
+ {formatRateLimit(limit ?? 60, window ?? "1m")}
+ </span>
+ );
+ },
+ meta: {
+ icon: <LuGauge />
+ }
+ },
{
id: "createdBy",
header: "Created By",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.createdBy} />
- ),
+ cell: ({ row }) => {
+ return <EmployeeAvatar employeeId={row.original.createdBy} />;
+ },
meta: {
icon: <LuUser />,
filter: {
@@ -68,6 +124,24 @@ const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {
}
}
},
+ {
+ id: "expiresAt",
+ header: "Expires",
+ cell: ({ row }) => {
+ const expiresAt = (row.original as any).expiresAt as string | null;
+ if (!expiresAt)
+ return <span className="text-muted-foreground">Never</span>;
+ const isExpired = new Date(expiresAt) < new Date();
+ return (
+ <Badge variant={isExpired ? "destructive" : "secondary"}>
+ {isExpired ? "Expired" : formatDate(expiresAt)}
+ </Badge>
+ );
+ },
+ meta: {
+ icon: <LuCalendar />
+ }
+ },
{
accessorKey: "createdAt",
header: "Created At",
diff --git a/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx b/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx
index f0653aa0b8..4fa4d6fd2f 100644
--- a/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx
+++ b/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx
@@ -100,14 +100,14 @@ const CreateCustomerModal = () => {
</>
)}
</VStack>
- <ModalFooter>
- <HStack>
- <Submit isLoading={formFetcher.state !== "idle"}>
- Create User
- </Submit>
- </HStack>
- </ModalFooter>
</ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>
+ Create User
+ </Submit>
+ </HStack>
+ </ModalFooter>
</ValidatedForm>
</ModalContent>
</Modal>
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
index 5aa5fba2b9..1f3463db4e 100644
--- a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
@@ -1,23 +1,28 @@
import { ValidatedForm } from "@carbon/form";
import {
Button,
- Drawer,
- DrawerBody,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerTitle,
HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
VStack
} from "@carbon/react";
-import { useState } from "react";
+import { useMemo } from "react";
import { useNavigate } from "react-router";
import type { z } from "zod";
import { Hidden, Input, Submit } from "~/components/Form";
+import PermissionMatrix from "~/components/PermissionMatrix";
import { usePermissions } from "~/hooks";
+import {
+ fromEmployeeTypePermissions,
+ toEmployeeTypePermissions,
+ usePermissionMatrix
+} from "~/hooks/usePermissionMatrix";
import type { CompanyPermission } from "~/modules/users";
import { employeeTypeValidator } from "~/modules/users";
-import PermissionCheckboxes from "~/modules/users/ui/components/Permission";
import { path } from "~/utils/path";
type EmployeeTypeFormProps = {
@@ -37,30 +42,35 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
const navigate = useNavigate();
const onClose = () => navigate(-1);
- const [permissions, setPermissions] = useState(initialValues.permissions);
- const updatePermissions = (module: string, permission: CompanyPermission) => {
- setPermissions((prevPermissions) => ({
- ...prevPermissions,
- [module]: {
- name: prevPermissions[module].name,
- permission
- }
- }));
- };
+ const { state: initialState, modules } = useMemo(
+ () => fromEmployeeTypePermissions(initialValues.permissions),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
+ );
+
+ const matrix = usePermissionMatrix({
+ modules,
+ initialState
+ });
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
? !userPermissions.can("update", "users")
: !userPermissions.can("create", "users");
+ // Serialize permissions to the format expected by the action
+ const permissionsData = JSON.stringify(
+ Object.values(toEmployeeTypePermissions(matrix.permissions))
+ );
+
return (
- <Drawer
+ <Modal
open
onOpenChange={(open) => {
if (!open) onClose();
}}
>
- <DrawerContent>
+ <ModalContent size="xlarge">
<ValidatedForm
validator={employeeTypeValidator}
method="post"
@@ -72,49 +82,30 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
defaultValues={initialValues}
className="flex flex-col h-full"
>
- <DrawerHeader>
- <DrawerTitle>
- {isEditing ? "Edit" : "New"} Employee Type
- </DrawerTitle>
- </DrawerHeader>
- <DrawerBody>
+ <ModalHeader>
+ <ModalTitle>{isEditing ? "Edit" : "New"} Employee Type</ModalTitle>
+ </ModalHeader>
+ <ModalBody className="max-h-[70dvh] overflow-y-auto">
<Hidden name="id" />
<VStack spacing={4}>
<Input name="name" label="Employee Type" />
- <Hidden
- name="data"
- value={JSON.stringify(Object.values(permissions))}
- />
- </VStack>
- <VStack>
- <label className="block text-sm font-medium leading-none">
- Default Permissions
- </label>
- <VStack spacing={8}>
- {Object.entries(permissions)
- .sort((a, b) => a[0].localeCompare(b[0]))
- .map(([module, data], index) => (
- <PermissionCheckboxes
- key={index}
- module={module}
- permissions={data.permission}
- updatePermissions={updatePermissions}
- />
- ))}
- </VStack>
+ <Hidden name="data" value={permissionsData} />
</VStack>
- </DrawerBody>
- <DrawerFooter>
+ <div className="mt-4">
+ <PermissionMatrix matrix={matrix} label="Default Permissions" />
+ </div>
+ </ModalBody>
+ <ModalFooter>
<HStack>
<Submit isDisabled={isDisabled}>Save</Submit>
<Button size="md" variant="solid" onClick={onClose}>
Cancel
</Button>
</HStack>
- </DrawerFooter>
+ </ModalFooter>
</ValidatedForm>
- </DrawerContent>
- </Drawer>
+ </ModalContent>
+ </Modal>
);
};
diff --git a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
index 5cd04d43bf..296dc07c84 100644
--- a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
@@ -11,13 +11,18 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo } from "react";
import { useFetcher } from "react-router";
import { Employees, Hidden, Radios, Submit } from "~/components/Form";
+import PermissionMatrix from "~/components/PermissionMatrix";
+import {
+ fromEmployeeTypePermissions,
+ toCompanyPermissions,
+ usePermissionMatrix
+} from "~/hooks/usePermissionMatrix";
import type { CompanyPermission } from "~/modules/users";
import { bulkPermissionsValidator } from "~/modules/users";
import { path } from "~/utils/path";
-import PermissionCheckboxes from "../components/Permission";
type BulkEditPermissionsProps = {
userIds: string[];
@@ -30,17 +35,6 @@ const BulkEditPermissions = ({
isOpen,
onClose
}: BulkEditPermissionsProps) => {
- const [permissions, setPermissions] = useState<
- Record<string, CompanyPermission>
- >({});
-
- const updatePermissions = (module: string, permission: CompanyPermission) => {
- setPermissions((prevPermissions) => ({
- ...prevPermissions,
- [module]: permission
- }));
- };
-
const emptyPermissionsFetcher = useFetcher<{
permissions: Record<
string,
@@ -55,18 +49,38 @@ const BulkEditPermissions = ({
emptyPermissionsFetcher.load(path.to.api.emptyPermissions);
});
+ const { state: initialState, modules } = useMemo(() => {
+ if (emptyPermissionsFetcher.data) {
+ return fromEmployeeTypePermissions(
+ emptyPermissionsFetcher.data.permissions
+ );
+ }
+ return { state: {}, modules: {} };
+ }, [emptyPermissionsFetcher.data]);
+
+ const matrix = usePermissionMatrix({
+ modules,
+ initialState
+ });
+
+ // When new empty permissions arrive, reset the matrix state
useEffect(() => {
if (emptyPermissionsFetcher.data) {
- let emptyPermissions: Record<string, CompanyPermission> = {};
- Object.entries(emptyPermissionsFetcher.data.permissions).forEach(
- ([module, data]) => {
- emptyPermissions[module] = data.permission;
- }
+ const { state } = fromEmployeeTypePermissions(
+ emptyPermissionsFetcher.data.permissions
);
- setPermissions(emptyPermissions);
+ matrix.setPermissions(state);
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [emptyPermissionsFetcher.data]);
+ // Serialize permissions to the format expected by the action
+ const permissionsData = JSON.stringify(
+ toCompanyPermissions(matrix.permissions)
+ );
+
+ const hasModules = Object.keys(modules).length > 0;
+
return (
<Drawer
onOpenChange={(open) => {
@@ -111,22 +125,8 @@ const BulkEditPermissions = ({
label="Users to Update"
/>
- <label className="block text-sm font-medium leading-none">
- Permissions
- </label>
- <VStack spacing={8}>
- {Object.entries(permissions)
- .sort((a, b) => a[0].localeCompare(b[0]))
- .map(([module, data], index) => (
- <PermissionCheckboxes
- key={index}
- module={module}
- permissions={data}
- updatePermissions={updatePermissions}
- />
- ))}
- </VStack>
- <Hidden name="data" value={JSON.stringify(permissions)} />
+ {hasModules && <PermissionMatrix matrix={matrix} />}
+ <Hidden name="data" value={permissionsData} />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
index d97eb8c978..2081e04f6c 100644
--- a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
@@ -78,12 +78,12 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
/>
<Location name="locationId" label="Location" />
</VStack>
- <ModalFooter>
- <HStack>
- <Submit isLoading={formFetcher.state !== "idle"}>Invite</Submit>
- </HStack>
- </ModalFooter>
</ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>Invite</Submit>
+ </HStack>
+ </ModalFooter>
</ValidatedForm>
</ModalContent>
</Modal>
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx
index 1039b21deb..9e4f4c0866 100644
--- a/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx
@@ -1,22 +1,27 @@
import { ValidatedForm } from "@carbon/form";
import {
Button,
- Drawer,
- DrawerBody,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerTitle,
HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
VStack
} from "@carbon/react";
-import { useState } from "react";
+import { useMemo } from "react";
import { useNavigate } from "react-router";
import type { z } from "zod";
import { Hidden, Select, Submit } from "~/components/Form";
+import PermissionMatrix from "~/components/PermissionMatrix";
+import {
+ fromCompanyPermissions,
+ toCompanyPermissions,
+ usePermissionMatrix
+} from "~/hooks/usePermissionMatrix";
import type { CompanyPermission } from "~/modules/users";
import { employeeValidator } from "~/modules/users";
-import PermissionCheckboxes from "~/modules/users/ui/components/Permission";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
@@ -42,22 +47,30 @@ const EmployeePermissionsForm = ({
label: et.name
})) ?? [];
- const [permissions, setPermissions] = useState(initialValues.permissions);
- const updatePermissions = (module: string, permission: CompanyPermission) => {
- setPermissions((prevPermissions) => ({
- ...prevPermissions,
- [module]: permission
- }));
- };
+ const { state: initialState, modules } = useMemo(
+ () => fromCompanyPermissions(initialValues.permissions),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
+ );
+
+ const matrix = usePermissionMatrix({
+ modules,
+ initialState
+ });
+
+ // Serialize permissions to the format expected by the action
+ const permissionsData = JSON.stringify(
+ toCompanyPermissions(matrix.permissions)
+ );
return (
- <Drawer
+ <Modal
open
onOpenChange={(open) => {
if (!open) onClose();
}}
>
- <DrawerContent>
+ <ModalContent size="xlarge">
<ValidatedForm
validator={employeeValidator}
method="post"
@@ -65,10 +78,10 @@ const EmployeePermissionsForm = ({
defaultValues={initialValues}
className="flex flex-col h-full"
>
- <DrawerHeader>
- <DrawerTitle>{name}</DrawerTitle>
- </DrawerHeader>
- <DrawerBody>
+ <ModalHeader>
+ <ModalTitle>{name}</ModalTitle>
+ </ModalHeader>
+ <ModalBody className="max-h-[70dvh] overflow-y-auto">
<VStack spacing={4}>
<Select
name="employeeType"
@@ -76,36 +89,22 @@ const EmployeePermissionsForm = ({
options={employeeTypeOptions}
placeholder="Select Employee Type"
/>
- <label className="block text-sm font-medium leading-none">
- Permissions
- </label>
- <VStack spacing={8}>
- {Object.entries(permissions)
- .sort((a, b) => a[0].localeCompare(b[0]))
- .map(([module, data], index) => (
- <PermissionCheckboxes
- key={index}
- module={module}
- permissions={data}
- updatePermissions={updatePermissions}
- />
- ))}
- </VStack>
+ <PermissionMatrix matrix={matrix} />
<Hidden name="id" />
- <Hidden name="data" value={JSON.stringify(permissions)} />
+ <Hidden name="data" value={permissionsData} />
</VStack>
- </DrawerBody>
- <DrawerFooter>
+ </ModalBody>
+ <ModalFooter>
<HStack>
<Submit>Save</Submit>
<Button size="md" variant="solid" onClick={onClose}>
Cancel
</Button>
</HStack>
- </DrawerFooter>
+ </ModalFooter>
</ValidatedForm>
- </DrawerContent>
- </Drawer>
+ </ModalContent>
+ </Modal>
);
};
diff --git a/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
index 9be8cec306..8861e124a2 100644
--- a/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
+++ b/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
@@ -99,14 +99,14 @@ const CreateSupplierModal = () => {
</>
)}
</VStack>
- <ModalFooter>
- <HStack>
- <Submit isLoading={formFetcher.state !== "idle"}>
- Create User
- </Submit>
- </HStack>
- </ModalFooter>
</ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>
+ Create User
+ </Submit>
+ </HStack>
+ </ModalFooter>
</ValidatedForm>
</ModalContent>
</Modal>
diff --git a/apps/erp/app/modules/users/ui/components/Permission.tsx b/apps/erp/app/modules/users/ui/components/Permission.tsx
deleted file mode 100644
index 4c81a9683d..0000000000
--- a/apps/erp/app/modules/users/ui/components/Permission.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Checkbox, HStack, VStack } from "@carbon/react";
-import type { CompanyPermission } from "~/modules/users";
-import { capitalize } from "~/utils/string";
-
-type PermissionProps = {
- module: string;
- permissions: CompanyPermission;
- updatePermissions: (module: string, permissions: CompanyPermission) => void;
-};
-
-const labels = ["view", "create", "update", "delete"] as const;
-
-const PermissionCheckboxes = ({
- module,
- permissions,
- updatePermissions
-}: PermissionProps) => {
- const allChecked = Object.values(permissions).every(Boolean);
- const isIndeterminate =
- Object.values(permissions).some(Boolean) && !allChecked;
-
- const updateByPosition = (position: number, value: boolean) => {
- const newPermissions = { ...permissions };
- newPermissions[labels[position]] = value;
- updatePermissions(module, newPermissions);
- };
-
- if (["messaging", "items", "timecards"].includes(module)) {
- return null;
- }
-
- return (
- <div>
- <HStack>
- <Checkbox
- isChecked={allChecked || isIndeterminate}
- isIndeterminate={isIndeterminate}
- onCheckedChange={(checked) =>
- updatePermissions(module, {
- view: !!checked,
- create: !!checked,
- update: !!checked,
- delete: !!checked
- })
- }
- />
- <span>{capitalize(module)}</span>
- </HStack>
-
- <VStack className="pl-6 mt-2">
- {labels.map((verb, index) => (
- <HStack key={index}>
- <Checkbox
- isChecked={permissions[verb]}
- onCheckedChange={(checked) => updateByPosition(index, !!checked)}
- />
- <span>{`${capitalize(labels[index])} ${capitalize(module)}`}</span>
- </HStack>
- ))}
- </VStack>
- </div>
- );
-};
-
-export default PermissionCheckboxes;
diff --git a/apps/erp/app/modules/users/ui/components/index.ts b/apps/erp/app/modules/users/ui/components/index.ts
index dec83cf573..109c68881b 100644
--- a/apps/erp/app/modules/users/ui/components/index.ts
+++ b/apps/erp/app/modules/users/ui/components/index.ts
@@ -1,11 +1,5 @@
import DeactivateUsersModal from "./DeactivateUsersModal";
-import PermissionCheckboxes from "./Permission";
import ResendInviteModal from "./ResendInviteModal";
import RevokeInviteModal from "./RevokeInviteModal";
-export {
- DeactivateUsersModal,
- PermissionCheckboxes,
- ResendInviteModal,
- RevokeInviteModal
-};
+export { DeactivateUsersModal, ResendInviteModal, RevokeInviteModal };
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 9126e455b5..5ac527ed43 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -37,8 +37,8 @@ import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
import NProgress from "~/styles/nprogress.css?url";
import Tailwind from "~/styles/tailwind.css?url";
-import "./polyfill";
import type { Route } from "./+types/root";
+import "./polyfill";
import { getTheme } from "./services/theme.server";
export const links: LinksFunction = () => {
@@ -60,6 +60,7 @@ export const meta: MetaFunction = () => {
export async function loader({ request, context }: LoaderFunctionArgs) {
const {
CARBON_EDITION,
+ CARBON_API_URL,
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
ERP_URL,
@@ -84,6 +85,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
{
env: {
CARBON_EDITION,
+ CARBON_API_URL,
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
ERP_URL,
diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.ts
index 10a61bad74..14c58b302f 100644
--- a/apps/erp/app/routes/api+/docs.ts
+++ b/apps/erp/app/routes/api+/docs.ts
@@ -1,11 +1,11 @@
import swaggerDocsSchema from "@carbon/database/swagger-docs-schema";
import { redis } from "@carbon/kv";
import { Ratelimit } from "@upstash/ratelimit";
-import type {
- ClientLoaderFunctionArgs,
- LoaderFunctionArgs
+import {
+ type ClientLoaderFunctionArgs,
+ data,
+ type LoaderFunctionArgs
} from "react-router";
-import { data } from "react-router";
import { docsQuery } from "~/utils/react-query";
const ratelimit = new Ratelimit({
diff --git a/apps/erp/app/routes/docs+/api+/$lang.intro.tsx b/apps/erp/app/routes/docs+/api+/$lang.intro.tsx
index 70ab03b7a5..7e7640f65f 100644
--- a/apps/erp/app/routes/docs+/api+/$lang.intro.tsx
+++ b/apps/erp/app/routes/docs+/api+/$lang.intro.tsx
@@ -1,34 +1,23 @@
-import { getBrowserEnv, SUPABASE_ANON_KEY } from "@carbon/auth";
-import { getAuthSession } from "@carbon/auth/session.server";
+import { getBrowserEnv } from "@carbon/auth";
import { Alert, AlertDescription, AlertTitle } from "@carbon/react";
import { LuTriangleAlert } from "react-icons/lu";
-import type { LoaderFunctionArgs } from "react-router";
-import { Link, useLoaderData } from "react-router";
-import { CodeSnippet, Snippets, useSelectedLang } from "~/modules/api";
+import { Link } from "react-router";
+import {
+ CodeSnippet,
+ Snippets,
+ useApiDocsConfig,
+ useSelectedLang
+} from "~/modules/api";
import { path } from "~/utils/path";
-const { SUPABASE_URL } = getBrowserEnv();
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const session = await getAuthSession(request);
- if (session) {
- return {
- isLoggedIn: true,
- companyId: session.companyId,
- publicKey: SUPABASE_ANON_KEY
- };
- }
-
- return {
- isLoggedIn: false,
- companyId: "<your-company-id>",
- publicKey: "<public-key>"
- };
-}
+const { CARBON_API_URL } = getBrowserEnv();
export default function Route() {
- const { companyId, publicKey } = useLoaderData<typeof loader>();
const selectedLang = useSelectedLang();
+ const config = useApiDocsConfig();
+
+ const apiUrl = config.apiUrl || CARBON_API_URL!;
+ const apiKey = config.apiKey || "<your-api-key>";
return (
<>
@@ -43,18 +32,12 @@ export default function Route() {
<article>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.env({
- appUrl: window.location.origin,
- apiKey: "<your-api-key>",
- publicKey: publicKey,
- apiUrl: SUPABASE_URL,
- companyId: companyId
- })}
+ snippet={Snippets.env({ apiUrl, apiKey })}
/>
</article>
<p>
- The API Key is provided via the <code>carbon-key</code> header when
- making requests to the API.
+ The API Key is provided via the <code>Authorization</code> header
+ when making requests to the API.
</p>
</article>
</div>
@@ -74,8 +57,7 @@ export default function Route() {
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4 my-1" />
<AlertTitle className="!my-0 font-bold text-base">
- You should never expose the <code>carbon-key</code> in the
- client
+ You should never expose the API key in the client
</AlertTitle>
<AlertDescription>
Your API key gives full access to your database. Never expose
@@ -92,7 +74,7 @@ export default function Route() {
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.init(SUPABASE_URL)}
+ snippet={Snippets.init(apiUrl)}
/>
</article>
</div>
diff --git a/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx b/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx
index 1f6b7ddd26..9757dd8951 100644
--- a/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx
+++ b/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx
@@ -1,19 +1,24 @@
import { getBrowserEnv } from "@carbon/auth";
import { useParams } from "react-router";
-import { TableDocs, useSelectedLang } from "~/modules/api";
+import { TableDocs, useApiDocsConfig, useSelectedLang } from "~/modules/api";
-const { SUPABASE_URL } = getBrowserEnv();
+const { CARBON_API_URL } = getBrowserEnv();
export default function Route() {
const selectedLang = useSelectedLang();
+ const config = useApiDocsConfig();
const { id } = useParams();
if (!id) throw new Error("Table id not found");
+ const endpoint = config.apiUrl || CARBON_API_URL!;
+ const apiKey = config.apiKey || undefined;
+
return (
<TableDocs
- endpoint={SUPABASE_URL}
+ endpoint={endpoint}
selectedLang={selectedLang}
resourceId={id}
+ apiKey={apiKey}
/>
);
}
diff --git a/apps/erp/app/routes/docs+/api+/_layout.tsx b/apps/erp/app/routes/docs+/api+/_layout.tsx
index 8b5d5a4020..ed45147346 100644
--- a/apps/erp/app/routes/docs+/api+/_layout.tsx
+++ b/apps/erp/app/routes/docs+/api+/_layout.tsx
@@ -1,12 +1,24 @@
-import { Button, ClientOnly } from "@carbon/react";
-import { LuEye, LuTable2 } from "react-icons/lu";
+import {
+ Button,
+ ClientOnly,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@carbon/react";
+import { useState } from "react";
+import { LuEye, LuEyeOff, LuSettings2, LuTable2 } from "react-icons/lu";
import type { MetaFunction } from "react-router";
import { Link, Outlet, useLocation, useNavigate } from "react-router";
import { GroupedContentSidebar } from "~/components/Layout";
import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";
import { useSwaggerDocs } from "~/hooks/useSwaggerDocs";
import type { ValidLang } from "~/modules/api";
-import { useSelectedLang } from "~/modules/api";
+import {
+ ApiDocsProvider,
+ useApiDocsConfig,
+ useSelectedLang
+} from "~/modules/api";
import DocsStyle from "~/styles/docs.css?url";
import type { RouteGroup } from "~/types";
import type { Handle } from "~/utils/handle";
@@ -50,50 +62,131 @@ export default function ApiDocsRoute() {
};
return (
- <CollapsibleSidebarProvider>
- <div className="flex flex-col h-screen">
- <div className="bg-background border-b h-[var(--header-height)] col-span-full px-6 items-center flex flex-shrink-0">
- <Link to={path.to.authenticatedRoot}>
- <img
- src="/carbon-word-light.svg"
- alt="Carbon Logo"
- className="h-6 dark:hidden z-50"
- />
- <img
- src="/carbon-word-dark.svg"
- alt="Carbon Logo"
- className="h-6 dark:block hidden z-50"
- />
- </Link>
+ <ApiDocsProvider>
+ <CollapsibleSidebarProvider>
+ <div className="flex flex-col h-screen">
+ <div className="bg-background border-b h-[var(--header-height)] col-span-full px-6 items-center flex flex-shrink-0 justify-between">
+ <Link to={path.to.authenticatedRoot}>
+ <img
+ src="/carbon-word-light.svg"
+ alt="Carbon Logo"
+ className="h-6 dark:hidden z-50"
+ />
+ <img
+ src="/carbon-word-dark.svg"
+ alt="Carbon Logo"
+ className="h-6 dark:block hidden z-50"
+ />
+ </Link>
+ <ApiDocsConfigInputs />
+ </div>
+ <div className="relative grid grid-cols-[auto_1fr] w-full h-full">
+ <div className="flex absolute top-2 right-2 z-50 gap-2">
+ <Button
+ variant={selectedLang === "js" ? "primary" : "secondary"}
+ onClick={() => {
+ onChangeLanguage("js");
+ }}
+ >
+ JS
+ </Button>
+ <Button
+ variant={selectedLang === "bash" ? "primary" : "secondary"}
+ onClick={() => {
+ onChangeLanguage("bash");
+ }}
+ >
+ Bash
+ </Button>
+ </div>
+ <GroupedContentSidebar groups={groups} width={270} exactMatch />
+ <div className="Docs Docs--api-page w-full h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <div className="Docs--inner-wrapper pt-4">
+ <ClientOnly>{() => <Outlet />}</ClientOnly>
+ </div>
+ </div>
+ </div>
</div>
- <div className="relative grid grid-cols-[auto_1fr] w-full h-full">
- <div className="flex absolute top-2 right-2 z-50 gap-2">
- <Button
- variant={selectedLang === "js" ? "primary" : "secondary"}
- onClick={() => {
- onChangeLanguage("js");
- }}
- >
- JS
- </Button>
- <Button
- variant={selectedLang === "bash" ? "primary" : "secondary"}
- onClick={() => {
- onChangeLanguage("bash");
- }}
- >
- Bash
- </Button>
+ </CollapsibleSidebarProvider>
+ </ApiDocsProvider>
+ );
+}
+
+function ApiDocsConfigInputs() {
+ const { apiUrl, apiKey, setApiUrl, setApiKey } = useApiDocsConfig();
+ const [showKey, setShowKey] = useState(false);
+ const isConfigured = !!(apiUrl || apiKey);
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="secondary" size="sm" className="gap-1.5">
+ <LuSettings2 className="h-3.5 w-3.5" />
+ <span>API Settings</span>
+ {isConfigured && (
+ <span className="h-1.5 w-1.5 rounded-full bg-green-500" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" sideOffset={8} className="w-[400px] p-0">
+ <div className="p-4 space-y-4">
+ <div>
+ <h4 className="text-sm font-semibold text-foreground">
+ API Configuration
+ </h4>
+ <p className="text-xs text-muted-foreground mt-1">
+ Set a custom server URL and API key. Snippets will update
+ automatically.
+ </p>
</div>
- <GroupedContentSidebar groups={groups} width={270} exactMatch />
- <div className="Docs Docs--api-page w-full h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
- <div className="Docs--inner-wrapper pt-4">
- <ClientOnly>{() => <Outlet />}</ClientOnly>
+ <div className="space-y-3">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-muted-foreground">
+ Server URL
+ </label>
+ <Input
+ size="sm"
+ placeholder="https://your-api-url.supabase.co"
+ value={apiUrl}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
+ setApiUrl(e.target.value)
+ }
+ className="font-mono text-xs"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-muted-foreground">
+ API Key
+ </label>
+ <div className="relative">
+ <Input
+ size="sm"
+ type={showKey ? "text" : "password"}
+ placeholder="your-api-key"
+ value={apiKey}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
+ setApiKey(e.target.value)
+ }
+ className="font-mono text-xs pr-8"
+ />
+ <button
+ type="button"
+ onClick={() => setShowKey((prev) => !prev)}
+ className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
+ aria-label={showKey ? "Hide API key" : "Show API key"}
+ >
+ {showKey ? (
+ <LuEyeOff className="h-3.5 w-3.5" />
+ ) : (
+ <LuEye className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
</div>
</div>
</div>
- </div>
- </CollapsibleSidebarProvider>
+ </PopoverContent>
+ </Popover>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx b/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
index b589af36b0..160cbd12aa 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
@@ -25,9 +25,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // biome-ignore lint/correctness/noUnusedVariables: we destructure to omit id from validation
+ const { id: _id, scopes: scopesJson, expiresAt, ...d } = validation.data;
+
+ // Parse scopes from JSON string
+ const scopes = scopesJson ? JSON.parse(scopesJson) : {};
+
const updateApiKey = await upsertApiKey(client, {
id,
- ...validation.data
+ ...d,
+ scopes,
+ expiresAt: expiresAt || undefined
});
if (updateApiKey.error) {
@@ -49,20 +57,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
export default function EditApiKeyRoute() {
const navigate = useNavigate();
const params = useParams();
- const routeData = useRouteData<{ apiKeys: ApiKey[] }>(path.to.apiKeys);
+ const routeData = useRouteData<{ apiKeys: ApiKey[]; companyId: string }>(
+ path.to.apiKeys
+ );
const apiKey = routeData?.apiKeys.find((apiKey) => apiKey.id === params.id);
if (!apiKey) throw new Error("API key not found");
const initialValues = {
id: apiKey?.id ?? undefined,
- name: apiKey?.name ?? ""
+ name: apiKey?.name ?? "",
+ expiresAt: (apiKey as any)?.expiresAt ?? undefined
};
return (
<ApiKeyForm
key={initialValues.id}
initialValues={initialValues}
+ companyId={routeData?.companyId}
+ existingScopes={(apiKey as any)?.scopes ?? null}
onClose={() => navigate(-1)}
/>
);
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.new.tsx b/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
index 484b1d192e..8f8b90b285 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
@@ -1,10 +1,13 @@
import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
+import { hashApiKey, requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { nanoid } from "nanoid";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, useNavigate } from "react-router";
+import { useRouteData } from "~/hooks";
import { ApiKeyForm, apiKeyValidator, upsertApiKey } from "~/modules/settings";
+import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
await requirePermissions(request, {
@@ -28,10 +31,23 @@ export async function action({ request }: ActionFunctionArgs) {
}
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- const { id, ...d } = validation.data;
+ const { id, scopes: scopesJson, expiresAt, ...d } = validation.data;
+
+ // Parse scopes from JSON string
+ const scopes = scopesJson ? JSON.parse(scopesJson) : {};
+
+ // Generate key + hash in the route action (server-only context)
+ const rawKey = `crbn_${nanoid()}`;
+ const keyHash = hashApiKey(rawKey);
+ const keyPreview = rawKey.slice(-5);
const insertApiKey = await upsertApiKey(client, {
...d,
+ scopes,
+ expiresAt: expiresAt || undefined,
+ rawKey,
+ keyHash,
+ keyPreview,
companyId,
createdBy: userId
});
@@ -58,11 +74,17 @@ export async function action({ request }: ActionFunctionArgs) {
export default function NewApiKeyRoute() {
const navigate = useNavigate();
+ const routeData = useRouteData<{ companyId: string }>(path.to.apiKeys);
+
const initialValues = {
name: ""
};
return (
- <ApiKeyForm onClose={() => navigate(-1)} initialValues={initialValues} />
+ <ApiKeyForm
+ onClose={() => navigate(-1)}
+ initialValues={initialValues}
+ companyId={routeData?.companyId}
+ />
);
}
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.tsx b/apps/erp/app/routes/x+/settings+/api-keys.tsx
index 3e883762ac..4a54f4fc1a 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.tsx
@@ -39,12 +39,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
return {
- apiKeys:
- apiKeys.data?.map((apiKey) => ({
- ...apiKey,
- key: apiKey.key.substring(0, 12) + "…"
- })) ?? [],
- count: apiKeys.count ?? 0
+ apiKeys: apiKeys.data?.map(({ keyHash, ...rest }: any) => rest) ?? [],
+ count: apiKeys.count ?? 0,
+ companyId
};
}
diff --git a/apps/erp/app/styles/docs.css b/apps/erp/app/styles/docs.css
index c0bda68f30..278262756f 100644
--- a/apps/erp/app/styles/docs.css
+++ b/apps/erp/app/styles/docs.css
@@ -2,72 +2,14 @@
width: 100%;
}
-.Code .prism-code {
+.Code pre {
margin: 0;
- padding: 0.25rem;
- background-color: none;
- white-space: normal;
- word-break: break-word;
-}
-
-.Code .token-line {
+ padding: 0.5rem 0rem !important;
+ background-color: transparent!important;
font-size: 0.875rem;
line-height: 1.25rem;
}
-.Code .token.function,
-.Code .token.imports,
-.Code .token.keyword.module,
-.Code .token.property-access {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.function,
-.Code .token.keyword.module {
- font-style: normal !important;
-}
-
-.Code .token.console.class-name,
-.Code .token.doc-comment.optional-parameter,
-.Code .token.doc-comment.optional-parameter.punctuation,
-.Code .token.doc-comment.parameter,
-.Code .token.doc-comment.parameter.punctuation,
-.Code .token.operator,
-.Code .token.parameter,
-.Code .token.plain,
-.Code .token.punctuation {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.doc-comment.keyword,
-.Code .token.keyword {
- font-style: normal !important;
-}
-
-.Code .token.string {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.constant {
- font-style: normal !important;
-}
-
-.Code .token.comment {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.number {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.boolean,
-.Code .token.doc-comment.class-name {
- --tw-text-opacity: 1;
-}
-
.Code .codeBlock {
margin-bottom: 0;
overflow: hidden;
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 70759743c4..af994cc48e 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -56,6 +56,7 @@ export const meta: MetaFunction = () => {
export async function loader({ request }: LoaderFunctionArgs) {
const {
CARBON_EDITION,
+ CARBON_API_URL,
CONTROLLED_ENVIRONMENT,
ERP_URL,
MES_URL,
@@ -73,6 +74,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
{
env: {
CARBON_EDITION,
+ CARBON_API_URL,
CONTROLLED_ENVIRONMENT,
ERP_URL,
MES_URL,
diff --git a/apps/mes/app/styles/docs.css b/apps/mes/app/styles/docs.css
index c0bda68f30..278262756f 100644
--- a/apps/mes/app/styles/docs.css
+++ b/apps/mes/app/styles/docs.css
@@ -2,72 +2,14 @@
width: 100%;
}
-.Code .prism-code {
+.Code pre {
margin: 0;
- padding: 0.25rem;
- background-color: none;
- white-space: normal;
- word-break: break-word;
-}
-
-.Code .token-line {
+ padding: 0.5rem 0rem !important;
+ background-color: transparent!important;
font-size: 0.875rem;
line-height: 1.25rem;
}
-.Code .token.function,
-.Code .token.imports,
-.Code .token.keyword.module,
-.Code .token.property-access {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.function,
-.Code .token.keyword.module {
- font-style: normal !important;
-}
-
-.Code .token.console.class-name,
-.Code .token.doc-comment.optional-parameter,
-.Code .token.doc-comment.optional-parameter.punctuation,
-.Code .token.doc-comment.parameter,
-.Code .token.doc-comment.parameter.punctuation,
-.Code .token.operator,
-.Code .token.parameter,
-.Code .token.plain,
-.Code .token.punctuation {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.doc-comment.keyword,
-.Code .token.keyword {
- font-style: normal !important;
-}
-
-.Code .token.string {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.constant {
- font-style: normal !important;
-}
-
-.Code .token.comment {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.number {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.boolean,
-.Code .token.doc-comment.class-name {
- --tw-text-opacity: 1;
-}
-
.Code .codeBlock {
margin-bottom: 0;
overflow: hidden;
diff --git a/apps/starter/app/styles/docs.css b/apps/starter/app/styles/docs.css
index c0bda68f30..00c7cbd8e4 100644
--- a/apps/starter/app/styles/docs.css
+++ b/apps/starter/app/styles/docs.css
@@ -2,72 +2,14 @@
width: 100%;
}
-.Code .prism-code {
+.Code pre {
margin: 0;
- padding: 0.25rem;
- background-color: none;
- white-space: normal;
- word-break: break-word;
-}
-
-.Code .token-line {
+ padding: 0.5rem 0.75rem;
+ background-color: transparent;
font-size: 0.875rem;
line-height: 1.25rem;
}
-.Code .token.function,
-.Code .token.imports,
-.Code .token.keyword.module,
-.Code .token.property-access {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.function,
-.Code .token.keyword.module {
- font-style: normal !important;
-}
-
-.Code .token.console.class-name,
-.Code .token.doc-comment.optional-parameter,
-.Code .token.doc-comment.optional-parameter.punctuation,
-.Code .token.doc-comment.parameter,
-.Code .token.doc-comment.parameter.punctuation,
-.Code .token.operator,
-.Code .token.parameter,
-.Code .token.plain,
-.Code .token.punctuation {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.doc-comment.keyword,
-.Code .token.keyword {
- font-style: normal !important;
-}
-
-.Code .token.string {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.constant {
- font-style: normal !important;
-}
-
-.Code .token.comment {
- font-style: normal !important;
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.number {
- --tw-text-opacity: 1 !important;
-}
-
-.Code .token.boolean,
-.Code .token.doc-comment.class-name {
- --tw-text-opacity: 1;
-}
-
.Code .codeBlock {
margin-bottom: 0;
overflow: hidden;
diff --git a/llm/cache/authentication-system.md b/llm/cache/authentication-system.md
index 4b819b45d2..1acacf7399 100644
--- a/llm/cache/authentication-system.md
+++ b/llm/cache/authentication-system.md
@@ -17,11 +17,20 @@ Located at `/packages/auth/`, the auth package provides:
### Key Files:
- `src/lib/supabase/client.ts` - Supabase client configurations
-- `src/services/auth.server.ts` - Server-side authentication logic
+- `src/services/auth.server.ts` - Server-side authentication logic (includes `hashApiKey`, `requirePermissions` with scope checking, `getCompanyIdFromAPIKey`)
- `src/services/session.server.ts` - Session management and cookies
- `src/services/users.ts` - User queries and permission handling
- `src/types.ts` - Authentication type definitions
+### Exports (package.json):
+
+- `.` - Client-safe types and utilities
+- `./auth.server` - Server-side auth logic (hashApiKey, requirePermissions, etc.)
+- `./company.server` - Company management
+- `./session.server` - Session management
+- `./users.server` - User management
+- `./verification.server` - Email verification
+
## Authentication Flow
### Login Process
@@ -112,14 +121,43 @@ Located at `/packages/auth/`, the auth package provides:
```typescript
{
id: string
- key: string
+ keyHash: string (SHA-256 hex digest of raw key)
name: string
companyId: string (FK)
createdBy: string (FK to user.id)
+ scopes: JSONB (matches userPermission structure, {} = full access)
+ rateLimit: number (default 1000)
+ rateLimitWindow: "1m" | "1h" | "1d" (default "1h")
+ expiresAt: string | null
+ lastUsedAt: string | null
createdAt: string
}
```
+**apiKeyRateLimit** table (UNLOGGED -- no WAL, fast writes):
+
+```typescript
+{
+ apiKeyId: string (FK to apiKey.id)
+ windowStart: timestamp
+ requestCount: number
+}
+```
+
+Rate limiting uses `check_api_key_rate_limit()` Postgres function with atomic upsert + probabilistic cleanup (~1% of requests).
+
+**Single `checkApiKeyRateLimit()` function** using Supabase `.rpc()`:
+
+- **Canonical**: `packages/database/src/ratelimit.ts` (exported as `@carbon/database/ratelimit`)
+- **Edge copy**: `packages/database/supabase/functions/lib/ratelimit.ts` (same implementation, Deno can't import npm workspace packages)
+
+Called from auth layer (NOT per-handler):
+
+- ERP: `requirePermissions()` in `@carbon/auth/auth.server` (also handles expiration + lastUsedAt)
+- Edge functions: `getSupabaseServiceRole()` in `packages/database/supabase/functions/lib/supabase.ts`
+
+API key hashing uses `node:crypto` `createHash("sha256")` across all runtimes (Node.js ERP, Deno edge functions). The `hashApiKey()` function in `@carbon/auth/auth.server` is the canonical Node implementation. Edge functions use the same `createHash` via Deno's Node compat layer.
+
## User Registration/Invitation System
### Invitation Flow
@@ -149,8 +187,6 @@ Located at `/packages/auth/`, the auth package provides:
- `public.userPermission` table with the user's ID
3. **Identity Group**: A separate trigger creates an identity group for the user
-
-
### Self-Signup Flow
- Login page has a "Sign up for free" link pointing to `/signup`
@@ -205,14 +241,27 @@ The `requirePermissions` function validates:
- Used for server-to-server communication
- Scoped to specific company context
- No user session required
+- Keys are SHA-256 hashed; raw key shown once at creation, only hash stored
+- Supports JSONB scopes matching `userPermission` structure (empty `{}` = full access)
+- Rate limited via Postgres unlogged table (not Redis) with configurable limit + window
+- Optional expiration date
+- `lastUsedAt` tracked via fire-and-forget update in ERP middleware
+- `requirePermissions()` in `auth.server.ts` enforces scope restrictions
+- RLS functions (`get_company_id_from_api_key`, `check_api_key_scope`) enforce at DB level
## Security Features
### Rate Limiting
-- Magic link requests: 5 per hour per IP
-- Implemented using Upstash Redis
-- Applied to login endpoints
+- **Login rate limiting**: Magic link requests: 5 per hour per IP, implemented using Upstash Redis (unchanged)
+- **API key rate limiting**: Uses Postgres unlogged table `apiKeyRateLimit` + `check_api_key_rate_limit()` function
+ - Configurable per-key: `rateLimit` (count) + `rateLimitWindow` ("1m", "1h", "1d")
+ - Default: 1000 requests per hour
+ - ERP: inside `requirePermissions()` in `@carbon/auth/auth.server` via `@carbon/database/ratelimit`
+ - Edge functions: inside `getSupabaseServiceRole()` in `lib/supabase.ts` via `lib/ratelimit.ts`
+ - Returns 429 with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` headers
+ - Old Redis-based `ratelimit.server.ts` has been deleted; `@upstash/ratelimit` and `@carbon/kv` peer deps removed from `@carbon/auth`
+ - Old ERP middleware `apps/erp/app/middleware/api-key-ratelimit.ts` has been deleted; rate limiting consolidated into `requirePermissions()`
### Session Security
diff --git a/llm/plans/api-key-rate-limiting-scopes.md b/llm/plans/api-key-rate-limiting-scopes.md
new file mode 100644
index 0000000000..56b20eaea6
--- /dev/null
+++ b/llm/plans/api-key-rate-limiting-scopes.md
@@ -0,0 +1,439 @@
+# API Key Rate Limiting and Read/Write Scopes
+
+## Context
+
+Currently, API keys in Carbon grant **full access** to all company data without any permission restrictions or rate limiting. This creates security and resource management concerns:
+
+1. **No granular permissions**: Any valid API key can read, create, update, or delete all data within a company
+2. **No rate limiting**: API keys can make unlimited requests, risking resource exhaustion
+3. **No scope control**: Cannot create read-only or module-specific API keys
+
+The goal is to add scoped permissions and rate limiting to API keys while maintaining backward compatibility with existing integrations.
+
+## Architecture Considerations
+
+### Why Dual-Layer Rate Limiting?
+
+Carbon has three entry points for API key requests:
+
+1. **PostgREST (Direct DB)**: Most common - clients call `/rest/v1/*` endpoints directly. These bypass all application code and go straight to PostgreSQL via PostgREST. RLS policies are the only enforcement layer.
+
+2. **Remix Routes**: Some operations go through `requirePermissions()` in the application layer before hitting the database.
+
+3. **Supabase Edge Functions**: Deno functions like `post-sales-invoice`, `import-csv` that handle complex operations.
+
+Rate limiting must be implemented at **all three layers** to be effective:
+- **Database**: Catches PostgREST requests (the majority)
+- **Application**: Provides better error responses with 429 status + headers
+- **Edge Functions**: Handles Deno function calls
+
+### Database Rate Limiting Challenges
+
+1. **Multiple RLS calls per request**: A single API request may access multiple tables, triggering RLS checks multiple times. We use `request.id` to avoid double-counting.
+
+2. **Performance**: Rate limit checks add overhead to every query. Using a simple fixed-window approach (vs sliding window) is more performant for PostgreSQL.
+
+3. **Cleanup**: The rate limit table needs periodic cleanup of old entries (pg_cron or application-level job).
+
+## Current Architecture
+
+### API Key Authentication Flow
+
+1. Request arrives with `carbon-key` header
+2. `requirePermissions()` in `packages/auth/src/services/auth.server.ts:112-127` **bypasses all permission checks** for API keys
+3. RLS helper functions (`get_companies_with_employee_permission`, etc.) in `packages/database/supabase/migrations/20250201181148_rls-refactor.sql` return **full company access** for API keys
+
+### Key Files
+
+| File | Current Behavior |
+|------|------------------|
+| `packages/auth/src/services/auth.server.ts:63-70` | `getCompanyIdFromAPIKey()` - only retrieves companyId and createdBy |
+| `packages/auth/src/services/auth.server.ts:112-127` | `requirePermissions()` - returns immediately for API keys, no permission check |
+| `packages/database/supabase/migrations/20250201181148_rls-refactor.sql:48-61` | `get_companies_with_employee_permission()` - returns full access for API keys |
+| `packages/database/supabase/migrations/20240728004118_api-keys.sql` | API key table schema - no scope fields |
+
+## Implementation Plan
+
+### Phase 1: Database Schema Changes
+
+Create migration: `packages/database/supabase/migrations/YYYYMMDDHHMMSS_api-key-scopes-rate-limits.sql`
+
+```sql
+ALTER TABLE "apiKey"
+ADD COLUMN "scopes" JSONB NOT NULL DEFAULT '{}',
+ADD COLUMN "rateLimit" INTEGER NOT NULL DEFAULT 1000,
+ADD COLUMN "rateLimitWindow" TEXT NOT NULL DEFAULT '1h',
+ADD COLUMN "expiresAt" TIMESTAMP WITH TIME ZONE,
+ADD COLUMN "lastUsedAt" TIMESTAMP WITH TIME ZONE;
+```
+
+**Scope format** (mirrors userPermission structure):
+```json
+{
+ "sales_view": ["<companyId>"],
+ "sales_create": ["<companyId>"],
+ "inventory_view": ["<companyId>"],
+ "accounting_view": []
+}
+```
+
+### Phase 2: SQL Functions for API Key Scope Checking
+
+Add new function to retrieve API key scopes:
+```sql
+CREATE OR REPLACE FUNCTION get_api_key_scopes() RETURNS JSONB
+LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ scopes JSONB;
+BEGIN
+ SELECT "scopes" INTO scopes
+ FROM "apiKey"
+ WHERE "key" = (current_setting('request.headers'::text, true)::json ->> 'api-key')::text;
+ RETURN COALESCE(scopes, '{}'::jsonb);
+END;
+$$;
+```
+
+**Modify** `get_companies_with_employee_permission()` to check API key scopes:
+```sql
+-- Current (bypasses permissions):
+IF api_key_company IS NOT NULL THEN
+ RETURN ARRAY[api_key_company];
+END IF;
+
+-- New (checks scopes):
+IF api_key_company IS NOT NULL THEN
+ IF (get_api_key_scopes()->>permission) IS NOT NULL
+ AND api_key_company = ANY(jsonb_to_text_array(get_api_key_scopes()->permission)) THEN
+ RETURN ARRAY[api_key_company];
+ ELSE
+ RETURN '{}';
+ END IF;
+END IF;
+```
+
+Apply same pattern to:
+- `get_companies_with_employee_role()`
+- `get_companies_with_any_role()`
+
+### Phase 3: Application-Level Permission Checking
+
+**Modify** `packages/auth/src/services/auth.server.ts`:
+
+1. Update `getCompanyIdFromAPIKey()` to return scopes and rate limit config
+2. Add scope checking in `requirePermissions()` for API key requests
+3. Add rate limiting check before processing API key requests
+
+```typescript
+// In requirePermissions(), after API key validation:
+const scopes = company.data.scopes as Record<string, string[]>;
+
+// Check required permissions against scopes
+const hasRequiredScopes = checkApiKeyScopes(scopes, requiredPermissions, companyId);
+if (!hasRequiredScopes) {
+ throw new Response("API key lacks required permissions", { status: 403 });
+}
+
+// Rate limit check
+await checkApiKeyRateLimit(apiKey, company.data.rateLimit, company.data.rateLimitWindow);
+```
+
+### Phase 4: Rate Limiting Implementation (Dual Layer)
+
+Most API calls go directly to PostgREST/database, bypassing the application layer entirely. Therefore, rate limiting must be implemented at **both** the database and application levels.
+
+#### 4A: Database-Level Rate Limiting
+
+**Challenge**: RLS policy functions are called multiple times per request (once per table). We need to:
+1. Track rate limits per API key
+2. Only count once per HTTP request (not per table access)
+3. Handle sliding window or fixed window semantics
+
+**Solution**: Use a rate limit tracking table + a function that checks the `request.id` to avoid double-counting within the same request.
+
+Create rate limit tracking table:
+```sql
+CREATE TABLE "apiKeyRateLimit" (
+ "apiKeyId" TEXT NOT NULL,
+ "windowStart" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "requestCount" INTEGER NOT NULL DEFAULT 0,
+ "lastRequestId" TEXT,
+ CONSTRAINT "apiKeyRateLimit_pkey" PRIMARY KEY ("apiKeyId", "windowStart"),
+ CONSTRAINT "apiKeyRateLimit_apiKeyId_fkey" FOREIGN KEY ("apiKeyId")
+ REFERENCES "apiKey"("id") ON DELETE CASCADE
+);
+
+-- Cleanup old entries periodically (can use pg_cron)
+CREATE INDEX "apiKeyRateLimit_windowStart_idx" ON "apiKeyRateLimit" ("windowStart");
+```
+
+Create rate limit check function:
+```sql
+CREATE OR REPLACE FUNCTION check_api_key_rate_limit() RETURNS BOOLEAN
+LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ api_key_record RECORD;
+ current_window_start TIMESTAMP WITH TIME ZONE;
+ current_request_id TEXT;
+ window_interval INTERVAL;
+ current_count INTEGER;
+BEGIN
+ -- Get API key from header
+ SELECT ak.* INTO api_key_record
+ FROM "apiKey" ak
+ WHERE ak."key" = (current_setting('request.headers'::text, true)::json ->> 'api-key')::text;
+
+ IF api_key_record IS NULL THEN
+ RETURN TRUE; -- No API key = not rate limited (handled elsewhere)
+ END IF;
+
+ -- Get current request ID to avoid double-counting within same request
+ current_request_id := current_setting('request.id', true);
+
+ -- Calculate window interval from rateLimitWindow (e.g., '1h', '1d', '1m')
+ window_interval := CASE api_key_record."rateLimitWindow"
+ WHEN '1m' THEN INTERVAL '1 minute'
+ WHEN '1h' THEN INTERVAL '1 hour'
+ WHEN '1d' THEN INTERVAL '1 day'
+ ELSE INTERVAL '1 hour'
+ END;
+
+ -- Calculate current window start (truncate to window boundary)
+ current_window_start := date_trunc(
+ CASE api_key_record."rateLimitWindow"
+ WHEN '1m' THEN 'minute'
+ WHEN '1h' THEN 'hour'
+ WHEN '1d' THEN 'day'
+ ELSE 'hour'
+ END,
+ NOW()
+ );
+
+ -- Check/insert rate limit entry
+ INSERT INTO "apiKeyRateLimit" ("apiKeyId", "windowStart", "requestCount", "lastRequestId")
+ VALUES (api_key_record."id", current_window_start, 1, current_request_id)
+ ON CONFLICT ("apiKeyId", "windowStart") DO UPDATE
+ SET
+ "requestCount" = CASE
+ WHEN "apiKeyRateLimit"."lastRequestId" = current_request_id THEN "apiKeyRateLimit"."requestCount"
+ ELSE "apiKeyRateLimit"."requestCount" + 1
+ END,
+ "lastRequestId" = current_request_id
+ RETURNING "requestCount" INTO current_count;
+
+ -- Check if over limit
+ IF current_count > api_key_record."rateLimit" THEN
+ RAISE EXCEPTION 'Rate limit exceeded' USING ERRCODE = 'P0001';
+ END IF;
+
+ RETURN TRUE;
+END;
+$$;
+```
+
+**Integration with RLS policies**: Call rate limit check in the centralized helper functions:
+```sql
+-- In get_companies_with_employee_permission():
+IF api_key_company IS NOT NULL THEN
+ -- Check rate limit first
+ PERFORM check_api_key_rate_limit();
+
+ -- Then check scopes...
+END IF;
+```
+
+**Cleanup job** (optional, using pg_cron if available):
+```sql
+-- Delete rate limit entries older than 2 days
+SELECT cron.schedule('cleanup-api-rate-limits', '0 * * * *', $$
+ DELETE FROM "apiKeyRateLimit" WHERE "windowStart" < NOW() - INTERVAL '2 days'
+$$);
+```
+
+#### 4B: Application-Level Rate Limiting
+
+For routes that go through `requirePermissions()`, also check rate limits in the application layer for better error responses (proper 429 status with headers).
+
+Create `packages/auth/src/services/ratelimit.server.ts`:
+
+```typescript
+import { redis } from "@carbon/kv";
+import { Ratelimit } from "@upstash/ratelimit";
+
+export async function checkApiKeyRateLimit(
+ apiKeyId: string,
+ limit: number,
+ window: string
+): Promise<void> {
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(limit, window as "1m" | "1h" | "1d"),
+ prefix: "api-key-rl",
+ });
+
+ const { success, limit: l, remaining, reset } = await ratelimit.limit(apiKeyId);
+
+ if (!success) {
+ throw new Response("Rate limit exceeded", {
+ status: 429,
+ headers: {
+ "X-RateLimit-Limit": l.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ },
+ });
+ }
+}
+```
+
+#### 4C: Supabase Edge Functions Rate Limiting
+
+For Deno edge functions (e.g., `post-sales-invoice`, `import-csv`), add rate limit checks at the function entry point:
+
+```typescript
+// In packages/database/supabase/functions/lib/ratelimit.ts
+import { Redis } from "@upstash/redis";
+import { Ratelimit } from "@upstash/ratelimit";
+
+const redis = new Redis({
+ url: Deno.env.get("UPSTASH_REDIS_REST_URL")!,
+ token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!,
+});
+
+export async function checkRateLimit(
+ apiKeyId: string,
+ limit: number,
+ window: string
+): Promise<{ success: boolean; headers: Record<string, string> }> {
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(limit, window as Duration),
+ prefix: "api-key-rl",
+ });
+
+ const result = await ratelimit.limit(apiKeyId);
+
+ return {
+ success: result.success,
+ headers: {
+ "X-RateLimit-Limit": result.limit.toString(),
+ "X-RateLimit-Remaining": result.remaining.toString(),
+ "X-RateLimit-Reset": result.reset.toString(),
+ }
+ };
+}
+```
+
+Usage in edge functions:
+```typescript
+const auth = await getAuthFromAPIKey(apiKey);
+if (auth) {
+ const rateCheck = await checkRateLimit(auth.apiKeyId, auth.rateLimit, auth.rateLimitWindow);
+ if (!rateCheck.success) {
+ return new Response("Rate limit exceeded", { status: 429, headers: rateCheck.headers });
+ }
+}
+```
+
+### Phase 5: UI Updates
+
+**Files to modify:**
+- `apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx` - Add scope selection and rate limit config
+- `apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx` - Display scope count, rate limit, expiration
+- `apps/erp/app/modules/settings/settings.models.ts` - Update apiKeyValidator with new fields
+- `apps/erp/app/modules/settings/settings.service.ts` - Update upsertApiKey to handle scopes
+
+**New component:**
+- `apps/erp/app/modules/settings/ui/ApiKeys/PermissionMatrix.tsx` - Checkbox grid for module/action selection
+
+### Phase 6: Migration Strategy for Existing API Keys
+
+Grant full access to existing API keys for backward compatibility:
+
+```sql
+UPDATE "apiKey"
+SET "scopes" = (
+ SELECT jsonb_object_agg(
+ permission || '_' || action,
+ jsonb_build_array("companyId")
+ )
+ FROM (
+ SELECT unnest(ARRAY['sales', 'inventory', 'accounting', 'purchasing', 'parts',
+ 'production', 'resources', 'documents', 'settings', 'users',
+ 'people', 'timecards', 'scheduling', 'messaging']) as permission,
+ unnest(ARRAY['view', 'create', 'update', 'delete']) as action
+ ) perms
+)
+WHERE "scopes" = '{}';
+```
+
+## Files to Create/Modify
+
+### Database Layer
+| File | Action | Description |
+|------|--------|-------------|
+| `packages/database/supabase/migrations/XXXXXX_api-key-scopes.sql` | Create | Schema changes (apiKey columns + apiKeyRateLimit table) |
+| `packages/database/supabase/migrations/XXXXXX_api-key-rls-functions.sql` | Create | Scope checking + rate limit SQL functions |
+| `packages/database/supabase/migrations/XXXXXX_update-rls-helpers.sql` | Create | Modify get_companies_* functions for scope/rate limit checks |
+
+### Application Layer
+| File | Action | Description |
+|------|--------|-------------|
+| `packages/auth/src/services/auth.server.ts` | Modify | Add scope checking + rate limiting for API keys |
+| `packages/auth/src/services/ratelimit.server.ts` | Create | Application-level rate limiting utility |
+
+### Edge Functions Layer
+| File | Action | Description |
+|------|--------|-------------|
+| `packages/database/supabase/functions/lib/ratelimit.ts` | Create | Edge function rate limiting utility |
+| `packages/database/supabase/functions/lib/supabase.ts` | Modify | Update getAuthFromAPIKey to return scopes/rate limit config |
+
+### UI Layer
+| File | Action | Description |
+|------|--------|-------------|
+| `apps/erp/app/modules/settings/settings.models.ts` | Modify | Update apiKeyValidator |
+| `apps/erp/app/modules/settings/settings.service.ts` | Modify | Update upsertApiKey |
+| `apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx` | Modify | Add scope/rate limit UI |
+| `apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx` | Modify | Add new columns |
+| `apps/erp/app/modules/settings/ui/ApiKeys/PermissionMatrix.tsx` | Create | Permission selection grid |
+| `apps/erp/app/routes/x+/settings+/api-keys.new.tsx` | Modify | Handle new fields |
+| `apps/erp/app/routes/x+/settings+/api-keys.$id.tsx` | Modify | Handle scope editing |
+
+## Verification
+
+### Schema & Migration
+1. **Database migration**: Run migration, verify columns added to apiKey table
+2. **Rate limit table**: Verify apiKeyRateLimit table created with proper indexes
+3. **Existing API keys**: Verify existing keys get full access scopes (backward compatible)
+
+### Scope Enforcement
+4. **Scope enforcement - RLS (PostgREST)**:
+ - Use API key with only `sales_view` scope
+ - Make direct PostgREST request: `GET /rest/v1/salesOrder` - should succeed
+ - Make direct PostgREST request: `GET /rest/v1/journal` - should fail (no accounting scope)
+5. **Scope enforcement - Application**:
+ - Call route requiring `{ view: "accounting" }` with sales-only key
+ - Verify 403 response
+6. **Scope enforcement - Edge Functions**:
+ - Call `post-sales-invoice` with limited scope key
+ - Verify appropriate scope checking
+
+### Rate Limiting (Dual Layer)
+7. **Rate limiting - Database layer (PostgREST)**:
+ - Create key with limit of 5 requests per minute
+ - Make 6 direct PostgREST requests
+ - Verify 6th request raises PostgreSQL exception
+ - Verify apiKeyRateLimit table tracks request counts correctly
+ - Verify same request ID doesn't double-count
+8. **Rate limiting - Application layer**:
+ - Call route through `requirePermissions()`
+ - Verify 429 response with proper headers (X-RateLimit-*)
+9. **Rate limiting - Edge Functions**:
+ - Call edge function with rate-limited API key
+ - Verify 429 response
+
+### UI
+10. **UI**: Verify permission matrix works correctly, rate limit fields save properly
+11. **New API key creation**: Create key with limited scopes via UI
diff --git a/package-lock.json b/package-lock.json
index 002f0548ef..5508973280 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1680,6 +1680,7 @@
},
"node_modules/@babel/plugin-syntax-async-generators": {
"version": "7.8.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1690,6 +1691,7 @@
},
"node_modules/@babel/plugin-syntax-bigint": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1700,6 +1702,7 @@
},
"node_modules/@babel/plugin-syntax-class-properties": {
"version": "7.12.13",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.12.13"
@@ -1710,6 +1713,7 @@
},
"node_modules/@babel/plugin-syntax-class-static-block": {
"version": "7.14.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.14.5"
@@ -1723,6 +1727,7 @@
},
"node_modules/@babel/plugin-syntax-import-attributes": {
"version": "7.27.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.27.1"
@@ -1736,6 +1741,7 @@
},
"node_modules/@babel/plugin-syntax-import-meta": {
"version": "7.10.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.10.4"
@@ -1746,6 +1752,7 @@
},
"node_modules/@babel/plugin-syntax-json-strings": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1769,6 +1776,7 @@
},
"node_modules/@babel/plugin-syntax-logical-assignment-operators": {
"version": "7.10.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.10.4"
@@ -1779,6 +1787,7 @@
},
"node_modules/@babel/plugin-syntax-nullish-coalescing-operator": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1789,6 +1798,7 @@
},
"node_modules/@babel/plugin-syntax-numeric-separator": {
"version": "7.10.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.10.4"
@@ -1799,6 +1809,7 @@
},
"node_modules/@babel/plugin-syntax-object-rest-spread": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1809,6 +1820,7 @@
},
"node_modules/@babel/plugin-syntax-optional-catch-binding": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1819,6 +1831,7 @@
},
"node_modules/@babel/plugin-syntax-optional-chaining": {
"version": "7.8.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.8.0"
@@ -1829,6 +1842,7 @@
},
"node_modules/@babel/plugin-syntax-private-property-in-object": {
"version": "7.14.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.14.5"
@@ -1842,6 +1856,7 @@
},
"node_modules/@babel/plugin-syntax-top-level-await": {
"version": "7.14.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-plugin-utils": "^7.14.5"
@@ -1962,6 +1977,7 @@
},
"node_modules/@bcoe/v8-coverage": {
"version": "0.2.3",
+ "dev": true,
"license": "MIT"
},
"node_modules/@biomejs/biome": {
@@ -2212,6 +2228,7 @@
},
"node_modules/@cnakazawa/watch": {
"version": "1.0.4",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"exec-sh": "^0.3.2",
@@ -2226,6 +2243,7 @@
},
"node_modules/@csstools/selector-resolve-nested": {
"version": "1.1.0",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -2246,6 +2264,7 @@
},
"node_modules/@csstools/selector-specificity": {
"version": "3.1.1",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -3086,6 +3105,7 @@
},
"node_modules/@isaacs/fs-minipass": {
"version": "4.0.1",
+ "dev": true,
"license": "ISC",
"dependencies": {
"minipass": "^7.0.4"
@@ -3096,6 +3116,7 @@
},
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"camelcase": "^5.3.1",
@@ -3110,6 +3131,7 @@
},
"node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": {
"version": "5.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3117,6 +3139,7 @@
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.3",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3124,6 +3147,7 @@
},
"node_modules/@jest/console": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -3139,6 +3163,7 @@
},
"node_modules/@jest/console/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -3152,6 +3177,7 @@
},
"node_modules/@jest/console/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -3166,6 +3192,7 @@
},
"node_modules/@jest/console/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -3176,10 +3203,12 @@
},
"node_modules/@jest/console/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/@jest/console/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3187,6 +3216,7 @@
},
"node_modules/@jest/core": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/console": "^26.6.2",
@@ -3224,6 +3254,7 @@
},
"node_modules/@jest/core/node_modules/ansi-escapes": {
"version": "4.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"type-fest": "^0.21.3"
@@ -3237,6 +3268,7 @@
},
"node_modules/@jest/core/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -3250,6 +3282,7 @@
},
"node_modules/@jest/core/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -3264,6 +3297,7 @@
},
"node_modules/@jest/core/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -3274,10 +3308,12 @@
},
"node_modules/@jest/core/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/@jest/core/node_modules/glob": {
"version": "7.2.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -3296,6 +3332,7 @@
},
"node_modules/@jest/core/node_modules/rimraf": {
"version": "3.0.2",
+ "dev": true,
"license": "ISC",
"dependencies": {
"glob": "^7.1.3"
@@ -3309,6 +3346,7 @@
},
"node_modules/@jest/core/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3316,6 +3354,7 @@
},
"node_modules/@jest/core/node_modules/strip-ansi": {
"version": "6.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -3326,6 +3365,7 @@
},
"node_modules/@jest/core/node_modules/type-fest": {
"version": "0.21.3",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=10"
@@ -3336,6 +3376,7 @@
},
"node_modules/@jest/environment": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/fake-timers": "^26.6.2",
@@ -3349,6 +3390,7 @@
},
"node_modules/@jest/fake-timers": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -3364,6 +3406,7 @@
},
"node_modules/@jest/globals": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/environment": "^26.6.2",
@@ -3376,6 +3419,7 @@
},
"node_modules/@jest/reporters": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^0.2.3",
@@ -3412,6 +3456,7 @@
},
"node_modules/@jest/reporters/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -3425,6 +3470,7 @@
},
"node_modules/@jest/reporters/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -3439,6 +3485,7 @@
},
"node_modules/@jest/reporters/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -3449,10 +3496,12 @@
},
"node_modules/@jest/reporters/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/@jest/reporters/node_modules/glob": {
"version": "7.2.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -3471,6 +3520,7 @@
},
"node_modules/@jest/reporters/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3478,6 +3528,7 @@
},
"node_modules/@jest/reporters/node_modules/source-map": {
"version": "0.6.1",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -3485,6 +3536,7 @@
},
"node_modules/@jest/source-map": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"callsites": "^3.0.0",
@@ -3497,6 +3549,7 @@
},
"node_modules/@jest/source-map/node_modules/source-map": {
"version": "0.6.1",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -3504,6 +3557,7 @@
},
"node_modules/@jest/test-result": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/console": "^26.6.2",
@@ -3517,6 +3571,7 @@
},
"node_modules/@jest/test-sequencer": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/test-result": "^26.6.2",
@@ -3531,6 +3586,7 @@
},
"node_modules/@jest/transform": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/core": "^7.1.0",
@@ -3555,6 +3611,7 @@
},
"node_modules/@jest/transform/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -3568,6 +3625,7 @@
},
"node_modules/@jest/transform/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -3582,6 +3640,7 @@
},
"node_modules/@jest/transform/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -3592,10 +3651,12 @@
},
"node_modules/@jest/transform/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/@jest/transform/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3603,6 +3664,7 @@
},
"node_modules/@jest/transform/node_modules/source-map": {
"version": "0.6.1",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -8518,70 +8580,6 @@
"version": "0.9.0",
"license": "MIT"
},
- "node_modules/@remix-run/router": {
- "version": "1.23.2",
- "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
- "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
- "license": "MIT",
- "peer": true,
- "engines": {
- "node": ">=14.0.0"
- }
- },
- "node_modules/@remix-run/server-runtime": {
- "version": "2.17.4",
- "resolved": "https://registry.npmjs.org/@remix-run/server-runtime/-/server-runtime-2.17.4.tgz",
- "integrity": "sha512-oCsFbPuISgh8KpPKsfBChzjcntvTz5L+ggq9VNYWX8RX3yA7OgQpKspRHOSxb05bw7m0Hx+L1KRHXjf3juKX8w==",
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "@remix-run/router": "1.23.2",
- "@types/cookie": "^0.6.0",
- "@web3-storage/multipart-parser": "^1.0.0",
- "cookie": "^0.7.2",
- "set-cookie-parser": "^2.4.8",
- "source-map": "^0.7.3",
- "turbo-stream": "2.4.1"
- },
- "engines": {
- "node": ">=18.0.0"
- },
- "peerDependencies": {
- "typescript": "^5.1.0"
- },
- "peerDependenciesMeta": {
- "typescript": {
- "optional": true
- }
- }
- },
- "node_modules/@remix-run/server-runtime/node_modules/@types/cookie": {
- "version": "0.6.0",
- "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
- "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
- "license": "MIT",
- "peer": true
- },
- "node_modules/@remix-run/server-runtime/node_modules/cookie": {
- "version": "0.7.2",
- "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
- "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
- "license": "MIT",
- "peer": true,
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/@remix-run/server-runtime/node_modules/source-map": {
- "version": "0.7.6",
- "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
- "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
- "license": "BSD-3-Clause",
- "peer": true,
- "engines": {
- "node": ">= 12"
- }
- },
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.55.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.55.1.tgz",
@@ -8944,6 +8942,73 @@
"url": "https://ko-fi.com/killymxi"
}
},
+ "node_modules/@shikijs/core": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.23.0.tgz",
+ "integrity": "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "3.23.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4",
+ "hast-util-to-html": "^9.0.5"
+ }
+ },
+ "node_modules/@shikijs/engine-javascript": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.23.0.tgz",
+ "integrity": "sha512-aHt9eiGFobmWR5uqJUViySI1bHMqrAgamWE1TYSUoftkAeCCAiGawPMwM+VCadylQtF4V3VNOZ5LmfItH5f3yA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "3.23.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "oniguruma-to-es": "^4.3.4"
+ }
+ },
+ "node_modules/@shikijs/engine-oniguruma": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.23.0.tgz",
+ "integrity": "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "3.23.0",
+ "@shikijs/vscode-textmate": "^10.0.2"
+ }
+ },
+ "node_modules/@shikijs/langs": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.23.0.tgz",
+ "integrity": "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "3.23.0"
+ }
+ },
+ "node_modules/@shikijs/themes": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.23.0.tgz",
+ "integrity": "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "3.23.0"
+ }
+ },
+ "node_modules/@shikijs/types": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.23.0.tgz",
+ "integrity": "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4"
+ }
+ },
+ "node_modules/@shikijs/vscode-textmate": {
+ "version": "10.0.2",
+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",
+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",
+ "license": "MIT"
+ },
"node_modules/@sideway/address": {
"version": "4.1.5",
"dev": true,
@@ -8981,6 +9046,7 @@
},
"node_modules/@sinonjs/commons": {
"version": "1.8.6",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"type-detect": "4.0.8"
@@ -8988,6 +9054,7 @@
},
"node_modules/@sinonjs/fake-timers": {
"version": "6.0.1",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/commons": "^1.7.0"
@@ -9969,6 +10036,7 @@
},
"node_modules/@tootallnate/once": {
"version": "1.1.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
@@ -10266,6 +10334,7 @@
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.20.7",
@@ -10277,6 +10346,7 @@
},
"node_modules/@types/babel__generator": {
"version": "7.27.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.0.0"
@@ -10284,6 +10354,7 @@
},
"node_modules/@types/babel__template": {
"version": "7.4.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.1.0",
@@ -10292,6 +10363,7 @@
},
"node_modules/@types/babel__traverse": {
"version": "7.28.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.28.2"
@@ -10572,6 +10644,7 @@
},
"node_modules/@types/graceful-fs": {
"version": "4.1.9",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
@@ -10681,6 +10754,7 @@
},
"node_modules/@types/normalize-package-data": {
"version": "2.4.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/nprogress": {
@@ -10706,10 +10780,7 @@
},
"node_modules/@types/prettier": {
"version": "2.7.3",
- "license": "MIT"
- },
- "node_modules/@types/prismjs": {
- "version": "1.26.5",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/prop-types": {
@@ -10734,7 +10805,7 @@
},
"node_modules/@types/react-dom": {
"version": "18.3.7",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
@@ -10761,6 +10832,7 @@
},
"node_modules/@types/stack-utils": {
"version": "2.0.3",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/strip-bom": {
@@ -11336,13 +11408,6 @@
"node": ">=12"
}
},
- "node_modules/@web3-storage/multipart-parser": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz",
- "integrity": "sha512-BEO6al7BYqcnfX15W2cnGR+Q566ACXAT9UQykORCWW80lmkpWsnEob6zJS1ZVBKsSJC8+7vJkHwlp+lXG1UCdw==",
- "license": "(Apache-2.0 AND MIT)",
- "peer": true
- },
"node_modules/@xyflow/react": {
"version": "12.10.0",
"license": "MIT",
@@ -11404,6 +11469,7 @@
},
"node_modules/abab": {
"version": "2.0.6",
+ "dev": true,
"license": "BSD-3-Clause"
},
"node_modules/abbrev": {
@@ -11442,6 +11508,7 @@
},
"node_modules/acorn-globals": {
"version": "6.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^7.1.1",
@@ -11450,6 +11517,7 @@
},
"node_modules/acorn-globals/node_modules/acorn": {
"version": "7.4.1",
+ "dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
@@ -11467,6 +11535,7 @@
},
"node_modules/acorn-walk": {
"version": "7.2.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
@@ -11474,6 +11543,7 @@
},
"node_modules/agent-base": {
"version": "6.0.2",
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"debug": "4"
@@ -11609,6 +11679,7 @@
},
"node_modules/argparse": {
"version": "1.0.10",
+ "dev": true,
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
@@ -11634,6 +11705,7 @@
},
"node_modules/arr-diff": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -11641,6 +11713,7 @@
},
"node_modules/arr-flatten": {
"version": "1.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -11648,6 +11721,7 @@
},
"node_modules/arr-union": {
"version": "3.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -11684,6 +11758,7 @@
},
"node_modules/array-unique": {
"version": "0.3.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -11715,6 +11790,7 @@
},
"node_modules/assign-symbols": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -11734,6 +11810,7 @@
},
"node_modules/atob": {
"version": "2.1.2",
+ "dev": true,
"license": "(MIT OR Apache-2.0)",
"bin": {
"atob": "bin/atob.js"
@@ -11846,6 +11923,7 @@
},
"node_modules/babel-jest": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/transform": "^26.6.2",
@@ -11866,6 +11944,7 @@
},
"node_modules/babel-jest/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -11879,6 +11958,7 @@
},
"node_modules/babel-jest/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -11893,6 +11973,7 @@
},
"node_modules/babel-jest/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -11903,10 +11984,12 @@
},
"node_modules/babel-jest/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/babel-jest/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -11914,6 +11997,7 @@
},
"node_modules/babel-plugin-istanbul": {
"version": "6.1.1",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@babel/helper-plugin-utils": "^7.0.0",
@@ -11928,6 +12012,7 @@
},
"node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": {
"version": "5.2.1",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@babel/core": "^7.12.3",
@@ -11942,6 +12027,7 @@
},
"node_modules/babel-plugin-istanbul/node_modules/semver": {
"version": "6.3.1",
+ "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -11949,6 +12035,7 @@
},
"node_modules/babel-plugin-jest-hoist": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.3.3",
@@ -11975,6 +12062,7 @@
},
"node_modules/babel-preset-current-node-syntax": {
"version": "1.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/plugin-syntax-async-generators": "^7.8.4",
@@ -11999,6 +12087,7 @@
},
"node_modules/babel-preset-jest": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"babel-plugin-jest-hoist": "^26.6.2",
@@ -12025,6 +12114,7 @@
},
"node_modules/base": {
"version": "0.11.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cache-base": "^1.0.1",
@@ -12041,6 +12131,7 @@
},
"node_modules/base/node_modules/define-property": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^1.0.0"
@@ -12166,6 +12257,7 @@
},
"node_modules/bin-links": {
"version": "6.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"cmd-shim": "^8.0.0",
@@ -12180,6 +12272,7 @@
},
"node_modules/bin-links/node_modules/signal-exit": {
"version": "4.1.0",
+ "dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
@@ -12190,6 +12283,7 @@
},
"node_modules/bin-links/node_modules/write-file-atomic": {
"version": "7.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"imurmurhash": "^0.1.4",
@@ -12297,6 +12391,7 @@
},
"node_modules/browser-process-hrtime": {
"version": "1.0.0",
+ "dev": true,
"license": "BSD-2-Clause"
},
"node_modules/browserify-zlib": {
@@ -12349,6 +12444,7 @@
},
"node_modules/bser": {
"version": "2.1.1",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"node-int64": "^0.4.0"
@@ -12405,6 +12501,7 @@
},
"node_modules/cache-base": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"collection-visit": "^1.0.0",
@@ -12471,6 +12568,7 @@
},
"node_modules/camelcase": {
"version": "5.3.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -12517,6 +12615,7 @@
},
"node_modules/capture-exit": {
"version": "2.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"rsvp": "^4.8.4"
@@ -12545,6 +12644,7 @@
},
"node_modules/char-regex": {
"version": "1.0.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -12627,6 +12727,7 @@
},
"node_modules/class-utils": {
"version": "0.3.6",
+ "dev": true,
"license": "MIT",
"dependencies": {
"arr-union": "^3.1.0",
@@ -12640,6 +12741,7 @@
},
"node_modules/class-utils/node_modules/define-property": {
"version": "0.2.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^0.1.0"
@@ -12650,6 +12752,7 @@
},
"node_modules/class-utils/node_modules/is-descriptor": {
"version": "0.1.7",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -12708,6 +12811,7 @@
},
"node_modules/cliui": {
"version": "6.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
@@ -12717,6 +12821,7 @@
},
"node_modules/cliui/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -12730,6 +12835,7 @@
},
"node_modules/cliui/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -12740,14 +12846,17 @@
},
"node_modules/cliui/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/cliui/node_modules/emoji-regex": {
"version": "8.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/cliui/node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -12755,6 +12864,7 @@
},
"node_modules/cliui/node_modules/string-width": {
"version": "4.2.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -12767,6 +12877,7 @@
},
"node_modules/cliui/node_modules/strip-ansi": {
"version": "6.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -12777,6 +12888,7 @@
},
"node_modules/cliui/node_modules/wrap-ansi": {
"version": "6.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
@@ -12803,6 +12915,7 @@
},
"node_modules/cmd-shim": {
"version": "8.0.0",
+ "dev": true,
"license": "ISC",
"engines": {
"node": "^20.17.0 || >=22.9.0"
@@ -13038,6 +13151,7 @@
},
"node_modules/co": {
"version": "4.6.0",
+ "dev": true,
"license": "MIT",
"engines": {
"iojs": ">= 1.0.0",
@@ -13051,10 +13165,12 @@
},
"node_modules/collect-v8-coverage": {
"version": "1.0.3",
+ "dev": true,
"license": "MIT"
},
"node_modules/collection-visit": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"map-visit": "^1.0.0",
@@ -13129,6 +13245,7 @@
},
"node_modules/component-emitter": {
"version": "1.3.1",
+ "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
@@ -13260,6 +13377,7 @@
},
"node_modules/copy-descriptor": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -13411,10 +13529,12 @@
},
"node_modules/cssom": {
"version": "0.4.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/cssstyle": {
"version": "2.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cssom": "~0.3.6"
@@ -13425,6 +13545,7 @@
},
"node_modules/cssstyle/node_modules/cssom": {
"version": "0.3.8",
+ "dev": true,
"license": "MIT"
},
"node_modules/csstype": {
@@ -13796,6 +13917,7 @@
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 12"
@@ -13803,6 +13925,7 @@
},
"node_modules/data-urls": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"abab": "^2.0.3",
@@ -13815,6 +13938,7 @@
},
"node_modules/data-urls/node_modules/tr46": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"punycode": "^2.1.1"
@@ -13825,6 +13949,7 @@
},
"node_modules/data-urls/node_modules/whatwg-url": {
"version": "8.7.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"lodash": "^4.7.0",
@@ -13900,6 +14025,7 @@
},
"node_modules/decamelize": {
"version": "1.2.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -13926,6 +14052,7 @@
},
"node_modules/decode-uri-component": {
"version": "0.2.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10"
@@ -14032,6 +14159,7 @@
},
"node_modules/define-property": {
"version": "2.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^1.0.2",
@@ -14094,6 +14222,7 @@
},
"node_modules/detect-newline": {
"version": "3.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -14124,6 +14253,7 @@
},
"node_modules/diff-sequences": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.14.2"
@@ -14196,6 +14326,7 @@
},
"node_modules/domexception": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"webidl-conversions": "^5.0.0"
@@ -14206,6 +14337,7 @@
},
"node_modules/domexception/node_modules/webidl-conversions": {
"version": "5.0.0",
+ "dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=8"
@@ -14349,6 +14481,7 @@
},
"node_modules/emittery": {
"version": "0.7.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -14374,6 +14507,7 @@
},
"node_modules/end-of-stream": {
"version": "1.4.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
@@ -14719,6 +14853,7 @@
},
"node_modules/escodegen": {
"version": "2.1.0",
+ "dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"esprima": "^4.0.1",
@@ -14738,6 +14873,7 @@
},
"node_modules/escodegen/node_modules/source-map": {
"version": "0.6.1",
+ "dev": true,
"license": "BSD-3-Clause",
"optional": true,
"engines": {
@@ -14746,6 +14882,7 @@
},
"node_modules/esprima": {
"version": "4.0.1",
+ "dev": true,
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
@@ -14757,6 +14894,7 @@
},
"node_modules/estraverse": {
"version": "5.3.0",
+ "dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=4.0"
@@ -14772,6 +14910,7 @@
},
"node_modules/esutils": {
"version": "2.0.3",
+ "dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.10.0"
@@ -14823,6 +14962,7 @@
},
"node_modules/exec-sh": {
"version": "0.3.6",
+ "dev": true,
"license": "MIT"
},
"node_modules/execa": {
@@ -14849,6 +14989,7 @@
},
"node_modules/exit": {
"version": "0.1.2",
+ "dev": true,
"engines": {
"node": ">= 0.8.0"
}
@@ -14865,6 +15006,7 @@
},
"node_modules/expand-brackets": {
"version": "2.1.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"debug": "^2.3.3",
@@ -14881,6 +15023,7 @@
},
"node_modules/expand-brackets/node_modules/debug": {
"version": "2.6.9",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
@@ -14888,6 +15031,7 @@
},
"node_modules/expand-brackets/node_modules/define-property": {
"version": "0.2.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^0.1.0"
@@ -14898,6 +15042,7 @@
},
"node_modules/expand-brackets/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -14908,6 +15053,7 @@
},
"node_modules/expand-brackets/node_modules/is-descriptor": {
"version": "0.1.7",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -14919,6 +15065,7 @@
},
"node_modules/expand-brackets/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -14926,10 +15073,12 @@
},
"node_modules/expand-brackets/node_modules/ms": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/expect": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -14945,6 +15094,7 @@
},
"node_modules/expect/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -14958,6 +15108,7 @@
},
"node_modules/expect/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -14968,6 +15119,7 @@
},
"node_modules/expect/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/express": {
@@ -15060,6 +15212,7 @@
},
"node_modules/extend-shallow": {
"version": "3.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"assign-symbols": "^1.0.0",
@@ -15071,6 +15224,7 @@
},
"node_modules/extglob": {
"version": "2.0.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"array-unique": "^0.3.2",
@@ -15088,6 +15242,7 @@
},
"node_modules/extglob/node_modules/define-property": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^1.0.0"
@@ -15098,6 +15253,7 @@
},
"node_modules/extglob/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -15108,6 +15264,7 @@
},
"node_modules/extglob/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -15198,6 +15355,7 @@
},
"node_modules/fb-watchman": {
"version": "2.0.2",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"bser": "2.1.1"
@@ -15220,6 +15378,7 @@
},
"node_modules/fetch-blob": {
"version": "3.2.0",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -15307,6 +15466,7 @@
},
"node_modules/find-up": {
"version": "4.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"locate-path": "^5.0.0",
@@ -15372,6 +15532,7 @@
},
"node_modules/for-in": {
"version": "1.0.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -15434,6 +15595,7 @@
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
+ "dev": true,
"license": "MIT",
"dependencies": {
"fetch-blob": "^3.1.2"
@@ -15462,6 +15624,7 @@
},
"node_modules/fragment-cache": {
"version": "0.2.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"map-cache": "^0.2.2"
@@ -15543,6 +15706,7 @@
},
"node_modules/fs.realpath": {
"version": "1.0.0",
+ "devOptional": true,
"license": "ISC"
},
"node_modules/fsevents": {
@@ -15670,6 +15834,7 @@
},
"node_modules/get-caller-file": {
"version": "2.0.5",
+ "dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
@@ -15706,6 +15871,7 @@
},
"node_modules/get-package-type": {
"version": "0.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8.0.0"
@@ -15763,7 +15929,7 @@
},
"node_modules/get-tsconfig": {
"version": "4.13.0",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"dependencies": {
"resolve-pkg-maps": "^1.0.0"
@@ -15774,6 +15940,7 @@
},
"node_modules/get-value": {
"version": "2.0.6",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -15897,6 +16064,7 @@
},
"node_modules/growly": {
"version": "1.3.0",
+ "dev": true,
"license": "MIT",
"optional": true
},
@@ -15998,6 +16166,7 @@
},
"node_modules/has-value": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"get-value": "^2.0.6",
@@ -16010,6 +16179,7 @@
},
"node_modules/has-values": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^3.0.0",
@@ -16021,6 +16191,7 @@
},
"node_modules/has-values/node_modules/is-number": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"kind-of": "^3.0.2"
@@ -16031,6 +16202,7 @@
},
"node_modules/has-values/node_modules/is-number/node_modules/kind-of": {
"version": "3.2.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -16041,6 +16213,7 @@
},
"node_modules/has-values/node_modules/kind-of": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -16144,11 +16317,34 @@
"url": "https://opencollective.com/unified"
}
},
- "node_modules/hast-util-to-jsx-runtime": {
- "version": "2.3.6",
+ "node_modules/hast-util-to-html": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",
"license": "MIT",
"dependencies": {
- "@types/estree": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "html-void-elements": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "stringify-entities": "^4.0.0",
+ "zwitch": "^2.0.4"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-jsx-runtime": {
+ "version": "2.3.6",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
"@types/hast": "^3.0.0",
"@types/unist": "^3.0.0",
"comma-separated-tokens": "^2.0.0",
@@ -16232,6 +16428,7 @@
},
"node_modules/hosted-git-info": {
"version": "2.8.9",
+ "dev": true,
"license": "ISC"
},
"node_modules/hsl-to-hex": {
@@ -16247,6 +16444,7 @@
},
"node_modules/html-encoding-sniffer": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"whatwg-encoding": "^1.0.5"
@@ -16257,6 +16455,7 @@
},
"node_modules/html-escaper": {
"version": "2.0.2",
+ "dev": true,
"license": "MIT"
},
"node_modules/html-to-text": {
@@ -16326,6 +16525,7 @@
},
"node_modules/http-proxy-agent": {
"version": "4.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@tootallnate/once": "1",
@@ -16338,6 +16538,7 @@
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"agent-base": "6",
@@ -16445,6 +16646,7 @@
},
"node_modules/import-local": {
"version": "3.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"pkg-dir": "^4.2.0",
@@ -16462,6 +16664,7 @@
},
"node_modules/imurmurhash": {
"version": "0.1.4",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.8.19"
@@ -16469,6 +16672,7 @@
},
"node_modules/inflight": {
"version": "1.0.6",
+ "devOptional": true,
"license": "ISC",
"dependencies": {
"once": "^1.3.0",
@@ -16560,6 +16764,7 @@
},
"node_modules/is-accessor-descriptor": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.0"
@@ -16681,6 +16886,7 @@
},
"node_modules/is-buffer": {
"version": "1.1.6",
+ "dev": true,
"license": "MIT"
},
"node_modules/is-callable": {
@@ -16722,6 +16928,7 @@
},
"node_modules/is-data-descriptor": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.0"
@@ -16771,6 +16978,7 @@
},
"node_modules/is-descriptor": {
"version": "1.0.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -16782,7 +16990,7 @@
},
"node_modules/is-docker": {
"version": "2.2.1",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"bin": {
"is-docker": "cli.js"
@@ -16800,6 +17008,7 @@
},
"node_modules/is-extendable": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-plain-object": "^2.0.4"
@@ -16810,6 +17019,7 @@
},
"node_modules/is-extendable/node_modules/is-plain-object": {
"version": "2.0.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"isobject": "^3.0.1"
@@ -16852,6 +17062,7 @@
},
"node_modules/is-generator-fn": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -16959,6 +17170,7 @@
},
"node_modules/is-potential-custom-element-name": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT"
},
"node_modules/is-promise": {
@@ -17072,6 +17284,7 @@
},
"node_modules/is-typedarray": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/is-url": {
@@ -17130,6 +17343,7 @@
},
"node_modules/is-windows": {
"version": "1.0.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -17137,7 +17351,7 @@
},
"node_modules/is-wsl": {
"version": "2.2.0",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-docker": "^2.0.0"
@@ -17164,6 +17378,7 @@
},
"node_modules/isobject": {
"version": "3.0.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -17171,6 +17386,7 @@
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
@@ -17178,6 +17394,7 @@
},
"node_modules/istanbul-lib-instrument": {
"version": "4.0.3",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@babel/core": "^7.7.5",
@@ -17191,6 +17408,7 @@
},
"node_modules/istanbul-lib-instrument/node_modules/semver": {
"version": "6.3.1",
+ "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -17198,6 +17416,7 @@
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
@@ -17210,6 +17429,7 @@
},
"node_modules/istanbul-lib-source-maps": {
"version": "4.0.1",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"debug": "^4.1.1",
@@ -17222,6 +17442,7 @@
},
"node_modules/istanbul-lib-source-maps/node_modules/source-map": {
"version": "0.6.1",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -17229,6 +17450,7 @@
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
@@ -17260,6 +17482,7 @@
},
"node_modules/jest": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/core": "^26.6.3",
@@ -17275,6 +17498,7 @@
},
"node_modules/jest-changed-files": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17287,6 +17511,7 @@
},
"node_modules/jest-changed-files/node_modules/execa": {
"version": "4.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.0",
@@ -17308,6 +17533,7 @@
},
"node_modules/jest-changed-files/node_modules/get-stream": {
"version": "5.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"pump": "^3.0.0"
@@ -17321,6 +17547,7 @@
},
"node_modules/jest-changed-files/node_modules/human-signals": {
"version": "1.1.1",
+ "dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8.12.0"
@@ -17328,6 +17555,7 @@
},
"node_modules/jest-changed-files/node_modules/is-stream": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -17338,6 +17566,7 @@
},
"node_modules/jest-changed-files/node_modules/mimic-fn": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -17345,6 +17574,7 @@
},
"node_modules/jest-changed-files/node_modules/npm-run-path": {
"version": "4.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.0.0"
@@ -17355,6 +17585,7 @@
},
"node_modules/jest-changed-files/node_modules/onetime": {
"version": "5.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"mimic-fn": "^2.1.0"
@@ -17368,6 +17599,7 @@
},
"node_modules/jest-changed-files/node_modules/strip-final-newline": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -17375,6 +17607,7 @@
},
"node_modules/jest-cli": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/core": "^26.6.3",
@@ -17400,6 +17633,7 @@
},
"node_modules/jest-cli/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17413,6 +17647,7 @@
},
"node_modules/jest-cli/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17427,6 +17662,7 @@
},
"node_modules/jest-cli/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17437,10 +17673,12 @@
},
"node_modules/jest-cli/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-config": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/core": "^7.1.0",
@@ -17476,6 +17714,7 @@
},
"node_modules/jest-config/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17489,6 +17728,7 @@
},
"node_modules/jest-config/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17503,6 +17743,7 @@
},
"node_modules/jest-config/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17513,10 +17754,12 @@
},
"node_modules/jest-config/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-config/node_modules/glob": {
"version": "7.2.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -17535,6 +17778,7 @@
},
"node_modules/jest-diff": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"chalk": "^4.0.0",
@@ -17548,6 +17792,7 @@
},
"node_modules/jest-diff/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17561,6 +17806,7 @@
},
"node_modules/jest-diff/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17575,6 +17821,7 @@
},
"node_modules/jest-diff/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17585,10 +17832,12 @@
},
"node_modules/jest-diff/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-docblock": {
"version": "26.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"detect-newline": "^3.0.0"
@@ -17599,6 +17848,7 @@
},
"node_modules/jest-each": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17613,6 +17863,7 @@
},
"node_modules/jest-each/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17626,6 +17877,7 @@
},
"node_modules/jest-each/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17640,6 +17892,7 @@
},
"node_modules/jest-each/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17650,10 +17903,12 @@
},
"node_modules/jest-each/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-environment-jsdom": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/environment": "^26.6.2",
@@ -17670,6 +17925,7 @@
},
"node_modules/jest-environment-node": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/environment": "^26.6.2",
@@ -17685,6 +17941,7 @@
},
"node_modules/jest-get-type": {
"version": "26.3.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.14.2"
@@ -17692,6 +17949,7 @@
},
"node_modules/jest-haste-map": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17717,6 +17975,7 @@
},
"node_modules/jest-jasmine2": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/traverse": "^7.1.0",
@@ -17744,6 +18003,7 @@
},
"node_modules/jest-jasmine2/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17757,6 +18017,7 @@
},
"node_modules/jest-jasmine2/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17771,6 +18032,7 @@
},
"node_modules/jest-jasmine2/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17781,10 +18043,12 @@
},
"node_modules/jest-jasmine2/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-leak-detector": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"jest-get-type": "^26.3.0",
@@ -17796,6 +18060,7 @@
},
"node_modules/jest-matcher-utils": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"chalk": "^4.0.0",
@@ -17809,6 +18074,7 @@
},
"node_modules/jest-matcher-utils/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17822,6 +18088,7 @@
},
"node_modules/jest-matcher-utils/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17836,6 +18103,7 @@
},
"node_modules/jest-matcher-utils/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17846,10 +18114,12 @@
},
"node_modules/jest-matcher-utils/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-message-util": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.0.0",
@@ -17868,6 +18138,7 @@
},
"node_modules/jest-message-util/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17881,6 +18152,7 @@
},
"node_modules/jest-message-util/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -17895,6 +18167,7 @@
},
"node_modules/jest-message-util/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -17905,10 +18178,12 @@
},
"node_modules/jest-message-util/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-message-util/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -17916,6 +18191,7 @@
},
"node_modules/jest-mock": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17927,6 +18203,7 @@
},
"node_modules/jest-pnp-resolver": {
"version": "1.2.3",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -17942,6 +18219,7 @@
},
"node_modules/jest-regex-util": {
"version": "26.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.14.2"
@@ -17949,6 +18227,7 @@
},
"node_modules/jest-resolve": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17966,6 +18245,7 @@
},
"node_modules/jest-resolve-dependencies": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -17978,6 +18258,7 @@
},
"node_modules/jest-resolve/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -17991,6 +18272,7 @@
},
"node_modules/jest-resolve/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18005,6 +18287,7 @@
},
"node_modules/jest-resolve/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18015,10 +18298,12 @@
},
"node_modules/jest-resolve/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-resolve/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -18026,6 +18311,7 @@
},
"node_modules/jest-runner": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/console": "^26.6.2",
@@ -18055,6 +18341,7 @@
},
"node_modules/jest-runner/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -18068,6 +18355,7 @@
},
"node_modules/jest-runner/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18082,6 +18370,7 @@
},
"node_modules/jest-runner/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18092,10 +18381,12 @@
},
"node_modules/jest-runner/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-runtime": {
"version": "26.6.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/console": "^26.6.2",
@@ -18135,6 +18426,7 @@
},
"node_modules/jest-runtime/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -18148,6 +18440,7 @@
},
"node_modules/jest-runtime/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18162,10 +18455,12 @@
},
"node_modules/jest-runtime/node_modules/cjs-module-lexer": {
"version": "0.6.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-runtime/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18176,10 +18471,12 @@
},
"node_modules/jest-runtime/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-runtime/node_modules/glob": {
"version": "7.2.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -18198,6 +18495,7 @@
},
"node_modules/jest-runtime/node_modules/slash": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -18205,6 +18503,7 @@
},
"node_modules/jest-runtime/node_modules/strip-bom": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -18212,6 +18511,7 @@
},
"node_modules/jest-serializer": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
@@ -18223,6 +18523,7 @@
},
"node_modules/jest-snapshot": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.0.0",
@@ -18248,6 +18549,7 @@
},
"node_modules/jest-snapshot/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -18261,6 +18563,7 @@
},
"node_modules/jest-snapshot/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18275,6 +18578,7 @@
},
"node_modules/jest-snapshot/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18285,6 +18589,7 @@
},
"node_modules/jest-snapshot/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-util": {
@@ -18345,6 +18650,7 @@
},
"node_modules/jest-validate": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -18360,6 +18666,7 @@
},
"node_modules/jest-validate/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -18373,6 +18680,7 @@
},
"node_modules/jest-validate/node_modules/camelcase": {
"version": "6.3.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -18383,6 +18691,7 @@
},
"node_modules/jest-validate/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18397,6 +18706,7 @@
},
"node_modules/jest-validate/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18407,10 +18717,12 @@
},
"node_modules/jest-validate/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-watcher": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/test-result": "^26.6.2",
@@ -18427,6 +18739,7 @@
},
"node_modules/jest-watcher/node_modules/ansi-escapes": {
"version": "4.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"type-fest": "^0.21.3"
@@ -18440,6 +18753,7 @@
},
"node_modules/jest-watcher/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -18453,6 +18767,7 @@
},
"node_modules/jest-watcher/node_modules/chalk": {
"version": "4.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -18467,6 +18782,7 @@
},
"node_modules/jest-watcher/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -18477,10 +18793,12 @@
},
"node_modules/jest-watcher/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/jest-watcher/node_modules/type-fest": {
"version": "0.21.3",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=10"
@@ -18491,6 +18809,7 @@
},
"node_modules/jest-worker": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
@@ -18621,6 +18940,7 @@
},
"node_modules/js-yaml": {
"version": "3.14.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
@@ -18632,6 +18952,7 @@
},
"node_modules/jsdom": {
"version": "16.7.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"abab": "^2.0.5",
@@ -18676,6 +18997,7 @@
},
"node_modules/jsdom/node_modules/form-data": {
"version": "3.0.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
@@ -18690,6 +19012,7 @@
},
"node_modules/jsdom/node_modules/mime-db": {
"version": "1.52.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -18697,6 +19020,7 @@
},
"node_modules/jsdom/node_modules/mime-types": {
"version": "2.1.35",
+ "dev": true,
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
@@ -18707,6 +19031,7 @@
},
"node_modules/jsdom/node_modules/tr46": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"punycode": "^2.1.1"
@@ -18717,6 +19042,7 @@
},
"node_modules/jsdom/node_modules/whatwg-url": {
"version": "8.7.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"lodash": "^4.7.0",
@@ -18729,6 +19055,7 @@
},
"node_modules/jsdom/node_modules/ws": {
"version": "7.5.10",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8.3.0"
@@ -18910,6 +19237,7 @@
},
"node_modules/kind-of": {
"version": "6.0.3",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -18925,6 +19253,7 @@
},
"node_modules/kleur": {
"version": "3.0.3",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -19126,6 +19455,7 @@
},
"node_modules/locate-path": {
"version": "5.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"p-locate": "^4.1.0"
@@ -19267,6 +19597,7 @@
},
"node_modules/make-dir": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
@@ -19291,6 +19622,7 @@
},
"node_modules/makeerror": {
"version": "1.0.12",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"tmpl": "1.0.5"
@@ -19298,6 +19630,7 @@
},
"node_modules/map-cache": {
"version": "0.2.2",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -19305,6 +19638,7 @@
},
"node_modules/map-visit": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"object-visit": "^1.0.0"
@@ -20340,6 +20674,7 @@
},
"node_modules/mixin-deep": {
"version": "1.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"for-in": "^1.0.2",
@@ -20497,6 +20832,7 @@
},
"node_modules/nanomatch": {
"version": "1.2.13",
+ "dev": true,
"license": "MIT",
"dependencies": {
"arr-diff": "^4.0.0",
@@ -20534,6 +20870,7 @@
},
"node_modules/natural-compare": {
"version": "1.4.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/negotiator": {
@@ -20549,10 +20886,12 @@
},
"node_modules/nice-try": {
"version": "1.0.5",
+ "dev": true,
"license": "MIT"
},
"node_modules/node-domexception": {
"version": "1.0.0",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -20588,10 +20927,12 @@
},
"node_modules/node-int64": {
"version": "0.4.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/node-notifier": {
"version": "8.0.2",
+ "dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
@@ -20605,6 +20946,7 @@
},
"node_modules/node-notifier/node_modules/uuid": {
"version": "8.3.2",
+ "dev": true,
"license": "MIT",
"optional": true,
"bin": {
@@ -20739,6 +21081,7 @@
},
"node_modules/normalize-package-data": {
"version": "2.5.0",
+ "dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"hosted-git-info": "^2.1.4",
@@ -20749,6 +21092,7 @@
},
"node_modules/normalize-package-data/node_modules/semver": {
"version": "5.7.2",
+ "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver"
@@ -20777,6 +21121,7 @@
},
"node_modules/npm-normalize-package-bin": {
"version": "5.0.0",
+ "dev": true,
"license": "ISC",
"engines": {
"node": "^20.17.0 || >=22.9.0"
@@ -20958,6 +21303,7 @@
},
"node_modules/nwsapi": {
"version": "2.2.23",
+ "dev": true,
"license": "MIT"
},
"node_modules/object-assign": {
@@ -20969,6 +21315,7 @@
},
"node_modules/object-copy": {
"version": "0.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"copy-descriptor": "^0.1.0",
@@ -20981,6 +21328,7 @@
},
"node_modules/object-copy/node_modules/define-property": {
"version": "0.2.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^0.1.0"
@@ -20991,6 +21339,7 @@
},
"node_modules/object-copy/node_modules/is-descriptor": {
"version": "0.1.7",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -21002,6 +21351,7 @@
},
"node_modules/object-copy/node_modules/kind-of": {
"version": "3.2.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -21052,6 +21402,7 @@
},
"node_modules/object-visit": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"isobject": "^3.0.0"
@@ -21081,6 +21432,7 @@
},
"node_modules/object.pick": {
"version": "1.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"isobject": "^3.0.1"
@@ -21135,6 +21487,23 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/oniguruma-parser": {
+ "version": "0.12.1",
+ "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz",
+ "integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==",
+ "license": "MIT"
+ },
+ "node_modules/oniguruma-to-es": {
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.4.tgz",
+ "integrity": "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA==",
+ "license": "MIT",
+ "dependencies": {
+ "oniguruma-parser": "^0.12.1",
+ "regex": "^6.0.1",
+ "regex-recursion": "^6.0.2"
+ }
+ },
"node_modules/open": {
"version": "7.4.2",
"dev": true,
@@ -21231,6 +21600,7 @@
},
"node_modules/p-each-series": {
"version": "2.2.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -21248,6 +21618,7 @@
},
"node_modules/p-limit": {
"version": "2.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"p-try": "^2.0.0"
@@ -21261,6 +21632,7 @@
},
"node_modules/p-locate": {
"version": "4.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"p-limit": "^2.2.0"
@@ -21320,6 +21692,7 @@
},
"node_modules/p-try": {
"version": "2.2.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -21390,6 +21763,7 @@
},
"node_modules/parse5": {
"version": "6.0.1",
+ "dev": true,
"license": "MIT"
},
"node_modules/parseley": {
@@ -21412,6 +21786,7 @@
},
"node_modules/pascalcase": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -21496,6 +21871,7 @@
},
"node_modules/path-exists": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -21503,6 +21879,7 @@
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
+ "devOptional": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -21710,6 +22087,7 @@
},
"node_modules/pkg-dir": {
"version": "4.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"find-up": "^4.0.0"
@@ -21740,6 +22118,7 @@
},
"node_modules/posix-character-classes": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -21884,6 +22263,7 @@
},
"node_modules/postcss-nesting": {
"version": "12.1.5",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -22004,6 +22384,7 @@
},
"node_modules/pretty-format": {
"version": "26.6.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@jest/types": "^26.6.2",
@@ -22017,6 +22398,7 @@
},
"node_modules/pretty-format/node_modules/ansi-styles": {
"version": "4.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -22030,6 +22412,7 @@
},
"node_modules/pretty-format/node_modules/color-convert": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -22040,23 +22423,14 @@
},
"node_modules/pretty-format/node_modules/color-name": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/pretty-format/node_modules/react-is": {
"version": "17.0.2",
+ "dev": true,
"license": "MIT"
},
- "node_modules/prism-react-renderer": {
- "version": "2.4.1",
- "license": "MIT",
- "dependencies": {
- "@types/prismjs": "^1.26.0",
- "clsx": "^2.0.0"
- },
- "peerDependencies": {
- "react": ">=16.0.0"
- }
- },
"node_modules/prismjs": {
"version": "1.30.0",
"license": "MIT",
@@ -22066,6 +22440,7 @@
},
"node_modules/proc-log": {
"version": "6.1.0",
+ "dev": true,
"license": "ISC",
"engines": {
"node": "^20.17.0 || >=22.9.0"
@@ -22084,6 +22459,7 @@
},
"node_modules/prompts": {
"version": "2.4.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"kleur": "^3.0.3",
@@ -22316,6 +22692,7 @@
},
"node_modules/psl": {
"version": "1.15.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
@@ -22331,6 +22708,7 @@
},
"node_modules/pump": {
"version": "3.0.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
@@ -22372,6 +22750,7 @@
},
"node_modules/querystringify": {
"version": "2.2.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/queue": {
@@ -22856,6 +23235,33 @@
"selecto": "~1.26.3"
}
},
+ "node_modules/react-shiki": {
+ "version": "0.9.1",
+ "resolved": "https://registry.npmjs.org/react-shiki/-/react-shiki-0.9.1.tgz",
+ "integrity": "sha512-Ln1PnISi7WaSlheSBRdxVruVbU1zMUkCmxe+vmbIvZSsHdfvOF5NBOgf1h4cCr6OjdR0dLAxmPKcx3tobdyxVA==",
+ "license": "MIT",
+ "dependencies": {
+ "clsx": "^2.1.1",
+ "dequal": "^2.0.3",
+ "hast-util-to-jsx-runtime": "^2.3.6",
+ "shiki": "^3.11.0",
+ "unist-util-visit": "^5.0.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8.0",
+ "@types/react-dom": ">=16.8.0",
+ "react": ">= 16.8.0",
+ "react-dom": ">= 16.8.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-smooth": {
"version": "4.0.4",
"license": "MIT",
@@ -22967,6 +23373,7 @@
},
"node_modules/read-cmd-shim": {
"version": "6.0.0",
+ "dev": true,
"license": "ISC",
"engines": {
"node": "^20.17.0 || >=22.9.0"
@@ -22987,6 +23394,7 @@
},
"node_modules/read-pkg-up": {
"version": "7.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"find-up": "^4.1.0",
@@ -23002,6 +23410,7 @@
},
"node_modules/read-pkg-up/node_modules/parse-json": {
"version": "5.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.0.0",
@@ -23018,6 +23427,7 @@
},
"node_modules/read-pkg-up/node_modules/read-pkg": {
"version": "5.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/normalize-package-data": "^2.4.0",
@@ -23031,6 +23441,7 @@
},
"node_modules/read-pkg-up/node_modules/read-pkg/node_modules/type-fest": {
"version": "0.6.0",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=8"
@@ -23038,6 +23449,7 @@
},
"node_modules/read-pkg-up/node_modules/type-fest": {
"version": "0.8.1",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=8"
@@ -23144,8 +23556,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/regex": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",
+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
"node_modules/regex-not": {
"version": "1.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"extend-shallow": "^3.0.2",
@@ -23155,6 +23577,21 @@
"node": ">=0.10.0"
}
},
+ "node_modules/regex-recursion": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",
+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
+ "node_modules/regex-utilities": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",
+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",
+ "license": "MIT"
+ },
"node_modules/regexp.prototype.flags": {
"version": "1.5.4",
"dev": true,
@@ -23302,10 +23739,12 @@
},
"node_modules/remove-trailing-separator": {
"version": "1.1.0",
+ "dev": true,
"license": "ISC"
},
"node_modules/repeat-element": {
"version": "1.1.4",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -23313,6 +23752,7 @@
},
"node_modules/repeat-string": {
"version": "1.6.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10"
@@ -23320,6 +23760,7 @@
},
"node_modules/require-directory": {
"version": "2.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -23365,10 +23806,12 @@
},
"node_modules/require-main-filename": {
"version": "2.0.0",
+ "dev": true,
"license": "ISC"
},
"node_modules/requires-port": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/resend": {
@@ -23417,6 +23860,7 @@
},
"node_modules/resolve-cwd": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"resolve-from": "^5.0.0"
@@ -23427,6 +23871,7 @@
},
"node_modules/resolve-cwd/node_modules/resolve-from": {
"version": "5.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -23441,7 +23886,7 @@
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
@@ -23449,6 +23894,7 @@
},
"node_modules/resolve-url": {
"version": "0.2.1",
+ "dev": true,
"license": "MIT"
},
"node_modules/restore-cursor": {
@@ -23494,6 +23940,7 @@
},
"node_modules/ret": {
"version": "0.1.15",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12"
@@ -23591,6 +24038,7 @@
},
"node_modules/rsvp": {
"version": "4.8.5",
+ "dev": true,
"license": "MIT",
"engines": {
"node": "6.* || >= 7.*"
@@ -23689,6 +24137,7 @@
},
"node_modules/safe-regex": {
"version": "1.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ret": "~0.1.10"
@@ -23715,6 +24164,7 @@
},
"node_modules/sane": {
"version": "4.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@cnakazawa/watch": "^1.0.3",
@@ -23736,6 +24186,7 @@
},
"node_modules/sane/node_modules/anymatch": {
"version": "2.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"micromatch": "^3.1.4",
@@ -23744,6 +24195,7 @@
},
"node_modules/sane/node_modules/braces": {
"version": "2.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"arr-flatten": "^1.1.0",
@@ -23763,6 +24215,7 @@
},
"node_modules/sane/node_modules/braces/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -23773,6 +24226,7 @@
},
"node_modules/sane/node_modules/cross-spawn": {
"version": "6.0.6",
+ "dev": true,
"license": "MIT",
"dependencies": {
"nice-try": "^1.0.4",
@@ -23787,6 +24241,7 @@
},
"node_modules/sane/node_modules/execa": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^6.0.0",
@@ -23803,6 +24258,7 @@
},
"node_modules/sane/node_modules/fill-range": {
"version": "4.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"extend-shallow": "^2.0.1",
@@ -23816,6 +24272,7 @@
},
"node_modules/sane/node_modules/fill-range/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -23826,6 +24283,7 @@
},
"node_modules/sane/node_modules/get-stream": {
"version": "4.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"pump": "^3.0.0"
@@ -23836,6 +24294,7 @@
},
"node_modules/sane/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -23843,6 +24302,7 @@
},
"node_modules/sane/node_modules/is-number": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"kind-of": "^3.0.2"
@@ -23853,6 +24313,7 @@
},
"node_modules/sane/node_modules/is-number/node_modules/kind-of": {
"version": "3.2.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -23863,6 +24324,7 @@
},
"node_modules/sane/node_modules/is-stream": {
"version": "1.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -23870,6 +24332,7 @@
},
"node_modules/sane/node_modules/micromatch": {
"version": "3.1.10",
+ "dev": true,
"license": "MIT",
"dependencies": {
"arr-diff": "^4.0.0",
@@ -23892,6 +24355,7 @@
},
"node_modules/sane/node_modules/normalize-path": {
"version": "2.1.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"remove-trailing-separator": "^1.0.1"
@@ -23902,6 +24366,7 @@
},
"node_modules/sane/node_modules/npm-run-path": {
"version": "2.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^2.0.0"
@@ -23912,6 +24377,7 @@
},
"node_modules/sane/node_modules/path-key": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
@@ -23919,6 +24385,7 @@
},
"node_modules/sane/node_modules/semver": {
"version": "5.7.2",
+ "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver"
@@ -23926,6 +24393,7 @@
},
"node_modules/sane/node_modules/shebang-command": {
"version": "1.2.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^1.0.0"
@@ -23936,6 +24404,7 @@
},
"node_modules/sane/node_modules/shebang-regex": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -23943,6 +24412,7 @@
},
"node_modules/sane/node_modules/to-regex-range": {
"version": "2.1.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^3.0.0",
@@ -23954,6 +24424,7 @@
},
"node_modules/sane/node_modules/which": {
"version": "1.3.1",
+ "dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -23980,6 +24451,7 @@
},
"node_modules/saxes": {
"version": "5.0.1",
+ "dev": true,
"license": "ISC",
"dependencies": {
"xmlchars": "^2.2.0"
@@ -24093,6 +24565,7 @@
},
"node_modules/set-blocking": {
"version": "2.0.0",
+ "devOptional": true,
"license": "ISC"
},
"node_modules/set-cookie-parser": {
@@ -24143,6 +24616,7 @@
},
"node_modules/set-value": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"extend-shallow": "^2.0.1",
@@ -24156,6 +24630,7 @@
},
"node_modules/set-value/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -24166,6 +24641,7 @@
},
"node_modules/set-value/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -24173,6 +24649,7 @@
},
"node_modules/set-value/node_modules/is-plain-object": {
"version": "2.0.4",
+ "dev": true,
"license": "MIT",
"dependencies": {
"isobject": "^3.0.1"
@@ -24215,9 +24692,26 @@
},
"node_modules/shellwords": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"optional": true
},
+ "node_modules/shiki": {
+ "version": "3.23.0",
+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.23.0.tgz",
+ "integrity": "sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/core": "3.23.0",
+ "@shikijs/engine-javascript": "3.23.0",
+ "@shikijs/engine-oniguruma": "3.23.0",
+ "@shikijs/langs": "3.23.0",
+ "@shikijs/themes": "3.23.0",
+ "@shikijs/types": "3.23.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4"
+ }
+ },
"node_modules/side-channel": {
"version": "1.1.0",
"license": "MIT",
@@ -24284,6 +24778,7 @@
},
"node_modules/signal-exit": {
"version": "3.0.7",
+ "devOptional": true,
"license": "ISC"
},
"node_modules/simple-concat": {
@@ -24339,6 +24834,7 @@
},
"node_modules/sisteransi": {
"version": "1.0.5",
+ "dev": true,
"license": "MIT"
},
"node_modules/slash": {
@@ -24381,6 +24877,7 @@
},
"node_modules/snapdragon": {
"version": "0.8.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"base": "^0.11.1",
@@ -24398,6 +24895,7 @@
},
"node_modules/snapdragon-node": {
"version": "2.1.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"define-property": "^1.0.0",
@@ -24410,6 +24908,7 @@
},
"node_modules/snapdragon-node/node_modules/define-property": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^1.0.0"
@@ -24420,6 +24919,7 @@
},
"node_modules/snapdragon-util": {
"version": "3.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"kind-of": "^3.2.0"
@@ -24430,6 +24930,7 @@
},
"node_modules/snapdragon-util/node_modules/kind-of": {
"version": "3.2.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -24440,6 +24941,7 @@
},
"node_modules/snapdragon/node_modules/debug": {
"version": "2.6.9",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
@@ -24447,6 +24949,7 @@
},
"node_modules/snapdragon/node_modules/define-property": {
"version": "0.2.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^0.1.0"
@@ -24457,6 +24960,7 @@
},
"node_modules/snapdragon/node_modules/extend-shallow": {
"version": "2.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
@@ -24467,6 +24971,7 @@
},
"node_modules/snapdragon/node_modules/is-descriptor": {
"version": "0.1.7",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -24478,6 +24983,7 @@
},
"node_modules/snapdragon/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -24485,6 +24991,7 @@
},
"node_modules/snapdragon/node_modules/ms": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/socket.io": {
@@ -24632,6 +25139,7 @@
},
"node_modules/source-map-resolve": {
"version": "0.5.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"atob": "^2.1.2",
@@ -24658,6 +25166,7 @@
},
"node_modules/source-map-url": {
"version": "0.4.1",
+ "dev": true,
"license": "MIT"
},
"node_modules/space-separated-tokens": {
@@ -24670,6 +25179,7 @@
},
"node_modules/spdx-correct": {
"version": "3.2.0",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"spdx-expression-parse": "^3.0.0",
@@ -24678,10 +25188,12 @@
},
"node_modules/spdx-exceptions": {
"version": "2.5.0",
+ "dev": true,
"license": "CC-BY-3.0"
},
"node_modules/spdx-expression-parse": {
"version": "3.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"spdx-exceptions": "^2.1.0",
@@ -24690,6 +25202,7 @@
},
"node_modules/spdx-license-ids": {
"version": "3.0.22",
+ "dev": true,
"license": "CC0-1.0"
},
"node_modules/spin-delay": {
@@ -24701,6 +25214,7 @@
},
"node_modules/split-string": {
"version": "3.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"extend-shallow": "^3.0.0"
@@ -24718,6 +25232,7 @@
},
"node_modules/sprintf-js": {
"version": "1.0.3",
+ "dev": true,
"license": "BSD-3-Clause"
},
"node_modules/sst": {
@@ -24839,6 +25354,7 @@
},
"node_modules/stack-utils": {
"version": "2.0.6",
+ "dev": true,
"license": "MIT",
"dependencies": {
"escape-string-regexp": "^2.0.0"
@@ -24849,6 +25365,7 @@
},
"node_modules/stack-utils/node_modules/escape-string-regexp": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -24864,6 +25381,7 @@
},
"node_modules/static-extend": {
"version": "0.1.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"define-property": "^0.2.5",
@@ -24875,6 +25393,7 @@
},
"node_modules/static-extend/node_modules/define-property": {
"version": "0.2.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-descriptor": "^0.1.0"
@@ -24885,6 +25404,7 @@
},
"node_modules/static-extend/node_modules/is-descriptor": {
"version": "0.1.7",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-accessor-descriptor": "^1.0.1",
@@ -24934,6 +25454,7 @@
},
"node_modules/string-length": {
"version": "4.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"char-regex": "^1.0.2",
@@ -24945,6 +25466,7 @@
},
"node_modules/string-length/node_modules/strip-ansi": {
"version": "6.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -25128,6 +25650,7 @@
},
"node_modules/strip-eof": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -25216,6 +25739,7 @@
},
"node_modules/supabase": {
"version": "2.54.11",
+ "dev": true,
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
@@ -25233,6 +25757,7 @@
},
"node_modules/supabase/node_modules/agent-base": {
"version": "7.1.4",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 14"
@@ -25240,6 +25765,7 @@
},
"node_modules/supabase/node_modules/chownr": {
"version": "3.0.0",
+ "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
@@ -25247,6 +25773,7 @@
},
"node_modules/supabase/node_modules/https-proxy-agent": {
"version": "7.0.6",
+ "dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
@@ -25258,6 +25785,7 @@
},
"node_modules/supabase/node_modules/minizlib": {
"version": "3.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"minipass": "^7.1.2"
@@ -25268,6 +25796,7 @@
},
"node_modules/supabase/node_modules/node-fetch": {
"version": "3.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
@@ -25284,6 +25813,7 @@
},
"node_modules/supabase/node_modules/tar": {
"version": "7.5.1",
+ "dev": true,
"license": "ISC",
"dependencies": {
"@isaacs/fs-minipass": "^4.0.0",
@@ -25298,6 +25828,7 @@
},
"node_modules/supabase/node_modules/yallist": {
"version": "5.0.0",
+ "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
@@ -25325,6 +25856,7 @@
},
"node_modules/supports-hyperlinks": {
"version": "2.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0",
@@ -25361,6 +25893,7 @@
},
"node_modules/symbol-tree": {
"version": "3.2.4",
+ "dev": true,
"license": "MIT"
},
"node_modules/tailwind-merge": {
@@ -25373,6 +25906,7 @@
},
"node_modules/tailwind-scrollbar": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=12.13.0"
@@ -25383,6 +25917,7 @@
},
"node_modules/tailwind-scrollbar-hide": {
"version": "1.3.1",
+ "dev": true,
"license": "MIT",
"peerDependencies": {
"tailwindcss": ">=3.0.0 || >= 4.0.0 || >= 4.0.0-beta.8 || >= 4.0.0-alpha.20"
@@ -25551,6 +26086,7 @@
},
"node_modules/terminal-link": {
"version": "2.1.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-escapes": "^4.2.1",
@@ -25565,6 +26101,7 @@
},
"node_modules/terminal-link/node_modules/ansi-escapes": {
"version": "4.3.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"type-fest": "^0.21.3"
@@ -25578,6 +26115,7 @@
},
"node_modules/terminal-link/node_modules/type-fest": {
"version": "0.21.3",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=10"
@@ -25588,6 +26126,7 @@
},
"node_modules/test-exclude": {
"version": "6.0.0",
+ "dev": true,
"license": "ISC",
"dependencies": {
"@istanbuljs/schema": "^0.1.2",
@@ -25600,6 +26139,7 @@
},
"node_modules/test-exclude/node_modules/glob": {
"version": "7.2.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -25635,6 +26175,7 @@
},
"node_modules/throat": {
"version": "5.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/throttleit": {
@@ -25726,10 +26267,12 @@
},
"node_modules/tmpl": {
"version": "1.0.5",
+ "dev": true,
"license": "BSD-3-Clause"
},
"node_modules/to-object-path": {
"version": "0.3.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"kind-of": "^3.0.2"
@@ -25740,6 +26283,7 @@
},
"node_modules/to-object-path/node_modules/kind-of": {
"version": "3.2.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-buffer": "^1.1.5"
@@ -25750,6 +26294,7 @@
},
"node_modules/to-regex": {
"version": "3.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"define-property": "^2.0.2",
@@ -25788,6 +26333,7 @@
},
"node_modules/tough-cookie": {
"version": "4.1.4",
+ "dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"psl": "^1.1.33",
@@ -25801,6 +26347,7 @@
},
"node_modules/tough-cookie/node_modules/universalify": {
"version": "0.2.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 4.0.0"
@@ -26197,7 +26744,7 @@
},
"node_modules/tsx": {
"version": "4.21.0",
- "devOptional": true,
+ "dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.27.0",
@@ -26587,7 +27134,7 @@
},
"node_modules/tsx/node_modules/esbuild": {
"version": "0.27.2",
- "devOptional": true,
+ "dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
@@ -26686,13 +27233,6 @@
"darwin"
]
},
- "node_modules/turbo-stream": {
- "version": "2.4.1",
- "resolved": "https://registry.npmjs.org/turbo-stream/-/turbo-stream-2.4.1.tgz",
- "integrity": "sha512-v8kOJXpG3WoTN/+at8vK7erSzo6nW6CIaeOvNOkHQVDajfz1ZVeSxCbc6tOH4hrGZW7VUCV0TOXd8CPzYnYkrw==",
- "license": "ISC",
- "peer": true
- },
"node_modules/turbo/node_modules/turbo-darwin-64": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/turbo-darwin-64/-/turbo-darwin-64-2.7.2.tgz",
@@ -26765,6 +27305,7 @@
},
"node_modules/type-detect": {
"version": "4.0.8",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
@@ -26865,6 +27406,7 @@
},
"node_modules/typedarray-to-buffer": {
"version": "3.1.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"is-typedarray": "^1.0.0"
@@ -26874,6 +27416,7 @@
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
+ "dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -26979,6 +27522,7 @@
},
"node_modules/union-value": {
"version": "1.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"arr-union": "^3.1.0",
@@ -26992,6 +27536,7 @@
},
"node_modules/union-value/node_modules/is-extendable": {
"version": "0.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -27071,6 +27616,7 @@
},
"node_modules/unset-value": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"has-value": "^0.3.1",
@@ -27082,6 +27628,7 @@
},
"node_modules/unset-value/node_modules/has-value": {
"version": "0.3.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"get-value": "^2.0.3",
@@ -27094,6 +27641,7 @@
},
"node_modules/unset-value/node_modules/has-value/node_modules/isobject": {
"version": "2.1.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"isarray": "1.0.0"
@@ -27104,6 +27652,7 @@
},
"node_modules/unset-value/node_modules/has-values": {
"version": "0.1.4",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -27111,6 +27660,7 @@
},
"node_modules/unset-value/node_modules/isarray": {
"version": "1.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/update-browserslist-db": {
@@ -27154,6 +27704,7 @@
},
"node_modules/urix": {
"version": "0.1.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/url": {
@@ -27166,6 +27717,7 @@
},
"node_modules/url-parse": {
"version": "1.5.10",
+ "dev": true,
"license": "MIT",
"dependencies": {
"querystringify": "^2.1.1",
@@ -27178,6 +27730,7 @@
},
"node_modules/use": {
"version": "3.1.1",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -27269,6 +27822,7 @@
},
"node_modules/v8-to-istanbul": {
"version": "7.1.2",
+ "dev": true,
"license": "ISC",
"dependencies": {
"@types/istanbul-lib-coverage": "^2.0.1",
@@ -27281,6 +27835,7 @@
},
"node_modules/v8-to-istanbul/node_modules/source-map": {
"version": "0.7.6",
+ "dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">= 12"
@@ -27300,6 +27855,7 @@
},
"node_modules/validate-npm-package-license": {
"version": "3.0.4",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"spdx-correct": "^3.0.0",
@@ -28013,6 +28569,7 @@
},
"node_modules/w3c-hr-time": {
"version": "1.0.2",
+ "dev": true,
"license": "MIT",
"dependencies": {
"browser-process-hrtime": "^1.0.0"
@@ -28024,6 +28581,7 @@
},
"node_modules/w3c-xmlserializer": {
"version": "2.0.0",
+ "dev": true,
"license": "MIT",
"dependencies": {
"xml-name-validator": "^3.0.0"
@@ -28052,6 +28610,7 @@
},
"node_modules/walker": {
"version": "1.0.8",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"makeerror": "1.0.12"
@@ -28074,6 +28633,7 @@
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
@@ -28085,6 +28645,7 @@
},
"node_modules/webidl-conversions": {
"version": "6.1.0",
+ "dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=10.4"
@@ -28092,6 +28653,7 @@
},
"node_modules/whatwg-encoding": {
"version": "1.0.5",
+ "dev": true,
"license": "MIT",
"dependencies": {
"iconv-lite": "0.4.24"
@@ -28099,6 +28661,7 @@
},
"node_modules/whatwg-encoding/node_modules/iconv-lite": {
"version": "0.4.24",
+ "dev": true,
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
@@ -28109,6 +28672,7 @@
},
"node_modules/whatwg-mimetype": {
"version": "2.3.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/whatwg-url": {
@@ -28199,6 +28763,7 @@
},
"node_modules/which-module": {
"version": "2.0.1",
+ "dev": true,
"license": "ISC"
},
"node_modules/which-typed-array": {
@@ -28376,6 +28941,7 @@
},
"node_modules/write-file-atomic": {
"version": "3.0.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"imurmurhash": "^0.1.4",
@@ -28405,6 +28971,7 @@
},
"node_modules/xml-name-validator": {
"version": "3.0.0",
+ "dev": true,
"license": "Apache-2.0"
},
"node_modules/xml2js": {
@@ -28427,6 +28994,7 @@
},
"node_modules/xmlchars": {
"version": "2.2.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/xmlhttprequest-ssl": {
@@ -28444,6 +29012,7 @@
},
"node_modules/y18n": {
"version": "4.0.3",
+ "dev": true,
"license": "ISC"
},
"node_modules/yallist": {
@@ -28467,6 +29036,7 @@
},
"node_modules/yargs": {
"version": "15.4.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^6.0.0",
@@ -28487,6 +29057,7 @@
},
"node_modules/yargs-parser": {
"version": "18.1.3",
+ "dev": true,
"license": "ISC",
"dependencies": {
"camelcase": "^5.0.0",
@@ -28498,10 +29069,12 @@
},
"node_modules/yargs/node_modules/emoji-regex": {
"version": "8.0.0",
+ "dev": true,
"license": "MIT"
},
"node_modules/yargs/node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -28509,6 +29082,7 @@
},
"node_modules/yargs/node_modules/string-width": {
"version": "4.2.3",
+ "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -28521,6 +29095,7 @@
},
"node_modules/yargs/node_modules/strip-ansi": {
"version": "6.0.1",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -28627,7 +29202,6 @@
},
"peerDependencies": {
"@carbon/database": "*",
- "@carbon/kv": "*",
"@carbon/react": "*",
"@carbon/utils": "*",
"@react-router/dev": "7.12.0",
@@ -29288,11 +29862,11 @@
"intl-parse-accept-language": "^1.0.0",
"is-hotkey": "^0.2.0",
"online-3d-viewer": "0.15.0",
- "prism-react-renderer": "^2.3.1",
"react-aria-components": "1.0.1",
"react-colorful": "^5.6.1",
"react-hotkeys-hook": "~4.5.0",
"react-resizable-panels": "^2.1.3",
+ "react-shiki": "^0.9.1",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 7facffa87a..1f4aa3269e 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -25,7 +25,6 @@
"peerDependencies": {
"@carbon/database": "*",
"@carbon/react": "*",
- "@carbon/kv": "*",
"@carbon/utils": "*",
"@react-router/dev": "7.12.0",
"react-router": "7.12.0",
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index 089475b9df..e9ca2a2031 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -5,6 +5,7 @@ declare global {
env: {
AUTH_PROVIDERS: string;
CARBON_EDITION: string;
+ CARBON_API_URL: string;
CLOUDFLARE_TURNSTILE_SITE_KEY: string;
CONTROLLED_ENVIRONMENT: string;
ERP_URL: string;
@@ -27,6 +28,7 @@ declare global {
namespace NodeJS {
interface ProcessEnv {
CARBON_EDITION: string;
+ CARBON_API_URL: string;
CLOUDFLARE_TURNSTILE_SITE_KEY: string;
CLOUDFLARE_TURNSTILE_SECRET_KEY: string;
DOMAIN: string;
@@ -126,6 +128,12 @@ const getEdition = () => {
export const CarbonEdition = getEdition();
+export const CARBON_API_URL =
+ getEnv("CARBON_API_URL", {
+ isRequired: false,
+ isSecret: false
+ }) ?? getEnv("SUPABASE_URL", { isSecret: false });
+
export const CLOUDFLARE_TURNSTILE_SITE_KEY = getEnv(
"CLOUDFLARE_TURNSTILE_SITE_KEY",
{ isSecret: false, isRequired: false }
@@ -354,6 +362,7 @@ export function getMESUrl() {
export function getBrowserEnv() {
return {
CARBON_EDITION,
+ CARBON_API_URL,
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
ERP_URL,
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index 74416b0548..9c207ff2b8 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -1,8 +1,10 @@
import type { Database } from "@carbon/database";
+import { checkApiKeyRateLimit } from "@carbon/database/ratelimit";
import type {
AuthSession as SupabaseAuthSession,
SupabaseClient
} from "@supabase/supabase-js";
+import { createHash } from "crypto";
import { redirect } from "react-router";
import { REFRESH_ACCESS_TOKEN_THRESHOLD, VERCEL_URL } from "../config/env";
import { getCarbon, getCarbonServiceRole } from "../lib/supabase";
@@ -60,12 +62,30 @@ export async function getAuthAccountByAccessToken(accessToken: string) {
return data.user;
}
+/** Hash an API key using SHA-256 for secure storage/lookup */
+export function hashApiKey(rawKey: string): string {
+ return createHash("sha256").update(rawKey).digest("hex");
+}
+
+type ApiKeyRecord = {
+ id: string;
+ companyId: string;
+ createdBy: string;
+ scopes: Record<string, string[]>;
+ rateLimit: number;
+ rateLimitWindow: "1m" | "1h" | "1d";
+ expiresAt: string | null;
+};
+
function getCompanyIdFromAPIKey(apiKey: string) {
const serviceRole = getCarbonServiceRole();
+ const keyHash = hashApiKey(apiKey);
return serviceRole
.from("apiKey")
- .select("companyId, createdBy")
- .eq("key", apiKey)
+ .select(
+ "id, companyId, createdBy, scopes, rateLimit, rateLimitWindow, expiresAt"
+ )
+ .eq("keyHash", keyHash)
.single();
}
@@ -113,10 +133,72 @@ export async function requirePermissions(
if (apiKey) {
const company = await getCompanyIdFromAPIKey(apiKey);
if (company.data) {
- const companyId = company.data.companyId;
- const userId = company.data.createdBy;
- const client = getCarbonAPIKeyClient(apiKey);
+ const apiKeyData = company.data as unknown as ApiKeyRecord;
+ const companyId = apiKeyData.companyId;
+ const userId = apiKeyData.createdBy;
+
+ // Check expiration
+ if (apiKeyData.expiresAt && new Date(apiKeyData.expiresAt) < new Date()) {
+ throw new Response("API key has expired", { status: 401 });
+ }
+
+ // Check rate limit via Postgres function
+ const serviceRole = getCarbonServiceRole();
+ const rl = await checkApiKeyRateLimit(
+ serviceRole,
+ apiKeyData.id,
+ apiKeyData.rateLimit,
+ apiKeyData.rateLimitWindow
+ );
+ if (!rl.success) {
+ throw new Response("Rate limit exceeded", {
+ status: 429,
+ headers: {
+ "Content-Type": "application/json",
+ "X-RateLimit-Limit": rl.limit.toString(),
+ "X-RateLimit-Remaining": rl.remaining.toString(),
+ "X-RateLimit-Reset": rl.resetAt.toString(),
+ "Retry-After": Math.ceil(
+ (rl.resetAt - Date.now()) / 1000
+ ).toString()
+ }
+ });
+ }
+
+ // Update lastUsedAt (fire-and-forget)
+ // @ts-expect-error -- Supabase deep type instantiation on chained calls
+ void serviceRole
+ .from("apiKey")
+ .update({ lastUsedAt: new Date().toISOString() } as any)
+ .eq("id" as any, apiKeyData.id);
+
+ // Check scopes against required permissions
+ const scopes = apiKeyData.scopes ?? {};
+ const scopeCheckPassed = Object.entries(requiredPermissions).every(
+ ([action, permission]) => {
+ if (action === "bypassRls" || action === "role") return true;
+ if (typeof permission === "string") {
+ const scopeKey = `${permission}_${action}`;
+ return scopeKey in scopes && scopes[scopeKey]?.includes(companyId);
+ } else if (Array.isArray(permission)) {
+ return permission.every((p) => {
+ const scopeKey = `${p}_${action}`;
+ return (
+ scopeKey in scopes && scopes[scopeKey]?.includes(companyId)
+ );
+ });
+ }
+ return false;
+ }
+ );
+ if (!scopeCheckPassed) {
+ throw new Response("API key lacks required permissions", {
+ status: 403
+ });
+ }
+
+ const client = getCarbonAPIKeyClient(apiKey);
return {
client,
companyId,
diff --git a/packages/database/package.json b/packages/database/package.json
index 94a56e4a19..2eee3d59eb 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -18,6 +18,7 @@
".": "./src/index.ts",
"./client": "./src/client.ts",
"./event": "./src/event.ts",
+ "./ratelimit": "./src/ratelimit.ts",
"./audit": "./src/audit.ts",
"./audit.config": "./src/audit.config.ts",
"./audit.types": "./src/audit.types.ts",
diff --git a/packages/database/src/ratelimit.ts b/packages/database/src/ratelimit.ts
new file mode 100644
index 0000000000..9838598228
--- /dev/null
+++ b/packages/database/src/ratelimit.ts
@@ -0,0 +1,32 @@
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+export type RateLimitResult = {
+ success: boolean;
+ count: number;
+ limit: number;
+ remaining: number;
+ resetAt: number;
+};
+
+/**
+ * Check rate limit for an API key using the Postgres
+ * check_api_key_rate_limit() function via Supabase .rpc().
+ *
+ * Returns the rate limit result. Callers are responsible for
+ * throwing/returning an appropriate 429 response when !success.
+ */
+export async function checkApiKeyRateLimit(
+ client: SupabaseClient,
+ apiKeyId: string,
+ limit: number,
+ window: string
+): Promise<RateLimitResult> {
+ const { data, error } = await client.rpc("check_api_key_rate_limit", {
+ p_api_key_id: apiKeyId,
+ p_limit: limit,
+ p_window: window
+ });
+
+ if (error) throw error;
+ return data as RateLimitResult;
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 7e67e074c5..5edde84c3c 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -15642,6 +15642,123 @@ export default {
tags: ["kanbans"],
},
},
+ "/apiKeyRateLimit": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.apiKeyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.windowStart",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.requestCount",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/apiKeyRateLimit",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["apiKeyRateLimit"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.apiKeyRateLimit",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["apiKeyRateLimit"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.apiKeyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.windowStart",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.requestCount",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["apiKeyRateLimit"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.apiKeyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.windowStart",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKeyRateLimit.requestCount",
+ },
+ {
+ $ref: "#/parameters/body.apiKeyRateLimit",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["apiKeyRateLimit"],
+ },
+ },
"/companies": {
get: {
parameters: [
@@ -54162,9 +54279,6 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.name",
},
- {
- $ref: "#/parameters/rowFilter.apiKey.key",
- },
{
$ref: "#/parameters/rowFilter.apiKey.companyId",
},
@@ -54174,6 +54288,27 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyHash",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyPreview",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.scopes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimitWindow",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.expiresAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.lastUsedAt",
+ },
{
$ref: "#/parameters/select",
},
@@ -54239,9 +54374,6 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.name",
},
- {
- $ref: "#/parameters/rowFilter.apiKey.key",
- },
{
$ref: "#/parameters/rowFilter.apiKey.companyId",
},
@@ -54251,6 +54383,27 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyHash",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyPreview",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.scopes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimitWindow",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.expiresAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.lastUsedAt",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -54270,9 +54423,6 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.name",
},
- {
- $ref: "#/parameters/rowFilter.apiKey.key",
- },
{
$ref: "#/parameters/rowFilter.apiKey.companyId",
},
@@ -54282,6 +54432,27 @@ export default {
{
$ref: "#/parameters/rowFilter.apiKey.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyHash",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.keyPreview",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.scopes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.rateLimitWindow",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.expiresAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.apiKey.lastUsedAt",
+ },
{
$ref: "#/parameters/body.apiKey",
},
@@ -65281,6 +65452,49 @@ export default {
tags: ["(rpc) xid_decode"],
},
},
+ "/rpc/check_api_key_rate_limit": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_api_key_id: {
+ format: "text",
+ type: "string",
+ },
+ p_limit: {
+ format: "integer",
+ type: "integer",
+ },
+ p_window: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["p_api_key_id", "p_limit", "p_window"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) check_api_key_rate_limit"],
+ },
+ },
"/rpc/nanoid_optimized": {
post: {
parameters: [
@@ -67007,6 +67221,34 @@ export default {
tags: ["(rpc) get_material_naming_details"],
},
},
+ "/rpc/get_api_key_scopes": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_api_key_scopes"],
+ },
+ },
"/rpc/drop_audit_log_table": {
post: {
parameters: [
@@ -76110,6 +76352,28 @@ export default {
},
type: "object",
},
+ apiKeyRateLimit: {
+ required: ["apiKeyId", "windowStart", "requestCount"],
+ properties: {
+ apiKeyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `apiKey.id`.<fk table='apiKey' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ windowStart: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ requestCount: {
+ default: 1,
+ format: "integer",
+ type: "integer",
+ },
+ },
+ type: "object",
+ },
companies: {
properties: {
id: {
@@ -94146,7 +94410,17 @@ export default {
type: "object",
},
apiKey: {
- required: ["id", "name", "key", "companyId", "createdBy", "createdAt"],
+ required: [
+ "id",
+ "name",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "keyHash",
+ "scopes",
+ "rateLimit",
+ "rateLimitWindow",
+ ],
properties: {
id: {
default: "public.id('api'::text)",
@@ -94158,10 +94432,6 @@ export default {
format: "text",
type: "string",
},
- key: {
- format: "text",
- type: "string",
- },
companyId: {
description:
"Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
@@ -94179,6 +94449,35 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ keyHash: {
+ format: "text",
+ type: "string",
+ },
+ keyPreview: {
+ format: "text",
+ type: "string",
+ },
+ scopes: {
+ format: "jsonb",
+ },
+ rateLimit: {
+ default: 60,
+ format: "integer",
+ type: "integer",
+ },
+ rateLimitWindow: {
+ default: "1m",
+ format: "text",
+ type: "string",
+ },
+ expiresAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ lastUsedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
},
type: "object",
},
@@ -107243,6 +107542,33 @@ export default {
in: "query",
type: "string",
},
+ "body.apiKeyRateLimit": {
+ name: "apiKeyRateLimit",
+ description: "apiKeyRateLimit",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/apiKeyRateLimit",
+ },
+ },
+ "rowFilter.apiKeyRateLimit.apiKeyId": {
+ name: "apiKeyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKeyRateLimit.windowStart": {
+ name: "windowStart",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKeyRateLimit.requestCount": {
+ name: "requestCount",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.companies": {
name: "companies",
description: "companies",
@@ -127615,12 +127941,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.apiKey.key": {
- name: "key",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.apiKey.companyId": {
name: "companyId",
required: false,
@@ -127639,6 +127959,48 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.apiKey.keyHash": {
+ name: "keyHash",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.keyPreview": {
+ name: "keyPreview",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.scopes": {
+ name: "scopes",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.rateLimit": {
+ name: "rateLimit",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.rateLimitWindow": {
+ name: "rateLimitWindow",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.expiresAt": {
+ name: "expiresAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.apiKey.lastUsedAt": {
+ name: "lastUsedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.workCentersWithBlockingStatus": {
name: "workCentersWithBlockingStatus",
description: "workCentersWithBlockingStatus",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2b130a1cf5..10f2e8048e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1603,25 +1603,43 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ expiresAt: string | null
id: string
- key: string
+ keyHash: string
+ keyPreview: string | null
+ lastUsedAt: string | null
name: string
+ rateLimit: number
+ rateLimitWindow: string
+ scopes: Json
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
+ expiresAt?: string | null
id?: string
- key: string
+ keyHash: string
+ keyPreview?: string | null
+ lastUsedAt?: string | null
name: string
+ rateLimit?: number
+ rateLimitWindow?: string
+ scopes?: Json
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
+ expiresAt?: string | null
id?: string
- key?: string
+ keyHash?: string
+ keyPreview?: string | null
+ lastUsedAt?: string | null
name?: string
+ rateLimit?: number
+ rateLimitWindow?: string
+ scopes?: Json
}
Relationships: [
{
@@ -1689,6 +1707,32 @@ export type Database = {
},
]
}
+ apiKeyRateLimit: {
+ Row: {
+ apiKeyId: string
+ requestCount: number
+ windowStart: string
+ }
+ Insert: {
+ apiKeyId: string
+ requestCount?: number
+ windowStart: string
+ }
+ Update: {
+ apiKeyId?: string
+ requestCount?: number
+ windowStart?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "apiKeyRateLimit_apiKeyId_fkey"
+ columns: ["apiKeyId"]
+ isOneToOne: false
+ referencedRelation: "apiKey"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
approvalRequest: {
Row: {
amount: number | null
@@ -52148,14 +52192,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55722,6 +55766,10 @@ export type Database = {
Args: { sync_functions?: string[]; table_name_text: string }
Returns: undefined
}
+ check_api_key_rate_limit: {
+ Args: { p_api_key_id: string; p_limit: number; p_window: string }
+ Returns: Json
+ }
check_operation_dependencies: {
Args: { operation_id: string }
Returns: boolean
@@ -55921,6 +55969,7 @@ export type Database = {
workCenterId: string
}[]
}
+ get_api_key_scopes: { Args: never; Returns: Json }
get_assigned_job_operations: {
Args: { company_id: string; user_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/lib/ratelimit.ts b/packages/database/supabase/functions/lib/ratelimit.ts
new file mode 100644
index 0000000000..6b220bcc61
--- /dev/null
+++ b/packages/database/supabase/functions/lib/ratelimit.ts
@@ -0,0 +1,32 @@
+import { createClient } from "https://esm.sh/@supabase/[email protected]";
+
+export type RateLimitResult = {
+ success: boolean;
+ count: number;
+ limit: number;
+ remaining: number;
+ resetAt: number;
+};
+
+/**
+ * Check rate limit for an API key using the Postgres
+ * check_api_key_rate_limit() function via Supabase .rpc().
+ *
+ * Returns the rate limit result. Callers are responsible for
+ * throwing/returning an appropriate 429 response when !success.
+ */
+export async function checkApiKeyRateLimit(
+ client: ReturnType<typeof createClient>,
+ apiKeyId: string,
+ limit: number,
+ window: string
+): Promise<RateLimitResult> {
+ const { data, error } = await client.rpc("check_api_key_rate_limit", {
+ p_api_key_id: apiKeyId,
+ p_limit: limit,
+ p_window: window,
+ });
+
+ if (error) throw error;
+ return data as RateLimitResult;
+}
diff --git a/packages/database/supabase/functions/lib/supabase.ts b/packages/database/supabase/functions/lib/supabase.ts
index 916ed17f38..e487ed4a08 100644
--- a/packages/database/supabase/functions/lib/supabase.ts
+++ b/packages/database/supabase/functions/lib/supabase.ts
@@ -1,7 +1,26 @@
+import { createHash } from "node:crypto";
import { createClient } from "https://esm.sh/@supabase/[email protected]";
import type { Database } from "../lib/types.ts";
+import { checkApiKeyRateLimit } from "./ratelimit.ts";
-export const getAuthFromAPIKey = async (apiKey: string) => {
+/** Hash an API key using SHA-256 for secure lookup */
+function hashApiKey(rawKey: string): string {
+ return createHash("sha256").update(rawKey).digest("hex");
+}
+
+type ApiKeyAuth = {
+ client: ReturnType<typeof createClient<Database>>;
+ companyId: string;
+ userId: string;
+ apiKeyId: string;
+ scopes: Record<string, string[]>;
+ rateLimit: number;
+ rateLimitWindow: "1m" | "1h" | "1d";
+};
+
+export const getAuthFromAPIKey = async (
+ apiKey: string
+): Promise<ApiKeyAuth | null> => {
const serviceRole = createClient<Database>(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "",
@@ -13,14 +32,25 @@ export const getAuthFromAPIKey = async (apiKey: string) => {
}
);
+ const keyHash = hashApiKey(apiKey);
+
const apiKeyRow = await serviceRole
.from("apiKey")
- .select("companyId, createdBy")
- .eq("key", apiKey)
+ .select(
+ "id, companyId, createdBy, scopes, rateLimit, rateLimitWindow, expiresAt"
+ )
+ .eq("keyHash" as any, keyHash)
.single();
if (apiKeyRow.error) return null;
+ const row = apiKeyRow.data as any;
+
+ // Check expiration
+ if (row.expiresAt && new Date(row.expiresAt) < new Date()) {
+ return null;
+ }
+
return {
client: createClient<Database>(
Deno.env.get("SUPABASE_URL") ?? "",
@@ -33,8 +63,12 @@ export const getAuthFromAPIKey = async (apiKey: string) => {
},
}
),
- companyId: apiKeyRow.data.companyId,
- userId: apiKeyRow.data.createdBy,
+ companyId: row.companyId,
+ userId: row.createdBy,
+ apiKeyId: row.id,
+ scopes: row.scopes ?? {},
+ rateLimit: row.rateLimit ?? 60,
+ rateLimitWindow: row.rateLimitWindow ?? "1m",
};
};
@@ -77,10 +111,11 @@ export const getSupabaseServiceRole = async (
);
if (apiKeyHeader && companyId) {
+ const keyHash = hashApiKey(apiKeyHeader);
const { data, error } = await serviceRole
.from("apiKey")
- .select("companyId")
- .eq("key", apiKeyHeader)
+ .select("id, companyId, rateLimit, rateLimitWindow, expiresAt")
+ .eq("keyHash" as any, keyHash)
.eq("companyId", companyId)
.single();
@@ -92,6 +127,24 @@ export const getSupabaseServiceRole = async (
throw new Error("API key not found");
}
+ const row = data as any;
+
+ // Check expiration
+ if (row.expiresAt && new Date(row.expiresAt) < new Date()) {
+ throw new Error("API key has expired");
+ }
+
+ // Check rate limit
+ const rl = await checkApiKeyRateLimit(
+ serviceRole,
+ row.id,
+ row.rateLimit ?? 60,
+ row.rateLimitWindow ?? "1m"
+ );
+ if (!rl.success) {
+ throw new Error("Rate limit exceeded");
+ }
+
return serviceRole;
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2b130a1cf5..10f2e8048e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1603,25 +1603,43 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ expiresAt: string | null
id: string
- key: string
+ keyHash: string
+ keyPreview: string | null
+ lastUsedAt: string | null
name: string
+ rateLimit: number
+ rateLimitWindow: string
+ scopes: Json
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
+ expiresAt?: string | null
id?: string
- key: string
+ keyHash: string
+ keyPreview?: string | null
+ lastUsedAt?: string | null
name: string
+ rateLimit?: number
+ rateLimitWindow?: string
+ scopes?: Json
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
+ expiresAt?: string | null
id?: string
- key?: string
+ keyHash?: string
+ keyPreview?: string | null
+ lastUsedAt?: string | null
name?: string
+ rateLimit?: number
+ rateLimitWindow?: string
+ scopes?: Json
}
Relationships: [
{
@@ -1689,6 +1707,32 @@ export type Database = {
},
]
}
+ apiKeyRateLimit: {
+ Row: {
+ apiKeyId: string
+ requestCount: number
+ windowStart: string
+ }
+ Insert: {
+ apiKeyId: string
+ requestCount?: number
+ windowStart: string
+ }
+ Update: {
+ apiKeyId?: string
+ requestCount?: number
+ windowStart?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "apiKeyRateLimit_apiKeyId_fkey"
+ columns: ["apiKeyId"]
+ isOneToOne: false
+ referencedRelation: "apiKey"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
approvalRequest: {
Row: {
amount: number | null
@@ -52148,14 +52192,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55722,6 +55766,10 @@ export type Database = {
Args: { sync_functions?: string[]; table_name_text: string }
Returns: undefined
}
+ check_api_key_rate_limit: {
+ Args: { p_api_key_id: string; p_limit: number; p_window: string }
+ Returns: Json
+ }
check_operation_dependencies: {
Args: { operation_id: string }
Returns: boolean
@@ -55921,6 +55969,7 @@ export type Database = {
workCenterId: string
}[]
}
+ get_api_key_scopes: { Args: never; Returns: Json }
get_assigned_job_operations: {
Args: { company_id: string; user_id: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20260219162954_api-key-scopes-rate-limits.sql b/packages/database/supabase/migrations/20260219162954_api-key-scopes-rate-limits.sql
new file mode 100644
index 0000000000..6e6516cd2e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260219162954_api-key-scopes-rate-limits.sql
@@ -0,0 +1,337 @@
+-- API Key Scopes, Key Hashing, Rate Limiting, and Expiration
+-- Rate limiting uses an unlogged table with a Postgres function (check_api_key_rate_limit).
+-- Scope enforcement is handled via RLS helper functions.
+
+-- ============================================================================
+-- Step 1: Add new columns to apiKey table
+-- ============================================================================
+
+ALTER TABLE "apiKey"
+ ADD COLUMN "keyHash" TEXT,
+ ADD COLUMN "keyPreview" TEXT,
+ ADD COLUMN "scopes" JSONB NOT NULL DEFAULT '{}',
+ ADD COLUMN "rateLimit" INTEGER NOT NULL DEFAULT 1000,
+ ADD COLUMN "rateLimitWindow" TEXT NOT NULL DEFAULT '1h',
+ ADD COLUMN "expiresAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN "lastUsedAt" TIMESTAMP WITH TIME ZONE;
+
+-- Backfill keyHash from existing plaintext keys
+UPDATE "apiKey"
+SET "keyHash" = encode(digest("key"::bytea, 'sha256'::text), 'hex');
+
+-- Make keyHash NOT NULL and add unique index
+ALTER TABLE "apiKey" ALTER COLUMN "keyHash" SET NOT NULL;
+CREATE UNIQUE INDEX "apiKey_keyHash_key" ON "apiKey"("keyHash");
+
+-- ============================================================================
+-- Step 2: Update SQL functions to use keyHash BEFORE dropping the key column
+-- ============================================================================
+
+-- Update get_company_id_from_api_key() to use hash lookup
+-- Note: lastUsedAt is updated at the application layer (middleware), not here,
+-- because this function runs inside RLS policy evaluation (read-only transaction).
+CREATE OR REPLACE FUNCTION get_company_id_from_api_key() RETURNS TEXT
+ LANGUAGE "plpgsql" SECURITY DEFINER
+ SET search_path = public, extensions
+ AS $$
+ DECLARE
+ company_id TEXT;
+ raw_key TEXT;
+ BEGIN
+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';
+ IF raw_key IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ SELECT "companyId" INTO company_id
+ FROM "apiKey"
+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')
+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW());
+
+ RETURN company_id;
+ END;
+$$;
+
+-- Update has_valid_api_key_for_company() to use hash lookup
+CREATE OR REPLACE FUNCTION has_valid_api_key_for_company(company TEXT) RETURNS "bool"
+ LANGUAGE "plpgsql" SECURITY DEFINER
+ SET search_path = public, extensions
+ AS $$
+ DECLARE
+ has_valid_key boolean;
+ raw_key TEXT;
+ BEGIN
+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';
+ IF raw_key IS NULL THEN
+ RETURN FALSE;
+ END IF;
+
+ SELECT EXISTS(
+ SELECT 1 FROM "apiKey"
+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')
+ AND "companyId" = company
+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW())
+ ) INTO has_valid_key;
+
+ RETURN has_valid_key;
+ END;
+$$;
+
+-- ============================================================================
+-- Step 3: Drop and recreate the RLS policy on "user" that directly references
+-- "apiKey"."key", replacing it with get_company_id_from_api_key()
+-- ============================================================================
+
+DROP POLICY IF EXISTS "Requests with an API key can select users from their company" ON "user";
+
+CREATE POLICY "Requests with an API key can select users from their company" ON "user"
+FOR SELECT USING (
+ EXISTS (
+ SELECT 1
+ FROM "userToCompany"
+ WHERE "userToCompany"."userId" = "user"."id"::text
+ AND "userToCompany"."companyId" = get_company_id_from_api_key()
+ )
+);
+
+-- ============================================================================
+-- Step 4: Backfill keyPreview from plaintext key (last 5 chars)
+-- ============================================================================
+
+UPDATE "apiKey" SET "keyPreview" = RIGHT("key", 5);
+
+-- ============================================================================
+-- Step 5: Now safe to drop the plaintext key column
+-- ============================================================================
+
+ALTER TABLE "apiKey" DROP CONSTRAINT "apiKey_key_key";
+ALTER TABLE "apiKey" DROP COLUMN "key";
+
+-- ============================================================================
+-- Step 6: Backfill existing API keys with full access scopes
+-- ============================================================================
+
+UPDATE "apiKey"
+SET "scopes" = (
+ SELECT jsonb_object_agg(perm, jsonb_build_array(ak."companyId"))
+ FROM (
+ SELECT unnest(ARRAY[
+ 'sales_view', 'sales_create', 'sales_update', 'sales_delete',
+ 'inventory_view', 'inventory_create', 'inventory_update', 'inventory_delete',
+ 'accounting_view', 'accounting_create', 'accounting_update', 'accounting_delete',
+ 'purchasing_view', 'purchasing_create', 'purchasing_update', 'purchasing_delete',
+ 'parts_view', 'parts_create', 'parts_update', 'parts_delete',
+ 'production_view', 'production_create', 'production_update', 'production_delete',
+ 'resources_view', 'resources_create', 'resources_update', 'resources_delete',
+ 'people_view', 'people_create', 'people_update', 'people_delete',
+ 'invoicing_view', 'invoicing_create', 'invoicing_update', 'invoicing_delete',
+ 'quality_view', 'quality_create', 'quality_update', 'quality_delete',
+ 'settings_view', 'settings_create', 'settings_update', 'settings_delete',
+ 'documents_view', 'documents_create', 'documents_update', 'documents_delete',
+ 'users_create', 'users_update', 'users_delete'
+ ]) as perm
+ ) perms
+)
+FROM "apiKey" ak
+WHERE "apiKey"."id" = ak."id";
+
+-- ============================================================================
+-- Step 7: New function for scope checking
+-- ============================================================================
+
+-- Get API key scopes from the current request
+CREATE OR REPLACE FUNCTION get_api_key_scopes() RETURNS JSONB
+ LANGUAGE "plpgsql" SECURITY DEFINER
+ SET search_path = public, extensions
+ AS $$
+ DECLARE
+ scopes JSONB;
+ raw_key TEXT;
+ BEGIN
+ raw_key := (current_setting('request.headers'::text, true))::json ->> 'carbon-key';
+ IF raw_key IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ SELECT "apiKey"."scopes" INTO scopes
+ FROM "apiKey"
+ WHERE "keyHash" = encode(digest(raw_key::bytea, 'sha256'::text), 'hex')
+ AND ("expiresAt" IS NULL OR "expiresAt" > NOW());
+
+ RETURN scopes;
+ END;
+$$;
+-- ============================================================================
+-- Step 8: Unlogged table + function for rate limiting
+-- Unlogged tables skip WAL for performance; data is ephemeral (lost on crash,
+-- which is acceptable for rate limit counters).
+-- ============================================================================
+
+CREATE UNLOGGED TABLE "apiKeyRateLimit" (
+ "apiKeyId" TEXT NOT NULL REFERENCES "apiKey"("id") ON DELETE CASCADE,
+ "windowStart" TIMESTAMPTZ NOT NULL,
+ "requestCount" INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY ("apiKeyId", "windowStart")
+);
+
+CREATE OR REPLACE FUNCTION check_api_key_rate_limit(
+ p_api_key_id TEXT,
+ p_limit INTEGER,
+ p_window TEXT -- '1m', '1h', '1d'
+) RETURNS JSONB
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_window_start TIMESTAMPTZ;
+ v_interval INTERVAL;
+ v_count INTEGER;
+BEGIN
+ v_interval := CASE p_window
+ WHEN '1m' THEN INTERVAL '1 minute'
+ WHEN '1h' THEN INTERVAL '1 hour'
+ WHEN '1d' THEN INTERVAL '1 day'
+ ELSE INTERVAL '1 hour'
+ END;
+
+ v_window_start := date_trunc(
+ CASE p_window
+ WHEN '1m' THEN 'minute'
+ WHEN '1h' THEN 'hour'
+ WHEN '1d' THEN 'day'
+ ELSE 'hour'
+ END,
+ NOW()
+ );
+
+ -- Atomic upsert: insert or increment counter in one statement
+ INSERT INTO "apiKeyRateLimit" ("apiKeyId", "windowStart", "requestCount")
+ VALUES (p_api_key_id, v_window_start, 1)
+ ON CONFLICT ("apiKeyId", "windowStart")
+ DO UPDATE SET "requestCount" = "apiKeyRateLimit"."requestCount" + 1
+ RETURNING "requestCount" INTO v_count;
+
+ -- Probabilistic cleanup: ~1% of requests clean up expired windows
+ IF random() < 0.01 THEN
+ DELETE FROM "apiKeyRateLimit"
+ WHERE "apiKeyId" = p_api_key_id
+ AND "windowStart" < v_window_start;
+ END IF;
+
+ RETURN jsonb_build_object(
+ 'success', v_count <= p_limit,
+ 'count', v_count,
+ 'limit', p_limit,
+ 'remaining', GREATEST(p_limit - v_count, 0),
+ 'resetAt', EXTRACT(EPOCH FROM (v_window_start + v_interval))::BIGINT * 1000
+ );
+END;
+$$;
+
+-- ============================================================================
+-- Step 9: Update RLS helper functions for scope checking
+-- Rate limiting is NOT done in RLS (read-only transaction context).
+-- It is called explicitly from application middleware and edge functions.
+-- ============================================================================
+
+CREATE OR REPLACE FUNCTION get_companies_with_any_role() RETURNS text[] LANGUAGE "plpgsql" SECURITY DEFINER
+SET search_path = public AS $$
+DECLARE
+ user_companies text[];
+ api_key_company text;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ RETURN ARRAY[api_key_company];
+ END IF;
+
+ SELECT array_agg("companyId"::text)
+ INTO user_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text;
+
+ RETURN user_companies;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION get_companies_with_employee_role() RETURNS text[] LANGUAGE "plpgsql" SECURITY DEFINER
+SET search_path = public AS $$
+DECLARE
+ user_companies text[];
+ api_key_company text;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ RETURN ARRAY[api_key_company];
+ END IF;
+
+ SELECT array_agg("companyId"::text)
+ INTO user_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';
+
+ RETURN user_companies;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION get_companies_with_employee_permission (permission text) RETURNS text[] LANGUAGE "plpgsql" SECURITY DEFINER
+SET search_path = public AS $$
+DECLARE
+ permission_companies text[];
+ api_key_company text;
+ employee_companies text[];
+ api_key_scopes JSONB;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ -- Get scopes for this API key
+ api_key_scopes := get_api_key_scopes();
+
+ -- NULL or empty scopes = no access
+ IF api_key_scopes IS NULL OR api_key_scopes = '{}'::jsonb THEN
+ RETURN '{}';
+ END IF;
+
+ -- Check if the requested permission exists in scopes
+ IF (api_key_scopes ? permission)
+ AND api_key_company = ANY(jsonb_to_text_array(api_key_scopes->permission)) THEN
+ RETURN ARRAY[api_key_company];
+ ELSE
+ RETURN '{}';
+ END IF;
+ END IF;
+
+ -- Normal user permission flow (unchanged)
+ SELECT array_agg("companyId"::text)
+ INTO employee_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';
+
+ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))
+ INTO permission_companies
+ FROM public."userPermission"
+ WHERE id::text = auth.uid()::text;
+
+ IF permission_companies IS NOT NULL AND employee_companies IS NOT NULL THEN
+ SELECT array_agg(company)
+ INTO permission_companies
+ FROM unnest(permission_companies) company
+ WHERE company = ANY(employee_companies);
+ ELSE
+ permission_companies := '{}';
+ END IF;
+
+ IF permission_companies IS NOT NULL AND '0'::text = ANY(permission_companies) THEN
+ SELECT array_agg(id::text)
+ INTO permission_companies
+ FROM company
+ WHERE id::text = ANY(employee_companies);
+ END IF;
+
+ RETURN permission_companies;
+END;
+$$;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20260227130000_platform-rate-limits.sql b/packages/database/supabase/migrations/20260227130000_platform-rate-limits.sql
new file mode 100644
index 0000000000..c88df48189
--- /dev/null
+++ b/packages/database/supabase/migrations/20260227130000_platform-rate-limits.sql
@@ -0,0 +1,12 @@
+-- Make API key rate limits platform-controlled only (not user-configurable).
+-- Default: 60 requests per 60 seconds (1 minute).
+
+-- Update column defaults
+ALTER TABLE "apiKey"
+ ALTER COLUMN "rateLimit" SET DEFAULT 60,
+ ALTER COLUMN "rateLimitWindow" SET DEFAULT '1m';
+
+-- Migrate all existing API keys to the new default
+UPDATE "apiKey"
+SET "rateLimit" = 60,
+ "rateLimitWindow" = '1m';
diff --git a/packages/database/supabase/migrations/20260228000000_rls-refactor-3.sql b/packages/database/supabase/migrations/20260228000000_rls-refactor-3.sql
new file mode 100644
index 0000000000..71279f56b5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260228000000_rls-refactor-3.sql
@@ -0,0 +1,3358 @@
+-- ============================================================================
+-- RLS Refactor 3: Continue standardizing RLS policies
+-- Continues work from 20250201181148_rls-refactor.sql and 20250208221244_rls-refactor-2.sql
+-- ============================================================================
+
+
+
+-- location
+
+DROP POLICY IF EXISTS "Employees can view locations for their companies" ON "public"."location";
+DROP POLICY IF EXISTS "Employees with resources_create can insert locations" ON "public"."location";
+DROP POLICY IF EXISTS "Employees with resources_update can update locations" ON "public"."location";
+DROP POLICY IF EXISTS "Employees with resources_delete can delete locations" ON "public"."location";
+DROP POLICY IF EXISTS "Requests with an API key can access locations" ON "public"."location";
+
+CREATE POLICY "SELECT" ON "public"."location"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."location"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."location"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."location"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]
+ )
+);
+
+-- partner
+
+DROP POLICY IF EXISTS "Employees with resources_view can view partners" ON "public"."partner";
+DROP POLICY IF EXISTS "Employees with resources_create can insert partners" ON "public"."partner";
+DROP POLICY IF EXISTS "Employees with resources_update can update partners" ON "public"."partner";
+DROP POLICY IF EXISTS "Employees with resources_delete can delete partners" ON "public"."partner";
+DROP POLICY IF EXISTS "Requests with an API key can access partners" ON "public"."partner";
+
+CREATE POLICY "SELECT" ON "public"."partner"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."partner"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."partner"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."partner"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]
+ )
+);
+
+-- process
+
+DROP POLICY IF EXISTS "Employees can view processes" ON "public"."process";
+DROP POLICY IF EXISTS "Employees with resources_create can insert processes" ON "public"."process";
+DROP POLICY IF EXISTS "Employees with resources_update can update processes" ON "public"."process";
+DROP POLICY IF EXISTS "Employees with resources_delete can delete processes" ON "public"."process";
+DROP POLICY IF EXISTS "Requests with an API key can access processes" ON "public"."process";
+
+CREATE POLICY "SELECT" ON "public"."process"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."process"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."process"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."process"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]
+ )
+);
+
+-- shift
+
+DROP POLICY IF EXISTS "Employees can view shifts" ON "public"."shift";
+DROP POLICY IF EXISTS "Employees with people_create can insert shifts" ON "public"."shift";
+DROP POLICY IF EXISTS "Employees with people_update can update shifts" ON "public"."shift";
+DROP POLICY IF EXISTS "Employees with people_delete can delete shifts" ON "public"."shift";
+DROP POLICY IF EXISTS "Requests with an API key can access shifts" ON "public"."shift";
+
+CREATE POLICY "SELECT" ON "public"."shift"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."shift"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."shift"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."shift"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_delete'))::text[]
+ )
+);
+
+-- workCenter
+
+DROP POLICY IF EXISTS "Employees can view work centers" ON "public"."workCenter";
+DROP POLICY IF EXISTS "Employees with resources_create can insert work centers" ON "public"."workCenter";
+DROP POLICY IF EXISTS "Employees with resources_update can update work centers" ON "public"."workCenter";
+DROP POLICY IF EXISTS "Employees with resources_delete can delete work centers" ON "public"."workCenter";
+DROP POLICY IF EXISTS "Requests with an API key can access work centers" ON "public"."workCenter";
+
+CREATE POLICY "SELECT" ON "public"."workCenter"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."workCenter"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."workCenter"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."workCenter"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]
+ )
+);
+
+-- workCenterProcess
+
+DROP POLICY IF EXISTS "Employees can view work center/processes" ON "public"."workCenterProcess";
+DROP POLICY IF EXISTS "Employees with resources_create can insert work center/processes" ON "public"."workCenterProcess";
+DROP POLICY IF EXISTS "Employees with resources_update can update work center/processes" ON "public"."workCenterProcess";
+DROP POLICY IF EXISTS "Employees with resources_delete can delete work center/processes" ON "public"."workCenterProcess";
+DROP POLICY IF EXISTS "Requests with an API key can access work center processes" ON "public"."workCenterProcess";
+
+CREATE POLICY "SELECT" ON "public"."workCenterProcess"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."workCenterProcess"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."workCenterProcess"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."workCenterProcess"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 2: Parts & Inventory
+-- ============================================================================
+
+-- itemPostingGroup
+
+DROP POLICY IF EXISTS "Employees with parts_view can view item groups" ON "public"."itemPostingGroup";
+DROP POLICY IF EXISTS "Employees with parts_create can insert item groups" ON "public"."itemPostingGroup";
+DROP POLICY IF EXISTS "Employees with parts_update can update item groups" ON "public"."itemPostingGroup";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete item groups" ON "public"."itemPostingGroup";
+DROP POLICY IF EXISTS "Requests with an API key can access item posting groups" ON "public"."itemPostingGroup";
+
+CREATE POLICY "SELECT" ON "public"."itemPostingGroup"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."itemPostingGroup"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."itemPostingGroup"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."itemPostingGroup"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_delete'))::text[]
+ )
+);
+
+-- itemReplenishment
+
+DROP POLICY IF EXISTS "Employees with part_view can view part costs" ON "public"."itemReplenishment";
+DROP POLICY IF EXISTS "Employees with parts_update can update part costs" ON "public"."itemReplenishment";
+DROP POLICY IF EXISTS "Suppliers with parts_view can view part replenishment they supply" ON "public"."itemReplenishment";
+DROP POLICY IF EXISTS "Suppliers with parts_update can update parts replenishments that they supply" ON "public"."itemReplenishment";
+DROP POLICY IF EXISTS "Requests with an API key can access item replenishment" ON "public"."itemReplenishment";
+
+CREATE POLICY "SELECT" ON "public"."itemReplenishment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."itemReplenishment"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."itemReplenishment"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."itemReplenishment"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- itemUnitSalePrice
+
+DROP POLICY IF EXISTS "Employees with part_view can view part sale prices" ON "public"."itemUnitSalePrice";
+DROP POLICY IF EXISTS "Employees with parts_update can update part sale prices" ON "public"."itemUnitSalePrice";
+DROP POLICY IF EXISTS "Requests with an API key can access item unit sale prices" ON "public"."itemUnitSalePrice";
+
+CREATE POLICY "SELECT" ON "public"."itemUnitSalePrice"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('parts_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."itemUnitSalePrice"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."itemUnitSalePrice"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."itemUnitSalePrice"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- makeMethod
+
+DROP POLICY IF EXISTS "Employees with parts_view can view make methods" ON "public"."makeMethod";
+DROP POLICY IF EXISTS "Employees with parts_create can create make methods" ON "public"."makeMethod";
+DROP POLICY IF EXISTS "Employees with parts_update can update make methods" ON "public"."makeMethod";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete make methods" ON "public"."makeMethod";
+DROP POLICY IF EXISTS "Requests with an API key can access make methods" ON "public"."makeMethod";
+
+CREATE POLICY "SELECT" ON "public"."makeMethod"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."makeMethod"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."makeMethod"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."makeMethod"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- methodMaterial
+
+DROP POLICY IF EXISTS "Employees with parts_view can view method materials" ON "public"."methodMaterial";
+DROP POLICY IF EXISTS "Employees with parts_create can create method materials" ON "public"."methodMaterial";
+DROP POLICY IF EXISTS "Employees with parts_update can update method materials" ON "public"."methodMaterial";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete method materials" ON "public"."methodMaterial";
+DROP POLICY IF EXISTS "Requests with an API key can access method materials" ON "public"."methodMaterial";
+
+CREATE POLICY "SELECT" ON "public"."methodMaterial"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."methodMaterial"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."methodMaterial"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."methodMaterial"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- methodOperation
+
+DROP POLICY IF EXISTS "Employees with parts_view can view method operation" ON "public"."methodOperation";
+DROP POLICY IF EXISTS "Employees with parts_create can create method operation" ON "public"."methodOperation";
+DROP POLICY IF EXISTS "Employees with parts_update can update method operation" ON "public"."methodOperation";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete method operation" ON "public"."methodOperation";
+DROP POLICY IF EXISTS "Requests with an API key can access method operations" ON "public"."methodOperation";
+
+CREATE POLICY "SELECT" ON "public"."methodOperation"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."methodOperation"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."methodOperation"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."methodOperation"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- modelUpload
+
+DROP POLICY IF EXISTS "Employees can view model uploads" ON "public"."modelUpload";
+DROP POLICY IF EXISTS "Employees with parts_create can create model uploads" ON "public"."modelUpload";
+DROP POLICY IF EXISTS "Employees with parts_update can update model uploads" ON "public"."modelUpload";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete model uploads" ON "public"."modelUpload";
+DROP POLICY IF EXISTS "Requests with an API key can access model uploads" ON "public"."modelUpload";
+
+CREATE POLICY "SELECT" ON "public"."modelUpload"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."modelUpload"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."modelUpload"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."modelUpload"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- part
+
+DROP POLICY IF EXISTS "Employees can view parts" ON "public"."part";
+DROP POLICY IF EXISTS "Employees with parts_create can insert parts" ON "public"."part";
+DROP POLICY IF EXISTS "Employees with parts_update can update parts" ON "public"."part";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete parts" ON "public"."part";
+DROP POLICY IF EXISTS "Requests with an API key can access parts" ON "public"."part";
+
+CREATE POLICY "SELECT" ON "public"."part"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."part"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."part"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."part"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- pickMethod
+
+DROP POLICY IF EXISTS "Employees with part_view can view part planning" ON "public"."pickMethod";
+DROP POLICY IF EXISTS "Employees with part_view can insert part planning" ON "public"."pickMethod";
+DROP POLICY IF EXISTS "Employees with parts_update can update part planning" ON "public"."pickMethod";
+DROP POLICY IF EXISTS "Requests with an API key can access pick methods" ON "public"."pickMethod";
+
+CREATE POLICY "SELECT" ON "public"."pickMethod"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."pickMethod"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."pickMethod"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+-- service
+
+DROP POLICY IF EXISTS "Employees can view services" ON "public"."service";
+DROP POLICY IF EXISTS "Employees with parts_create can insert services" ON "public"."service";
+DROP POLICY IF EXISTS "Employees with parts_update can update services" ON "public"."service";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete services" ON "public"."service";
+DROP POLICY IF EXISTS "Requests with an API key can access services" ON "public"."service";
+
+CREATE POLICY "SELECT" ON "public"."service"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."service"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."service"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."service"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- shelf
+
+DROP POLICY IF EXISTS "Authenticated users can view shelves" ON "public"."shelf";
+DROP POLICY IF EXISTS "Employees with parts_create can insert shelves" ON "public"."shelf";
+DROP POLICY IF EXISTS "Employees with parts_update can update shelves" ON "public"."shelf";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete shelves" ON "public"."shelf";
+DROP POLICY IF EXISTS "Requests with an API key can access shelves" ON "public"."shelf";
+
+CREATE POLICY "SELECT" ON "public"."shelf"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."shelf"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."shelf"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."shelf"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- unitOfMeasure
+
+DROP POLICY IF EXISTS "Employees can view units of measure" ON "public"."unitOfMeasure";
+DROP POLICY IF EXISTS "Employees with parts_create can insert units of measure" ON "public"."unitOfMeasure";
+DROP POLICY IF EXISTS "Employees with parts_update can update units of measure" ON "public"."unitOfMeasure";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete units of measure" ON "public"."unitOfMeasure";
+DROP POLICY IF EXISTS "Requests with an API key can access units of measure" ON "public"."unitOfMeasure";
+
+CREATE POLICY "SELECT" ON "public"."unitOfMeasure"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_any_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."unitOfMeasure"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."unitOfMeasure"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."unitOfMeasure"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- warehouse
+
+DROP POLICY IF EXISTS "Employees can view warehouses" ON "public"."warehouse";
+DROP POLICY IF EXISTS "Employees with parts_create can insert warehouses" ON "public"."warehouse";
+DROP POLICY IF EXISTS "Employees with parts_update can update warehouses" ON "public"."warehouse";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete warehouses" ON "public"."warehouse";
+DROP POLICY IF EXISTS "Requests with an API key can access warehouses" ON "public"."warehouse";
+
+CREATE POLICY "SELECT" ON "public"."warehouse"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."warehouse"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."warehouse"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."warehouse"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 3: Accounting
+-- ============================================================================
+
+-- journal
+
+DROP POLICY IF EXISTS "Employees with accounting_view can view journals" ON "public"."journal";
+DROP POLICY IF EXISTS "Employees with accounting_create can insert journals" ON "public"."journal";
+DROP POLICY IF EXISTS "Requests with an API key can access journals" ON "public"."journal";
+
+CREATE POLICY "SELECT" ON "public"."journal"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."journal"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_create'))::text[]
+ )
+);
+
+-- journalLine
+
+DROP POLICY IF EXISTS "Employees with accounting_view can view journal lines" ON "public"."journalLine";
+DROP POLICY IF EXISTS "Employees with accounting_create can insert journal lines" ON "public"."journalLine";
+DROP POLICY IF EXISTS "Requests with an API key can access journal lines" ON "public"."journalLine";
+
+CREATE POLICY "SELECT" ON "public"."journalLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."journalLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_create'))::text[]
+ )
+);
+
+-- paymentTerm
+
+DROP POLICY IF EXISTS "Certain employees can view payment terms" ON "public"."paymentTerm";
+DROP POLICY IF EXISTS "Employees with accounting_create can insert payment terms" ON "public"."paymentTerm";
+DROP POLICY IF EXISTS "Employees with accounting_update can update payment terms" ON "public"."paymentTerm";
+DROP POLICY IF EXISTS "Employees with accounting_delete can delete payment terms" ON "public"."paymentTerm";
+DROP POLICY IF EXISTS "Requests with an API key can access payment terms" ON "public"."paymentTerm";
+
+CREATE POLICY "SELECT" ON "public"."paymentTerm"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('accounting_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."paymentTerm"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."paymentTerm"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."paymentTerm"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_delete'))::text[]
+ )
+);
+
+-- postingGroupInventory
+
+DROP POLICY IF EXISTS "Employees with accounting_view can view inventory posting groups" ON "public"."postingGroupInventory";
+DROP POLICY IF EXISTS "Employees with accounting_update can update inventory posting groups" ON "public"."postingGroupInventory";
+DROP POLICY IF EXISTS "Requests with an API key can access inventory posting groups" ON "public"."postingGroupInventory";
+
+CREATE POLICY "SELECT" ON "public"."postingGroupInventory"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."postingGroupInventory"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_update'))::text[]
+ )
+);
+
+-- postingGroupPurchasing
+
+DROP POLICY IF EXISTS "Employees with accounting_view can view purchasing posting groups" ON "public"."postingGroupPurchasing";
+DROP POLICY IF EXISTS "Employees with accounting_update can update purchasing posting groups" ON "public"."postingGroupPurchasing";
+DROP POLICY IF EXISTS "Requests with an API key can access purchasing posting groups" ON "public"."postingGroupPurchasing";
+
+CREATE POLICY "SELECT" ON "public"."postingGroupPurchasing"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."postingGroupPurchasing"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_update'))::text[]
+ )
+);
+
+-- postingGroupSales
+
+DROP POLICY IF EXISTS "Employees with accounting_view can view sales posting groups" ON "public"."postingGroupSales";
+DROP POLICY IF EXISTS "Employees with accounting_update can update sales posting groups" ON "public"."postingGroupSales";
+DROP POLICY IF EXISTS "Requests with an API key can access sales posting groups" ON "public"."postingGroupSales";
+
+CREATE POLICY "SELECT" ON "public"."postingGroupSales"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."postingGroupSales"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_update'))::text[]
+ )
+);
+
+-- supplierLedger
+
+DROP POLICY IF EXISTS "Certain employees can view the parts ledger" ON "public"."supplierLedger";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier ledger" ON "public"."supplierLedger";
+
+CREATE POLICY "SELECT" ON "public"."supplierLedger"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('accounting_view'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 4: Production
+-- ============================================================================
+
+-- job (policies were refactored in 20250707135534 with customer checks - removing those)
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."job";
+DROP POLICY IF EXISTS "INSERT" ON "public"."job";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."job";
+DROP POLICY IF EXISTS "DELETE" ON "public"."job";
+
+CREATE POLICY "SELECT" ON "public"."job"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."job"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."job"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."job"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- jobMakeMethod
+
+DROP POLICY IF EXISTS "Requests with an API key can access jobs" ON "public"."jobMakeMethod";
+DROP POLICY IF EXISTS "Employees can view job make methods" ON "public"."jobMakeMethod";
+DROP POLICY IF EXISTS "Employees with production_create can insert job make methods" ON "public"."jobMakeMethod";
+DROP POLICY IF EXISTS "Employees with production_update can update job make methods" ON "public"."jobMakeMethod";
+DROP POLICY IF EXISTS "Employees with production_delete can delete job make methods" ON "public"."jobMakeMethod";
+DROP POLICY IF EXISTS "Customers with production_view can view their own job make methods" ON "public"."jobMakeMethod";
+
+CREATE POLICY "SELECT" ON "public"."jobMakeMethod"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."jobMakeMethod"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobMakeMethod"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."jobMakeMethod"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- jobMaterial (policies were refactored in 20250707135534 with customer checks - removing those)
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."jobMaterial";
+DROP POLICY IF EXISTS "INSERT" ON "public"."jobMaterial";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."jobMaterial";
+DROP POLICY IF EXISTS "DELETE" ON "public"."jobMaterial";
+
+CREATE POLICY "SELECT" ON "public"."jobMaterial"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."jobMaterial"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobMaterial"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."jobMaterial"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- jobOperation (policies were refactored in 20250707135534 with customer checks - removing those)
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."jobOperation";
+DROP POLICY IF EXISTS "INSERT" ON "public"."jobOperation";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."jobOperation";
+DROP POLICY IF EXISTS "DELETE" ON "public"."jobOperation";
+
+CREATE POLICY "SELECT" ON "public"."jobOperation"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."jobOperation"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobOperation"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."jobOperation"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- productionEvent
+
+DROP POLICY IF EXISTS "Requests with an API key can access production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Employees can view their own production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Users with production_view can see all production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Users with production_create can insert production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Users with production_update can update production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Users with production_delete can delete production events" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Employees can insert production events for their company's job operations" ON "public"."productionEvent";
+DROP POLICY IF EXISTS "Employees can update production events for their company's job operations" ON "public"."productionEvent";
+
+CREATE POLICY "SELECT" ON "public"."productionEvent"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."productionEvent"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."productionEvent"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."productionEvent"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- productionQuantity
+
+DROP POLICY IF EXISTS "Employees can view production quantities" ON "public"."productionQuantity";
+DROP POLICY IF EXISTS "Employees can insert production quantities" ON "public"."productionQuantity";
+DROP POLICY IF EXISTS "Employees can update production quantities" ON "public"."productionQuantity";
+DROP POLICY IF EXISTS "Employees can delete production quantities" ON "public"."productionQuantity";
+DROP POLICY IF EXISTS "Employees can insert production quantities for their company's job operations" ON "public"."productionQuantity";
+
+CREATE POLICY "SELECT" ON "public"."productionQuantity"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."productionQuantity"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."productionQuantity"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."productionQuantity"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- scrapReason
+
+DROP POLICY IF EXISTS "Employees can view scrap reasons" ON "public"."scrapReason";
+DROP POLICY IF EXISTS "Employees with production_create can insert scrap reasons" ON "public"."scrapReason";
+DROP POLICY IF EXISTS "Employees with production_update can update scrap reasons" ON "public"."scrapReason";
+DROP POLICY IF EXISTS "Employees with production_delete can delete scrap reasons" ON "public"."scrapReason";
+
+CREATE POLICY "SELECT" ON "public"."scrapReason"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."scrapReason"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."scrapReason"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."scrapReason"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 5: Purchasing
+-- ============================================================================
+
+-- purchaseOrder
+
+DROP POLICY IF EXISTS "Employees with purchasing_view, inventory_view, or invoicing_view can view purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can their own purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Suppliers with purchasing_update can their own purchase orders" ON "public"."purchaseOrder";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase orders" ON "public"."purchaseOrder";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrder"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('inventory_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('invoicing_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseOrder"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseOrder"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseOrder"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- purchaseOrderDelivery
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can their own purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Suppliers with purchasing_update can their own purchase order deliveries" ON "public"."purchaseOrderDelivery";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase order deliveries" ON "public"."purchaseOrderDelivery";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrderDelivery"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseOrderDelivery"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseOrderDelivery"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseOrderDelivery"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- purchaseOrderLine
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can their own purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Suppliers with purchasing_create can create lines on their own purchase order" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Suppliers with purchasing_update can their own purchase order lines" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "public"."purchaseOrderLine";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase order lines" ON "public"."purchaseOrderLine";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrderLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseOrderLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseOrderLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseOrderLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- purchaseOrderPayment
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchase order payments" ON "public"."purchaseOrderPayment";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create purchase order payments" ON "public"."purchaseOrderPayment";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update purchase order payments" ON "public"."purchaseOrderPayment";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete purchase order payments" ON "public"."purchaseOrderPayment";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase order payments" ON "public"."purchaseOrderPayment";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrderPayment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseOrderPayment"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseOrderPayment"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseOrderPayment"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- purchaseOrderStatusHistory (no companyId - uses FK lookup)
+
+DROP POLICY IF EXISTS "Users can view purchase order status history" ON "public"."purchaseOrderStatusHistory";
+DROP POLICY IF EXISTS "Users can insert purchase order status history" ON "public"."purchaseOrderStatusHistory";
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchase order status history" ON "public"."purchaseOrderStatusHistory";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase order status history" ON "public"."purchaseOrderStatusHistory";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrderStatusHistory"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+-- purchaseOrderTransaction (no companyId - uses FK lookup)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view purchase order transactions" ON "public"."purchaseOrderTransaction";
+DROP POLICY IF EXISTS "User with purchasing_update can insert purchase order transactions" ON "public"."purchaseOrderTransaction";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase order transactions" ON "public"."purchaseOrderTransaction";
+
+CREATE POLICY "SELECT" ON "public"."purchaseOrderTransaction"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseOrderTransaction"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 6: Invoicing
+-- ============================================================================
+
+-- purchaseInvoice
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP invoices" ON "public"."purchaseInvoice";
+DROP POLICY IF EXISTS "Employees with invoicing_create can insert AP invoices" ON "public"."purchaseInvoice";
+DROP POLICY IF EXISTS "Employees with invoicing_update can update AP invoices" ON "public"."purchaseInvoice";
+DROP POLICY IF EXISTS "Employees with invoicing_delete can delete AP invoices" ON "public"."purchaseInvoice";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase invoices" ON "public"."purchaseInvoice";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoice"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseInvoice"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseInvoice"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseInvoice"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]
+ )
+);
+
+-- purchaseInvoiceDelivery
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view purchase invoice deliveries" ON "public"."purchaseInvoiceDelivery";
+DROP POLICY IF EXISTS "Employees with invoicing_create can insert purchase invoice deliveries" ON "public"."purchaseInvoiceDelivery";
+DROP POLICY IF EXISTS "Employees with invoicing_update can update purchase invoice deliveries" ON "public"."purchaseInvoiceDelivery";
+DROP POLICY IF EXISTS "Employees with invoicing_delete can delete purchase invoice deliveries" ON "public"."purchaseInvoiceDelivery";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoiceDelivery"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseInvoiceDelivery"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseInvoiceDelivery"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseInvoiceDelivery"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]
+ )
+);
+
+-- purchaseInvoiceLine
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP invoice lines" ON "public"."purchaseInvoiceLine";
+DROP POLICY IF EXISTS "Employees with invoicing_create can insert AP invoice lines" ON "public"."purchaseInvoiceLine";
+DROP POLICY IF EXISTS "Employees with invoicing_update can update AP invoice lines" ON "public"."purchaseInvoiceLine";
+DROP POLICY IF EXISTS "Employees with invoicing_delete can delete AP invoice lines" ON "public"."purchaseInvoiceLine";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase invoice lines" ON "public"."purchaseInvoiceLine";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoiceLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchaseInvoiceLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchaseInvoiceLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchaseInvoiceLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]
+ )
+);
+
+-- purchaseInvoicePaymentRelation (no companyId - uses FK lookup, SELECT only)
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP invoice/payment relations" ON "public"."purchaseInvoicePaymentRelation";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase invoice payment relations" ON "public"."purchaseInvoicePaymentRelation";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoicePaymentRelation"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice') = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+-- purchaseInvoicePriceChange (no companyId - uses FK lookup, SELECT only)
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP invoice price changes" ON "public"."purchaseInvoicePriceChange";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase invoice price changes" ON "public"."purchaseInvoicePriceChange";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoicePriceChange"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice') = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+-- purchaseInvoiceStatusHistory (no companyId - uses FK lookup, SELECT only)
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP invoices status history" ON "public"."purchaseInvoiceStatusHistory";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase invoice status history" ON "public"."purchaseInvoiceStatusHistory";
+
+CREATE POLICY "SELECT" ON "public"."purchaseInvoiceStatusHistory"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice') = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+-- purchasePayment
+
+DROP POLICY IF EXISTS "Employees with invoicing_view can view AP payments" ON "public"."purchasePayment";
+DROP POLICY IF EXISTS "Employees with invoicing_create can insert AP payments" ON "public"."purchasePayment";
+DROP POLICY IF EXISTS "Employees with invoicing_update can update AP payments" ON "public"."purchasePayment";
+DROP POLICY IF EXISTS "Employees with invoicing_delete can delete AP payments" ON "public"."purchasePayment";
+DROP POLICY IF EXISTS "Requests with an API key can access purchase payments" ON "public"."purchasePayment";
+
+CREATE POLICY "SELECT" ON "public"."purchasePayment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."purchasePayment"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."purchasePayment"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."purchasePayment"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 7: Sales - Quotes
+-- ============================================================================
+
+-- noQuoteReason (has new-style policies from a later migration)
+
+DROP POLICY IF EXISTS "Employees can view no quote reasons" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "Employees with sales_create can insert no quote reasons" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "Employees with sales_update can update no quote reasons" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete no quote reasons" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "SELECT" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "INSERT" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."noQuoteReason";
+DROP POLICY IF EXISTS "DELETE" ON "public"."noQuoteReason";
+
+CREATE POLICY "SELECT" ON "public"."noQuoteReason"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."noQuoteReason"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."noQuoteReason"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."noQuoteReason"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- opportunity
+
+DROP POLICY IF EXISTS "Employees with sales_view can view opportunities" ON "public"."opportunity";
+DROP POLICY IF EXISTS "Employees with sales_create can insert opportunities" ON "public"."opportunity";
+DROP POLICY IF EXISTS "Employees with sales_create can update opportunities" ON "public"."opportunity";
+DROP POLICY IF EXISTS "Requests with an API key can access opportunities" ON "public"."opportunity";
+DROP POLICY IF EXISTS "SELECT" ON "public"."opportunity";
+DROP POLICY IF EXISTS "INSERT" ON "public"."opportunity";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."opportunity";
+DROP POLICY IF EXISTS "DELETE" ON "public"."opportunity";
+
+CREATE POLICY "SELECT" ON "public"."opportunity"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."opportunity"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."opportunity"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+-- quote
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Employees with sales_create can create quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Employees with sales_update can update quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Customers with sales_view can their own quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Customers with sales_update can their own quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "Requests with an API key can access quotes" ON "public"."quote";
+DROP POLICY IF EXISTS "SELECT" ON "public"."quote";
+DROP POLICY IF EXISTS "INSERT" ON "public"."quote";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."quote";
+DROP POLICY IF EXISTS "DELETE" ON "public"."quote";
+
+CREATE POLICY "SELECT" ON "public"."quote"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quote"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quote"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quote"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quoteFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own quote favorites" ON "public"."quoteFavorite";
+DROP POLICY IF EXISTS "Users can create their own quote favorites" ON "public"."quoteFavorite";
+DROP POLICY IF EXISTS "Users can delete their own quote favorites" ON "public"."quoteFavorite";
+DROP POLICY IF EXISTS "Requests with an API key can access quote favorites" ON "public"."quoteFavorite";
+
+CREATE POLICY "SELECT" ON "public"."quoteFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."quoteFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."quoteFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- quoteLine
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Customers with sales_view can their own quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Customers with sales_create can create lines on their own quote" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Customers with sales_update can their own quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Customers with sales_delete can delete lines on their own quote" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "Requests with an API key can access quote lines" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "SELECT" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "INSERT" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."quoteLine";
+DROP POLICY IF EXISTS "DELETE" ON "public"."quoteLine";
+
+CREATE POLICY "SELECT" ON "public"."quoteLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quoteLinePrice (FK via quoteLineId -> quoteLine)
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote line pricing" ON "public"."quoteLinePrice";
+DROP POLICY IF EXISTS "Employees with sales_create can insert quote line pricing" ON "public"."quoteLinePrice";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote line pricing" ON "public"."quoteLinePrice";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote line pricing" ON "public"."quoteLinePrice";
+DROP POLICY IF EXISTS "Requests with an API key can access quote line prices" ON "public"."quoteLinePrice";
+
+CREATE POLICY "SELECT" ON "public"."quoteLinePrice"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("quoteLineId", 'quoteLine') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteLinePrice"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("quoteLineId", 'quoteLine') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteLinePrice"
+FOR UPDATE USING (
+ get_company_id_from_foreign_key("quoteLineId", 'quoteLine') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteLinePrice"
+FOR DELETE USING (
+ get_company_id_from_foreign_key("quoteLineId", 'quoteLine') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quoteMakeMethod
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote make methods" ON "public"."quoteMakeMethod";
+DROP POLICY IF EXISTS "Customers with sales_view can their own quote make methods" ON "public"."quoteMakeMethod";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote make methods" ON "public"."quoteMakeMethod";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote make methods" ON "public"."quoteMakeMethod";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote make methods" ON "public"."quoteMakeMethod";
+DROP POLICY IF EXISTS "Requests with an API key can access quote make methods" ON "public"."quoteMakeMethod";
+
+CREATE POLICY "SELECT" ON "public"."quoteMakeMethod"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteMakeMethod"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteMakeMethod"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteMakeMethod"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quoteMaterial
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote materials" ON "public"."quoteMaterial";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote materials" ON "public"."quoteMaterial";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote materials" ON "public"."quoteMaterial";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote materials" ON "public"."quoteMaterial";
+DROP POLICY IF EXISTS "Requests with an API key can access quote materials" ON "public"."quoteMaterial";
+
+CREATE POLICY "SELECT" ON "public"."quoteMaterial"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteMaterial"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteMaterial"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteMaterial"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quoteOperation
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote operations" ON "public"."quoteOperation";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote operations" ON "public"."quoteOperation";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote operations" ON "public"."quoteOperation";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote operations" ON "public"."quoteOperation";
+DROP POLICY IF EXISTS "Requests with an API key can access quote operations" ON "public"."quoteOperation";
+
+CREATE POLICY "SELECT" ON "public"."quoteOperation"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteOperation"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteOperation"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteOperation"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- quotePayment
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote payments" ON "public"."quotePayment";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote payments" ON "public"."quotePayment";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote payments" ON "public"."quotePayment";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote payments" ON "public"."quotePayment";
+DROP POLICY IF EXISTS "Requests with an API can access quote payments" ON "public"."quotePayment";
+
+
+-- quoteShipment
+
+DROP POLICY IF EXISTS "Employees with sales_view can view quote shipments" ON "public"."quoteShipment";
+DROP POLICY IF EXISTS "Employees with sales_create can create quote shipments" ON "public"."quoteShipment";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote shipments" ON "public"."quoteShipment";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote shipments" ON "public"."quoteShipment";
+DROP POLICY IF EXISTS "Requests with an API can access quote shipments" ON "public"."quoteShipment";
+
+
+-- ============================================================================
+-- Batch 8: Sales - Orders & RFQs
+-- ============================================================================
+
+-- salesOrder (multi-permission SELECT)
+
+DROP POLICY IF EXISTS "Employees with sales_view, inventory_view, or invoicing_view can view sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Employees with sales_update can update sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Customers with sales_view can their own sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Customers with sales_create can create lines on their own sales order" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Customers with sales_update can update their own sales orders" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Customers with sales_delete can delete lines on their own sales order" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "SELECT" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "INSERT" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."salesOrder";
+DROP POLICY IF EXISTS "DELETE" ON "public"."salesOrder";
+
+CREATE POLICY "SELECT" ON "public"."salesOrder"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('inventory_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('invoicing_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrder"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrder"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrder"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- salesOrderFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own sales order favorites" ON "public"."salesOrderFavorite";
+DROP POLICY IF EXISTS "Users can create their own sales order favorites" ON "public"."salesOrderFavorite";
+DROP POLICY IF EXISTS "Users can delete their own sales order favorites" ON "public"."salesOrderFavorite";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order favorites" ON "public"."salesOrderFavorite";
+
+CREATE POLICY "SELECT" ON "public"."salesOrderFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."salesOrderFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."salesOrderFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- salesOrderLine
+
+DROP POLICY IF EXISTS "Employees with sales_view can view sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Employees with sales_update can update sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Customers with sales_view can their own sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Customers with sales_create can create lines on their own sales order" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Customers with sales_update can update their own sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Customers with sales_delete can delete lines on their own sales order" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order lines" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "SELECT" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "INSERT" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."salesOrderLine";
+DROP POLICY IF EXISTS "DELETE" ON "public"."salesOrderLine";
+
+CREATE POLICY "SELECT" ON "public"."salesOrderLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrderLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrderLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrderLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- salesOrderShipment
+
+DROP POLICY IF EXISTS "Employees with sales_view can view sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Employees with sales_update can update sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Customers with sales_view can their own sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Customers with sales_update can their own sales order shipments" ON "public"."salesOrderShipment";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order shipments" ON "public"."salesOrderShipment";
+
+
+-- salesOrderStatusHistory (FK via salesOrderId -> salesOrder, SELECT only)
+
+DROP POLICY IF EXISTS "Anyone with sales_view can view sales order status history" ON "public"."salesOrderStatusHistory";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order status history" ON "public"."salesOrderStatusHistory";
+
+CREATE POLICY "SELECT" ON "public"."salesOrderStatusHistory"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("salesOrderId", 'salesOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+-- salesOrderTransaction (FK via salesOrderId -> salesOrder, SELECT + INSERT only)
+
+DROP POLICY IF EXISTS "Requests with an API key can access sales order transactions" ON "public"."salesOrderTransaction";
+
+CREATE POLICY "SELECT" ON "public"."salesOrderTransaction"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("salesOrderId", 'salesOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrderTransaction"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("salesOrderId", 'salesOrder') = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+-- salesRfq
+
+DROP POLICY IF EXISTS "Employees with sales_view can view sales rfqs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales rfqs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfqs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfqs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "Customer with sales_view can view their own sales rfqs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "Requests with an API key can access sales RFQs" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "SELECT" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "INSERT" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."salesRfq";
+DROP POLICY IF EXISTS "DELETE" ON "public"."salesRfq";
+
+CREATE POLICY "SELECT" ON "public"."salesRfq"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfq"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfq"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfq"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- salesRfqFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own salesRfq favorites" ON "public"."salesRfqFavorite";
+DROP POLICY IF EXISTS "Users can create their own salesRfq favorites" ON "public"."salesRfqFavorite";
+DROP POLICY IF EXISTS "Users can delete their own salesRfq favorites" ON "public"."salesRfqFavorite";
+DROP POLICY IF EXISTS "Requests with an API key can access sales RFQ favorites" ON "public"."salesRfqFavorite";
+
+CREATE POLICY "SELECT" ON "public"."salesRfqFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."salesRfqFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."salesRfqFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- salesRfqLine
+
+DROP POLICY IF EXISTS "Employees with sales_view can view sales rfq lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales rfq lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfq lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfq lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_create can insert salesRfqLine" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete salesRfqLine" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_update can update salesRfqLine" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Employees with sales_view can view salesRfqLine" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Customers with sales_view can their own purchase order lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "Requests with an API key can access sales RFQ lines" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "SELECT" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "INSERT" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."salesRfqLine";
+DROP POLICY IF EXISTS "DELETE" ON "public"."salesRfqLine";
+
+CREATE POLICY "SELECT" ON "public"."salesRfqLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfqLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfqLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfqLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('sales_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 9: Supplier
+-- ============================================================================
+
+-- supplier
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier" ON "public"."supplier";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can their own organization" ON "public"."supplier";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create suppliers" ON "public"."supplier";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update suppliers" ON "public"."supplier";
+DROP POLICY IF EXISTS "Suppliers with purchasing_update can update their own organization" ON "public"."supplier";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete suppliers" ON "public"."supplier";
+DROP POLICY IF EXISTS "Requests with an API key can access suppliers" ON "public"."supplier";
+
+CREATE POLICY "SELECT" ON "public"."supplier"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplier"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplier"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplier"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierAccount
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier accounts" ON "public"."supplierAccount";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier accounts" ON "public"."supplierAccount";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier accounts" ON "public"."supplierAccount";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier accounts" ON "public"."supplierAccount";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier accounts" ON "public"."supplierAccount";
+
+CREATE POLICY "SELECT" ON "public"."supplierAccount"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierAccount"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierAccount"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierAccount"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierContact (FK via supplierId -> supplier)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier contact" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can their own supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Suppliers with purchasing_create can create supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Suppliers with purchasing_update can update their supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier contacts" ON "public"."supplierContact";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier contacts" ON "public"."supplierContact";
+
+CREATE POLICY "SELECT" ON "public"."supplierContact"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierContact"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierContact"
+FOR UPDATE USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierContact"
+FOR DELETE USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierInteraction (has both old and new-style policies)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier interactions" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier interactions" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier interactions" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier interactions" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier interactions" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "SELECT" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "INSERT" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."supplierInteraction";
+DROP POLICY IF EXISTS "DELETE" ON "public"."supplierInteraction";
+
+CREATE POLICY "SELECT" ON "public"."supplierInteraction"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierInteraction"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierInteraction"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierInteraction"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierLocation (FK via supplierId -> supplier)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier locations" ON "public"."supplierLocation";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier locations" ON "public"."supplierLocation";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier locations" ON "public"."supplierLocation";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier locations" ON "public"."supplierLocation";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier locations" ON "public"."supplierLocation";
+
+CREATE POLICY "SELECT" ON "public"."supplierLocation"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierLocation"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierLocation"
+FOR UPDATE USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierLocation"
+FOR DELETE USING (
+ get_company_id_from_foreign_key("supplierId", 'supplier') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierPayment (SELECT + UPDATE only)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier payment" ON "public"."supplierPayment";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier payment" ON "public"."supplierPayment";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier payments" ON "public"."supplierPayment";
+
+CREATE POLICY "SELECT" ON "public"."supplierPayment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierPayment"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+-- supplierQuote
+
+DROP POLICY IF EXISTS "Employees with purchasing_view or purchasing_view can view supplier quotes" ON "public"."supplierQuote";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier quotes" ON "public"."supplierQuote";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier quotes" ON "public"."supplierQuote";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier quotes" ON "public"."supplierQuote";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier quotes" ON "public"."supplierQuote";
+
+CREATE POLICY "SELECT" ON "public"."supplierQuote"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierQuote"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierQuote"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierQuote"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierQuoteFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own supplier quote favorites" ON "public"."supplierQuoteFavorite";
+DROP POLICY IF EXISTS "Users can create their own supplier quote favorites" ON "public"."supplierQuoteFavorite";
+DROP POLICY IF EXISTS "Users can delete their own supplier quote favorites" ON "public"."supplierQuoteFavorite";
+
+CREATE POLICY "SELECT" ON "public"."supplierQuoteFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."supplierQuoteFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."supplierQuoteFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- supplierQuoteLine
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier quote lines" ON "public"."supplierQuoteLine";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier quote lines" ON "public"."supplierQuoteLine";
+DROP POLICY IF EXISTS "Suppliers with purchasing_create can create lines on their own supplier quote" ON "public"."supplierQuoteLine";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier quote lines" ON "public"."supplierQuoteLine";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier quote lines" ON "public"."supplierQuoteLine";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier quotes" ON "public"."supplierQuoteLine";
+
+CREATE POLICY "SELECT" ON "public"."supplierQuoteLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierQuoteLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierQuoteLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierQuoteLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierQuoteLinePrice (FK via supplierQuoteId -> supplierQuote)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier quote line pricing" ON "public"."supplierQuoteLinePrice";
+DROP POLICY IF EXISTS "Suppliers with purchasing_view can view their own quote line pricing" ON "public"."supplierQuoteLinePrice";
+DROP POLICY IF EXISTS "Employees with purchasing_create can insert supplier quote line pricing" ON "public"."supplierQuoteLinePrice";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier quote line pricing" ON "public"."supplierQuoteLinePrice";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier quote line pricing" ON "public"."supplierQuoteLinePrice";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier quote line pricing" ON "public"."supplierQuoteLinePrice";
+
+CREATE POLICY "SELECT" ON "public"."supplierQuoteLinePrice"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierQuoteLinePrice"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierQuoteLinePrice"
+FOR UPDATE USING (
+ get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierQuoteLinePrice"
+FOR DELETE USING (
+ get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote') = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierShipping (SELECT + UPDATE only)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier shipping" ON "public"."supplierShipping";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier shipping" ON "public"."supplierShipping";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier shipping" ON "public"."supplierShipping";
+
+CREATE POLICY "SELECT" ON "public"."supplierShipping"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_view'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierShipping"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+-- supplierStatus (any_role for SELECT)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier statuses" ON "public"."supplierStatus";
+
+CREATE POLICY "SELECT" ON "public"."supplierStatus"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_any_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierStatus"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierStatus"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierStatus"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- supplierType (any_role for SELECT)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier types" ON "public"."supplierType";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier types" ON "public"."supplierType";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier types" ON "public"."supplierType";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier types" ON "public"."supplierType";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier types" ON "public"."supplierType";
+
+CREATE POLICY "SELECT" ON "public"."supplierType"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_any_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierType"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierType"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierType"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 10: Shipping & Misc
+-- ============================================================================
+
+-- membership (FK via groupId -> group)
+
+DROP POLICY IF EXISTS "All employees can view memberships" ON "public"."membership";
+DROP POLICY IF EXISTS "Employees with users_update can create memberships" ON "public"."membership";
+DROP POLICY IF EXISTS "Employees with users_update can update memberships" ON "public"."membership";
+DROP POLICY IF EXISTS "Employees with users_update can delete memberships" ON "public"."membership";
+DROP POLICY IF EXISTS "Requests with an API key can access memberships" ON "public"."membership";
+
+CREATE POLICY "SELECT" ON "public"."membership"
+FOR SELECT USING (
+ get_company_id_from_foreign_key("groupId", 'group') = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."membership"
+FOR INSERT WITH CHECK (
+ get_company_id_from_foreign_key("groupId", 'group') = ANY (
+ (SELECT get_companies_with_employee_permission('users_update'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."membership"
+FOR UPDATE USING (
+ get_company_id_from_foreign_key("groupId", 'group') = ANY (
+ (SELECT get_companies_with_employee_permission('users_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."membership"
+FOR DELETE USING (
+ get_company_id_from_foreign_key("groupId", 'group') = ANY (
+ (SELECT get_companies_with_employee_permission('users_update'))::text[]
+ )
+);
+
+-- note (user-scoped UPDATE/DELETE)
+
+DROP POLICY IF EXISTS "Employees can view notes" ON "public"."note";
+DROP POLICY IF EXISTS "Employees can insert notes" ON "public"."note";
+DROP POLICY IF EXISTS "Employees can update their own notes" ON "public"."note";
+DROP POLICY IF EXISTS "Employees can delete their own notes" ON "public"."note";
+DROP POLICY IF EXISTS "Requests with an API key can access notes" ON "public"."note";
+
+CREATE POLICY "SELECT" ON "public"."note"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."note"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."note"
+FOR UPDATE USING (
+ "createdBy"::uuid = (SELECT auth.uid())
+);
+
+CREATE POLICY "DELETE" ON "public"."note"
+FOR DELETE USING (
+ "createdBy"::uuid = (SELECT auth.uid())
+);
+
+-- receipt
+
+DROP POLICY IF EXISTS "Employees with inventory_view can view receipts" ON "public"."receipt";
+DROP POLICY IF EXISTS "Employees with inventory_create can insert receipts" ON "public"."receipt";
+DROP POLICY IF EXISTS "Employees with inventory_update can update receipts" ON "public"."receipt";
+DROP POLICY IF EXISTS "Employees with inventory_delete can delete receipts" ON "public"."receipt";
+DROP POLICY IF EXISTS "Requests with an API key can access receipts" ON "public"."receipt";
+
+CREATE POLICY "SELECT" ON "public"."receipt"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."receipt"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."receipt"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."receipt"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]
+ )
+);
+
+-- receiptLine
+
+DROP POLICY IF EXISTS "Employees with inventory_view can view receipt lines" ON "public"."receiptLine";
+DROP POLICY IF EXISTS "Employees with inventory_create can insert receipt lines" ON "public"."receiptLine";
+DROP POLICY IF EXISTS "Employees with inventory_update can update receipt lines" ON "public"."receiptLine";
+DROP POLICY IF EXISTS "Employees with inventory_delete can delete receipt lines" ON "public"."receiptLine";
+DROP POLICY IF EXISTS "Requests with an API key can access receipt lines" ON "public"."receiptLine";
+
+CREATE POLICY "SELECT" ON "public"."receiptLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."receiptLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."receiptLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."receiptLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]
+ )
+);
+
+-- sequence
+
+DROP POLICY IF EXISTS "Employees with settings_view can view sequences" ON "public"."sequence";
+DROP POLICY IF EXISTS "Employees with settings_create can create sequences" ON "public"."sequence";
+DROP POLICY IF EXISTS "Employees with settings_update can update sequences" ON "public"."sequence";
+DROP POLICY IF EXISTS "Employees with settings_delete can delete sequences" ON "public"."sequence";
+DROP POLICY IF EXISTS "Requests with an API key can access sequences" ON "public"."sequence";
+
+CREATE POLICY "SELECT" ON "public"."sequence"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."sequence"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."sequence"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."sequence"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]
+ )
+);
+
+-- shippingMethod
+
+DROP POLICY IF EXISTS "Certain employees can view shipping methods" ON "public"."shippingMethod";
+DROP POLICY IF EXISTS "Employees with inventory_create can insert shipping methods" ON "public"."shippingMethod";
+DROP POLICY IF EXISTS "Employees with inventory_update can update shipping methods" ON "public"."shippingMethod";
+DROP POLICY IF EXISTS "Employees with inventory_delete can delete shipping methods" ON "public"."shippingMethod";
+DROP POLICY IF EXISTS "Requests with an API key can access shipping methods" ON "public"."shippingMethod";
+
+CREATE POLICY "SELECT" ON "public"."shippingMethod"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."shippingMethod"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."shippingMethod"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."shippingMethod"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]
+ )
+);
+
+-- shippingTerm
+
+DROP POLICY IF EXISTS "Certain employees can view shipping terms" ON "public"."shippingTerm";
+DROP POLICY IF EXISTS "Employees with inventory_create can insert shipping terms" ON "public"."shippingTerm";
+DROP POLICY IF EXISTS "Employees with inventory_update can update shipping terms" ON "public"."shippingTerm";
+DROP POLICY IF EXISTS "Employees with inventory_delete can delete shipping terms" ON "public"."shippingTerm";
+DROP POLICY IF EXISTS "Requests with an API key can access shipping terms" ON "public"."shippingTerm";
+
+CREATE POLICY "SELECT" ON "public"."shippingTerm"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."shippingTerm"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."shippingTerm"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."shippingTerm"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]
+ )
+);
+
+-- tag
+
+DROP POLICY IF EXISTS "Users can view tags in their company" ON "public"."tag";
+DROP POLICY IF EXISTS "Users can insert tags in their company" ON "public"."tag";
+DROP POLICY IF EXISTS "Users can delete tags in their company" ON "public"."tag";
+DROP POLICY IF EXISTS "Requests with an API key can access tags" ON "public"."tag";
+
+CREATE POLICY "SELECT" ON "public"."tag"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."tag"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."tag"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 11: User-based favorites
+-- ============================================================================
+
+-- jobFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own job favorites" ON "public"."jobFavorite";
+DROP POLICY IF EXISTS "Users can create their own job favorites" ON "public"."jobFavorite";
+DROP POLICY IF EXISTS "Users can delete their own job favorites" ON "public"."jobFavorite";
+
+CREATE POLICY "SELECT" ON "public"."jobFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."jobFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."jobFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- purchasingRfqFavorite (user-scoped, no companyId)
+
+DROP POLICY IF EXISTS "Users can view their own purchasingRfq favorites" ON "public"."purchasingRfqFavorite";
+DROP POLICY IF EXISTS "Users can create their own purchasingRfq favorites" ON "public"."purchasingRfqFavorite";
+DROP POLICY IF EXISTS "Users can delete their own purchasingRfq favorites" ON "public"."purchasingRfqFavorite";
+
+CREATE POLICY "SELECT" ON "public"."purchasingRfqFavorite"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."purchasingRfqFavorite"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "DELETE" ON "public"."purchasingRfqFavorite"
+FOR DELETE USING ((SELECT auth.uid())::text = "userId");
+
+-- ============================================================================
+-- Batch 12: Missed Tables - Standard companyId
+-- ============================================================================
+
+
+
+-- jobOperationDependency (SELECT only)
+
+DROP POLICY IF EXISTS "Employees can view job operation dependencies" ON "public"."jobOperationDependency";
+
+CREATE POLICY "SELECT" ON "public"."jobOperationDependency"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+-- jobOperationNote
+
+DROP POLICY IF EXISTS "Employees can view job operation notes" ON "public"."jobOperationNote";
+DROP POLICY IF EXISTS "Employees can insert job operation notes" ON "public"."jobOperationNote";
+DROP POLICY IF EXISTS "Employees with production_update can update job operation notes" ON "public"."jobOperationNote";
+DROP POLICY IF EXISTS "Employees with production_delete can delete job operation notes" ON "public"."jobOperationNote";
+
+CREATE POLICY "SELECT" ON "public"."jobOperationNote"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."jobOperationNote"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobOperationNote"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."jobOperationNote"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+);
+
+-- material
+
+DROP POLICY IF EXISTS "Employees can view materials" ON "public"."material";
+DROP POLICY IF EXISTS "Employees with parts_create can insert materials" ON "public"."material";
+DROP POLICY IF EXISTS "Employees with parts_update can update materials" ON "public"."material";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete materials" ON "public"."material";
+DROP POLICY IF EXISTS "Requests with an API key can access materials" ON "public"."material";
+
+CREATE POLICY "SELECT" ON "public"."material"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."material"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."material"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."material"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+
+-- tool
+
+DROP POLICY IF EXISTS "Employees can view tools" ON "public"."tool";
+DROP POLICY IF EXISTS "Employees with parts_create can insert tools" ON "public"."tool";
+DROP POLICY IF EXISTS "Employees with parts_update can update tools" ON "public"."tool";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete tools" ON "public"."tool";
+DROP POLICY IF EXISTS "Requests with an API key can access tools" ON "public"."tool";
+
+CREATE POLICY "SELECT" ON "public"."tool"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."tool"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."tool"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."tool"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- userToCompany
+
+DROP POLICY IF EXISTS "Authenticated users can view userToCompany" ON "public"."userToCompany";
+DROP POLICY IF EXISTS "Employees with users_create can create userToCompany" ON "public"."userToCompany";
+DROP POLICY IF EXISTS "Employees with users_update can update userToCompany" ON "public"."userToCompany";
+DROP POLICY IF EXISTS "Employees with users_delete can delete userToCompany" ON "public"."userToCompany";
+
+CREATE POLICY "SELECT" ON "public"."userToCompany"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."userToCompany"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('users_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."userToCompany"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('users_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."userToCompany"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('users_delete'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 13: Multi-permission SELECT tables
+-- ============================================================================
+
+-- supplierPart (renamed from buyMethod)
+
+DROP POLICY IF EXISTS "Employees with part/purchasing_view can view part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Employees with parts_create can create part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Employees with parts_update can update part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Suppliers with parts_view can view their own part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Suppliers with parts_update can update their own part suppliers" ON "public"."supplierPart";
+DROP POLICY IF EXISTS "Requests with an API key can access buy methods" ON "public"."supplierPart";
+
+CREATE POLICY "SELECT" ON "public"."supplierPart"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('parts_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierPart"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierPart"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierPart"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]
+ )
+);
+
+-- supplierProcess (multi-permission SELECT + INSERT + DELETE)
+
+DROP POLICY IF EXISTS "Employees with purchasing, resources, or sales can read supplier processes" ON "public"."supplierProcess";
+DROP POLICY IF EXISTS "Employees with resources and purchasing can create supplier processes" ON "public"."supplierProcess";
+DROP POLICY IF EXISTS "Employees with resources can update supplier processes" ON "public"."supplierProcess";
+DROP POLICY IF EXISTS "Employees with resources or purchasing can delete supplier processes" ON "public"."supplierProcess";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier processes" ON "public"."supplierProcess";
+
+CREATE POLICY "SELECT" ON "public"."supplierProcess"
+FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('resources_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ ))
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierProcess"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('purchasing_update'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('resources_update'))
+ ))
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierProcess"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierProcess"
+FOR DELETE USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('purchasing_delete'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('resources_delete'))
+ ))
+ )
+);
+
+-- ============================================================================
+-- Batch 14: Special ID pattern + FK lookup
+-- ============================================================================
+
+-- terms (id = companyId, SELECT + UPDATE only)
+
+DROP POLICY IF EXISTS "Employees with purchasing_view or sales_view or settings_view can view terms" ON "public"."terms";
+DROP POLICY IF EXISTS "Employees with settings_update can update terms" ON "public"."terms";
+
+CREATE POLICY "SELECT" ON "public"."terms"
+FOR SELECT USING (
+ "id" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('settings_view'))
+ ))
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."terms"
+FOR UPDATE USING (
+ "id" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]
+ )
+);
+
+-- ============================================================================
+-- Batch 15: Clean up old policies on tables that already have new-style policies
+-- ============================================================================
+
+-- jobOperationTool (new-style policies already exist from 20250207105852_tools-rls.sql)
+
+DROP POLICY IF EXISTS "Employees can view job operation tools" ON "public"."jobOperationTool";
+DROP POLICY IF EXISTS "Employees with production_create can create job operation tools" ON "public"."jobOperationTool";
+DROP POLICY IF EXISTS "Employees with production_delete can delete job operation tools" ON "public"."jobOperationTool";
+DROP POLICY IF EXISTS "Employees with production_update can update job operation tools" ON "public"."jobOperationTool";
+DROP POLICY IF EXISTS "Employees with production_view can view job operation tools" ON "public"."jobOperationTool";
+DROP POLICY IF EXISTS "Requests with an API key can access job operation tools" ON "public"."jobOperationTool";
+
+-- methodOperationTool (new-style policies already exist from 20250207105852_tools-rls.sql)
+
+DROP POLICY IF EXISTS "Employees with parts_create can create method operation tools" ON "public"."methodOperationTool";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete method operation tools" ON "public"."methodOperationTool";
+DROP POLICY IF EXISTS "Employees with parts_update can update method operation tools" ON "public"."methodOperationTool";
+DROP POLICY IF EXISTS "Employees with parts_view can view method operation tools" ON "public"."methodOperationTool";
+DROP POLICY IF EXISTS "Requests with an API key can access method operation tools" ON "public"."methodOperationTool";
+
+-- quoteOperationTool (new-style policies already exist from 20250207105852_tools-rls.sql)
+
+DROP POLICY IF EXISTS "Employees with sales_create can create quote operation tools" ON "public"."quoteOperationTool";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete quote operation tools" ON "public"."quoteOperationTool";
+DROP POLICY IF EXISTS "Employees with sales_update can update quote operation tools" ON "public"."quoteOperationTool";
+DROP POLICY IF EXISTS "Employees with sales_view can view quote operation tools" ON "public"."quoteOperationTool";
+DROP POLICY IF EXISTS "Requests with an API key can access quote operation tools" ON "public"."quoteOperationTool";
+
+-- materialForm (new-style policies already exist from 20250827201650_radan-v1.sql)
+
+DROP POLICY IF EXISTS "Authenticated users can view global material forms" ON "public"."materialForm";
+DROP POLICY IF EXISTS "Employees can view material forms" ON "public"."materialForm";
+DROP POLICY IF EXISTS "Employees with parts_create can insert material forms" ON "public"."materialForm";
+DROP POLICY IF EXISTS "Employees with parts_update can update material forms" ON "public"."materialForm";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete material forms" ON "public"."materialForm";
+DROP POLICY IF EXISTS "Requests with an API key can access material forms" ON "public"."materialForm";
+
+-- materialSubstance (new-style policies already exist from 20250827201650_radan-v1.sql)
+
+DROP POLICY IF EXISTS "Authenticated users can view global material substances" ON "public"."materialSubstance";
+DROP POLICY IF EXISTS "Employees can view material substances" ON "public"."materialSubstance";
+DROP POLICY IF EXISTS "Employees with parts_create can insert material substances" ON "public"."materialSubstance";
+DROP POLICY IF EXISTS "Employees with parts_update can update material substances" ON "public"."materialSubstance";
+DROP POLICY IF EXISTS "Employees with parts_delete can delete material substances" ON "public"."materialSubstance";
+DROP POLICY IF EXISTS "Requests with an API key can access material substances" ON "public"."materialSubstance";
+
+-- ============================================================================
+-- Batch 16: Drop leftover old policies on already-refactored tables
+-- ============================================================================
+
+-- companyIntegration (old UPDATE policy duplicates new "UPDATE" from rls-refactor.sql)
+
+DROP POLICY IF EXISTS "Employees with settings_update can update company integrations." ON "public"."companyIntegration";
+
+-- documentTransaction (old policies duplicate new-style from 20250707 migration)
+
+DROP POLICY IF EXISTS "Users can insert document transactions" ON "public"."documentTransaction";
+DROP POLICY IF EXISTS "Users with documents_view can see document transactions" ON "public"."documentTransaction";
+
+-- salesOrderPayment (old policies + API key policy)
+
+DROP POLICY IF EXISTS "Employees with sales_view can view sales order payments" ON "public"."salesOrderPayment";
+DROP POLICY IF EXISTS "Employees with sales_create can create sales order payments" ON "public"."salesOrderPayment";
+DROP POLICY IF EXISTS "Employees with sales_update can update sales order payments" ON "public"."salesOrderPayment";
+DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order payments" ON "public"."salesOrderPayment";
+DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order payments" ON "public"."salesOrderPayment";
+
+-- ============================================================================
+-- Batch 17: Fix auth.() -> (select auth.()) performance issues
+-- ============================================================================
+
+-- user: fix "Users can modify themselves"
+
+DROP POLICY IF EXISTS "Users can modify themselves" ON "public"."user";
+
+CREATE POLICY "Users can modify themselves" ON "public"."user"
+FOR UPDATE WITH CHECK ((SELECT auth.uid())::text = "id");
+
+-- user: fix "Users can view other users from their same company"
+
+DROP POLICY IF EXISTS "Users can view other users from their same company" ON "public"."user";
+
+CREATE POLICY "Users can view other users from their same company" ON "public"."user"
+FOR SELECT USING (
+ "id" = (SELECT auth.uid())::text OR
+ "id" IN (
+ SELECT "userId" FROM "userToCompany" WHERE "companyId" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = (SELECT auth.uid())::text
+ )
+ )
+);
+
+-- userPermission: fix "Users with users_update can view permissions of other users in their company"
+
+DROP POLICY IF EXISTS "Users with users_update can view permissions of other users in their company" ON "public"."userPermission";
+
+CREATE POLICY "Users with users_update can view permissions of other users in their company" ON "public"."userPermission"
+FOR SELECT USING (
+ "id" IN (
+ SELECT "userId" FROM "userToCompany" WHERE "companyId" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = (SELECT auth.uid())::text
+ )
+ )
+);
+
+-- attributeDataType: fix auth.role()
+
+DROP POLICY IF EXISTS "Authenticated users can view attribute data types" ON "public"."attributeDataType";
+
+CREATE POLICY "Authenticated users can view attribute data types" ON "public"."attributeDataType"
+FOR SELECT USING ((SELECT auth.role()) = 'authenticated');
+
+-- config: fix auth.role()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."config";
+
+CREATE POLICY "SELECT" ON "public"."config"
+FOR SELECT USING ((SELECT auth.role()) = 'authenticated');
+
+-- webhookTable: fix auth.role()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."webhookTable";
+
+CREATE POLICY "SELECT" ON "public"."webhookTable"
+FOR SELECT USING ((SELECT auth.role()) = 'authenticated');
+
+-- companyUsage: fix auth.role() and auth.uid()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."companyUsage";
+
+CREATE POLICY "SELECT" ON "public"."companyUsage"
+FOR SELECT USING (
+ (SELECT auth.role()) = 'authenticated' AND "id" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = (SELECT auth.uid())::text
+ )
+);
+
+-- plan: fix auth.role()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."plan";
+
+CREATE POLICY "SELECT" ON "public"."plan"
+FOR SELECT USING ((SELECT auth.role()) = 'authenticated');
+
+-- companyPlan: fix auth.role() and auth.uid()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."companyPlan";
+
+CREATE POLICY "SELECT" ON "public"."companyPlan"
+FOR SELECT USING (
+ (SELECT auth.role()) = 'authenticated' AND "id" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = (SELECT auth.uid())::text
+ )
+);
+
+-- lessonCompletion: fix auth.uid()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."lessonCompletion";
+DROP POLICY IF EXISTS "INSERT" ON "public"."lessonCompletion";
+
+CREATE POLICY "SELECT" ON "public"."lessonCompletion"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."lessonCompletion"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+-- challengeAttempt: fix auth.uid()
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."challengeAttempt";
+DROP POLICY IF EXISTS "INSERT" ON "public"."challengeAttempt";
+
+CREATE POLICY "SELECT" ON "public"."challengeAttempt"
+FOR SELECT USING ((SELECT auth.uid())::text = "userId");
+
+CREATE POLICY "INSERT" ON "public"."challengeAttempt"
+FOR INSERT WITH CHECK ((SELECT auth.uid())::text = "userId");
+
+-- trainingCompletion: fix auth.uid() in INSERT
+
+DROP POLICY IF EXISTS "INSERT" ON "public"."trainingCompletion";
+
+CREATE POLICY "INSERT" ON "public"."trainingCompletion"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_create'))::text[]
+ ) OR (
+ (SELECT auth.uid())::text = "employeeId"
+ AND "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+ )
+);
+
+-- maintenanceDispatchComment: fix auth.uid()
+
+DROP POLICY IF EXISTS "UPDATE" ON "public"."maintenanceDispatchComment";
+DROP POLICY IF EXISTS "DELETE" ON "public"."maintenanceDispatchComment";
+
+CREATE POLICY "UPDATE" ON "public"."maintenanceDispatchComment"
+FOR UPDATE USING (
+ "createdBy" = (SELECT auth.uid())::text
+);
+
+CREATE POLICY "DELETE" ON "public"."maintenanceDispatchComment"
+FOR DELETE USING (
+ "createdBy" = (SELECT auth.uid())::text
+);
+
+-- eventSystemSubscription: fix auth.role()
+
+DROP POLICY IF EXISTS "manage_subscriptions" ON "public"."eventSystemSubscription";
+
+CREATE POLICY "manage_subscriptions" ON "public"."eventSystemSubscription"
+FOR ALL USING ((SELECT auth.role()) = 'authenticated');
+
+-- approvalRule: fix duplicate policies (UPDATE and DELETE use USING instead of proper FOR syntax)
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."approvalRule";
+DROP POLICY IF EXISTS "INSERT" ON "public"."approvalRule";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."approvalRule";
+DROP POLICY IF EXISTS "DELETE" ON "public"."approvalRule";
+
+CREATE POLICY "SELECT" ON "public"."approvalRule"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."approvalRule"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."approvalRule"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."approvalRule"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]
+ )
+);
diff --git a/packages/database/supabase/migrations/20260228102915_api-key-rls.sql b/packages/database/supabase/migrations/20260228102915_api-key-rls.sql
new file mode 100644
index 0000000000..00b49c9713
--- /dev/null
+++ b/packages/database/supabase/migrations/20260228102915_api-key-rls.sql
@@ -0,0 +1,29 @@
+DROP POLICY IF EXISTS "ALL" ON "public"."apiKey";
+
+CREATE POLICY "SELECT" ON "public"."apiKey"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_view'))::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."apiKey"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."apiKey"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."apiKey"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]
+ )
+);
diff --git a/packages/react/package.json b/packages/react/package.json
index 1766665f7e..4c6894ff32 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -66,11 +66,11 @@
"intl-parse-accept-language": "^1.0.0",
"is-hotkey": "^0.2.0",
"online-3d-viewer": "0.15.0",
- "prism-react-renderer": "^2.3.1",
"react-aria-components": "1.0.1",
"react-colorful": "^5.6.1",
"react-hotkeys-hook": "~4.5.0",
"react-resizable-panels": "^2.1.3",
+ "react-shiki": "^0.9.1",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
diff --git a/packages/react/src/CodeBlock.tsx b/packages/react/src/CodeBlock.tsx
index a8bf35f9c3..d5aa02f409 100644
--- a/packages/react/src/CodeBlock.tsx
+++ b/packages/react/src/CodeBlock.tsx
@@ -1,20 +1,36 @@
-/**
- * Copyright (c) 2017-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
-import type { Language } from "prism-react-renderer";
-import { Highlight, themes } from "prism-react-renderer";
+import type { ShikiTransformer } from "@shikijs/types";
import type { PropsWithChildren } from "react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
+import ShikiHighlighter, {
+ createHighlighterCore,
+ createJavaScriptRegexEngine
+} from "react-shiki/core";
import { Button } from "./Button";
-const prism = {
- defaultLanguage: "js",
- plugins: ["line-numbers", "show-language"]
+// ─── Highlighter Setup ───────────────────────────────────────────────────────
+
+const highlighter = await createHighlighterCore({
+ themes: [import("@shikijs/themes/night-owl")],
+ langs: [
+ import("@shikijs/langs/bash"),
+ import("@shikijs/langs/javascript"),
+ import("@shikijs/langs/tsx")
+ ],
+ engine: createJavaScriptRegexEngine()
+});
+
+const removeItalics: ShikiTransformer = {
+ name: "remove-italics",
+ span(node) {
+ const style = node.properties?.style;
+ if (typeof style === "string" && style.includes("font-style")) {
+ node.properties.style = style.replace(/font-style:\s*italic;?/g, "");
+ }
+ }
};
+// ─── Component ───────────────────────────────────────────────────────────────
+
interface CodeBlockProps {
parentClassName?: string;
className?: string;
@@ -28,8 +44,6 @@ const CodeBlock = ({
showCopy = true
}: PropsWithChildren<CodeBlockProps>) => {
const [showCopied, setShowCopied] = useState(false);
- const target = useRef(null);
- let highlightLines: any = [];
useEffect(() => {
if (!showCopied) return;
@@ -37,62 +51,36 @@ const CodeBlock = ({
return () => clearTimeout(timer);
}, [showCopied]);
- let language =
- languageClassName && languageClassName.replace(/language-/, "");
+ const language = languageClassName?.replace(/language-/, "") || "typescript";
+ const code = (children as string)?.trim() ?? "";
- if (!language && prism.defaultLanguage) {
- language = prism.defaultLanguage;
- }
-
- const handleCopyCode = (code: any) => {
+ const handleCopyCode = () => {
window.navigator.clipboard.writeText(code);
setShowCopied(true);
};
- // html tag has dark className
- const isDarkMode =
- document?.documentElement.classList.contains("dark") ?? true;
-
return (
- <Highlight
- theme={isDarkMode ? themes.nightOwl : themes.nightOwlLight}
- code={(children as string)?.trim() ?? ""}
- language={language as Language}
- >
- {({ className, tokens, getLineProps, getTokenProps }) => {
- return (
- <div className="Code codeBlockWrapper group">
- <pre
- ref={target}
- className={`codeBlock ${className} ${parentClassName}`}
- >
- {tokens.map((line, i) => {
- const lineProps = getLineProps({ line, key: i });
-
- if (highlightLines.includes(i + 1)) {
- lineProps.className = `${lineProps.className} docusaurus-highlight-code-line`;
- }
+ <div className={`Code codeBlockWrapper group ${parentClassName ?? ""}`}>
+ <ShikiHighlighter
+ highlighter={highlighter}
+ language={language}
+ theme={"night-owl"}
+ showLanguage={false}
+ addDefaultStyles={true}
+ className="codeBlock"
+ transformers={[removeItalics]}
+ >
+ {code}
+ </ShikiHighlighter>
- return (
- <div key={i} {...lineProps}>
- {line.map((token, key) => (
- <span key={key} {...getTokenProps({ token, key })} />
- ))}
- </div>
- );
- })}
- </pre>
- {showCopy && (
- <div className="invisible absolute right-0 top-0 opacity-0 transition-opacity group-hover:visible group-hover:opacity-100">
- <Button size="sm" onClick={() => handleCopyCode(children)}>
- {showCopied ? "Copied" : "Copy"}
- </Button>
- </div>
- )}
- </div>
- );
- }}
- </Highlight>
+ {showCopy && (
+ <div className="invisible absolute right-0 top-0 opacity-0 transition-opacity group-hover:visible group-hover:opacity-100">
+ <Button size="sm" onClick={handleCopyCode}>
+ {showCopied ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ )}
+ </div>
);
};
diff --git a/scripts/sandbox.ts b/scripts/sandbox.ts
index f336f35e88..d33c4a3e2b 100644
--- a/scripts/sandbox.ts
+++ b/scripts/sandbox.ts
@@ -9,14 +9,14 @@ const carbon = createClient(
{
global: {
headers: {
- "carbon-key": "crbn_**************",
+ "carbon-key": "crbn_yPkz1hszqh6mVLDf4jiDv",
},
},
}
);
(async () => {
- const employees = await carbon.from("employees").select("*").limit(1000);
+ const employees = await carbon.from("salesOrder").select("*").limit(1000);
console.log(employees);
})();