damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

NIP98AuthenticatedRequest.swift (1565B)


      1 //
      2 //  NIP98AuthenticatedRequest.swift
      3 //  damus
      4 //
      5 //  Created by Daniel D’Aquino on 2023-12-15.
      6 //
      7 
      8 import Foundation
      9 
     10 enum HTTPMethod: String {
     11     case get = "GET"
     12     case post = "POST"
     13     case put = "PUT"
     14     case delete = "DELETE"
     15 }
     16 
     17 enum HTTPPayloadType: String {
     18     case json = "application/json"
     19     case binary = "application/octet-stream"
     20 }
     21 
     22 func make_nip98_authenticated_request(method: HTTPMethod, url: URL, payload: Data?, payload_type: HTTPPayloadType?, auth_keypair: Keypair) async throws -> (data: Data, response: URLResponse) {
     23     var request = URLRequest(url: url)
     24     request.httpMethod = method.rawValue
     25     request.httpBody = payload
     26     
     27     var tag_pairs = [
     28         ["u", url.absoluteString],
     29         ["method", method.rawValue],
     30     ]
     31     
     32     if let payload {
     33         let payload_hash = sha256(payload)
     34         let payload_hash_hex = hex_encode(payload_hash)
     35         tag_pairs.append(["payload", payload_hash_hex])
     36     }
     37         
     38     let auth_note = NdbNote(
     39         content: "",
     40         keypair: auth_keypair,
     41         kind: 27235,
     42         tags: tag_pairs,
     43         createdAt: UInt32(Date().timeIntervalSince1970)
     44     )
     45 
     46     let auth_note_json_data: Data = try encode_json_data(auth_note)
     47     let auth_note_base64: String = base64_encode(auth_note_json_data.bytes)
     48     
     49     request.setValue("Nostr " + auth_note_base64, forHTTPHeaderField: "Authorization")
     50     if let payload_type {
     51         request.setValue(payload_type.rawValue, forHTTPHeaderField: "Content-Type")
     52     }
     53     return try await URLSession.shared.data(for: request)
     54 }