Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow superadmins to change the username assigned to the blueprint #93

Open
wants to merge 8 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"@radix-ui/react-switch": "^1.1.1",
"@radix-ui/react-tooltip": "^1.1.6",
"@react-oauth/google": "^0.12.1",
"@zk-email/sdk": "0.0.126",
"@zk-email/sdk": "^0.0.132",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"framer-motion": "^11.11.11",
Expand Down
2 changes: 1 addition & 1 deletion src/app/(bluerpint-list)/BlueprintList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default function BlueprintList({ search, filters, sort }: BlueprintListPr
}

if (results) {
setBlueprints(results);
setBlueprints((prevBlueprints) => [...prevBlueprints, ...results]);
// If we got fewer results than the limit, we've reached the end
setHasMore(results.length === PAGINATION_LIMIT);
setSkip((prevSkip) => prevSkip + PAGINATION_LIMIT);
Expand Down
5 changes: 4 additions & 1 deletion src/app/[id]/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,11 @@ export const useProofStore = create<ProofState>()(
// TODO: Notify user about this
}

const { blueprint } = get();

try {
await parseEmail(content);
// Use ignoreBodyHashCheck if already set
await parseEmail(content, blueprint?.props.ignoreBodyHashCheck);
} catch (err) {
console.error('Failed to parse email, email is invalid: ', err);
throw err;
Expand Down
2 changes: 1 addition & 1 deletion src/app/create/[id]/createBlueprintSteps/EmailDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ const EmailDetails = ({
}

const content = await getFileContent(file);
const parsedEmail = await parseEmail(content);
const parsedEmail = await parseEmail(content, false);
const value = e.target.value;

if (!value) {
Expand Down
25 changes: 22 additions & 3 deletions src/app/create/[id]/createBlueprintSteps/ExtractFields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ const ExtractFields = ({
}

const content = await getFileContent(file);
const parsedEmail = await parseEmail(content);
const parsedEmail = await parseEmail(content, store.ignoreBodyHashCheck);
const body = parsedEmail.cleanedBody;
const header = parsedEmail.canonicalizedHeader;

Expand All @@ -144,12 +144,18 @@ const ExtractFields = ({
parsedRegex,
revealPrivateFields
);

setRegexGeneratedOutputs((prev) => {
const updated = [...prev];
// @ts-ignore
updated[index] = regexOutputs;
return updated;
});

// update the max length of the regex at that particular index
const decomposedRegexes = [...store.decomposedRegexes];
decomposedRegexes[index].maxLength = regexOutputs[0].length ?? 64;
setField('decomposedRegexes', decomposedRegexes);
} catch (error) {
console.error('Error testing decomposed regex:', error);
setRegexGeneratedOutputs((prev) => {
Expand All @@ -168,7 +174,18 @@ const ExtractFields = ({
generateRegexOutputs().finally(() => {
setIsGeneratingFields(false);
});
}, [file, JSON.stringify(store.decomposedRegexes)]);
}, [
file,
revealPrivateFields,
JSON.stringify(
store.decomposedRegexes?.map((regex) => ({
name: regex.name,
location: regex.location,
parts: regex.parts,
isHashed: regex.isHashed,
}))
),
]);

const handleGenerateFields = async (index: number) => {
const updatedIsGeneratingFieldsLoading = [...isGeneratingFieldsLoading];
Expand Down Expand Up @@ -277,7 +294,9 @@ const ExtractFields = ({
}
if (
!regexGeneratedOutputs.length ||
regexGeneratedOutputs.some((output) => output.length === 0)
regexGeneratedOutputs.some((output) =>
Array.isArray(output) ? output.join('').includes('Error') : output.includes('Error')
)
) {
setCanCompile(false);
return (
Expand Down
6 changes: 2 additions & 4 deletions src/app/create/[id]/createBlueprintSteps/PatternDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { useCreateBlueprintStore } from '../store';
import Image from 'next/image';
import sdk from '@/lib/sdk';
import { useDebouncedCallback } from 'use-debounce';
import { getFileContent } from '@/lib/utils';
import { extractEMLDetails } from '@zk-email/sdk';
import { findOrCreateDSP } from '@/app/utils';
import { toast } from 'react-toastify';

Expand All @@ -27,7 +25,7 @@ const PatternDetails = ({
const githubUserName = useAuthStore((state) => state.username);
const store = useCreateBlueprintStore();
const validationErrors = useCreateBlueprintStore((state) => state.validationErrors);

const { isAdmin } = useAuthStore();
const { setField } = store;

const checkExistingBlueprint = useDebouncedCallback(async (circuitName: string) => {
Expand Down Expand Up @@ -70,7 +68,7 @@ const PatternDetails = ({
error={!!validationErrors.title}
errorMessage={validationErrors.title}
/>
<Input title="Slug" disabled value={store.slug} />
<Input title="Slug" disabled={!isAdmin} value={store.slug} onChange={(e) => setField('slug', e.target.value)} />
{/* TODO: Add check for email body max length */}
<DragAndDropFile
accept=".eml"
Expand Down
19 changes: 10 additions & 9 deletions src/app/create/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,7 @@ import { useCreateBlueprintStore } from './store';
import { use, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import Image from 'next/image';
import {
extractEMLDetails,
DecomposedRegex,
testBlueprint,
getDKIMSelector,
parseEmail,
} from '@zk-email/sdk';
import { extractEMLDetails, DecomposedRegex, testBlueprint, parseEmail } from '@zk-email/sdk';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { getFileContent } from '@/lib/utils';
import { toast } from 'react-toastify';
Expand Down Expand Up @@ -59,6 +53,7 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => {
compile,
file,
setFile,
blueprint,
} = store;

const [errors, setErrors] = useState<string[]>([]);
Expand Down Expand Up @@ -170,9 +165,9 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => {
let content: string;
try {
content = await getFileContent(file);
const parsedEmail = await parseEmail(content);
const parsedEmail = await parseEmail(content, blueprint?.props.ignoreBodyHashCheck);
const { senderDomain, selector, emailQuery, headerLength, emailBodyMaxLength } =
await extractEMLDetails(content);
await extractEMLDetails(content, parsedEmail);
setCanonicalizedHeader(parsedEmail.canonicalizedHeader);
setCanonicalizedBody(parsedEmail.canonicalizedBody);
setDkimSelector(selector);
Expand All @@ -192,9 +187,15 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => {
posthog.capture('$test_email_error:failed_to_get_content', { error: err });
}
console.error('Failed to get content from email', err);
if (file) {
toast.error('Invalid email');
}
return;
}

// Bleurpint was not defined yet, skip testing email against blueprint
if (id === 'new') return;

try {
const parsed = getParsedDecomposedRegexes();

Expand Down
2 changes: 1 addition & 1 deletion src/app/create/[id]/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const initialState: BlueprintProps = {
senderDomain: '',
enableHeaderMasking: false,
enableBodyMasking: false,
isPublic: false,
isPublic: true,
verifierContract: {
chain: 84532,
address: '',
Expand Down
38 changes: 0 additions & 38 deletions src/app/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,44 +113,6 @@ const formatDateAndTime = (date: Date) => {
});
};

const getMaxEmailBodyLength = async (emlContent: string, shaPrecomputeSelector: string) => {
const parsedEmail = await parseEmail(emlContent);

const body = parsedEmail.cleanedBody;
const index = body.indexOf(shaPrecomputeSelector);

if (index === -1) {
return body.length;
}

return body.length - index - shaPrecomputeSelector.length;
};

const getDKIMSelector = (emlContent: string): string | null => {
const headerLines: string[] = [];
const lines = emlContent.split('\n');
for (const line of lines) {
if (line.trim() === '') break;
// If line starts with whitespace, it's a continuation of previous header
if (line.startsWith(' ') || line.startsWith('\t')) {
headerLines[headerLines.length - 1] += line.trim();
} else {
headerLines.push(line);
}
}

// Then look for DKIM-Signature in the joined headers
for (const line of headerLines) {
if (line.includes('DKIM-Signature')) {
const match = line.match(/s=([^;]+)/);
if (match && match[1]) {
return match[1].trim();
}
}
}
return null;
};

/**
* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed
* since the last time the debounced function was invoked.
Expand Down