Skip to content

Commit

Permalink
Fix scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
mrruby committed Mar 13, 2024
1 parent 7defa9b commit efda5b5
Show file tree
Hide file tree
Showing 26 changed files with 548 additions and 296 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fs.readFile(manifestPath, 'utf8', (err, data) => {
const updatedManifest = {
...manifest,
background: {
scripts: ['holo-key-manager-extension/scripts/background.js'],
scripts: ['scripts/background.js'],
type: 'module'
},
browser_specific_settings: {
Expand Down
13 changes: 5 additions & 8 deletions holo-key-manager-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
"version": "0.0.3",
"private": true,
"scripts": {
"build": "pnpm build:vite && pnpm build:script && pnpm build:removeExport && pnpm build:removeInline",
"buildDev": "pnpm build:vite && pnpm build:script && pnpm build:removeExport && pnpm build:removeInline && pnpm build:buildForFirefoxDev",
"build": "pnpm build:vite && pnpm build:script && pnpm build:removeInline",
"buildDev": "pnpm build:vite && pnpm build:script && pnpm build:removeInline && pnpm build:buildForFirefoxDev",
"build:vite": "vite build",
"build:script": "tsc --p scripts/tsconfig.json",
"build:removeExport": "node build-scripts/removeExportFromScript.cjs",
"build:script": "cd scripts && pnpm build && cd ..",
"build:removeInline": "node build-scripts/removeInlineScript.cjs",
"build:replaceForFirefox": "node build-scripts/replaceForFirefox.cjs",
"build:buildForFirefoxDev": "node build-scripts/devFirefox.cjs",
Expand All @@ -16,10 +15,9 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.1",
"@sveltejs/adapter-static": "^3.0.1",
"@sveltejs/kit": "2.0.2",
"@sveltejs/vite-plugin-svelte": "^3.0.2",
"@types/chrome": "^0.0.254",
"@types/file-saver": "^2.0.7",
"archiver": "^7.0.1",
"autoprefixer": "^10.4.18",
Expand All @@ -41,7 +39,6 @@
"jszip": "^3.10.1",
"svelte": "^4.2.12",
"tailwindcss": "^3.4.1",
"tiny-glob": "^0.2.9",
"zod": "^3.22.4"
"tiny-glob": "^0.2.9"
}
}
72 changes: 35 additions & 37 deletions holo-key-manager-extension/scripts/background.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import type { Message } from '@sharedTypes';
import { SENDER_EXTENSION } from '@sharedConst';
import { type ActionPayload, type Message, MessageWithIdSchema } from '@sharedTypes';

let windowId: number | undefined;

const handleError = (error: string, sendResponse: (response?: Message) => void) => {
type SendResponse = (response?: Message) => void;
type SendResponseWithSender = (response: ActionPayload) => void;

const handleError = (error: string, sendResponse: SendResponseWithSender) => {
console.error(error);
windowId = undefined;
sendResponse({ action: 'GenericError' });
};

const handleSuccess = (sendResponse: (response?: Message) => void, payload?: string) => {
sendResponse(payload ? { action: 'SuccessWithPayload', payload } : { action: 'Success' });
};

const focusWindow = (sendResponse: (response?: Message) => void) => {
if (typeof windowId !== 'number') return handleError('Window ID is not a number', sendResponse);
chrome.windows.update(windowId, { focused: true }, () => {
chrome.runtime.lastError
? handleError('Error focusing window: ' + chrome.runtime.lastError.message, sendResponse)
: handleSuccess(sendResponse);
});
const createAndFocusWindow = async (sendResponse: SendResponseWithSender) => {
if (typeof windowId === 'number') {
chrome.windows.update(windowId, { focused: true }, () => {
if (chrome.runtime.lastError) {
handleError('Error focusing window: ' + chrome.runtime.lastError.message, sendResponse);
} else {
sendResponse({ action: 'Success' });
}
});
return true;
}
return false;
};

const createWindow = () => {
Expand All @@ -41,32 +46,25 @@ const createWindow = () => {
);
};

const signInHandler = async (sendResponse: (response?: Message) => void) => {
if (windowId !== undefined) {
focusWindow(sendResponse);
return;
}
const handleSignIn = async (sendResponse: SendResponseWithSender) => {
if (await createAndFocusWindow(sendResponse)) return;
createWindow();
sendResponse({ action: 'Success' });
};

chrome.runtime.onMessage.addListener((message: Message, sender, sendResponse: SendResponse) => {
const sendResponseWithSender = (response: ActionPayload) =>
sendResponse({ ...response, sender: SENDER_EXTENSION });

const parsedMessage = MessageWithIdSchema.safeParse(message);
if (!parsedMessage.success || parsedMessage.data.action !== 'SignIn') return;
try {
createWindow();
// const deviceKey = await storageService.getWithoutCallback({ key: DEVICE_KEY, area: 'local' });
// if (typeof deviceKey === 'string') {
// handleSuccess(sendResponse, deviceKey);
// } else {
// handleError('Device key is not a string', sendResponse);
// }
chrome.storage.local.get(['deviceKey'], (result) => {
handleSuccess(sendResponse, result.deviceKey);
});
handleSignIn(sendResponseWithSender);
} catch (error) {
handleError(
'Error creating window: ' + (error instanceof Error ? error.message : String(error)),
sendResponse
'Error processing sign in: ' + (error instanceof Error ? error.message : String(error)),
sendResponseWithSender
);
}
};

chrome.runtime.onMessage.addListener(
(message: Message, sender, sendResponse: (response?: Message) => void) => {
if (message.action === 'SignIn') signInHandler(sendResponse);
}
);
return true;
});
25 changes: 16 additions & 9 deletions holo-key-manager-extension/scripts/content.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import type { Message } from '@sharedTypes';
import { responseToMessage, sendMessage } from '@sharedServices';
import { MessageSchema, MessageWithIdSchema } from '@sharedTypes';

console.log('Content script loaded');
const isMessageFromSelf = (event: MessageEvent) => event.source === window;
const isSignInAction = (data: Message) => data.action === 'SignIn';

window.addEventListener('message', async (event: MessageEvent) => {
const parseAndHandleMessage = async (event: MessageEvent) => {
if (!isMessageFromSelf(event)) return;
if (isSignInAction(event.data)) {
const response = await chrome.runtime.sendMessage(event.data);
window.postMessage({ ...response, id: event.data.id }, '*');
const parsedResult = MessageWithIdSchema.safeParse(event.data);
if (!parsedResult.success || parsedResult.data.action !== 'SignIn') return;

try {
const response = await sendMessage(parsedResult.data);
const parsedMessageSchema = MessageSchema.safeParse(response);
if (!parsedMessageSchema.success) throw new Error('Invalid response format');
window.postMessage(responseToMessage(parsedMessageSchema.data, parsedResult.data.id), '*');
} catch (error) {
console.error(error);
}
});
};

window.addEventListener('message', parseAndHandleMessage);
9 changes: 9 additions & 0 deletions holo-key-manager-extension/scripts/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "holo-key-manager-extension-scripts",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "rollup -c"
}
}
17 changes: 17 additions & 0 deletions holo-key-manager-extension/scripts/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import resolve from '@rollup/plugin-node-resolve';
import tscAlias from 'rollup-plugin-tsc-alias';
import typescript from 'rollup-plugin-typescript2';

const createConfig = (input, file) => ({
input,
output: {
file,
format: 'esm'
},
plugins: [tscAlias(), typescript(), resolve()]
});

export default [
createConfig('background.ts', '../build/scripts/background.js'),
createConfig('content.ts', '../build/scripts/content.js')
];
6 changes: 1 addition & 5 deletions holo-key-manager-extension/scripts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../build",
"paths": {
"@sharedTypes": ["../../shared/types"],
"@sharedTypes/*": ["../../shared/types/*"]
}
"outDir": "../build"
},
"include": ["background.ts", "content.ts"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export function createApplicationKeyMutation() {
console.log(decryptedKey);

const app_key_1 = decryptedKey.derive(0);

console.log(app_key_1);

return decryptedKey.zero();
Expand Down
12 changes: 5 additions & 7 deletions holo-key-manager-extension/static/manifest.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
{
"name": "Holo key manager",
"description": "A browser extension to manage holo keys",
"version": "0.0.35",
"version": "0.0.36",
"manifest_version": 3,
"action": {
"default_title": "Holo key manager",
"default_icon": "favicon.png",
"default_popup": "index.html"
},
"content_security_policy": {
"extension_pages": "default-src 'self' 'wasm-unsafe-eval'"
"extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'"
},
"background": {
"service_worker": "holo-key-manager-extension/scripts/background.js",
"service_worker": "scripts/background.js",
"type": "module"
},
"permissions": ["activeTab", "storage", "tabs", "nativeMessaging"],
"externally_connectable": {
"matches": ["*://localhost/*"]
},
"host_permissions": ["<all_urls>"],
"content_scripts": [
{
"matches": ["*://localhost/*"],
"js": ["holo-key-manager-extension/scripts/content.js"]
"js": ["scripts/content.js"]
}
]
}
6 changes: 3 additions & 3 deletions holo-key-manager-js-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
"name": "holo-key-manager-js-client",
"version": "1.0.0",
"description": "A JavaScript client API for managing Holo keys",
"main": "lib/holo-key-manager-js-client/src/index.js",
"main": "lib/index.js",
"types": "lib/holo-key-manager-js-client/src/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"buildPack": "tsc && npm pack"
"buildPack": "rollup -c && npm pack"
},
"keywords": [
"holo",
Expand All @@ -19,7 +20,6 @@
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"uid": "^2.0.2",
"zod": "^3.22.4"
},
"type": "module",
Expand Down
14 changes: 14 additions & 0 deletions holo-key-manager-js-client/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import resolve from '@rollup/plugin-node-resolve';
import tscAlias from 'rollup-plugin-tsc-alias';
import typescript from 'rollup-plugin-typescript2';

export default [
{
input: 'src/index.ts',
output: {
file: 'lib/index.js',
format: 'esm'
},
plugins: [typescript(), resolve(), tscAlias()]
}
];
43 changes: 20 additions & 23 deletions holo-key-manager-js-client/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
import { type Message, MessageWithIdSchema } from '@sharedTypes';
import { uid } from 'uid';
import { SENDER_WEBAPP } from '@sharedConst';
import { createMessageWithId } from '@sharedServices';
import { type Message, type MessageWithId, MessageWithIdSchema } from '@sharedTypes';

const isWindowDefined = () => typeof window !== 'undefined';

const createMessageWithId = (message: Message) => ({
...message,
id: uid(),
appId: 'holo-key-manager'
});

const handleResponse =
(resolve: (value: Message | PromiseLike<Message>) => void, removeListener: () => void) =>
(event: MessageEvent) => {
const result = MessageWithIdSchema.safeParse(event.data);
if (!result.success) {
console.error('Invalid message format:', result.error);
return;
}
resolve(event.data);
removeListener();
};

export const sendMessage = (message: Message): Promise<Message> =>
export const sendMessage = (message: Message): Promise<MessageWithId> =>
new Promise((resolve, reject) => {
if (!isWindowDefined()) {
reject(new Error('window is not defined'));
Expand All @@ -31,10 +14,24 @@ export const sendMessage = (message: Message): Promise<Message> =>
const messageWithId = createMessageWithId(message);

const removeListener = () => window.removeEventListener('message', responseHandler);
const responseHandler = handleResponse(resolve, removeListener);
const responseHandler = (event: MessageEvent) => {
const parseResult = MessageWithIdSchema.safeParse(event.data);
if (!parseResult.success) {
console.error(event.data);
console.error('Invalid message format:', parseResult.error);
return;
}
const responseData = parseResult.data;
if (responseData.id !== messageWithId.id || responseData.sender === SENDER_WEBAPP) {
console.error('Invalid message id or sender:', responseData.id, responseData.sender);
return;
}
resolve(responseData);
removeListener();
};

window.addEventListener('message', responseHandler);
window.postMessage(messageWithId, '*');
window.addEventListener('message', responseHandler);

setTimeout(() => {
removeListener();
Expand Down
Loading

0 comments on commit efda5b5

Please sign in to comment.