-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1105 lines (964 loc) · 31.6 KB
/
main.go
File metadata and controls
1105 lines (964 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"encoding/base64"
"fmt"
"os"
"path/filepath"
"strings"
"zep/utils"
"github.com/spf13/cobra"
"golang.org/x/term"
)
var (
username string
keyPath string
historyFile = filepath.Join(os.TempDir(), ".zephyrus_history")
)
func main() {
var rootCmd = &cobra.Command{
Use: "zep",
Short: "Zephyrus CLI - Secure Vault on GitHub",
}
// Persistent flag allows -u to be used across all subcommands
rootCmd.PersistentFlags().StringVarP(&username, "user", "u", "", "GitHub username (forces stateless mode if no session exists)")
// --- SESSION HELPER ---
// This logic prioritizes the local zephyrus.conf, but falls back to
// manual auth if -u is provided or if the user is not connected.
getEffectiveSession := func() (*utils.Session, error) {
// 1. Check for active local session
sess, err := utils.GetSession()
if err == nil {
return sess, nil
}
// 2. Stateless Fallback: If not connected, prompt for info
if username == "" {
fmt.Print("No active session. Enter GitHub Username: ")
fmt.Scanln(&username)
}
pass, err := utils.GetPassword("Enter Vault Password: ")
if err != nil {
return nil, err
}
fmt.Println("Authenticating and fetching index (Stateless Mode)...")
return utils.FetchSessionStateless(username, pass)
}
// --- SETUP ---
var setupCmd = &cobra.Command{
Use: "setup [username] [key-path]",
Short: "Initialize vault and encrypt master key",
Args: cobra.MaximumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
if len(args) > 0 {
username = args[0]
}
if len(args) > 1 {
keyPath = args[1]
}
// Interactive guide if no arguments provided
if len(args) == 0 {
fmt.Println("\n=== Zephyrus Vault Setup Guide ===")
fmt.Println("Before we begin, please ensure you have completed the following steps:")
fmt.Println("1. ✓ Created a GitHub account (https://github.com)")
fmt.Println("2. ✓ Created an EMPTY repository named `.zephyrus` in your GitHub account")
fmt.Println("3. ✓ Generated an SSH key pair (run: ssh-keygen -t ed25519)")
fmt.Println("4. ✓ Added your PUBLIC key as a Deploy Key to your `.zephyrus` repository")
fmt.Println(" - Go to: https://github.com/YOUR_USERNAME/.zephyrus/settings/keys")
fmt.Println(" - Click 'Add deploy key'")
fmt.Println(" - Paste your PUBLIC key (id_ed25519.pub) content")
fmt.Println(" - Enable 'Allow write access' ✓")
fmt.Println("Do you have all of this ready? (y/n): ")
var ready string
fmt.Scanln(&ready)
if ready != "y" && ready != "yes" {
fmt.Println("\n❌ Setup cancelled. Please complete the prerequisites first.")
fmt.Println("📖 For detailed instructions, visit: https://github.com/zephyrus-development/zephyrus-cli#setup-your-vault")
return
}
fmt.Println("\n--- Step 1: GitHub Username ---")
fmt.Print("Enter your GitHub username: ")
fmt.Scanln(&username)
if username == "" {
fmt.Println("❌ Username cannot be empty.")
return
}
fmt.Println("\n--- Step 2: SSH Private Key Path ---")
fmt.Print("Enter the path to your SSH PRIVATE key (e.g., ~/.ssh/id_ed25519): ")
reader := bufio.NewReader(os.Stdin)
keyPathInput, _ := reader.ReadString('\n')
keyPath = strings.TrimSpace(keyPathInput)
if keyPath == "" {
fmt.Println("❌ Key path cannot be empty.")
return
}
// Expand ~ to home directory
if strings.HasPrefix(keyPath, "~") {
home, err := os.UserHomeDir()
if err == nil {
keyPath = strings.Replace(keyPath, "~", home, 1)
}
}
// Verify key file exists
if _, err := os.Stat(keyPath); err != nil {
fmt.Printf("❌ SSH key file not found at: %s\n", keyPath)
return
}
fmt.Println("\n--- Step 3: Vault Password ---")
fmt.Println("Create a strong password to encrypt your SSH key.")
fmt.Println("⚠️ IMPORTANT: This password cannot be recovered. Please remember it!")
pass, _ := utils.GetPassword("Create Vault Password: ")
if pass == "" {
fmt.Println("❌ Password cannot be empty.")
return
}
passConfirm, _ := utils.GetPassword("Confirm Vault Password: ")
if pass != passConfirm {
fmt.Println("❌ Passwords do not match.")
return
}
fmt.Println("\n--- Initializing Vault ---")
fmt.Printf("Setting up vault for user: %s\n", username)
err := utils.SetupVault(username, keyPath, pass)
if err != nil {
fmt.Printf("❌ Setup failed: %v\n", err)
fmt.Println("\n📖 Troubleshooting:")
fmt.Println("- Ensure .zephyrus repository exists at https://github.com/" + username + "/.zephyrus")
fmt.Println("- Verify your SSH key has been added as a Deploy Key with write access")
fmt.Println("- Check that your SSH key has permissions (chmod 600 on Unix-like systems)")
return
}
fmt.Println("\n✔ Setup complete!")
fmt.Println("\n--- Next Steps ---")
fmt.Println("1. Run 'zep connect' to create a local session")
fmt.Println("2. Run 'zep upload <file> <vault-path>' to upload your first file")
fmt.Println("3. Run 'zep help' to see all available commands")
return
}
// Non-interactive mode (arguments provided)
if username == "" || keyPath == "" {
fmt.Println("Error: Username and Key Path are required.")
return
}
pass, _ := utils.GetPassword("Create Vault Password: ")
err := utils.SetupVault(username, keyPath, pass)
if err != nil {
fmt.Printf("❌ Setup failed: %v\n", err)
return
}
fmt.Println("✔ Setup complete.")
},
}
// --- RESET PASSWORD ---
var resetPasswordCmd = &cobra.Command{
Use: "reset-password",
Aliases: []string{"reset-pass", "change-password", "change-pass"},
Short: "Change your vault password",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
// Check if the config file exists BEFORE starting
_, err := os.Stat("zephyrus.conf")
isPersistent := err == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
// Confirm current password
fmt.Println("For security, please confirm your current vault password.")
currentPass, err := utils.GetPassword("Current Vault Password: ")
if err != nil {
fmt.Printf("❌ Error reading password: %v\n", err)
return
}
if currentPass != session.Password {
fmt.Println("❌ Current password is incorrect.")
return
}
// Get new password
fmt.Println("\nCreate a new vault password.")
fmt.Println("⚠️ IMPORTANT: This password cannot be recovered. Please remember it!")
newPass, err := utils.GetPassword("New Vault Password: ")
if err != nil {
fmt.Printf("❌ Error reading password: %v\n", err)
return
}
if newPass == "" {
fmt.Println("❌ New password cannot be empty.")
return
}
// Confirm new password
passConfirm, err := utils.GetPassword("Confirm New Vault Password: ")
if err != nil {
fmt.Printf("❌ Error reading password: %v\n", err)
return
}
if newPass != passConfirm {
fmt.Println("❌ New passwords do not match.")
return
}
fmt.Println("\nResetting vault password...")
// Reset the password
err = utils.ResetPassword(session, newPass)
if err != nil {
fmt.Printf("❌ Password reset failed: %v\n", err)
return
}
// Only save the updated session if we were already in a persistent session
if isPersistent {
session.Save()
}
fmt.Println("✔ Password reset successful!")
fmt.Println("Your vault has been re-encrypted with the new password.")
},
}
// --- TRANSFER VAULT ---
var transferVaultCmd = &cobra.Command{
Use: "transfer-vault [source-username] [dest-username]",
Aliases: []string{"transfer", "xfer", "copy-vault"},
Short: "Transfer all files from one vault to another",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
sourceUsername := args[0]
destUsername := args[1]
if sourceUsername == destUsername {
fmt.Println("❌ Source and destination vaults must be different.")
return
}
// Get source vault password
fmt.Printf("Source vault authentication (%s):\n", sourceUsername)
sourcePass, err := utils.GetPassword("Source Vault Password: ")
if err != nil {
fmt.Printf("❌ Error reading password: %v\n", err)
return
}
// Get destination vault password
fmt.Printf("\nDestination vault authentication (%s):\n", destUsername)
destPass, err := utils.GetPassword("Destination Vault Password: ")
if err != nil {
fmt.Printf("❌ Error reading password: %v\n", err)
return
}
// Confirm transfer
fmt.Printf("\n⚠️ You are about to transfer all files from %s to %s.\n", sourceUsername, destUsername)
fmt.Print("This will copy all vault contents. Continue? (y/n): ")
var confirm string
fmt.Scanln(&confirm)
if confirm != "y" && confirm != "yes" {
fmt.Println("Transfer cancelled.")
return
}
// Perform transfer
err = utils.TransferVault(sourceUsername, sourcePass, destUsername, destPass)
if err != nil {
fmt.Printf("❌ Transfer failed: %v\n", err)
return
}
fmt.Println("✔ Vault transfer complete!")
fmt.Printf("All files have been successfully transferred from %s to %s\n", sourceUsername, destUsername)
},
}
// --- CONNECT ---
var connectCmd = &cobra.Command{
Use: "connect [username]",
Aliases: []string{"conn", "login", "auth", "signin", "con", "cn"},
Short: "Login and create a local session (caching the index)",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
target := username
if len(args) > 0 {
target = args[0]
}
if target == "" {
fmt.Print("Enter Username: ")
fmt.Scanln(&target)
}
pass, _ := utils.GetPassword("Enter Password: ")
err := utils.Connect(target, pass)
if err != nil {
fmt.Printf("❌ Connection failed: %v\n", err)
return
}
fmt.Println("✔ Connected.")
},
}
// --- UPLOAD ---
var uploadCmd = &cobra.Command{
Use: "upload [local-path] [vault-path]",
Aliases: []string{"up", "u", "add"}, // Multiple aliases allowed
Short: "Upload a file or directory to the vault",
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
localPath := args[0]
vaultPath := localPath
if len(args) > 1 {
vaultPath = args[1]
} else {
// Use basename of local path if vault path not provided
vaultPath = filepath.Base(localPath)
}
// 1. Check if the config file exists BEFORE starting
_, err := os.Stat("zephyrus.conf")
isPersistent := err == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
// Check if the local path is a directory
fileInfo, err := os.Stat(localPath)
if err != nil {
fmt.Printf("❌ Cannot access path: %v\n", err)
return
}
var uploadErr error
if fileInfo.IsDir() {
// Directory upload
uploadErr = utils.UploadDirectory(localPath, vaultPath, session)
} else {
// Single file upload
uploadErr = utils.UploadFile(localPath, vaultPath, session)
}
if uploadErr != nil {
fmt.Printf("❌ Upload failed: %v\n", uploadErr)
return
}
// 2. Only save the updated index if we were already in a persistent session
if isPersistent {
session.Save()
}
fmt.Println("✔ Upload successful.")
},
}
// --- DOWNLOAD ---
var sharedFlag string
var downloadCmd = &cobra.Command{
Use: "download [vault-path] [local-path]",
Aliases: []string{"down", "d", "get"},
Short: "Download a file or directory from the vault",
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
vaultPath := args[0]
localPath := vaultPath
if len(args) > 1 {
localPath = args[1]
} else {
// Use basename of vault path if local path not provided
localPath = filepath.Base(vaultPath)
}
// Check if downloading a shared file
if sharedFlag != "" {
err := utils.DownloadSharedFile(sharedFlag, localPath)
if err != nil {
fmt.Printf("❌ Shared file download failed: %v\n", err)
return
}
fmt.Println("✔ Shared file download successful.")
return
}
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
// Check if the vault path is a directory or file
entry, err := session.Index.FindEntry(vaultPath)
if err != nil {
fmt.Printf("❌ Download failed: %v\n", err)
return
}
var downloadErr error
if entry.Type == "folder" {
// Directory download
downloadErr = utils.DownloadDirectory(vaultPath, localPath, session)
} else {
// Single file download
downloadErr = utils.DownloadFile(vaultPath, localPath, session)
}
if downloadErr != nil {
fmt.Printf("❌ Download failed: %v\n", downloadErr)
return
}
fmt.Println("✔ Download successful.")
},
}
downloadCmd.Flags().StringVar(&sharedFlag, "shared", "", "Download a shared file using share string (username:storage_id:key)")
// --- DELETE ---
var deleteCmd = &cobra.Command{
Use: "delete [vault-path]",
Aliases: []string{"del", "rm", "remove"},
Short: "Delete a file or folder (recursive)",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
_, err := os.Stat("zephyrus.conf")
isPersistent := err == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
err = utils.DeletePath(args[0], session)
if err != nil {
fmt.Printf("❌ Delete failed: %v\n", err)
return
}
if isPersistent {
session.Save()
}
fmt.Println("✔ Item removed.")
},
}
// --- LIST ---
var listCmd = &cobra.Command{
Use: "ls [folder]",
Short: "List vault contents",
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
path := ""
if len(args) > 0 {
path = args[0]
}
utils.ListFiles(session, path)
},
}
// --- SEARCH ---
var searchCmd = &cobra.Command{
Use: "search [query]",
Aliases: []string{"s"},
Short: "Search the vault index",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
utils.SearchFiles(session, args[0])
},
}
// --- PURGE ---
var purgeCmd = &cobra.Command{
Use: "purge",
Short: "Wipe all remote data",
Run: func(cmd *cobra.Command, args []string) {
// Check if we are persistent BEFORE running
_, statErr := os.Stat("zephyrus.conf")
isPersistent := statErr == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
fmt.Print("⚠️ Confirm PURGE? This wipes all remote data and history. (y/N): ")
var confirm string
fmt.Scanln(&confirm)
if confirm != "y" {
return
}
err = utils.PurgeVault(session)
if err != nil {
fmt.Printf("❌ Purge failed: %v\n", err)
return
}
// Only update the local session file if it existed
if isPersistent {
session.Save()
}
fmt.Println("✔ Remote vault has been wiped and local index cleared.")
},
}
// --- DISCONNECT ---
var disconnectCmd = &cobra.Command{
Use: "disconnect",
Aliases: []string{"disc", "logout", "signout", "logoff", "exit", "dc"},
Short: "Remove local session cache",
Run: func(cmd *cobra.Command, args []string) {
utils.Disconnect()
fmt.Println("✔ Logged out.")
},
}
// --- SHARE ---
var shareCmd = &cobra.Command{
Use: "share [vault-path]",
Short: "Generate a share string for a file",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Check if the config file exists BEFORE starting
_, err := os.Stat("zephyrus.conf")
isPersistent := err == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
// Prompt for share password
sharePassword, _ := utils.GetPassword("Enter Share Password (recipients will use this to decrypt): ")
if sharePassword == "" {
fmt.Println("❌ Share password cannot be empty.")
return
}
shareString, err := utils.ShareFile(args[0], sharePassword, session)
if err != nil {
fmt.Printf("❌ Share failed: %v\n", err)
return
}
// Save the updated session if we were already in a persistent session
if isPersistent {
session.Save()
}
// Extract filename for display
filename := filepath.Base(args[0])
fmt.Println("\n✔ File shared successfully!")
fmt.Printf("Filename: %s\n", filename)
fmt.Println("\nShare this string with recipient:")
fmt.Println(shareString)
fmt.Println("\nWeb Share Link:")
fmt.Printf(" https://zep.ftp.sh/shared/#%s\n", shareString)
fmt.Println("\nRecipient can download with:")
fmt.Printf(" zep download _ output.file --shared \"%s\"\n", shareString)
fmt.Println("\nOr read with:")
fmt.Printf(" zep read _ --shared \"%s\"\n", shareString)
},
}
// --- READ ---
var readSharedFlag string
var readCmd = &cobra.Command{
Use: "read [vault-path]",
Aliases: []string{"cat"},
Short: "Read and display file content (no download)",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Check if reading a shared file
if readSharedFlag != "" {
err := utils.ReadSharedFile(readSharedFlag)
if err != nil {
fmt.Printf("❌ Shared file read failed: %v\n", err)
return
}
return
}
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
err = utils.ReadFile(args[0], session)
if err != nil {
fmt.Printf("❌ Read failed: %v\n", err)
return
}
},
}
readCmd.Flags().StringVar(&readSharedFlag, "shared", "", "Read a shared file using share string (username:storage_id:key)")
// --- SHARED MANAGEMENT ---
var sharedCmd = &cobra.Command{
Use: "shared",
Short: "Manage shared files",
}
var sharedLsCmd = &cobra.Command{
Use: "ls [file-name-pattern]",
Aliases: []string{"list", "find", "search"},
Short: "List shared files (optionally search by name)",
Long: `List all shared files, or search by partial/fuzzy filename match.
Without arguments: Shows all shared files with references and dates.
With file-name-pattern: Searches for files matching the pattern.
Examples:
zep shared ls # List all shared files
zep shared list # Same as ls (alias)
zep shared find report.pdf # Find files matching "report.pdf"
zep shared search report # Same as find (alias)`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
// If no arguments, list all shared files
if len(args) == 0 {
files := utils.ListSharedFiles(session)
if len(files) == 0 {
fmt.Println("No shared files.")
return
}
fmt.Println("\n📤 SHARED FILES")
fmt.Println("REFERENCE FILE NAME SHARED AT")
fmt.Println("--------- ---------- ---------")
for _, f := range files {
fmt.Printf("%-9s %-24s %s\n", f.Reference, f.OriginalPath, f.SharedAt.Format("2006-01-02 15:04"))
}
fmt.Println()
return
}
// If argument provided, search by name
nameQuery := args[0]
matches, err := utils.FindSharedFilesByName(nameQuery, session)
if err != nil {
fmt.Printf("❌ %v\n", err)
return
}
if len(matches) == 0 {
fmt.Printf("❌ No shared files found matching '%s'\n", nameQuery)
return
}
fmt.Printf("\n📂 Found %d match(es) for '%s':\n\n", len(matches), nameQuery)
for i, match := range matches {
fmt.Printf("[%d] %s\n", i+1, match.FileName)
fmt.Printf(" Vault Path: %s\n", match.OriginalPath)
fmt.Printf(" Reference: %s\n", match.Reference)
fmt.Printf(" Match Type: ")
if match.MatchScore == 0 {
fmt.Println("Exact match")
} else if match.MatchScore < 50 {
fmt.Println("Prefix match")
} else {
fmt.Println("Substring match")
}
fmt.Println()
}
},
}
var sharedRmCmd = &cobra.Command{
Use: "rm [reference-or-name]",
Aliases: []string{"revoke", "delete", "remove"},
Short: "Revoke/remove a shared file by reference or name",
Long: `Revoke a shared file using its reference hash or file name.
Can match by:
- Reference hash: zep shared rm AbC123
- File name (exact or partial): zep shared rm report.pdf
Fuzzy matching is supported for file names:
- Exact match: "report.pdf"
- Prefix match: "report"
- Substring match: "port.pdf"
If multiple files match a name, you'll be prompted to be more specific.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
query := args[0]
// First, try to find by name (name matching is more flexible)
matches, err := utils.FindSharedFilesByName(query, session)
var reference string
var displayName string
if len(matches) > 0 {
// Found by name
if len(matches) > 1 {
// Ambiguous - show options
fmt.Printf("Multiple files match '%s':\n\n", query)
for i, match := range matches {
fmt.Printf("[%d] %s (ref: %s)\n", i+1, match.FileName, match.Reference)
}
fmt.Println("\n⚠️ Please be more specific with the file name.")
return
}
// Exactly one match
reference = matches[0].Reference
displayName = matches[0].FileName
} else {
// Not found by name - try as reference directly
entry, err := utils.GetSharedFileInfo(query, session)
if err != nil {
fmt.Printf("❌ No shared file found matching '%s'\n", query)
return
}
reference = entry.Reference
displayName = entry.OriginalPath
}
// Confirm revocation
fmt.Printf("⚠️ Revoke shared file '%s'? (y/N): ", displayName)
var confirm string
fmt.Scanln(&confirm)
if confirm != "y" && confirm != "yes" {
fmt.Println("Cancelled.")
return
}
err = utils.RevokeSharedFile(reference, session)
if err != nil {
fmt.Printf("❌ Revoke failed: %v\n", err)
return
}
// Save updated session if persistent
_, statErr := os.Stat("zephyrus.conf")
if statErr == nil {
session.Save()
}
fmt.Printf("✔ Shared file '%s' revoked.\n", displayName)
},
}
var sharedInfoCmd = &cobra.Command{
Use: "info [reference]",
Short: "Show info about a shared file",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
reference := args[0]
entry, err := utils.GetSharedFileInfo(reference, session)
if err != nil {
fmt.Printf("❌ %v\n", err)
return
}
// Encode filename to base64 for share string
encodedFilename := base64.StdEncoding.EncodeToString([]byte(entry.Name))
shareString := fmt.Sprintf("%s:%s:%s:%s", session.Username, entry.Reference, entry.Password, encodedFilename)
fmt.Printf("\n📄 SHARED FILE INFO\n")
fmt.Printf("Reference: %s\n", entry.Reference)
fmt.Printf("File Name: %s\n", entry.OriginalPath)
fmt.Printf("Shared At: %s\n", entry.SharedAt.Format("2006-01-02 15:04:05"))
fmt.Printf("Password: %s\n", entry.Password)
fmt.Printf("\nShare String: %s\n", shareString)
fmt.Printf("\nWeb Share Link: https://zep.ftp.sh/shared/#%s\n\n", shareString)
},
}
sharedCmd.AddCommand(sharedLsCmd, sharedRmCmd, sharedInfoCmd)
// --- SETTINGS MANAGEMENT ---
var settingsCmd = &cobra.Command{
Use: "settings",
Short: "Manage vault settings",
}
var settingsInfoCmd = &cobra.Command{
Use: "info",
Short: "Display current vault settings",
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
fmt.Println("\n⚙️ VAULT SETTINGS")
fmt.Println("─────────────────────────────────────────")
fmt.Printf("Commit Author Name (author-name): %s\n", session.Settings.CommitAuthorName)
fmt.Printf("Commit Author Email (author-email): %s\n", session.Settings.CommitAuthorEmail)
fmt.Printf("Commit Message (commit-message): %s\n", session.Settings.CommitMessage)
fmt.Printf("File Hash Length (file-hash-length): %d characters\n", session.Settings.FileHashLength)
fmt.Printf("Share Hash Length (share-hash-length): %d characters\n", session.Settings.ShareHashLength)
fmt.Println("─────────────────────────────────────────")
},
}
var settingsSetCmd = &cobra.Command{
Use: "set [key] [value]",
Short: "Update a vault setting",
Long: "Update a setting. Keys: author-name, author-email, commit-message, file-hash-length, share-hash-length",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
key := args[0]
value := args[1]
switch key {
case "author-name":
session.Settings.CommitAuthorName = value
case "author-email":
session.Settings.CommitAuthorEmail = value
case "commit-message":
session.Settings.CommitMessage = value
case "file-hash-length":
var length int
_, err := fmt.Sscanf(value, "%d", &length)
if err != nil {
fmt.Printf("❌ Invalid number: %v\n", err)
return
}
session.Settings.FileHashLength = length
case "share-hash-length":
var length int
_, err := fmt.Sscanf(value, "%d", &length)
if err != nil {
fmt.Printf("❌ Invalid number: %v\n", err)
return
}
session.Settings.ShareHashLength = length
default:
fmt.Printf("❌ Unknown setting: %s\n", key)
fmt.Println("Available keys: author-name, author-email, commit-message, file-hash-length, share-hash-length")
return
}
// Validate the settings
if err := session.Settings.Validate(); err != nil {
fmt.Printf("❌ Invalid setting: %v\n", err)
return
}
// Save settings to remote vault
err = utils.SaveSettings(session.Username, session.Password, session.RawKey, session.Settings)
if err != nil {
fmt.Printf("❌ Failed to save settings: %v\n", err)
return
}
// Save updated session if persistent
_, statErr := os.Stat("zephyrus.conf")
if statErr == nil {
session.Save()
}
fmt.Printf("✔ Setting '%s' updated to '%v'\n", key, value)
},
}
settingsCmd.AddCommand(settingsInfoCmd, settingsSetCmd)
// --- INFO ---
var infoCmd = &cobra.Command{
Use: "info [file-path]",
Short: "Display vault or file information",
Long: `Display information about your vault or a specific file.
Without arguments: Shows vault statistics (file/folder counts, username) and settings.
With file-path: Shows detailed file information (name, storage ID, encrypted size, file key).
Examples:
zep info # Show vault statistics and settings
zep info documents/file.pdf # Show file information`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// 1. Check if the config file exists BEFORE starting
_, err := os.Stat("zephyrus.conf")
isPersistent := err == nil
session, err := getEffectiveSession()
if err != nil {
fmt.Printf("❌ Authentication failed: %v\n", err)
return
}
if len(args) == 0 {
// Show general vault information
utils.PrintVaultInfo(session)
} else {
// Show specific file information
filePath := args[0]
fileInfo, err := utils.GetFileInfo(filePath, session)
if err != nil {
fmt.Printf("❌ Failed to get file info: %v\n", err)
return
}
utils.PrintFileInfo(fileInfo)
}
// Save session if persistent
if isPersistent {
session.Save()
}
},
}
// --- SHELL ---
var shellCmd = &cobra.Command{
Use: "shell [username]",
Aliases: []string{"sh"},
Short: "Launch interactive REPL",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if len(args) > 0 {
username = args[0]
}
runInteractiveShell(rootCmd)
},
}
// --- LOCAL FILESYSTEM COMMANDS (REPL-only) ---
var locallsCmd = &cobra.Command{
Use: "localls [args...]",
Aliases: []string{"lls"},
Short: "Run 'ls' command from main terminal (REPL-only)",
Args: cobra.ArbitraryArgs,
Run: func(cmd *cobra.Command, args []string) {
if err := utils.LocalLS(args); err != nil {
fmt.Printf("Error: %v\n", err)
}
},
}
var localdirCmd = &cobra.Command{
Use: "localdir [args...]",
Aliases: []string{"ldir"},
Short: "Run 'dir' command from main terminal (REPL-only)",
Args: cobra.ArbitraryArgs,
Run: func(cmd *cobra.Command, args []string) {