Merge pull request #92 from loki-project/security

Don't Include an Auth Token with Encrypted File Uploads
pull/94/head
gmbnt 5 years ago committed by GitHub
commit ee93683a37

@ -1 +1 @@
Subproject commit 9aa5aae61fd7223a84239fc521184396aa3bedb7 Subproject commit edac100a2bda084edbba3291b080615aa26e5948

@ -76,6 +76,13 @@
<key>NSIncludesSubdomains</key> <key>NSIncludesSubdomains</key>
<true/> <true/>
</dict> </dict>
<key>file-dev.lokinet.org</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>imaginary.stream</key> <key>imaginary.stream</key>
<dict> <dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key> <key>NSExceptionAllowsInsecureHTTPLoads</key>

@ -777,7 +777,7 @@ static NSTimeInterval launchStartedAt;
[self startLongPollerIfNeeded]; [self startLongPollerIfNeeded];
// Loki: Get device links // Loki: Get device links
[LKStorageAPI getDeviceLinksAssociatedWith:self.tsAccountManager.localNumber]; [LKFileServerAPI getDeviceLinksAssociatedWith:self.tsAccountManager.localNumber];
if (![UIApplication sharedApplication].isRegisteredForRemoteNotifications) { if (![UIApplication sharedApplication].isRegisteredForRemoteNotifications) {
OWSLogInfo(@"Retrying to register for remote notifications since user hasn't registered yet."); OWSLogInfo(@"Retrying to register for remote notifications since user hasn't registered yet.");
@ -1448,7 +1448,7 @@ static NSTimeInterval launchStartedAt;
[self startLongPollerIfNeeded]; [self startLongPollerIfNeeded];
// Loki: Get device links // Loki: Get device links
[LKStorageAPI getDeviceLinksAssociatedWith:self.tsAccountManager.localNumber]; [LKFileServerAPI getDeviceLinksAssociatedWith:self.tsAccountManager.localNumber];
} }
} }

