mojic 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ ## Our Standards
8
+
9
+ Examples of behavior that contributes to creating a positive environment include:
10
+
11
+ * Using welcoming and inclusive language
12
+ * Being respectful of differing viewpoints and experiences
13
+ * Gracefully accepting constructive criticism
14
+ * Focusing on what is best for the community
15
+ * Showing empathy towards other community members
16
+
17
+ Examples of unacceptable behavior by participants include:
18
+
19
+ * The use of sexualized language or imagery and unwelcome sexual attention or advances
20
+ * Trolling, insulting/derogatory comments, and personal or political attacks
21
+ * Public or private harassment
22
+ * Publishing others' private information, such as a physical or electronic address, without explicit permission
23
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
24
+
25
+ ## Enforcement
26
+
27
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at **amitdutta4255@gmail.com** or **mail@amit.is-a.dev**. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident.
28
+
29
+ ## Attribution
30
+
31
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
32
+
33
+ [homepage]: http://contributor-covenant.org
34
+ [version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,39 @@
1
+ # Contributing to Emojic
2
+
3
+ First off, thanks for taking the time to contribute! 🎉
4
+
5
+ The following is a set of guidelines for contributing to Emojic. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
6
+
7
+ ## How Can I Contribute?
8
+
9
+ ### Reporting Bugs
10
+
11
+ This section guides you through submitting a bug report for Emojic. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior, and find related reports.
12
+
13
+ * **Use a clear and descriptive title** for the issue to identify the problem.
14
+ * **Describe the exact steps which reproduce the problem** in as many details as possible.
15
+ * **Provide specific examples** to demonstrate the steps.
16
+
17
+ ### Suggesting Enhancements
18
+
19
+ This section guides you through submitting an enhancement suggestion for Emojic, including completely new features and minor improvements to existing functionality.
20
+
21
+ * **Use a clear and descriptive title** for the issue to identify the suggestion.
22
+ * **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
23
+ * **Explain why this enhancement would be useful** to most Emojic users.
24
+
25
+ ## Styleguides
26
+
27
+ ### Git Commit Messages
28
+
29
+ * Use the present tense ("Add feature" not "Added feature")
30
+ * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
31
+ * Limit the first line to 72 characters or less
32
+ * Reference issues and pull requests liberally after the first line
33
+
34
+ ### Emojic Code Style
35
+
36
+ * If you are writing Emojic examples, try to make them as unreadable as possible.
37
+ * Use `😒` for `int` whenever possible.
38
+
39
+ Happy Hacking! 🚀
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # Emojic 🤯
2
+
3
+ > A chaotic, emoji-based C transpiler and IDE. Write C code using emojis, compile it, or transform normal C into a cursed emoji nightmare.
4
+
5
+
6
+ ## What is this?
7
+
8
+ **Emojic** is a dangerous experiment in compiler theory. It allows you to write valid C code using emojis as preprocessor definitions. It comes with a full-stack **Emojic Studio** IDE that lets you:
9
+
10
+ 1. **Compile Emojic to C**: Turn `😒 😊😂🤣👌` into `int main()`.
11
+ 2. **Transform C to Emojic**: Turn your clean code into an unreadable emoji mess.
12
+ 3. **Run in Cloud**: Execute your cursed code instantly via the `compiler.amit.is-a.dev` backend.
13
+
14
+ ## 🚀 Features
15
+
16
+ - **Dynamic Token Analysis**: Automatically detects keywords in your C code.
17
+ - **Custom Mapping**: Choose which emojis represent `int`, `return`, or `;`.
18
+ - **Live Terminal**: Real-time output streaming via WebSockets.
19
+ - **Dark Mode IDE**: A VS Code-like experience in the browser.
20
+
21
+ ## 🛠️ Installation & Deployment
22
+
23
+ This project is designed to be deployed on **Vercel** (Frontend + API).
24
+
25
+ 1. **Clone the repo**
26
+ ```bash
27
+ git clone [https://github.com/notamitgamer/](https://github.com/notamitgamer/)emojic.git
28
+ cd emojic
29
+ ```
30
+
31
+ 2. **Install Backend Dependencies**
32
+ ```bash
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ 3. **Run Locally**
37
+ ```bash
38
+ python api/index.py
39
+ # Open index.html in your browser
40
+ ```
41
+
42
+ ## 😒 Example Code
43
+
44
+ ```c
45
+ /* The Hello World of Emojic */
46
+ #include<stdio.h>
47
+
48
+ #define 😒 int
49
+ #define 😊 main
50
+ #define 😂 (
51
+ #define 🤣 )
52
+ #define ❤️ printf
53
+ #define 😍 ;
54
+ #define 🙌 return
55
+ #define 👌 {
56
+ #define 😘 }
57
+
58
+ 😒 😊😂🤣👌
59
+ ❤️😂"Hello World!\n"🤣😍
60
+ 🙌 0😍
61
+ 😘
62
+ ```
63
+
64
+ ## 🤝 Contributing
65
+
66
+ We welcome chaos! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.
67
+
68
+ ## 📄 License
69
+
70
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
package/SECURITY.md ADDED
@@ -0,0 +1,9 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ We take security seriously, even if this project is a joke.
6
+
7
+ If you discover a security vulnerability within Emojic, please send an e-mail to **amitdutta4255@gmail.com**. All security vulnerabilities will be promptly addressed.
8
+
9
+ **Please do not open public issues for security vulnerabilities.**
package/bin/mojic.js ADDED
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from 'commander';
4
+ import inquirer from 'inquirer';
5
+ import chalk from 'chalk';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { Transform } from 'stream';
9
+ import { StringDecoder } from 'string_decoder';
10
+ import { CipherEngine } from '../lib/CipherEngine.js';
11
+
12
+ program
13
+ .name('mojic')
14
+ .description('Obfuscate C source code into emojis')
15
+ .version('1.0.0')
16
+ .addHelpCommand('help [command]', 'Display help for command')
17
+ .showHelpAfterError();
18
+
19
+ // --- Helpers ---
20
+
21
+ const promptPassword = async (msg) => {
22
+ const { password } = await inquirer.prompt([{
23
+ type: 'password', name: 'password', message: msg, mask: '*',
24
+ validate: (input) => input.length > 5 || 'Password must be > 5 chars.'
25
+ }]);
26
+ return password;
27
+ };
28
+
29
+ const getStreamHeader = async (filePath) => {
30
+ const fileStream = fs.createReadStream(filePath, { highWaterMark: 1024 });
31
+ const decoder = new StringDecoder('utf8');
32
+
33
+ return new Promise((resolve, reject) => {
34
+ let buffer = '';
35
+ let found = false;
36
+
37
+ fileStream.on('data', (chunk) => {
38
+ if (found) return;
39
+ buffer += decoder.write(chunk);
40
+ const newlineIndex = buffer.indexOf('\n');
41
+ if (newlineIndex !== -1) {
42
+ found = true;
43
+ fileStream.destroy();
44
+ resolve(buffer.substring(0, newlineIndex));
45
+ }
46
+ });
47
+
48
+ fileStream.on('end', () => {
49
+ if (!found) resolve(buffer + decoder.end());
50
+ });
51
+ fileStream.on('error', reject);
52
+ });
53
+ };
54
+
55
+ const createHeaderSkipper = () => {
56
+ const decoder = new StringDecoder('utf8');
57
+ let isHeaderSkipped = false;
58
+ let buffer = '';
59
+
60
+ return new Transform({
61
+ transform(chunk, encoding, cb) {
62
+ if (isHeaderSkipped) {
63
+ this.push(chunk);
64
+ return cb();
65
+ }
66
+
67
+ buffer += decoder.write(chunk);
68
+ const nlIndex = buffer.indexOf('\n');
69
+
70
+ if (nlIndex !== -1) {
71
+ const remainder = buffer.substring(nlIndex + 1);
72
+ this.push(remainder);
73
+ isHeaderSkipped = true;
74
+ buffer = '';
75
+ }
76
+ cb();
77
+ }
78
+ });
79
+ };
80
+
81
+ // --- Recursive Logic ---
82
+
83
+ async function traverseDirectory(currentPath, extension, callback) {
84
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
85
+
86
+ for (const entry of entries) {
87
+ const fullPath = path.join(currentPath, entry.name);
88
+ if (entry.isDirectory()) {
89
+ await traverseDirectory(fullPath, extension, callback);
90
+ } else if (entry.isFile() && entry.name.endsWith(extension)) {
91
+ await callback(fullPath);
92
+ }
93
+ }
94
+ }
95
+
96
+ // --- Main Commands ---
97
+
98
+ program
99
+ .command('encode')
100
+ .argument('<path>', 'File or Directory to encode')
101
+ .option('-r, --recursive', 'Recursively encrypt all .c files in directory')
102
+ .description('Encrypt a file or directory into emojis')
103
+ .action(async (targetPath, options) => {
104
+ try {
105
+ if (!fs.existsSync(targetPath)) throw new Error('Path not found');
106
+ const stats = fs.statSync(targetPath);
107
+
108
+ // Validation
109
+ if (stats.isDirectory() && !options.recursive) {
110
+ throw new Error(`'${targetPath}' is a directory. Use -r to process recursively.`);
111
+ }
112
+
113
+ console.log(chalk.blue('🔒 Initiating Mojic Encryption...'));
114
+ const password = await promptPassword('Create password for file(s):');
115
+
116
+ const processFile = async (filePath) => {
117
+ const outputName = filePath.replace(/\.c$/, '') + '.mojic';
118
+ console.log(chalk.dim(` Processing: ${path.basename(filePath)} -> ${path.basename(outputName)}`));
119
+
120
+ const engine = new CipherEngine(password);
121
+ await engine.init(); // Unique salt per file
122
+
123
+ const readStream = fs.createReadStream(filePath);
124
+ const writeStream = fs.createWriteStream(outputName);
125
+
126
+ writeStream.write(engine._encodeHeader());
127
+
128
+ await new Promise((resolve, reject) => {
129
+ readStream
130
+ .pipe(engine.getEncryptStream())
131
+ .pipe(writeStream)
132
+ .on('finish', resolve)
133
+ .on('error', reject);
134
+ });
135
+ };
136
+
137
+ if (stats.isDirectory()) {
138
+ console.log(chalk.blue(`📂 Scanning directory: ${targetPath}`));
139
+ await traverseDirectory(targetPath, '.c', processFile);
140
+ console.log(chalk.green('✅ Batch encryption complete.'));
141
+ } else {
142
+ await processFile(targetPath);
143
+ console.log(chalk.green(`✅ Encrypted.`));
144
+ }
145
+
146
+ } catch (err) {
147
+ console.error(chalk.red('Error:'), err.message);
148
+ }
149
+ });
150
+
151
+ program
152
+ .command('decode')
153
+ .argument('<path>', 'File or Directory to decode')
154
+ .option('-r, --recursive', 'Recursively decode all .mojic files')
155
+ .description('Restore mojic files to C source code')
156
+ .action(async (targetPath, options) => {
157
+ try {
158
+ if (!fs.existsSync(targetPath)) throw new Error('Path not found');
159
+ const stats = fs.statSync(targetPath);
160
+
161
+ if (stats.isDirectory() && !options.recursive) {
162
+ throw new Error(`'${targetPath}' is a directory. Use -r to process recursively.`);
163
+ }
164
+
165
+ console.log(chalk.blue('🔓 Initiating Decryption...'));
166
+ const password = await promptPassword('Enter password:'); // Assume same pass for dir
167
+
168
+ const processFile = async (filePath) => {
169
+ try {
170
+ const outputName = filePath.replace(/\.mojic$/, '') + '.restored.c';
171
+ console.log(chalk.dim(` Restoring: ${path.basename(filePath)}`));
172
+
173
+ const headerStr = await getStreamHeader(filePath);
174
+ const metadata = CipherEngine.decodeHeader(headerStr);
175
+
176
+ const engine = new CipherEngine(password);
177
+ await engine.init(metadata.saltHex);
178
+
179
+ if (engine.authHash.toString('hex') !== metadata.authHex) {
180
+ console.log(chalk.red(` ❌ Skipped ${path.basename(filePath)}: Incorrect Password`));
181
+ return;
182
+ }
183
+
184
+ const readStream = fs.createReadStream(filePath);
185
+ const writeStream = fs.createWriteStream(outputName);
186
+
187
+ await new Promise((resolve, reject) => {
188
+ readStream
189
+ .pipe(createHeaderSkipper())
190
+ .pipe(engine.getDecryptStream())
191
+ .pipe(writeStream)
192
+ .on('finish', resolve)
193
+ .on('error', reject);
194
+ });
195
+ } catch (e) {
196
+ console.log(chalk.red(` ⚠️ Error processing ${path.basename(filePath)}: ${e.message}`));
197
+ }
198
+ };
199
+
200
+ if (stats.isDirectory()) {
201
+ console.log(chalk.blue(`📂 Scanning directory: ${targetPath}`));
202
+ await traverseDirectory(targetPath, '.mojic', processFile);
203
+ console.log(chalk.green('✅ Batch decryption complete.'));
204
+ } else {
205
+ await processFile(targetPath);
206
+ console.log(chalk.green(`✅ Restored.`));
207
+ }
208
+
209
+ } catch (err) {
210
+ console.error(chalk.red('Error:'), err.message);
211
+ }
212
+ });
213
+
214
+ // --- Security Rotation Tools (SRT) ---
215
+
216
+ const rotatePassword = async (file) => {
217
+ try {
218
+ if (!fs.existsSync(file)) throw new Error('File not found');
219
+ console.log(chalk.yellow(`🔄 Rotating Password for ${path.basename(file)}...`));
220
+
221
+ // 1. Authenticate Old
222
+ const headerStr = await getStreamHeader(file);
223
+ const metadata = CipherEngine.decodeHeader(headerStr);
224
+ const oldPass = await promptPassword('Enter CURRENT password:');
225
+
226
+ const oldEngine = new CipherEngine(oldPass);
227
+ await oldEngine.init(metadata.saltHex);
228
+
229
+ if (oldEngine.authHash.toString('hex') !== metadata.authHex) {
230
+ console.error(chalk.red('❌ Incorrect Current Password'));
231
+ process.exit(1);
232
+ }
233
+
234
+ // 2. Init New
235
+ const newPass = await promptPassword('Enter NEW password:');
236
+ const newEngine = new CipherEngine(newPass);
237
+ await newEngine.init();
238
+
239
+ // 3. Process
240
+ const tempFile = file + '.tmp';
241
+ const readStream = fs.createReadStream(file);
242
+ const writeStream = fs.createWriteStream(tempFile);
243
+
244
+ writeStream.write(newEngine._encodeHeader());
245
+
246
+ await new Promise((resolve, reject) => {
247
+ readStream
248
+ .pipe(createHeaderSkipper())
249
+ .pipe(oldEngine.getDecryptStream())
250
+ .pipe(newEngine.getEncryptStream())
251
+ .pipe(writeStream)
252
+ .on('finish', resolve)
253
+ .on('error', reject);
254
+ });
255
+
256
+ fs.renameSync(tempFile, file);
257
+ console.log(chalk.green(`✅ Password updated.`));
258
+
259
+ } catch (err) {
260
+ console.error(chalk.red('Error:'), err.message);
261
+ }
262
+ };
263
+
264
+ const reEncrypt = async (file) => {
265
+ try {
266
+ if (!fs.existsSync(file)) throw new Error('File not found');
267
+ console.log(chalk.yellow(`🎲 Re-shuffling Entropy for ${path.basename(file)}...`));
268
+
269
+ // 1. Authenticate
270
+ const headerStr = await getStreamHeader(file);
271
+ const metadata = CipherEngine.decodeHeader(headerStr);
272
+ const password = await promptPassword('Enter password:');
273
+
274
+ const oldEngine = new CipherEngine(password);
275
+ await oldEngine.init(metadata.saltHex);
276
+
277
+ if (oldEngine.authHash.toString('hex') !== metadata.authHex) {
278
+ console.error(chalk.red('❌ Incorrect Password'));
279
+ process.exit(1);
280
+ }
281
+
282
+ // 2. Init New
283
+ const newEngine = new CipherEngine(password);
284
+ await newEngine.init();
285
+
286
+ // 3. Process
287
+ const tempFile = file + '.tmp';
288
+ const readStream = fs.createReadStream(file);
289
+ const writeStream = fs.createWriteStream(tempFile);
290
+
291
+ writeStream.write(newEngine._encodeHeader());
292
+
293
+ await new Promise((resolve, reject) => {
294
+ readStream
295
+ .pipe(createHeaderSkipper())
296
+ .pipe(oldEngine.getDecryptStream())
297
+ .pipe(newEngine.getEncryptStream())
298
+ .pipe(writeStream)
299
+ .on('finish', resolve)
300
+ .on('error', reject);
301
+ });
302
+
303
+ fs.renameSync(tempFile, file);
304
+ console.log(chalk.green(`✅ File re-encrypted.`));
305
+
306
+ } catch (err) {
307
+ console.error(chalk.red('Error:'), err.message);
308
+ }
309
+ };
310
+
311
+ program
312
+ .command('srt')
313
+ .description('Security and Rotation Tools')
314
+ .option('--pass <file>', 'Update the password for an existing file')
315
+ .option('--re <file>', 'Re-encrypt with new random seed (Same password)')
316
+ .addHelpText('after', `
317
+ Examples:
318
+ $ mojic srt --pass secret.mojic # Change the password of an encrypted file
319
+ $ mojic srt --re secret.mojic # Re-scramble the emojis (new salt) with same password
320
+ `)
321
+ .action(async (options) => {
322
+ if (options.pass) {
323
+ await rotatePassword(options.pass);
324
+ } else if (options.re) {
325
+ await reEncrypt(options.re);
326
+ } else {
327
+ console.log(chalk.yellow('Please specify an option: --pass <file> or --re <file>'));
328
+ program.commands.find(c => c.name() === 'srt').help();
329
+ }
330
+ });
331
+
332
+ program.addHelpText('after', `
333
+ Usage Examples:
334
+ $ mojic encode test.c # Encrypt a single C file
335
+ $ mojic encode ./src -r # Recursively encrypt all .c files in ./src
336
+ $ mojic decode test.mojic # Decrypt a single file
337
+ $ mojic decode ./src -r # Recursively decrypt all .mojic files
338
+ `);
339
+
340
+ program.parse(process.argv);
@@ -0,0 +1,253 @@
1
+ import crypto from 'crypto';
2
+ import { Transform } from 'stream';
3
+ import { StringDecoder } from 'string_decoder';
4
+
5
+ /**
6
+ * Emojic CipherEngine
7
+ * Handles the logic for mapping C-code to Emojis based on a password seed.
8
+ * * * Updates:
9
+ * - Uses Intl.Segmenter for robust Emoji/Grapheme decoding.
10
+ * - Implements 'tail buffering' in streams to prevent splitting multi-codepoint emojis.
11
+ */
12
+
13
+ const HEADER_ALPHABET = ['🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘', '🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗'];
14
+
15
+ const EMOJI_UNIVERSE = [
16
+ '😀','😃','😄','😁','😆','😅','🤣','😂','🙂','🙃','😉','😊','😇','🥰','😍','🤩',
17
+ '😘','😗','☺️','😚','😙','🥲','😋','😛','😜','🤪','😝','🤑','🤗','🤭','🤫','🤔',
18
+ '🤐','🤨','😐','😑','😶','😏','😒','🙄','😬','🤥','😌','😔','😪','🤤','😴','😷',
19
+ '🤒','🤕','🤢','🤮','🤧','🥵','🥶','🥴','😵','🤯','🤠','🥳','😎','🤓','🧐','😕',
20
+ '😟','🙁','☹️','😮','😯','😲','😳','🥺','😦','😧','😨','😰','😥','😢','😭','😱',
21
+ '😖','😣','😞','😓','😩','😫','🥱','😤','😡','😠','🤬','😈','👿','💀','☠️','💩',
22
+ '🤡','👹','👺','👻','👽','👾','🤖','😺','😸','😹','😻','😼','😽','🙀','😿','😾',
23
+ '🙈','🙉','🙊','💋','💌','💘','💝','💖','💗','💓','💞','💕','💟','❣️','💔','❤️',
24
+ '🧡','💛','💚','💙','💜','🤎','🖤','🤍','💯','💢','💥','💫','💦','💨','🕳️','💣',
25
+ '💬','👁️','💭','💤','👋','🤚','🖐️','✋','🖖','👌','🤏','✌️','🤞','🤟','🤘',
26
+ '🤙','👈','👉','👆','🖕','👇','☝️','👍','👎','✊','👊','🤛','🤜','👏','🙌','👐',
27
+ '🤲','🤝','🙏','✍️','💅','🤳','💪','🦾','🦿','🦵','🦶','👂','🦻','👃','🧠','🫀',
28
+ '🫁','🦷','🦴','👀','👅','👄','👶','🧒','👦','👧','🧑','👱','👨','🧔','👨‍🦰','👨‍🦱',
29
+ '🔥','🌈','☀️','⛈️','🌩️','❄️','🌵','🌷','🌲','🌳','🌴','🐲','🐉','🦕','🦖','🐍',
30
+ '🐎','🦄','🦓','🐆','🐅','🐂','🐄','🐖','🐏','🐑','🐐','🐪','🐫','🦙','🦒','🐘',
31
+ '🦏','🦛','🐁','🐀','🐹','🐰','🐇','🐿️','🦔','🦇','🐻','🐨','🐼','🦥','🦦','🦨',
32
+ '🦘','🦡','🐾','🦃','🐔','🐓','🐣','🐤','🐥','🐦','🐧','🕊️','🦅','🦆','🦢','🦉',
33
+ '🎈','🧨','🧧','🎀','🎁','🎗️','🎟️','🎫','🎖️','🏆','🏅','🥇','🥈','🥉','⚽','⚾',
34
+ '🥎','🏀','🏐','🏈','🏉','🎾','🥏','🎳','🏏','🏑','🏒','🥍','🏓','🏸','🥊','🥋',
35
+ '🥅','⛳','⛸️','🎣','🤿','🎽','🎿','🛷','🥌','🎯','🪀','🪁','🎱','🔮','🧿','🎮'
36
+ ];
37
+
38
+ const C_KEYWORDS = [
39
+ 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
40
+ 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
41
+ 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
42
+ 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while',
43
+ 'include', 'define', 'main', 'printf', 'NULL'
44
+ ];
45
+
46
+ const ASCII_CHARS = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32))
47
+ .concat(['\n', '\t', '\r']);
48
+
49
+ const TOTAL_TOKENS = C_KEYWORDS.length + ASCII_CHARS.length;
50
+
51
+ export class CipherEngine {
52
+ constructor(password) {
53
+ this.password = password;
54
+ this.tokenMap = new Map();
55
+ this.reverseMap = new Map();
56
+ this.isReady = false;
57
+
58
+ if (EMOJI_UNIVERSE.length < TOTAL_TOKENS) {
59
+ throw new Error(`CRITICAL: Not enough emojis. Need ${TOTAL_TOKENS}, have ${EMOJI_UNIVERSE.length}`);
60
+ }
61
+ }
62
+
63
+ async init(existingSaltHex = null) {
64
+ this.salt = existingSaltHex
65
+ ? Buffer.from(existingSaltHex, 'hex')
66
+ : crypto.randomBytes(16);
67
+
68
+ const derivedKey = await new Promise((resolve, reject) => {
69
+ crypto.pbkdf2(this.password, this.salt, 100000, 36, 'sha256', (err, key) => {
70
+ if (err) reject(err); else resolve(key);
71
+ });
72
+ });
73
+
74
+ const seedBuffer = derivedKey.subarray(0, 4);
75
+ this.authHash = derivedKey.subarray(4);
76
+ const seedInt = seedBuffer.readUInt32BE(0);
77
+
78
+ const shuffledEmojis = this._shuffleArray([...EMOJI_UNIVERSE], seedInt);
79
+
80
+ let emojiIndex = 0;
81
+ for (const keyword of C_KEYWORDS) {
82
+ const emo = shuffledEmojis[emojiIndex++];
83
+ this.tokenMap.set(keyword, emo);
84
+ this.reverseMap.set(emo, keyword);
85
+ }
86
+
87
+ for (const char of ASCII_CHARS) {
88
+ const emo = shuffledEmojis[emojiIndex++];
89
+ this.tokenMap.set(char, emo);
90
+ this.reverseMap.set(emo, char);
91
+ }
92
+
93
+ this.isReady = true;
94
+ }
95
+
96
+ _mulberry32(a) {
97
+ return function() {
98
+ var t = a += 0x6D2B79F5;
99
+ t = Math.imul(t ^ t >>> 15, t | 1);
100
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
101
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
102
+ }
103
+ }
104
+
105
+ _shuffleArray(array, seed) {
106
+ const rng = this._mulberry32(seed);
107
+ for (let i = array.length - 1; i > 0; i--) {
108
+ const j = Math.floor(rng() * (i + 1));
109
+ [array[i], array[j]] = [array[j], array[i]];
110
+ }
111
+ return array;
112
+ }
113
+
114
+ _encodeHeader() {
115
+ const saltHex = this.salt.toString('hex');
116
+ const authHex = this.authHash.toString('hex');
117
+ const fullHexString = saltHex + authHex;
118
+
119
+ let headerStr = '';
120
+ for (const char of fullHexString) {
121
+ const val = parseInt(char, 16);
122
+ headerStr += HEADER_ALPHABET[val];
123
+ }
124
+ return headerStr + '\n';
125
+ }
126
+
127
+ static decodeHeader(headerStr) {
128
+ let hexString = '';
129
+ // Use segmenter here just in case moon emojis have variation selectors
130
+ const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
131
+ const segments = segmenter.segment(headerStr.trim());
132
+
133
+ for (const { segment } of segments) {
134
+ const index = HEADER_ALPHABET.indexOf(segment);
135
+ if (index === -1) throw new Error("Invalid Header format.");
136
+ hexString += index.toString(16);
137
+ }
138
+ const saltHex = hexString.substring(0, 32);
139
+ const authHex = hexString.substring(32);
140
+ return { saltHex, authHex };
141
+ }
142
+
143
+ getEncryptStream() {
144
+ if (!this.isReady) throw new Error("Engine not initialized");
145
+ const engine = this;
146
+ const decoder = new StringDecoder('utf8');
147
+ let buffer = '';
148
+
149
+ return new Transform({
150
+ transform(chunk, encoding, callback) {
151
+ buffer += decoder.write(chunk);
152
+
153
+ const sortedKeywords = [...C_KEYWORDS].sort((a, b) => b.length - a.length);
154
+ const keywordPattern = sortedKeywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
155
+ const regex = new RegExp(`\\b(${keywordPattern})\\b|([\\s\\S])`, 'g');
156
+
157
+ let match;
158
+ let output = '';
159
+
160
+ while ((match = regex.exec(buffer)) !== null) {
161
+ const token = match[0];
162
+ if (engine.tokenMap.has(token)) {
163
+ output += engine.tokenMap.get(token);
164
+ } else {
165
+ output += token;
166
+ }
167
+ }
168
+
169
+ buffer = '';
170
+ this.push(output);
171
+ callback();
172
+ },
173
+ flush(callback) {
174
+ buffer += decoder.end();
175
+ // Simple flush for MVP; in prod, we'd regex one last time.
176
+ callback();
177
+ }
178
+ });
179
+ }
180
+
181
+ getDecryptStream() {
182
+ if (!this.isReady) throw new Error("Engine not initialized");
183
+ const engine = this;
184
+ const decoder = new StringDecoder('utf8');
185
+ const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
186
+
187
+ let buffer = '';
188
+
189
+ return new Transform({
190
+ transform(chunk, encoding, callback) {
191
+ // 1. Decode bytes to string (handles partial UTF8 bytes)
192
+ buffer += decoder.write(chunk);
193
+
194
+ // 2. Segment into Graphemes (Emojis)
195
+ const segments = [...segmenter.segment(buffer)];
196
+
197
+ // 3. Process all BUT the last segment
198
+ // We keep the last segment in the buffer because it might be
199
+ // the start of a multi-codepoint emoji that was split by the chunk boundary.
200
+ // (e.g. Base char is here, Variation Selector is in next chunk)
201
+
202
+ const processUntilIndex = segments.length > 1 ? segments.length - 1 : 0;
203
+ let output = '';
204
+ let processedString = '';
205
+
206
+ // If we only have 1 segment, we can't be sure it's complete, wait for next chunk
207
+ // UNLESS the buffer is getting huge, then force it.
208
+ if (segments.length === 1 && buffer.length < 100) {
209
+ // Wait for more data
210
+ callback();
211
+ return;
212
+ }
213
+
214
+ // Process safe segments
215
+ for (let i = 0; i < processUntilIndex; i++) {
216
+ const char = segments[i].segment;
217
+ processedString += char;
218
+
219
+ if (engine.reverseMap.has(char)) {
220
+ output += engine.reverseMap.get(char);
221
+ } else {
222
+ output += char;
223
+ }
224
+ }
225
+
226
+ // Update buffer to only contain the remaining tail
227
+ // Note: buffer might contain bytes not yet in segments if StringDecoder held them?
228
+ // No, decoder.write returns what is available.
229
+ // We just need to remove the processed part from the buffer string.
230
+ if (processUntilIndex > 0) {
231
+ buffer = buffer.slice(processedString.length);
232
+ this.push(output);
233
+ }
234
+
235
+ callback();
236
+ },
237
+ flush(callback) {
238
+ // Process any remaining tail (buffer + decoder leftovers)
239
+ buffer += decoder.end();
240
+ if (buffer) {
241
+ const segments = segmenter.segment(buffer);
242
+ let output = '';
243
+ for (const { segment } of segments) {
244
+ if (engine.reverseMap.has(segment)) output += engine.reverseMap.get(segment);
245
+ else output += segment;
246
+ }
247
+ this.push(output);
248
+ }
249
+ callback();
250
+ }
251
+ });
252
+ }
253
+ }
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "mojic",
3
+ "version": "1.0.0",
4
+ "description": "Obfuscate C source code into emojis using password-seeded mapping",
5
+ "main": "bin/mojic.js",
6
+ "bin": {
7
+ "mojic": "bin/mojic.js"
8
+ },
9
+ "type": "module",
10
+ "scripts": {
11
+ "start": "node bin/mojic.js"
12
+ },
13
+ "dependencies": {
14
+ "chalk": "^5.3.0",
15
+ "commander": "^11.1.0",
16
+ "inquirer": "^9.2.12"
17
+ },
18
+ "engines": {
19
+ "node": ">=18.0.0"
20
+ },
21
+ "keywords": [
22
+ "cli",
23
+ "encryption",
24
+ "emoji",
25
+ "obfuscation",
26
+ "c",
27
+ "security"
28
+ ],
29
+ "author": "",
30
+ "license": "Apache-2.0"
31
+ }