wip: update

This commit is contained in:
reya
2024-12-22 07:35:25 +07:00
parent 8349bec65a
commit a1d87bcd74
24 changed files with 39476 additions and 33318 deletions

View File

@@ -1,148 +0,0 @@
{
"root": true,
"parserOptions": {
"ecmaVersion": 2020,
"ecmaFeatures": {
"jsx": true
},
"sourceType": "module",
"allowImportExportEverywhere": false
},
"env": {
"es6": true,
"node": true
},
"plugins": [
"react",
"babel"
],
"globals": {
"document": false,
"navigator": false,
"window": false,
"location": false,
"URL": false,
"URLSearchParams": false,
"fetch": false,
"EventSource": false,
"localStorage": false,
"sessionStorage": false
},
"rules": {
"react/jsx-uses-vars": 2,
"react/jsx-no-undef": 2,
"react/jsx-uses-react": 2,
"accessor-pairs": 2,
"arrow-spacing": [2, { "before": true, "after": true }],
"block-spacing": [2, "always"],
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
"comma-dangle": 0,
"comma-spacing": [2, { "before": false, "after": true }],
"comma-style": [2, "last"],
"constructor-super": 2,
"curly": [0, "multi-line"],
"dot-location": [2, "property"],
"eol-last": 2,
"eqeqeq": [2, "allow-null"],
"generator-star-spacing": [2, { "before": true, "after": true }],
"handle-callback-err": [2, "^(err|error)$" ],
"indent": 0,
"jsx-quotes": [2, "prefer-double"],
"key-spacing": [2, { "beforeColon": false, "afterColon": true }],
"keyword-spacing": [2, { "before": true, "after": true }],
"new-cap": 0,
"new-parens": 0,
"no-array-constructor": 2,
"no-caller": 2,
"no-class-assign": 2,
"no-cond-assign": 2,
"no-const-assign": 2,
"no-control-regex": 0,
"no-debugger": 0,
"no-delete-var": 2,
"no-dupe-args": 2,
"no-dupe-class-members": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty-character-class": 2,
"no-empty-pattern": 2,
"no-eval": 0,
"no-ex-assign": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": [2, "functions"],
"no-fallthrough": 2,
"no-floating-decimal": 2,
"no-func-assign": 2,
"no-implied-eval": 2,
"no-inner-declarations": [0, "functions"],
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-iterator": 2,
"no-label-var": 2,
"no-labels": [2, { "allowLoop": false, "allowSwitch": false }],
"no-lone-blocks": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multi-spaces": 2,
"no-multi-str": 2,
"no-multiple-empty-lines": [2, { "max": 2 }],
"no-native-reassign": 2,
"no-negated-in-lhs": 2,
"no-new": 0,
"no-new-func": 2,
"no-new-object": 2,
"no-new-require": 2,
"no-new-symbol": 2,
"no-new-wrappers": 2,
"no-obj-calls": 2,
"no-octal": 2,
"no-octal-escape": 2,
"no-path-concat": 0,
"no-proto": 2,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-return-assign": 0,
"no-self-assign": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-shadow-restricted-names": 2,
"no-spaced-func": 2,
"no-sparse-arrays": 2,
"no-this-before-super": 2,
"no-throw-literal": 2,
"no-trailing-spaces": 2,
"no-undef": 2,
"no-undef-init": 2,
"no-unexpected-multiline": 2,
"no-unneeded-ternary": [2, { "defaultAssignment": false }],
"no-unreachable": 2,
"no-unused-vars": [2, { "vars": "local", "args": "none", "varsIgnorePattern": "^_"}],
"no-useless-call": 2,
"no-useless-constructor": 2,
"no-with": 2,
"one-var": [0, { "initialized": "never" }],
"operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }],
"padded-blocks": [2, "never"],
"quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi": [2, "never"],
"semi-spacing": [2, { "before": false, "after": true }],
"space-before-blocks": [2, "always"],
"space-before-function-paren": 0,
"space-in-parens": [2, "never"],
"space-infix-ops": 2,
"space-unary-ops": [2, { "words": true, "nonwords": false }],
"spaced-comment": 0,
"template-curly-spacing": [2, "never"],
"use-isnan": 2,
"valid-typeof": 2,
"wrap-iife": [2, "any"],
"yield-star-spacing": [2, "both"],
"yoda": 0,
"no-unsafe-optional-chaning": 0
}
}

View File

@@ -1,9 +0,0 @@
arrowParens: avoid
bracketSpacing: false
jsxBracketSameLine: false
printWidth: 80
proseWrap: preserve
semi: false
singleQuote: true
trailingComma: none
useTabs: false

28
biome.json Normal file
View File

@@ -0,0 +1,28 @@
{
"$schema": "https://biomejs.dev/schemas/1.4.1/schema.json",
"organizeImports": {
"enabled": true
},
"files": {
"ignore": []
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"style": {
"noNonNullAssertion": "warn",
"noUselessElse": "off"
},
"correctness": {
"useExhaustiveDependencies": "off"
},
"a11y": {
"noSvgWithoutTitle": "off"
},
"complexity": {
"noStaticOnlyClass": "off"
}
}
}
}

View File