@ -175,7 +175,7 @@ final class DeviceLinkingModal : Modal, DeviceLinkingSessionDelegate {
dismiss(animated: true, completion: nil) dismiss(animated: true, completion: nil)
let master = DeviceLink.Device(hexEncodedPublicKey: deviceLink.master.hexEncodedPublicKey, signature: linkingAuthorizationMessage.masterSignature) let master = DeviceLink.Device(hexEncodedPublicKey: deviceLink.master.hexEncodedPublicKey, signature: linkingAuthorizationMessage.masterSignature)
let signedDeviceLink = DeviceLink(between: master, and: deviceLink.slave) let signedDeviceLink = DeviceLink(between: master, and: deviceLink.slave)
LokiStorageAPI.addDeviceLink(signedDeviceLink).done { LokiFileServerAPI.addDeviceLink(signedDeviceLink).done {
self.delegate?.handleDeviceLinkAuthorized(signedDeviceLink) // Intentionally capture self strongly self.delegate?.handleDeviceLinkAuthorized(signedDeviceLink) // Intentionally capture self strongly
}.catch { error in }.catch { error in
print("[Loki] Failed to add device link due to error: \(error).") print("[Loki] Failed to add device link due to error: \(error).")
@ -191,7 +191,7 @@ final class DeviceLinkingModal : Modal, DeviceLinkingSessionDelegate {
subtitleLabel.text = NSLocalizedString("Your device has been linked successfully", comment: "") subtitleLabel.text = NSLocalizedString("Your device has been linked successfully", comment: "")
mnemonicLabel.isHidden = true mnemonicLabel.isHidden = true
buttonStackView.isHidden = true buttonStackView.isHidden = true
LokiStorageAPI.addDeviceLink(deviceLink).catch { error in LokiFileServerAPI.addDeviceLink(deviceLink).catch { error in
print("[Loki] Failed to add device link due to error: \(error).") print("[Loki] Failed to add device link due to error: \(error).")
} }
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in

@ -152,7 +152,7 @@ final class DeviceLinksVC : UIViewController, UITableViewDataSource, UITableView
} }
private func removeDeviceLink(_ deviceLink: DeviceLink) { private func removeDeviceLink(_ deviceLink: DeviceLink) {
LokiStorageAPI.removeDeviceLink(deviceLink).done { [weak self] in LokiFileServerAPI.removeDeviceLink(deviceLink).done { [weak self] in
let linkedDeviceHexEncodedPublicKey = deviceLink.other.hexEncodedPublicKey let linkedDeviceHexEncodedPublicKey = deviceLink.other.hexEncodedPublicKey
guard let thread = TSContactThread.fetch(uniqueId: TSContactThread.threadId(fromContactId: linkedDeviceHexEncodedPublicKey)) else { return } guard let thread = TSContactThread.fetch(uniqueId: TSContactThread.threadId(fromContactId: linkedDeviceHexEncodedPublicKey)) else { return }
let unlinkDeviceMessage = UnlinkDeviceMessage(thread: thread)! let unlinkDeviceMessage = UnlinkDeviceMessage(thread: thread)!

@ -157,7 +157,7 @@ final class LandingVC : UIViewController, LinkDeviceVCDelegate, DeviceLinkingMod
TSAccountManager.sharedInstance().phoneNumberAwaitingVerification = keyPair.hexEncodedPublicKey TSAccountManager.sharedInstance().phoneNumberAwaitingVerification = keyPair.hexEncodedPublicKey
TSAccountManager.sharedInstance().didRegister() TSAccountManager.sharedInstance().didRegister()
setUserInteractionEnabled(false) setUserInteractionEnabled(false)
let _ = LokiStorageAPI.getDeviceLinks(associatedWith: hexEncodedPublicKey).done(on: DispatchQueue.main) { [weak self] deviceLinks in let _ = LokiFileServerAPI.getDeviceLinks(associatedWith: hexEncodedPublicKey).done(on: DispatchQueue.main) { [weak self] deviceLinks in
guard let self = self else { return } guard let self = self else { return }
defer { self.setUserInteractionEnabled(true) } defer { self.setUserInteractionEnabled(true) }
guard deviceLinks.count < 2 else { guard deviceLinks.count < 2 else {

@ -302,7 +302,7 @@ NS_ASSUME_NONNULL_BEGIN
publicChat = [LKDatabaseUtilities getPublicChatForThreadID:self.viewItem.interaction.uniqueThreadId transaction: transaction]; publicChat = [LKDatabaseUtilities getPublicChatForThreadID:self.viewItem.interaction.uniqueThreadId transaction: transaction];
}]; }];
if (publicChat != nil) { if (publicChat != nil) {
BOOL isModerator = [LKPublicChatAPI isUserModerator:incomingMessage.authorId forGroup:publicChat.channel onServer:publicChat.server]; BOOL isModerator = [LKPublicChatAPI isUserModerator:incomingMessage.authorId forChannel:publicChat.channel onServer:publicChat.server];
UIImage *moderatorIcon = [UIImage imageNamed:@"Crown"]; UIImage *moderatorIcon = [UIImage imageNamed:@"Crown"];
self.moderatorIconImageView.image = moderatorIcon; self.moderatorIconImageView.image = moderatorIcon;
self.moderatorIconImageView.hidden = !isModerator; self.moderatorIconImageView.hidden = !isModerator;

@ -1271,7 +1271,7 @@ NSString *NSStringForOWSMessageCellType(OWSMessageCellType cellType)
if (interationType == OWSInteractionType_IncomingMessage) { if (interationType == OWSInteractionType_IncomingMessage) {
// Only allow deletion on incoming messages if the user has moderation permission // Only allow deletion on incoming messages if the user has moderation permission
return [LKPublicChatAPI isUserModerator:self.userHexEncodedPublicKey forGroup:publicChat.channel onServer:publicChat.server]; return [LKPublicChatAPI isUserModerator:self.userHexEncodedPublicKey forChannel:publicChat.channel onServer:publicChat.server];
} }
// Only allow deletion on outgoing messages if the user was the sender (i.e. it was not sent from another linked device) // Only allow deletion on outgoing messages if the user was the sender (i.e. it was not sent from another linked device)

@ -411,7 +411,7 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
NSData *encryptedAvatarData = [self encryptProfileData:avatarData profileKey:newProfileKey]; NSData *encryptedAvatarData = [self encryptProfileData:avatarData profileKey:newProfileKey];
OWSAssertDebug(encryptedAvatarData.length > 0); OWSAssertDebug(encryptedAvatarData.length > 0);
[[LKStorageAPI setProfilePicture:encryptedAvatarData] [[LKFileServerAPI setProfilePicture:encryptedAvatarData]
.thenOn(dispatch_get_main_queue(), ^(NSString *url) { .thenOn(dispatch_get_main_queue(), ^(NSString *url) {
[self.localUserProfile updateWithProfileKey:newProfileKey dbConnection:self.dbConnection completion:^{ [self.localUserProfile updateWithProfileKey:newProfileKey dbConnection:self.dbConnection completion:^{
successBlock(url); successBlock(url);

@ -132,7 +132,7 @@ public final class LokiAPI : NSObject {
if timeSinceLastUpdate > deviceLinkUpdateInterval { if timeSinceLastUpdate > deviceLinkUpdateInterval {
storage.dbReadConnection.read { transaction in storage.dbReadConnection.read { transaction in
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
LokiStorageAPI.getDeviceLinks(associatedWith: masterHexEncodedPublicKey).done(on: DispatchQueue.global()) { _ in LokiFileServerAPI.getDeviceLinks(associatedWith: masterHexEncodedPublicKey).done(on: DispatchQueue.global()) { _ in
getDestinations() getDestinations()
lastDeviceLinkUpdate[hexEncodedPublicKey] = Date() lastDeviceLinkUpdate[hexEncodedPublicKey] = Date()
}.catch(on: DispatchQueue.global()) { error in }.catch(on: DispatchQueue.global()) { error in

@ -1,6 +1,6 @@
import PromiseKit import PromiseKit
/// Base class for `LokiStorageAPI` and `LokiPublicChatAPI`. /// Base class for `LokiFileServerAPI` and `LokiPublicChatAPI`.
public class LokiDotNetAPI : NSObject { public class LokiDotNetAPI : NSObject {
// MARK: Convenience // MARK: Convenience
@ -39,12 +39,13 @@ public class LokiDotNetAPI : NSObject {
// MARK: Attachments (Public API) // MARK: Attachments (Public API)
public static func uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> Promise<Void> { public static func uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> Promise<Void> {
let isEncryptionRequired = (server == LokiStorageAPI.server) let isEncryptionRequired = (server == LokiFileServerAPI.server)
return Promise<Void>() { seal in return Promise<Void>() { seal in
getAuthToken(for: server).done(on: DispatchQueue.global()) { token in func proceed(with token: String) {
// Get the attachment
let data: Data let data: Data
guard let unencryptedAttachmentData = try? attachment.readDataFromFile() else { guard let unencryptedAttachmentData = try? attachment.readDataFromFile() else {
print("[Loki] Couldn't read attachment data from disk.") print("[Loki] Couldn't read attachment from disk.")
return seal.reject(Error.generic) return seal.reject(Error.generic)
} }
// Encrypt the attachment if needed // Encrypt the attachment if needed
@ -71,7 +72,7 @@ public class LokiDotNetAPI : NSObject {
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
if let error = error { if let error = error {
print("[Loki] Couldn't upload attachment due to error: \(error).") print("[Loki] Couldn't upload attachment due to error: \(error).")
throw error return seal.reject(error)
} }
// Send the request // Send the request
func parseResponse(_ response: Any) { func parseResponse(_ response: Any) {
@ -87,7 +88,7 @@ public class LokiDotNetAPI : NSObject {
attachment.save() attachment.save()
seal.fulfill(()) seal.fulfill(())
} }
let isProxyingRequired = (server == LokiStorageAPI.server) // Don't proxy open group requests for now let isProxyingRequired = (server == LokiFileServerAPI.server) // Don't proxy open group requests for now
if isProxyingRequired { if isProxyingRequired {
let _ = LokiFileServerProxy(for: server).performLokiFileServerNSURLRequest(request as NSURLRequest).done { responseObject in let _ = LokiFileServerProxy(for: server).performLokiFileServerNSURLRequest(request as NSURLRequest).done { responseObject in
parseResponse(responseObject) parseResponse(responseObject)
@ -117,9 +118,16 @@ public class LokiDotNetAPI : NSObject {
}) })
task.resume() task.resume()
} }
}.catch(on: DispatchQueue.global()) { error in }
print("[Loki] Couldn't upload attachment.") if server == LokiFileServerAPI.server {
seal.reject(error) proceed(with: "loki") // Uploads to the Loki File Server shouldn't include any personally identifiable information so use a dummy auth token
} else {
getAuthToken(for: server).done(on: DispatchQueue.global()) { token in
proceed(with: token)
}.catch(on: DispatchQueue.global()) { error in
print("[Loki] Couldn't upload attachment due to error: \(error).")
seal.reject(error)
}
} }
} }
} }
@ -148,7 +156,7 @@ public class LokiDotNetAPI : NSObject {
throw Error.parsingFailed throw Error.parsingFailed
} }
// Discard the "05" prefix if needed // Discard the "05" prefix if needed
if (serverPublicKey.count == 33) { if serverPublicKey.count == 33 {
let hexEncodedServerPublicKey = serverPublicKey.toHexString() let hexEncodedServerPublicKey = serverPublicKey.toHexString()
serverPublicKey = Data.data(fromHex: hexEncodedServerPublicKey.substring(from: 2))! serverPublicKey = Data.data(fromHex: hexEncodedServerPublicKey.substring(from: 2))!
} }

@ -1,14 +1,14 @@
import PromiseKit import PromiseKit
@objc(LKStorageAPI) @objc(LKFileServerAPI)
public final class LokiStorageAPI : LokiDotNetAPI { public final class LokiFileServerAPI : LokiDotNetAPI {
// MARK: Settings // MARK: Settings
// #if DEBUG #if DEBUG
// private static let server = "http://file-dev.lokinet.org" @objc public static let server = "http://file-dev.lokinet.org"
// #else #else
@objc public static let server = "https://file.getsession.org" @objc public static let server = "https://file.getsession.org"
// #endif #endif
private static let deviceLinkType = "network.loki.messenger.devicemapping" private static let deviceLinkType = "network.loki.messenger.devicemapping"
private static let attachmentType = "net.app.core.oembed" private static let attachmentType = "net.app.core.oembed"
@ -168,7 +168,7 @@ public final class LokiStorageAPI : LokiDotNetAPI {
}) })
task.resume() task.resume()
}.catch { error in }.catch { error in
print("[Loki] Couldn't upload profile picture.") print("[Loki] Couldn't upload profile picture due to error: \(error).")
seal.reject(error) seal.reject(error)
} }
} }

@ -37,7 +37,7 @@ internal class LokiFileServerProxy : LokiHTTPClient {
// MARK: Proxying // MARK: Proxying
override internal func perform(_ request: TSRequest, withCompletionQueue queue: DispatchQueue = DispatchQueue.main) -> LokiAPI.RawResponsePromise { override internal func perform(_ request: TSRequest, withCompletionQueue queue: DispatchQueue = DispatchQueue.main) -> LokiAPI.RawResponsePromise {
let isLokiFileServer = (server == LokiStorageAPI.server) let isLokiFileServer = (server == LokiFileServerAPI.server)
guard isLokiFileServer else { return super.perform(request, withCompletionQueue: queue) } // Don't proxy open group requests for now guard isLokiFileServer else { return super.perform(request, withCompletionQueue: queue) } // Don't proxy open group requests for now
return performLokiFileServerNSURLRequest(request, withCompletionQueue: queue) return performLokiFileServerNSURLRequest(request, withCompletionQueue: queue)
} }

@ -13,7 +13,7 @@ public enum LokiRSSFeedProxy {
} }
public static func fetchContent(for url: String) -> Promise<String> { public static func fetchContent(for url: String) -> Promise<String> {
let server = LokiStorageAPI.server let server = LokiFileServerAPI.server
let endpoints = [ "messenger-updates/feed" : "loki/v1/rss/messenger", "loki.network/feed" : "loki/v1/rss/loki" ] let endpoints = [ "messenger-updates/feed" : "loki/v1/rss/messenger", "loki.network/feed" : "loki/v1/rss/loki" ]
let endpoint = endpoints.first { url.lowercased().contains($0.key) }!.value let endpoint = endpoints.first { url.lowercased().contains($0.key) }!.value
let url = URL(string: server + "/" + endpoint)! let url = URL(string: server + "/" + endpoint)!

@ -12,13 +12,10 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
// MARK: Public Chat // MARK: Public Chat
private static let channelInfoType = "net.patter-app.settings" private static let channelInfoType = "net.patter-app.settings"
private static let attachmentType = "net.app.core.oembed" private static let attachmentType = "net.app.core.oembed"
public static let avatarType = "network.loki.messenger.avatar" public static let profilePictureType = "network.loki.messenger.avatar"
@objc public static let publicChatMessageType = "network.loki.messenger.publicChat" @objc public static let publicChatMessageType = "network.loki.messenger.publicChat"
@objc public static let defaultChats: [LokiPublicChat] = { @objc public static let defaultChats: [LokiPublicChat] = [] // Currently unused
var result: [LokiPublicChat] = []
return result
}()
// MARK: Convenience // MARK: Convenience
private static var userDisplayName: String { private static var userDisplayName: String {
@ -70,6 +67,11 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
} }
public static func clearCaches(for channel: UInt64, on server: String) {
removeLastMessageServerID(for: channel, on: server)
removeLastDeletionServerID(for: channel, on: server)
}
// MARK: Public API // MARK: Public API
public static func getMessages(for channel: UInt64, on server: String) -> Promise<[LokiPublicChatMessage]> { public static func getMessages(for channel: UInt64, on server: String) -> Promise<[LokiPublicChatMessage]> {
var queryParameters = "include_annotations=1" var queryParameters = "include_annotations=1"
@ -97,23 +99,26 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
var avatar: LokiPublicChatMessage.Avatar? = nil var avatar: LokiPublicChatMessage.Avatar? = nil
let displayName = user["name"] as? String ?? NSLocalizedString("Anonymous", comment: "") let displayName = user["name"] as? String ?? NSLocalizedString("Anonymous", comment: "")
if let userAnnotations = user["annotations"] as? [JSON], let avatarAnnotation = userAnnotations.first(where: { $0["type"] as? String == avatarType }), if let userAnnotations = user["annotations"] as? [JSON], let avatarAnnotation = userAnnotations.first(where: { $0["type"] as? String == profilePictureType }),
let avatarValue = avatarAnnotation["value"] as? JSON, let profileKeyString = avatarValue["profileKey"] as? String, let profileKey = Data(base64Encoded: profileKeyString), let url = avatarValue["url"] as? String { let avatarValue = avatarAnnotation["value"] as? JSON, let profileKeyString = avatarValue["profileKey"] as? String, let profileKey = Data(base64Encoded: profileKeyString), let url = avatarValue["url"] as? String {
avatar = LokiPublicChatMessage.Avatar(profileKey: profileKey, url: url) avatar = LokiPublicChatMessage.Avatar(profileKey: profileKey, url: url)
} }
let lastMessageServerID = getLastMessageServerID(for: channel, on: server) let lastMessageServerID = getLastMessageServerID(for: channel, on: server)
if serverID > (lastMessageServerID ?? 0) { setLastMessageServerID(for: channel, on: server, to: serverID) } if serverID > (lastMessageServerID ?? 0) { setLastMessageServerID(for: channel, on: server, to: serverID) }
let quote: LokiPublicChatMessage.Quote? let quote: LokiPublicChatMessage.Quote?
if let quoteAsJSON = value["quote"] as? JSON, let quotedMessageTimestamp = quoteAsJSON["id"] as? UInt64, let quoteeHexEncodedPublicKey = quoteAsJSON["author"] as? String, let quotedMessageBody = quoteAsJSON["text"] as? String { if let quoteAsJSON = value["quote"] as? JSON, let quotedMessageTimestamp = quoteAsJSON["id"] as? UInt64, let quoteeHexEncodedPublicKey = quoteAsJSON["author"] as? String,
let quotedMessageBody = quoteAsJSON["text"] as? String {
let quotedMessageServerID = message["reply_to"] as? UInt64 let quotedMessageServerID = message["reply_to"] as? UInt64
quote = LokiPublicChatMessage.Quote(quotedMessageTimestamp: quotedMessageTimestamp, quoteeHexEncodedPublicKey: quoteeHexEncodedPublicKey, quotedMessageBody: quotedMessageBody, quotedMessageServerID: quotedMessageServerID) quote = LokiPublicChatMessage.Quote(quotedMessageTimestamp: quotedMessageTimestamp, quoteeHexEncodedPublicKey: quoteeHexEncodedPublicKey, quotedMessageBody: quotedMessageBody,
quotedMessageServerID: quotedMessageServerID)
} else { } else {
quote = nil quote = nil
} }
let signature = LokiPublicChatMessage.Signature(data: Data(hex: hexEncodedSignatureData), version: signatureVersion) let signature = LokiPublicChatMessage.Signature(data: Data(hex: hexEncodedSignatureData), version: signatureVersion)
let attachmentsAsJSON = annotations.filter { $0["type"] as? String == attachmentType } let attachmentsAsJSON = annotations.filter { $0["type"] as? String == attachmentType }
let attachments: [LokiPublicChatMessage.Attachment] = attachmentsAsJSON.compactMap { attachmentAsJSON in let attachments: [LokiPublicChatMessage.Attachment] = attachmentsAsJSON.compactMap { attachmentAsJSON in
guard let value = attachmentAsJSON["value"] as? JSON, let kindAsString = value["lokiType"] as? String, let kind = LokiPublicChatMessage.Attachment.Kind(rawValue: kindAsString), let serverID = value["id"] as? UInt64, let contentType = value["contentType"] as? String, let size = value["size"] as? UInt, let url = value["url"] as? String else { return nil } guard let value = attachmentAsJSON["value"] as? JSON, let kindAsString = value["lokiType"] as? String, let kind = LokiPublicChatMessage.Attachment.Kind(rawValue: kindAsString),
let serverID = value["id"] as? UInt64, let contentType = value["contentType"] as? String, let size = value["size"] as? UInt, let url = value["url"] as? String else { return nil }
let fileName = value["fileName"] as? String ?? UUID().description let fileName = value["fileName"] as? String ?? UUID().description
let width = value["width"] as? UInt ?? 0 let width = value["width"] as? UInt ?? 0
let height = value["height"] as? UInt ?? 0 let height = value["height"] as? UInt ?? 0
@ -127,9 +132,11 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
return nil return nil
} }
} }
return LokiPublicChatMessage.Attachment(kind: kind, server: server, serverID: serverID, contentType: contentType, size: size, fileName: fileName, flags: flags, width: width, height: height, caption: caption, url: url, linkPreviewURL: linkPreviewURL, linkPreviewTitle: linkPreviewTitle) return LokiPublicChatMessage.Attachment(kind: kind, server: server, serverID: serverID, contentType: contentType, size: size, fileName: fileName, flags: flags,
width: width, height: height, caption: caption, url: url, linkPreviewURL: linkPreviewURL, linkPreviewTitle: linkPreviewTitle)
} }
let result = LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: hexEncodedPublicKey, displayName: displayName, avatar: avatar, body: body, type: publicChatMessageType, timestamp: timestamp, quote: quote, attachments: attachments, signature: signature) let result = LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: hexEncodedPublicKey, displayName: displayName, avatar: avatar,
body: body, type: publicChatMessageType, timestamp: timestamp, quote: quote, attachments: attachments, signature: signature)
guard result.hasValidSignature() else { guard result.hasValidSignature() else {
print("[Loki] Ignoring public chat message with invalid signature.") print("[Loki] Ignoring public chat message with invalid signature.")
return nil return nil
@ -260,7 +267,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
public static func getUserCount(for channel: UInt64, on server: String) -> Promise<Int> { public static func getUserCount(for channel: UInt64, on server: String) -> Promise<Int> {
return getAuthToken(for: server).then(on: DispatchQueue.global()) { token -> Promise<Int> in return getAuthToken(for: server).then(on: DispatchQueue.global()) { token -> Promise<Int> in
let queryParameters = "count=2500" let queryParameters = "count=200"
let url = URL(string: "\(server)/channels/\(channel)/subscribers?\(queryParameters)")! let url = URL(string: "\(server)/channels/\(channel)/subscribers?\(queryParameters)")!
let request = TSRequest(url: url) let request = TSRequest(url: url)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
@ -306,7 +313,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
} }
@objc (isUserModerator:forGroup:onServer:) @objc(isUserModerator:forChannel:onServer:)
public static func isUserModerator(_ hexEncodedPublicString: String, for channel: UInt64, on server: String) -> Bool { public static func isUserModerator(_ hexEncodedPublicString: String, for channel: UInt64, on server: String) -> Bool {
return moderators[server]?[channel]?.contains(hexEncodedPublicString) ?? false return moderators[server]?[channel]?.contains(hexEncodedPublicString) ?? false
} }
@ -322,13 +329,13 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
print("Couldn't update display name due to error: \(error).") print("Couldn't update display name due to error: \(error).")
throw error throw error
} }
}.retryingIfNeeded(maxRetryCount: 3) }.retryingIfNeeded(maxRetryCount: maxRetryCount)
} }
public static func setProfilePictureURL(to url: String?, using profileKey: Data, on server: String) -> Promise<Void> { public static func setProfilePictureURL(to url: String?, using profileKey: Data, on server: String) -> Promise<Void> {
print("[Loki] Updating profile picture on server: \(server).") print("[Loki] Updating profile picture on server: \(server).")
return getAuthToken(for: server).then(on: DispatchQueue.global()) { token -> Promise<Void> in return getAuthToken(for: server).then(on: DispatchQueue.global()) { token -> Promise<Void> in
var annotation: JSON = [ "type" : avatarType ] var annotation: JSON = [ "type" : profilePictureType ]
if let url = url { if let url = url {
annotation["value"] = [ "profileKey" : profileKey.base64EncodedString(), "url" : url ] annotation["value"] = [ "profileKey" : profileKey.base64EncodedString(), "url" : url ]
} }
@ -340,7 +347,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
print("[Loki] Couldn't update profile picture due to error: \(error).") print("[Loki] Couldn't update profile picture due to error: \(error).")
throw error throw error
} }
}.retryingIfNeeded(maxRetryCount: 3) }.retryingIfNeeded(maxRetryCount: maxRetryCount)
} }
public static func getInfo(for channel: UInt64, on server: String) -> Promise<LokiPublicChatInfo> { public static func getInfo(for channel: UInt64, on server: String) -> Promise<LokiPublicChatInfo> {
@ -366,11 +373,6 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
return LokiFileServerProxy(for: server).perform(request).map { _ in } return LokiFileServerProxy(for: server).perform(request).map { _ in }
} }
@objc public static func clearCaches(for channel: UInt64, on server: String) {
removeLastMessageServerID(for: channel, on: server)
removeLastDeletionServerID(for: channel, on: server)
}
// MARK: Public API (Obj-C) // MARK: Public API (Obj-C)
@objc(getMessagesForGroup:onServer:) @objc(getMessagesForGroup:onServer:)
public static func objc_getMessages(for group: UInt64, on server: String) -> AnyPromise { public static func objc_getMessages(for group: UInt64, on server: String) -> AnyPromise {

@ -192,7 +192,7 @@ public final class LokiPublicChatPoller : NSObject {
if !hexEncodedPublicKeysToUpdate.isEmpty { if !hexEncodedPublicKeysToUpdate.isEmpty {
let storage = OWSPrimaryStorage.shared() let storage = OWSPrimaryStorage.shared()
storage.dbReadConnection.read { transaction in storage.dbReadConnection.read { transaction in
LokiStorageAPI.getDeviceLinks(associatedWith: hexEncodedPublicKeysToUpdate).done(on: DispatchQueue.global()) { _ in LokiFileServerAPI.getDeviceLinks(associatedWith: hexEncodedPublicKeysToUpdate).done(on: DispatchQueue.global()) { _ in
proceed() proceed()
hexEncodedPublicKeysToUpdate.forEach { hexEncodedPublicKeysToUpdate.forEach {
LokiAPI.lastDeviceLinkUpdate[$0] = Date() LokiAPI.lastDeviceLinkUpdate[$0] = Date()

@ -1249,7 +1249,7 @@ NS_ASSUME_NONNULL_BEGIN
}]) { }]) {
return; return;
} }
[LKStorageAPI getDeviceLinksAssociatedWith:userHexEncodedPublicKey].thenOn(dispatch_get_main_queue(), ^(NSSet<LKDeviceLink *> *deviceLinks) { [LKFileServerAPI getDeviceLinksAssociatedWith:userHexEncodedPublicKey].thenOn(dispatch_get_main_queue(), ^(NSSet<LKDeviceLink *> *deviceLinks) {
if ([deviceLinks contains:^BOOL(LKDeviceLink *deviceLink) { if ([deviceLinks contains:^BOOL(LKDeviceLink *deviceLink) {
return [deviceLink.master.hexEncodedPublicKey isEqual:senderHexEncodedPublicKey] && [deviceLink.slave.hexEncodedPublicKey isEqual:userHexEncodedPublicKey]; return [deviceLink.master.hexEncodedPublicKey isEqual:senderHexEncodedPublicKey] && [deviceLink.slave.hexEncodedPublicKey isEqual:userHexEncodedPublicKey];
}]) { }]) {

@ -484,9 +484,6 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException";
}); });
} }
failure:^(NSError *error) { failure:^(NSError *error) {
OWSLogError(@"Could not obtain UD sender certificate: %@", error);
// Proceed using non-UD message sends.
dispatch_async([OWSDispatch sendingQueue], ^{ dispatch_async([OWSDispatch sendingQueue], ^{
[self sendMessageToService:message senderCertificate:nil success:success failure:failure]; [self sendMessageToService:message senderCertificate:nil success:success failure:failure];
}); });

@ -65,14 +65,13 @@ static const CGFloat kAttachmentUploadProgressTheta = 0.001f;
- (void)run - (void)run
{ {
__block TSAttachmentStream *attachmentStream; __block TSAttachmentStream *attachmentStream;
[self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { [self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
attachmentStream = [TSAttachmentStream fetchObjectWithUniqueID:self.attachmentId transaction:transaction]; attachmentStream = [TSAttachmentStream fetchObjectWithUniqueID:self.attachmentId transaction:transaction];
}]; }];
if (!attachmentStream) { if (!attachmentStream) {
OWSProdError([OWSAnalyticsEvents messageSenderErrorCouldNotLoadAttachment]);
NSError *error = OWSErrorMakeFailedToSendOutgoingMessageError(); NSError *error = OWSErrorMakeFailedToSendOutgoingMessageError();
// Not finding local attachment is a terminal failure. // Not finding a local attachment is a terminal failure
error.isRetryable = NO; error.isRetryable = NO;
[self reportError:error]; [self reportError:error];
return; return;
@ -90,9 +89,9 @@ static const CGFloat kAttachmentUploadProgressTheta = 0.001f;
[self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) { [self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
publicChat = [LKDatabaseUtilities getPublicChatForThreadID:self.threadID transaction:transaction]; publicChat = [LKDatabaseUtilities getPublicChatForThreadID:self.threadID transaction:transaction];
}]; }];
NSString *server = (publicChat != nil) ? publicChat.server : LKStorageAPI.server; NSString *server = (publicChat != nil) ? publicChat.server : LKFileServerAPI.server;
[[LKStorageAPI uploadAttachment:attachmentStream withID:self.attachmentId toServer:server] [[LKFileServerAPI uploadAttachment:attachmentStream withID:self.attachmentId toServer:server]
.thenOn(dispatch_get_main_queue(), ^() { .thenOn(dispatch_get_main_queue(), ^() {
[self reportSuccess]; [self reportSuccess];
}) })

@ -26,6 +26,13 @@
<dict> <dict>
<key>NSExceptionDomains</key> <key>NSExceptionDomains</key>
<dict> <dict>
<key>file-dev.lokinet.org</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>149.56.148.124</key> <key>149.56.148.124</key>
<dict> <dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key> <key>NSExceptionAllowsInsecureHTTPLoads</key>

Loading…
Cancel
Save