wip: update
This commit is contained in:
148
.eslintrc.json
148
.eslintrc.json
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
28
biome.json
Normal 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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,225 +1,227 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import { Mutex } from "async-mutex";
|
||||
import {
|
||||
validateEvent,
|
||||
getSignature,
|
||||
getEventHash,
|
||||
getPublicKey,
|
||||
nip19
|
||||
} from 'nostr-tools'
|
||||
import {nip04} from 'nostr-tools'
|
||||
import {Mutex} from 'async-mutex'
|
||||
getSignature,
|
||||
nip19,
|
||||
validateEvent,
|
||||
} from "nostr-tools";
|
||||
import { nip04 } from "nostr-tools";
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
import {
|
||||
NO_PERMISSIONS_REQUIRED,
|
||||
getPermissionStatus,
|
||||
showNotification,
|
||||
updatePermission,
|
||||
showNotification
|
||||
} from './common'
|
||||
} from "./common";
|
||||
|
||||
const {encrypt, decrypt} = nip04
|
||||
const { encrypt, decrypt } = nip04;
|
||||
|
||||
let openPrompt = null
|
||||
let promptMutex = new Mutex()
|
||||
let releasePromptMutex = () => {}
|
||||
let openPrompt = null;
|
||||
const promptMutex = new Mutex();
|
||||
let releasePromptMutex = () => {};
|
||||
|
||||
browser.runtime.onInstalled.addListener((_, __, reason) => {
|
||||
if (reason === 'install') browser.runtime.openOptionsPage()
|
||||
})
|
||||
if (reason === "install") browser.runtime.openOptionsPage();
|
||||
});
|
||||
|
||||
browser.runtime.onMessage.addListener(async (req, sender) => {
|
||||
let {prompt} = req
|
||||
const { prompt } = req;
|
||||
|
||||
if (prompt) {
|
||||
handlePromptMessage(req, sender)
|
||||
handlePromptMessage(req, sender);
|
||||
} else {
|
||||
return handleContentScriptMessage(req)
|
||||
return handleContentScriptMessage(req);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
browser.runtime.onMessageExternal.addListener(
|
||||
async ({type, params}, sender) => {
|
||||
let extensionId = new URL(sender.url).host
|
||||
return handleContentScriptMessage({type, params, host: extensionId})
|
||||
}
|
||||
)
|
||||
async ({ type, params }, sender) => {
|
||||
const extensionId = new URL(sender.url).host;
|
||||
return handleContentScriptMessage({ type, params, host: extensionId });
|
||||
},
|
||||
);
|
||||
|
||||
browser.windows.onRemoved.addListener(windowId => {
|
||||
browser.windows.onRemoved.addListener((windowId) => {
|
||||
if (openPrompt) {
|
||||
// calling this with a simple "no" response will not store anything, so it's fine
|
||||
// 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]) {
|
||||
// authorized, and we won't do anything with private key here, so do a separate handler
|
||||
switch (type) {
|
||||
case 'replaceURL': {
|
||||
let {protocol_handler: ph} = await browser.storage.local.get([
|
||||
'protocol_handler'
|
||||
])
|
||||
if (!ph) return false
|
||||
case "replaceURL": {
|
||||
const { protocol_handler: ph } = await browser.storage.local.get([
|
||||
"protocol_handler",
|
||||
]);
|
||||
if (!ph) return false;
|
||||
|
||||
let {url} = params
|
||||
let raw = url.split('nostr:')[1]
|
||||
let {type, data} = nip19.decode(raw)
|
||||
let replacements = {
|
||||
const { url } = params;
|
||||
const raw = url.split("nostr:")[1];
|
||||
const { type, data } = nip19.decode(raw);
|
||||
const replacements = {
|
||||
raw,
|
||||
hrp: type,
|
||||
hex:
|
||||
type === 'npub' || type === 'note'
|
||||
type === "npub" || type === "note"
|
||||
? data
|
||||
: type === 'nprofile'
|
||||
: type === "nprofile"
|
||||
? data.pubkey
|
||||
: type === 'nevent'
|
||||
: type === "nevent"
|
||||
? data.id
|
||||
: null,
|
||||
p_or_e: {npub: 'p', note: 'e', nprofile: 'p', nevent: 'e'}[type],
|
||||
u_or_n: {npub: 'u', note: 'n', nprofile: 'u', nevent: 'n'}[type],
|
||||
relay0: type === 'nprofile' ? data.relays[0] : null,
|
||||
relay1: type === 'nprofile' ? data.relays[1] : null,
|
||||
relay2: type === 'nprofile' ? data.relays[2] : null
|
||||
}
|
||||
let result = ph
|
||||
p_or_e: { npub: "p", note: "e", nprofile: "p", nevent: "e" }[type],
|
||||
u_or_n: { npub: "u", note: "n", nprofile: "u", nevent: "n" }[type],
|
||||
relay0: type === "nprofile" ? data.relays[0] : null,
|
||||
relay1: type === "nprofile" ? data.relays[1] : null,
|
||||
relay2: type === "nprofile" ? data.relays[2] : null,
|
||||
};
|
||||
let result = ph;
|
||||
// biome-ignore lint/complexity/noForEach: TODO: fix this
|
||||
Object.entries(replacements).forEach(([pattern, value]) => {
|
||||
result = result.replace(new RegExp(`{ *${pattern} *}`, 'g'), value)
|
||||
})
|
||||
result = result.replace(new RegExp(`{ *${pattern} *}`, "g"), value);
|
||||
});
|
||||
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
return;
|
||||
} else {
|
||||
// acquire mutex here before reading policies
|
||||
releasePromptMutex = await promptMutex.acquire()
|
||||
releasePromptMutex = await promptMutex.acquire();
|
||||
|
||||
let allowed = await getPermissionStatus(
|
||||
const allowed = await getPermissionStatus(
|
||||
host,
|
||||
type,
|
||||
type === 'signEvent' ? params.event : undefined
|
||||
)
|
||||
type === "signEvent" ? params.event : undefined,
|
||||
);
|
||||
|
||||
if (allowed === true) {
|
||||
// authorized, proceed
|
||||
releasePromptMutex()
|
||||
showNotification(host, allowed, type, params)
|
||||
releasePromptMutex();
|
||||
showNotification(host, allowed, type, params);
|
||||
} else if (allowed === false) {
|
||||
// denied, just refuse immediately
|
||||
releasePromptMutex()
|
||||
showNotification(host, allowed, type, params)
|
||||
releasePromptMutex();
|
||||
showNotification(host, allowed, type, params);
|
||||
return {
|
||||
error: 'denied'
|
||||
}
|
||||
error: "denied",
|
||||
};
|
||||
} else {
|
||||
// ask for authorization
|
||||
try {
|
||||
let id = Math.random().toString().slice(4)
|
||||
let qs = new URLSearchParams({
|
||||
const id = Math.random().toString().slice(4);
|
||||
const qs = new URLSearchParams({
|
||||
host,
|
||||
id,
|
||||
params: JSON.stringify(params),
|
||||
type
|
||||
})
|
||||
type,
|
||||
});
|
||||
|
||||
// prompt will be resolved with true or false
|
||||
let accept = await new Promise((resolve, reject) => {
|
||||
openPrompt = {resolve, reject}
|
||||
const accept = await new Promise((resolve, reject) => {
|
||||
openPrompt = { resolve, reject };
|
||||
const url = `${browser.runtime.getURL(
|
||||
'prompt.html'
|
||||
)}?${qs.toString()}`
|
||||
"prompt.html",
|
||||
)}?${qs.toString()}`;
|
||||
|
||||
if (browser.windows) {
|
||||
browser.windows.create({
|
||||
url,
|
||||
type: 'popup',
|
||||
type: "popup",
|
||||
width: 600,
|
||||
height: 600
|
||||
})
|
||||
height: 600,
|
||||
});
|
||||
} else {
|
||||
browser.tabs.create({
|
||||
url,
|
||||
active: true
|
||||
})
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// denied, stop here
|
||||
if (!accept) return {error: 'denied'}
|
||||
if (!accept) return { error: "denied" };
|
||||
} catch (err) {
|
||||
// errored, stop here
|
||||
releasePromptMutex()
|
||||
releasePromptMutex();
|
||||
return {
|
||||
error: `error: ${err}`
|
||||
}
|
||||
error: `error: ${err}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return {error: 'no private key found'}
|
||||
return { error: "no private key found" };
|
||||
}
|
||||
|
||||
let sk = results.private_key
|
||||
const sk = results.private_key;
|
||||
|
||||
try {
|
||||
switch (type) {
|
||||
case 'getPublicKey': {
|
||||
return getPublicKey(sk)
|
||||
case "getPublicKey": {
|
||||
return getPublicKey(sk);
|
||||
}
|
||||
case 'getRelays': {
|
||||
let results = await browser.storage.local.get('relays')
|
||||
return results.relays || {}
|
||||
case "getRelays": {
|
||||
const results = await browser.storage.local.get("relays");
|
||||
return results.relays || {};
|
||||
}
|
||||
case 'signEvent': {
|
||||
let {event} = params
|
||||
case "signEvent": {
|
||||
const { event } = params;
|
||||
|
||||
if (!event.pubkey) event.pubkey = getPublicKey(sk)
|
||||
if (!event.id) event.id = getEventHash(event)
|
||||
if (!validateEvent(event)) return {error: {message: 'invalid event'}}
|
||||
if (!event.pubkey) event.pubkey = getPublicKey(sk);
|
||||
if (!event.id) event.id = getEventHash(event);
|
||||
if (!validateEvent(event))
|
||||
return { error: { message: "invalid event" } };
|
||||
|
||||
event.sig = await getSignature(event, sk)
|
||||
return event
|
||||
event.sig = await getSignature(event, sk);
|
||||
return event;
|
||||
}
|
||||
case 'nip04.encrypt': {
|
||||
let {peer, plaintext} = params
|
||||
return encrypt(sk, peer, plaintext)
|
||||
case "nip04.encrypt": {
|
||||
const { peer, plaintext } = params;
|
||||
return encrypt(sk, peer, plaintext);
|
||||
}
|
||||
case 'nip04.decrypt': {
|
||||
let {peer, ciphertext} = params
|
||||
return decrypt(sk, peer, ciphertext)
|
||||
case "nip04.decrypt": {
|
||||
const { peer, ciphertext } = params;
|
||||
return decrypt(sk, peer, ciphertext);
|
||||
}
|
||||
}
|
||||
} 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
|
||||
openPrompt?.resolve?.(accept)
|
||||
openPrompt?.resolve?.(accept);
|
||||
|
||||
// update policies
|
||||
if (conditions) {
|
||||
await updatePermission(host, type, accept, conditions)
|
||||
await updatePermission(host, type, accept, conditions);
|
||||
}
|
||||
|
||||
// cleanup this
|
||||
openPrompt = null
|
||||
openPrompt = null;
|
||||
|
||||
// release mutex here after updating policies
|
||||
releasePromptMutex()
|
||||
releasePromptMutex();
|
||||
|
||||
// close prompt
|
||||
if (sender) {
|
||||
if (browser.windows) {
|
||||
browser.windows.remove(sender.tab.windowId)
|
||||
browser.windows.remove(sender.tab.windowId);
|
||||
} else {
|
||||
// Android Firefox
|
||||
browser.tabs.remove(sender.tab.id)
|
||||
browser.tabs.remove(sender.tab.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
1137
extension/build/style.css
Normal file
1137
extension/build/style.css
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,116 +1,118 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
export const NO_PERMISSIONS_REQUIRED = {
|
||||
replaceURL: true
|
||||
}
|
||||
replaceURL: true,
|
||||
};
|
||||
|
||||
export const PERMISSION_NAMES = Object.fromEntries([
|
||||
['getPublicKey', 'read your public key'],
|
||||
['getRelays', 'read your list of preferred relays'],
|
||||
['signEvent', 'sign events using your private key'],
|
||||
['nip04.encrypt', 'encrypt messages to peers'],
|
||||
['nip04.decrypt', 'decrypt messages from peers']
|
||||
])
|
||||
["getPublicKey", "read your public key"],
|
||||
["getRelays", "read your list of preferred relays"],
|
||||
["signEvent", "sign events using your private key"],
|
||||
["nip04.encrypt", "encrypt messages to peers"],
|
||||
["nip04.decrypt", "decrypt messages from peers"],
|
||||
]);
|
||||
|
||||
function matchConditions(conditions, event) {
|
||||
if (conditions?.kinds) {
|
||||
if (event.kind in conditions.kinds) return true
|
||||
else return false
|
||||
if (event.kind in conditions.kinds) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
return true
|
||||
return true;
|
||||
}
|
||||
|
||||
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++) {
|
||||
let accept = answers[i]
|
||||
let {conditions} = policies?.[host]?.[accept]?.[type] || {}
|
||||
const accept = answers[i];
|
||||
const { conditions } = policies?.[host]?.[accept]?.[type] || {};
|
||||
|
||||
if (conditions) {
|
||||
if (type === 'signEvent') {
|
||||
if (type === "signEvent") {
|
||||
if (matchConditions(conditions, event)) {
|
||||
return accept // may be true or false
|
||||
return accept; // may be true or false
|
||||
} else {
|
||||
// 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
|
||||
continue
|
||||
// biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
return accept // may be true or false
|
||||
return accept; // may be true or false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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 (Object.keys(conditions).length === 0) {
|
||||
conditions = {}
|
||||
conditions = {};
|
||||
} else {
|
||||
// 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
|
||||
})
|
||||
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
|
||||
let other = !accept
|
||||
let reverse = policies?.[host]?.[other]?.[type]
|
||||
const other = !accept;
|
||||
const reverse = policies?.[host]?.[other]?.[type];
|
||||
if (
|
||||
reverse &&
|
||||
JSON.stringify(reverse.conditions) === JSON.stringify(conditions)
|
||||
) {
|
||||
delete policies[host][other][type]
|
||||
delete policies[host][other][type];
|
||||
}
|
||||
|
||||
// insert our new policy
|
||||
policies[host] = policies[host] || {}
|
||||
policies[host][accept] = policies[host][accept] || {}
|
||||
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)
|
||||
}
|
||||
created_at: Math.round(Date.now() / 1000),
|
||||
};
|
||||
|
||||
browser.storage.local.set({policies})
|
||||
browser.storage.local.set({ policies });
|
||||
}
|
||||
|
||||
export async function removePermissions(host, accept, type) {
|
||||
let {policies = {}} = await browser.storage.local.get('policies')
|
||||
delete policies[host]?.[accept]?.[type]
|
||||
browser.storage.local.set({policies})
|
||||
const { policies = {} } = await browser.storage.local.get("policies");
|
||||
delete policies[host]?.[accept]?.[type];
|
||||
browser.storage.local.set({ policies });
|
||||
}
|
||||
|
||||
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) {
|
||||
let action = answer ? 'allowed' : 'denied'
|
||||
const action = answer ? "allowed" : "denied";
|
||||
browser.notifications.create(undefined, {
|
||||
type: 'basic',
|
||||
type: "basic",
|
||||
title: `${type} ${action} for ${host}`,
|
||||
message: JSON.stringify(
|
||||
params?.event
|
||||
? {
|
||||
kind: params.event.kind,
|
||||
content: params.event.content,
|
||||
tags: params.event.tags
|
||||
tags: params.event.tags,
|
||||
}
|
||||
: params,
|
||||
null,
|
||||
2
|
||||
2,
|
||||
),
|
||||
iconUrl: 'icons/48x48.png'
|
||||
})
|
||||
iconUrl: "icons/48x48.png",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
let script = document.createElement('script')
|
||||
script.setAttribute('async', 'false')
|
||||
script.setAttribute('type', 'text/javascript')
|
||||
script.setAttribute('src', browser.runtime.getURL('nostr-provider.js'))
|
||||
document.head.appendChild(script)
|
||||
const script = document.createElement("script");
|
||||
script.setAttribute("async", "false");
|
||||
script.setAttribute("type", "text/javascript");
|
||||
script.setAttribute("src", browser.runtime.getURL("nostr-provider.js"));
|
||||
document.head.appendChild(script);
|
||||
|
||||
// listen for messages from that script
|
||||
window.addEventListener('message', async message => {
|
||||
if (message.source !== window) return
|
||||
if (!message.data) return
|
||||
if (!message.data.params) return
|
||||
if (message.data.ext !== EXTENSION) return
|
||||
window.addEventListener("message", async (message) => {
|
||||
if (message.source !== window) return;
|
||||
if (!message.data) return;
|
||||
if (!message.data.params) return;
|
||||
if (message.data.ext !== EXTENSION) return;
|
||||
|
||||
// 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
|
||||
})
|
||||
host: location.host,
|
||||
});
|
||||
} catch (error) {
|
||||
response = {error}
|
||||
response = { error };
|
||||
}
|
||||
|
||||
// return response
|
||||
window.postMessage(
|
||||
{id: message.data.id, ext: EXTENSION, response},
|
||||
message.origin
|
||||
)
|
||||
})
|
||||
{ id: message.data.id, ext: EXTENSION, response },
|
||||
message.origin,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react'
|
||||
import React from "react";
|
||||
|
||||
export function LogoIcon() {
|
||||
return (
|
||||
@@ -9,7 +9,7 @@ export function LogoIcon() {
|
||||
fill="none"
|
||||
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
|
||||
width="55"
|
||||
height="55"
|
||||
@@ -18,7 +18,7 @@ export function LogoIcon() {
|
||||
stroke="#5A41F4"
|
||||
strokeOpacity="0.25"
|
||||
rx="15.5"
|
||||
></rect>
|
||||
/>
|
||||
<rect
|
||||
width="39"
|
||||
height="39"
|
||||
@@ -26,17 +26,10 @@ export function LogoIcon() {
|
||||
y="8.5"
|
||||
fill="url(#paint0_linear_24_2379)"
|
||||
rx="19.5"
|
||||
></rect>
|
||||
<rect
|
||||
width="39"
|
||||
height="39"
|
||||
x="8.5"
|
||||
y="8.5"
|
||||
stroke="#6149F6"
|
||||
rx="19.5"
|
||||
></rect>
|
||||
/>
|
||||
<rect width="39" height="39" x="8.5" y="8.5" stroke="#6149F6" rx="19.5" />
|
||||
<g fill="#fff" stroke="#6149F6" clipPath="url(#clip0_24_2379)">
|
||||
<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>
|
||||
<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" />
|
||||
</g>
|
||||
<defs>
|
||||
<linearGradient
|
||||
@@ -47,19 +40,15 @@ export function LogoIcon() {
|
||||
y2="48"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#8E7CFF"></stop>
|
||||
<stop offset="1" stopColor="#5A41F4"></stop>
|
||||
<stop stopColor="#8E7CFF" />
|
||||
<stop offset="1" stopColor="#5A41F4" />
|
||||
</linearGradient>
|
||||
<clipPath id="clip0_24_2379">
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M0 0H24V24H0z"
|
||||
transform="translate(16 15)"
|
||||
></path>
|
||||
<path fill="#fff" d="M0 0H24V24H0z" transform="translate(16 15)" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsIcon(props) {
|
||||
@@ -83,5 +72,5 @@ export function SettingsIcon(props) {
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,66 +1,61 @@
|
||||
const EXTENSION = 'nostrconnect'
|
||||
const EXTENSION = "nostrconnect";
|
||||
|
||||
window.nostr = {
|
||||
_requests: {},
|
||||
_pubkey: null,
|
||||
|
||||
async getPublicKey() {
|
||||
if (this._pubkey) return this._pubkey
|
||||
this._pubkey = await this._call('getPublicKey', {})
|
||||
return this._pubkey
|
||||
if (this._pubkey) return this._pubkey;
|
||||
this._pubkey = await this._call("getPublicKey", {});
|
||||
return this._pubkey;
|
||||
},
|
||||
|
||||
async signEvent(event) {
|
||||
return this._call('signEvent', {event})
|
||||
return this._call("signEvent", { event });
|
||||
},
|
||||
|
||||
async getRelays() {
|
||||
return this._call('getRelays', {})
|
||||
return this._call("getRelays", {});
|
||||
},
|
||||
|
||||
nip04: {
|
||||
async encrypt(peer, plaintext) {
|
||||
return window.nostr._call('nip04.encrypt', {peer, plaintext})
|
||||
return window.nostr._call("nip04.encrypt", { peer, plaintext });
|
||||
},
|
||||
|
||||
async decrypt(peer, ciphertext) {
|
||||
return window.nostr._call('nip04.decrypt', {peer, ciphertext})
|
||||
}
|
||||
return window.nostr._call("nip04.decrypt", { peer, ciphertext });
|
||||
},
|
||||
},
|
||||
|
||||
_call(type, params) {
|
||||
let id = Math.random().toString().slice(-4)
|
||||
const id = Math.random().toString().slice(-4);
|
||||
console.log(
|
||||
'%c[nostrconnect:%c' +
|
||||
id +
|
||||
'%c]%c calling %c' +
|
||||
type +
|
||||
'%c with %c' +
|
||||
JSON.stringify(params || {}),
|
||||
'background-color:#f1b912;font-weight:bold;color:white',
|
||||
'background-color:#f1b912;font-weight:bold;color:#a92727',
|
||||
'background-color:#f1b912;color:white;font-weight:bold',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#08589d;font-family:monospace',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#90b12d;font-family:monospace'
|
||||
)
|
||||
`%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`,
|
||||
"background-color:#f1b912;font-weight:bold;color:white",
|
||||
"background-color:#f1b912;font-weight:bold;color:#a92727",
|
||||
"background-color:#f1b912;color:white;font-weight:bold",
|
||||
"color:auto",
|
||||
"font-weight:bold;color:#08589d;font-family:monospace",
|
||||
"color:auto",
|
||||
"font-weight:bold;color:#90b12d;font-family:monospace",
|
||||
);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._requests[id] = {resolve, reject}
|
||||
this._requests[id] = { resolve, reject };
|
||||
window.postMessage(
|
||||
{
|
||||
id,
|
||||
ext: EXTENSION,
|
||||
type,
|
||||
params
|
||||
params,
|
||||
},
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
"*",
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
window.addEventListener('message', message => {
|
||||
window.addEventListener("message", (message) => {
|
||||
if (
|
||||
!message.data ||
|
||||
message.data.response === null ||
|
||||
@@ -68,47 +63,46 @@ window.addEventListener('message', message => {
|
||||
message.data.ext !== EXTENSION ||
|
||||
!window.nostr._requests[message.data.id]
|
||||
)
|
||||
return
|
||||
return;
|
||||
|
||||
if (message.data.response.error) {
|
||||
let error = new Error(
|
||||
`${EXTENSION}: ` + message.data.response.error.message
|
||||
)
|
||||
error.stack = message.data.response.error.stack
|
||||
window.nostr._requests[message.data.id].reject(error)
|
||||
const error = new Error(
|
||||
`${EXTENSION}: ${message.data.response.error.message}`,
|
||||
);
|
||||
error.stack = message.data.response.error.stack;
|
||||
window.nostr._requests[message.data.id].reject(error);
|
||||
} else {
|
||||
window.nostr._requests[message.data.id].resolve(message.data.response)
|
||||
window.nostr._requests[message.data.id].resolve(message.data.response);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'%c[nostrconnect:%c' +
|
||||
message.data.id +
|
||||
'%c]%c result: %c' +
|
||||
JSON.stringify(
|
||||
message?.data?.response || message?.data?.response?.error?.message || {}
|
||||
),
|
||||
'background-color:#f1b912;font-weight:bold;color:white',
|
||||
'background-color:#f1b912;font-weight:bold;color:#a92727',
|
||||
'background-color:#f1b912;color:white;font-weight:bold',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#08589d'
|
||||
)
|
||||
`%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify(
|
||||
message?.data?.response || message?.data?.response?.error?.message || {},
|
||||
)}`,
|
||||
"background-color:#f1b912;font-weight:bold;color:white",
|
||||
"background-color:#f1b912;font-weight:bold;color:#a92727",
|
||||
"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
|
||||
let replacing = null
|
||||
document.addEventListener('mousedown', replaceNostrSchemeLink)
|
||||
let replacing = null;
|
||||
document.addEventListener("mousedown", replaceNostrSchemeLink);
|
||||
async function replaceNostrSchemeLink(e) {
|
||||
if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return
|
||||
if (replacing === false) return
|
||||
if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return;
|
||||
if (replacing === false) return;
|
||||
|
||||
let response = await window.nostr._call('replaceURL', {url: e.target.href})
|
||||
const response = await window.nostr._call("replaceURL", {
|
||||
url: e.target.href,
|
||||
});
|
||||
if (response === false) {
|
||||
replacing = false
|
||||
return
|
||||
replacing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
e.target.href = response
|
||||
e.target.href = response;
|
||||
}
|
||||
|
||||
@@ -1,83 +1,87 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import React, {useState, useCallback, useEffect} from 'react'
|
||||
import {render} from 'react-dom'
|
||||
import {generatePrivateKey, nip19} from 'nostr-tools'
|
||||
import QRCode from 'react-qr-code'
|
||||
import * as Tabs from '@radix-ui/react-tabs'
|
||||
import {LogoIcon} from './icons'
|
||||
import {removePermissions} from './common'
|
||||
import * as Checkbox from '@radix-ui/react-checkbox'
|
||||
import * as Checkbox from "@radix-ui/react-checkbox";
|
||||
import * as Tabs from "@radix-ui/react-tabs";
|
||||
import { generatePrivateKey, nip19 } from "nostr-tools";
|
||||
import React, { useState, useCallback, useEffect } from "react";
|
||||
import QRCode from "react-qr-code";
|
||||
import browser from "webextension-polyfill";
|
||||
import { removePermissions } from "./common";
|
||||
import { LogoIcon } from "./icons";
|
||||
|
||||
function Options() {
|
||||
let [privKey, setPrivKey] = useState('')
|
||||
let [relays, setRelays] = useState([])
|
||||
let [newRelayURL, setNewRelayURL] = useState('')
|
||||
let [policies, setPermissions] = useState([])
|
||||
let [protocolHandler, setProtocolHandler] = useState('https://njump.me/{raw}')
|
||||
let [hidingPrivateKey, hidePrivateKey] = useState(true)
|
||||
let [showNotifications, setNotifications] = useState(false)
|
||||
let [messages, setMessages] = useState([])
|
||||
let [handleNostrLinks, setHandleNostrLinks] = useState(false)
|
||||
let [showProtocolHandlerHelp, setShowProtocolHandlerHelp] = useState(false)
|
||||
let [unsavedChanges, setUnsavedChanges] = useState([])
|
||||
const [privKey, setPrivKey] = useState("");
|
||||
const [relays, setRelays] = useState([]);
|
||||
const [newRelayURL, setNewRelayURL] = useState("");
|
||||
const [policies, setPermissions] = useState([]);
|
||||
const [protocolHandler, setProtocolHandler] = useState(
|
||||
"https://njump.me/{raw}",
|
||||
);
|
||||
const [hidingPrivateKey, hidePrivateKey] = useState(true);
|
||||
const [showNotifications, setNotifications] = useState(false);
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [handleNostrLinks, setHandleNostrLinks] = useState(false);
|
||||
const [showProtocolHandlerHelp, setShowProtocolHandlerHelp] = useState(false);
|
||||
const [unsavedChanges, setUnsavedChanges] = useState([]);
|
||||
|
||||
const showMessage = useCallback(msg => {
|
||||
messages.push(msg)
|
||||
setMessages(messages)
|
||||
setTimeout(() => setMessages([]), 3000)
|
||||
})
|
||||
const showMessage = useCallback((msg) => {
|
||||
messages.push(msg);
|
||||
setMessages(messages);
|
||||
setTimeout(() => setMessages([]), 3000);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
browser.storage.local
|
||||
.get(['private_key', 'relays', 'protocol_handler', 'notifications'])
|
||||
.then(results => {
|
||||
.get(["private_key", "relays", "protocol_handler", "notifications"])
|
||||
.then((results) => {
|
||||
if (results.private_key) {
|
||||
setPrivKey(nip19.nsecEncode(results.private_key))
|
||||
setPrivKey(nip19.nsecEncode(results.private_key));
|
||||
}
|
||||
if (results.relays) {
|
||||
let relaysList = []
|
||||
for (let url in results.relays) {
|
||||
const relaysList = [];
|
||||
for (const url in results.relays) {
|
||||
relaysList.push({
|
||||
url,
|
||||
policy: results.relays[url]
|
||||
})
|
||||
policy: results.relays[url],
|
||||
});
|
||||
}
|
||||
setRelays(relaysList)
|
||||
setRelays(relaysList);
|
||||
}
|
||||
if (results.protocol_handler) {
|
||||
setProtocolHandler(results.protocol_handler)
|
||||
setHandleNostrLinks(true)
|
||||
setShowProtocolHandlerHelp(false)
|
||||
setProtocolHandler(results.protocol_handler);
|
||||
setHandleNostrLinks(true);
|
||||
setShowProtocolHandlerHelp(false);
|
||||
}
|
||||
if (results.notifications) {
|
||||
setNotifications(true)
|
||||
setNotifications(true);
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadPermissions()
|
||||
}, [])
|
||||
loadPermissions();
|
||||
}, []);
|
||||
|
||||
async function loadPermissions() {
|
||||
let {policies = {}} = await browser.storage.local.get('policies')
|
||||
let list = []
|
||||
const { policies = {} } = await browser.storage.local.get("policies");
|
||||
const list = [];
|
||||
|
||||
// biome-ignore lint/complexity/noForEach: TODO: fix this
|
||||
Object.entries(policies).forEach(([host, accepts]) => {
|
||||
// biome-ignore lint/complexity/noForEach: TODO: fix this
|
||||
Object.entries(accepts).forEach(([accept, types]) => {
|
||||
Object.entries(types).forEach(([type, {conditions, created_at}]) => {
|
||||
// biome-ignore lint/complexity/noForEach: TODO: fix this
|
||||
Object.entries(types).forEach(([type, { conditions, created_at }]) => {
|
||||
list.push({
|
||||
host,
|
||||
type,
|
||||
accept,
|
||||
conditions,
|
||||
created_at
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
created_at,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
setPermissions(list)
|
||||
setPermissions(list);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -96,7 +100,7 @@ function Options() {
|
||||
<div>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type={hidingPrivateKey ? 'password' : 'text'}
|
||||
type={hidingPrivateKey ? "password" : "text"}
|
||||
value={privKey}
|
||||
onChange={handleKeyChange}
|
||||
className="flex-1 h-9 bg-transparent border border-primary px-3 py-1 rounded-lg"
|
||||
@@ -146,7 +150,7 @@ function Options() {
|
||||
<QRCode
|
||||
size={256}
|
||||
value={privKey.toUpperCase()}
|
||||
viewBox={`0 0 256 256`}
|
||||
viewBox="0 0 256 256"
|
||||
className="w-full max-w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -178,8 +182,8 @@ function Options() {
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="font-semibold text-base">Preferred Relays:</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{relays.map(({url, policy}, i) => (
|
||||
<div key={i} className="flex items-center gap-4">
|
||||
{relays.map(({ url, policy }, i) => (
|
||||
<div key={url} className="flex items-center gap-4">
|
||||
<input
|
||||
value={url}
|
||||
onChange={changeRelayURL.bind(null, i)}
|
||||
@@ -193,7 +197,7 @@ function Options() {
|
||||
onCheckedChange={toggleRelayPolicy.bind(
|
||||
null,
|
||||
i,
|
||||
'read'
|
||||
"read",
|
||||
)}
|
||||
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"
|
||||
>
|
||||
@@ -228,7 +232,7 @@ function Options() {
|
||||
onCheckedChange={toggleRelayPolicy.bind(
|
||||
null,
|
||||
i,
|
||||
'write'
|
||||
"write",
|
||||
)}
|
||||
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"
|
||||
>
|
||||
@@ -258,6 +262,7 @@ function Options() {
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={removeRelay.bind(null, i)}
|
||||
className="shrink-0 px-3 w-24 h-9 font-semibold border border-primary shadow-sm rounded-lg inline-flex items-center justify-center disabled:text-muted"
|
||||
>
|
||||
@@ -268,14 +273,15 @@ function Options() {
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={newRelayURL}
|
||||
onChange={e => setNewRelayURL(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') addNewRelay()
|
||||
onChange={(e) => setNewRelayURL(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") addNewRelay();
|
||||
}}
|
||||
placeholder="wss://"
|
||||
className="flex-1 h-9 bg-transparent border px-3 py-1 border-primary rounded-lg placeholder:text-muted"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!newRelayURL}
|
||||
onClick={addNewRelay}
|
||||
className="shrink-0 px-3 w-24 h-9 font-semibold border border-primary shadow-sm rounded-lg inline-flex items-center justify-center disabled:text-muted"
|
||||
@@ -312,12 +318,12 @@ function Options() {
|
||||
<th className="text-left border-b-8 border-transparent">
|
||||
Since
|
||||
</th>
|
||||
<th></th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{policies.map(
|
||||
({host, type, accept, conditions, created_at}) => (
|
||||
({ host, type, accept, conditions, created_at }) => (
|
||||
<tr
|
||||
key={
|
||||
host + type + accept + JSON.stringify(conditions)
|
||||
@@ -326,24 +332,25 @@ function Options() {
|
||||
<td className="font-semibold">{host}</td>
|
||||
<td className="text-muted">{type}</td>
|
||||
<td className="text-muted">
|
||||
{accept === 'true' ? 'allow' : 'deny'}
|
||||
{accept === "true" ? "allow" : "deny"}
|
||||
</td>
|
||||
<td className="text-muted">
|
||||
{conditions.kinds
|
||||
? `kinds: ${Object.keys(conditions.kinds).join(
|
||||
', '
|
||||
", ",
|
||||
)}`
|
||||
: 'always'}
|
||||
: "always"}
|
||||
</td>
|
||||
<td className="text-muted">
|
||||
{new Date(created_at * 1000)
|
||||
.toISOString()
|
||||
.split('.')[0]
|
||||
.split('T')
|
||||
.join(' ')}
|
||||
.split(".")[0]
|
||||
.split("T")
|
||||
.join(" ")}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRevoke}
|
||||
data-host={host}
|
||||
data-accept={accept}
|
||||
@@ -354,14 +361,14 @@ function Options() {
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
),
|
||||
)}
|
||||
{!policies.length && (
|
||||
<tr>
|
||||
{Array(5)
|
||||
.fill('N/A')
|
||||
.map((v, i) => (
|
||||
<td key={i}>{v}</td>
|
||||
.fill("N/A")
|
||||
.map((v) => (
|
||||
<td key={v}>{v}</td>
|
||||
))}
|
||||
</tr>
|
||||
)}
|
||||
@@ -458,7 +465,10 @@ function Options() {
|
||||
onChange={handleChangeProtocolHandler}
|
||||
/>
|
||||
{!showProtocolHandlerHelp && (
|
||||
<button onClick={changeShowProtocolHandlerHelp}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={changeShowProtocolHandlerHelp}
|
||||
>
|
||||
?
|
||||
</button>
|
||||
)}
|
||||
@@ -487,6 +497,7 @@ examples:
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!unsavedChanges.length}
|
||||
onClick={saveChanges}
|
||||
className="w-full h-10 bg-primary rounded-xl font-bold inline-flex items-center justify-center text-white disabled:cursor-not-allowed disabled:opacity-70 transform active:translate-y-1 transition-transform ease-in-out duration-75"
|
||||
@@ -495,59 +506,59 @@ examples:
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
async function handleKeyChange(e) {
|
||||
let key = e.target.value.toLowerCase().trim()
|
||||
setPrivKey(key)
|
||||
addUnsavedChanges('private_key')
|
||||
const key = e.target.value.toLowerCase().trim();
|
||||
setPrivKey(key);
|
||||
addUnsavedChanges("private_key");
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
setPrivKey(nip19.nsecEncode(generatePrivateKey()))
|
||||
addUnsavedChanges('private_key')
|
||||
setPrivKey(nip19.nsecEncode(generatePrivateKey()));
|
||||
addUnsavedChanges("private_key");
|
||||
}
|
||||
|
||||
async function saveKey() {
|
||||
if (!isKeyValid()) {
|
||||
showMessage('PRIVATE KEY IS INVALID! did not save private key.')
|
||||
return
|
||||
showMessage("PRIVATE KEY IS INVALID! did not save private key.");
|
||||
return;
|
||||
}
|
||||
|
||||
let hexOrEmptyKey = privKey
|
||||
let hexOrEmptyKey = privKey;
|
||||
|
||||
try {
|
||||
let {type, data} = nip19.decode(privKey)
|
||||
if (type === 'nsec') hexOrEmptyKey = data
|
||||
const { type, data } = nip19.decode(privKey);
|
||||
if (type === "nsec") hexOrEmptyKey = data;
|
||||
} catch (_) {}
|
||||
|
||||
await browser.storage.local.set({
|
||||
private_key: hexOrEmptyKey
|
||||
})
|
||||
private_key: hexOrEmptyKey,
|
||||
});
|
||||
|
||||
if (hexOrEmptyKey !== '') {
|
||||
setPrivKey(nip19.nsecEncode(hexOrEmptyKey))
|
||||
if (hexOrEmptyKey !== "") {
|
||||
setPrivKey(nip19.nsecEncode(hexOrEmptyKey));
|
||||
}
|
||||
|
||||
showMessage('saved private key!')
|
||||
showMessage("saved private key!");
|
||||
}
|
||||
|
||||
function isKeyValid() {
|
||||
if (privKey === '') return true
|
||||
if (privKey.match(/^[a-f0-9]{64}$/)) return true
|
||||
if (privKey === "") return true;
|
||||
if (privKey.match(/^[a-f0-9]{64}$/)) return true;
|
||||
try {
|
||||
if (nip19.decode(privKey).type === 'nsec') return true
|
||||
if (nip19.decode(privKey).type === "nsec") return true;
|
||||
} catch (_) {}
|
||||
return false
|
||||
return false;
|
||||
}
|
||||
|
||||
function changeRelayURL(i, ev) {
|
||||
setRelays([
|
||||
...relays.slice(0, i),
|
||||
{url: ev.target.value, policy: relays[i].policy},
|
||||
...relays.slice(i + 1)
|
||||
])
|
||||
addUnsavedChanges('relays')
|
||||
{ url: ev.target.value, policy: relays[i].policy },
|
||||
...relays.slice(i + 1),
|
||||
]);
|
||||
addUnsavedChanges("relays");
|
||||
}
|
||||
|
||||
function toggleRelayPolicy(i, cat) {
|
||||
@@ -555,122 +566,125 @@ examples:
|
||||
...relays.slice(0, i),
|
||||
{
|
||||
url: relays[i].url,
|
||||
policy: {...relays[i].policy, [cat]: !relays[i].policy[cat]}
|
||||
policy: { ...relays[i].policy, [cat]: !relays[i].policy[cat] },
|
||||
},
|
||||
...relays.slice(i + 1)
|
||||
])
|
||||
addUnsavedChanges('relays')
|
||||
...relays.slice(i + 1),
|
||||
]);
|
||||
addUnsavedChanges("relays");
|
||||
}
|
||||
|
||||
function removeRelay(i) {
|
||||
setRelays([...relays.slice(0, i), ...relays.slice(i + 1)])
|
||||
addUnsavedChanges('relays')
|
||||
setRelays([...relays.slice(0, i), ...relays.slice(i + 1)]);
|
||||
addUnsavedChanges("relays");
|
||||
}
|
||||
|
||||
function addNewRelay() {
|
||||
if (newRelayURL.trim() === '') return
|
||||
if (!newRelayURL.startsWith('wss://')) return
|
||||
if (newRelayURL.trim() === "") return;
|
||||
if (!newRelayURL.startsWith("wss://")) return;
|
||||
relays.push({
|
||||
url: newRelayURL,
|
||||
policy: {read: true, write: true}
|
||||
})
|
||||
setRelays(relays)
|
||||
addUnsavedChanges('relays')
|
||||
setNewRelayURL('')
|
||||
policy: { read: true, write: true },
|
||||
});
|
||||
setRelays(relays);
|
||||
addUnsavedChanges("relays");
|
||||
setNewRelayURL("");
|
||||
}
|
||||
|
||||
async function handleRevoke(e) {
|
||||
let {host, accept, type} = e.target.dataset
|
||||
const { host, accept, type } = e.target.dataset;
|
||||
if (
|
||||
window.confirm(
|
||||
`revoke all ${
|
||||
accept === 'true' ? 'accept' : 'deny'
|
||||
} ${type} policies from ${host}?`
|
||||
accept === "true" ? "accept" : "deny"
|
||||
} ${type} policies from ${host}?`,
|
||||
)
|
||||
) {
|
||||
await removePermissions(host, accept, type)
|
||||
showMessage('removed policies')
|
||||
loadPermissions()
|
||||
await removePermissions(host, accept, type);
|
||||
showMessage("removed policies");
|
||||
loadPermissions();
|
||||
}
|
||||
}
|
||||
|
||||
function handleNotifications() {
|
||||
setNotifications(!showNotifications)
|
||||
addUnsavedChanges('notifications')
|
||||
if (!showNotifications) requestBrowserNotificationPermissions()
|
||||
setNotifications(!showNotifications);
|
||||
addUnsavedChanges("notifications");
|
||||
if (!showNotifications) requestBrowserNotificationPermissions();
|
||||
}
|
||||
|
||||
async function requestBrowserNotificationPermissions() {
|
||||
let granted = await browser.permissions.request({
|
||||
permissions: ['notifications']
|
||||
})
|
||||
if (!granted) setNotifications(false)
|
||||
const granted = await browser.permissions.request({
|
||||
permissions: ["notifications"],
|
||||
});
|
||||
if (!granted) setNotifications(false);
|
||||
}
|
||||
|
||||
async function saveNotifications() {
|
||||
await browser.storage.local.set({notifications: showNotifications})
|
||||
showMessage('saved notifications!')
|
||||
await browser.storage.local.set({ notifications: showNotifications });
|
||||
showMessage("saved notifications!");
|
||||
}
|
||||
|
||||
async function saveRelays() {
|
||||
await browser.storage.local.set({
|
||||
relays: Object.fromEntries(
|
||||
relays
|
||||
.filter(({url}) => url.trim() !== '')
|
||||
.map(({url, policy}) => [url.trim(), policy])
|
||||
)
|
||||
})
|
||||
showMessage('saved relays!')
|
||||
.filter(({ url }) => url.trim() !== "")
|
||||
.map(({ url, policy }) => [url.trim(), policy]),
|
||||
),
|
||||
});
|
||||
showMessage("saved relays!");
|
||||
}
|
||||
|
||||
function changeShowProtocolHandlerHelp() {
|
||||
setShowProtocolHandlerHelp(true)
|
||||
setShowProtocolHandlerHelp(true);
|
||||
}
|
||||
|
||||
function changeHandleNostrLinks() {
|
||||
if (handleNostrLinks) {
|
||||
setProtocolHandler('')
|
||||
addUnsavedChanges('protocol_handler')
|
||||
} else setShowProtocolHandlerHelp(true)
|
||||
setHandleNostrLinks(!handleNostrLinks)
|
||||
setProtocolHandler("");
|
||||
addUnsavedChanges("protocol_handler");
|
||||
} else setShowProtocolHandlerHelp(true);
|
||||
setHandleNostrLinks(!handleNostrLinks);
|
||||
}
|
||||
|
||||
function handleChangeProtocolHandler(e) {
|
||||
setProtocolHandler(e.target.value)
|
||||
addUnsavedChanges('protocol_handler')
|
||||
setProtocolHandler(e.target.value);
|
||||
addUnsavedChanges("protocol_handler");
|
||||
}
|
||||
|
||||
async function saveNostrProtocolHandlerSettings() {
|
||||
await browser.storage.local.set({protocol_handler: protocolHandler})
|
||||
showMessage('saved protocol handler!')
|
||||
await browser.storage.local.set({ protocol_handler: protocolHandler });
|
||||
showMessage("saved protocol handler!");
|
||||
}
|
||||
|
||||
function addUnsavedChanges(section) {
|
||||
if (!unsavedChanges.find(s => s === section)) {
|
||||
unsavedChanges.push(section)
|
||||
setUnsavedChanges(unsavedChanges)
|
||||
if (!unsavedChanges.find((s) => s === section)) {
|
||||
unsavedChanges.push(section);
|
||||
setUnsavedChanges(unsavedChanges);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveChanges() {
|
||||
for (let section of unsavedChanges) {
|
||||
for (const section of unsavedChanges) {
|
||||
switch (section) {
|
||||
case 'private_key':
|
||||
await saveKey()
|
||||
break
|
||||
case 'relays':
|
||||
await saveRelays()
|
||||
break
|
||||
case 'protocol_handler':
|
||||
await saveNostrProtocolHandlerSettings()
|
||||
break
|
||||
case 'notifications':
|
||||
await saveNotifications()
|
||||
break
|
||||
case "private_key":
|
||||
await saveKey();
|
||||
break;
|
||||
case "relays":
|
||||
await saveRelays();
|
||||
break;
|
||||
case "protocol_handler":
|
||||
await saveNostrProtocolHandlerSettings();
|
||||
break;
|
||||
case "notifications":
|
||||
await saveNotifications();
|
||||
break;
|
||||
}
|
||||
}
|
||||
setUnsavedChanges([])
|
||||
setUnsavedChanges([]);
|
||||
}
|
||||
}
|
||||
|
||||
render(<Options />, document.getElementById('main'))
|
||||
const container = document.getElementById("main");
|
||||
const root = createRoot(container);
|
||||
|
||||
root.render(<Options />);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,116 +1,118 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
export const NO_PERMISSIONS_REQUIRED = {
|
||||
replaceURL: true
|
||||
}
|
||||
replaceURL: true,
|
||||
};
|
||||
|
||||
export const PERMISSION_NAMES = Object.fromEntries([
|
||||
['getPublicKey', 'read your public key'],
|
||||
['getRelays', 'read your list of preferred relays'],
|
||||
['signEvent', 'sign events using your private key'],
|
||||
['nip04.encrypt', 'encrypt messages to peers'],
|
||||
['nip04.decrypt', 'decrypt messages from peers']
|
||||
])
|
||||
["getPublicKey", "read your public key"],
|
||||
["getRelays", "read your list of preferred relays"],
|
||||
["signEvent", "sign events using your private key"],
|
||||
["nip04.encrypt", "encrypt messages to peers"],
|
||||
["nip04.decrypt", "decrypt messages from peers"],
|
||||
]);
|
||||
|
||||
function matchConditions(conditions, event) {
|
||||
if (conditions?.kinds) {
|
||||
if (event.kind in conditions.kinds) return true
|
||||
else return false
|
||||
if (event.kind in conditions.kinds) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
return true
|
||||
return true;
|
||||
}
|
||||
|
||||
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++) {
|
||||
let accept = answers[i]
|
||||
let {conditions} = policies?.[host]?.[accept]?.[type] || {}
|
||||
const accept = answers[i];
|
||||
const { conditions } = policies?.[host]?.[accept]?.[type] || {};
|
||||
|
||||
if (conditions) {
|
||||
if (type === 'signEvent') {
|
||||
if (type === "signEvent") {
|
||||
if (matchConditions(conditions, event)) {
|
||||
return accept // may be true or false
|
||||
return accept; // may be true or false
|
||||
} else {
|
||||
// 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
|
||||
continue
|
||||
// biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
return accept // may be true or false
|
||||
return accept; // may be true or false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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 (Object.keys(conditions).length === 0) {
|
||||
conditions = {}
|
||||
conditions = {};
|
||||
} else {
|
||||
// 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
|
||||
})
|
||||
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
|
||||
let other = !accept
|
||||
let reverse = policies?.[host]?.[other]?.[type]
|
||||
const other = !accept;
|
||||
const reverse = policies?.[host]?.[other]?.[type];
|
||||
if (
|
||||
reverse &&
|
||||
JSON.stringify(reverse.conditions) === JSON.stringify(conditions)
|
||||
) {
|
||||
delete policies[host][other][type]
|
||||
delete policies[host][other][type];
|
||||
}
|
||||
|
||||
// insert our new policy
|
||||
policies[host] = policies[host] || {}
|
||||
policies[host][accept] = policies[host][accept] || {}
|
||||
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)
|
||||
}
|
||||
created_at: Math.round(Date.now() / 1000),
|
||||
};
|
||||
|
||||
browser.storage.local.set({policies})
|
||||
browser.storage.local.set({ policies });
|
||||
}
|
||||
|
||||
export async function removePermissions(host, accept, type) {
|
||||
let {policies = {}} = await browser.storage.local.get('policies')
|
||||
delete policies[host]?.[accept]?.[type]
|
||||
browser.storage.local.set({policies})
|
||||
const { policies = {} } = await browser.storage.local.get("policies");
|
||||
delete policies[host]?.[accept]?.[type];
|
||||
browser.storage.local.set({ policies });
|
||||
}
|
||||
|
||||
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) {
|
||||
let action = answer ? 'allowed' : 'denied'
|
||||
const action = answer ? "allowed" : "denied";
|
||||
browser.notifications.create(undefined, {
|
||||
type: 'basic',
|
||||
type: "basic",
|
||||
title: `${type} ${action} for ${host}`,
|
||||
message: JSON.stringify(
|
||||
params?.event
|
||||
? {
|
||||
kind: params.event.kind,
|
||||
content: params.event.content,
|
||||
tags: params.event.tags
|
||||
tags: params.event.tags,
|
||||
}
|
||||
: params,
|
||||
null,
|
||||
2
|
||||
2,
|
||||
),
|
||||
iconUrl: 'icons/48x48.png'
|
||||
})
|
||||
iconUrl: "icons/48x48.png",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,12 +3,7 @@
|
||||
"description": "Nostr Signer Extension",
|
||||
"version": "0.1.2",
|
||||
"homepage_url": "https://github.com/reyamir/nostr-connect",
|
||||
"manifest_version": 2,
|
||||
"browser_specific_settings": {
|
||||
"gecko": {
|
||||
"id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}"
|
||||
}
|
||||
},
|
||||
"manifest_version": 3,
|
||||
"icons": {
|
||||
"16": "icons/icon16.png",
|
||||
"32": "icons/icon32.png",
|
||||
@@ -17,19 +12,25 @@
|
||||
},
|
||||
"options_page": "options.html",
|
||||
"background": {
|
||||
"scripts": ["background.build.js"]
|
||||
"service_worker": "background.build.js"
|
||||
},
|
||||
"browser_action": {
|
||||
"action": {
|
||||
"default_title": "Nostr Connect",
|
||||
"default_popup": "popup.html"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["<all_urls>"],
|
||||
"js": ["content-script.build.js"]
|
||||
"js": ["content-script.build.js"],
|
||||
"all_frames": true
|
||||
}
|
||||
],
|
||||
"permissions": ["storage"],
|
||||
"optional_permissions": ["notifications"],
|
||||
"web_accessible_resources": ["nostr-provider.js"]
|
||||
"web_accessible_resources": [
|
||||
{
|
||||
"resources": ["nostr-provider.js"],
|
||||
"matches": ["https://*/*", "http://localhost:*/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,66 +1,61 @@
|
||||
const EXTENSION = 'nostrconnect'
|
||||
const EXTENSION = "nostrconnect";
|
||||
|
||||
window.nostr = {
|
||||
_requests: {},
|
||||
_pubkey: null,
|
||||
|
||||
async getPublicKey() {
|
||||
if (this._pubkey) return this._pubkey
|
||||
this._pubkey = await this._call('getPublicKey', {})
|
||||
return this._pubkey
|
||||
if (this._pubkey) return this._pubkey;
|
||||
this._pubkey = await this._call("getPublicKey", {});
|
||||
return this._pubkey;
|
||||
},
|
||||
|
||||
async signEvent(event) {
|
||||
return this._call('signEvent', {event})
|
||||
return this._call("signEvent", { event });
|
||||
},
|
||||
|
||||
async getRelays() {
|
||||
return this._call('getRelays', {})
|
||||
return this._call("getRelays", {});
|
||||
},
|
||||
|
||||
nip04: {
|
||||
async encrypt(peer, plaintext) {
|
||||
return window.nostr._call('nip04.encrypt', {peer, plaintext})
|
||||
return window.nostr._call("nip04.encrypt", { peer, plaintext });
|
||||
},
|
||||
|
||||
async decrypt(peer, ciphertext) {
|
||||
return window.nostr._call('nip04.decrypt', {peer, ciphertext})
|
||||
}
|
||||
return window.nostr._call("nip04.decrypt", { peer, ciphertext });
|
||||
},
|
||||
},
|
||||
|
||||
_call(type, params) {
|
||||
let id = Math.random().toString().slice(-4)
|
||||
const id = Math.random().toString().slice(-4);
|
||||
console.log(
|
||||
'%c[nostrconnect:%c' +
|
||||
id +
|
||||
'%c]%c calling %c' +
|
||||
type +
|
||||
'%c with %c' +
|
||||
JSON.stringify(params || {}),
|
||||
'background-color:#f1b912;font-weight:bold;color:white',
|
||||
'background-color:#f1b912;font-weight:bold;color:#a92727',
|
||||
'background-color:#f1b912;color:white;font-weight:bold',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#08589d;font-family:monospace',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#90b12d;font-family:monospace'
|
||||
)
|
||||
`%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`,
|
||||
"background-color:#f1b912;font-weight:bold;color:white",
|
||||
"background-color:#f1b912;font-weight:bold;color:#a92727",
|
||||
"background-color:#f1b912;color:white;font-weight:bold",
|
||||
"color:auto",
|
||||
"font-weight:bold;color:#08589d;font-family:monospace",
|
||||
"color:auto",
|
||||
"font-weight:bold;color:#90b12d;font-family:monospace",
|
||||
);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._requests[id] = {resolve, reject}
|
||||
this._requests[id] = { resolve, reject };
|
||||
window.postMessage(
|
||||
{
|
||||
id,
|
||||
ext: EXTENSION,
|
||||
type,
|
||||
params
|
||||
params,
|
||||
},
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
"*",
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
window.addEventListener('message', message => {
|
||||
window.addEventListener("message", (message) => {
|
||||
if (
|
||||
!message.data ||
|
||||
message.data.response === null ||
|
||||
@@ -68,47 +63,46 @@ window.addEventListener('message', message => {
|
||||
message.data.ext !== EXTENSION ||
|
||||
!window.nostr._requests[message.data.id]
|
||||
)
|
||||
return
|
||||
return;
|
||||
|
||||
if (message.data.response.error) {
|
||||
let error = new Error(
|
||||
`${EXTENSION}: ` + message.data.response.error.message
|
||||
)
|
||||
error.stack = message.data.response.error.stack
|
||||
window.nostr._requests[message.data.id].reject(error)
|
||||
const error = new Error(
|
||||
`${EXTENSION}: ${message.data.response.error.message}`,
|
||||
);
|
||||
error.stack = message.data.response.error.stack;
|
||||
window.nostr._requests[message.data.id].reject(error);
|
||||
} else {
|
||||
window.nostr._requests[message.data.id].resolve(message.data.response)
|
||||
window.nostr._requests[message.data.id].resolve(message.data.response);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'%c[nostrconnect:%c' +
|
||||
message.data.id +
|
||||
'%c]%c result: %c' +
|
||||
JSON.stringify(
|
||||
message?.data?.response || message?.data?.response?.error?.message || {}
|
||||
),
|
||||
'background-color:#f1b912;font-weight:bold;color:white',
|
||||
'background-color:#f1b912;font-weight:bold;color:#a92727',
|
||||
'background-color:#f1b912;color:white;font-weight:bold',
|
||||
'color:auto',
|
||||
'font-weight:bold;color:#08589d'
|
||||
)
|
||||
`%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify(
|
||||
message?.data?.response || message?.data?.response?.error?.message || {},
|
||||
)}`,
|
||||
"background-color:#f1b912;font-weight:bold;color:white",
|
||||
"background-color:#f1b912;font-weight:bold;color:#a92727",
|
||||
"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
|
||||
let replacing = null
|
||||
document.addEventListener('mousedown', replaceNostrSchemeLink)
|
||||
let replacing = null;
|
||||
document.addEventListener("mousedown", replaceNostrSchemeLink);
|
||||
async function replaceNostrSchemeLink(e) {
|
||||
if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return
|
||||
if (replacing === false) return
|
||||
if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return;
|
||||
if (replacing === false) return;
|
||||
|
||||
let response = await window.nostr._call('replaceURL', {url: e.target.href})
|
||||
const response = await window.nostr._call("replaceURL", {
|
||||
url: e.target.href,
|
||||
});
|
||||
if (response === false) {
|
||||
replacing = false
|
||||
return
|
||||
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
@@ -1,58 +1,56 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import {render} from 'react-dom'
|
||||
import {getPublicKey, nip19} from 'nostr-tools'
|
||||
import React, {useState, useMemo, useEffect} from 'react'
|
||||
import QRCode from 'react-qr-code'
|
||||
import {SettingsIcon} from './icons'
|
||||
import {minidenticon} from 'minidenticons'
|
||||
import * as Tabs from '@radix-ui/react-tabs'
|
||||
import * as Tabs from "@radix-ui/react-tabs";
|
||||
import { minidenticon } from "minidenticons";
|
||||
import { getPublicKey, nip19 } from "nostr-tools";
|
||||
import React, { useState, useMemo, useEffect } from "react";
|
||||
import QRCode from "react-qr-code";
|
||||
import browser from "webextension-polyfill";
|
||||
import { SettingsIcon } from "./icons";
|
||||
|
||||
function Popup() {
|
||||
let [keys, setKeys] = useState(null)
|
||||
let avatarURI = useMemo(
|
||||
const [keys, setKeys] = useState(null);
|
||||
const avatarURI = useMemo(
|
||||
() =>
|
||||
keys
|
||||
? 'data:image/svg+xml;utf8,' +
|
||||
encodeURIComponent(minidenticon(keys.npub, 90, 30))
|
||||
? `data:image/svg+xml;utf8,${encodeURIComponent(minidenticon(keys.npub, 90, 30))}`
|
||||
: null,
|
||||
[keys]
|
||||
)
|
||||
[keys],
|
||||
);
|
||||
|
||||
const gotoSettings = () => {
|
||||
browser.tabs.create({
|
||||
url: browser.runtime.getURL('/options.html')
|
||||
})
|
||||
}
|
||||
url: browser.runtime.getURL("/options.html"),
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
browser.storage.local.get(['private_key', 'relays']).then(results => {
|
||||
browser.storage.local.get(["private_key", "relays"]).then((results) => {
|
||||
if (results.private_key) {
|
||||
let hexKey = getPublicKey(results.private_key)
|
||||
let npubKey = nip19.npubEncode(hexKey)
|
||||
const hexKey = getPublicKey(results.private_key);
|
||||
const npubKey = nip19.npubEncode(hexKey);
|
||||
|
||||
setKeys({npub: npubKey, hex: hexKey})
|
||||
setKeys({ npub: npubKey, hex: hexKey });
|
||||
|
||||
if (results.relays) {
|
||||
let relaysList = []
|
||||
for (let url in results.relays) {
|
||||
const relaysList = [];
|
||||
for (const url in results.relays) {
|
||||
if (results.relays[url].write) {
|
||||
relaysList.push(url)
|
||||
if (relaysList.length >= 3) break
|
||||
relaysList.push(url);
|
||||
if (relaysList.length >= 3) break;
|
||||
}
|
||||
}
|
||||
if (relaysList.length) {
|
||||
let nprofileKey = nip19.nprofileEncode({
|
||||
const nprofileKey = nip19.nprofileEncode({
|
||||
pubkey: hexKey,
|
||||
relays: relaysList
|
||||
})
|
||||
setKeys(prev => ({...prev, nprofile: nprofileKey}))
|
||||
relays: relaysList,
|
||||
});
|
||||
setKeys((prev) => ({ ...prev, nprofile: nprofileKey }));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setKeys(null)
|
||||
setKeys(null);
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="w-[320px] p-6">
|
||||
@@ -94,6 +92,7 @@ function Popup() {
|
||||
{avatarURI ? (
|
||||
<img
|
||||
src={avatarURI}
|
||||
alt="Avatar"
|
||||
className="w-9 h-9 rounded-full bg-muted"
|
||||
/>
|
||||
) : (
|
||||
@@ -176,7 +175,10 @@ function Popup() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
render(<Popup />, document.getElementById('main'))
|
||||
const container = document.getElementById("main");
|
||||
const root = createRoot(container);
|
||||
|
||||
root.render(<Popup />);
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
import {render} from 'react-dom'
|
||||
import React, {useState} from 'react'
|
||||
|
||||
import {PERMISSION_NAMES} from './common'
|
||||
import {LogoIcon} from './icons'
|
||||
import * as Checkbox from '@radix-ui/react-checkbox'
|
||||
import React, { useState } from "react";
|
||||
import browser from "webextension-polyfill";
|
||||
import * as Checkbox from "@radix-ui/react-checkbox";
|
||||
import { PERMISSION_NAMES } from "./common";
|
||||
import { LogoIcon } from "./icons";
|
||||
|
||||
function Prompt() {
|
||||
const [isRemember, setIsRemember] = useState(false)
|
||||
const [isRemember, setIsRemember] = useState(false);
|
||||
|
||||
let qs = new URLSearchParams(location.search)
|
||||
let id = qs.get('id')
|
||||
let host = qs.get('host')
|
||||
let type = qs.get('type')
|
||||
let params, event
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const id = qs.get("id");
|
||||
const host = qs.get("host");
|
||||
const type = qs.get("type");
|
||||
|
||||
let params;
|
||||
let event;
|
||||
|
||||
try {
|
||||
params = JSON.parse(qs.get('params'))
|
||||
if (Object.keys(params).length === 0) params = null
|
||||
else if (params.event) event = params.event
|
||||
params = JSON.parse(qs.get("params"));
|
||||
if (Object.keys(params).length === 0) params = null;
|
||||
else if (params.event) event = params.event;
|
||||
} catch (err) {
|
||||
params = null
|
||||
params = null;
|
||||
}
|
||||
|
||||
function authorizeHandler(accept) {
|
||||
const conditions = isRemember ? {} : null
|
||||
return function (ev) {
|
||||
ev.preventDefault()
|
||||
const conditions = isRemember ? {} : null;
|
||||
return (ev) => {
|
||||
ev.preventDefault();
|
||||
browser.runtime.sendMessage({
|
||||
prompt: true,
|
||||
id,
|
||||
host,
|
||||
type,
|
||||
accept,
|
||||
conditions
|
||||
})
|
||||
}
|
||||
conditions,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -88,12 +88,14 @@ function Prompt() {
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={authorizeHandler(false)}
|
||||
className="flex-1 h-10 rounded-lg shadow-sm border border-primary inline-flex items-center justify-center font-semibold"
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={authorizeHandler(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"
|
||||
>
|
||||
@@ -101,65 +103,12 @@ function Prompt() {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/*
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'space-around'
|
||||
}}
|
||||
>
|
||||
<button
|
||||
style={{marginTop: '5px'}}
|
||||
onClick={authorizeHandler(
|
||||
true,
|
||||
{} // store this and answer true forever
|
||||
)}
|
||||
>
|
||||
authorize forever
|
||||
</button>
|
||||
{event?.kind !== undefined && (
|
||||
<button
|
||||
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 />);
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
.data-\[state\=active\]\:text-primary[data-state=active] > .bg-muted {
|
||||
@apply bg-secondary
|
||||
.data-\[state\=active\]\:text-primary[data-state="active"] > .bg-muted {
|
||||
@apply bg-secondary;
|
||||
}
|
||||
|
||||
14
package.json
14
package.json
@@ -5,20 +5,16 @@
|
||||
"@radix-ui/react-tabs": "^1.1.2",
|
||||
"async-mutex": "^0.3.2",
|
||||
"esbuild": "^0.14.54",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-plugin-babel": "^5.3.1",
|
||||
"eslint-plugin-react": "^7.37.2",
|
||||
"events": "^3.3.0",
|
||||
"minidenticons": "^4.2.1",
|
||||
"nostr-tools": "^1.17.0",
|
||||
"prettier": "^2.8.8",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"nostr-tools": "^2.10.4",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-native-svg": "^13.14.1",
|
||||
"react-qr-code": "^2.0.15",
|
||||
"use-boolean-state": "^1.0.2",
|
||||
"use-debounce": "^7.0.1",
|
||||
"webextension-polyfill": "^0.8.0"
|
||||
"webextension-polyfill": "^0.12.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "./build.js; pnpm exec tailwindcss -i ./extension/style.css -o ./extension/build/style.css --watch",
|
||||
@@ -27,6 +23,8 @@
|
||||
"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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.9.4",
|
||||
"@types/webextension-polyfill": "^0.12.1",
|
||||
"esbuild-plugin-copy": "^2.1.1",
|
||||
"tailwindcss": "^3.4.17"
|
||||
}
|
||||
|
||||
1847
pnpm-lock.yaml
generated
1847
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user