@@ -1,225 +1,227 @@
import browser from 'webextension-polyfill' import { Mutex } from "async-mutex";
import { import {
validateEvent, getEventHash,
getSignature, getPublicKey,
getEventHash, getSignature,
getPublicKey, nip19,
nip19 validateEvent,
} from 'nostr-tools' } from "nostr-tools";
import {nip04} from 'nostr-tools' import { nip04 } from "nostr-tools";
import {Mutex} from 'async-mutex' import browser from "webextension-polyfill";
import { import {
NO_PERMISSIONS_REQUIRED, NO_PERMISSIONS_REQUIRED,
getPermissionStatus, getPermissionStatus,
updatePermission, showNotification,
showNotification updatePermission,
} from './common' } from "./common";
const {encrypt, decrypt} = nip04 const { encrypt, decrypt } = nip04;
let openPrompt = null let openPrompt = null;
let promptMutex = new Mutex() const promptMutex = new Mutex();
let releasePromptMutex = () => {} let releasePromptMutex = () => {};
browser.runtime.onInstalled.addListener((_, __, reason) => { browser.runtime.onInstalled.addListener((_, __, reason) => {
if (reason === 'install') browser.runtime.openOptionsPage() if (reason === "install") browser.runtime.openOptionsPage();
}) });
browser.runtime.onMessage.addListener(async (req, sender) => { browser.runtime.onMessage.addListener(async (req, sender) => {
let {prompt} = req const { prompt } = req;
if (prompt) { if (prompt) {
handlePromptMessage(req, sender) handlePromptMessage(req, sender);
} else { } else {
return handleContentScriptMessage(req) return handleContentScriptMessage(req);
} }
}) });
browser.runtime.onMessageExternal.addListener( browser.runtime.onMessageExternal.addListener(
async ({type, params}, sender) => { async ({ type, params }, sender) => {
let extensionId = new URL(sender.url).host const extensionId = new URL(sender.url).host;
return handleContentScriptMessage({type, params, host: extensionId}) return handleContentScriptMessage({ type, params, host: extensionId });
} },
) );
browser.windows.onRemoved.addListener(windowId => { browser.windows.onRemoved.addListener((windowId) => {
if (openPrompt) { if (openPrompt) {
// calling this with a simple "no" response will not store anything, so it's fine // calling this with a simple "no" response will not store anything, so it's fine
// it will just return a failure // it will just return a failure
handlePromptMessage({accept: false}, null) handlePromptMessage({ accept: false }, null);
} }
}) });
async function handleContentScriptMessage({type, params, host}) { async function handleContentScriptMessage({ type, params, host }) {
if (NO_PERMISSIONS_REQUIRED[type]) { if (NO_PERMISSIONS_REQUIRED[type]) {
// authorized, and we won't do anything with private key here, so do a separate handler // authorized, and we won't do anything with private key here, so do a separate handler
switch (type) { switch (type) {
case 'replaceURL': { case "replaceURL": {
let {protocol_handler: ph} = await browser.storage.local.get([ const { protocol_handler: ph } = await browser.storage.local.get([
'protocol_handler' "protocol_handler",
]) ]);
if (!ph) return false if (!ph) return false;
let {url} = params const { url } = params;
let raw = url.split('nostr:')[1] const raw = url.split("nostr:")[1];
let {type, data} = nip19.decode(raw) const { type, data } = nip19.decode(raw);
let replacements = { const replacements = {
raw, raw,
hrp: type, hrp: type,
hex: hex:
type === 'npub' || type === 'note' type === "npub" || type === "note"
? data ? data
: type === 'nprofile' : type === "nprofile"
? data.pubkey ? data.pubkey
: type === 'nevent' : type === "nevent"
? data.id ? data.id
: null, : null,
p_or_e: {npub: 'p', note: 'e', nprofile: 'p', nevent: 'e'}[type], p_or_e: { npub: "p", note: "e", nprofile: "p", nevent: "e" }[type],
u_or_n: {npub: 'u', note: 'n', nprofile: 'u', nevent: 'n'}[type], u_or_n: { npub: "u", note: "n", nprofile: "u", nevent: "n" }[type],
relay0: type === 'nprofile' ? data.relays[0] : null, relay0: type === "nprofile" ? data.relays[0] : null,
relay1: type === 'nprofile' ? data.relays[1] : null, relay1: type === "nprofile" ? data.relays[1] : null,
relay2: type === 'nprofile' ? data.relays[2] : null relay2: type === "nprofile" ? data.relays[2] : null,
} };
let result = ph let result = ph;
Object.entries(replacements).forEach(([pattern, value]) => { // biome-ignore lint/complexity/noForEach: TODO: fix this
result = result.replace(new RegExp(`{ *${pattern} *}`, 'g'), value) Object.entries(replacements).forEach(([pattern, value]) => {
}) result = result.replace(new RegExp(`{ *${pattern} *}`, "g"), value);
});
return result return result;
} }
} }
return return;
} else { } else {
// acquire mutex here before reading policies // acquire mutex here before reading policies
releasePromptMutex = await promptMutex.acquire() releasePromptMutex = await promptMutex.acquire();
let allowed = await getPermissionStatus( const allowed = await getPermissionStatus(
host, host,
type, type,
type === 'signEvent' ? params.event : undefined type === "signEvent" ? params.event : undefined,
) );
if (allowed === true) { if (allowed === true) {
// authorized, proceed // authorized, proceed
releasePromptMutex() releasePromptMutex();
showNotification(host, allowed, type, params) showNotification(host, allowed, type, params);
} else if (allowed === false) { } else if (allowed === false) {
// denied, just refuse immediately // denied, just refuse immediately
releasePromptMutex() releasePromptMutex();
showNotification(host, allowed, type, params) showNotification(host, allowed, type, params);
return { return {
error: 'denied' error: "denied",
} };
} else { } else {
// ask for authorization // ask for authorization
try { try {
let id = Math.random().toString().slice(4) const id = Math.random().toString().slice(4);
let qs = new URLSearchParams({ const qs = new URLSearchParams({
host, host,
id, id,
params: JSON.stringify(params), params: JSON.stringify(params),
type type,
}) });
// prompt will be resolved with true or false // prompt will be resolved with true or false
let accept = await new Promise((resolve, reject) => { const accept = await new Promise((resolve, reject) => {
openPrompt = {resolve, reject} openPrompt = { resolve, reject };
const url = `${browser.runtime.getURL( const url = `${browser.runtime.getURL(
'prompt.html' "prompt.html",
)}?${qs.toString()}` )}?${qs.toString()}`;
if (browser.windows) { if (browser.windows) {
browser.windows.create({ browser.windows.create({
url, url,
type: 'popup', type: "popup",
width: 600, width: 600,
height: 600 height: 600,
}) });
} else { } else {
browser.tabs.create({ browser.tabs.create({
url, url,
active: true active: true,
}) });
} }
}) });
// denied, stop here // denied, stop here
if (!accept) return {error: 'denied'} if (!accept) return { error: "denied" };
} catch (err) { } catch (err) {
// errored, stop here // errored, stop here
releasePromptMutex() releasePromptMutex();
return { return {
error: `error: ${err}` error: `error: ${err}`,
} };
} }
} }
} }
// if we're here this means it was accepted // if we're here this means it was accepted
let results = await browser.storage.local.get('private_key') const results = await browser.storage.local.get("private_key");
if (!results || !results.private_key) { if (!results || !results.private_key) {
return {error: 'no private key found'} return { error: "no private key found" };
} }
let sk = results.private_key const sk = results.private_key;
try { try {
switch (type) { switch (type) {
case 'getPublicKey': { case "getPublicKey": {
return getPublicKey(sk) return getPublicKey(sk);
} }
case 'getRelays': { case "getRelays": {
let results = await browser.storage.local.get('relays') const results = await browser.storage.local.get("relays");
return results.relays || {} return results.relays || {};
} }
case 'signEvent': { case "signEvent": {
let {event} = params const { event } = params;
if (!event.pubkey) event.pubkey = getPublicKey(sk) if (!event.pubkey) event.pubkey = getPublicKey(sk);
if (!event.id) event.id = getEventHash(event) if (!event.id) event.id = getEventHash(event);
if (!validateEvent(event)) return {error: {message: 'invalid event'}} if (!validateEvent(event))
return { error: { message: "invalid event" } };
event.sig = await getSignature(event, sk) event.sig = await getSignature(event, sk);
return event return event;
} }
case 'nip04.encrypt': { case "nip04.encrypt": {
let {peer, plaintext} = params const { peer, plaintext } = params;
return encrypt(sk, peer, plaintext) return encrypt(sk, peer, plaintext);
} }
case 'nip04.decrypt': { case "nip04.decrypt": {
let {peer, ciphertext} = params const { peer, ciphertext } = params;
return decrypt(sk, peer, ciphertext) return decrypt(sk, peer, ciphertext);
} }
} }
} catch (error) { } catch (error) {
return {error: {message: error.message, stack: error.stack}} return { error: { message: error.message, stack: error.stack } };
} }
} }
async function handlePromptMessage({host, type, accept, conditions}, sender) { async function handlePromptMessage({ host, type, accept, conditions }, sender) {
// return response // return response
openPrompt?.resolve?.(accept) openPrompt?.resolve?.(accept);
// update policies // update policies
if (conditions) { if (conditions) {
await updatePermission(host, type, accept, conditions) await updatePermission(host, type, accept, conditions);
} }
// cleanup this // cleanup this
openPrompt = null openPrompt = null;
// release mutex here after updating policies // release mutex here after updating policies
releasePromptMutex() releasePromptMutex();
// close prompt // close prompt
if (sender) { if (sender) {
if (browser.windows) { if (browser.windows) {
browser.windows.remove(sender.tab.windowId) browser.windows.remove(sender.tab.windowId);
} else { } else {
// Android Firefox // Android Firefox
browser.tabs.remove(sender.tab.id) browser.tabs.remove(sender.tab.id);
} }
} }
} }

1137
extension/build/style.css Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,36 +1,36 @@
{ {
"name": "Nostr Connect", "name": "Nostr Connect",
"description": "Nostr Signer Extension", "description": "Nostr Signer Extension",
"version": "0.1.2", "version": "0.1.2",
"homepage_url": "https://github.com/reyamir/nostr-connect", "homepage_url": "https://github.com/reyamir/nostr-connect",
"manifest_version": 3, "manifest_version": 3,
"icons": { "icons": {
"16": "icons/icon16.png", "16": "icons/icon16.png",
"32": "icons/icon32.png", "32": "icons/icon32.png",
"48": "icons/icon48.png", "48": "icons/icon48.png",
"128": "icons/icon128.png" "128": "icons/icon128.png"
}, },
"options_page": "options.html", "options_page": "options.html",
"background": { "background": {
"service_worker": "background.build.js" "service_worker": "background.build.js"
}, },
"action": { "action": {
"default_title": "Nostr Connect", "default_title": "Nostr Connect",
"default_popup": "popup.html" "default_popup": "popup.html"
}, },
"content_scripts": [ "content_scripts": [
{ {
"matches": ["<all_urls>"], "matches": ["<all_urls>"],
"js": ["content-script.build.js"], "js": ["content-script.build.js"],
"all_frames": true "all_frames": true
} }
], ],
"permissions": ["storage"], "permissions": ["storage"],
"optional_permissions": ["notifications"], "optional_permissions": ["notifications"],
"web_accessible_resources": [ "web_accessible_resources": [
{ {
"resources": ["nostr-provider.js"], "resources": ["nostr-provider.js"],
"matches": ["https://*/*", "http://localhost:*/*"] "matches": ["https://*/*", "http://localhost:*/*"]
} }
] ]
} }

