ADD CROSS DOMAIN SUPPORT
This commit is contained in:
@@ -15,14 +15,34 @@ export async function postEvent(
|
|||||||
const ip = getClientIp(request)!;
|
const ip = getClientIp(request)!;
|
||||||
const ua = request.headers['user-agent']!;
|
const ua = request.headers['user-agent']!;
|
||||||
const origin = request.headers.origin!;
|
const origin = request.headers.origin!;
|
||||||
const salts = await getSalts();
|
const projectId = request.client?.projectId;
|
||||||
|
|
||||||
|
if (!projectId) {
|
||||||
|
reply.status(400).send('missing origin');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [salts, geo] = await Promise.all([getSalts(), parseIp(ip)]);
|
||||||
const currentDeviceId = generateDeviceId({
|
const currentDeviceId = generateDeviceId({
|
||||||
salt: salts.current,
|
salt: salts.current,
|
||||||
origin: origin,
|
origin: projectId,
|
||||||
ip,
|
ip,
|
||||||
ua,
|
ua,
|
||||||
});
|
});
|
||||||
const previousDeviceId = generateDeviceId({
|
const previousDeviceId = generateDeviceId({
|
||||||
|
salt: salts.previous,
|
||||||
|
origin: projectId,
|
||||||
|
ip,
|
||||||
|
ua,
|
||||||
|
});
|
||||||
|
// TODO: Remove after 2024-09-26
|
||||||
|
const currentDeviceIdDeprecated = generateDeviceId({
|
||||||
|
salt: salts.current,
|
||||||
|
origin,
|
||||||
|
ip,
|
||||||
|
ua,
|
||||||
|
});
|
||||||
|
const previousDeviceIdDeprecated = generateDeviceId({
|
||||||
salt: salts.previous,
|
salt: salts.previous,
|
||||||
origin,
|
origin,
|
||||||
ip,
|
ip,
|
||||||
@@ -34,13 +54,15 @@ export async function postEvent(
|
|||||||
payload: {
|
payload: {
|
||||||
projectId: request.projectId,
|
projectId: request.projectId,
|
||||||
headers: {
|
headers: {
|
||||||
origin,
|
|
||||||
ua,
|
ua,
|
||||||
},
|
},
|
||||||
event: request.body,
|
event: request.body,
|
||||||
geo: await parseIp(ip),
|
geo,
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
previousDeviceId,
|
previousDeviceId,
|
||||||
|
// TODO: Remove after 2024-09-26
|
||||||
|
currentDeviceIdDeprecated,
|
||||||
|
previousDeviceIdDeprecated,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -17,16 +17,15 @@ const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
|
|||||||
reply
|
reply
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const projectId = await validateSdkRequest(req.headers).catch(
|
const client = await validateSdkRequest(req.headers).catch((error) => {
|
||||||
(error) => {
|
logger.error(error, 'Failed to validate sdk request');
|
||||||
logger.error(error, 'Failed to validate sdk request');
|
return null;
|
||||||
return null;
|
});
|
||||||
}
|
if (!client?.projectId) {
|
||||||
);
|
|
||||||
if (!projectId) {
|
|
||||||
return reply.status(401).send();
|
return reply.status(401).send();
|
||||||
}
|
}
|
||||||
req.projectId = projectId;
|
req.projectId = client.projectId;
|
||||||
|
req.client = client;
|
||||||
|
|
||||||
const bot = req.headers['user-agent']
|
const bot = req.headers['user-agent']
|
||||||
? isBot(req.headers['user-agent'])
|
? isBot(req.headers['user-agent'])
|
||||||
@@ -37,7 +36,7 @@ const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
|
|||||||
req.body?.properties?.path) as string | undefined;
|
req.body?.properties?.path) as string | undefined;
|
||||||
await createBotEvent({
|
await createBotEvent({
|
||||||
...bot,
|
...bot,
|
||||||
projectId,
|
projectId: client.projectId,
|
||||||
path: path ?? '',
|
path: path ?? '',
|
||||||
createdAt: new Date(req.body?.timestamp),
|
createdAt: new Date(req.body?.timestamp),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,24 +7,25 @@ import type { FastifyPluginCallback } from 'fastify';
|
|||||||
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
|
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
|
||||||
fastify.addHook('preHandler', async (req, reply) => {
|
fastify.addHook('preHandler', async (req, reply) => {
|
||||||
try {
|
try {
|
||||||
const projectId = await validateSdkRequest(req.headers).catch((error) => {
|
const client = await validateSdkRequest(req.headers).catch((error) => {
|
||||||
logger.error(error, 'Failed to validate sdk request');
|
logger.error(error, 'Failed to validate sdk request');
|
||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
if (!projectId) {
|
if (!client?.projectId) {
|
||||||
return reply.status(401).send();
|
return reply.status(401).send();
|
||||||
}
|
}
|
||||||
req.projectId = projectId;
|
req.projectId = client.projectId;
|
||||||
|
req.client = client;
|
||||||
|
|
||||||
const bot = req.headers['user-agent']
|
const bot = req.headers['user-agent']
|
||||||
? isBot(req.headers['user-agent'])
|
? isBot(req.headers['user-agent'])
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
if (bot) {
|
if (bot) {
|
||||||
reply.log.warn({ ...req.headers, bot }, 'Bot detected (profile)');
|
return reply.status(202).send('OK');
|
||||||
reply.status(202).send('OK');
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error(e, 'Failed to create bot event');
|
||||||
reply.status(401).send();
|
reply.status(401).send();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { RawRequestDefaultExpression } from 'fastify';
|
|||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
import { verifyPassword } from '@openpanel/common';
|
import { verifyPassword } from '@openpanel/common';
|
||||||
import type { IServiceClient } from '@openpanel/db';
|
import type { Client, IServiceClient } from '@openpanel/db';
|
||||||
import { ClientType, db } from '@openpanel/db';
|
import { ClientType, db } from '@openpanel/db';
|
||||||
|
|
||||||
import { logger } from './logger';
|
import { logger } from './logger';
|
||||||
@@ -36,7 +36,7 @@ class SdkAuthError extends Error {
|
|||||||
|
|
||||||
export async function validateSdkRequest(
|
export async function validateSdkRequest(
|
||||||
headers: RawRequestDefaultExpression['headers']
|
headers: RawRequestDefaultExpression['headers']
|
||||||
): Promise<string> {
|
): Promise<Client> {
|
||||||
const clientIdNew = headers['openpanel-client-id'] as string;
|
const clientIdNew = headers['openpanel-client-id'] as string;
|
||||||
const clientIdOld = headers['mixan-client-id'] as string;
|
const clientIdOld = headers['mixan-client-id'] as string;
|
||||||
const clientSecretNew = headers['openpanel-client-secret'] as string;
|
const clientSecretNew = headers['openpanel-client-secret'] as string;
|
||||||
@@ -83,17 +83,17 @@ export async function validateSdkRequest(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (domainAllowed) {
|
if (domainAllowed) {
|
||||||
return client.projectId;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (client.cors === '*' && origin) {
|
if (client.cors === '*' && origin) {
|
||||||
return client.projectId;
|
return client;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (client.secret && clientSecret) {
|
if (client.secret && clientSecret) {
|
||||||
if (await verifyPassword(clientSecret, client.secret)) {
|
if (await verifyPassword(clientSecret, client.secret)) {
|
||||||
return client.projectId;
|
return client;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ export function EventDetails({ event, open, setOpen }: Props) {
|
|||||||
const [, setEvents] = useEventQueryNamesFilter({ shallow: false });
|
const [, setEvents] = useEventQueryNamesFilter({ shallow: false });
|
||||||
|
|
||||||
const common = [
|
const common = [
|
||||||
|
{
|
||||||
|
name: 'Origin',
|
||||||
|
value: event.origin,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'Duration',
|
name: 'Duration',
|
||||||
value: event.duration ? round(event.duration / 1000, 1) : undefined,
|
value: event.duration ? round(event.duration / 1000, 1) : undefined,
|
||||||
@@ -154,7 +158,7 @@ export function EventDetails({ event, open, setOpen }: Props) {
|
|||||||
{properties.map((item) => (
|
{properties.map((item) => (
|
||||||
<KeyValue
|
<KeyValue
|
||||||
key={item.name}
|
key={item.name}
|
||||||
name={item.name}
|
name={item.name.replace(/^__/, '')}
|
||||||
value={item.value}
|
value={item.value}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setFilter(
|
setFilter(
|
||||||
|
|||||||
@@ -83,9 +83,9 @@ export default function ListProjects({ projects, clients }: ListProjectsProps) {
|
|||||||
Client ID: ...{item.id.slice(-12)}
|
Client ID: ...{item.id.slice(-12)}
|
||||||
</Tooltiper>
|
</Tooltiper>
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
{item.secret
|
{item.cors &&
|
||||||
? 'Secret: Hidden'
|
item.cors !== '*' &&
|
||||||
: `Website: ${item.cors}`}
|
`Website: ${item.cors}`}
|
||||||
</div>
|
</div>
|
||||||
<div className="absolute right-4 top-4">
|
<div className="absolute right-4 top-4">
|
||||||
<ClientActions {...item} />
|
<ClientActions {...item} />
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { ButtonContainer } from '@/components/button-container';
|
import { ButtonContainer } from '@/components/button-container';
|
||||||
import { InputWithLabel } from '@/components/forms/input-with-label';
|
import CopyInput from '@/components/forms/copy-input';
|
||||||
import { LinkButton } from '@/components/ui/button';
|
import { LinkButton } from '@/components/ui/button';
|
||||||
import { useClientSecret } from '@/hooks/useClientSecret';
|
import { useClientSecret } from '@/hooks/useClientSecret';
|
||||||
import { LockIcon } from 'lucide-react';
|
import { LockIcon } from 'lucide-react';
|
||||||
@@ -36,13 +36,13 @@ const Connect = ({ project }: Props) => {
|
|||||||
</OnboardingDescription>
|
</OnboardingDescription>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div className="bg-def-200 flex flex-col gap-4 rounded-xl border p-4 md:p-6">
|
<div className="flex flex-col gap-4 rounded-xl border p-4 md:p-6">
|
||||||
<div className="flex items-center gap-2 text-2xl capitalize">
|
<div className="flex items-center gap-2 text-2xl capitalize">
|
||||||
<LockIcon />
|
<LockIcon />
|
||||||
Credentials
|
Credentials
|
||||||
</div>
|
</div>
|
||||||
<InputWithLabel label="Client ID" disabled value={client.id} />
|
<CopyInput label="Client ID" value={client.id} />
|
||||||
<InputWithLabel label="Client Secret" disabled value={secret} />
|
<CopyInput label="Secret" value={secret} />
|
||||||
</div>
|
</div>
|
||||||
{project.types.map((type) => {
|
{project.types.map((type) => {
|
||||||
const Component = {
|
const Component = {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { cookies } from 'next/headers';
|
|
||||||
|
|
||||||
import { getCurrentOrganizations, getProjectWithClients } from '@openpanel/db';
|
import { getCurrentOrganizations, getProjectWithClients } from '@openpanel/db';
|
||||||
|
|
||||||
import OnboardingConnect from './onboarding-connect';
|
import OnboardingConnect from './onboarding-connect';
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import { useEffect } from 'react';
|
|||||||
import AnimateHeight from '@/components/animate-height';
|
import AnimateHeight from '@/components/animate-height';
|
||||||
import { ButtonContainer } from '@/components/button-container';
|
import { ButtonContainer } from '@/components/button-container';
|
||||||
import { CheckboxItem } from '@/components/forms/checkbox-item';
|
import { CheckboxItem } from '@/components/forms/checkbox-item';
|
||||||
import { InputWithLabel } from '@/components/forms/input-with-label';
|
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
|
||||||
|
import TagInput from '@/components/forms/tag-input';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Combobox } from '@/components/ui/combobox';
|
import { Combobox } from '@/components/ui/combobox';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
@@ -155,11 +156,41 @@ const Tracking = ({
|
|||||||
>
|
>
|
||||||
<AnimateHeight open={isWebsite && !isApp}>
|
<AnimateHeight open={isWebsite && !isApp}>
|
||||||
<div className="p-4 pl-14">
|
<div className="p-4 pl-14">
|
||||||
<InputWithLabel
|
<Controller
|
||||||
label="Domain"
|
name="domain"
|
||||||
placeholder="https://example.com"
|
control={form.control}
|
||||||
error={form.formState.errors.domain?.message}
|
render={({ field }) => (
|
||||||
{...form.register('domain')}
|
<WithLabel
|
||||||
|
label="Domain(s)"
|
||||||
|
error={form.formState.errors.domain?.message}
|
||||||
|
>
|
||||||
|
<TagInput
|
||||||
|
{...field}
|
||||||
|
placeholder="Add a domain"
|
||||||
|
value={field.value?.split(',') ?? []}
|
||||||
|
renderTag={(tag) =>
|
||||||
|
tag === '*' ? 'Allow domains' : tag
|
||||||
|
}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
field.onChange(
|
||||||
|
newValue
|
||||||
|
.map((item) => {
|
||||||
|
const trimmed = item.trim();
|
||||||
|
if (
|
||||||
|
trimmed.startsWith('http://') ||
|
||||||
|
trimmed.startsWith('https://') ||
|
||||||
|
trimmed === '*'
|
||||||
|
) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
return `https://${trimmed}`;
|
||||||
|
})
|
||||||
|
.join(',')
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</WithLabel>
|
||||||
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</AnimateHeight>
|
</AnimateHeight>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||||
import { clipboard } from '@/utils/clipboard';
|
import { RocketIcon } from 'lucide-react';
|
||||||
import { Copy, RocketIcon } from 'lucide-react';
|
|
||||||
|
|
||||||
import type { IServiceClient } from '@openpanel/db';
|
import type { IServiceClient } from '@openpanel/db';
|
||||||
|
|
||||||
|
import CopyInput from '../forms/copy-input';
|
||||||
import { Label } from '../ui/label';
|
import { Label } from '../ui/label';
|
||||||
|
|
||||||
type Props = IServiceClient;
|
type Props = IServiceClient;
|
||||||
@@ -11,25 +11,10 @@ type Props = IServiceClient;
|
|||||||
export function CreateClientSuccess({ id, secret, cors }: Props) {
|
export function CreateClientSuccess({ id, secret, cors }: Props) {
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-4">
|
<div className="grid gap-4">
|
||||||
<button className="text-left" onClick={() => clipboard(id)}>
|
<CopyInput label="Client ID" value={id} />
|
||||||
<Label>Client ID</Label>
|
|
||||||
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
|
|
||||||
{id}
|
|
||||||
<Copy size={16} />
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
{secret && (
|
{secret && (
|
||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<button
|
<CopyInput label="Secret" value={secret} />
|
||||||
className="w-full text-left"
|
|
||||||
onClick={() => clipboard(secret)}
|
|
||||||
>
|
|
||||||
<Label>Client secret</Label>
|
|
||||||
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
|
|
||||||
{secret}
|
|
||||||
<Copy size={16} />
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
{cors && (
|
{cors && (
|
||||||
<p className="mt-1 text-xs text-muted-foreground">
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
You will only need the secret if you want to send server events.
|
You will only need the secret if you want to send server events.
|
||||||
@@ -40,7 +25,7 @@ export function CreateClientSuccess({ id, secret, cors }: Props) {
|
|||||||
{cors && (
|
{cors && (
|
||||||
<div className="text-left">
|
<div className="text-left">
|
||||||
<Label>CORS settings</Label>
|
<Label>CORS settings</Label>
|
||||||
<div className="flex items-center justify-between rounded border-input bg-background p-2 px-3 font-mono text-sm">
|
<div className="flex items-center justify-between rounded border-input bg-def-200 p-2 px-3 font-mono text-sm">
|
||||||
{cors}
|
{cors}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
28
apps/dashboard/src/components/forms/copy-input.tsx
Normal file
28
apps/dashboard/src/components/forms/copy-input.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { clipboard } from '@/utils/clipboard';
|
||||||
|
import { cn } from '@/utils/cn';
|
||||||
|
import { CopyIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
import { Label } from '../ui/label';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
label: React.ReactNode;
|
||||||
|
value: string;
|
||||||
|
className?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CopyInput = ({ label, value, className }: Props) => {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className={cn('w-full text-left', className)}
|
||||||
|
onClick={() => clipboard(value)}
|
||||||
|
>
|
||||||
|
{!!label && <Label>{label}</Label>}
|
||||||
|
<div className="flex items-center justify-between rounded border-input bg-def-200 p-2 px-3 font-mono text-sm">
|
||||||
|
{value}
|
||||||
|
<CopyIcon size={16} />
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default CopyInput;
|
||||||
@@ -6,39 +6,56 @@ import type { InputProps } from '../ui/input';
|
|||||||
import { Label } from '../ui/label';
|
import { Label } from '../ui/label';
|
||||||
import { Tooltiper } from '../ui/tooltip';
|
import { Tooltiper } from '../ui/tooltip';
|
||||||
|
|
||||||
type InputWithLabelProps = InputProps & {
|
type WithLabel = {
|
||||||
|
children: React.ReactNode;
|
||||||
label: string;
|
label: string;
|
||||||
error?: string | undefined;
|
error?: string | undefined;
|
||||||
info?: string;
|
info?: string;
|
||||||
|
className?: string;
|
||||||
|
};
|
||||||
|
type InputWithLabelProps = InputProps & Omit<WithLabel, 'children'>;
|
||||||
|
|
||||||
|
export const WithLabel = ({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
label,
|
||||||
|
info,
|
||||||
|
error,
|
||||||
|
}: WithLabel) => {
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<div className="mb-2 flex items-end justify-between">
|
||||||
|
<Label
|
||||||
|
className="mb-0 flex flex-1 shrink-0 items-center gap-1 whitespace-nowrap"
|
||||||
|
htmlFor={label}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
{info && (
|
||||||
|
<Tooltiper content={info}>
|
||||||
|
<InfoIcon size={14} />
|
||||||
|
</Tooltiper>
|
||||||
|
)}
|
||||||
|
</Label>
|
||||||
|
{error && (
|
||||||
|
<Tooltiper asChild content={error}>
|
||||||
|
<div className="flex items-center gap-1 text-sm leading-none text-destructive">
|
||||||
|
Issues
|
||||||
|
<BanIcon size={14} />
|
||||||
|
</div>
|
||||||
|
</Tooltiper>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
|
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
|
||||||
({ label, className, info, ...props }, ref) => {
|
(props, ref) => {
|
||||||
return (
|
return (
|
||||||
<div className={className}>
|
<WithLabel {...props}>
|
||||||
<div className="mb-2 flex items-end justify-between">
|
<Input ref={ref} id={props.label} {...props} />
|
||||||
<Label
|
</WithLabel>
|
||||||
className="mb-0 flex flex-1 shrink-0 items-center gap-1 whitespace-nowrap"
|
|
||||||
htmlFor={label}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
{info && (
|
|
||||||
<Tooltiper content={info}>
|
|
||||||
<InfoIcon size={14} />
|
|
||||||
</Tooltiper>
|
|
||||||
)}
|
|
||||||
</Label>
|
|
||||||
{props.error && (
|
|
||||||
<Tooltiper asChild content={props.error}>
|
|
||||||
<div className="flex items-center gap-1 text-sm leading-none text-destructive">
|
|
||||||
Issues
|
|
||||||
<BanIcon size={14} />
|
|
||||||
</div>
|
|
||||||
</Tooltiper>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Input ref={ref} id={label} {...props} />
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
139
apps/dashboard/src/components/forms/tag-input.tsx
Normal file
139
apps/dashboard/src/components/forms/tag-input.tsx
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
// Based on Christin Alares tag input component (https://github.com/christianalares/seventy-seven)
|
||||||
|
|
||||||
|
import type { ElementRef } from 'react';
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { cn } from '@/utils/cn';
|
||||||
|
import { useAnimate } from 'framer-motion';
|
||||||
|
import { XIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
placeholder: string;
|
||||||
|
value: string[];
|
||||||
|
error?: string;
|
||||||
|
className?: string;
|
||||||
|
onChange: (value: string[]) => void;
|
||||||
|
renderTag?: (tag: string) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const TagInput = ({
|
||||||
|
value: propValue,
|
||||||
|
onChange,
|
||||||
|
renderTag,
|
||||||
|
placeholder,
|
||||||
|
error,
|
||||||
|
}: Props) => {
|
||||||
|
const value = (
|
||||||
|
Array.isArray(propValue) ? propValue : propValue ? [propValue] : []
|
||||||
|
).filter(Boolean);
|
||||||
|
|
||||||
|
const [isMarkedForDeletion, setIsMarkedForDeletion] = useState(false);
|
||||||
|
const inputRef = useRef<ElementRef<'input'>>(null);
|
||||||
|
const [inputValue, setInputValue] = useState('');
|
||||||
|
|
||||||
|
const [scope, animate] = useAnimate();
|
||||||
|
|
||||||
|
const appendTag = (tag: string) => {
|
||||||
|
onChange([...value, tag]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeTag = (tag: string) => {
|
||||||
|
onChange(value.filter((t) => t !== tag));
|
||||||
|
inputRef.current?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (inputValue.length > 0) {
|
||||||
|
setIsMarkedForDeletion(false);
|
||||||
|
}
|
||||||
|
}, [inputValue]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={scope}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex w-full flex-wrap items-center gap-2 rounded-md border border-input p-1 px-3 ring-offset-background has-[input:focus]:ring-2 has-[input:focus]:ring-ring has-[input:focus]:ring-offset-1',
|
||||||
|
!!error && 'border-destructive'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{value.map((tag, i) => {
|
||||||
|
const isCreating = false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-tag={tag}
|
||||||
|
key={tag}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center gap-2 rounded bg-def-200 px-2 py-1 text-sm',
|
||||||
|
isMarkedForDeletion &&
|
||||||
|
i === value.length - 1 &&
|
||||||
|
'bg-destructive-foreground ring-2 ring-destructive/50 ring-offset-1',
|
||||||
|
isCreating && 'opacity-60'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{renderTag ? renderTag(tag) : tag}
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="outline"
|
||||||
|
className="h-4 w-4 rounded-full"
|
||||||
|
onClick={() => removeTag(tag)}
|
||||||
|
>
|
||||||
|
<span className="sr-only">Remove tag</span>
|
||||||
|
<XIcon name="close" className="size-3" />
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
placeholder={`${placeholder} ↵`}
|
||||||
|
className="min-w-20 flex-1 py-1 text-sm focus-visible:outline-none"
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const tagAlreadyExists = value.some(
|
||||||
|
(tag) => tag.toLowerCase() === inputValue.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (inputValue) {
|
||||||
|
if (tagAlreadyExists) {
|
||||||
|
animate(
|
||||||
|
`span[data-tag="${inputValue.toLowerCase()}"]`,
|
||||||
|
{
|
||||||
|
scale: [1, 1.3, 1],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
duration: 0.3,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
appendTag(inputValue);
|
||||||
|
setInputValue('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.key === 'Backspace' && inputValue === '') {
|
||||||
|
if (!isMarkedForDeletion) {
|
||||||
|
setIsMarkedForDeletion(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const last = value[value.length - 1];
|
||||||
|
if (last) {
|
||||||
|
removeTag(last);
|
||||||
|
}
|
||||||
|
setIsMarkedForDeletion(false);
|
||||||
|
setInputValue('');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TagInput;
|
||||||
@@ -12,7 +12,7 @@ const Checkbox = React.forwardRef<
|
|||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
'block h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -29,9 +29,14 @@ Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
|||||||
const CheckboxInput = React.forwardRef<
|
const CheckboxInput = React.forwardRef<
|
||||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||||
>((props, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<label className="flex min-h-10 cursor-pointer select-none items-center gap-4 rounded-md border border-border px-3">
|
<label
|
||||||
<Checkbox ref={ref} {...props} />
|
className={cn(
|
||||||
|
'flex min-h-10 cursor-pointer select-none gap-4 rounded-md border border-border px-3 py-[0.5rem]',
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Checkbox ref={ref} {...props} className="relative top-0.5" />
|
||||||
<div className="text-sm font-medium">{props.children}</div>
|
<div className="text-sm font-medium">{props.children}</div>
|
||||||
</label>
|
</label>
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ export function KeyValue({ href, onClick, name, value }: KeyValueProps) {
|
|||||||
)}
|
)}
|
||||||
{...{ href, onClick }}
|
{...{ href, onClick }}
|
||||||
>
|
>
|
||||||
<div className="bg-black/5 p-1 px-2">{name}</div>
|
<div className="bg-black/5 p-1 px-2 capitalize">{name}</div>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'text-highlight overflow-hidden text-ellipsis whitespace-nowrap bg-card p-1 px-2 font-mono',
|
'overflow-hidden text-ellipsis whitespace-nowrap bg-card p-1 px-2 font-mono text-highlight',
|
||||||
clickable && 'group-hover:underline'
|
clickable && 'group-hover:underline'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import AnimateHeight from '@/components/animate-height';
|
import AnimateHeight from '@/components/animate-height';
|
||||||
import { CreateClientSuccess } from '@/components/clients/create-client-success';
|
import { CreateClientSuccess } from '@/components/clients/create-client-success';
|
||||||
|
import TagInput from '@/components/forms/tag-input';
|
||||||
import { Button, buttonVariants } from '@/components/ui/button';
|
import { Button, buttonVariants } from '@/components/ui/button';
|
||||||
|
import { CheckboxInput } from '@/components/ui/checkbox';
|
||||||
import { Combobox } from '@/components/ui/combobox';
|
import { Combobox } from '@/components/ui/combobox';
|
||||||
import { DialogFooter } from '@/components/ui/dialog';
|
import { DialogFooter } from '@/components/ui/dialog';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -25,9 +27,10 @@ import { ModalContent, ModalHeader } from './Modal/Container';
|
|||||||
|
|
||||||
const validation = z.object({
|
const validation = z.object({
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
cors: z.string().url().or(z.literal('')),
|
cors: z.string().min(1).or(z.literal('')),
|
||||||
projectId: z.string(),
|
projectId: z.string(),
|
||||||
type: z.enum(['read', 'write', 'root']),
|
type: z.enum(['read', 'write', 'root']),
|
||||||
|
crossDomain: z.boolean().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type IForm = z.infer<typeof validation>;
|
type IForm = z.infer<typeof validation>;
|
||||||
@@ -45,6 +48,7 @@ export default function AddClient(props: Props) {
|
|||||||
cors: '',
|
cors: '',
|
||||||
projectId: props.projectId ?? projectId,
|
projectId: props.projectId ?? projectId,
|
||||||
type: 'write',
|
type: 'write',
|
||||||
|
crossDomain: undefined,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const [hasDomain, setHasDomain] = useState(true);
|
const [hasDomain, setHasDomain] = useState(true);
|
||||||
@@ -59,12 +63,19 @@ export default function AddClient(props: Props) {
|
|||||||
organizationSlug,
|
organizationSlug,
|
||||||
});
|
});
|
||||||
const onSubmit: SubmitHandler<IForm> = (values) => {
|
const onSubmit: SubmitHandler<IForm> = (values) => {
|
||||||
|
if (hasDomain && values.cors === '') {
|
||||||
|
return form.setError('cors', {
|
||||||
|
type: 'required',
|
||||||
|
message: 'Please add a domain',
|
||||||
|
});
|
||||||
|
}
|
||||||
mutation.mutate({
|
mutation.mutate({
|
||||||
name: values.name,
|
name: values.name,
|
||||||
cors: hasDomain ? values.cors : null,
|
cors: hasDomain ? values.cors : null,
|
||||||
projectId: values.projectId,
|
projectId: values.projectId,
|
||||||
organizationSlug,
|
organizationSlug,
|
||||||
type: values.type,
|
type: values.type,
|
||||||
|
crossDomain: values.crossDomain,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -132,14 +143,59 @@ export default function AddClient(props: Props) {
|
|||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label className="flex items-center justify-between">
|
<Label className="flex items-center justify-between">
|
||||||
<span>Domain</span>
|
<span>Domain(s)</span>
|
||||||
<Switch checked={hasDomain} onCheckedChange={setHasDomain} />
|
<Switch checked={hasDomain} onCheckedChange={setHasDomain} />
|
||||||
</Label>
|
</Label>
|
||||||
<AnimateHeight open={hasDomain}>
|
<AnimateHeight open={hasDomain}>
|
||||||
<Input
|
<Controller
|
||||||
placeholder="https://example.com"
|
name="cors"
|
||||||
error={form.formState.errors.cors?.message}
|
control={form.control}
|
||||||
{...form.register('cors')}
|
render={({ field }) => (
|
||||||
|
<TagInput
|
||||||
|
{...field}
|
||||||
|
error={form.formState.errors.cors?.message}
|
||||||
|
placeholder="Add a domain"
|
||||||
|
value={field.value?.split(',') ?? []}
|
||||||
|
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
field.onChange(
|
||||||
|
newValue
|
||||||
|
.map((item) => {
|
||||||
|
const trimmed = item.trim();
|
||||||
|
if (
|
||||||
|
trimmed.startsWith('http://') ||
|
||||||
|
trimmed.startsWith('https://') ||
|
||||||
|
trimmed === '*'
|
||||||
|
) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
return `https://${trimmed}`;
|
||||||
|
})
|
||||||
|
.join(',')
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="crossDomain"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => {
|
||||||
|
return (
|
||||||
|
<CheckboxInput
|
||||||
|
className="mt-4"
|
||||||
|
ref={field.ref}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
defaultChecked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
>
|
||||||
|
<div>Enable cross domain support</div>
|
||||||
|
<div className="font-normal text-muted-foreground">
|
||||||
|
This will let you track users across multiple domains
|
||||||
|
</div>
|
||||||
|
</CheckboxInput>
|
||||||
|
);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</AnimateHeight>
|
</AnimateHeight>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { ButtonContainer } from '@/components/button-container';
|
import { ButtonContainer } from '@/components/button-container';
|
||||||
import { InputWithLabel } from '@/components/forms/input-with-label';
|
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
|
||||||
|
import TagInput from '@/components/forms/tag-input';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { CheckboxInput } from '@/components/ui/checkbox';
|
||||||
import { api, handleError } from '@/trpc/client';
|
import { api, handleError } from '@/trpc/client';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { useForm } from 'react-hook-form';
|
import { Controller, useForm } from 'react-hook-form';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -19,20 +21,28 @@ const validator = z.object({
|
|||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
cors: z.string().nullable(),
|
cors: z.string().nullable(),
|
||||||
|
crossDomain: z.boolean().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type IForm = z.infer<typeof validator>;
|
type IForm = z.infer<typeof validator>;
|
||||||
|
|
||||||
export default function EditClient({ id, name, cors }: EditClientProps) {
|
export default function EditClient({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
cors,
|
||||||
|
crossDomain,
|
||||||
|
}: EditClientProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { register, handleSubmit, reset, formState } = useForm<IForm>({
|
const { register, handleSubmit, reset, formState, control, setError } =
|
||||||
resolver: zodResolver(validator),
|
useForm<IForm>({
|
||||||
defaultValues: {
|
resolver: zodResolver(validator),
|
||||||
id,
|
defaultValues: {
|
||||||
name,
|
id,
|
||||||
cors,
|
name,
|
||||||
},
|
cors,
|
||||||
});
|
crossDomain,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const mutation = api.client.update.useMutation({
|
const mutation = api.client.update.useMutation({
|
||||||
onError: handleError,
|
onError: handleError,
|
||||||
@@ -51,6 +61,13 @@ export default function EditClient({ id, name, cors }: EditClientProps) {
|
|||||||
<ModalHeader title="Edit client" />
|
<ModalHeader title="Edit client" />
|
||||||
<form
|
<form
|
||||||
onSubmit={handleSubmit((values) => {
|
onSubmit={handleSubmit((values) => {
|
||||||
|
if (!values.cors) {
|
||||||
|
return setError('cors', {
|
||||||
|
type: 'required',
|
||||||
|
message: 'Please add a domain',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
mutation.mutate(values);
|
mutation.mutate(values);
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
@@ -60,10 +77,61 @@ export default function EditClient({ id, name, cors }: EditClientProps) {
|
|||||||
placeholder="Name"
|
placeholder="Name"
|
||||||
{...register('name')}
|
{...register('name')}
|
||||||
/>
|
/>
|
||||||
<InputWithLabel
|
|
||||||
label="Cors"
|
<Controller
|
||||||
placeholder="Cors"
|
name="cors"
|
||||||
{...register('cors')}
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<WithLabel
|
||||||
|
label="Domain(s)"
|
||||||
|
error={formState.errors.cors?.message}
|
||||||
|
>
|
||||||
|
<TagInput
|
||||||
|
{...field}
|
||||||
|
error={formState.errors.cors?.message}
|
||||||
|
placeholder="Add a domain"
|
||||||
|
value={field.value?.split(',') ?? []}
|
||||||
|
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
field.onChange(
|
||||||
|
newValue
|
||||||
|
.map((item) => {
|
||||||
|
const trimmed = item.trim();
|
||||||
|
if (
|
||||||
|
trimmed.startsWith('http://') ||
|
||||||
|
trimmed.startsWith('https://') ||
|
||||||
|
trimmed === '*'
|
||||||
|
) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
return `https://${trimmed}`;
|
||||||
|
})
|
||||||
|
.join(',')
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</WithLabel>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Controller
|
||||||
|
name="crossDomain"
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => {
|
||||||
|
return (
|
||||||
|
<CheckboxInput
|
||||||
|
ref={field.ref}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
defaultChecked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
>
|
||||||
|
<div>Enable cross domain support</div>
|
||||||
|
<div className="font-normal text-muted-foreground">
|
||||||
|
This will let you track users across multiple domains
|
||||||
|
</div>
|
||||||
|
</CheckboxInput>
|
||||||
|
);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<ButtonContainer>
|
<ButtonContainer>
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
"name": "@openpanel/worker",
|
"name": "@openpanel/worker",
|
||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"qweqweq": "dotenv -e ../../.env -c -v WATCH=1 tsup",
|
"dev": "dotenv -e ../../.env -c -v WATCH=1 tsup",
|
||||||
"qweqwe": "WORKER_PORT=9999 pnpm dev",
|
"testing": "WORKER_PORT=9999 pnpm dev",
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
"build": "rm -rf dist && tsup",
|
"build": "rm -rf dist && tsup",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ export async function incomingEvent(job: Job<EventsQueuePayloadIncomingEvent>) {
|
|||||||
projectId,
|
projectId,
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
previousDeviceId,
|
previousDeviceId,
|
||||||
|
// TODO: Remove after 2024-09-26
|
||||||
|
currentDeviceIdDeprecated,
|
||||||
|
previousDeviceIdDeprecated,
|
||||||
} = job.data.payload;
|
} = job.data.payload;
|
||||||
let deviceId: string | null = null;
|
let deviceId: string | null = null;
|
||||||
|
|
||||||
@@ -106,20 +109,43 @@ export async function incomingEvent(job: Job<EventsQueuePayloadIncomingEvent>) {
|
|||||||
sessionEndKeys,
|
sessionEndKeys,
|
||||||
`sessionEnd:${projectId}:${previousDeviceId}:`
|
`sessionEnd:${projectId}:${previousDeviceId}:`
|
||||||
);
|
);
|
||||||
|
// TODO: Remove after 2024-09-26
|
||||||
|
const sessionEndJobCurrentDeviceIdDeprecated = await findJobByPrefix(
|
||||||
|
eventsQueue,
|
||||||
|
sessionEndKeys,
|
||||||
|
`sessionEnd:${projectId}:${currentDeviceIdDeprecated}:`
|
||||||
|
);
|
||||||
|
const sessionEndJobPreviousDeviceIdDeprecated = await findJobByPrefix(
|
||||||
|
eventsQueue,
|
||||||
|
sessionEndKeys,
|
||||||
|
`sessionEnd:${projectId}:${previousDeviceIdDeprecated}:`
|
||||||
|
);
|
||||||
|
|
||||||
const createSessionStart =
|
let createSessionStart = false;
|
||||||
!sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId;
|
|
||||||
|
|
||||||
if (sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId) {
|
if (sessionEndJobCurrentDeviceId) {
|
||||||
deviceId = currentDeviceId;
|
deviceId = currentDeviceId;
|
||||||
const diff = Date.now() - sessionEndJobCurrentDeviceId.timestamp;
|
const diff = Date.now() - sessionEndJobCurrentDeviceId.timestamp;
|
||||||
sessionEndJobCurrentDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
|
sessionEndJobCurrentDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
|
||||||
} else if (!sessionEndJobCurrentDeviceId && sessionEndJobPreviousDeviceId) {
|
} else if (sessionEndJobPreviousDeviceId) {
|
||||||
deviceId = previousDeviceId;
|
deviceId = previousDeviceId;
|
||||||
const diff = Date.now() - sessionEndJobPreviousDeviceId.timestamp;
|
const diff = Date.now() - sessionEndJobPreviousDeviceId.timestamp;
|
||||||
sessionEndJobPreviousDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
|
sessionEndJobPreviousDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
|
||||||
|
} else if (sessionEndJobCurrentDeviceIdDeprecated) {
|
||||||
|
deviceId = currentDeviceIdDeprecated;
|
||||||
|
const diff = Date.now() - sessionEndJobCurrentDeviceIdDeprecated.timestamp;
|
||||||
|
sessionEndJobCurrentDeviceIdDeprecated.changeDelay(
|
||||||
|
diff + SESSION_END_TIMEOUT
|
||||||
|
);
|
||||||
|
} else if (sessionEndJobPreviousDeviceIdDeprecated) {
|
||||||
|
deviceId = previousDeviceIdDeprecated;
|
||||||
|
const diff = Date.now() - sessionEndJobPreviousDeviceIdDeprecated.timestamp;
|
||||||
|
sessionEndJobPreviousDeviceIdDeprecated.changeDelay(
|
||||||
|
diff + SESSION_END_TIMEOUT
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
deviceId = currentDeviceId;
|
deviceId = currentDeviceId;
|
||||||
|
createSessionStart = true;
|
||||||
// Queue session end
|
// Queue session end
|
||||||
eventsQueue.add(
|
eventsQueue.add(
|
||||||
'event',
|
'event',
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "clients" ADD COLUMN "crossDomain" BOOLEAN NOT NULL DEFAULT false;
|
||||||
@@ -171,6 +171,7 @@ model Client {
|
|||||||
organization Organization? @relation(fields: [organizationId], references: [id])
|
organization Organization? @relation(fields: [organizationId], references: [id])
|
||||||
organizationId String?
|
organizationId String?
|
||||||
cors String?
|
cors String?
|
||||||
|
crossDomain Boolean @default(false)
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @default(now()) @updatedAt
|
updatedAt DateTime @default(now()) @updatedAt
|
||||||
|
|||||||
@@ -16,5 +16,8 @@ export async function getClientsByOrganizationSlug(organizationSlug: string) {
|
|||||||
include: {
|
include: {
|
||||||
project: true,
|
project: true,
|
||||||
},
|
},
|
||||||
|
orderBy: {
|
||||||
|
createdAt: 'asc',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,12 @@ export interface EventsQueuePayloadIncomingEvent {
|
|||||||
latitude: number | undefined;
|
latitude: number | undefined;
|
||||||
};
|
};
|
||||||
headers: {
|
headers: {
|
||||||
origin: string | undefined;
|
|
||||||
ua: string | undefined;
|
ua: string | undefined;
|
||||||
};
|
};
|
||||||
currentDeviceId: string;
|
currentDeviceId: string;
|
||||||
previousDeviceId: string;
|
previousDeviceId: string;
|
||||||
|
currentDeviceIdDeprecated: string;
|
||||||
|
previousDeviceIdDeprecated: string;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export interface EventsQueuePayloadCreateEvent {
|
export interface EventsQueuePayloadCreateEvent {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { clerkClient } from '@clerk/fastify';
|
|
||||||
|
|
||||||
import { db, getProjectById } from '@openpanel/db';
|
import { db, getProjectById } from '@openpanel/db';
|
||||||
import { cacheable } from '@openpanel/redis';
|
import { cacheable } from '@openpanel/redis';
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { randomUUID } from 'crypto';
|
import crypto from 'crypto';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { hashPassword, stripTrailingSlash } from '@openpanel/common';
|
import { hashPassword, stripTrailingSlash } from '@openpanel/common';
|
||||||
@@ -14,6 +14,7 @@ export const clientRouter = createTRPCRouter({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
cors: z.string().nullable(),
|
cors: z.string().nullable(),
|
||||||
|
crossDomain: z.boolean().optional(),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.mutation(({ input }) => {
|
.mutation(({ input }) => {
|
||||||
@@ -24,6 +25,7 @@ export const clientRouter = createTRPCRouter({
|
|||||||
data: {
|
data: {
|
||||||
name: input.name,
|
name: input.name,
|
||||||
cors: input.cors ?? null,
|
cors: input.cors ?? null,
|
||||||
|
crossDomain: input.crossDomain,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -34,11 +36,12 @@ export const clientRouter = createTRPCRouter({
|
|||||||
projectId: z.string(),
|
projectId: z.string(),
|
||||||
organizationSlug: z.string(),
|
organizationSlug: z.string(),
|
||||||
cors: z.string().nullable(),
|
cors: z.string().nullable(),
|
||||||
|
crossDomain: z.boolean().optional(),
|
||||||
type: z.enum(['read', 'write', 'root']).optional(),
|
type: z.enum(['read', 'write', 'root']).optional(),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input }) => {
|
||||||
const secret = randomUUID();
|
const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
|
||||||
const data: Prisma.ClientCreateArgs['data'] = {
|
const data: Prisma.ClientCreateArgs['data'] = {
|
||||||
organizationSlug: input.organizationSlug,
|
organizationSlug: input.organizationSlug,
|
||||||
organizationId: input.organizationSlug,
|
organizationId: input.organizationSlug,
|
||||||
@@ -47,6 +50,7 @@ export const clientRouter = createTRPCRouter({
|
|||||||
type: input.type ?? 'write',
|
type: input.type ?? 'write',
|
||||||
cors: input.cors ? stripTrailingSlash(input.cors) : null,
|
cors: input.cors ? stripTrailingSlash(input.cors) : null,
|
||||||
secret: await hashPassword(secret),
|
secret: await hashPassword(secret),
|
||||||
|
crossDomain: input.crossDomain ?? false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const client = await db.client.create({ data });
|
const client = await db.client.create({ data });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { randomUUID } from 'crypto';
|
import crypto from 'crypto';
|
||||||
import type { z } from 'zod';
|
import type { z } from 'zod';
|
||||||
|
|
||||||
import { hashPassword, slug, stripTrailingSlash } from '@openpanel/common';
|
import { hashPassword, stripTrailingSlash } from '@openpanel/common';
|
||||||
import { db, getId, getOrganizationBySlug, getUserById } from '@openpanel/db';
|
import { db, getId, getOrganizationBySlug, getUserById } from '@openpanel/db';
|
||||||
import type { ProjectType } from '@openpanel/db';
|
import type { ProjectType } from '@openpanel/db';
|
||||||
import { zOnboardingProject } from '@openpanel/validation';
|
import { zOnboardingProject } from '@openpanel/validation';
|
||||||
@@ -66,7 +66,7 @@ export const onboardingRouter = createTRPCRouter({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const secret = randomUUID();
|
const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
|
||||||
const client = await db.client.create({
|
const client = await db.client.create({
|
||||||
data: {
|
data: {
|
||||||
name: `${project.name} Client`,
|
name: `${project.name} Client`,
|
||||||
|
|||||||
Reference in New Issue
Block a user