Merge branch 'main' of ssh://code.freedombone.net:2222/bashrc/epicyon into main

main
Bob Mottram 2021-03-12 10:55:03 +00:00
commit ea38b4e91f
5 changed files with 95 additions and 20 deletions

View File

@ -6276,6 +6276,11 @@ class PubServer(BaseHTTPRequestHandler):
originPathStr = path.split('/followapprove=')[0] originPathStr = path.split('/followapprove=')[0]
followerNickname = originPathStr.replace('/users/', '') followerNickname = originPathStr.replace('/users/', '')
followingHandle = path.split('/followapprove=')[1] followingHandle = path.split('/followapprove=')[1]
if '://' in followingHandle:
handleNickname = getNicknameFromActor(followingHandle)
handleDomain, handlePort = getDomainFromActor(followingHandle)
followingHandle = \
handleNickname + '@' + getFullDomain(handleDomain, handlePort)
if '@' in followingHandle: if '@' in followingHandle:
if not self.server.session: if not self.server.session:
print('Starting new session during follow approval') print('Starting new session during follow approval')
@ -6437,6 +6442,11 @@ class PubServer(BaseHTTPRequestHandler):
originPathStr = path.split('/followdeny=')[0] originPathStr = path.split('/followdeny=')[0]
followerNickname = originPathStr.replace('/users/', '') followerNickname = originPathStr.replace('/users/', '')
followingHandle = path.split('/followdeny=')[1] followingHandle = path.split('/followdeny=')[1]
if '://' in followingHandle:
handleNickname = getNicknameFromActor(followingHandle)
handleDomain, handlePort = getDomainFromActor(followingHandle)
followingHandle = \
handleNickname + '@' + getFullDomain(handleDomain, handlePort)
if '@' in followingHandle: if '@' in followingHandle:
manualDenyFollowRequest(self.server.session, manualDenyFollowRequest(self.server.session,
baseDir, httpPrefix, baseDir, httpPrefix,

View File

@ -84,7 +84,7 @@ def _removeFromFollowBase(baseDir: str,
nickname: str, domain: str, nickname: str, domain: str,
acceptOrDenyHandle: str, followFile: str, acceptOrDenyHandle: str, followFile: str,
debug: bool) -> None: debug: bool) -> None:
"""Removes a handle from follow requests or rejects file """Removes a handle/actor from follow requests or rejects file
""" """
handle = nickname + '@' + domain handle = nickname + '@' + domain
accountsDir = baseDir + '/accounts/' + handle accountsDir = baseDir + '/accounts/' + handle
@ -94,13 +94,34 @@ def _removeFromFollowBase(baseDir: str,
print('WARN: Approve follow requests file ' + print('WARN: Approve follow requests file ' +
approveFollowsFilename + ' not found') approveFollowsFilename + ' not found')
return return
acceptDenyActor = None
if acceptOrDenyHandle not in open(approveFollowsFilename).read(): if acceptOrDenyHandle not in open(approveFollowsFilename).read():
# is this stored in the file as an actor rather than a handle?
acceptDenyNickname = acceptOrDenyHandle.split('@')[0]
acceptDenyDomain = acceptOrDenyHandle.split('@')[1]
# for each possible users path construct an actor and
# check if it exists in teh file
usersPaths = ('users', 'profile', 'channel', 'accounts', 'u')
actorFound = False
for usersName in usersPaths:
acceptDenyActor = \
'://' + acceptDenyDomain + '/' + \
usersName + '/' + acceptDenyNickname
if acceptDenyActor in open(approveFollowsFilename).read():
actorFound = True
break
if not actorFound:
return return
approvefilenew = open(approveFollowsFilename + '.new', 'w+') approvefilenew = open(approveFollowsFilename + '.new', 'w+')
with open(approveFollowsFilename, 'r') as approvefile: with open(approveFollowsFilename, 'r') as approvefile:
if not acceptDenyActor:
for approveHandle in approvefile: for approveHandle in approvefile:
if not approveHandle.startswith(acceptOrDenyHandle): if not approveHandle.startswith(acceptOrDenyHandle):
approvefilenew.write(approveHandle) approvefilenew.write(approveHandle)
else:
for approveHandle in approvefile:
if acceptDenyActor not in approveHandle:
approvefilenew.write(approveHandle)
approvefilenew.close() approvefilenew.close()
os.rename(approveFollowsFilename + '.new', approveFollowsFilename) os.rename(approveFollowsFilename + '.new', approveFollowsFilename)

View File

@ -11,7 +11,9 @@ import html
import time import time
import sys import sys
import select import select
from pathlib import Path
from random import randint from random import randint
from utils import saveJson
from utils import getNicknameFromActor from utils import getNicknameFromActor
from utils import getDomainFromActor from utils import getDomainFromActor
from utils import getFullDomain from utils import getFullDomain
@ -29,6 +31,7 @@ from announce import sendAnnounceViaServer
from pgp import pgpDecrypt from pgp import pgpDecrypt
from pgp import hasLocalPGPkey from pgp import hasLocalPGPkey
from pgp import pgpEncryptToActor from pgp import pgpEncryptToActor
from pgp import isPGPEncrypted
def _waitForKeypress(timeout: int, debug: bool) -> str: def _waitForKeypress(timeout: int, debug: bool) -> str:
@ -369,6 +372,23 @@ def _notificationNewDM(session, toHandle: str,
_sayCommand(sayStr, sayStr, screenreader, systemLanguage, espeak) _sayCommand(sayStr, sayStr, screenreader, systemLanguage, espeak)
def _storeMessage(speakerJson: {}) -> None:
"""Stores a message for later reading
"""
if not speakerJson.get('published'):
return
homeDir = str(Path.home())
if not os.path.isdir(homeDir + '/.config'):
os.mkdir(homeDir + '/.config')
if not os.path.isdir(homeDir + '/.config/epicyon'):
os.mkdir(homeDir + '/.config/epicyon')
msgDir = homeDir + '/.config/epicyon/dm'
if not os.path.isdir(msgDir):
os.mkdir(msgDir)
msgFilename = msgDir + '/' + speakerJson['published'] + '.json'
saveJson(speakerJson, msgFilename)
def runNotificationsClient(baseDir: str, proxyType: str, httpPrefix: str, def runNotificationsClient(baseDir: str, proxyType: str, httpPrefix: str,
nickname: str, domain: str, port: int, nickname: str, domain: str, port: int,
password: str, screenreader: str, password: str, screenreader: str,
@ -518,16 +538,16 @@ def runNotificationsClient(baseDir: str, proxyType: str, httpPrefix: str,
else: else:
messageStr = speakerJson['say'] + '. ' + \ messageStr = speakerJson['say'] + '. ' + \
speakerJson['imageDescription'] speakerJson['imageDescription']
if speakerJson.get('id'): encryptedMessage = False
if speakerJson.get('id') and \
isPGPEncrypted(messageStr):
encryptedMessage = True
messageStr = pgpDecrypt(messageStr, messageStr = pgpDecrypt(messageStr,
speakerJson['id']) speakerJson['id'])
content = messageStr content = messageStr
if speakerJson.get('content'): if speakerJson.get('content'):
if speakerJson.get('id'): if not encryptedMessage:
content = pgpDecrypt(speakerJson['content'],
speakerJson['id'])
else:
content = speakerJson['content'] content = speakerJson['content']
# say the speaker's name # say the speaker's name
@ -542,6 +562,12 @@ def runNotificationsClient(baseDir: str, proxyType: str, httpPrefix: str,
systemLanguage, espeak, systemLanguage, espeak,
nameStr, gender) nameStr, gender)
if encryptedMessage:
speakerJson['content'] = content
speakerJson['say'] = messageStr
speakerJson['decrypted'] = True
_storeMessage(speakerJson)
print('') print('')
prevSay = speakerJson['say'] prevSay = speakerJson['say']

33
pgp.py
View File

@ -52,7 +52,7 @@ def getPGPpubKey(actorJson: {}) -> str:
continue continue
if propertyValue['type'] != 'PropertyValue': if propertyValue['type'] != 'PropertyValue':
continue continue
if '--BEGIN PGP PUBLIC KEY' not in propertyValue['value']: if not containsPGPPublicKey(propertyValue['value']):
continue continue
return propertyValue['value'] return propertyValue['value']
return '' return ''
@ -139,7 +139,7 @@ def setPGPpubKey(actorJson: {}, PGPpubKey: str) -> None:
if not PGPpubKey: if not PGPpubKey:
removeKey = True removeKey = True
else: else:
if '--BEGIN PGP PUBLIC KEY' not in PGPpubKey: if not containsPGPPublicKey(PGPpubKey):
removeKey = True removeKey = True
if '<' in PGPpubKey: if '<' in PGPpubKey:
removeKey = True removeKey = True
@ -318,7 +318,7 @@ def _pgpEncrypt(content: str, recipientPubKey: str) -> str:
if not encryptResult: if not encryptResult:
return None return None
encryptResult = encryptResult.decode('utf-8') encryptResult = encryptResult.decode('utf-8')
if '--BEGIN PGP MESSAGE--' not in encryptResult: if not isPGPEncrypted(encryptResult):
return None return None
return encryptResult return encryptResult
@ -343,8 +343,7 @@ def _getPGPPublicKeyFromActor(handle: str, actorJson=None) -> str:
continue continue
if not isinstance(tag['value'], str): if not isinstance(tag['value'], str):
continue continue
if '--BEGIN PGP PUBLIC KEY BLOCK--' in tag['value']: if containsPGPPublicKey(tag['value']):
if '--END PGP PUBLIC KEY BLOCK--' in tag['value']:
return tag['value'] return tag['value']
return None return None
@ -370,17 +369,33 @@ def pgpEncryptToActor(content: str, toHandle: str) -> str:
return _pgpEncrypt(content, recipientPubKey) return _pgpEncrypt(content, recipientPubKey)
def isPGPEncrypted(content: str) -> bool:
"""Returns true if the given content is PGP encrypted
"""
if '--BEGIN PGP MESSAGE--' in content:
if '--END PGP MESSAGE--' in content:
return True
return False
def containsPGPPublicKey(content: str) -> bool:
"""Returns true if the given content contains a PGP public key
"""
if '--BEGIN PGP PUBLIC KEY BLOCK--' in content:
if '--END PGP PUBLIC KEY BLOCK--' in content:
return True
return False
def pgpDecrypt(content: str, fromHandle: str) -> str: def pgpDecrypt(content: str, fromHandle: str) -> str:
""" Encrypt using your default pgp key to the given recipient """ Encrypt using your default pgp key to the given recipient
fromHandle can be a handle or actor url fromHandle can be a handle or actor url
""" """
if '--BEGIN PGP MESSAGE--' not in content: if not isPGPEncrypted(content):
return content return content
# if the public key is also included within the message then import it # if the public key is also included within the message then import it
startBlock = '--BEGIN PGP PUBLIC KEY BLOCK--' if containsPGPPublicKey(content):
endBlock = '--END PGP PUBLIC KEY BLOCK--'
if startBlock in content and endBlock in content:
pubKey = extractPGPPublicKey(content) pubKey = extractPGPPublicKey(content)
else: else:
pubKey = _getPGPPublicKeyFromActor(content, fromHandle) pubKey = _getPGPPublicKeyFromActor(content, fromHandle)

View File

@ -103,6 +103,7 @@ from webapp_post import prepareHtmlPostNickname
from webapp_utils import markdownToHtml from webapp_utils import markdownToHtml
from speaker import speakerReplaceLinks from speaker import speakerReplaceLinks
from pgp import extractPGPPublicKey from pgp import extractPGPPublicKey
from pgp import containsPGPPublicKey
testServerAliceRunning = False testServerAliceRunning = False
testServerBobRunning = False testServerBobRunning = False
@ -3439,6 +3440,8 @@ def testExtractPGPPublicKey():
'=gv5G\n' + \ '=gv5G\n' + \
'-----END PGP PUBLIC KEY BLOCK-----' '-----END PGP PUBLIC KEY BLOCK-----'
testStr = "Some introduction\n\n" + pubKey + "\n\nSome message." testStr = "Some introduction\n\n" + pubKey + "\n\nSome message."
assert containsPGPPublicKey(testStr)
assert not containsPGPPublicKey('String without a pgp key')
result = extractPGPPublicKey(testStr) result = extractPGPPublicKey(testStr)
assert result assert result
assert result == pubKey assert result == pubKey