View File

@@ -1,116 +1,118 @@
import browser from 'webextension-polyfill' import browser from "webextension-polyfill";
export const NO_PERMISSIONS_REQUIRED = { export const NO_PERMISSIONS_REQUIRED = {
replaceURL: true replaceURL: true,
} };
export const PERMISSION_NAMES = Object.fromEntries([ export const PERMISSION_NAMES = Object.fromEntries([
['getPublicKey', 'read your public key'], ["getPublicKey", "read your public key"],
['getRelays', 'read your list of preferred relays'], ["getRelays", "read your list of preferred relays"],
['signEvent', 'sign events using your private key'], ["signEvent", "sign events using your private key"],
['nip04.encrypt', 'encrypt messages to peers'], ["nip04.encrypt", "encrypt messages to peers"],
['nip04.decrypt', 'decrypt messages from peers'] ["nip04.decrypt", "decrypt messages from peers"],
]) ]);
function matchConditions(conditions, event) { function matchConditions(conditions, event) {
if (conditions?.kinds) { if (conditions?.kinds) {
if (event.kind in conditions.kinds) return true if (event.kind in conditions.kinds) return true;
else return false else return false;
} }
return true return true;
} }
export async function getPermissionStatus(host, type, event) { export async function getPermissionStatus(host, type, event) {
let {policies} = await browser.storage.local.get('policies') const { policies } = await browser.storage.local.get("policies");
let answers = [true, false] const answers = [true, false];
for (let i = 0; i < answers.length; i++) { for (let i = 0; i < answers.length; i++) {
let accept = answers[i] const accept = answers[i];
let {conditions} = policies?.[host]?.[accept]?.[type] || {} const { conditions } = policies?.[host]?.[accept]?.[type] || {};
if (conditions) { if (conditions) {
if (type === 'signEvent') { if (type === "signEvent") {
if (matchConditions(conditions, event)) { if (matchConditions(conditions, event)) {
return accept // may be true or false return accept; // may be true or false
} else { } else {
// if this doesn't match we just continue so it will either match for the opposite answer (reject) // if this doesn't match we just continue so it will either match for the opposite answer (reject)
// or it will end up returning undefined at the end // or it will end up returning undefined at the end
continue // biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
} continue;
} else { }
return accept // may be true or false } else {
} return accept; // may be true or false
} }
} }
}
return undefined return undefined;
} }
export async function updatePermission(host, type, accept, conditions) { export async function updatePermission(host, type, accept, conditions) {
let {policies = {}} = await browser.storage.local.get('policies') const { policies = {} } = await browser.storage.local.get("policies");
// if the new conditions is "match everything", override the previous // if the new conditions is "match everything", override the previous
if (Object.keys(conditions).length === 0) { if (Object.keys(conditions).length === 0) {
conditions = {} conditions = {};
} else { } else {
// if we already had a policy for this, merge the conditions // if we already had a policy for this, merge the conditions
let existingConditions = policies[host]?.[accept]?.[type]?.conditions const existingConditions = policies[host]?.[accept]?.[type]?.conditions;
if (existingConditions) {
if (existingConditions.kinds && conditions.kinds) {
Object.keys(existingConditions.kinds).forEach(kind => {
conditions.kinds[kind] = true
})
}
}
}
// if we have a reverse policy (accept / reject) that is exactly equal to this, remove it if (existingConditions) {
let other = !accept if (existingConditions.kinds && conditions.kinds) {
let reverse = policies?.[host]?.[other]?.[type] Object.keys(existingConditions.kinds).forEach((kind) => {
if ( conditions.kinds[kind] = true;
reverse && });
JSON.stringify(reverse.conditions) === JSON.stringify(conditions) }
) { }
delete policies[host][other][type] }
}
// insert our new policy // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it
policies[host] = policies[host] || {} const other = !accept;
policies[host][accept] = policies[host][accept] || {} const reverse = policies?.[host]?.[other]?.[type];
policies[host][accept][type] = { if (
conditions, // filter that must match the event (in case of signEvent) reverse &&
created_at: Math.round(Date.now() / 1000) JSON.stringify(reverse.conditions) === JSON.stringify(conditions)
} ) {
delete policies[host][other][type];
}
browser.storage.local.set({policies}) // insert our new policy
policies[host] = policies[host] || {};
policies[host][accept] = policies[host][accept] || {};
policies[host][accept][type] = {
conditions, // filter that must match the event (in case of signEvent)
created_at: Math.round(Date.now() / 1000),
};
browser.storage.local.set({ policies });
} }
export async function removePermissions(host, accept, type) { export async function removePermissions(host, accept, type) {
let {policies = {}} = await browser.storage.local.get('policies') const { policies = {} } = await browser.storage.local.get("policies");
delete policies[host]?.[accept]?.[type] delete policies[host]?.[accept]?.[type];
browser.storage.local.set({policies}) browser.storage.local.set({ policies });
} }
export async function showNotification(host, answer, type, params) { export async function showNotification(host, answer, type, params) {
let ok = await browser.storage.local.get('notifications') const ok = await browser.storage.local.get("notifications");
if (ok) { if (ok) {
let action = answer ? 'allowed' : 'denied' const action = answer ? "allowed" : "denied";
browser.notifications.create(undefined, { browser.notifications.create(undefined, {
type: 'basic', type: "basic",
title: `${type} ${action} for ${host}`, title: `${type} ${action} for ${host}`,
message: JSON.stringify( message: JSON.stringify(
params?.event params?.event
? { ? {
kind: params.event.kind, kind: params.event.kind,
content: params.event.content, content: params.event.content,
tags: params.event.tags tags: params.event.tags,
} }
: params, : params,
null, null,
2 2,
), ),
iconUrl: 'icons/48x48.png' iconUrl: "icons/48x48.png",
}) });
} }
} }

View File

@@ -1,36 +1,37 @@
import browser from 'webextension-polyfill' import browser from "webextension-polyfill";
const EXTENSION = 'nostrconnect' const EXTENSION = "nostrconnect";
// inject the script that will provide window.nostr // inject the script that will provide window.nostr
let script = document.createElement('script') const script = document.createElement("script");
script.setAttribute('async', 'false') script.setAttribute("async", "false");
script.setAttribute('type', 'text/javascript') script.setAttribute("type", "text/javascript");
script.setAttribute('src', browser.runtime.getURL('nostr-provider.js')) script.setAttribute("src", browser.runtime.getURL("nostr-provider.js"));
document.head.appendChild(script) document.head.appendChild(script);
// listen for messages from that script // listen for messages from that script
window.addEventListener('message', async message => { window.addEventListener("message", async (message) => {
if (message.source !== window) return if (message.source !== window) return;
if (!message.data) return if (!message.data) return;
if (!message.data.params) return if (!message.data.params) return;
if (message.data.ext !== EXTENSION) return if (message.data.ext !== EXTENSION) return;
// pass on to background // pass on to background
var response let response;
try {
response = await browser.runtime.sendMessage({
type: message.data.type,
params: message.data.params,
host: location.host
})
} catch (error) {
response = {error}
}
// return response try {
window.postMessage( response = await browser.runtime.sendMessage({
{id: message.data.id, ext: EXTENSION, response}, type: message.data.type,
message.origin params: message.data.params,
) host: location.host,
}) });
} catch (error) {
response = { error };
}
// return response
window.postMessage(
{ id: message.data.id, ext: EXTENSION, response },
message.origin,
);
});

View File

@@ -1,35 +1,35 @@
{ {
"name": "Nostr Connect", "name": "Nostr Connect",
"description": "Nostr Signer Extension", "description": "Nostr Signer Extension",
"version": "0.1.2", "version": "0.1.2",
"homepage_url": "https://github.com/reyamir/nostr-connect", "homepage_url": "https://github.com/reyamir/nostr-connect",
"manifest_version": 2, "manifest_version": 2,
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}" "id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}"
} }
}, },
"icons": { "icons": {
"16": "icons/icon16.png", "16": "icons/icon16.png",
"32": "icons/icon32.png", "32": "icons/icon32.png",
"48": "icons/icon48.png", "48": "icons/icon48.png",
"128": "icons/icon128.png" "128": "icons/icon128.png"
}, },
"options_page": "options.html", "options_page": "options.html",
"background": { "background": {
"scripts": ["background.build.js"] "scripts": ["background.build.js"]
}, },
"browser_action": { "browser_action": {
"default_title": "Nostr Connect", "default_title": "Nostr Connect",
"default_popup": "popup.html" "default_popup": "popup.html"
}, },
"content_scripts": [ "content_scripts": [
{ {
"matches": ["<all_urls>"], "matches": ["<all_urls>"],
"js": ["content-script.build.js"] "js": ["content-script.build.js"]
} }
], ],
"permissions": ["storage"], "permissions": ["storage"],
"optional_permissions": ["notifications"], "optional_permissions": ["notifications"],
"web_accessible_resources": ["nostr-provider.js"] "web_accessible_resources": ["nostr-provider.js"]
} }

