Class: OStatus2::Salmon

Inherits:
Object
  • Object
show all
Includes:
MagicKey
Defined in:
lib/ostatus2/salmon.rb

Constant Summary collapse

XMLNS =
'http://salmon-protocol.org/ns/magic-env'

Instance Method Summary collapse

Methods included from MagicKey

#decode_base64, #magic_key_to_pem, #set_key

Instance Method Details

#pack(body, key) ⇒ String

Create a magical envelope XML document around the original body and sign it with a private key

Parameters:

  • body (String)
  • key (OpenSSL::PKey::RSA)

    The private part of the key will be used

Returns:

  • (String)

    Magical envelope XML



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ostatus2/salmon.rb', line 12

def pack(body, key)
  signed    = plaintext_signature(body, 'application/atom+xml', 'base64url', 'RSA-SHA256')
  signature = Base64.urlsafe_encode64(key.sign(digest, signed))

  Nokogiri::XML::Builder.new do |xml|
    xml['me'].env({ 'xmlns:me' => XMLNS }) do
      xml['me'].data({ type: 'application/atom+xml' }, Base64.urlsafe_encode64(body))
      xml['me'].encoding('base64url')
      xml['me'].alg('RSA-SHA256')
      xml['me'].sig({ key_id: Base64.urlsafe_encode64(key.public_key.to_s) }, signature)
    end
  end.to_xml
end

#post(salmon_url, envelope) ⇒ HTTP::Response

Deliver the magical envelope to a Salmon endpoint

Parameters:

  • salmon_url (String)

    Salmon endpoint URL

  • envelope (String)

    Magical envelope

Returns:

  • (HTTP::Response)

Raises:

  • (HTTP::Error)

    Error raised upon delivery failure

  • (OpenSSL::SSL::SSLError)

    Error raised upon SSL-related failure during delivery



32
33
34
# File 'lib/ostatus2/salmon.rb', line 32

def post(salmon_url, envelope)
  http_client.headers(HTTP::Headers::CONTENT_TYPE => 'application/magic-envelope+xml').post(Addressable::URI.parse(salmon_url), body: envelope)
end

#unpack(raw_body) ⇒ String

Unpack a magical envelope to get the content inside

Parameters:

  • raw_body (String)

    Magical envelope

Returns:

  • (String)

    Content inside the envelope

Raises:



40
41
42
43
# File 'lib/ostatus2/salmon.rb', line 40

def unpack(raw_body)
  body, _, _ = parse(raw_body)
  body
end

#verify(raw_body, key) ⇒ Boolean

Verify the magical envelope’s integrity

Parameters:

  • raw_body (String)

    Magical envelope

  • key (OpenSSL::PKey::RSA)

    The public part of the key will be used

Returns:

  • (Boolean)


49
50
51
52
53
54
# File 'lib/ostatus2/salmon.rb', line 49

def verify(raw_body, key)
  _, plaintext, signature = parse(raw_body)
  key.public_key.verify(digest, signature, plaintext)
rescue OStatus2::BadSalmonError
  false
end