rework permissions and popup prompts, make each permission fine grained.

This commit is contained in:
fiatjaf
2023-06-10 22:26:49 -03:00
parent 4759ce6d36
commit 0b1d849f19
6 changed files with 447 additions and 386 deletions

View File

@@ -10,9 +10,8 @@ import {nip04} from 'nostr-tools'
import {Mutex} from 'async-mutex'
import {
PERMISSIONS_REQUIRED,
NO_PERMISSIONS_REQUIRED,
readPermissionLevel,
getPermissionStatus,
updatePermission
} from './common'
@@ -90,24 +89,60 @@ async function handleContentScriptMessage({type, params, host}) {
return
} else {
let level = await readPermissionLevel(host)
// acquire mutex here before reading policies
releasePromptMutex = await promptMutex.acquire()
if (level >= PERMISSIONS_REQUIRED[type]) {
let allowed = await getPermissionStatus(
host,
type,
type === 'signEvent' ? params.event : undefined
)
if (allowed === true) {
// authorized, proceed
releasePromptMutex()
} else if (allowed === false) {
// denied, just refuse immediately
releasePromptMutex()
return {
error: 'denied'
}
} else {
// ask for authorization
try {
await promptPermission(host, PERMISSIONS_REQUIRED[type], params)
// authorized, proceed
} catch (_) {
// not authorized, stop here
let id = Math.random().toString().slice(4)
let qs = new URLSearchParams({
host,
id,
params: JSON.stringify(params),
type
})
// prompt will be resolved with true or false
let accept = await new Promise((resolve, reject) => {
openPrompt = {resolve, reject}
browser.windows.create({
url: `${browser.runtime.getURL('prompt.html')}?${qs.toString()}`,
type: 'popup',
width: 340,
height: 360
})
})
// denied, stop here
if (!accept) return {error: 'denied'}
} catch (err) {
// errored, stop here
releasePromptMutex()
return {
error: `insufficient permissions, required ${PERMISSIONS_REQUIRED[type]}`
error: `error: ${err}`
}
}
}
}
// if we're here this means it was accepted
let results = await browser.storage.local.get('private_key')
if (!results || !results.private_key) {
return {error: 'no private key found'}
@@ -148,51 +183,23 @@ async function handleContentScriptMessage({type, params, host}) {
}
}
function handlePromptMessage({id, condition, host, level}, sender) {
switch (condition) {
case 'forever':
case 'expirable':
openPrompt?.resolve?.()
updatePermission(host, {
level,
condition
})
break
case 'single':
openPrompt?.resolve?.()
break
case 'no':
openPrompt?.reject?.()
break
function handlePromptMessage({id, host, type, accept, conditions}, sender) {
// return response
openPrompt?.resolve?.(accept)
// update policies
if (conditions) {
updatePermission(host, type, accept, conditions)
}
// cleanup this
openPrompt = null
// release mutex here after updating policies
releasePromptMutex()
// close prompt
if (sender) {
browser.windows.remove(sender.tab.windowId)
}
}
async function promptPermission(host, level, params) {
releasePromptMutex = await promptMutex.acquire()
let id = Math.random().toString().slice(4)
let qs = new URLSearchParams({
host,
level,
id,
params: JSON.stringify(params)
})
return new Promise((resolve, reject) => {
openPrompt = {resolve, reject}
browser.windows.create({
url: `${browser.runtime.getURL('prompt.html')}?${qs.toString()}`,
type: 'popup',
width: 340,
height: 330
})
})
}

View File

@@ -4,90 +4,90 @@ export const NO_PERMISSIONS_REQUIRED = {
replaceURL: true
}
export const PERMISSIONS_REQUIRED = {
getPublicKey: 1,
getRelays: 5,
signEvent: 10,
'nip04.encrypt': 20,
'nip04.decrypt': 20,
}
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']
])
const ORDERED_PERMISSIONS = [
[1, ['getPublicKey']],
[5, ['getRelays']],
[10, ['signEvent']],
[20, ['nip04.encrypt']],
[20, ['nip04.decrypt']]
]
const PERMISSION_NAMES = {
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',
}
export function getAllowedCapabilities(permission) {
let requestedMethods = []
for (let i = 0; i < ORDERED_PERMISSIONS.length; i++) {
let [perm, methods] = ORDERED_PERMISSIONS[i]
if (perm > permission) break
requestedMethods = requestedMethods.concat(methods)
function matchConditions(conditions, event) {
if (conditions?.kinds) {
if (event.kind in conditions.kinds) return true
else return false
}
if (requestedMethods.length === 0) return 'nothing'
return requestedMethods.map(method => PERMISSION_NAMES[method])
return true
}
export function getPermissionsString(permission) {
let capabilities = getAllowedCapabilities(permission)
export async function getPermissionStatus(host, type, event) {
let {policies} = await browser.storage.local.get('policies')
if (capabilities.length === 0) return 'none'
if (capabilities.length === 1) return capabilities[0]
let answers = [true, false]
for (let i = 0; i < answers.length; i++) {
let accept = answers[i]
let {conditions} = policies?.[host]?.[accept]?.[type] || {}
return (
capabilities.slice(0, -1).join(', ') +
' and ' +
capabilities[capabilities.length - 1]
)
}
export async function readPermissions() {
let {permissions = {}} = await browser.storage.local.get('permissions')
// delete expired
var needsUpdate = false
for (let host in permissions) {
if (
permissions[host].condition === 'expirable' &&
permissions[host].created_at < Date.now() / 1000 - 5 * 60
) {
delete permissions[host]
needsUpdate = true
if (conditions) {
if (type === 'signEvent') {
if (matchConditions(conditions, event)) {
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
}
} else {
return accept // may be true or false
}
}
}
if (needsUpdate) browser.storage.local.set({permissions})
return permissions
return undefined
}
export async function readPermissionLevel(host) {
return (await readPermissions())[host]?.level || 0
}
export async function updatePermission(host, type, accept, conditions) {
let {policies = {}} = await browser.storage.local.get('policies')
export async function updatePermission(host, permission) {
let {permissions = {}} = await browser.storage.local.get('permissions')
permissions[host] = {
...permission,
// if the new conditions is "match everything", override the previous
if (Object.keys(conditions).length === 0) {
conditions = {}
} else {
// if we already had a policy for this, merge the conditions
let 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
let other = !accept
let reverse = policies?.[host]?.[other]?.[type]
if (
reverse &&
JSON.stringify(reverse.conditions) === JSON.stringify(conditions)
) {
delete policies[host][other][type]
}
// 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({permissions})
browser.storage.local.set({policies})
}
export async function removePermissions(host) {
let {permissions = {}} = await browser.storage.local.get('permissions')
delete permissions[host]
browser.storage.local.set({permissions})
export async function removePermissions(host, accept, type) {
let {policies = {}} = await browser.storage.local.get('policies')
delete policies[host]
browser.storage.local.set({policies})
}

View File

@@ -4,18 +4,14 @@ import {render} from 'react-dom'
import {generatePrivateKey, getPublicKey, nip19} from 'nostr-tools'
import QRCode from 'react-qr-code'
import {
getPermissionsString,
readPermissions,
removePermissions
} from './common'
import {removePermissions, PERMISSION_NAMES} from './common'
function Options() {
let [pubKey, setPubKey] = useState('')
let [privKey, setPrivKey] = useState('')
let [relays, setRelays] = useState([])
let [newRelayURL, setNewRelayURL] = useState('')
let [permissions, setPermissions] = useState()
let [policies, setPermissions] = useState()
let [protocolHandler, setProtocolHandler] = useState(null)
let [hidingPrivateKey, hidePrivateKey] = useState(true)
let [message, setMessage] = useState('')
@@ -28,217 +24,241 @@ function Options() {
useEffect(() => {
browser.storage.local
.get(['private_key', 'relays', 'protocol_handler'])
.then(results => {
if (results.private_key) {
setPrivKey(nip19.nsecEncode(results.private_key))
.get(['private_key', 'relays', 'protocol_handler'])
.then(results => {
if (results.private_key) {
setPrivKey(nip19.nsecEncode(results.private_key))
let hexKey = getPublicKey(results.private_key)
let npubKey = nip19.npubEncode(hexKey)
let hexKey = getPublicKey(results.private_key)
let npubKey = nip19.npubEncode(hexKey)
setPubKey(npubKey)
}
if (results.relays) {
let relaysList = []
for (let url in results.relays) {
relaysList.push({
url,
policy: results.relays[url]
})
setPubKey(npubKey)
}
setRelays(relaysList)
}
if (results.protocol_handler) {
setProtocolHandler(results.protocol_handler)
}
})
if (results.relays) {
let relaysList = []
for (let url in results.relays) {
relaysList.push({
url,
policy: results.relays[url]
})
}
setRelays(relaysList)
}
if (results.protocol_handler) {
setProtocolHandler(results.protocol_handler)
}
})
}, [])
useEffect(() => {
loadPermissions()
}, [])
function loadPermissions() {
readPermissions().then(permissions => {
setPermissions(
Object.entries(permissions).map(
([host, {level, condition, created_at}]) => ({
host,
level,
condition,
created_at
})
)
)
async function loadPermissions() {
let {policies = {}} = await browser.storage.local.get('policies')
let list = []
Object.entries(policies).forEach(([host, accepts]) => {
Object.entries(accepts).forEach(([accept, types]) => {
Object.entries(types).forEach(([type, {conditions, created_at}]) => {
list.push({
host,
type,
accept: {true: 'allow', false: 'deny'}[accept],
conditions,
created_at
})
})
})
})
setPermissions(list)
}
return (
<>
<h1>nos2x</h1>
<p>nostr signer extension</p>
<h2>options</h2>
<div style={{marginBottom: '10px'}}>
<div style={{display: 'flex', alignItems: 'center'}}>
<span>preferred relays:</span>
<button style={{marginLeft: '20px'}} onClick={saveRelays}>
save
</button>
</div>
<div style={{marginLeft: '10px'}}>
{relays.map(({url, policy}, i) => (
<div key={i} style={{display: 'flex'}}>
<input
style={{marginRight: '10px', width: '400px'}}
value={url}
onChange={changeRelayURL.bind(null, i)}
/>
<label>
read
<input
type="checkbox"
checked={policy.read}
onChange={toggleRelayPolicy.bind(null, i, 'read')}
/>
</label>
<label>
write
<input
type="checkbox"
checked={policy.write}
onChange={toggleRelayPolicy.bind(null, i, 'write')}
/>
</label>
</div>
))}
<div style={{display: 'flex'}}>
<>
<h1>nos2x</h1>
<p>nostr signer extension</p>
<h2>options</h2>
<div style={{marginBottom: '10px'}}>
<div style={{display: 'flex', alignItems: 'center'}}>
<span>preferred relays:</span>
<button style={{marginLeft: '20px'}} onClick={saveRelays}>
save
</button>
</div>
<div style={{marginLeft: '10px'}}>
{relays.map(({url, policy}, i) => (
<div key={i} style={{display: 'flex'}}>
<input
style={{width: '400px'}}
value={newRelayURL}
onChange={e => setNewRelayURL(e.target.value)}
onBlur={addNewRelay}
style={{marginRight: '10px', width: '400px'}}
value={url}
onChange={changeRelayURL.bind(null, i)}
/>
<label>
read
<input
type="checkbox"
checked={policy.read}
onChange={toggleRelayPolicy.bind(null, i, 'read')}
/>
</label>
<label>
write
<input
type="checkbox"
checked={policy.write}
onChange={toggleRelayPolicy.bind(null, i, 'write')}
/>
</label>
</div>
))}
<div style={{display: 'flex'}}>
<input
style={{width: '400px'}}
value={newRelayURL}
onChange={e => setNewRelayURL(e.target.value)}
onBlur={addNewRelay}
/>
</div>
</div>
<div style={{marginBottom: '10px'}}>
<label>
<div>private key:&nbsp;</div>
<div style={{marginLeft: '10px'}}>
<div style={{display: 'flex'}}>
<input
type={hidingPrivateKey ? 'password' : 'text'}
style={{width: '600px'}}
value={privKey}
onChange={handleKeyChange}
onFocus={() => hidePrivateKey(false)}
onBlur={() => hidePrivateKey(true)}
/>
{privKey === '' && <button onClick={generate}>generate</button>}
</div>
<button disabled={!isKeyValid()} onClick={saveKey}>
save
</button>
<button disabled={!isKeyValid()} onClick={() => setShowQR('priv')}>
Show QR for private key
</button>
<button disabled={!isKeyValid()} onClick={() => setShowQR('pub')}>
Show QR for public key
</button>
{ showQR && (
<div id={'qrCodeDiv'} style={{ height: 'auto', maxWidth: 256, width: '100%', marginTop: '20px', marginBottom: '30px' }}>
<QRCode
size={256}
style={{ height: 'auto', maxWidth: '100%', width: '100%' }}
value={showQR === 'priv' ? privKey : pubKey}
viewBox={`0 0 256 256`}
/>
</div>
)}
</div>
<div style={{marginBottom: '10px'}}>
<label>
<div>private key:&nbsp;</div>
<div style={{marginLeft: '10px'}}>
<div style={{display: 'flex'}}>
<input
type={hidingPrivateKey ? 'password' : 'text'}
style={{width: '600px'}}
value={privKey}
onChange={handleKeyChange}
onFocus={() => hidePrivateKey(false)}
onBlur={() => hidePrivateKey(true)}
/>
{privKey === '' && <button onClick={generate}>generate</button>}
</div>
</label>
{permissions?.length > 0 && (
<>
<h2>permissions</h2>
<table>
<thead>
<tr>
<th>domain</th>
<th>permissions</th>
<th>condition</th>
<th>since</th>
<th></th>
</tr>
</thead>
<tbody>
{permissions.map(({host, level, condition, created_at}) => (
<tr key={host}>
<td>{host}</td>
<td>{getPermissionsString(level)}</td>
<td>{condition}</td>
<td>
{new Date(created_at * 1000)
<button disabled={!isKeyValid()} onClick={saveKey}>
save
</button>
<button disabled={!isKeyValid()} onClick={() => setShowQR('priv')}>
Show QR for private key
</button>
<button disabled={!isKeyValid()} onClick={() => setShowQR('pub')}>
Show QR for public key
</button>
{showQR && (
<div
id={'qrCodeDiv'}
style={{
height: 'auto',
maxWidth: 256,
width: '100%',
marginTop: '20px',
marginBottom: '30px'
}}
>
<QRCode
size={256}
style={{height: 'auto', maxWidth: '100%', width: '100%'}}
value={showQR === 'priv' ? privKey : pubKey}
viewBox={`0 0 256 256`}
/>
</div>
)}
</div>
</label>
{policies?.length > 0 && (
<>
<h2>policies</h2>
<table>
<thead>
<tr>
<th>domain</th>
<th>permission</th>
<th>answer</th>
<th>conditions</th>
<th>since</th>
<th></th>
</tr>
</thead>
<tbody>
{policies.map(
({host, type, accept, conditions, created_at}) => (
<tr key={host}>
<td>{host}</td>
<td>{PERMISSION_NAMES[type]}</td>
<td>{accept}</td>
<td>{JSON.stringify(conditions).slice(1, -1)}</td>
<td>
{new Date(created_at * 1000)
.toISOString()
.split('.')[0]
.split('T')
.join(' ')}
</td>
<td>
<button onClick={handleRevoke} data-domain={host}>
revoke
</button>
</td>
</tr>
))}
</tbody>
</table>
</>
)}
</div>
<div>
<h2>
handle{' '}
<span style={{padding: '2px', background: 'silver'}}>nostr:</span>{' '}
links:
</h2>
<div style={{marginLeft: '10px'}}>
</td>
<td>
<button
onClick={handleRevoke}
data-host={host}
data-accept={accept}
data-type={type}
>
revoke
</button>
</td>
</tr>
)
)}
</tbody>
</table>
</>
)}
</div>
<div>
<h2>
handle{' '}
<span style={{padding: '2px', background: 'silver'}}>nostr:</span>{' '}
links:
</h2>
<div style={{marginLeft: '10px'}}>
<div>
<label>
<input
type="radio"
name="ph"
value="no"
checked={protocolHandler === null}
onChange={handleChangeProtocolHandler}
/>{' '}
no
</label>
</div>
<div>
<label>
<input
type="radio"
name="ph"
value="yes"
checked={protocolHandler !== null}
onChange={handleChangeProtocolHandler}
/>
yes
</label>
</div>
{protocolHandler !== null && (
<div>
<label>
<input
type="radio"
name="ph"
value="no"
checked={protocolHandler === null}
onChange={handleChangeProtocolHandler}
/>{' '}
no
</label>
</div>
<div>
<label>
<input
type="radio"
name="ph"
value="yes"
checked={protocolHandler !== null}
onChange={handleChangeProtocolHandler}
/>
yes
</label>
</div>
{protocolHandler !== null && (
<div>
<input
placeholder="url template"
value={protocolHandler}
onChange={handleChangeProtocolHandler}
style={{width: '680px', maxWidth: '90%'}}
/>
<pre>{`
<input
placeholder="url template"
value={protocolHandler}
onChange={handleChangeProtocolHandler}
style={{width: '680px', maxWidth: '90%'}}
/>
<pre>{`
{hex} = hex pubkey for npub or nprofile, hex event id for note or nevent
{p_or_e} = "p" for npub or nprofile, "e" for note or nevent
{u_or_n} = "u" for npub or nprofile, "n" for note or nevent
@@ -253,18 +273,18 @@ function Options() {
- https://brb.io/{u_or_n}/{hex}
- https://notes.blockcore.net/{p_or_e}/{hex}
`}</pre>
</div>
)}
<button
style={{marginTop: '10px'}}
onClick={saveNostrProtocolHandlerSettings}
>
save
</button>
</div>
</div>
)}
<button
style={{marginTop: '10px'}}
onClick={saveNostrProtocolHandlerSettings}
>
save
</button>
</div>
<div style={{marginTop: '12px', fontSize: '120%'}}>{message}</div>
</>
</div>
<div style={{marginTop: '12px', fontSize: '120%'}}>{message}</div>
</>
)
async function handleKeyChange(e) {
@@ -335,10 +355,16 @@ function Options() {
}
async function handleRevoke(e) {
let host = e.target.dataset.domain
if (window.confirm(`revoke all permissions from ${host}?`)) {
await removePermissions(host)
showMessage(`removed permissions from ${host}`)
let {host, accept, type} = e.target.dataset
if (
window.confirm(
`revoke all ${
accept ? 'accept' : 'deny'
} ${type} policies from ${host}?`
)
) {
await removePermissions(host, accept, type)
showMessage('removed policies')
loadPermissions()
}
}
@@ -346,7 +372,7 @@ function Options() {
async function saveRelays() {
await browser.storage.local.set({
relays: Object.fromEntries(
relays
relays
.filter(({url}) => url.trim() !== '')
.map(({url, policy}) => [url.trim(), policy])
)

View File

@@ -2,17 +2,18 @@ import browser from 'webextension-polyfill'
import {render} from 'react-dom'
import React from 'react'
import {getAllowedCapabilities} from './common'
import {PERMISSION_NAMES} from './common'
function Prompt() {
let qs = new URLSearchParams(location.search)
let id = qs.get('id')
let host = qs.get('host')
let level = parseInt(qs.get('level'))
let params
let type = qs.get('type')
let params, event
try {
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
}
@@ -23,20 +24,15 @@ function Prompt() {
<b style={{display: 'block', textAlign: 'center', fontSize: '200%'}}>
{host}
</b>{' '}
<p>is requesting your permission to </p>
<ul>
{getAllowedCapabilities(level).map(cap => (
<li key={cap}>
<i style={{fontSize: '140%'}}>{cap}</i>
</li>
))}
</ul>
<p>
is requesting your permission to <b>{PERMISSION_NAMES[type]}:</b>
</p>
</div>
{params && (
<>
<p>now acting on</p>
<pre style={{overflow: 'auto', maxHeight: '100px'}}>
<code>{JSON.stringify(params, null, 2)}</code>
<pre style={{overflow: 'auto', maxHeight: '120px'}}>
<code>{JSON.stringify(event || params, null, 2)}</code>
</pre>
</>
)}
@@ -49,35 +45,65 @@ function Prompt() {
>
<button
style={{marginTop: '5px'}}
onClick={authorizeHandler('forever')}
onClick={authorizeHandler(
true,
{} // store this and answer true forever
)}
>
authorize forever
</button>
<button
style={{marginTop: '5px'}}
onClick={authorizeHandler('expirable')}
>
authorize for 5 minutes
</button>
<button style={{marginTop: '5px'}} onClick={authorizeHandler('single')}>
{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>
<button style={{marginTop: '5px'}} onClick={authorizeHandler('no')}>
cancel
{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>
</>
)
function authorizeHandler(condition) {
function authorizeHandler(accept, conditions) {
return function (ev) {
ev.preventDefault()
browser.runtime.sendMessage({
prompt: true,
id,
host,
level,
condition
type,
accept,
conditions
})
}
}