View File

@@ -1,87 +1,76 @@
import React from 'react' import React from "react";
export function LogoIcon() { export function LogoIcon() {
return ( return (
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
width="56" width="56"
height="56" height="56"
fill="none" fill="none"
viewBox="0 0 56 56" viewBox="0 0 56 56"
> >
<rect width="56" height="56" fill="#EEECFD" rx="16"></rect> <rect width="56" height="56" fill="#EEECFD" rx="16" />
<rect <rect
width="55" width="55"
height="55" height="55"
x="0.5" x="0.5"
y="0.5" y="0.5"
stroke="#5A41F4" stroke="#5A41F4"
strokeOpacity="0.25" strokeOpacity="0.25"
rx="15.5" rx="15.5"
></rect> />
<rect <rect
width="39" width="39"
height="39" height="39"
x="8.5" x="8.5"
y="8.5" y="8.5"
fill="url(#paint0_linear_24_2379)" fill="url(#paint0_linear_24_2379)"
rx="19.5" rx="19.5"
></rect> />
<rect <rect width="39" height="39" x="8.5" y="8.5" stroke="#6149F6" rx="19.5" />
width="39" <g fill="#fff" stroke="#6149F6" clipPath="url(#clip0_24_2379)">
height="39" <path d="M23.78 20.634l.408-.235-.21-.422a4.432 4.432 0 01-.458-1.797l-.031-.78-.696.355A11.533 11.533 0 0016.5 27.998h0V28c.002.87.103 1.738.302 2.585a3.525 3.525 0 102.843-1.058A8.377 8.377 0 0119.5 28a8.523 8.523 0 014.28-7.366zM36.5 28.023v.468l.467.03c.621.042 1.227.212 1.778.5l.687.36.044-.774.005-.075c.01-.166.02-.349.02-.532v-.001a11.524 11.524 0 00-8.142-10.99 3.526 3.526 0 10-.501 2.989A8.524 8.524 0 0136.5 28s0 0 0 0v.022zM33.185 32.622a3.49 3.49 0 00.311 1.844 8.442 8.442 0 01-9.766.877l-.407-.239-.262.392c-.343.514-.79.95-1.311 1.282l-.652.414.645.425a11.39 11.39 0 0014.092-1.23c.264.069.536.107.81.113h.01a3.5 3.5 0 002.803-5.6h.556l-1.603-.932a3.49 3.49 0 00-5.226 2.654z" />
x="8.5" </g>
y="8.5" <defs>
stroke="#6149F6" <linearGradient
rx="19.5" id="paint0_linear_24_2379"
></rect> x1="28"
<g fill="#fff" stroke="#6149F6" clipPath="url(#clip0_24_2379)"> x2="28"
<path d="M23.78 20.634l.408-.235-.21-.422a4.432 4.432 0 01-.458-1.797l-.031-.78-.696.355A11.533 11.533 0 0016.5 27.998h0V28c.002.87.103 1.738.302 2.585a3.525 3.525 0 102.843-1.058A8.377 8.377 0 0119.5 28a8.523 8.523 0 014.28-7.366zM36.5 28.023v.468l.467.03c.621.042 1.227.212 1.778.5l.687.36.044-.774.005-.075c.01-.166.02-.349.02-.532v-.001a11.524 11.524 0 00-8.142-10.99 3.526 3.526 0 10-.501 2.989A8.524 8.524 0 0136.5 28s0 0 0 0v.022zM33.185 32.622a3.49 3.49 0 00.311 1.844 8.442 8.442 0 01-9.766.877l-.407-.239-.262.392c-.343.514-.79.95-1.311 1.282l-.652.414.645.425a11.39 11.39 0 0014.092-1.23c.264.069.536.107.81.113h.01a3.5 3.5 0 002.803-5.6h.556l-1.603-.932a3.49 3.49 0 00-5.226 2.654z"></path> y1="8"
</g> y2="48"
<defs> gradientUnits="userSpaceOnUse"
<linearGradient >
id="paint0_linear_24_2379" <stop stopColor="#8E7CFF" />
x1="28" <stop offset="1" stopColor="#5A41F4" />
x2="28" </linearGradient>
y1="8" <clipPath id="clip0_24_2379">
y2="48" <path fill="#fff" d="M0 0H24V24H0z" transform="translate(16 15)" />
gradientUnits="userSpaceOnUse" </clipPath>
> </defs>
<stop stopColor="#8E7CFF"></stop> </svg>
<stop offset="1" stopColor="#5A41F4"></stop> );
</linearGradient>
<clipPath id="clip0_24_2379">
<path
fill="#fff"
d="M0 0H24V24H0z"
transform="translate(16 15)"
></path>
</clipPath>
</defs>
</svg>
)
} }
export function SettingsIcon(props) { export function SettingsIcon(props) {
return ( return (
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
fill="none" fill="none"
viewBox="0 0 24 24" viewBox="0 0 24 24"
strokeWidth={1.5} strokeWidth={1.5}
stroke="currentColor" stroke="currentColor"
{...props} {...props}
> >
<path <path
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
/> />
<path <path
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/> />
</svg> </svg>
) );
} }

View File

