-
Notifications
You must be signed in to change notification settings - Fork 23
#622 - Implement Collection Export to ZIP with Secret Handling #655
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
Open
giemic8
wants to merge
2
commits into
main
Choose a base branch
from
feature/622-trufos-exporter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { describe, it, expect, beforeEach } from 'vitest'; | ||
| import { ExportService } from './export-service'; | ||
| import { Collection } from 'shim/objects/collection'; | ||
| import path from 'path'; | ||
| import fs from 'node:fs/promises'; | ||
| import { tmpdir } from 'os'; | ||
| import { ZipReader, BlobReader, TextWriter } from '@zip.js/zip.js'; | ||
|
|
||
| const exportService = ExportService.instance; | ||
|
|
||
| describe('ExportService', () => { | ||
| let tempDir: string; | ||
| let testCollection: Collection; | ||
|
|
||
| beforeEach(async () => { | ||
| tempDir = path.join(tmpdir(), 'trufos-export-test-' + Date.now()); | ||
| await fs.mkdir(tempDir, { recursive: true }); | ||
|
|
||
| testCollection = { | ||
| id: 'test-collection-id', | ||
| type: 'collection', | ||
| title: 'Test Collection', | ||
| dirPath: path.join(tempDir, 'test-collection'), | ||
| variables: {}, | ||
| environments: {}, | ||
| children: [], | ||
| }; | ||
|
|
||
| await fs.mkdir(testCollection.dirPath, { recursive: true }); | ||
| await fs.writeFile( | ||
| path.join(testCollection.dirPath, 'collection.json'), | ||
| JSON.stringify({ | ||
| title: 'Test Collection', | ||
| variables: { | ||
| normalVar: { value: 'normal-value', secret: false }, | ||
| secretVar: { value: 'secret-value', secret: true }, | ||
| }, | ||
| environments: { | ||
| dev: { | ||
| variables: { | ||
| envNormal: { value: 'env-normal', secret: false }, | ||
| envSecret: { value: 'env-secret', secret: true }, | ||
| }, | ||
| }, | ||
| }, | ||
| }) | ||
| ); | ||
| }); | ||
|
|
||
| it('should export collection as ZIP file', async () => { | ||
| const outputPath = await exportService.exportCollection(testCollection, tempDir); | ||
|
|
||
| expect(outputPath).toBe(path.join(tempDir, 'Test Collection.trufos.zip')); | ||
| const stats = await fs.stat(outputPath); | ||
| expect(stats.isFile()).toBe(true); | ||
| }); | ||
|
|
||
| it('should exclude secrets by default', async () => { | ||
| await fs.writeFile(path.join(testCollection.dirPath, '.secrets.bin'), 'secret-data'); | ||
|
|
||
| await exportService.exportCollection(testCollection, tempDir); | ||
| }); | ||
|
|
||
| it('should include secrets when option is set', async () => { | ||
| await fs.writeFile(path.join(testCollection.dirPath, '.secrets.bin'), 'secret-data'); | ||
|
|
||
| await exportService.exportCollection(testCollection, tempDir, { | ||
| includeSecrets: true, | ||
| }); | ||
| }); | ||
|
|
||
| it('should clear secret values but keep keys when not including secrets', async () => { | ||
| const outputPath = await exportService.exportCollection(testCollection, tempDir, { | ||
| includeSecrets: false, | ||
| }); | ||
|
|
||
| const zipBlob = new Blob([await fs.readFile(outputPath)]); | ||
| const zipReader = new ZipReader(new BlobReader(zipBlob)); | ||
| const entries = await zipReader.getEntries(); | ||
|
|
||
| const collectionJsonEntry = entries.find((e) => e.filename === 'collection.json'); | ||
| expect(collectionJsonEntry).toBeDefined(); | ||
|
|
||
| if (collectionJsonEntry && collectionJsonEntry.getData) { | ||
| const textWriter = new TextWriter(); | ||
| const content = await collectionJsonEntry.getData(textWriter); | ||
| const json = JSON.parse(content); | ||
|
|
||
| expect(json.variables.normalVar.value).toBe('normal-value'); | ||
| expect(json.variables.secretVar.value).toBe(''); | ||
| expect(json.variables.secretVar.secret).toBe(true); | ||
|
|
||
| expect(json.environments.dev.variables.envNormal.value).toBe('env-normal'); | ||
| expect(json.environments.dev.variables.envSecret.value).toBe(''); | ||
| expect(json.environments.dev.variables.envSecret.secret).toBe(true); | ||
| } | ||
|
|
||
| await zipReader.close(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| import { Collection } from 'shim/objects/collection'; | ||
| import path from 'path'; | ||
| import { BlobWriter, ZipWriter, TextReader } from '@zip.js/zip.js'; | ||
| import fs from 'node:fs/promises'; | ||
| import { SECRETS_FILE_NAME } from 'main/persistence/constants'; | ||
| import { VariableMap } from 'shim/objects/variables'; | ||
|
|
||
| export type ExportOptions = { | ||
| includeSecrets: boolean; | ||
| password?: string; | ||
| }; | ||
|
|
||
| function clearSecretValues(variables: VariableMap): VariableMap { | ||
| const cleared: VariableMap = {}; | ||
| for (const [key, variable] of Object.entries(variables)) { | ||
| if (variable.secret) { | ||
| cleared[key] = { ...variable, value: '' }; | ||
| } else { | ||
| cleared[key] = variable; | ||
| } | ||
| } | ||
| return cleared; | ||
| } | ||
|
|
||
| export class ExportService { | ||
| public static readonly instance = new ExportService(); | ||
|
|
||
| async exportCollection( | ||
| collection: Collection, | ||
| outputPath: string, | ||
| options: ExportOptions = { includeSecrets: false } | ||
| ): Promise<string> { | ||
| const collectionDirPath = collection.dirPath; | ||
| const collectionName = collection.title; | ||
| const zipFileName = `${collectionName}.trufos.zip`; | ||
| const fullOutputPath = path.join(outputPath, zipFileName); | ||
|
|
||
| logger.info(`Exporting collection "${collectionName}" to "${fullOutputPath}"`); | ||
|
|
||
| const blobWriter = new BlobWriter('application/zip'); | ||
| const zipWriter = new ZipWriter(blobWriter, { | ||
| password: options.password, | ||
| encryptionStrength: 3, | ||
| }); | ||
|
|
||
| await this.addDirectoryToZip(zipWriter, collectionDirPath, '', options.includeSecrets); | ||
|
|
||
| await zipWriter.close(); | ||
| const blob = await blobWriter.getData(); | ||
| const buffer = await blob.arrayBuffer(); | ||
|
|
||
| await fs.writeFile(fullOutputPath, Buffer.from(buffer)); | ||
| logger.info(`Successfully exported collection to "${fullOutputPath}"`); | ||
|
|
||
| return fullOutputPath; | ||
| } | ||
|
|
||
| private async addDirectoryToZip( | ||
| zipWriter: ZipWriter<unknown>, | ||
| dirPath: string, | ||
| basePath: string, | ||
| includeSecrets: boolean | ||
| ): Promise<void> { | ||
| const entries = await fs.readdir(dirPath, { withFileTypes: true }); | ||
|
|
||
| for (const entry of entries) { | ||
| const entryPath = path.join(dirPath, entry.name); | ||
| const zipPath = path.join(basePath, entry.name); | ||
|
|
||
| if (entry.isDirectory()) { | ||
| await this.addDirectoryToZip(zipWriter, entryPath, zipPath, includeSecrets); | ||
| } else { | ||
| if (entry.name === SECRETS_FILE_NAME) { | ||
| if (!includeSecrets) { | ||
| logger.debug(`Skipping secrets file: ${zipPath}`); | ||
| continue; | ||
| } | ||
| } | ||
|
|
||
| let fileContent = await fs.readFile(entryPath, 'utf-8'); | ||
|
|
||
| if (!includeSecrets && entry.name.endsWith('.json')) { | ||
| try { | ||
| const json = JSON.parse(fileContent); | ||
|
|
||
| if (json.variables) { | ||
| json.variables = clearSecretValues(json.variables); | ||
| } | ||
|
|
||
| if (json.environments) { | ||
| for (const [envKey, envValue] of Object.entries(json.environments)) { | ||
| if (envValue && typeof envValue === 'object' && 'variables' in envValue) { | ||
| json.environments[envKey].variables = clearSecretValues( | ||
| (envValue as { variables: VariableMap }).variables | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fileContent = JSON.stringify(json, null, 2); | ||
| } catch { | ||
| logger.debug(`Could not parse JSON file ${zipPath}, adding as-is`); | ||
| } | ||
| } | ||
|
|
||
| await zipWriter.add(zipPath, new TextReader(fileContent)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,10 +11,12 @@ import { | |
| import { Button } from '@/components/ui/button'; | ||
| import { Separator } from '@/components/ui/separator'; | ||
| import { Input } from '@/components/ui/input'; | ||
| import { Checkbox } from '@/components/ui/checkbox'; | ||
| import { MdOutlineContentCopy, MdOutlineModeEdit } from 'react-icons/md'; | ||
| import { TypographyLineClamp } from '@/components/shared/TypographyLineClamp'; | ||
| import { cn } from '@/lib/utils'; | ||
| import { RendererEventService } from '@/services/event/renderer-event-service'; | ||
| import { Download } from 'lucide-react'; | ||
|
|
||
| const eventService = RendererEventService.instance; | ||
|
|
||
|
|
@@ -28,6 +30,8 @@ export const CollectionSettings = ({ trufosObject, isOpen, onClose }: Collection | |
| const [name, setName] = useState(''); | ||
| const [pathName, setPathName] = useState(''); | ||
| const [collections, setCollections] = useState<CollectionBase[]>([]); | ||
| const [isExporting, setIsExporting] = useState(false); | ||
| const [includeSecrets, setIncludeSecrets] = useState(false); | ||
|
|
||
| const loadCollections = useCallback(async () => { | ||
| setCollections(await eventService.listCollections()); | ||
|
|
@@ -71,6 +75,27 @@ export const CollectionSettings = ({ trufosObject, isOpen, onClose }: Collection | |
| await navigator.clipboard.writeText(trufosObject.dirPath); | ||
| }; | ||
|
|
||
| const handleExportCollection = async () => { | ||
| try { | ||
| setIsExporting(true); | ||
| const result = await eventService.showOpenDialog({ | ||
| title: 'Select Export Location', | ||
| buttonLabel: 'Export', | ||
| properties: ['openDirectory'], | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why directory and not (ZIP)-file? |
||
| }); | ||
|
|
||
| if (!result.canceled && result.filePaths.length > 0) { | ||
| const outputPath = result.filePaths[0]; | ||
| await eventService.exportCollection(trufosObject, outputPath, includeSecrets); | ||
| console.info('Collection exported successfully'); | ||
| } | ||
| } catch (err) { | ||
| console.error('Failed to export collection', err); | ||
| } finally { | ||
| setIsExporting(false); | ||
| } | ||
| }; | ||
|
|
||
| const isValid = useMemo(() => { | ||
| return name.trim().length > 0 && name !== trufosObject.title; | ||
| }, [name, trufosObject.title]); | ||
|
|
@@ -80,7 +105,7 @@ export const CollectionSettings = ({ trufosObject, isOpen, onClose }: Collection | |
| <DialogContent> | ||
| <DialogHeader> | ||
| <DialogTitle>Collection Settings</DialogTitle> | ||
| <DialogDescription className={'text-[var(--text-secondary)]'}> | ||
| <DialogDescription className={'text-text-secondary'}> | ||
| Manage your collection options below. | ||
| </DialogDescription> | ||
| </DialogHeader> | ||
|
|
@@ -114,6 +139,39 @@ export const CollectionSettings = ({ trufosObject, isOpen, onClose }: Collection | |
|
|
||
| <Separator /> | ||
|
|
||
| <div className="space-y-3"> | ||
| <div className="flex items-center justify-between"> | ||
| <span className="text-text-secondary font-medium">Export Collection</span> | ||
|
|
||
| <Button | ||
| variant={'secondary'} | ||
| size="sm" | ||
| disabled={isExporting} | ||
| className="flex gap-2 rounded-full" | ||
| onClick={handleExportCollection} | ||
| > | ||
| <Download size={16} /> | ||
| {isExporting ? 'Exporting...' : 'Export'} | ||
| </Button> | ||
| </div> | ||
|
|
||
| <div className="flex items-center gap-2 pl-4"> | ||
| <Checkbox | ||
| id="include-secrets" | ||
| checked={includeSecrets} | ||
| onCheckedChange={(checked) => setIncludeSecrets(checked === true)} | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this also work? onCheckedChange={setIncludeSecrets} |
||
| /> | ||
| <label | ||
| htmlFor="include-secrets" | ||
| className="text-text-secondary cursor-pointer text-sm" | ||
| > | ||
| Include secret values | ||
| </label> | ||
| </div> | ||
| </div> | ||
|
|
||
| <Separator /> | ||
|
|
||
| <div className="flex items-center justify-between"> | ||
| <span className="text-destructive font-medium">Close Collection</span> | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should not be necessary. It would be the easiest to simply include or not include secret files from disk while zipping. No parsing needed.