@@ -1,114 +1,108 @@
const EXTENSION = 'nostrconnect' const EXTENSION = "nostrconnect";
window.nostr = { window.nostr = {
_requests: {}, _requests: {},
_pubkey: null, _pubkey: null,
async getPublicKey() { async getPublicKey() {
if (this._pubkey) return this._pubkey if (this._pubkey) return this._pubkey;
this._pubkey = await this._call('getPublicKey', {}) this._pubkey = await this._call("getPublicKey", {});
return this._pubkey return this._pubkey;
}, },
async signEvent(event) { async signEvent(event) {
return this._call('signEvent', {event}) return this._call("signEvent", { event });
}, },
async getRelays() { async getRelays() {
return this._call('getRelays', {}) return this._call("getRelays", {});
}, },
nip04: { nip04: {
async encrypt(peer, plaintext) { async encrypt(peer, plaintext) {
return window.nostr._call('nip04.encrypt', {peer, plaintext}) return window.nostr._call("nip04.encrypt", { peer, plaintext });
}, },
async decrypt(peer, ciphertext) { async decrypt(peer, ciphertext) {
return window.nostr._call('nip04.decrypt', {peer, ciphertext}) return window.nostr._call("nip04.decrypt", { peer, ciphertext });
} },
}, },
_call(type, params) { _call(type, params) {
let id = Math.random().toString().slice(-4) const id = Math.random().toString().slice(-4);
console.log( console.log(
'%c[nostrconnect:%c' + `%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`,
id + "background-color:#f1b912;font-weight:bold;color:white",
'%c]%c calling %c' + "background-color:#f1b912;font-weight:bold;color:#a92727",
type + "background-color:#f1b912;color:white;font-weight:bold",
'%c with %c' + "color:auto",
JSON.stringify(params || {}), "font-weight:bold;color:#08589d;font-family:monospace",
'background-color:#f1b912;font-weight:bold;color:white', "color:auto",
'background-color:#f1b912;font-weight:bold;color:#a92727', "font-weight:bold;color:#90b12d;font-family:monospace",
'background-color:#f1b912;color:white;font-weight:bold', );
'color:auto', return new Promise((resolve, reject) => {
'font-weight:bold;color:#08589d;font-family:monospace', this._requests[id] = { resolve, reject };
'color:auto', window.postMessage(
'font-weight:bold;color:#90b12d;font-family:monospace' {
) id,
return new Promise((resolve, reject) => { ext: EXTENSION,
this._requests[id] = {resolve, reject} type,
window.postMessage( params,
{ },
id, "*",
ext: EXTENSION, );
type, });
params },
}, };
'*'
)
})
}
}
window.addEventListener('message', message => { window.addEventListener("message", (message) => {
if ( if (
!message.data || !message.data ||
message.data.response === null || message.data.response === null ||
message.data.response === undefined || message.data.response === undefined ||
message.data.ext !== EXTENSION || message.data.ext !== EXTENSION ||
!window.nostr._requests[message.data.id] !window.nostr._requests[message.data.id]
) )
return return;
if (message.data.response.error) { if (message.data.response.error) {
let error = new Error( const error = new Error(
`${EXTENSION}: ` + message.data.response.error.message `${EXTENSION}: ${message.data.response.error.message}`,
) );
error.stack = message.data.response.error.stack error.stack = message.data.response.error.stack;
window.nostr._requests[message.data.id].reject(error) window.nostr._requests[message.data.id].reject(error);
} else { } else {
window.nostr._requests[message.data.id].resolve(message.data.response) window.nostr._requests[message.data.id].resolve(message.data.response);
} }
console.log( console.log(
'%c[nostrconnect:%c' + `%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify(
message.data.id + message?.data?.response || message?.data?.response?.error?.message || {},
'%c]%c result: %c' + )}`,
JSON.stringify( "background-color:#f1b912;font-weight:bold;color:white",
message?.data?.response || message?.data?.response?.error?.message || {} "background-color:#f1b912;font-weight:bold;color:#a92727",
), "background-color:#f1b912;color:white;font-weight:bold",
'background-color:#f1b912;font-weight:bold;color:white', "color:auto",
'background-color:#f1b912;font-weight:bold;color:#a92727', "font-weight:bold;color:#08589d",
'background-color:#f1b912;color:white;font-weight:bold', );
'color:auto',
'font-weight:bold;color:#08589d'
)
delete window.nostr._requests[message.data.id] delete window.nostr._requests[message.data.id];
}) });
// hack to replace nostr:nprofile.../etc links with something else // hack to replace nostr:nprofile.../etc links with something else
let replacing = null let replacing = null;
document.addEventListener('mousedown', replaceNostrSchemeLink) document.addEventListener("mousedown", replaceNostrSchemeLink);
async function replaceNostrSchemeLink(e) { async function replaceNostrSchemeLink(e) {
if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return;
if (replacing === false) return if (replacing === false) return;
let response = await window.nostr._call('replaceURL', {url: e.target.href}) const response = await window.nostr._call("replaceURL", {
if (response === false) { url: e.target.href,
replacing = false });
return if (response === false) {
} replacing = false;
return;
}
e.target.href = response e.target.href = response;
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,116 +1,118 @@
import browser from 'webextension-polyfill' import browser from "webextension-polyfill";
export const NO_PERMISSIONS_REQUIRED = { export const NO_PERMISSIONS_REQUIRED = {
replaceURL: true replaceURL: true,
} };
export const PERMISSION_NAMES = Object.fromEntries([ export const PERMISSION_NAMES = Object.fromEntries([
['getPublicKey', 'read your public key'], ["getPublicKey", "read your public key"],
['getRelays', 'read your list of preferred relays'], ["getRelays", "read your list of preferred relays"],
['signEvent', 'sign events using your private key'], ["signEvent", "sign events using your private key"],
['nip04.encrypt', 'encrypt messages to peers'], ["nip04.encrypt", "encrypt messages to peers"],
['nip04.decrypt', 'decrypt messages from peers'] ["nip04.decrypt", "decrypt messages from peers"],
]) ]);
function matchConditions(conditions, event) { function matchConditions(conditions, event) {
if (conditions?.kinds) { if (conditions?.kinds) {
if (event.kind in conditions.kinds) return true if (event.kind in conditions.kinds) return true;
else return false else return false;
} }
return true return true;
} }
export async function getPermissionStatus(host, type, event) { export async function getPermissionStatus(host, type, event) {
let {policies} = await browser.storage.local.get('policies') const { policies } = await browser.storage.local.get("policies");
let answers = [true, false] const answers = [true, false];
for (let i = 0; i < answers.length; i++) { for (let i = 0; i < answers.length; i++) {
let accept = answers[i] const accept = answers[i];
let {conditions} = policies?.[host]?.[accept]?.[type] || {} const { conditions } = policies?.[host]?.[accept]?.[type] || {};
if (conditions) { if (conditions) {
if (type === 'signEvent') { if (type === "signEvent") {
if (matchConditions(conditions, event)) { if (matchConditions(conditions, event)) {
return accept // may be true or false return accept; // may be true or false
} else { } else {
// if this doesn't match we just continue so it will either match for the opposite answer (reject) // if this doesn't match we just continue so it will either match for the opposite answer (reject)
// or it will end up returning undefined at the end // or it will end up returning undefined at the end
continue // biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
} continue;
} else { }
return accept // may be true or false } else {
} return accept; // may be true or false
} }
} }
}
return undefined return undefined;
} }
export async function updatePermission(host, type, accept, conditions) { export async function updatePermission(host, type, accept, conditions) {
let {policies = {}} = await browser.storage.local.get('policies') const { policies = {} } = await browser.storage.local.get("policies");
// if the new conditions is "match everything", override the previous // if the new conditions is "match everything", override the previous
if (Object.keys(conditions).length === 0) { if (Object.keys(conditions).length === 0) {
conditions = {} conditions = {};
} else { } else {
// if we already had a policy for this, merge the conditions // if we already had a policy for this, merge the conditions
let existingConditions = policies[host]?.[accept]?.[type]?.conditions const existingConditions = policies[host]?.[accept]?.[type]?.conditions;
if (existingConditions) {
if (existingConditions.kinds && conditions.kinds) {
Object.keys(existingConditions.kinds).forEach(kind => {
conditions.kinds[kind] = true
})
}
}
}
// if we have a reverse policy (accept / reject) that is exactly equal to this, remove it if (existingConditions) {
let other = !accept if (existingConditions.kinds && conditions.kinds) {
let reverse = policies?.[host]?.[other]?.[type] Object.keys(existingConditions.kinds).forEach((kind) => {
if ( conditions.kinds[kind] = true;
reverse && });
JSON.stringify(reverse.conditions) === JSON.stringify(conditions) }
) { }
delete policies[host][other][type] }
}
// insert our new policy // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it
policies[host] = policies[host] || {} const other = !accept;
policies[host][accept] = policies[host][accept] || {} const reverse = policies?.[host]?.[other]?.[type];
policies[host][accept][type] = { if (
conditions, // filter that must match the event (in case of signEvent) reverse &&
created_at: Math.round(Date.now() / 1000) JSON.stringify(reverse.conditions) === JSON.stringify(conditions)
} ) {
delete policies[host][other][type];
}
browser.storage.local.set({policies}) // insert our new policy
policies[host] = policies[host] || {};
policies[host][accept] = policies[host][accept] || {};
policies[host][accept][type] = {
conditions, // filter that must match the event (in case of signEvent)
created_at: Math.round(Date.now() / 1000),
};
browser.storage.local.set({ policies });
} }
export async function removePermissions(host, accept, type) { export async function removePermissions(host, accept, type) {
let {policies = {}} = await browser.storage.local.get('policies') const { policies = {} } = await browser.storage.local.get("policies");
delete policies[host]?.[accept]?.[type] delete policies[host]?.[accept]?.[type];
browser.storage.local.set({policies}) browser.storage.local.set({ policies });
} }
export async function showNotification(host, answer, type, params) { export async function showNotification(host, answer, type, params) {
let ok = await browser.storage.local.get('notifications') const ok = await browser.storage.local.get("notifications");
if (ok) { if (ok) {
let action = answer ? 'allowed' : 'denied' const action = answer ? "allowed" : "denied";
browser.notifications.create(undefined, { browser.notifications.create(undefined, {
type: 'basic', type: "basic",
title: `${type} ${action} for ${host}`, title: `${type} ${action} for ${host}`,
message: JSON.stringify( message: JSON.stringify(
params?.event params?.event
? { ? {
kind: params.event.kind, kind: params.event.kind,
content: params.event.content, content: params.event.content,
tags: params.event.tags tags: params.event.tags,
} }
: params, : params,
null, null,
2 2,
), ),
iconUrl: 'icons/48x48.png' iconUrl: "icons/48x48.png",
}) });
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,35 +1,36 @@
{ {
"name": "Nostr Connect", "name": "Nostr Connect",
"description": "Nostr Signer Extension", "description": "Nostr Signer Extension",
"version": "0.1.2", "version": "0.1.2",
"homepage_url": "https://github.com/reyamir/nostr-connect", "homepage_url": "https://github.com/reyamir/nostr-connect",
"manifest_version": 2, "manifest_version": 3,
"browser_specific_settings": { "icons": {
"gecko": { "16": "icons/icon16.png",
"id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}" "32": "icons/icon32.png",
} "48": "icons/icon48.png",
}, "128": "icons/icon128.png"
"icons": { },
"16": "icons/icon16.png", "options_page": "options.html",
"32": "icons/icon32.png", "background": {
"48": "icons/icon48.png", "service_worker": "background.build.js"
"128": "icons/icon128.png" },
}, "action": {
"options_page": "options.html", "default_title": "Nostr Connect",
"background": { "default_popup": "popup.html"
"scripts": ["background.build.js"] },
}, "content_scripts": [
"browser_action": { {
"default_title": "Nostr Connect", "matches": ["<all_urls>"],
"default_popup": "popup.html" "js": ["content-script.build.js"],
}, "all_frames": true
"content_scripts": [ }
{ ],
"matches": ["<all_urls>"], "permissions": ["storage"],
"js": ["content-script.build.js"] "optional_permissions": ["notifications"],
} "web_accessible_resources": [
], {
"permissions": ["storage"], "resources": ["nostr-provider.js"],
"optional_permissions": ["notifications"], "matches": ["https://*/*", "http://localhost:*/*"]
"web_accessible_resources": ["nostr-provider.js"] }
]
} }

View File

@@ -1,114 +1,108 @@
const EXTENSION = 'nostrconnect' const EXTENSION = "nostrconnect";
window.nostr = { window.nostr = {
_requests: {}, _requests: {},
_pubkey: null, _pubkey: null,
async getPublicKey() { async getPublicKey() {
if (this._pubkey) return this._pubkey if (this._pubkey) return this._pubkey;
this._pubkey = await this._call('getPublicKey', {}) this._pubkey = await this._call("getPublicKey", {});
return this._pubkey return this._pubkey;
}, },
async signEvent(event) { async signEvent(event) {
return this._call('signEvent', {event}) return this._call("signEvent", { event });
}, },
async getRelays() { async getRelays() {
return this._call('getRelays', {}) return this._call("getRelays", {});
}, },
nip04: { nip04: {
async encrypt(peer, plaintext) { async encrypt(peer, plaintext) {
return window.nostr._call('nip04.encrypt', {peer, plaintext}) return window.nostr._call("nip04.encrypt", { peer, plaintext });
}, },
async decrypt(peer, ciphertext) { async decrypt(peer, ciphertext) {
return window.nostr._call('nip04.decrypt', {peer, ciphertext}) return window.nostr._call("nip04.decrypt", { peer, ciphertext });
} },
}, },
_call(type, params) { _call(type, params) {
let id = Math.random().toString().slice(-4) const id = Math.random().toString().slice(-4);
console.log( console.log(
'%c[nostrconnect:%c' + `%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`,
id + "background-color:#f1b912;font-weight:bold;color:white",
'%c]%c calling %c' + "background-color:#f1b912;font-weight:bold;color:#a92727",
type + "background-color:#f1b912;color:white;font-weight:bold",
'%c with %c' + "color:auto",
JSON.stringify(params || {}), "font-weight:bold;color:#08589d;font-family:monospace",
'background-color:#f1b912;font-weight:bold;color:white', "color:auto",
'background-color:#f1b912;font-weight:bold;color:#a92727', "font-weight:bold;color:#90b12d;font-family:monospace",
'background-color:#f1b912;color:white;font-weight:bold', );
'color:auto', return new Promise((resolve, reject) => {
'font-weight:bold;color:#08589d;font-family:monospace', this._requests[id] = { resolve, reject };
'color:auto', window.postMessage(
'font-weight:bold;color:#90b12d;font-family:monospace' {
) id,
return new Promise((resolve, reject) => { ext: EXTENSION,
this._requests[id] = {resolve, reject} type,
window.postMessage( params,
{ },
id, "*",
ext: EXTENSION, );
type, });
params },
}, };
'*'
)
})
}
}
window.addEventListener('message', message => { window.addEventListener("message", (message) => {
if ( if (
!message.data || !message.data ||
message.data.response === null || message.data.response === null ||
message.data.response === undefined || message.data.response === undefined ||
message.data.ext !== EXTENSION || message.data.ext !== EXTENSION ||
!window.nostr._requests[message.data.id] !window.nostr._requests[message.data.id]
) )
return return;
if (message.data.response.error) { if (message.data.response.error) {
let error = new Error( const error = new Error(
`${EXTENSION}: ` + message.data.response.error.message `${EXTENSION}: ${message.data.response.error.message}`,
) );
error.stack = message.data.response.error.stack error.stack = message.data.response.error.stack;
window.nostr._requests[message.data.id].reject(error) window.nostr._requests[message.data.id].reject(error);
} else { } else {
window.nostr._requests[message.data.id].resolve(message.data.response) window.nostr._requests[message.data.id].resolve(message.data.response);
} }
console.log( console.log(
'%c[nostrconnect:%c' + `%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify(
message.data.id + message?.data?.response || message?.data?.response?.error?.message || {},
'%c]%c result: %c' + )}`,
JSON.stringify( "background-color:#f1b912;font-weight:bold;color:white",
message?.data?.response || message?.data?.response?.error?.message || {} "background-color:#f1b912;font-weight:bold;color:#a92727",
), "background-color:#f1b912;color:white;font-weight:bold",
'background-color:#f1b912;font-weight:bold;color:white', "color:auto",
'background-color:#f1b912;font-weight:bold;color:#a92727', "font-weight:bold;color:#08589d",
'background-color:#f1b912;color:white;font-weight:bold', );
'color:auto',
'font-weight:bold;color:#08589d'
)
delete window.nostr._requests[message.data.id] delete window.nostr._requests[message.data.id];
}) });
// hack to replace nostr:nprofile.../etc links with something else // hack to replace nostr:nprofile.../etc links with something else
let replacing = null let replacing = null;
document.addEventListener('mousedown', replaceNostrSchemeLink) document.addEventListener("mousedown", replaceNostrSchemeLink);
async function replaceNostrSchemeLink(e) { async function replaceNostrSchemeLink(e) {
if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return;
if (replacing === false) return if (replacing === false) return;
let response = await window.nostr._call('replaceURL', {url: e.target.href}) const response = await window.nostr._call("replaceURL", {
if (response === false) { url: e.target.href,
replacing = false });
return if (response === false) {
} replacing = false;
return;
}
e.target.href = response e.target.href = response;
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,182 +1,184 @@
import browser from 'webextension-polyfill' import * as Tabs from "@radix-ui/react-tabs";
import {render} from 'react-dom' import { minidenticon } from "minidenticons";
import {getPublicKey, nip19} from 'nostr-tools' import { getPublicKey, nip19 } from "nostr-tools";
import React, {useState, useMemo, useEffect} from 'react' import React, { useState, useMemo, useEffect } from "react";
import QRCode from 'react-qr-code' import QRCode from "react-qr-code";
import {SettingsIcon} from './icons' import browser from "webextension-polyfill";
import {minidenticon} from 'minidenticons' import { SettingsIcon } from "./icons";
import * as Tabs from '@radix-ui/react-tabs'
function Popup() { function Popup() {
let [keys, setKeys] = useState(null) const [keys, setKeys] = useState(null);
let avatarURI = useMemo( const avatarURI = useMemo(
() => () =>
keys keys
? 'data:image/svg+xml;utf8,' + ? `data:image/svg+xml;utf8,${encodeURIComponent(minidenticon(keys.npub, 90, 30))}`
encodeURIComponent(minidenticon(keys.npub, 90, 30)) : null,
: null, [keys],
[keys] );
)
const gotoSettings = () => { const gotoSettings = () => {
browser.tabs.create({ browser.tabs.create({
url: browser.runtime.getURL('/options.html') url: browser.runtime.getURL("/options.html"),
}) });
} };
useEffect(() => { useEffect(() => {
browser.storage.local.get(['private_key', 'relays']).then(results => { browser.storage.local.get(["private_key", "relays"]).then((results) => {
if (results.private_key) { if (results.private_key) {
let hexKey = getPublicKey(results.private_key) const hexKey = getPublicKey(results.private_key);
let npubKey = nip19.npubEncode(hexKey) const npubKey = nip19.npubEncode(hexKey);
setKeys({npub: npubKey, hex: hexKey}) setKeys({ npub: npubKey, hex: hexKey });
if (results.relays) { if (results.relays) {
let relaysList = [] const relaysList = [];
for (let url in results.relays) { for (const url in results.relays) {
if (results.relays[url].write) { if (results.relays[url].write) {
relaysList.push(url) relaysList.push(url);
if (relaysList.length >= 3) break if (relaysList.length >= 3) break;
} }
} }
if (relaysList.length) { if (relaysList.length) {
let nprofileKey = nip19.nprofileEncode({ const nprofileKey = nip19.nprofileEncode({
pubkey: hexKey, pubkey: hexKey,
relays: relaysList relays: relaysList,
}) });
setKeys(prev => ({...prev, nprofile: nprofileKey})) setKeys((prev) => ({ ...prev, nprofile: nprofileKey }));
} }
} }
} else { } else {
setKeys(null) setKeys(null);
} }
}) });
}, []) }, []);
return ( return (
<div className="w-[320px] p-6"> <div className="w-[320px] p-6">
{!keys ? ( {!keys ? (
<div className="flex items-center justify-between gap-6"> <div className="flex items-center justify-between gap-6">
<div className="flex-1 flex items-center justify-between"> <div className="flex-1 flex items-center justify-between">
<p className="text-sm font-medium"> <p className="text-sm font-medium">
Click here to enter or create Click here to enter or create
<br /> <br />
your first identity your first identity
</p> </p>
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
fill="none" fill="none"
viewBox="0 0 24 24" viewBox="0 0 24 24"
strokeWidth={1.5} strokeWidth={1.5}
stroke="currentColor" stroke="currentColor"
className="w-6 h-6" className="w-6 h-6"
> >
<path <path
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3"
/> />
</svg> </svg>
</div> </div>
<button <button
type="button" type="button"
onClick={() => gotoSettings()} onClick={() => gotoSettings()}
className="w-9 h-9 shrink-0 border border-primary shadow-sm rounded-xl inline-flex items-center justify-center" className="w-9 h-9 shrink-0 border border-primary shadow-sm rounded-xl inline-flex items-center justify-center"
> >
<SettingsIcon className="w-5 h-5 text-muted" /> <SettingsIcon className="w-5 h-5 text-muted" />
</button> </button>
</div> </div>
) : ( ) : (
<div> <div>
<div className="mb-2 flex items-center justify-between"> <div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{avatarURI ? ( {avatarURI ? (
<img <img
src={avatarURI} src={avatarURI}
className="w-9 h-9 rounded-full bg-muted" alt="Avatar"
/> className="w-9 h-9 rounded-full bg-muted"
) : ( />
<div className="w-9 h-9 rounded-full bg-muted" /> ) : (
)} <div className="w-9 h-9 rounded-full bg-muted" />
<p className="font-semibold">Account</p> )}
</div> <p className="font-semibold">Account</p>
<button </div>
type="button" <button
onClick={() => gotoSettings()} type="button"
className="w-9 h-9 shrink-0 border border-primary shadow-sm rounded-xl inline-flex items-center justify-center" onClick={() => gotoSettings()}
> className="w-9 h-9 shrink-0 border border-primary shadow-sm rounded-xl inline-flex items-center justify-center"
<SettingsIcon className="w-5 h-5 text-muted" /> >
</button> <SettingsIcon className="w-5 h-5 text-muted" />
</div> </button>
<div> </div>
<Tabs.Root defaultValue="npub"> <div>
<Tabs.List className="w-full border-b border-primary h-10 flex items-center"> <Tabs.Root defaultValue="npub">
<Tabs.Trigger <Tabs.List className="w-full border-b border-primary h-10 flex items-center">
value="npub" <Tabs.Trigger
className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary" value="npub"
> className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary"
npub >
</Tabs.Trigger> npub
<Tabs.Trigger </Tabs.Trigger>
value="hex" <Tabs.Trigger
className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary" value="hex"
> className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary"
hex >
</Tabs.Trigger> hex
{keys.nprofile ? ( </Tabs.Trigger>
<Tabs.Trigger {keys.nprofile ? (
value="nprofile" <Tabs.Trigger
className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary" value="nprofile"
> className="font-medium flex-1 flex items-center justify-center text-muted h-10 data-[state=active]:text-primary data-[state=active]:border-b data-[state=active]:border-secondary"
nprofile >
</Tabs.Trigger> nprofile
) : null} </Tabs.Trigger>
</Tabs.List> ) : null}
<Tabs.Content value="npub"> </Tabs.List>
<div className="my-4"> <Tabs.Content value="npub">
<textarea <div className="my-4">
value={keys.npub} <textarea
readOnly value={keys.npub}
className="w-full h-20 resize-none p-3 bg-muted rounded-xl" readOnly
/> className="w-full h-20 resize-none p-3 bg-muted rounded-xl"
</div> />
<div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center"> </div>
<QRCode size={128} value={keys.npub} /> <div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center">
</div> <QRCode size={128} value={keys.npub} />
</Tabs.Content> </div>
<Tabs.Content value="hex"> </Tabs.Content>
<div className="my-4"> <Tabs.Content value="hex">
<textarea <div className="my-4">
value={keys.hex} <textarea
readOnly value={keys.hex}
className="w-full h-20 resize-none p-3 bg-muted rounded-xl" readOnly
/> className="w-full h-20 resize-none p-3 bg-muted rounded-xl"
</div> />
<div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center"> </div>
<QRCode size={128} value={keys.hex} /> <div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center">
</div> <QRCode size={128} value={keys.hex} />
</Tabs.Content> </div>
{keys.nprofile ? ( </Tabs.Content>
<Tabs.Content value="nprofile"> {keys.nprofile ? (
<div className="my-4"> <Tabs.Content value="nprofile">
<textarea <div className="my-4">
value={keys.nprofile} <textarea
readOnly value={keys.nprofile}
className="w-full h-20 resize-none p-3 bg-muted rounded-xl" readOnly
/> className="w-full h-20 resize-none p-3 bg-muted rounded-xl"
</div> />
<div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center"> </div>
<QRCode size={128} value={keys.nprofile} /> <div className="w-full rounded-xl border border-primary p-4 flex items-center justify-center">
</div> <QRCode size={128} value={keys.nprofile} />
</Tabs.Content> </div>
) : null} </Tabs.Content>
</Tabs.Root> ) : null}
</div> </Tabs.Root>
</div> </div>
)} </div>
</div> )}
) </div>
);
} }
render(<Popup />, document.getElementById('main')) const container = document.getElementById("main");
const root = createRoot(container);
root.render(<Popup />);

View File

@@ -1,165 +1,114 @@
import browser from 'webextension-polyfill' import React, { useState } from "react";
import {render} from 'react-dom' import browser from "webextension-polyfill";
import React, {useState} from 'react' import * as Checkbox from "@radix-ui/react-checkbox";
import { PERMISSION_NAMES } from "./common";
import {PERMISSION_NAMES} from './common' import { LogoIcon } from "./icons";
import {LogoIcon} from './icons'
import * as Checkbox from '@radix-ui/react-checkbox'
function Prompt() { function Prompt() {
const [isRemember, setIsRemember] = useState(false) const [isRemember, setIsRemember] = useState(false);
let qs = new URLSearchParams(location.search) const qs = new URLSearchParams(location.search);
let id = qs.get('id') const id = qs.get("id");
let host = qs.get('host') const host = qs.get("host");
let type = qs.get('type') const type = qs.get("type");
let params, event
try { let params;
params = JSON.parse(qs.get('params')) let event;
if (Object.keys(params).length === 0) params = null
else if (params.event) event = params.event
} catch (err) {
params = null
}
function authorizeHandler(accept) { try {
const conditions = isRemember ? {} : null params = JSON.parse(qs.get("params"));
return function (ev) { if (Object.keys(params).length === 0) params = null;
ev.preventDefault() else if (params.event) event = params.event;
browser.runtime.sendMessage({ } catch (err) {
prompt: true, params = null;
id, }
host,
type,
accept,
conditions
})
}
}
return ( function authorizeHandler(accept) {
<div className="w-screen h-screen flex flex-col items-center justify-center"> const conditions = isRemember ? {} : null;
<div className="p-8 shadow-primary border border-primary rounded-2xl max-w-xl mx-auto flex flex-col gap-5"> return (ev) => {
<div className="flex flex-col items-center gap-5"> ev.preventDefault();
<LogoIcon /> browser.runtime.sendMessage({
<div className="flex flex-col items-center text-center"> prompt: true,
<h1 className="font-semibold text-lg">{host}</h1> id,
<p> host,
is requesting your permission to <b>{PERMISSION_NAMES[type]}</b> type,
</p> accept,
</div> conditions,
</div> });
{params && ( };
<div className="flex flex-col gap-1"> }
<p>Now acting on</p>
<pre className="bg-muted px-2 rounded-xl overflow-scroll"> return (
<code>{JSON.stringify(event || params, null, 2)}</code> <div className="w-screen h-screen flex flex-col items-center justify-center">
</pre> <div className="p-8 shadow-primary border border-primary rounded-2xl max-w-xl mx-auto flex flex-col gap-5">
</div> <div className="flex flex-col items-center gap-5">
)} <LogoIcon />
<div className="flex flex-col gap-4"> <div className="flex flex-col items-center text-center">
<div className="flex items-center justify-center gap-2"> <h1 className="font-semibold text-lg">{host}</h1>
<Checkbox.Root <p>
id="remember" is requesting your permission to <b>{PERMISSION_NAMES[type]}</b>
className="flex h-6 w-6 appearance-none items-center justify-center rounded-lg bg-white outline-none border border-primary data-[state=checked]:bg-primary data-[state=checked]:border-secondary" </p>
onCheckedChange={setIsRemember} </div>
> </div>
<Checkbox.Indicator className="text-white"> {params && (
<svg <div className="flex flex-col gap-1">
xmlns="http://www.w3.org/2000/svg" <p>Now acting on</p>
fill="none" <pre className="bg-muted px-2 rounded-xl overflow-scroll">
viewBox="0 0 24 24" <code>{JSON.stringify(event || params, null, 2)}</code>
strokeWidth={1.5} </pre>
stroke="currentColor" </div>
className="w-4 h-4" )}
> <div className="flex flex-col gap-4">
<path <div className="flex items-center justify-center gap-2">
strokeLinecap="round" <Checkbox.Root
strokeLinejoin="round" id="remember"
d="M4.5 12.75l6 6 9-13.5" className="flex h-6 w-6 appearance-none items-center justify-center rounded-lg bg-white outline-none border border-primary data-[state=checked]:bg-primary data-[state=checked]:border-secondary"
/> onCheckedChange={setIsRemember}
</svg> >
</Checkbox.Indicator> <Checkbox.Indicator className="text-white">
</Checkbox.Root> <svg
<label htmlFor="remember" className="text-muted"> xmlns="http://www.w3.org/2000/svg"
Remember my preference forever fill="none"
</label> viewBox="0 0 24 24"
</div> strokeWidth={1.5}
<div className="flex gap-3"> stroke="currentColor"
<button className="w-4 h-4"
onClick={authorizeHandler(false)} >
className="flex-1 h-10 rounded-lg shadow-sm border border-primary inline-flex items-center justify-center font-semibold" <path
> strokeLinecap="round"
Reject strokeLinejoin="round"
</button> d="M4.5 12.75l6 6 9-13.5"
<button />
onClick={authorizeHandler(true)} </svg>
className="flex-1 h-10 rounded-lg shadow-sm border border-secondary bg-primary text-white inline-flex items-center justify-center font-semibold" </Checkbox.Indicator>
> </Checkbox.Root>
Authorize <label htmlFor="remember" className="text-muted">
</button> Remember my preference forever
</div> </label>
</div> </div>
{/* <div className="flex gap-3">
<div <button
style={{ type="button"
display: 'flex', onClick={authorizeHandler(false)}
flexWrap: 'wrap', className="flex-1 h-10 rounded-lg shadow-sm border border-primary inline-flex items-center justify-center font-semibold"
justifyContent: 'space-around' >
}} Reject
> </button>
<button <button
style={{marginTop: '5px'}} type="button"
onClick={authorizeHandler( onClick={authorizeHandler(true)}
true, className="flex-1 h-10 rounded-lg shadow-sm border border-secondary bg-primary text-white inline-flex items-center justify-center font-semibold"
{} // store this and answer true forever >
)} Authorize
> </button>
authorize forever </div>
</button> </div>
{event?.kind !== undefined && ( </div>
<button </div>
style={{marginTop: '5px'}} );
onClick={authorizeHandler(
true,
{kinds: {[event.kind]: true}} // store and always answer true for all events that match this condition
)}
>
authorize kind {event.kind} forever
</button>
)}
<button style={{marginTop: '5px'}} onClick={authorizeHandler(true)}>
authorize just this
</button>
{event?.kind !== undefined ? (
<button
style={{marginTop: '5px'}}
onClick={authorizeHandler(
false,
{kinds: {[event.kind]: true}} // idem
)}
>
reject kind {event.kind} forever
</button>
) : (
<button
style={{marginTop: '5px'}}
onClick={authorizeHandler(
false,
{} // idem
)}
>
reject forever
</button>
)}
<button style={{marginTop: '5px'}} onClick={authorizeHandler(false)}>
reject
</button>
</div>*/}
</div>
</div>
)
} }
render(<Prompt />, document.getElementById('main')) const container = document.getElementById("main");
const root = createRoot(container);
root.render(<Prompt />);

View File

@@ -2,6 +2,6 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
.data-\[state\=active\]\:text-primary[data-state=active] > .bg-muted { .data-\[state\=active\]\:text-primary[data-state="active"] > .bg-muted {
@apply bg-secondary @apply bg-secondary;
} }

View File

@@ -1,33 +1,31 @@
{ {
"license": "WTFPL", "license": "WTFPL",
"dependencies": { "dependencies": {
"@radix-ui/react-checkbox": "^1.1.3", "@radix-ui/react-checkbox": "^1.1.3",
"@radix-ui/react-tabs": "^1.1.2", "@radix-ui/react-tabs": "^1.1.2",
"async-mutex": "^0.3.2", "async-mutex": "^0.3.2",
"esbuild": "^0.14.54", "esbuild": "^0.14.54",
"eslint": "^8.57.1", "events": "^3.3.0",
"eslint-plugin-babel": "^5.3.1", "minidenticons": "^4.2.1",
"eslint-plugin-react": "^7.37.2", "nostr-tools": "^2.10.4",
"events": "^3.3.0", "react": "^19.0.0",
"minidenticons": "^4.2.1", "react-dom": "^19.0.0",
"nostr-tools": "^1.17.0", "react-native-svg": "^13.14.1",
"prettier": "^2.8.8", "react-qr-code": "^2.0.15",
"react": "^17.0.2", "use-boolean-state": "^1.0.2",
"react-dom": "^17.0.2", "use-debounce": "^7.0.1",
"react-native-svg": "^13.14.1", "webextension-polyfill": "^0.12.0"
"react-qr-code": "^2.0.15", },
"use-boolean-state": "^1.0.2", "scripts": {
"use-debounce": "^7.0.1", "dev": "./build.js; pnpm exec tailwindcss -i ./extension/style.css -o ./extension/build/style.css --watch",
"webextension-polyfill": "^0.8.0" "build": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css; ./build.js prod",
}, "package:chrome": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css --minify; ./build.js prod; cd extension/output; zip -r archive *; cd ../../; mv extension/output/archive.zip extension/releases/nostrconnect_chrome.zip",
"scripts": { "package:firefox": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css --minify; ./build.js prod firefox; cd extension/output; zip -r archive *; cd ../../; mv extension/output/archive.zip extension/releases/nostrconnect_firefox.xpi"
"dev": "./build.js; pnpm exec tailwindcss -i ./extension/style.css -o ./extension/build/style.css --watch", },
"build": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css; ./build.js prod", "devDependencies": {
"package:chrome": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css --minify; ./build.js prod; cd extension/output; zip -r archive *; cd ../../; mv extension/output/archive.zip extension/releases/nostrconnect_chrome.zip", "@biomejs/biome": "1.9.4",
"package:firefox": "pnpm exec tailwindcss -i ./extension/style.css -o ./extension/output/style.css --minify; ./build.js prod firefox; cd extension/output; zip -r archive *; cd ../../; mv extension/output/archive.zip extension/releases/nostrconnect_firefox.xpi" "@types/webextension-polyfill": "^0.12.1",
}, "esbuild-plugin-copy": "^2.1.1",
"devDependencies": { "tailwindcss": "^3.4.17"
"esbuild-plugin-copy": "^2.1.1", }
"tailwindcss": "^3.4.17"
}
} }

1847
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff